 8810a73e87
			
		
	
	
		8810a73e87
		
	
	
	
	
		
			
			Port changes made to Material in #5053 to Material2d as well. This is more or less an exact copy of the implementation in bevy_pbr; I simply pretended the API existed, then copied stuff over until it started building and the shapes example was working again. # Objective The changes in #5053 makes it possible to add custom materials with a lot less boiler plate. However, the implementation isn't shared with Material 2d as it's a kind of fork of the bevy_pbr version. It should be possible to use AsBindGroup on the 2d version as well. ## Solution This makes the same kind of changes in Material2d in bevy_sprite. This makes the following work: ```rust //! Draws a circular purple bevy in the middle of the screen using a custom shader use bevy::{ prelude::*, reflect::TypeUuid, render::render_resource::{AsBindGroup, ShaderRef}, sprite::{Material2d, Material2dPlugin, MaterialMesh2dBundle}, }; fn main() { App::new() .add_plugins(DefaultPlugins) .add_plugin(Material2dPlugin::<CustomMaterial>::default()) .add_startup_system(setup) .run(); } /// set up a simple 2D scene fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<CustomMaterial>>, asset_server: Res<AssetServer>, ) { commands.spawn_bundle(MaterialMesh2dBundle { mesh: meshes.add(shape::Circle::new(50.).into()).into(), material: materials.add(CustomMaterial { color: Color::PURPLE, color_texture: Some(asset_server.load("branding/icon.png")), }), transform: Transform::from_translation(Vec3::new(-100., 0., 0.)), ..default() }); commands.spawn_bundle(Camera2dBundle::default()); } /// The Material2d trait is very configurable, but comes with sensible defaults for all methods. /// You only need to implement functions for features that need non-default behavior. See the Material api docs for details! impl Material2d for CustomMaterial { fn fragment_shader() -> ShaderRef { "shaders/custom_material.wgsl".into() } } // This is the struct that will be passed to your shader #[derive(AsBindGroup, TypeUuid, Debug, Clone)] #[uuid = "f690fdae-d598-45ab-8225-97e2a3f056e0"] pub struct CustomMaterial { #[uniform(0)] color: Color, #[texture(1)] #[sampler(2)] color_texture: Option<Handle<Image>>, } ```
		
			
				
	
	
		
			181 lines
		
	
	
		
			5.8 KiB
		
	
	
	
		
			Rust
		
	
	
	
	
	
			
		
		
	
	
			181 lines
		
	
	
		
			5.8 KiB
		
	
	
	
		
			Rust
		
	
	
	
	
	
| //! A custom post processing effect, using two cameras, with one reusing the render texture of the first one.
 | |
| //! Here a chromatic aberration is applied to a 3d scene containting a rotating cube.
 | |
| //! This example is useful to implement your own post-processing effect such as
 | |
| //! edge detection, blur, pixelization, vignette... and countless others.
 | |
| 
 | |
| use bevy::{
 | |
|     core_pipeline::clear_color::ClearColorConfig,
 | |
|     prelude::*,
 | |
|     reflect::TypeUuid,
 | |
|     render::{
 | |
|         camera::{Camera, RenderTarget},
 | |
|         render_resource::{
 | |
|             AsBindGroup, Extent3d, ShaderRef, TextureDescriptor, TextureDimension, TextureFormat,
 | |
|             TextureUsages,
 | |
|         },
 | |
|         view::RenderLayers,
 | |
|     },
 | |
|     sprite::{Material2d, Material2dPlugin, MaterialMesh2dBundle},
 | |
| };
 | |
| 
 | |
| fn main() {
 | |
|     let mut app = App::new();
 | |
|     app.add_plugins(DefaultPlugins)
 | |
|         .add_plugin(Material2dPlugin::<PostProcessingMaterial>::default())
 | |
|         .add_startup_system(setup)
 | |
|         .add_system(main_camera_cube_rotator_system);
 | |
| 
 | |
|     app.run();
 | |
| }
 | |
| 
 | |
| /// Marks the first camera cube (rendered to a texture.)
 | |
| #[derive(Component)]
 | |
| struct MainCube;
 | |
| 
 | |
