Skip to content

Type erased materials #19667

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 34 commits into from
Jun 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
99be854
Erase material types from the render world.
tychedelia Jun 15, 2025
1f74dfe
Custom material example.
tychedelia Jun 16, 2025
e449f3a
Ci.
tychedelia Jun 16, 2025
8d5d1ee
Switch to SmallVec + fn ptr.
tychedelia Jun 16, 2025
838c4d3
Use labels.
tychedelia Jun 16, 2025
235f823
Ci.
tychedelia Jun 16, 2025
0b98281
Ci.
tychedelia Jun 16, 2025
21f1b95
Ci.
tychedelia Jun 16, 2025
71f4a21
Ci.
tychedelia Jun 16, 2025
026c91e
Fix example.
tychedelia Jun 16, 2025
40348f3
Fix example.
tychedelia Jun 16, 2025
1b616da
Docs.
tychedelia Jun 16, 2025
0f2b1c5
Merge branch 'main' into 18075-type-erased-materials
tychedelia Jun 16, 2025
cf29e33
Store type id in erased key.
tychedelia Jun 20, 2025
72b89d5
Change example name.
tychedelia Jun 20, 2025
2999a8d
Merge branch 'main' into 18075-type-erased-materials
tychedelia Jun 20, 2025
0875c04
1.88.
tychedelia Jun 26, 2025
67ed7e4
Merge main.
tychedelia Jun 26, 2025
a2118c5
Fix rename.
tychedelia Jun 26, 2025
bb675be
Merge main.
tychedelia Jun 27, 2025
7a1b6dd
Fixes.
tychedelia Jun 27, 2025
0415540
Update crates/bevy_pbr/src/material.rs
tychedelia Jun 27, 2025
493d99c
Fix bind group number.
tychedelia Jun 27, 2025
1b7e4a0
Revert unrelated changes.
tychedelia Jun 27, 2025
f73113c
Fixes.
tychedelia Jun 27, 2025
3173100
Docs.
tychedelia Jun 27, 2025
aee1ed2
Ci.
tychedelia Jun 27, 2025
ab91ef7
Remove unused trait.
tychedelia Jun 27, 2025
141d233
Correct docs.
tychedelia Jun 27, 2025
1e6b8ed
Remove unused import.
tychedelia Jun 27, 2025
5d939a2
Couple of minor changes
IceSentry Jun 27, 2025
11e9eb0
Merge pull request #1 from IceSentry/erased_materials_minor_changes
tychedelia Jun 27, 2025
fd6534b
Ci.
tychedelia Jun 27, 2025
81c12e2
Merge branch 'main' into 18075-type-erased-materials
tychedelia Jun 27, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -579,7 +579,7 @@ ron = "0.10"
flate2 = "1.0"
serde = { version = "1", features = ["derive"] }
serde_json = "1.0.140"
bytemuck = "1.7"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why did this need to change?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So the way that we're erasing material key (aka bind group data) in this PR at the moment is by going through bytemuck (see MaterialProperties where it's stored as a SmallVec), which basically puts it in our public api.

I'm somewhat uncertain about this change as it enforces new constraints on AsBindGroup::Data, namely the bytemuck derives and repr c. On the one hand, our use of bind group data internal to the engine is always in the form of flags and so this just makes that explicit. On the other hand, if people want to have weird material keys, maybe it isn't our place to stop them.

The alternative is doing Box<dyn Any>, but I ran into problems with making that hashable. The key bit here is that while the erased key only needs to be downcast to the concrete material key in the event you are respecializing, it needs to be hashable for the internal pipeline cache check. While actual respecialization is rare, the cache check happens any time a mesh/material changes.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure I understand how this relates to changing the bytemuck version 😅

Copy link
Member Author

@tychedelia tychedelia Jun 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh sorry! It needs to match the version used in bevy_pbr. If we wanted to add that constraint, we should probably re-export it.

bytemuck = "1"
bevy_render = { path = "crates/bevy_render", version = "0.17.0-dev", default-features = false }
# The following explicit dependencies are needed for proc macros to work inside of examples as they are part of the bevy crate itself.
bevy_ecs = { path = "crates/bevy_ecs", version = "0.17.0-dev", default-features = false }
Expand Down Expand Up @@ -1051,6 +1051,17 @@ description = "Showcases different blend modes"
category = "3D Rendering"
wasm = true

