Skip to main content

meshlet/
meshlet.rs

1//! Meshlet rendering for dense high-poly scenes (experimental).
2
3// Note: This example showcases the meshlet API, but is not the type of scene that would benefit from using meshlets.
4
5use bevy::{
6    camera_controller::free_camera::{FreeCamera, FreeCameraPlugin},
7    light::{CascadeShadowConfigBuilder, DirectionalLightShadowMap},
8    pbr::experimental::meshlet::{MeshletMesh3d, MeshletPlugin},
9    prelude::*,
10    render::render_resource::AsBindGroup,
11};
12use std::f32::consts::PI;
13
14const ASSET_URL: &str =
15    "https://github.com/bevyengine/bevy_asset_files/raw/6dccaef517bde74d1969734703709aead7211dbc/meshlet/bunny.meshlet_mesh";
16
17fn main() {
18    App::new()
19        .insert_resource(DirectionalLightShadowMap { size: 4096 })
20        .add_plugins((
21            DefaultPlugins,
22            MeshletPlugin {
23                cluster_buffer_slots: 1 << 14,
24            },
25            MaterialPlugin::<MeshletDebugMaterial>::default(),
26            FreeCameraPlugin,
27        ))
28        .add_systems(Startup, setup)
29        .add_systems(Update, bunny_wiggler)
30        .run();
31}
32
33fn setup(
34    mut commands: Commands,
35    asset_server: Res<AssetServer>,
36    mut standard_materials: ResMut<Assets<StandardMaterial>>,
37    mut debug_materials: ResMut<Assets<MeshletDebugMaterial>>,
38    mut meshes: ResMut<Assets<Mesh>>,
39) {
40    commands.spawn((
41        Camera3d::default(),
42        Transform::from_translation(Vec3::new(1.8, 0.4, -0.1)).looking_at(Vec3::ZERO, Vec3::Y),
43        Msaa::Off,
44        EnvironmentMapLight {
45            diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"),
46            specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
47            intensity: 150.0,
48            ..default()
49        },
50        FreeCamera::default(),
51    ));
52
53    commands.spawn((
54        DirectionalLight {
55            illuminance: light_consts::lux::FULL_DAYLIGHT,
56            shadow_maps_enabled: true,
57            ..default()
58        },
59        CascadeShadowConfigBuilder {
60            num_cascades: 1,
61            maximum_distance: 15.0,
62            ..default()
63        }
64        .build(),
65        Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, PI * -0.15, PI * -0.15)),
66    ));
67
68    // A custom file format storing a [`bevy_mesh::Mesh`]
69    // that has been converted to a [`bevy_pbr::meshlet::MeshletMesh`]
70    // using [`bevy_pbr::meshlet::MeshletMesh::from_mesh`], which is
71    // a function only available when the `meshlet_processor` cargo feature is enabled.
72    let meshlet_mesh_handle = asset_server.load(ASSET_URL);
73    let debug_material = debug_materials.add(MeshletDebugMaterial::default());
74
75    for x in -2..=2 {
76        let mut bunny = commands.spawn((
77            MeshletMesh3d(meshlet_mesh_handle.clone()),
78            MeshMaterial3d(standard_materials.add(StandardMaterial {
79                base_color: match x {
80                    -2 => Srgba::hex("#dc2626").unwrap().into(),
81                    -1 => Srgba::hex("#ea580c").unwrap().into(),
82                    0 => Srgba::hex("#facc15").unwrap().into(),
83                    1 => Srgba::hex("#16a34a").unwrap().into(),
84                    2 => Srgba::hex("#0284c7").unwrap().into(),
85                    _ => unreachable!(),
86                },
87                perceptual_roughness: (x + 2) as f32 / 4.0,
88                ..default()
89            })),
90            Transform::default()
91                .with_scale(Vec3::splat(0.2))
92                .with_translation(Vec3::new(x as f32 / 2.0, 0.0, -0.3)),
93        ));
94        if x == 1 {
95            bunny.insert(BunnyWiggler);
96        }
97    }
98    for x in -2..=2 {
99        commands.spawn((
100            MeshletMesh3d(meshlet_mesh_handle.clone()),
101            MeshMaterial3d(debug_material.clone()),
102            Transform::default()
103                .with_scale(Vec3::splat(0.2))
104                .with_rotation(Quat::from_rotation_y(PI))
105                .with_translation(Vec3::new(x as f32 / 2.0, 0.0, 0.3)),
106        ));
107    }
108
109    commands.spawn((
110        Mesh3d(meshes.add(Plane3d::default().mesh().size(5.0, 5.0))),
111        MeshMaterial3d(standard_materials.add(StandardMaterial {
112            base_color: Color::WHITE,
113            perceptual_roughness: 1.0,
114            ..default()
115        })),
116    ));
117}
118
119#[derive(Component)]
120struct BunnyWiggler;
121
122fn bunny_wiggler(mut bunny: Query<&mut Transform, With<BunnyWiggler>>, time: Res<Time>) {
123    bunny.single_mut().as_deref_mut().unwrap().translation.z +=
124        ops::cos(time.elapsed_secs() * 10.0) * 0.003;
125}
126
127#[derive(Asset, TypePath, AsBindGroup, Clone, Default)]
128struct MeshletDebugMaterial {
129    _dummy: (),
130}
131
132impl Material for MeshletDebugMaterial {}