| fn setup(
 | |
|     mut commands: Commands,
 | |
|     mut windows: ResMut<Windows>,
 | |
|     mut meshes: ResMut<Assets<Mesh>>,
 | |
|     mut post_processing_materials: ResMut<Assets<PostProcessingMaterial>>,
 | |
|     mut materials: ResMut<Assets<StandardMaterial>>,
 | |
|     mut images: ResMut<Assets<Image>>,
 | |
|     asset_server: Res<AssetServer>,
 | |
| ) {
 | |
|     asset_server.watch_for_changes().unwrap();
 | |
| 
 | |
|     let window = windows.get_primary_mut().unwrap();
 | |
|     let size = Extent3d {
 | |
|         width: window.physical_width(),
 | |
|         height: window.physical_height(),
 | |
|         ..default()
 | |
|     };
 | |
| 
 | |
|     // This is the texture that will be rendered to.
 | |
|     let mut image = Image {
 | |
|         texture_descriptor: TextureDescriptor {
 | |
|             label: None,
 | |
|             size,
 | |
|             dimension: TextureDimension::D2,
 | |
|             format: TextureFormat::Bgra8UnormSrgb,
 | |
|             mip_level_count: 1,
 | |
|             sample_count: 1,
 | |
|             usage: TextureUsages::TEXTURE_BINDING
 | |
|                 | TextureUsages::COPY_DST
 | |
|                 | TextureUsages::RENDER_ATTACHMENT,
 | |
|         },
 | |
|         ..default()
 | |
|     };
 | |
| 
 | |
|     // fill image.data with zeroes
 | |
|     image.resize(size);
 | |
| 
 | |
|     let image_handle = images.add(image);
 | |
| 
 | |
|     let cube_handle = meshes.add(Mesh::from(shape::Cube { size: 4.0 }));
 | |
|     let cube_material_handle = materials.add(StandardMaterial {
 | |
|         base_color: Color::rgb(0.8, 0.7, 0.6),
 | |
|         reflectance: 0.02,
 | |
|         unlit: false,
 | |
|         ..default()
 | |
|     });
 | |
| 
 | |
|     // The cube that will be rendered to the texture.
 | |
|     commands
 | |
|         .spawn_bundle(PbrBundle {
 | |
|             mesh: cube_handle,
 | |
|             material: cube_material_handle,
 | |
|             transform: Transform::from_translation(Vec3::new(0.0, 0.0, 1.0)),
 | |
|             ..default()
 | |
|         })
 | |
|         .insert(MainCube);
 | |
| 
 | |
|     // Light
 | |
|     // NOTE: Currently lights are ignoring render layers - see https://github.com/bevyengine/bevy/issues/3462
 | |
|     commands.spawn_bundle(PointLightBundle {
 | |
|         transform: Transform::from_translation(Vec3::new(0.0, 0.0, 10.0)),
 | |
|         ..default()
 | |
|     });
 | |
| 
 | |
|     // Main camera, first to render
 | |
|     commands.spawn_bundle(Camera3dBundle {
 | |
|         camera_3d: Camera3d {
 | |
|             clear_color: ClearColorConfig::Custom(Color::WHITE),
 | |
|             ..default()
 | |
|         },
 | |
|         camera: Camera {
 | |
|             target: RenderTarget::Image(image_handle.clone()),
 | |
|             ..default()
 | |
|         },
 | |
|         transform: Transform::from_translation(Vec3::new(0.0, 0.0, 15.0))
 | |
|             .looking_at(Vec3::default(), Vec3::Y),
 | |
|         ..default()
 | |
|     });
 | |
| 
 | |
|     // This specifies the layer used for the post processing camera, which will be attached to the post processing camera and 2d quad.
 | |
|     let post_processing_pass_layer = RenderLayers::layer((RenderLayers::TOTAL_LAYERS - 1) as u8);
 | |
| 
 | |
|     let quad_handle = meshes.add(Mesh::from(shape::Quad::new(Vec2::new(
 | |
|         size.width as f32,
 | |
|         size.height as f32,
 | |
|     ))));
 | |
| 
 | |
|     // This material has the texture that has been rendered.
 | |
|     let material_handle = post_processing_materials.add(PostProcessingMaterial {
 | |
|         source_image: image_handle,
 | |
|     });
 | |
| 
 | |
|     // Post processing 2d quad, with material using the render texture done by the main camera, with a custom shader.
 | |
|     commands
 | |
|         .spawn_bundle(MaterialMesh2dBundle {
 | |
|             mesh: quad_handle.into(),
 | |
|             material: material_handle,
 | |
|             transform: Transform {
 | |
|                 translation: Vec3::new(0.0, 0.0, 1.5),
 | |
|                 ..default()
 | |
|             },
 | |
|             ..default()
 | |
|         })
 | |
|         .insert(post_processing_pass_layer);
 | |
| 
 | |
|     // The post-processing pass camera.
 | |
|     commands
 | |
|         .spawn_bundle(Camera2dBundle {
 | |
|             camera: Camera {
 | |
|                 // renders after the first main camera which has default value: 0.
 | |
|                 priority: 1,
 | |
|                 ..default()
 | |
|             },
 | |
|             ..Camera2dBundle::default()
 | |
|         })
 | |
|         .insert(post_processing_pass_layer);
 | |
| }
 | |
| 
 | |
| /// Rotates the cube rendered by the main camera
 | |
| fn main_camera_cube_rotator_system(
 | |
|     time: Res<Time>,
 | |
|     mut query: Query<&mut Transform, With<MainCube>>,
 | |
| ) {
 | |
|     for mut transform in &mut query {
 | |
|         transform.rotate_x(0.55 * time.delta_seconds());
 | |
|         transform.rotate_z(0.15 * time.delta_seconds());
 | |
|     }
 | |
| }
 | |
| 
 | |
| // Region below declares of the custom material handling post processing effect
 | |
| 
 | |
| /// Our custom post processing material
 | |
| #[derive(AsBindGroup, TypeUuid, Clone)]
 | |
| #[uuid = "bc2f08eb-a0fb-43f1-a908-54871ea597d5"]
 | |
| struct PostProcessingMaterial {
 | |
|     /// In this example, this image will be the result of the main camera.
 | |
|     #[texture(0)]
 | |
|     #[sampler(1)]
 | |
|     source_image: Handle<Image>,
 | |
| }
 | |
| 
 | |
| impl Material2d for PostProcessingMaterial {
 | |
|     fn fragment_shader() -> ShaderRef {
 | |
|         "shaders/custom_material_chromatic_aberration.wgsl".into()
 | |
|     }
 | |
| }
 |