[[example]]
name = "manual_material"
path = "examples/3d/manual_material.rs"
doc-scrape-examples = true

[package.metadata.example.manual_material]
name = "Manual Material Implementation"
description = "Demonstrates how to implement a material manually using the mid-level render APIs"
category = "3D Rendering"
wasm = true

[[example]]
name = "edit_material_on_gltf"
path = "examples/3d/edit_material_on_gltf.rs"
Expand Down
11 changes: 11 additions & 0 deletions assets/shaders/manual_material.wgsl
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#import bevy_pbr::forward_io::VertexOutput

@group(3) @binding(0) var material_color_texture: texture_2d<f32>;
@group(3) @binding(1) var material_color_sampler: sampler;

@fragment
fn fragment(
mesh: VertexOutput,
) -> @location(0) vec4<f32> {
return textureSample(material_color_texture, material_color_sampler, mesh.uv);
}
4 changes: 1 addition & 3 deletions crates/bevy_gizmos/src/pipeline_3d.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,7 @@ impl Plugin for LineGizmo3dPlugin {
.init_resource::<SpecializedRenderPipelines<LineJointGizmoPipeline>>()
.configure_sets(
Render,
GizmoRenderSystems::QueueLineGizmos3d
.in_set(RenderSystems::Queue)
.ambiguous_with(bevy_pbr::queue_material_meshes::<bevy_pbr::StandardMaterial>),
GizmoRenderSystems::QueueLineGizmos3d.in_set(RenderSystems::Queue),
)
.add_systems(
Render,
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_pbr/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ bevy_platform = { path = "../bevy_platform", version = "0.17.0-dev", default-fea
] }

# other
bitflags = "2.3"
bitflags = { version = "2.3", features = ["bytemuck"] }
fixedbitset = "0.5"
thiserror = { version = "2", default-features = false }
derive_more = { version = "2", default-features = false, features = ["from"] }
Expand Down
77 changes: 26 additions & 51 deletions crates/bevy_pbr/src/extended_material.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use alloc::borrow::Cow;

use bevy_asset::{Asset, Handle};
use bevy_asset::Asset;
use bevy_ecs::system::SystemParamItem;
use bevy_platform::{collections::HashSet, hash::FixedHasher};
use bevy_reflect::{impl_type_path, Reflect};
Expand All @@ -9,8 +9,8 @@ use bevy_render::{
mesh::MeshVertexBufferLayoutRef,
render_resource::{
AsBindGroup, AsBindGroupError, BindGroupLayout, BindGroupLayoutEntry, BindlessDescriptor,
BindlessResourceType, BindlessSlabResourceLimit, RenderPipelineDescriptor, Shader,
ShaderRef, SpecializedMeshPipelineError, UnpreparedBindGroup,
BindlessResourceType, BindlessSlabResourceLimit, RenderPipelineDescriptor, ShaderRef,
SpecializedMeshPipelineError, UnpreparedBindGroup,
},
renderer::RenderDevice,
};
Expand All @@ -19,10 +19,6 @@ use crate::{Material, MaterialPipeline, MaterialPipelineKey, MeshPipeline, MeshP

pub struct MaterialExtensionPipeline {
pub mesh_pipeline: MeshPipeline,
pub material_layout: BindGroupLayout,
pub vertex_shader: Option<Handle<Shader>>,
pub fragment_shader: Option<Handle<Shader>>,
pub bindless: bool,
}

pub struct MaterialExtensionKey<E: MaterialExtension> {
Expand Down Expand Up @@ -150,12 +146,19 @@ where
}
}

#[derive(bytemuck::Pod, bytemuck::Zeroable, Copy, Clone, PartialEq, Eq, Hash)]
#[repr(C, packed)]
pub struct MaterialExtensionBindGroupData<B, E> {
pub base: B,
pub extension: E,
}

// We don't use the `TypePath` derive here due to a bug where `#[reflect(type_path = false)]`
// causes the `TypePath` derive to not generate an implementation.
impl_type_path!((in bevy_pbr::extended_material) ExtendedMaterial<B: Material, E: MaterialExtension>);

impl<B: Material, E: MaterialExtension> AsBindGroup for ExtendedMaterial<B, E> {
type Data = (<B as AsBindGroup>::Data, <E as AsBindGroup>::Data);
type Data = MaterialExtensionBindGroupData<B::Data, E::Data>;
type Param = (<B as AsBindGroup>::Param, <E as AsBindGroup>::Param);

fn bindless_slot_count() -> Option<BindlessSlabResourceLimit> {
Expand All @@ -179,20 +182,24 @@ impl<B: Material, E: MaterialExtension> AsBindGroup for ExtendedMaterial<B, E> {
}
}

fn bind_group_data(&self) -> Self::Data {
MaterialExtensionBindGroupData {
base: self.base.bind_group_data(),
extension: self.extension.bind_group_data(),
}
}

fn unprepared_bind_group(
&self,
layout: &BindGroupLayout,
render_device: &RenderDevice,
(base_param, extended_param): &mut SystemParamItem<'_, '_, Self::Param>,
mut force_non_bindless: bool,
) -> Result<UnpreparedBindGroup<Self::Data>, AsBindGroupError> {
) -> Result<UnpreparedBindGroup, AsBindGroupError> {
force_non_bindless = force_non_bindless || Self::bindless_slot_count().is_none();

// add together the bindings of the base material and the user material
let UnpreparedBindGroup {
mut bindings,
data: base_data,
} = B::unprepared_bind_group(
let UnpreparedBindGroup { mut bindings } = B::unprepared_bind_group(
&self.base,
layout,
render_device,
Expand All @@ -209,10 +216,7 @@ impl<B: Material, E: MaterialExtension> AsBindGroup for ExtendedMaterial<B, E> {

bindings.extend(extended_bindgroup.bindings.0);

Ok(UnpreparedBindGroup {
bindings,
data: (base_data, extended_bindgroup.data),
})
Ok(UnpreparedBindGroup { bindings })
}

fn bind_group_layout_entries(
Expand Down Expand Up @@ -373,57 +377,28 @@ impl<B: Material, E: MaterialExtension> Material for ExtendedMaterial<B, E> {
}

fn specialize(
pipeline: &MaterialPipeline<Self>,
pipeline: &MaterialPipeline,
descriptor: &mut RenderPipelineDescriptor,
layout: &MeshVertexBufferLayoutRef,
key: MaterialPipelineKey<Self>,
) -> Result<(), SpecializedMeshPipelineError> {
// Call the base material's specialize function
let MaterialPipeline::<Self> {
mesh_pipeline,
material_layout,
vertex_shader,
fragment_shader,
bindless,
..
} = pipeline.clone();
let base_pipeline = MaterialPipeline::<B> {
mesh_pipeline,
material_layout,
vertex_shader,
fragment_shader,
bindless,
marker: Default::default(),
};
let base_key = MaterialPipelineKey::<B> {
mesh_key: key.mesh_key,
bind_group_data: key.bind_group_data.0,
bind_group_data: key.bind_group_data.base,
};
B::specialize(&base_pipeline, descriptor, layout, base_key)?;
B::specialize(pipeline, descriptor, layout, base_key)?;

// Call the extended material's specialize function afterwards
let MaterialPipeline::<Self> {
mesh_pipeline,
material_layout,
vertex_shader,
fragment_shader,
bindless,
..
} = pipeline.clone();

E::specialize(
&MaterialExtensionPipeline {
mesh_pipeline,
material_layout,
vertex_shader,
fragment_shader,
bindless,
mesh_pipeline: pipeline.mesh_pipeline.clone(),
},
descriptor,
layout,
MaterialExtensionKey {
mesh_key: key.mesh_key,
bind_group_data: key.bind_group_data.1,
bind_group_data: key.bind_group_data.extension,
},
)
}
Expand Down
3 changes: 3 additions & 0 deletions crates/bevy_pbr/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,9 @@ impl Plugin for PbrPlugin {
use_gpu_instance_buffer_builder: self.use_gpu_instance_buffer_builder,
debug_flags: self.debug_flags,
},
MaterialsPlugin {
debug_flags: self.debug_flags,
},
MaterialPlugin::<StandardMaterial> {
prepass_enabled: self.prepass_enabled,
debug_flags: self.debug_flags,
Expand Down
Loading