Path: blob/main/examples/shader/shader_material_bindless.rs
6595 views
//! A material that uses bindless textures.12use bevy::prelude::*;3use bevy::render::render_resource::{AsBindGroup, ShaderType};4use bevy::shader::ShaderRef;56const SHADER_ASSET_PATH: &str = "shaders/bindless_material.wgsl";78// `#[bindless(limit(4))]` indicates that we want Bevy to group materials into9// bind groups of at most 4 materials each.10// Note that we use the structure-level `#[uniform]` attribute to supply11// ordinary data to the shader.12#[derive(Asset, TypePath, AsBindGroup, Debug, Clone)]13#[uniform(0, BindlessMaterialUniform, binding_array(10))]14#[bindless(limit(4))]15struct BindlessMaterial {16color: LinearRgba,17// This will be exposed to the shader as a binding array of 4 textures and a18// binding array of 4 samplers.19#[texture(1)]20#[sampler(2)]21color_texture: Option<Handle<Image>>,22}2324// This buffer will be presented to the shader as `@binding(10)`.25#[derive(ShaderType)]26struct BindlessMaterialUniform {27color: LinearRgba,28}2930impl<'a> From<&'a BindlessMaterial> for BindlessMaterialUniform {31fn from(material: &'a BindlessMaterial) -> Self {32BindlessMaterialUniform {33color: material.color,34}35}36}3738// The entry point.39fn main() {40App::new()41.add_plugins((42DefaultPlugins,43MaterialPlugin::<BindlessMaterial>::default(),44))45.add_systems(Startup, setup)46.run();47}4849// Creates a simple scene.50fn setup(51mut commands: Commands,52mut meshes: ResMut<Assets<Mesh>>,53mut materials: ResMut<Assets<BindlessMaterial>>,54asset_server: Res<AssetServer>,55) {56// Add a cube with a blue tinted texture.57commands.spawn((58Mesh3d(meshes.add(Cuboid::default())),59MeshMaterial3d(materials.add(BindlessMaterial {60color: LinearRgba::BLUE,61color_texture: Some(asset_server.load("branding/bevy_logo_dark.png")),62})),63Transform::from_xyz(-2.0, 0.5, 0.0),64));6566// Add a cylinder with a red tinted texture.67commands.spawn((68Mesh3d(meshes.add(Cylinder::default())),69MeshMaterial3d(materials.add(BindlessMaterial {70color: LinearRgba::RED,71color_texture: Some(asset_server.load("branding/bevy_logo_light.png")),72})),73Transform::from_xyz(2.0, 0.5, 0.0),74));7576// Add a camera.77commands.spawn((78Camera3d::default(),79Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y),80));81}8283impl Material for BindlessMaterial {84fn fragment_shader() -> ShaderRef {85SHADER_ASSET_PATH.into()86}87}888990