audioshader/src/main.rs

79 lines
2.3 KiB
Rust
Raw Normal View History

2025-08-30 23:53:21 +00:00
//! A shader that uses the GLSL shading language.
use bevy::{
2025-08-31 00:05:01 +00:00
prelude::*,
reflect::TypePath,
render::render_resource::{AsBindGroup, ShaderRef},
2025-08-31 09:39:39 +00:00
sprite::{AlphaMode2d, Material2d, Material2dPlugin},
window::PrimaryWindow,
2025-08-30 23:53:21 +00:00
};
2025-08-31 09:39:39 +00:00
const SHADER_ASSET_PATH: &str = "shaders/default.wgsl";
2025-08-30 20:48:38 +00:00
fn main() {
App::new()
2025-08-31 09:39:39 +00:00
.add_plugins((
DefaultPlugins,
Material2dPlugin::<CustomMaterial>::default(),
))
2025-08-30 23:53:21 +00:00
.add_systems(Startup, setup)
2025-08-31 09:46:51 +00:00
.add_systems(Update, resize_fullscreen_quad)
2025-08-30 20:48:38 +00:00
.run();
}
2025-08-30 23:53:21 +00:00
2025-08-31 00:05:01 +00:00
/// set up a simple 2D-screen-like surface
2025-08-30 23:53:21 +00:00
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<CustomMaterial>>,
2025-08-31 09:39:39 +00:00
primary_window: Single<&Window, With<PrimaryWindow>>,
2025-08-30 23:53:21 +00:00
) {
2025-08-31 09:39:39 +00:00
// camera
commands.spawn(Camera2d);
// quad that fills the whole window
let size = Vec2::new(
primary_window.resolution.width(),
primary_window.resolution.height(),
);
2025-08-30 23:53:21 +00:00
commands.spawn((
2025-08-31 09:39:39 +00:00
Mesh2d(meshes.add(Rectangle::default())),
MeshMaterial2d(materials.add(CustomMaterial {})),
Transform::from_scale(Vec3::new(size.x, size.y, 1.0)),
2025-08-31 09:46:51 +00:00
FullscreenQuad,
2025-08-30 23:53:21 +00:00
));
}
2025-08-31 09:46:51 +00:00
/// Marker component for the fullscreen quad so we can update it on window resize
#[derive(Component)]
struct FullscreenQuad;
/// Update fullscreen quad transforms when the primary window is resized.
fn resize_fullscreen_quad(
primary_window: Single<&Window, With<PrimaryWindow>>,
mut transform: Single<&mut Transform, With<FullscreenQuad>>,
) {
let size = Vec2::new(
primary_window.resolution.width(),
primary_window.resolution.height(),
);
transform.scale = Vec3::new(size.x, size.y, 1.0);
}
2025-08-30 23:53:21 +00:00
// This is the struct that will be passed to your shader
#[derive(Asset, TypePath, AsBindGroup, Clone)]
2025-08-31 09:39:39 +00:00
struct CustomMaterial {}
2025-08-30 23:53:21 +00:00
2025-08-31 09:39:39 +00:00
/// 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 Material2d api docs for details!
impl Material2d for CustomMaterial {
2025-08-30 23:53:21 +00:00
fn fragment_shader() -> ShaderRef {
2025-08-31 09:39:39 +00:00
SHADER_ASSET_PATH.into()
2025-08-30 23:53:21 +00:00
}
2025-08-31 09:39:39 +00:00
fn alpha_mode(&self) -> AlphaMode2d {
AlphaMode2d::Opaque
2025-08-30 23:53:21 +00:00
}
}