feat: complete M2 content workspace and inspector

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

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
# Shared subtree rules
- Public schema or type changes require migration analysis and focused compatibility tests.
- Ordinary loading remains read-only unless an accepted architecture decision explicitly says
otherwise.
- Update accepted ADRs and canonical docs at the slice boundary.
- A shared type change invalidates dependents according to the verification matrix; it does not
automatically require packaging in the fast loop.
+1
View File
@@ -12,3 +12,4 @@ blake3 = "1"
ron = "0.8"
serde.workspace = true
settings.workspace = true
uuid = { version = "1", features = ["v4", "serde"] }
+2 -2
View File
@@ -94,7 +94,7 @@ pub struct SkinnedMeshRenderer {
pub scene_index: usize,
/// Stable material slots for every draw binding in the imported animated hierarchy.
#[serde(default)]
pub materials: crate::RendererMaterialSet,
pub materials: crate::MaterialSlotSet,
}
impl SkinnedMeshRenderer {
@@ -103,7 +103,7 @@ impl SkinnedMeshRenderer {
asset_id: String::new(),
path: path.into(),
scene_index: 0,
materials: crate::RendererMaterialSet::default(),
materials: crate::MaterialSlotSet::default(),
}
}
+33 -159
View File
@@ -2,6 +2,8 @@ use avian3d::prelude::ColliderConstructor;
use bevy::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{ColorDesc, MaterialDesc};
/// Stable persisted identity for an actor. Bevy [`Entity`] IDs are runtime-only.
#[derive(
Component, Reflect, Default, Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize,
@@ -617,12 +619,24 @@ pub enum PrimitiveShape {
Ramp,
}
pub const PRIMITIVE_SURFACE_SLOT_ID: &str = "slot:primitive:surface";
fn default_primitive_surface() -> crate::MaterialSlot {
crate::MaterialSlot {
id: ComponentInstanceId::new(PRIMITIVE_SURFACE_SLOT_ID),
name: "Surface".into(),
material: None,
}
}
/// Reflectable authoring primitive. Hydration turns this into `Mesh3d`.
#[derive(Component, Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[reflect(Component, Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct Primitive {
pub shape: PrimitiveShape,
pub size: Vec3,
#[serde(default = "default_primitive_surface")]
pub surface: crate::MaterialSlot,
}
impl Primitive {
@@ -630,6 +644,7 @@ impl Primitive {
Self {
shape: PrimitiveShape::Box,
size,
surface: default_primitive_surface(),
}
}
@@ -637,6 +652,7 @@ impl Primitive {
Self {
shape: PrimitiveShape::Sphere,
size: Vec3::splat(radius * 2.0),
surface: default_primitive_surface(),
}
}
@@ -644,6 +660,7 @@ impl Primitive {
Self {
shape: PrimitiveShape::Ramp,
size,
surface: default_primitive_surface(),
}
}
}
@@ -1132,10 +1149,6 @@ pub struct MeshRenderSlot {
/// Stable renderer material slot used by this draw part.
#[serde(default)]
pub material_slot_id: ComponentInstanceId,
/// Legacy inline imported-material reference. Schema-v4 migration moves this into the
/// renderer's shared `RendererMaterialSet`.
#[serde(default)]
pub material: Option<EditorAssetRef>,
#[serde(default)]
pub local_transform: Transform,
#[serde(default = "default_true")]
@@ -1153,7 +1166,6 @@ impl Default for MeshRenderSlot {
name: "Mesh".into(),
mesh: EditorAssetRef::default(),
material_slot_id: ComponentInstanceId::default(),
material: None,
local_transform: Transform::default(),
visible: true,
cast_shadows: true,
@@ -1176,14 +1188,14 @@ pub struct StaticMeshRenderer {
#[serde(default, alias = "entries")]
pub slots: Vec<MeshRenderSlot>,
#[serde(default)]
pub materials: crate::RendererMaterialSet,
pub materials: crate::MaterialSlotSet,
}
impl StaticMeshRenderer {
pub fn empty() -> Self {
Self {
slots: Vec::new(),
materials: crate::RendererMaterialSet::default(),
materials: crate::MaterialSlotSet::default(),
}
}
@@ -1191,12 +1203,10 @@ impl StaticMeshRenderer {
if slot.material_slot_id.0.trim().is_empty() {
slot.material_slot_id = ComponentInstanceId::new(format!("slot:{}", slot.id.0));
}
let source_material = slot.material.clone().map(crate::MaterialRef::new);
let materials = crate::RendererMaterialSet {
slots: vec![crate::RendererMaterialSlot {
let materials = crate::MaterialSlotSet {
slots: vec![crate::MaterialSlot {
id: slot.material_slot_id.clone(),
name: slot.name.clone(),
source_material,
material: None,
}],
orphaned_assignments: Vec::new(),
@@ -1207,10 +1217,7 @@ impl StaticMeshRenderer {
}
}
pub fn material_slot_for_part(
&self,
part: &MeshRenderSlot,
) -> Option<&crate::RendererMaterialSlot> {
pub fn material_slot_for_part(&self, part: &MeshRenderSlot) -> Option<&crate::MaterialSlot> {
let slot_id = if part.material_slot_id.0.trim().is_empty() {
&part.id
} else {
@@ -1262,148 +1269,6 @@ impl Default for ShaderRefDesc {
}
/// Typed material parameter value exposed by a shader schema.
#[derive(Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
pub enum MaterialParameterValue {
Bool(bool),
Float(f32),
Vec2(Vec2),
Vec3(Vec3),
Color(ColorDesc),
Enum(String),
}
impl Default for MaterialParameterValue {
fn default() -> Self {
Self::Float(0.0)
}
}
#[derive(Reflect, Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct MaterialParameter {
pub name: String,
pub value: MaterialParameterValue,
}
#[derive(Reflect, Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct MaterialTextureBinding {
pub name: String,
pub texture: Option<EditorAssetRef>,
}
/// Per-render-slot material override stored on scene actors.
#[derive(Reflect, Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct MaterialSlotOverride {
pub slot_id: ComponentInstanceId,
#[serde(default)]
pub base_material: Option<EditorAssetRef>,
pub material: MaterialDesc,
}
/// Actor-level material overrides. Shared material assets are edited by asset
/// inspectors, while actor inspectors write only to this component.
#[derive(Component, Reflect, Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[reflect(Component, Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct MaterialOverride {
#[serde(default)]
pub slots: Vec<MaterialSlotOverride>,
}
/// Serializable color description. This avoids coupling saved scenes to any
/// internal color representation details.
#[derive(Reflect, Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[reflect(Default, Debug, Serialize, Deserialize)]
pub struct ColorDesc {
pub r: f32,
pub g: f32,
pub b: f32,
pub a: f32,
}
impl ColorDesc {
pub const fn srgb(r: f32, g: f32, b: f32) -> Self {
Self { r, g, b, a: 1.0 }
}
pub fn to_color(self) -> Color {
Color::srgba(self.r, self.g, self.b, self.a)
}
}
impl Default for ColorDesc {
fn default() -> Self {
Self::srgb(0.8, 0.8, 0.8)
}
}
/// Reflectable authoring material. Hydration turns this into `StandardMaterial`.
#[derive(Component, Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[reflect(Component, Default, Debug, Serialize, Deserialize)]
pub struct MaterialDesc {
#[serde(default)]
pub shader: ShaderRefDesc,
pub base_color: ColorDesc,
pub metallic: f32,
pub roughness: f32,
/// Emissive radiance tint. Values are multiplied by `emissive_intensity`.
#[serde(default = "default_emissive_color")]
pub emissive_color: ColorDesc,
/// Emissive luminance multiplier in nits. `0.0` means non-emissive.
#[serde(default)]
pub emissive_intensity: f32,
/// Optional base color (albedo) texture, path relative to `assets/`.
pub base_color_texture: Option<String>,
/// Optional emissive texture, path relative to `assets/`.
#[serde(default)]
pub emissive_texture: Option<String>,
/// Optional normal map texture, path relative to `assets/`.
pub normal_map_texture: Option<String>,
/// Optional metallic/roughness texture, path relative to `assets/`.
pub metallic_roughness_texture: Option<String>,
/// When set, references a [`crate::MaterialAsset`] RON under `assets/materials/`.
#[serde(default)]
pub material_asset_path: Option<String>,
/// Shader-schema-driven scalar/vector/color values.
#[serde(default)]
pub parameters: Vec<MaterialParameter>,
/// Shader-schema-driven texture references.
#[serde(default)]
pub textures: Vec<MaterialTextureBinding>,
}
impl MaterialDesc {
pub fn new(base_color: ColorDesc, metallic: f32, roughness: f32) -> Self {
Self {
shader: ShaderRefDesc::default(),
base_color,
metallic,
roughness,
emissive_color: default_emissive_color(),
emissive_intensity: 0.0,
base_color_texture: None,
emissive_texture: None,
normal_map_texture: None,
metallic_roughness_texture: None,
material_asset_path: None,
parameters: Vec::new(),
textures: Vec::new(),
}
}
}
fn default_emissive_color() -> ColorDesc {
ColorDesc::srgb(1.0, 1.0, 1.0)
}
impl Default for MaterialDesc {
fn default() -> Self {
Self::new(ColorDesc::default(), 0.0, 0.65)
}
}
/// Reflectable reference to an imported 3D model scene (glTF/GLB or FBX).
/// Hydration turns this into a `WorldAssetRoot` on the entity.
#[derive(Component, Reflect, Default, Debug, Clone, Serialize, Deserialize)]
@@ -1906,8 +1771,8 @@ impl Default for PhysicsBody {
#[cfg(test)]
mod tests {
use super::{
AudioListenerDesc, AudioRolloff, AudioSourceDesc, EditorAssetRef, ModelRef,
AUDIO_CLIP_SUB_ASSET_ID,
AudioListenerDesc, AudioRolloff, AudioSourceDesc, EditorAssetRef, ModelRef, Primitive,
AUDIO_CLIP_SUB_ASSET_ID, PRIMITIVE_SURFACE_SLOT_ID,
};
use bevy::light::light_consts;
@@ -1948,6 +1813,15 @@ mod tests {
assert_eq!(model.scene_index, 2);
}
#[test]
fn legacy_primitive_deserializes_with_stable_unassigned_surface_slot() {
let primitive: Primitive = ron::from_str("(shape:Box,size:(1.0,2.0,3.0))").unwrap();
assert_eq!(primitive.surface.id.0, PRIMITIVE_SURFACE_SLOT_ID);
assert_eq!(primitive.surface.name, "Surface");
assert!(primitive.surface.material.is_none());
}
#[test]
fn audio_authoring_descriptors_round_trip() {
let source = AudioSourceDesc {
+693
View File
@@ -0,0 +1,693 @@
//! Stable project-content registry and import contracts shared by editor, runtime, and tools.
use bevy::prelude::Resource;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{AssetSourceFingerprint, ComponentInstanceId, EditorAssetRef, MaterialRef};
pub const ASSET_REGISTRY_SCHEMA_VERSION: u32 = 3;
pub const RUNTIME_CONTENT_CATALOG_VERSION: u32 = 2;
/// Stable identity for one top-level project asset.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct AssetId(pub Uuid);
impl AssetId {
pub fn new() -> Self {
Self(Uuid::new_v4())
}
pub fn as_string(&self) -> String {
self.0.to_string()
}
}
impl Default for AssetId {
fn default() -> Self {
Self::new()
}
}
/// Folder-independent authored/imported asset classification.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum AssetKind {
Model,
Texture,
Material,
MaterialInstance,
AudioClip,
Level,
Prefab,
PostProcessEffect,
RenderingProfile,
ShaderSchema,
#[default]
Unknown,
}
impl AssetKind {
pub fn from_legacy_tag(tag: &str) -> Self {
match tag {
"Model" => Self::Model,
"Texture" => Self::Texture,
"Material" => Self::Material,
"MaterialInstance" => Self::MaterialInstance,
"AudioClip" => Self::AudioClip,
"Level" => Self::Level,
"Prefab" => Self::Prefab,
"PostProcessEffect" => Self::PostProcessEffect,
"RenderingProfile" => Self::RenderingProfile,
"ShaderSchema" => Self::ShaderSchema,
_ => Self::Unknown,
}
}
pub const fn is_imported_source(self) -> bool {
matches!(self, Self::Model | Self::Texture | Self::AudioClip)
}
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
pub enum ModelPlacementMode {
#[default]
StaticAsset,
SceneInstance,
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
pub enum ModelHierarchyMode {
#[default]
SingleActor,
SourceHierarchy,
}
/// Legacy whole-model policy retained only for registry-v1 migration.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
pub enum MaterialImportPolicy {
#[default]
SourceMaterials,
AuthoringOverride,
}
/// Persisted model-asset default for one stable imported material slot.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub enum ModelMaterialSelection {
#[default]
Source,
Project(MaterialRef),
Default,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct ModelMaterialSlotSelection {
pub slot_id: ComponentInstanceId,
#[serde(default)]
pub selection: ModelMaterialSelection,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct OrphanedModelMaterialSelection {
pub slot_id: ComponentInstanceId,
#[serde(default)]
pub last_known_name: String,
pub material: MaterialRef,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ModelImportSettings {
pub scale: f32,
pub generate_collider: bool,
pub lod0_only: bool,
#[serde(default)]
pub placement_mode: ModelPlacementMode,
#[serde(default)]
pub hierarchy_mode: ModelHierarchyMode,
/// Registry-v1 compatibility input. Registry-v2 writers keep this at its default and use
/// `material_slots` instead.
#[serde(default, skip_serializing_if = "material_import_policy_is_default")]
pub material_policy: MaterialImportPolicy,
#[serde(default)]
pub material_slots: Vec<ModelMaterialSlotSelection>,
#[serde(default)]
pub orphaned_material_slots: Vec<OrphanedModelMaterialSelection>,
#[serde(default)]
pub static_mesh_manifest_path: Option<String>,
#[serde(default)]
pub animation_manifest_path: Option<String>,
#[serde(default)]
pub default_animation_clip_id: Option<String>,
}
fn material_import_policy_is_default(policy: &MaterialImportPolicy) -> bool {
*policy == MaterialImportPolicy::SourceMaterials
}
impl Default for ModelImportSettings {
fn default() -> Self {
Self {
scale: 1.0,
generate_collider: true,
lod0_only: true,
placement_mode: ModelPlacementMode::default(),
hierarchy_mode: ModelHierarchyMode::default(),
material_policy: MaterialImportPolicy::default(),
material_slots: Vec::new(),
orphaned_material_slots: Vec::new(),
static_mesh_manifest_path: None,
animation_manifest_path: None,
default_animation_clip_id: None,
}
}
}
/// Source role used to infer safe color-space and compression defaults.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum TextureAssetSemantic {
#[default]
Auto,
Color,
Normal,
MaskData,
Ui,
Hdr,
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum TextureColorSpace {
#[default]
Auto,
Srgb,
Linear,
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum TextureMipmapMode {
#[default]
Generate,
PreserveSource,
None,
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum TextureCompression {
#[default]
Auto,
Uastc,
Uncompressed,
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum TextureFilter {
Nearest,
#[default]
Linear,
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum TextureWrap {
#[default]
Repeat,
Clamp,
Mirror,
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum NormalMapConvention {
#[default]
OpenGl,
DirectX,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct TextureImportSettings {
#[serde(default)]
pub semantic: TextureAssetSemantic,
#[serde(default)]
pub color_space: TextureColorSpace,
#[serde(default)]
pub mipmaps: TextureMipmapMode,
#[serde(default)]
pub compression: TextureCompression,
#[serde(default)]
pub max_dimension: Option<u32>,
#[serde(default)]
pub filter: TextureFilter,
#[serde(default)]
pub wrap: TextureWrap,
#[serde(default = "default_texture_anisotropy")]
pub anisotropy: u16,
#[serde(default)]
pub normal_map_convention: NormalMapConvention,
}
const fn default_texture_anisotropy() -> u16 {
8
}
impl Default for TextureImportSettings {
fn default() -> Self {
Self {
semantic: TextureAssetSemantic::Auto,
color_space: TextureColorSpace::Auto,
mipmaps: TextureMipmapMode::Generate,
compression: TextureCompression::Auto,
max_dimension: None,
filter: TextureFilter::Linear,
wrap: TextureWrap::Repeat,
anisotropy: default_texture_anisotropy(),
normal_map_convention: NormalMapConvention::OpenGl,
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub enum AssetImportSettings {
#[default]
None,
Model(ModelImportSettings),
Texture(TextureImportSettings),
}
impl AssetImportSettings {
pub fn for_kind(kind: AssetKind) -> Self {
match kind {
AssetKind::Model => Self::Model(ModelImportSettings::default()),
AssetKind::Texture => Self::Texture(TextureImportSettings::default()),
_ => Self::None,
}
}
pub fn model(&self) -> Option<&ModelImportSettings> {
match self {
Self::Model(settings) => Some(settings),
_ => None,
}
}
pub fn model_mut(&mut self) -> Option<&mut ModelImportSettings> {
match self {
Self::Model(settings) => Some(settings),
_ => None,
}
}
pub fn texture(&self) -> Option<&TextureImportSettings> {
match self {
Self::Texture(settings) => Some(settings),
_ => None,
}
}
pub fn texture_mut(&mut self) -> Option<&mut TextureImportSettings> {
match self {
Self::Texture(settings) => Some(settings),
_ => None,
}
}
}
impl From<ModelImportSettings> for AssetImportSettings {
fn from(settings: ModelImportSettings) -> Self {
Self::Model(settings)
}
}
impl From<TextureImportSettings> for AssetImportSettings {
fn from(settings: TextureImportSettings) -> Self {
Self::Texture(settings)
}
}
/// One-cycle source alias used by model processing APIs while call sites adopt the typed enum.
pub type ImportSettings = ModelImportSettings;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AssetRecord {
pub id: AssetId,
pub path: String,
pub label: String,
pub kind: AssetKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source_fingerprint: Option<AssetSourceFingerprint>,
#[serde(default)]
pub import_settings: AssetImportSettings,
#[serde(default)]
pub dependencies: Vec<String>,
}
impl AssetRecord {
pub fn model_import(&self) -> &ModelImportSettings {
self.import_settings
.model()
.expect("model asset record must carry model import settings")
}
pub fn model_import_mut(&mut self) -> &mut ModelImportSettings {
self.import_settings
.model_mut()
.expect("model asset record must carry model import settings")
}
pub fn texture_import(&self) -> Option<&TextureImportSettings> {
self.import_settings.texture()
}
pub fn texture_import_mut(&mut self) -> Option<&mut TextureImportSettings> {
self.import_settings.texture_mut()
}
}
#[derive(Resource, Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProjectContentDefaults {
#[serde(default)]
pub default_material: Option<MaterialRef>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AssetRegistryDocument {
#[serde(default = "asset_registry_schema_version")]
pub schema_version: u32,
#[serde(default)]
pub defaults: ProjectContentDefaults,
#[serde(default)]
pub records: Vec<AssetRecord>,
}
impl Default for AssetRegistryDocument {
fn default() -> Self {
Self {
schema_version: ASSET_REGISTRY_SCHEMA_VERSION,
defaults: ProjectContentDefaults::default(),
records: Vec::new(),
}
}
}
const fn asset_registry_schema_version() -> u32 {
ASSET_REGISTRY_SCHEMA_VERSION
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
struct LegacyAssetRecord {
id: AssetId,
path: String,
label: String,
kind_tag: String,
#[serde(default)]
source_fingerprint: Option<AssetSourceFingerprint>,
#[serde(default)]
import_settings: ModelImportSettings,
#[serde(default)]
dependencies: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
struct AssetRegistryDocumentV2 {
schema_version: u32,
#[serde(default)]
defaults: ProjectContentDefaults,
#[serde(default)]
records: Vec<AssetRecordV2>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
struct AssetRecordV2 {
id: AssetId,
path: String,
label: String,
kind: AssetKind,
#[serde(default)]
source_fingerprint: Option<AssetSourceFingerprint>,
#[serde(default)]
import_settings: ModelImportSettings,
#[serde(default)]
dependencies: Vec<String>,
}
pub struct LoadedAssetRegistry {
pub document: AssetRegistryDocument,
pub migration_required: bool,
}
pub fn parse_asset_registry(source: &str) -> Result<LoadedAssetRegistry, String> {
if let Ok(document) = ron::from_str::<AssetRegistryDocument>(source) {
if document.schema_version != ASSET_REGISTRY_SCHEMA_VERSION {
return Err(format!(
"unsupported asset registry schema {}; expected {}",
document.schema_version, ASSET_REGISTRY_SCHEMA_VERSION
));
}
return Ok(LoadedAssetRegistry {
document,
migration_required: false,
});
}
if let Ok(document) = ron::from_str::<AssetRegistryDocumentV2>(source) {
if document.schema_version != 2 {
return Err(format!(
"unsupported asset registry schema {}; expected {}",
document.schema_version, ASSET_REGISTRY_SCHEMA_VERSION
));
}
return Ok(LoadedAssetRegistry {
document: AssetRegistryDocument {
schema_version: ASSET_REGISTRY_SCHEMA_VERSION,
defaults: document.defaults,
records: document
.records
.into_iter()
.map(|record| {
let import_settings = match record.kind {
AssetKind::Model => AssetImportSettings::Model(record.import_settings),
AssetKind::Texture => {
AssetImportSettings::Texture(TextureImportSettings::default())
}
_ => AssetImportSettings::None,
};
AssetRecord {
id: record.id,
path: record.path,
label: record.label,
kind: record.kind,
source_fingerprint: record.source_fingerprint,
import_settings,
dependencies: record.dependencies,
}
})
.collect(),
},
migration_required: true,
});
}
match ron::from_str::<Vec<LegacyAssetRecord>>(source) {
Ok(records) => Ok(LoadedAssetRegistry {
document: AssetRegistryDocument {
records: records
.into_iter()
.map(|record| {
let kind = AssetKind::from_legacy_tag(&record.kind_tag);
let import_settings = match kind {
AssetKind::Model => AssetImportSettings::Model(record.import_settings),
AssetKind::Texture => {
AssetImportSettings::Texture(TextureImportSettings::default())
}
_ => AssetImportSettings::None,
};
AssetRecord {
id: record.id,
path: record.path,
label: record.label,
kind,
source_fingerprint: record.source_fingerprint,
import_settings,
dependencies: record.dependencies,
}
})
.collect(),
..Default::default()
},
migration_required: true,
}),
Err(error) => Err(format!("invalid asset registry RON: {error}")),
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TextureRuntimeData {
pub source_path: String,
#[serde(default)]
pub processed_path: Option<String>,
#[serde(default)]
pub processing_key: Option<String>,
pub settings: TextureImportSettings,
pub is_srgb: bool,
}
/// Runtime-only description of one project texture load. This keeps Bevy-specific loading out of
/// the content catalog while ensuring every renderer consumes the same authored sampling state.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct RuntimeTextureLoadSpec {
pub path: String,
pub is_srgb: bool,
pub filter: TextureFilter,
pub wrap: TextureWrap,
pub anisotropy: u16,
}
impl TextureRuntimeData {
pub fn load_spec(&self) -> RuntimeTextureLoadSpec {
RuntimeTextureLoadSpec {
path: self
.processed_path
.clone()
.unwrap_or_else(|| self.source_path.clone()),
is_srgb: self.is_srgb,
filter: self.settings.filter,
wrap: self.settings.wrap,
anisotropy: self.settings.anisotropy,
}
}
}
impl RuntimeContentCatalog {
pub fn texture_load_spec(&self, reference: &EditorAssetRef) -> Option<RuntimeTextureLoadSpec> {
self.records
.iter()
.find(|record| record.id.as_string() == reference.asset_id)
.and_then(|record| record.texture.as_ref())
.map(TextureRuntimeData::load_spec)
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct MaterialRuntimeData {
#[serde(default)]
pub packed_arm_path: Option<String>,
#[serde(default)]
pub processing_key: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RuntimeContentRecord {
pub id: AssetId,
pub path: String,
pub label: String,
pub kind: AssetKind,
#[serde(default)]
pub material_slots: Vec<ModelMaterialSlotSelection>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub texture: Option<TextureRuntimeData>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub material: Option<MaterialRuntimeData>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RuntimeContentCatalog {
pub version: u32,
#[serde(default)]
pub defaults: ProjectContentDefaults,
#[serde(default)]
pub records: Vec<RuntimeContentRecord>,
}
impl From<&AssetRegistryDocument> for RuntimeContentCatalog {
fn from(document: &AssetRegistryDocument) -> Self {
Self {
version: RUNTIME_CONTENT_CATALOG_VERSION,
defaults: document.defaults.clone(),
records: document
.records
.iter()
.map(|record| RuntimeContentRecord {
id: record.id.clone(),
path: record.path.clone(),
label: record.label.clone(),
kind: record.kind,
material_slots: record
.import_settings
.model()
.map(|settings| settings.material_slots.clone())
.unwrap_or_default(),
texture: record
.import_settings
.texture()
.map(|settings| TextureRuntimeData {
source_path: record.path.clone(),
processed_path: None,
processing_key: None,
settings: settings.clone(),
is_srgb: resolves_srgb(settings),
}),
material: None,
})
.collect(),
}
}
}
pub fn resolves_srgb(settings: &TextureImportSettings) -> bool {
match settings.color_space {
TextureColorSpace::Srgb => true,
TextureColorSpace::Linear => false,
TextureColorSpace::Auto => matches!(
settings.semantic,
TextureAssetSemantic::Auto | TextureAssetSemantic::Color | TextureAssetSemantic::Ui
),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn legacy_record_lists_require_explicit_migration() {
let source = r#"[(id:("00000000-0000-0000-0000-000000000001"),path:"assets/Props/a.glb",label:"a",kind_tag:"Model")]"#;
let loaded = parse_asset_registry(source).unwrap();
assert!(loaded.migration_required);
assert_eq!(loaded.document.records[0].kind, AssetKind::Model);
}
#[test]
fn runtime_catalog_strips_editor_import_state() {
let record = AssetRecord {
id: AssetId::new(),
path: "assets/Props/a.glb".into(),
label: "a".into(),
kind: AssetKind::Model,
source_fingerprint: None,
import_settings: AssetImportSettings::Model(ImportSettings::default()),
dependencies: vec!["assets/Props/a.bin".into()],
};
let document = AssetRegistryDocument {
records: vec![record],
..Default::default()
};
let runtime = RuntimeContentCatalog::from(&document);
assert_eq!(runtime.records.len(), 1);
assert_eq!(runtime.records[0].kind, AssetKind::Model);
}
#[test]
fn registry_v2_writers_omit_the_legacy_whole_model_material_policy() {
let document = AssetRegistryDocument {
records: vec![AssetRecord {
id: AssetId::new(),
path: "assets/model.glb".into(),
label: "Model".into(),
kind: AssetKind::Model,
source_fingerprint: None,
import_settings: AssetImportSettings::Model(ImportSettings::default()),
dependencies: Vec::new(),
}],
..Default::default()
};
let serialized = ron::ser::to_string(&document).unwrap();
assert!(!serialized.contains("material_policy"));
}
}
+28 -7
View File
@@ -15,6 +15,7 @@ use crate::{
};
use super::materials::material_from_desc;
use super::{default_grid_emergency_handle, DefaultGridEmergencyMaterial};
/// Runtime marker for generated brush render/collider children.
#[derive(Component, Reflect, Default, Debug, Clone, Copy)]
@@ -22,11 +23,16 @@ use super::materials::material_from_desc;
pub struct HydratedBrushMesh;
#[allow(clippy::type_complexity)]
#[expect(
clippy::too_many_arguments,
reason = "Bevy system parameters keep independently change-tracked brush inputs explicit"
)]
pub fn hydrate_brushes(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut fallback: ResMut<DefaultGridEmergencyMaterial>,
brushes: Query<
(
Entity,
@@ -61,6 +67,7 @@ pub fn hydrate_brushes(
&asset_server,
&mut meshes,
&mut materials,
&mut fallback,
entity,
brush,
material.filter(|_| {
@@ -82,6 +89,7 @@ pub fn spawn_brush_mesh(
asset_server: &AssetServer,
meshes: &mut Assets<Mesh>,
materials: &mut Assets<StandardMaterial>,
fallback: &mut DefaultGridEmergencyMaterial,
parent: Entity,
brush: &BrushDesc,
material: Option<&MaterialDesc>,
@@ -103,22 +111,35 @@ pub fn spawn_brush_mesh(
continue;
};
let mesh = meshes.add(mesh);
let material = materials.add(brush_group_material(
asset_server,
material,
group.material_path.as_deref(),
group.texture_path.as_deref(),
));
let uses_default_grid =
material.is_none() && group.material_path.is_none() && group.texture_path.is_none();
let material_handle = if uses_default_grid {
default_grid_emergency_handle(materials, fallback)
} else {
materials.add(brush_group_material(
asset_server,
material,
group.material_path.as_deref(),
group.texture_path.as_deref(),
))
};
let mut brush_child = commands.spawn((
HydratedBrushMesh,
Name::new("Hydrated Brush Mesh"),
Mesh3d(mesh),
MeshMaterial3d(material),
MeshMaterial3d(material_handle),
Transform::default(),
Visibility::Visible,
ChildOf(parent),
));
if uses_default_grid {
brush_child.insert(crate::HydratedMaterialSlotBinding {
owner: parent,
slot_id: crate::ComponentInstanceId::new("brush:default"),
selection: crate::HydratedMaterialSelection::Inherit,
});
}
if !brush.cast_shadows {
brush_child.insert(NotShadowCaster);
}
+117 -45
View File
@@ -1,50 +1,29 @@
//! Standard materials from [`MaterialDesc`] authoring data.
use bevy::prelude::*;
use crate::{
asset_server_path, authoring_component_active, AuthoringComponentStates, InspectorOrder,
LevelObject, MaterialDesc, MaterialShaderKind, Primitive, COMPONENT_MATERIAL_DESC,
use bevy::{
image::{
ImageAddressMode, ImageFilterMode, ImageLoaderSettings, ImageSampler,
ImageSamplerDescriptor,
},
prelude::*,
};
#[allow(clippy::type_complexity)]
pub fn hydrate_materials(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut materials: ResMut<Assets<StandardMaterial>>,
targets: Query<
(
Entity,
&MaterialDesc,
Option<&AuthoringComponentStates>,
Option<&InspectorOrder>,
),
(
With<LevelObject>,
With<Mesh3d>,
Or<(
Changed<MaterialDesc>,
Added<Mesh3d>,
Changed<Primitive>,
Changed<AuthoringComponentStates>,
Changed<InspectorOrder>,
)>,
),
>,
) {
for (entity, desc, states, legacy_order) in &targets {
if !authoring_component_active(states, legacy_order, COMPONENT_MATERIAL_DESC) {
commands
.entity(entity)
.remove::<MeshMaterial3d<StandardMaterial>>();
continue;
}
let material = materials.add(material_from_desc(&asset_server, desc));
commands.entity(entity).insert(MeshMaterial3d(material));
}
}
use crate::{
asset_server_path, MaterialDesc, MaterialShaderKind, RuntimeTextureLoadSpec, TextureFilter,
TextureWrap,
};
pub fn material_from_desc(asset_server: &AssetServer, desc: &MaterialDesc) -> StandardMaterial {
material_from_desc_with_texture_loader(asset_server, desc, |path| {
asset_server.load(asset_server_path(path))
})
}
pub fn material_from_desc_with_texture_loader(
_asset_server: &AssetServer,
desc: &MaterialDesc,
mut load_texture: impl FnMut(&str) -> Handle<Image>,
) -> StandardMaterial {
StandardMaterial {
base_color: desc.base_color.to_color(),
metallic: desc.metallic,
@@ -53,7 +32,7 @@ pub fn material_from_desc(asset_server: &AssetServer, desc: &MaterialDesc) -> St
base_color_texture: desc
.base_color_texture
.as_ref()
.map(|path| asset_server.load(asset_server_path(path))),
.map(|path| load_texture(path)),
emissive: LinearRgba::rgb(
desc.emissive_color.r * desc.emissive_intensity,
desc.emissive_color.g * desc.emissive_intensity,
@@ -62,19 +41,70 @@ pub fn material_from_desc(asset_server: &AssetServer, desc: &MaterialDesc) -> St
emissive_texture: desc
.emissive_texture
.as_ref()
.map(|path| asset_server.load(asset_server_path(path))),
.map(|path| load_texture(path)),
normal_map_texture: desc
.normal_map_texture
.as_ref()
.map(|path| asset_server.load(asset_server_path(path))),
.map(|path| load_texture(path)),
metallic_roughness_texture: desc
.metallic_roughness_texture
.as_ref()
.map(|path| asset_server.load(asset_server_path(path))),
.map(|path| load_texture(path)),
occlusion_texture: desc
.occlusion_texture
.as_ref()
.map(|path| load_texture(path)),
uv_transform: bevy::math::Affine2::from_scale_angle_translation(
desc.uv_tiling,
0.0,
desc.uv_offset,
),
..default()
}
}
pub fn load_runtime_texture(
asset_server: &AssetServer,
spec: &RuntimeTextureLoadSpec,
) -> Handle<Image> {
let sampler = ImageSampler::Descriptor(runtime_image_sampler_descriptor(spec));
let is_srgb = spec.is_srgb;
asset_server
.load_builder()
.with_settings(move |settings: &mut ImageLoaderSettings| {
settings.is_srgb = is_srgb;
settings.sampler = sampler.clone();
})
.load(asset_server_path(&spec.path))
}
pub fn runtime_image_sampler_descriptor(spec: &RuntimeTextureLoadSpec) -> ImageSamplerDescriptor {
let address_mode = match spec.wrap {
TextureWrap::Repeat => ImageAddressMode::Repeat,
TextureWrap::Clamp => ImageAddressMode::ClampToEdge,
TextureWrap::Mirror => ImageAddressMode::MirrorRepeat,
};
let filter = match spec.filter {
TextureFilter::Nearest => ImageFilterMode::Nearest,
TextureFilter::Linear => ImageFilterMode::Linear,
};
let anisotropy = if filter == ImageFilterMode::Linear {
spec.anisotropy.clamp(1, 16)
} else {
1
};
ImageSamplerDescriptor {
address_mode_u: address_mode,
address_mode_v: address_mode,
address_mode_w: address_mode,
mag_filter: filter,
min_filter: filter,
mipmap_filter: filter,
anisotropy_clamp: anisotropy,
..Default::default()
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -97,4 +127,46 @@ mod tests {
assert_eq!(material.emissive.green, 250.0);
assert_eq!(material.emissive.blue, 1000.0);
}
#[test]
fn shared_uv_transform_maps_to_standard_material() {
let mut app = App::new();
app.add_plugins((MinimalPlugins, AssetPlugin::default()));
let asset_server = app.world().resource::<AssetServer>();
let desc = MaterialDesc {
uv_offset: Vec2::new(0.25, -0.5),
uv_tiling: Vec2::new(4.0, 2.0),
..Default::default()
};
let material = material_from_desc(asset_server, &desc);
assert_eq!(material.uv_transform.translation, desc.uv_offset);
assert_eq!(material.uv_transform.matrix2.x_axis.x, desc.uv_tiling.x);
assert_eq!(material.uv_transform.matrix2.y_axis.y, desc.uv_tiling.y);
}
#[test]
fn runtime_sampler_maps_authored_wrap_filter_and_anisotropy() {
let spec = RuntimeTextureLoadSpec {
path: "texture.basis".into(),
is_srgb: false,
filter: TextureFilter::Linear,
wrap: TextureWrap::Repeat,
anisotropy: 64,
};
let sampler = runtime_image_sampler_descriptor(&spec);
assert_eq!(sampler.address_mode_u, ImageAddressMode::Repeat);
assert_eq!(sampler.address_mode_v, ImageAddressMode::Repeat);
assert_eq!(sampler.address_mode_w, ImageAddressMode::Repeat);
assert_eq!(sampler.min_filter, ImageFilterMode::Linear);
assert_eq!(sampler.anisotropy_clamp, 16);
let mut nearest = spec;
nearest.filter = TextureFilter::Nearest;
nearest.wrap = TextureWrap::Mirror;
let sampler = runtime_image_sampler_descriptor(&nearest);
assert_eq!(sampler.address_mode_u, ImageAddressMode::MirrorRepeat);
assert_eq!(sampler.anisotropy_clamp, 1);
}
}
+89 -65
View File
@@ -21,8 +21,10 @@ use bevy::prelude::*;
use brushes::{hydrate_brushes, spawn_brush_mesh, HydratedBrushMesh};
use lights::{hydrate_lights, reconcile_missing_runtime_lights};
use materials::hydrate_materials;
pub use materials::material_from_desc;
pub use materials::{
load_runtime_texture, material_from_desc, material_from_desc_with_texture_loader,
runtime_image_sampler_descriptor,
};
use models::hydrate_models;
pub use models::HydratedModelRoot;
use physics::hydrate_physics;
@@ -34,9 +36,9 @@ use skinned_meshes::{
apply_skinned_renderer_material_changes, cleanup_removed_skinned_mesh_renderers,
hydrate_skinned_mesh_renderers, mark_skinned_materials_ready,
};
pub use static_meshes::StaticMeshArtifactCache;
use static_meshes::{
hydrate_static_mesh_renderers, spawn_static_mesh_parts, HydratedStaticMeshPart,
StaticMeshArtifactCache,
};
pub use terrain::HydratedTerrainChunk;
use terrain::{cleanup_removed_terrain, hydrate_terrain};
@@ -48,11 +50,32 @@ use visibility::{
use crate::{
authoring_component_active, AuthoringComponentStates, BrushDesc, ColliderDesc, InspectorOrder,
LevelObject, MaterialDesc, MaterialOverride, Primitive, StaticMeshRenderer,
COMPONENT_BRUSH_DESC, COMPONENT_COLLIDER_DESC, COMPONENT_LIGHT_DESC, COMPONENT_MATERIAL_DESC,
COMPONENT_PRIMITIVE, COMPONENT_STATIC_MESH_RENDERER,
LevelObject, MaterialDesc, Primitive, StaticMeshRenderer, COMPONENT_BRUSH_DESC,
COMPONENT_COLLIDER_DESC, COMPONENT_LIGHT_DESC, COMPONENT_MATERIAL_DESC, COMPONENT_PRIMITIVE,
COMPONENT_STATIC_MESH_RENDERER,
};
/// One neutral emergency handle used until the Surface plugin replaces it with embedded DefaultGrid.
#[derive(Resource, Default, Debug, Clone)]
pub struct DefaultGridEmergencyMaterial(pub Option<Handle<StandardMaterial>>);
pub(crate) fn default_grid_emergency_handle(
materials: &mut Assets<StandardMaterial>,
fallback: &mut DefaultGridEmergencyMaterial,
) -> Handle<StandardMaterial> {
fallback
.0
.get_or_insert_with(|| {
materials.add(StandardMaterial {
base_color: Color::srgb(0.46, 0.46, 0.46),
perceptual_roughness: 0.86,
cull_mode: None,
..default()
})
})
.clone()
}
/// Registers hydration systems in deterministic order.
pub struct HydrationPlugin;
@@ -65,6 +88,7 @@ enum HydrationSet {
impl Plugin for HydrationPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<StaticMeshArtifactCache>()
.init_resource::<DefaultGridEmergencyMaterial>()
.add_observer(tag_hydrated_prefab_members)
.add_observer(mark_skinned_materials_ready)
.add_observer(crate::prefab_overrides::apply_prefab_overrides_on_ready)
@@ -78,7 +102,6 @@ impl Plugin for HydrationPlugin {
hydrate_primitives,
hydrate_brushes,
hydrate_terrain,
hydrate_materials,
hydrate_lights,
reconcile_missing_runtime_lights,
hydrate_static_mesh_renderers,
@@ -115,6 +138,9 @@ pub fn flush_level_object_hydration(world: &mut World) {
if !world.contains_resource::<StaticMeshArtifactCache>() {
world.insert_resource(StaticMeshArtifactCache::default());
}
if !world.contains_resource::<DefaultGridEmergencyMaterial>() {
world.insert_resource(DefaultGridEmergencyMaterial::default());
}
initialize_level_object_visibility_hierarchy(world);
@@ -132,20 +158,6 @@ pub fn flush_level_object_hydration(world: &mut World) {
.map(|(entity, primitive, _, _)| (entity, primitive.clone()))
.collect();
let material_targets: Vec<(Entity, MaterialDesc)> = world
.query_filtered::<(
Entity,
&MaterialDesc,
Option<&AuthoringComponentStates>,
Option<&InspectorOrder>,
), With<LevelObject>>()
.iter(world)
.filter(|(_, _, states, order)| {
authoring_component_active(*states, *order, COMPONENT_MATERIAL_DESC)
})
.map(|(entity, desc, _, _)| (entity, desc.clone()))
.collect();
let brush_entities_for_cleanup: Vec<Entity> = world
.query_filtered::<(Entity, &BrushDesc), With<LevelObject>>()
.iter(world)
@@ -190,45 +202,27 @@ pub fn flush_level_object_hydration(world: &mut World) {
.map(|(entity, _)| entity)
.collect();
let static_mesh_renderers: Vec<(
Entity,
StaticMeshRenderer,
Option<MaterialDesc>,
Option<MaterialOverride>,
Option<ColliderDesc>,
)> = world
let static_mesh_renderers: Vec<(Entity, StaticMeshRenderer, Option<ColliderDesc>)> = world
.query_filtered::<(
Entity,
&StaticMeshRenderer,
Option<&MaterialDesc>,
Option<&MaterialOverride>,
Option<&ColliderDesc>,
Option<&AuthoringComponentStates>,
Option<&InspectorOrder>,
), With<LevelObject>>()
.iter(world)
.filter(|(_, _, _, _, _, states, order)| {
.filter(|(_, _, _, states, order)| {
authoring_component_active(*states, *order, COMPONENT_STATIC_MESH_RENDERER)
})
.map(
|(entity, renderer, material, material_override, collider, states, order)| {
(
entity,
renderer.clone(),
material
.filter(|_| {
authoring_component_active(states, order, COMPONENT_MATERIAL_DESC)
})
.cloned(),
material_override.cloned(),
collider
.filter(|_| {
authoring_component_active(states, order, COMPONENT_COLLIDER_DESC)
})
.cloned(),
)
},
)
.map(|(entity, renderer, collider, states, order)| {
(
entity,
renderer.clone(),
collider
.filter(|_| authoring_component_active(states, order, COMPONENT_COLLIDER_DESC))
.cloned(),
)
})
.collect();
let mut generated_static_mesh_parts = Vec::new();
@@ -285,21 +279,33 @@ pub fn flush_level_object_hydration(world: &mut World) {
ResMut<Assets<Mesh>>,
ResMut<Assets<StandardMaterial>>,
ResMut<StaticMeshArtifactCache>,
ResMut<DefaultGridEmergencyMaterial>,
)> = SystemState::new(world);
{
let (mut commands, asset_server, mut meshes, mut materials, mut artifact_cache) = state
let (
mut commands,
asset_server,
mut meshes,
mut materials,
mut artifact_cache,
mut fallback,
) = state
.get_mut(world)
.expect("hydrate_level_objects system params should be valid");
for (entity, primitive) in primitives {
let mesh = meshes.add(primitive_mesh(&primitive));
commands.entity(entity).insert(Mesh3d(mesh));
}
for (entity, desc) in material_targets {
let material = materials.add(material_from_desc(&asset_server, &desc));
commands.entity(entity).insert(MeshMaterial3d(material));
let material = default_grid_emergency_handle(&mut materials, &mut fallback);
commands.entity(entity).insert((
Mesh3d(mesh),
MeshMaterial3d(material),
crate::HydratedMaterialSlotBinding {
owner: entity,
slot_id: primitive.surface.id.clone(),
selection: primitive.surface.hydrated_selection(),
},
));
}
for child in generated_brush_meshes {
@@ -312,6 +318,7 @@ pub fn flush_level_object_hydration(world: &mut World) {
&asset_server,
&mut meshes,
&mut materials,
&mut fallback,
*entity,
brush,
material.as_ref(),
@@ -323,16 +330,15 @@ pub fn flush_level_object_hydration(world: &mut World) {
commands.entity(child).despawn();
}
for (entity, renderer, material, material_override, collider) in &static_mesh_renderers {
for (entity, renderer, collider) in &static_mesh_renderers {
spawn_static_mesh_parts(
&mut commands,
&asset_server,
&mut materials,
&mut artifact_cache,
&mut fallback,
*entity,
renderer,
material.as_ref(),
material_override.as_ref(),
collider.as_ref(),
);
}
@@ -510,7 +516,7 @@ mod tests {
}
#[test]
fn flush_hydration_spawns_mesh_material_from_primitive_and_desc() {
fn primitive_legacy_descriptors_do_not_create_actor_local_materials() {
let mut app = App::new();
app.add_plugins(MinimalPlugins);
app.add_plugins(AssetPlugin::default());
@@ -518,7 +524,7 @@ mod tests {
app.init_asset::<Mesh>();
let material = MaterialDesc::new(ColorDesc::srgb(0.85, 0.85, 0.88), 0.0, 0.3);
let entity = app
let first = app
.world_mut()
.spawn((
LevelObject,
@@ -526,13 +532,31 @@ mod tests {
material,
))
.id();
let second = app
.world_mut()
.spawn((
LevelObject,
Primitive::sphere(1.0),
MaterialDesc::new(ColorDesc::srgb(0.1, 0.8, 0.2), 1.0, 0.05),
))
.id();
flush_level_object_hydration(app.world_mut());
assert!(app.world().get::<Mesh3d>(entity).is_some());
let first_handle = app
.world()
.get::<MeshMaterial3d<StandardMaterial>>(first)
.unwrap();
let second_handle = app
.world()
.get::<MeshMaterial3d<StandardMaterial>>(second)
.unwrap();
assert_eq!(first_handle.0, second_handle.0);
assert!(app
.world()
.get::<MeshMaterial3d<StandardMaterial>>(entity)
.is_some());
.get::<crate::HydratedMaterialSlotBinding>(first)
.is_some_and(|binding| {
matches!(binding.selection, crate::HydratedMaterialSelection::Inherit)
}));
}
}
+13 -1
View File
@@ -2,6 +2,7 @@
use bevy::prelude::*;
use super::{default_grid_emergency_handle, DefaultGridEmergencyMaterial};
use crate::{
authoring_component_active, AuthoringComponentStates, InspectorOrder, LevelObject, Primitive,
PrimitiveShape, COMPONENT_PRIMITIVE,
@@ -49,6 +50,8 @@ pub fn hydrate_primitives(
),
>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut fallback: ResMut<DefaultGridEmergencyMaterial>,
) {
for (entity, primitive, states, legacy_order) in &primitives {
if !authoring_component_active(states, legacy_order, COMPONENT_PRIMITIVE) {
@@ -59,8 +62,17 @@ pub fn hydrate_primitives(
continue;
}
let mesh = meshes.add(primitive_mesh(primitive));
let material = default_grid_emergency_handle(&mut materials, &mut fallback);
commands.entity(entity).insert(Mesh3d(mesh));
commands.entity(entity).insert((
Mesh3d(mesh),
MeshMaterial3d(material),
crate::HydratedMaterialSlotBinding {
owner: entity,
slot_id: primitive.surface.id.clone(),
selection: primitive.surface.hydrated_selection(),
},
));
}
}
+19 -20
View File
@@ -10,13 +10,14 @@ use serde::Deserialize;
use crate::{
asset_server_path, authoring_component_active, AuthoringComponentStates,
HydratedRendererMaterialBinding, InspectorOrder, LevelObject, SkinnedMeshRenderer,
HydratedMaterialSlotBinding, InspectorOrder, LevelObject, SkinnedMeshRenderer,
ANIMATION_ARTIFACT_DIR, COMPONENT_SKINNED_MESH_RENDERER,
};
use super::static_meshes::{
renderer_error_material, resolve_renderer_material_handle, StaticMeshArtifactCache,
};
use super::DefaultGridEmergencyMaterial;
/// Runtime hierarchy root generated for one authored [`SkinnedMeshRenderer`].
///
@@ -176,6 +177,7 @@ pub(super) fn apply_skinned_renderer_material_changes(
asset_server: Res<AssetServer>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut artifact_cache: ResMut<StaticMeshArtifactCache>,
mut fallback: ResMut<DefaultGridEmergencyMaterial>,
dirty_roots: Query<(Entity, &HydratedSkinnedMeshRoot), With<SkinnedMaterialsDirty>>,
renderers: Query<&SkinnedMeshRenderer>,
children: Query<&Children>,
@@ -238,30 +240,27 @@ pub(super) fn apply_skinned_renderer_material_changes(
continue;
};
used.insert(*entity);
let effective = slot.effective_material().cloned();
let Some(reference) = effective.as_ref() else {
commands
.entity(*entity)
.insert(HydratedRendererMaterialBinding {
owner: root.owner,
slot_id: slot.id.clone(),
effective_material: None,
});
continue;
let mut selection = slot.hydrated_selection();
if matches!(selection, crate::HydratedMaterialSelection::Inherit) {
selection =
artifact_cache.resolve_model_material_selection(&renderer.asset_id, &slot.id);
}
let handle = match &selection {
crate::HydratedMaterialSelection::ImportedSource { reference } => {
resolve_renderer_material_handle(&asset_server, &mut artifact_cache, reference)
.unwrap_or_else(|| renderer_error_material(&mut materials, &mut fallback))
}
crate::HydratedMaterialSelection::Project { .. }
| crate::HydratedMaterialSelection::Inherit => {
renderer_error_material(&mut materials, &mut fallback)
}
};
let handle = resolve_renderer_material_handle(
&asset_server,
&mut materials,
&mut artifact_cache,
reference,
)
.unwrap_or_else(|| renderer_error_material(&mut materials));
commands.entity(*entity).insert((
MeshMaterial3d(handle),
HydratedRendererMaterialBinding {
HydratedMaterialSlotBinding {
owner: root.owner,
slot_id: slot.id.clone(),
effective_material: effective,
selection,
},
));
}
+93 -130
View File
@@ -3,19 +3,19 @@
use avian3d::prelude::ColliderConstructor;
use bevy::light::{NotShadowCaster, NotShadowReceiver};
use bevy::prelude::*;
use bevy::render::render_resource::Face;
use serde::Deserialize;
use std::collections::{HashMap, HashSet};
use crate::{
asset_server_path, authoring_component_active, standard_material_asset_path,
AuthoringComponentStates, ColliderDesc, ColliderShapeDesc, EditorAssetRef,
HydratedRendererMaterialBinding, InspectorOrder, LevelObject, MaterialAlphaMode, MaterialDesc,
MaterialOverride, MaterialRef, StaticMeshRenderer, StaticMeshRendererEntry,
COMPONENT_COLLIDER_DESC, COMPONENT_MATERIAL_DESC, COMPONENT_STATIC_MESH_RENDERER,
HydratedMaterialLayer, HydratedMaterialSelection, HydratedMaterialSlotBinding, InspectorOrder,
LevelObject, MaterialRef, ModelMaterialSelection, ModelMaterialSlotSelection,
StaticMeshRenderer, StaticMeshRendererEntry, COMPONENT_COLLIDER_DESC,
COMPONENT_STATIC_MESH_RENDERER,
};
use super::materials::material_from_desc;
use super::{default_grid_emergency_handle, DefaultGridEmergencyMaterial};
pub const STATIC_MESH_ARTIFACT_DIR: &str = "assets/meshes/generated";
@@ -28,7 +28,6 @@ pub struct HydratedStaticMeshPart;
struct ResolvedStaticMeshPart {
source_path: String,
mesh_label: String,
material_label: Option<String>,
}
#[derive(Debug, Clone)]
@@ -48,10 +47,10 @@ pub(crate) struct ResolvedRendererDraw {
pub struct StaticMeshArtifactCache {
parts: HashMap<(String, String), ResolvedStaticMeshPart>,
materials: HashMap<(String, String), ResolvedStaticMeshMaterial>,
model_materials: HashMap<(String, String), HydratedMaterialSelection>,
draw_bindings: HashMap<(String, String), ResolvedRendererDraw>,
loaded_assets: HashSet<String>,
failed_assets: HashSet<String>,
project_materials: HashMap<MaterialRef, Handle<StandardMaterial>>,
}
impl StaticMeshArtifactCache {
@@ -70,6 +69,18 @@ impl StaticMeshArtifactCache {
self.draw_bindings.get(&key).cloned()
}
pub(crate) fn resolve_model_material_selection(
&mut self,
asset_id: &str,
slot_id: &crate::ComponentInstanceId,
) -> HydratedMaterialSelection {
let key = (asset_id.to_string(), slot_id.0.clone());
if !self.loaded_assets.contains(asset_id) && !self.failed_assets.contains(asset_id) {
self.load_artifact(asset_id);
}
self.model_materials.get(&key).cloned().unwrap_or_default()
}
fn resolve(&mut self, mesh: &EditorAssetRef) -> Option<ResolvedStaticMeshPart> {
if !mesh.is_resolved() {
return None;
@@ -122,7 +133,7 @@ impl StaticMeshArtifactCache {
};
let slot_id = format!("slot:{part_id}");
self.draw_bindings.insert(
(asset_id.to_string(), slot_id),
(asset_id.to_string(), slot_id.clone()),
ResolvedRendererDraw {
mesh_label: part.mesh_label.clone(),
source_node: part.source_node.clone(),
@@ -141,6 +152,39 @@ impl StaticMeshArtifactCache {
material_label,
});
}
let model_selection = manifest
.import
.material_slots
.iter()
.find(|selection| selection.slot_id.0 == slot_id)
.map(|selection| selection.selection.clone())
.unwrap_or(ModelMaterialSelection::Source);
let hydrated_selection = match model_selection {
ModelMaterialSelection::Project(reference) => {
HydratedMaterialSelection::Project {
reference,
layer: HydratedMaterialLayer::Model,
}
}
ModelMaterialSelection::Default => HydratedMaterialSelection::Inherit,
ModelMaterialSelection::Source => part
.material_id
.clone()
.filter(|id| !id.trim().is_empty())
.or_else(|| part.material_label.as_deref().map(material_id_from_label))
.map(|material_id| HydratedMaterialSelection::ImportedSource {
reference: MaterialRef::new(EditorAssetRef::new(
asset_id,
material_id,
part.material_label
.clone()
.unwrap_or_else(|| "Imported Material".into()),
)),
})
.unwrap_or_default(),
};
self.model_materials
.insert((asset_id.to_string(), slot_id), hydrated_selection);
if part.skinned
|| manifest.metadata.animation_count > 0
|| manifest.metadata.skin_count > 0
@@ -156,7 +200,6 @@ impl StaticMeshArtifactCache {
ResolvedStaticMeshPart {
source_path: manifest.source.path.clone(),
mesh_label: part.mesh_label.clone(),
material_label: part.material_label.clone(),
},
);
}
@@ -174,11 +217,19 @@ impl StaticMeshArtifactCache {
struct StaticMeshResolveManifest {
source: StaticMeshResolveSource,
#[serde(default)]
import: StaticMeshResolveImport,
#[serde(default)]
metadata: StaticMeshResolveMetadata,
#[serde(default)]
parts: Vec<StaticMeshResolvePart>,
}
#[derive(Debug, Default, Deserialize)]
struct StaticMeshResolveImport {
#[serde(default)]
material_slots: Vec<ModelMaterialSlotSelection>,
}
#[derive(Debug, Default, Deserialize)]
struct StaticMeshResolveMetadata {
#[serde(default)]
@@ -208,17 +259,20 @@ struct StaticMeshResolvePart {
}
#[allow(clippy::type_complexity)]
#[expect(
clippy::too_many_arguments,
reason = "Bevy system parameters keep independently change-tracked renderer inputs explicit"
)]
pub fn hydrate_static_mesh_renderers(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut artifact_cache: ResMut<StaticMeshArtifactCache>,
mut fallback: ResMut<DefaultGridEmergencyMaterial>,
renderers: Query<
(
Entity,
&StaticMeshRenderer,
Option<&MaterialDesc>,
Option<&MaterialOverride>,
Option<&ColliderDesc>,
Option<&AuthoringComponentStates>,
Option<&InspectorOrder>,
@@ -228,8 +282,6 @@ pub fn hydrate_static_mesh_renderers(
Or<(
Added<StaticMeshRenderer>,
Changed<StaticMeshRenderer>,
Changed<MaterialDesc>,
Changed<MaterialOverride>,
Changed<ColliderDesc>,
Changed<AuthoringComponentStates>,
Changed<InspectorOrder>,
@@ -239,15 +291,11 @@ pub fn hydrate_static_mesh_renderers(
children: Query<&Children>,
generated_parts: Query<(), With<HydratedStaticMeshPart>>,
) {
for (entity, renderer, parent_material, material_override, collider, states, order) in
&renderers
{
for (entity, renderer, collider, states, order) in &renderers {
despawn_static_mesh_parts(&mut commands, entity, &children, &generated_parts);
if !authoring_component_active(states, order, COMPONENT_STATIC_MESH_RENDERER) {
continue;
}
let parent_material = parent_material
.filter(|_| authoring_component_active(states, order, COMPONENT_MATERIAL_DESC));
let collider =
collider.filter(|_| authoring_component_active(states, order, COMPONENT_COLLIDER_DESC));
spawn_static_mesh_parts(
@@ -255,10 +303,9 @@ pub fn hydrate_static_mesh_renderers(
&asset_server,
&mut materials,
&mut artifact_cache,
&mut fallback,
entity,
renderer,
parent_material,
material_override,
collider,
);
}
@@ -273,10 +320,9 @@ pub fn spawn_static_mesh_parts(
asset_server: &AssetServer,
materials: &mut Assets<StandardMaterial>,
artifact_cache: &mut StaticMeshArtifactCache,
fallback: &mut DefaultGridEmergencyMaterial,
parent: Entity,
renderer: &StaticMeshRenderer,
parent_material: Option<&MaterialDesc>,
material_override: Option<&MaterialOverride>,
collider: Option<&ColliderDesc>,
) {
let mut spawned = 0usize;
@@ -295,15 +341,22 @@ pub fn spawn_static_mesh_parts(
let source_path = asset_server_path(&resolved.source_path);
let mesh_handle: Handle<Mesh> =
asset_server.load(labeled_asset_path(&source_path, &resolved.mesh_label));
let material_handle = material_for_entry(
let material_slot_id = effective_material_slot_id(entry);
let selection = renderer
.materials
.slot(&material_slot_id)
.map(crate::MaterialSlot::hydrated_selection)
.filter(|selection| !matches!(selection, HydratedMaterialSelection::Inherit))
.unwrap_or_else(|| {
artifact_cache
.resolve_model_material_selection(&entry.mesh.asset_id, &material_slot_id)
});
let material_handle = material_for_selection(
asset_server,
materials,
artifact_cache,
renderer,
entry,
&resolved,
parent_material,
material_override,
fallback,
&selection,
);
let name = if entry.name.trim().is_empty() {
format!("Static Mesh Part {index}")
@@ -316,10 +369,10 @@ pub fn spawn_static_mesh_parts(
Name::new(name),
Mesh3d(mesh_handle),
MeshMaterial3d(material_handle),
HydratedRendererMaterialBinding {
HydratedMaterialSlotBinding {
owner: parent,
slot_id: effective_material_slot_id(entry),
effective_material: effective_material_ref(renderer, entry).cloned(),
slot_id: material_slot_id,
selection,
},
entry.local_transform,
Visibility::Visible,
@@ -361,37 +414,15 @@ pub fn despawn_static_mesh_parts(
}
#[allow(clippy::too_many_arguments)]
fn material_for_entry(
fn material_for_selection(
asset_server: &AssetServer,
materials: &mut Assets<StandardMaterial>,
artifact_cache: &mut StaticMeshArtifactCache,
renderer: &StaticMeshRenderer,
entry: &StaticMeshRendererEntry,
resolved: &ResolvedStaticMeshPart,
parent_material: Option<&MaterialDesc>,
material_override: Option<&MaterialOverride>,
fallback: &mut DefaultGridEmergencyMaterial,
selection: &HydratedMaterialSelection,
) -> Handle<StandardMaterial> {
if let Some(parent_material) = parent_material {
return materials.add(material_from_desc(asset_server, parent_material));
}
if let Some(override_material) = material_override.and_then(|overrides| {
overrides
.slots
.iter()
.find(|slot| slot.slot_id == entry.id)
.map(|slot| &slot.material)
}) {
return materials.add(material_from_desc(asset_server, override_material));
}
if let Some(material_ref) = effective_material_ref(renderer, entry) {
if let Some(handle) =
resolve_shared_material(asset_server, materials, artifact_cache, material_ref)
{
return handle;
}
if let Some(resolved_material) = artifact_cache.resolve_material(&material_ref.0) {
if let HydratedMaterialSelection::ImportedSource { reference } = selection {
if let Some(resolved_material) = artifact_cache.resolve_material(&reference.0) {
let source_path = asset_server_path(&resolved_material.source_path);
return asset_server.load(standard_material_asset_path(
&source_path,
@@ -400,34 +431,10 @@ fn material_for_entry(
}
debug!(
"Static mesh material ref unresolved: asset_id='{}' material='{}' label='{}'",
material_ref.0.asset_id, material_ref.0.sub_asset_id, material_ref.0.label
reference.0.asset_id, reference.0.sub_asset_id, reference.0.label
);
}
// Read-only compatibility path for schema-v1/v2 scenes. The explicit project upgrader moves
// this reference into `RendererMaterialSet` and clears the legacy draw-part field.
if let Some(material_ref) = entry.material.as_ref() {
let material_ref = MaterialRef::new(material_ref.clone());
if let Some(handle) =
resolve_shared_material(asset_server, materials, artifact_cache, &material_ref)
{
return handle;
}
if let Some(resolved_material) = artifact_cache.resolve_material(&material_ref.0) {
let source_path = asset_server_path(&resolved_material.source_path);
return asset_server.load(standard_material_asset_path(
&source_path,
&resolved_material.material_label,
));
}
}
if let Some(label) = resolved.material_label.as_deref() {
let source_path = asset_server_path(&resolved.source_path);
return asset_server.load(standard_material_asset_path(&source_path, label));
}
materials.add(error_material())
default_grid_emergency_handle(materials, fallback)
}
fn effective_material_slot_id(entry: &StaticMeshRendererEntry) -> crate::ComponentInstanceId {
@@ -438,47 +445,11 @@ fn effective_material_slot_id(entry: &StaticMeshRendererEntry) -> crate::Compone
}
}
fn effective_material_ref<'a>(
renderer: &'a StaticMeshRenderer,
entry: &'a StaticMeshRendererEntry,
) -> Option<&'a MaterialRef> {
let slot_id = effective_material_slot_id(entry);
renderer.materials.effective_material(&slot_id)
}
fn resolve_shared_material(
asset_server: &AssetServer,
materials: &mut Assets<StandardMaterial>,
cache: &mut StaticMeshArtifactCache,
reference: &MaterialRef,
) -> Option<Handle<StandardMaterial>> {
if let Some(handle) = cache.project_materials.get(reference) {
return Some(handle.clone());
}
let path = reference.0.source_path.as_deref()?;
let desc_and_state = crate::load_resolved_material_from_path(path).ok()?;
let mut material = material_from_desc(asset_server, &desc_and_state.0);
material.alpha_mode = match desc_and_state.1.alpha_mode {
MaterialAlphaMode::Opaque => AlphaMode::Opaque,
MaterialAlphaMode::Cutout => AlphaMode::Mask(desc_and_state.1.alpha_cutoff),
};
material.cull_mode = (!desc_and_state.1.double_sided).then_some(Face::Back);
let handle = materials.add(material);
cache
.project_materials
.insert(reference.clone(), handle.clone());
Some(handle)
}
pub(crate) fn resolve_renderer_material_handle(
asset_server: &AssetServer,
materials: &mut Assets<StandardMaterial>,
cache: &mut StaticMeshArtifactCache,
reference: &MaterialRef,
) -> Option<Handle<StandardMaterial>> {
if let Some(handle) = resolve_shared_material(asset_server, materials, cache, reference) {
return Some(handle);
}
let resolved = cache.resolve_material(&reference.0)?;
let source_path = asset_server_path(&resolved.source_path);
Some(asset_server.load(standard_material_asset_path(
@@ -489,17 +460,9 @@ pub(crate) fn resolve_renderer_material_handle(
pub(crate) fn renderer_error_material(
materials: &mut Assets<StandardMaterial>,
fallback: &mut DefaultGridEmergencyMaterial,
) -> Handle<StandardMaterial> {
materials.add(error_material())
}
fn error_material() -> StandardMaterial {
StandardMaterial {
base_color: Color::srgb(1.0, 0.0, 1.0),
perceptual_roughness: 0.35,
metallic: 0.0,
..default()
}
default_grid_emergency_handle(materials, fallback)
}
fn labeled_asset_path(path: &str, label: &str) -> String {
+39 -7
View File
@@ -9,8 +9,10 @@ mod animation;
mod asset_fingerprint;
pub mod brush_math;
mod components;
pub mod content;
mod hydration;
mod material_asset;
mod material_desc;
mod navigation;
mod post_process_effect_asset;
mod prefab_overrides;
@@ -21,17 +23,24 @@ pub use actor::{infer_actor_kind, validate_actor, ActorValidationError};
pub use animation::*;
pub use asset_fingerprint::AssetSourceFingerprint;
pub use components::*;
pub use content::*;
pub use hydration::{
cascade_config_from_rendering, flush_level_object_hydration,
initialize_level_object_visibility_hierarchy, material_from_desc, strip_hydrated,
initialize_level_object_visibility_hierarchy, load_runtime_texture, material_from_desc,
material_from_desc_with_texture_loader, runtime_image_sampler_descriptor, strip_hydrated,
strip_hydrated_entity, HydratedModelRoot, HydratedPrefabMember, HydratedPrefabReady,
HydratedSkinnedMeshRoot, HydratedTerrainChunk, HydrationPlugin, PrefabHydrationBlocked,
StaticMeshArtifactCache,
};
pub use material_asset::{
load_resolved_material_from_path, MaterialAlphaMode, MaterialAsset, MaterialInstanceAsset,
MaterialRenderState, ShaderPropertyDesc, ShaderPropertyType, ShaderSchemaAsset,
MATERIAL_ASSET_SCHEMA_VERSION, MATERIAL_INSTANCE_SCHEMA_VERSION, SURFACE_SHADER_SCHEMA_VERSION,
load_resolved_material_from_path, standard_lit_input_schema, MaterialAlphaMode, MaterialAsset,
MaterialInputDesc, MaterialInputGroupDesc, MaterialInputPresentation, MaterialInputSchema,
MaterialInputSet, MaterialInstanceAsset, MaterialProvenance, MaterialRenderState,
MaterialTextureInputDesc, ShaderPropertyDesc, ShaderPropertyType, ShaderSchemaAsset,
TextureSemantic, MATERIAL_ASSET_SCHEMA_VERSION, MATERIAL_INSTANCE_SCHEMA_VERSION,
SURFACE_SHADER_SCHEMA_VERSION,
};
pub use material_desc::*;
pub use navigation::*;
pub use post_process_effect_asset::{PostProcessEffectAsset, PostProcessEffectKind};
pub use prefab_overrides::{
@@ -69,7 +78,7 @@ pub fn standard_material_asset_path(asset_path: &str, material_label: &str) -> S
format!("{asset_path}#{label}")
}
use bevy::prelude::*;
use bevy::prelude::{App, Commands, Entity, Plugin, Query, Update, With, Without};
/// Registers all reflectable authoring types and installs hydration systems.
pub struct SharedTypesPlugin;
@@ -88,8 +97,8 @@ impl Plugin for SharedTypesPlugin {
.register_type::<ComponentInstanceId>()
.register_type::<EditorAssetRef>()
.register_type::<MaterialRef>()
.register_type::<RendererMaterialSlot>()
.register_type::<RendererMaterialSet>()
.register_type::<MaterialSlot>()
.register_type::<MaterialSlotSet>()
.register_type::<OrphanedMaterialAssignment>()
.register_type::<AnimationSkeletonSignature>()
.register_type::<SkinnedMeshRenderer>()
@@ -131,6 +140,8 @@ impl Plugin for SharedTypesPlugin {
.register_type::<MaterialParameterValue>()
.register_type::<MaterialParameter>()
.register_type::<MaterialTextureBinding>()
.register_type::<MaterialPropertyBlock>()
.register_type::<MaterialPropertyBlocks>()
.register_type::<MaterialSlotOverride>()
.register_type::<MaterialOverride>()
.register_type::<ColorDesc>()
@@ -183,6 +194,27 @@ fn migrate_legacy_authoring_component_states(
#[cfg(test)]
mod tests {
use super::*;
use bevy::{ecs::reflect::AppTypeRegistry, reflect::TypeInfo};
#[test]
fn runtime_material_property_blocks_are_registered_for_editor_tooling() {
let mut app = App::new();
app.add_plugins(SharedTypesPlugin);
let registry = app.world().resource::<AppTypeRegistry>().read();
let block = registry
.get(std::any::TypeId::of::<MaterialPropertyBlock>())
.expect("MaterialPropertyBlock must be registered");
let TypeInfo::Struct(block_info) = block.type_info() else {
panic!("MaterialPropertyBlock must reflect as a struct");
};
assert!(block_info.field("parameters").is_some());
assert!(block_info.field("textures").is_some());
assert!(registry
.get(std::any::TypeId::of::<MaterialPropertyBlocks>())
.is_some());
}
#[test]
fn gltf_standard_material_paths_use_pbr_conversion_label() {
+648 -60
View File
@@ -4,13 +4,13 @@ use bevy::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{
EditorAssetRef, MaterialDesc, MaterialParameter, MaterialRef, MaterialShaderKind,
MaterialTextureBinding,
ColorDesc, EditorAssetRef, MaterialDesc, MaterialParameter, MaterialParameterValue,
MaterialRef, MaterialShaderKind, MaterialTextureBinding, ShaderRefDesc, TextureChannel,
};
pub const MATERIAL_ASSET_SCHEMA_VERSION: u32 = 1;
pub const MATERIAL_INSTANCE_SCHEMA_VERSION: u32 = 1;
pub const SURFACE_SHADER_SCHEMA_VERSION: u32 = 1;
pub const MATERIAL_ASSET_SCHEMA_VERSION: u32 = 2;
pub const MATERIAL_INSTANCE_SCHEMA_VERSION: u32 = 2;
pub const SURFACE_SHADER_SCHEMA_VERSION: u32 = 2;
const fn default_material_schema_version() -> u32 {
MATERIAL_ASSET_SCHEMA_VERSION
@@ -55,20 +55,230 @@ impl Default for MaterialRenderState {
}
}
/// RON material asset: label plus authoring [`MaterialDesc`].
#[derive(Asset, TypePath, Debug, Clone, Serialize, Deserialize)]
/// Canonical values and texture bindings consumed by both built-in and custom material schemas.
///
/// Values are keyed by stable input names. Validation rejects duplicates before publication;
/// vectors are retained instead of maps so shader-defined presentation order remains serializable.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct MaterialInputSet {
#[serde(default)]
pub values: Vec<MaterialParameter>,
#[serde(default)]
pub textures: Vec<MaterialTextureBinding>,
}
impl MaterialInputSet {
pub fn from_material_desc(material: &MaterialDesc) -> Self {
let mut values = vec![
MaterialParameter {
name: "base_color".into(),
value: MaterialParameterValue::Color(material.base_color),
},
MaterialParameter {
name: "metallic".into(),
value: MaterialParameterValue::Float(material.metallic),
},
MaterialParameter {
name: "roughness".into(),
value: MaterialParameterValue::Float(material.roughness),
},
MaterialParameter {
name: "emissive_color".into(),
value: MaterialParameterValue::Color(material.emissive_color),
},
MaterialParameter {
name: "emissive_intensity".into(),
value: MaterialParameterValue::Float(material.emissive_intensity),
},
MaterialParameter {
name: "uv_offset".into(),
value: MaterialParameterValue::Vec2(material.uv_offset),
},
MaterialParameter {
name: "uv_tiling".into(),
value: MaterialParameterValue::Vec2(material.uv_tiling),
},
];
for parameter in &material.parameters {
if !is_standard_value_name(&parameter.name) {
upsert_parameter(&mut values, parameter.clone());
}
}
let mut textures = Vec::new();
if let Some(path) = material.base_color_texture.as_deref() {
textures.push(path_texture_binding(
"base_color",
path,
TextureChannel::Rgba,
));
}
if let Some(path) = material.normal_map_texture.as_deref() {
textures.push(path_texture_binding("normal", path, TextureChannel::Rgb));
}
if let Some(path) = material.metallic_roughness_texture.as_deref() {
textures.push(path_texture_binding("occlusion", path, TextureChannel::R));
textures.push(path_texture_binding("roughness", path, TextureChannel::G));
textures.push(path_texture_binding("metallic", path, TextureChannel::B));
}
if let Some(path) = material.occlusion_texture.as_deref() {
upsert_texture(
&mut textures,
path_texture_binding("occlusion", path, TextureChannel::R),
);
}
if let Some(path) = material.emissive_texture.as_deref() {
textures.push(path_texture_binding("emissive", path, TextureChannel::Rgb));
}
for texture in &material.textures {
if !is_standard_texture_name(&texture.name) {
upsert_texture(&mut textures, texture.clone());
}
}
Self { values, textures }
}
pub fn apply_to_material_desc(&self, material: &mut MaterialDesc) {
material.parameters.clear();
material.textures.clear();
for parameter in &self.values {
match (parameter.name.as_str(), &parameter.value) {
("base_color", MaterialParameterValue::Color(value)) => {
material.base_color = *value
}
("metallic", MaterialParameterValue::Float(value)) => material.metallic = *value,
("roughness", MaterialParameterValue::Float(value)) => material.roughness = *value,
("emissive_color", MaterialParameterValue::Color(value)) => {
material.emissive_color = *value
}
("emissive_intensity", MaterialParameterValue::Float(value)) => {
material.emissive_intensity = *value
}
("uv_offset", MaterialParameterValue::Vec2(value)) => material.uv_offset = *value,
("uv_tiling", MaterialParameterValue::Vec2(value)) => material.uv_tiling = *value,
_ => upsert_parameter(&mut material.parameters, parameter.clone()),
}
}
material.base_color_texture = binding_path(self.texture("base_color"));
material.normal_map_texture = binding_path(self.texture("normal"));
material.emissive_texture = binding_path(self.texture("emissive"));
let roughness = binding_path(self.texture("roughness"));
let metallic = binding_path(self.texture("metallic"));
material.metallic_roughness_texture = match (roughness, metallic) {
(Some(roughness), Some(metallic)) if roughness == metallic => Some(roughness),
(Some(path), None) | (None, Some(path)) => Some(path),
_ => None,
};
material.occlusion_texture = binding_path(self.texture("occlusion"));
for texture in &self.textures {
if !is_standard_texture_name(&texture.name) {
upsert_texture(&mut material.textures, texture.clone());
}
}
}
pub fn texture(&self, name: &str) -> Option<&MaterialTextureBinding> {
self.textures.iter().find(|binding| binding.name == name)
}
pub fn validate_unique(&self) -> Result<(), String> {
let mut names = std::collections::HashSet::new();
for value in &self.values {
if !names.insert(("value", value.name.as_str())) {
return Err(format!(
"material value `{}` is assigned more than once",
value.name
));
}
}
for texture in &self.textures {
if !names.insert(("texture", texture.name.as_str())) {
return Err(format!(
"material texture `{}` is assigned more than once",
texture.name
));
}
}
Ok(())
}
}
fn path_texture_binding(name: &str, path: &str, channel: TextureChannel) -> MaterialTextureBinding {
let label = std::path::Path::new(path)
.file_stem()
.and_then(|value| value.to_str())
.unwrap_or(path);
MaterialTextureBinding {
name: name.into(),
texture: Some(
EditorAssetRef::new(String::new(), format!("texture:{name}"), label)
.with_source_path(path),
),
channel,
}
}
fn binding_path(binding: Option<&MaterialTextureBinding>) -> Option<String> {
binding
.and_then(|binding| binding.texture.as_ref())
.and_then(|reference| reference.source_path.clone())
}
fn is_standard_value_name(name: &str) -> bool {
matches!(
name,
"base_color"
| "metallic"
| "roughness"
| "emissive_color"
| "emissive_intensity"
| "uv_offset"
| "uv_tiling"
)
}
fn is_standard_texture_name(name: &str) -> bool {
matches!(
name,
"base_color"
| "base_color_texture"
| "normal"
| "normal_map_texture"
| "occlusion"
| "roughness"
| "metallic"
| "metallic_roughness"
| "metallic_roughness_texture"
| "emissive"
| "emissive_texture"
)
}
/// RON material asset with schema-driven authoring inputs.
#[derive(Asset, TypePath, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct MaterialAsset {
#[serde(default = "default_material_schema_version")]
pub schema_version: u32,
pub label: String,
/// Legacy path/label retained for v0 compatibility. New assets use `shader_ref`.
#[serde(default)]
pub shader: Option<String>,
pub shader: ShaderRefDesc,
#[serde(default)]
pub shader_ref: Option<EditorAssetRef>,
#[serde(default)]
pub render_state: MaterialRenderState,
pub material: MaterialDesc,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provenance: Option<MaterialProvenance>,
#[serde(default)]
pub inputs: MaterialInputSet,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MaterialProvenance {
pub source_path: String,
pub source_fingerprint: String,
pub source_sub_asset_id: String,
pub source_label: String,
}
impl MaterialAsset {
@@ -87,7 +297,11 @@ pub fn load_resolved_material_from_path(
catalog_path: &str,
) -> Result<(MaterialDesc, MaterialRenderState), String> {
if let Ok(asset) = MaterialAsset::load_from_path(catalog_path) {
let mut material = asset.material;
let mut material = MaterialDesc {
shader: asset.shader,
..Default::default()
};
asset.inputs.apply_to_material_desc(&mut material);
material.material_asset_path = Some(catalog_path.to_string());
return Ok((material, asset.render_state));
}
@@ -100,7 +314,11 @@ pub fn load_resolved_material_from_path(
)
})?;
let base = MaterialAsset::load_from_path(base_path)?;
let mut material = base.material;
let mut material = MaterialDesc {
shader: base.shader,
..Default::default()
};
base.inputs.apply_to_material_desc(&mut material);
instance.apply_to(&mut material);
material.material_asset_path = Some(catalog_path.to_string());
Ok((material, base.render_state))
@@ -108,15 +326,14 @@ pub fn load_resolved_material_from_path(
/// Explicit reusable overrides over one project Material asset.
#[derive(Asset, TypePath, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct MaterialInstanceAsset {
#[serde(default = "default_material_instance_schema_version")]
pub schema_version: u32,
pub label: String,
pub base: MaterialRef,
#[serde(default)]
pub parameters: Vec<MaterialParameter>,
#[serde(default)]
pub textures: Vec<MaterialTextureBinding>,
pub overrides: MaterialInputSet,
}
impl MaterialInstanceAsset {
@@ -129,7 +346,7 @@ impl MaterialInstanceAsset {
/// Applies this instance's sparse overrides without mutating the shared base asset.
pub fn apply_to(&self, material: &mut MaterialDesc) {
for parameter in &self.parameters {
for parameter in &self.overrides.values {
match (parameter.name.as_str(), &parameter.value) {
("base_color", crate::MaterialParameterValue::Color(value)) => {
material.base_color = *value;
@@ -146,23 +363,45 @@ impl MaterialInstanceAsset {
("emissive_intensity", crate::MaterialParameterValue::Float(value)) => {
material.emissive_intensity = *value;
}
("uv_offset", crate::MaterialParameterValue::Vec2(value)) => {
material.uv_offset = *value;
}
("uv_tiling", crate::MaterialParameterValue::Vec2(value)) => {
material.uv_tiling = *value;
}
_ => upsert_parameter(&mut material.parameters, parameter.clone()),
}
}
for texture in &self.textures {
for texture in &self.overrides.textures {
let path = texture
.texture
.as_ref()
.and_then(|reference| reference.source_path.clone());
match texture.name.as_str() {
"base_color_texture" => material.base_color_texture = path,
"emissive_texture" => material.emissive_texture = path,
"normal_map_texture" => material.normal_map_texture = path,
"metallic_roughness_texture" => material.metallic_roughness_texture = path,
"base_color" | "base_color_texture" => material.base_color_texture = path,
"emissive" | "emissive_texture" => material.emissive_texture = path,
"normal" | "normal_map_texture" => material.normal_map_texture = path,
"roughness" | "metallic" | "metallic_roughness_texture" => {
material.metallic_roughness_texture = path
}
_ => upsert_texture(&mut material.textures, texture.clone()),
}
}
}
/// Overlays sparse runtime/property-block values onto this direct-base instance.
pub fn merge_overrides(
&mut self,
parameters: impl IntoIterator<Item = MaterialParameter>,
textures: impl IntoIterator<Item = MaterialTextureBinding>,
) {
for parameter in parameters {
upsert_parameter(&mut self.overrides.values, parameter);
}
for texture in textures {
upsert_texture(&mut self.overrides.textures, texture);
}
}
}
fn upsert_parameter(values: &mut Vec<MaterialParameter>, value: MaterialParameter) {
@@ -192,17 +431,107 @@ pub enum ShaderPropertyType {
Texture,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct MaterialInputGroupDesc {
pub id: String,
pub display_name: String,
#[serde(default)]
pub order: i32,
#[serde(default)]
pub advanced: bool,
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
pub enum TextureSemantic {
#[default]
Auto,
Color,
Normal,
Scalar,
Mask,
Hdr,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MaterialTextureInputDesc {
#[serde(default)]
pub semantic: TextureSemantic,
#[serde(default)]
pub default_channel: TextureChannel,
#[serde(default)]
pub allow_channel_override: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ShaderPropertyDesc {
pub struct MaterialInputDesc {
pub name: String,
pub display_name: String,
#[serde(default)]
pub group: String,
#[serde(default)]
pub order: i32,
pub property_type: ShaderPropertyType,
#[serde(default)]
pub default_value: Option<MaterialParameterValue>,
#[serde(default)]
pub texture: Option<MaterialTextureInputDesc>,
#[serde(default)]
pub tooltip: String,
#[serde(default)]
pub advanced: bool,
/// Authoring presentation only. Runtime evaluation continues to address inputs by `name`.
#[serde(default)]
pub presentation: MaterialInputPresentation,
}
impl Default for MaterialInputDesc {
fn default() -> Self {
Self {
name: String::new(),
display_name: String::new(),
group: String::new(),
order: 0,
property_type: ShaderPropertyType::Float {
min: None,
max: None,
},
default_value: None,
texture: None,
tooltip: String::new(),
advanced: false,
presentation: MaterialInputPresentation::Row,
}
}
}
/// Declares whether an input owns a visible row or is edited through another input's row.
///
/// Companion values remain independent in [`MaterialInputSet`]. This keeps the schema suitable for
/// generated/custom shaders while allowing related controls such as emissive color and intensity
/// to share one coherent Inspector row.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub enum MaterialInputPresentation {
#[default]
Row,
Companion {
owner: String,
},
}
/// Compatibility source alias for code that has not yet adopted the material-input terminology.
pub type ShaderPropertyDesc = MaterialInputDesc;
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct MaterialInputSchema {
#[serde(default)]
pub groups: Vec<MaterialInputGroupDesc>,
#[serde(default)]
pub inputs: Vec<MaterialInputDesc>,
}
/// RON shader schema describing material inspector parameters.
#[derive(Asset, TypePath, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct ShaderSchemaAsset {
#[serde(default = "default_surface_shader_schema_version")]
pub schema_version: u32,
@@ -211,11 +540,7 @@ pub struct ShaderSchemaAsset {
#[serde(default)]
pub wgsl_path: Option<String>,
#[serde(default)]
pub parameters: Vec<ShaderPropertyDesc>,
#[serde(default)]
pub default_values: Vec<MaterialParameter>,
#[serde(default)]
pub default_textures: Vec<MaterialTextureBinding>,
pub schema: MaterialInputSchema,
}
impl ShaderSchemaAsset {
@@ -227,18 +552,194 @@ impl ShaderSchemaAsset {
}
}
/// Engine-owned Standard Lit authoring schema. It is consumed by the same renderer used for
/// project Surface schemas, so a future graph compiler only needs to emit this descriptor shape.
pub fn standard_lit_input_schema() -> MaterialInputSchema {
let groups = vec![
MaterialInputGroupDesc {
id: "surface_inputs".into(),
display_name: "Surface Inputs".into(),
order: 0,
advanced: false,
},
MaterialInputGroupDesc {
id: "advanced_inputs".into(),
display_name: "Advanced Inputs".into(),
order: 100,
advanced: true,
},
MaterialInputGroupDesc {
id: "uv_transform".into(),
display_name: "UV Transform".into(),
order: 90,
advanced: false,
},
];
let scalar_texture = |channel| MaterialTextureInputDesc {
semantic: TextureSemantic::Scalar,
default_channel: channel,
allow_channel_override: true,
};
let inputs = vec![
MaterialInputDesc {
name: "base_color".into(),
display_name: "Base Color".into(),
group: "surface_inputs".into(),
order: 0,
property_type: ShaderPropertyType::Color,
default_value: Some(MaterialParameterValue::Color(ColorDesc::default())),
texture: Some(MaterialTextureInputDesc {
semantic: TextureSemantic::Color,
default_channel: TextureChannel::Rgba,
allow_channel_override: false,
}),
tooltip: "Color multiplier applied to the base-color texture.".into(),
advanced: false,
presentation: MaterialInputPresentation::Row,
},
MaterialInputDesc {
name: "metallic".into(),
display_name: "Metallic".into(),
group: "surface_inputs".into(),
order: 10,
property_type: ShaderPropertyType::Float {
min: Some(0.0),
max: Some(1.0),
},
default_value: Some(MaterialParameterValue::Float(0.0)),
texture: Some(scalar_texture(TextureChannel::B)),
tooltip: "Scalar multiplier; ARM/ORM uses the blue channel.".into(),
advanced: false,
presentation: MaterialInputPresentation::Row,
},
MaterialInputDesc {
name: "roughness".into(),
display_name: "Roughness".into(),
group: "surface_inputs".into(),
order: 20,
property_type: ShaderPropertyType::Float {
min: Some(0.0),
max: Some(1.0),
},
default_value: Some(MaterialParameterValue::Float(0.65)),
texture: Some(scalar_texture(TextureChannel::G)),
tooltip: "Scalar multiplier; ARM/ORM uses the green channel.".into(),
advanced: false,
presentation: MaterialInputPresentation::Row,
},
MaterialInputDesc {
name: "occlusion".into(),
display_name: "Occlusion".into(),
group: "surface_inputs".into(),
order: 30,
property_type: ShaderPropertyType::Float {
min: Some(0.0),
max: Some(1.0),
},
default_value: Some(MaterialParameterValue::Float(1.0)),
texture: Some(scalar_texture(TextureChannel::R)),
tooltip: "Ambient-occlusion strength; ARM/ORM uses the red channel.".into(),
advanced: false,
presentation: MaterialInputPresentation::Row,
},
MaterialInputDesc {
name: "normal".into(),
display_name: "Normal".into(),
group: "surface_inputs".into(),
order: 40,
property_type: ShaderPropertyType::Float {
min: Some(0.0),
max: Some(1.0),
},
default_value: Some(MaterialParameterValue::Float(0.85)),
texture: Some(MaterialTextureInputDesc {
semantic: TextureSemantic::Normal,
default_channel: TextureChannel::Rgb,
allow_channel_override: false,
}),
tooltip: String::new(),
advanced: false,
presentation: MaterialInputPresentation::Row,
},
MaterialInputDesc {
name: "emissive_color".into(),
display_name: "Emissive".into(),
group: "surface_inputs".into(),
order: 50,
property_type: ShaderPropertyType::Color,
default_value: Some(MaterialParameterValue::Color(ColorDesc::srgb(
1.0, 1.0, 1.0,
))),
texture: Some(MaterialTextureInputDesc {
semantic: TextureSemantic::Color,
default_channel: TextureChannel::Rgb,
allow_channel_override: false,
}),
tooltip: "Emissive color multiplied by the texture and intensity.".into(),
advanced: false,
presentation: MaterialInputPresentation::Row,
},
MaterialInputDesc {
name: "emissive_intensity".into(),
display_name: "Emissive Intensity".into(),
group: "surface_inputs".into(),
order: 60,
property_type: ShaderPropertyType::Float {
min: Some(0.0),
max: Some(50_000.0),
},
default_value: Some(MaterialParameterValue::Float(0.0)),
texture: None,
tooltip: "Emissive luminance multiplier in nits.".into(),
advanced: false,
presentation: MaterialInputPresentation::Companion {
owner: "emissive_color".into(),
},
},
MaterialInputDesc {
name: "uv_offset".into(),
display_name: "Offset".into(),
group: "uv_transform".into(),
order: 0,
property_type: ShaderPropertyType::Vec2,
default_value: Some(MaterialParameterValue::Vec2(Vec2::ZERO)),
texture: None,
tooltip: "Shared UV translation for every texture on this material.".into(),
advanced: false,
presentation: MaterialInputPresentation::Row,
},
MaterialInputDesc {
name: "uv_tiling".into(),
display_name: "Tiling".into(),
group: "uv_transform".into(),
order: 10,
property_type: ShaderPropertyType::Vec2,
default_value: Some(MaterialParameterValue::Vec2(Vec2::ONE)),
texture: None,
tooltip: "Shared UV scale for every texture on this material.".into(),
advanced: false,
presentation: MaterialInputPresentation::Row,
},
];
MaterialInputSchema { groups, inputs }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn legacy_material_defaults_to_current_schema_and_opaque() {
let parsed: MaterialAsset = ron::from_str(
r#"(label: "Legacy", material: (base_color: (r: 1.0, g: 1.0, b: 1.0, a: 1.0), metallic: 0.0, roughness: 0.5, base_color_texture: None, normal_map_texture: None, metallic_roughness_texture: None))"#,
)
.expect("legacy material should remain readable");
fn material_v2_defaults_to_opaque() {
let parsed = MaterialAsset {
schema_version: MATERIAL_ASSET_SCHEMA_VERSION,
label: "Material".into(),
shader: ShaderRefDesc::default(),
shader_ref: None,
render_state: MaterialRenderState::default(),
provenance: None,
inputs: MaterialInputSet::default(),
};
assert_eq!(parsed.schema_version, MATERIAL_ASSET_SCHEMA_VERSION);
assert_eq!(parsed.render_state.alpha_mode, MaterialAlphaMode::Opaque);
}
@@ -252,8 +753,7 @@ mod tests {
"material:source",
"Base",
)),
parameters: Vec::new(),
textures: Vec::new(),
overrides: MaterialInputSet::default(),
};
assert!(instance.base.is_resolved());
@@ -266,23 +766,26 @@ mod tests {
schema_version: MATERIAL_INSTANCE_SCHEMA_VERSION,
label: "Variant".into(),
base: MaterialRef::default(),
parameters: vec![
MaterialParameter {
name: "roughness".into(),
value: crate::MaterialParameterValue::Float(0.2),
},
MaterialParameter {
name: "edge_width".into(),
value: crate::MaterialParameterValue::Float(3.0),
},
],
textures: vec![MaterialTextureBinding {
name: "base_color_texture".into(),
texture: Some(
EditorAssetRef::new("texture", "texture:source", "Grid")
.with_source_path("assets/textures/grid.png"),
),
}],
overrides: MaterialInputSet {
values: vec![
MaterialParameter {
name: "roughness".into(),
value: crate::MaterialParameterValue::Float(0.2),
},
MaterialParameter {
name: "edge_width".into(),
value: crate::MaterialParameterValue::Float(3.0),
},
],
textures: vec![MaterialTextureBinding {
name: "base_color_texture".into(),
texture: Some(
EditorAssetRef::new("texture", "texture:source", "Grid")
.with_source_path("assets/textures/grid.png"),
),
channel: TextureChannel::Rgba,
}],
},
};
instance.apply_to(&mut material);
@@ -298,6 +801,88 @@ mod tests {
.any(|value| value.name == "edge_width"));
}
#[test]
fn material_inputs_round_trip_shared_uv_transform() {
let source = MaterialDesc {
uv_offset: Vec2::new(0.25, -0.5),
uv_tiling: Vec2::new(4.0, 2.0),
..Default::default()
};
let inputs = MaterialInputSet::from_material_desc(&source);
let mut resolved = MaterialDesc::default();
inputs.apply_to_material_desc(&mut resolved);
assert_eq!(resolved.uv_offset, source.uv_offset);
assert_eq!(resolved.uv_tiling, source.uv_tiling);
}
#[test]
fn standard_lit_surface_inputs_match_penpot_bindings() {
let schema = standard_lit_input_schema();
let surface = schema
.inputs
.iter()
.filter(|input| input.group == "surface_inputs")
.collect::<Vec<_>>();
let rows = surface
.iter()
.filter(|input| matches!(input.presentation, MaterialInputPresentation::Row))
.count();
assert_eq!(surface.len(), 7);
assert_eq!(rows, 6);
assert_eq!(surface[0].name, "base_color");
assert_eq!(surface[4].name, "normal");
assert!(matches!(
surface[4].property_type,
ShaderPropertyType::Float {
min: Some(0.0),
max: Some(1.0)
}
));
assert_eq!(surface[6].name, "emissive_intensity");
assert_eq!(
surface[6].presentation,
MaterialInputPresentation::Companion {
owner: "emissive_color".into()
}
);
}
#[test]
fn promotion_merge_replaces_existing_values_without_duplicates() {
let mut instance = MaterialInstanceAsset {
schema_version: MATERIAL_INSTANCE_SCHEMA_VERSION,
label: "Variant".into(),
base: MaterialRef::default(),
overrides: MaterialInputSet {
values: vec![MaterialParameter {
name: "roughness".into(),
value: crate::MaterialParameterValue::Float(0.8),
}],
textures: Vec::new(),
},
};
instance.merge_overrides(
[MaterialParameter {
name: "roughness".into(),
value: crate::MaterialParameterValue::Float(0.2),
}],
[MaterialTextureBinding {
name: "normal_map_texture".into(),
texture: None,
channel: TextureChannel::Rgb,
}],
);
assert_eq!(instance.overrides.values.len(), 1);
assert_eq!(
instance.overrides.values[0].value,
crate::MaterialParameterValue::Float(0.2)
);
assert_eq!(instance.overrides.textures.len(), 1);
}
#[test]
fn resolved_material_instance_applies_sparse_overrides_and_keeps_instance_path() {
let root = std::env::temp_dir().join(format!(
@@ -313,16 +898,17 @@ mod tests {
let base = MaterialAsset {
schema_version: MATERIAL_ASSET_SCHEMA_VERSION,
label: "Base".into(),
shader: None,
shader: ShaderRefDesc::default(),
shader_ref: None,
render_state: MaterialRenderState {
double_sided: true,
..Default::default()
},
material: MaterialDesc {
provenance: None,
inputs: MaterialInputSet::from_material_desc(&MaterialDesc {
roughness: 0.8,
..Default::default()
},
}),
};
std::fs::write(
&base_path,
@@ -336,11 +922,13 @@ mod tests {
EditorAssetRef::new("base", "material:source", "Base")
.with_source_path(base_path.to_string_lossy().into_owned()),
),
parameters: vec![MaterialParameter {
name: "roughness".into(),
value: crate::MaterialParameterValue::Float(0.25),
}],
textures: Vec::new(),
overrides: MaterialInputSet {
values: vec![MaterialParameter {
name: "roughness".into(),
value: crate::MaterialParameterValue::Float(0.25),
}],
textures: Vec::new(),
},
};
std::fs::write(
&instance_path,
+176
View File
@@ -0,0 +1,176 @@
//! Runtime and legacy-compatible material descriptor types.
use bevy::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{ComponentInstanceId, EditorAssetRef, ShaderRefDesc};
#[derive(Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
#[type_path = "shared::components"]
pub enum MaterialParameterValue {
Bool(bool),
Float(f32),
Vec2(Vec2),
Vec3(Vec3),
Color(ColorDesc),
Enum(String),
}
impl Default for MaterialParameterValue {
fn default() -> Self {
Self::Float(0.0)
}
}
#[derive(Reflect, Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
#[type_path = "shared::components"]
pub struct MaterialParameter {
pub name: String,
pub value: MaterialParameterValue,
}
/// Channels sampled from a texture binding. Scalar material inputs use one channel while
/// color/normal inputs use RGB or RGBA. The default preserves the pre-v2 whole-texture behavior.
#[derive(Reflect, Default, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
#[type_path = "shared::components"]
pub enum TextureChannel {
R,
G,
B,
A,
Rgb,
#[default]
Rgba,
}
#[derive(Reflect, Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
#[type_path = "shared::components"]
pub struct MaterialTextureBinding {
pub name: String,
pub texture: Option<EditorAssetRef>,
#[serde(default)]
pub channel: TextureChannel,
}
/// Per-render-slot material override stored on scene actors.
#[derive(Reflect, Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
#[type_path = "shared::components"]
pub struct MaterialSlotOverride {
pub slot_id: ComponentInstanceId,
#[serde(default)]
pub base_material: Option<EditorAssetRef>,
pub material: MaterialDesc,
}
/// Actor-level material overrides retained for legacy scene upgrade only.
#[derive(Component, Reflect, Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[reflect(Component, Default, Debug, PartialEq, Serialize, Deserialize)]
#[type_path = "shared::components"]
pub struct MaterialOverride {
#[serde(default)]
pub slots: Vec<MaterialSlotOverride>,
}
/// Serializable color description. This avoids coupling saved scenes to any internal color
/// representation details.
#[derive(Reflect, Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[reflect(Default, Debug, Serialize, Deserialize)]
#[type_path = "shared::components"]
pub struct ColorDesc {
pub r: f32,
pub g: f32,
pub b: f32,
pub a: f32,
}
impl ColorDesc {
pub const fn srgb(r: f32, g: f32, b: f32) -> Self {
Self { r, g, b, a: 1.0 }
}
pub fn to_color(self) -> Color {
Color::srgba(self.r, self.g, self.b, self.a)
}
}
impl Default for ColorDesc {
fn default() -> Self {
Self::srgb(0.8, 0.8, 0.8)
}
}
/// Resolved runtime and legacy-compatible material representation. Project authoring uses
/// `MaterialAsset`/`MaterialInputSet`; hydration maps this descriptor to renderer materials.
#[derive(Component, Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[reflect(Component, Default, Debug, Serialize, Deserialize)]
#[type_path = "shared::components"]
pub struct MaterialDesc {
#[serde(default)]
pub shader: ShaderRefDesc,
pub base_color: ColorDesc,
pub metallic: f32,
pub roughness: f32,
#[serde(default = "default_emissive_color")]
pub emissive_color: ColorDesc,
#[serde(default)]
pub emissive_intensity: f32,
pub base_color_texture: Option<String>,
#[serde(default)]
pub emissive_texture: Option<String>,
pub normal_map_texture: Option<String>,
pub metallic_roughness_texture: Option<String>,
#[serde(default)]
pub occlusion_texture: Option<String>,
#[serde(default)]
pub material_asset_path: Option<String>,
#[serde(default)]
pub parameters: Vec<MaterialParameter>,
#[serde(default)]
pub textures: Vec<MaterialTextureBinding>,
#[serde(default)]
pub uv_offset: Vec2,
#[serde(default = "default_material_uv_tiling")]
pub uv_tiling: Vec2,
}
impl MaterialDesc {
pub fn new(base_color: ColorDesc, metallic: f32, roughness: f32) -> Self {
Self {
shader: ShaderRefDesc::default(),
base_color,
metallic,
roughness,
emissive_color: default_emissive_color(),
emissive_intensity: 0.0,
base_color_texture: None,
emissive_texture: None,
normal_map_texture: None,
metallic_roughness_texture: None,
occlusion_texture: None,
material_asset_path: None,
parameters: Vec::new(),
textures: Vec::new(),
uv_offset: Vec2::ZERO,
uv_tiling: Vec2::ONE,
}
}
}
fn default_material_uv_tiling() -> Vec2 {
Vec2::ONE
}
fn default_emissive_color() -> ColorDesc {
ColorDesc::srgb(1.0, 1.0, 1.0)
}
impl Default for MaterialDesc {
fn default() -> Self {
Self::new(ColorDesc::default(), 0.0, 0.65)
}
}
+18 -3
View File
@@ -10,7 +10,10 @@ use bevy::world_serialization::{WorldInstanceReady, WorldInstanceSpawner};
use serde::de::{DeserializeOwned, DeserializeSeed};
use serde::{Deserialize, Serialize};
use crate::{ActorId, EditorVisibility, HydratedPrefabMember, MaterialDesc, PrefabInstance};
use crate::{
ActorId, EditorVisibility, HydratedPrefabMember, MaterialDesc, PrefabInstance,
COMPONENT_MATERIAL_DESC,
};
pub const PREFAB_OVERRIDE_FORMAT_VERSION: u32 = 2;
@@ -399,7 +402,7 @@ fn apply_component_override(
world.resource_scope(|world, registry: Mut<AppTypeRegistry>| {
let registry = registry.read();
let registration = registry
.get_with_type_path(&component.component_type)
.get_with_type_path(reflected_component_type_path(&component.component_type))
.ok_or_else(|| {
format!(
"component type `{}` is not registered",
@@ -449,7 +452,7 @@ fn apply_property_override(
world.resource_scope(|world, registry: Mut<AppTypeRegistry>| {
let registry = registry.read();
let registration = registry
.get_with_type_path(&property.component_type)
.get_with_type_path(reflected_component_type_path(&property.component_type))
.ok_or_else(|| {
format!(
"component type `{}` is not registered",
@@ -489,6 +492,17 @@ fn apply_property_override(
})
}
/// Rust's concrete type name follows the owning module after a domain extraction, while saved
/// reflected scene data deliberately keeps its stable public component path. Accept the concrete
/// name emitted by editor authoring without duplicating the type registration.
fn reflected_component_type_path(component_type: &str) -> &str {
if component_type == std::any::type_name::<MaterialDesc>() {
COMPONENT_MATERIAL_DESC
} else {
component_type
}
}
fn deserialize_component(
text: &str,
registration: &bevy::reflect::TypeRegistration,
@@ -633,6 +647,7 @@ mod tests {
let value = crate::Primitive {
shape: crate::PrimitiveShape::Sphere,
size: Vec3::splat(99.0),
..Default::default()
};
let merged = apply_serialized_navigation_property_override(
std::any::type_name::<crate::Primitive>(),
+77 -25
View File
@@ -32,23 +32,31 @@ impl From<EditorAssetRef> for MaterialRef {
}
}
/// One stable, named material assignment exposed by a renderer.
/// One stable, named material assignment exposed by any renderable surface.
#[derive(Reflect, Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct RendererMaterialSlot {
pub struct MaterialSlot {
pub id: ComponentInstanceId,
pub name: String,
/// Read-only imported default. Clearing `material` returns to this reference.
#[serde(default)]
pub source_material: Option<MaterialRef>,
/// Explicit shared Material or Material Instance assignment.
/// Actor-owned shared Material or Material Instance assignment.
/// Model defaults and imported source materials remain asset-owned.
#[serde(default)]
pub material: Option<MaterialRef>,
}
impl RendererMaterialSlot {
impl MaterialSlot {
pub fn effective_material(&self) -> Option<&MaterialRef> {
self.material.as_ref().or(self.source_material.as_ref())
self.material.as_ref()
}
pub fn hydrated_selection(&self) -> HydratedMaterialSelection {
self.material
.clone()
.map(|reference| HydratedMaterialSelection::Project {
reference,
layer: HydratedMaterialLayer::Actor,
})
.unwrap_or_default()
}
}
@@ -62,31 +70,36 @@ pub struct OrphanedMaterialAssignment {
pub material: MaterialRef,
}
/// Material slots shared by static and skinned renderer authoring components.
/// Material slots shared by primitive, static, and skinned authoring components.
#[derive(Reflect, Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct RendererMaterialSet {
pub struct MaterialSlotSet {
#[serde(default)]
pub slots: Vec<RendererMaterialSlot>,
pub slots: Vec<MaterialSlot>,
#[serde(default)]
pub orphaned_assignments: Vec<OrphanedMaterialAssignment>,
}
impl RendererMaterialSet {
pub fn slot(&self, id: &ComponentInstanceId) -> Option<&RendererMaterialSlot> {
impl MaterialSlotSet {
pub fn slot(&self, id: &ComponentInstanceId) -> Option<&MaterialSlot> {
self.slots.iter().find(|slot| &slot.id == id)
}
pub fn slot_mut(&mut self, id: &ComponentInstanceId) -> Option<&mut RendererMaterialSlot> {
pub fn slot_mut(&mut self, id: &ComponentInstanceId) -> Option<&mut MaterialSlot> {
self.slots.iter_mut().find(|slot| &slot.id == id)
}
pub fn effective_material(&self, id: &ComponentInstanceId) -> Option<&MaterialRef> {
self.slot(id)
.and_then(RendererMaterialSlot::effective_material)
self.slot(id).and_then(MaterialSlot::effective_material)
}
}
/// Source-compatible name retained for the schema-v4 transition.
pub type RendererMaterialSlot = MaterialSlot;
/// Source-compatible name retained for the schema-v4 transition.
pub type RendererMaterialSet = MaterialSlotSet;
/// Runtime-only property overrides analogous to a material property block.
///
/// Blocks never alter shared assets and are deliberately excluded from scene/prefab persistence.
@@ -94,9 +107,7 @@ impl RendererMaterialSet {
#[reflect(Default, Debug, PartialEq)]
pub struct MaterialPropertyBlock {
pub slot_id: ComponentInstanceId,
#[reflect(ignore)]
pub parameters: Vec<MaterialParameter>,
#[reflect(ignore)]
pub textures: Vec<MaterialTextureBinding>,
}
@@ -107,14 +118,47 @@ pub struct MaterialPropertyBlocks {
}
/// Runtime ownership/binding marker placed on every hydrated renderer draw entity.
#[derive(Reflect, Debug, Clone, Copy, PartialEq, Eq)]
#[reflect(Debug, PartialEq)]
pub enum HydratedMaterialLayer {
Actor,
Model,
}
#[derive(Reflect, Debug, Clone, PartialEq, Eq, Default)]
#[reflect(Debug, PartialEq, Default)]
pub enum HydratedMaterialSelection {
Project {
reference: MaterialRef,
layer: HydratedMaterialLayer,
},
ImportedSource {
reference: MaterialRef,
},
#[default]
Inherit,
}
impl HydratedMaterialSelection {
pub fn project_reference(&self) -> Option<&MaterialRef> {
match self {
Self::Project { reference, .. } => Some(reference),
Self::ImportedSource { .. } | Self::Inherit => None,
}
}
}
#[derive(Component, Reflect, Debug, Clone, PartialEq, Eq)]
#[reflect(Component, Debug, PartialEq)]
pub struct HydratedRendererMaterialBinding {
pub struct HydratedMaterialSlotBinding {
pub owner: Entity,
pub slot_id: ComponentInstanceId,
pub effective_material: Option<MaterialRef>,
pub selection: HydratedMaterialSelection,
}
/// Source-compatible name retained for the schema-v4 transition.
pub type HydratedRendererMaterialBinding = HydratedMaterialSlotBinding;
/// Runtime ownership marker consumed by the project terrain-layer renderer.
#[derive(Component, Reflect, Debug, Clone, PartialEq)]
#[reflect(Component, Default, Debug, PartialEq)]
@@ -141,19 +185,28 @@ mod tests {
}
#[test]
fn explicit_assignment_precedes_imported_source() {
let source = material_ref("source");
fn slot_contains_only_the_actor_assignment() {
let assigned = material_ref("assigned");
let mut slot = RendererMaterialSlot {
id: ComponentInstanceId::new("slot:body"),
name: "Body".into(),
source_material: Some(source.clone()),
material: Some(assigned.clone()),
};
assert_eq!(slot.effective_material(), Some(&assigned));
assert!(matches!(
slot.hydrated_selection(),
HydratedMaterialSelection::Project {
layer: HydratedMaterialLayer::Actor,
..
}
));
slot.material = None;
assert_eq!(slot.effective_material(), Some(&source));
assert_eq!(slot.effective_material(), None);
assert_eq!(
slot.hydrated_selection(),
HydratedMaterialSelection::Inherit
);
}
#[test]
@@ -162,7 +215,6 @@ mod tests {
slots: vec![RendererMaterialSlot {
id: ComponentInstanceId::new("slot:body"),
name: "Body".into(),
source_material: Some(material_ref("source")),
material: None,
}],
orphaned_assignments: vec![],