use bevy::{
core_pipeline::core_3d::{Opaque3d, Opaque3dBinKey, CORE_3D_DEPTH_FORMAT},
math::{vec3, vec4},
pbr::{
DrawMesh, MeshPipeline, MeshPipelineKey, MeshPipelineViewLayoutKey, RenderMeshInstances,
SetMeshBindGroup, SetMeshViewBindGroup,
},
prelude::*,
render::{
extract_component::{ExtractComponent, ExtractComponentPlugin},
mesh::{Indices, MeshVertexBufferLayoutRef, PrimitiveTopology, RenderMesh},
render_asset::{RenderAssetUsages, RenderAssets},
render_phase::{
AddRenderCommand, BinnedRenderPhaseType, DrawFunctions, SetItemPipeline,
ViewBinnedRenderPhases,
},
render_resource::{
ColorTargetState, ColorWrites, CompareFunction, DepthStencilState, Face, FragmentState,
FrontFace, MultisampleState, PipelineCache, PolygonMode, PrimitiveState,
RenderPipelineDescriptor, SpecializedMeshPipeline, SpecializedMeshPipelineError,
SpecializedMeshPipelines, TextureFormat, VertexState,
},
view::{self, ExtractedView, RenderVisibleEntities, ViewTarget, VisibilitySystems},
Render, RenderApp, RenderSet,
},
};
const SHADER_ASSET_PATH: &str = "shaders/specialized_mesh_pipeline.wgsl";
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(CustomRenderedMeshPipelinePlugin)
.add_systems(Startup, setup)
.run();
}
fn setup(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>) {
let mesh = Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::default(),
)
.with_inserted_indices(Indices::U32(vec![0, 1, 2]))
.with_inserted_attribute(
Mesh::ATTRIBUTE_POSITION,
vec![
vec3(-0.5, -0.5, 0.0),
vec3(0.5, -0.5, 0.0),
vec3(0.0, 0.25, 0.0),
],
)
.with_inserted_attribute(
Mesh::ATTRIBUTE_COLOR,
vec![
vec4(1.0, 0.0, 0.0, 1.0),
vec4(0.0, 1.0, 0.0, 1.0),
vec4(0.0, 0.0, 1.0, 1.0),
],
);
for (x, y) in [-0.5, 0.0, 0.5].into_iter().zip([-0.25, 0.5, -0.25]) {
commands.spawn((
CustomRenderedEntity,
Mesh3d(meshes.add(mesh.clone())),
Transform::from_xyz(x, y, 0.0),
));
}
commands.spawn((
Camera3d::default(),
Transform::from_xyz(0.0, 0.0, 3.0).looking_at(Vec3::ZERO, Vec3::Y),
));
}
struct CustomRenderedMeshPipelinePlugin;
impl Plugin for CustomRenderedMeshPipelinePlugin {
fn build(&self, app: &mut App) {
app.add_plugins(ExtractComponentPlugin::<CustomRenderedEntity>::default())
.add_systems(
PostUpdate,
view::check_visibility::<WithCustomRenderedEntity>
.in_set(VisibilitySystems::CheckVisibility),
);
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
return;
};
render_app
.init_resource::<SpecializedMeshPipelines<CustomMeshPipeline>>()
.add_render_command::<Opaque3d, DrawSpecializedPipelineCommands>()
.add_systems(Render, queue_custom_mesh_pipeline.in_set(RenderSet::Queue));
}
fn finish(&self, app: &mut App) {
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
return;
};
render_app.init_resource::<CustomMeshPipeline>();
}
}
#[derive(Clone, Component, ExtractComponent)]
struct CustomRenderedEntity;
type DrawSpecializedPipelineCommands = (
SetItemPipeline,
SetMeshViewBindGroup<0>,
SetMeshBindGroup<1>,
DrawMesh,
);
type WithCustomRenderedEntity = With<CustomRenderedEntity>;
#[derive(Resource)]
struct CustomMeshPipeline {
mesh_pipeline: MeshPipeline,
shader_handle: Handle<Shader>,
}
impl FromWorld for CustomMeshPipeline {
fn from_world(world: &mut World) -> Self {
let shader_handle: Handle<Shader> = world.resource::<AssetServer>().load(SHADER_ASSET_PATH);
Self {
mesh_pipeline: MeshPipeline::from_world(world),
shader_handle,
}
}
}
impl SpecializedMeshPipeline for CustomMeshPipeline {
type Key = MeshPipelineKey;
fn specialize(
&self,
mesh_key: Self::Key,
layout: &MeshVertexBufferLayoutRef,
) -> Result<RenderPipelineDescriptor, SpecializedMeshPipelineError> {
let mut vertex_attributes = Vec::new();
if layout.0.contains(Mesh::ATTRIBUTE_POSITION) {
vertex_attributes.push(Mesh::ATTRIBUTE_POSITION.at_shader_location(0));
}
if layout.0.contains(Mesh::ATTRIBUTE_COLOR) {
vertex_attributes.push(Mesh::ATTRIBUTE_COLOR.at_shader_location(1));
}
let vertex_buffer_layout = layout.0.get_layout(&vertex_attributes)?;
Ok(RenderPipelineDescriptor {
label: Some("Specialized Mesh Pipeline".into()),
layout: vec![
self.mesh_pipeline
.get_view_layout(MeshPipelineViewLayoutKey::from(mesh_key))
.clone(),
self.mesh_pipeline.mesh_layouts.model_only.clone(),
],
push_constant_ranges: vec![],
vertex: VertexState {
shader: self.shader_handle.clone(),
shader_defs: vec![],
entry_point: "vertex".into(),
buffers: vec![vertex_buffer_layout],
},
fragment: Some(FragmentState {
shader: self.shader_handle.clone(),
shader_defs: vec![],
entry_point: "fragment".into(),
targets: vec![Some(ColorTargetState {
format: if mesh_key.contains(MeshPipelineKey::HDR) {
ViewTarget::TEXTURE_FORMAT_HDR
} else {
TextureFormat::bevy_default()
},
blend: None,
write_mask: ColorWrites::ALL,
})],
}),
primitive: PrimitiveState {
topology: mesh_key.primitive_topology(),
front_face: FrontFace::Ccw,
cull_mode: Some(Face::Back),
polygon_mode: PolygonMode::Fill,
..default()
},
depth_stencil: Some(DepthStencilState {
format: CORE_3D_DEPTH_FORMAT,
depth_write_enabled: true,
depth_compare: CompareFunction::GreaterEqual,
stencil: default(),
bias: default(),
}),
multisample: MultisampleState {
count: mesh_key.msaa_samples(),
..MultisampleState::default()
},
zero_initialize_workgroup_memory: false,
})
}
}
#[allow(clippy::too_many_arguments)]
fn queue_custom_mesh_pipeline(
pipeline_cache: Res<PipelineCache>,
custom_mesh_pipeline: Res<CustomMeshPipeline>,
mut opaque_render_phases: ResMut<ViewBinnedRenderPhases<Opaque3d>>,
opaque_draw_functions: Res<DrawFunctions<Opaque3d>>,
mut specialized_mesh_pipelines: ResMut<SpecializedMeshPipelines<CustomMeshPipeline>>,
views: Query<(Entity, &RenderVisibleEntities, &ExtractedView, &Msaa), With<ExtractedView>>,
render_meshes: Res<RenderAssets<RenderMesh>>,
render_mesh_instances: Res<RenderMeshInstances>,
) {
let draw_function_id = opaque_draw_functions
.read()
.id::<DrawSpecializedPipelineCommands>();
for (view_entity, view_visible_entities, view, msaa) in views.iter() {
let Some(opaque_phase) = opaque_render_phases.get_mut(&view_entity) else {
continue;
};
let view_key = MeshPipelineKey::from_msaa_samples(msaa.samples())
| MeshPipelineKey::from_hdr(view.hdr);
for &(render_entity, visible_entity) in view_visible_entities
.get::<WithCustomRenderedEntity>()
.iter()
{
let Some(mesh_instance) = render_mesh_instances.render_mesh_queue_data(visible_entity)
else {
continue;
};
let Some(mesh) = render_meshes.get(mesh_instance.mesh_asset_id) else {
continue;
};
let mut mesh_key = view_key;
mesh_key |= MeshPipelineKey::from_primitive_topology(mesh.primitive_topology());
let pipeline_id = specialized_mesh_pipelines
.specialize(
&pipeline_cache,
&custom_mesh_pipeline,
mesh_key,
&mesh.layout,
)
.expect("Failed to specialize mesh pipeline");
opaque_phase.add(
Opaque3dBinKey {
draw_function: draw_function_id,
pipeline: pipeline_id,
asset_id: AssetId::<Mesh>::invalid().untyped(),
material_bind_group_id: None,
lightmap_image: None,
},
(render_entity, visible_entity),
BinnedRenderPhaseType::BatchableMesh,
);
}
}
}