repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/2d/move_sprite.rs
examples/2d/move_sprite.rs
//! Renders a 2D scene containing a single, moving sprite. use bevy::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, sprite_movement) .run(); } #[derive(Component)] enum Direction { Left, Right, } fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn(Camera2d); commands.spawn(( Sprite::from_image(asset_server.load("branding/icon.png")), Transform::from_xyz(0., 0., 0.), Direction::Right, )); } /// The sprite is animated by changing its translation depending on the time that has passed since /// the last frame. fn sprite_movement(time: Res<Time>, mut sprite_position: Query<(&mut Direction, &mut Transform)>) { for (mut logo, mut transform) in &mut sprite_position { match *logo { Direction::Right => transform.translation.x += 150. * time.delta_secs(), Direction::Left => transform.translation.x -= 150. * time.delta_secs(), } if transform.translation.x > 200. { *logo = Direction::Left; } else if transform.translation.x < -200. { *logo = Direction::Right; } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/2d/sprite_scale.rs
examples/2d/sprite_scale.rs
//! Shows how to use sprite scaling to fill and fit textures into the sprite. use bevy::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, (setup_sprites, setup_texture_atlas, setup_camera)) .add_systems(Update, animate_sprite) .run(); } fn setup_camera(mut commands: Commands) { commands.spawn(Camera2d); } fn setup_sprites(mut commands: Commands, asset_server: Res<AssetServer>) { let square = asset_server.load("textures/slice_square_2.png"); let banner = asset_server.load("branding/banner.png"); let rects = [ Rect { size: Vec2::new(100., 225.), text: "Stretched".to_string(), transform: Transform::from_translation(Vec3::new(-570., 230., 0.)), texture: square.clone(), image_mode: SpriteImageMode::Auto, }, Rect { size: Vec2::new(100., 225.), text: "Fill Center".to_string(), transform: Transform::from_translation(Vec3::new(-450., 230., 0.)), texture: square.clone(), image_mode: SpriteImageMode::Scale(SpriteScalingMode::FillCenter), }, Rect { size: Vec2::new(100., 225.), text: "Fill Start".to_string(), transform: Transform::from_translation(Vec3::new(-330., 230., 0.)), texture: square.clone(), image_mode: SpriteImageMode::Scale(SpriteScalingMode::FillStart), }, Rect { size: Vec2::new(100., 225.), text: "Fill End".to_string(), transform: Transform::from_translation(Vec3::new(-210., 230., 0.)), texture: square.clone(), image_mode: SpriteImageMode::Scale(SpriteScalingMode::FillEnd), }, Rect { size: Vec2::new(300., 100.), text: "Fill Start Horizontal".to_string(), transform: Transform::from_translation(Vec3::new(10., 290., 0.)), texture: square.clone(), image_mode: SpriteImageMode::Scale(SpriteScalingMode::FillStart), }, Rect { size: Vec2::new(300., 100.), text: "Fill End Horizontal".to_string(), transform: Transform::from_translation(Vec3::new(10., 155., 0.)), texture: square.clone(), image_mode: SpriteImageMode::Scale(SpriteScalingMode::FillEnd), }, Rect { size: Vec2::new(200., 200.), text: "Fill Center".to_string(), transform: Transform::from_translation(Vec3::new(280., 230., 0.)), texture: banner.clone(), image_mode: SpriteImageMode::Scale(SpriteScalingMode::FillCenter), }, Rect { size: Vec2::new(200., 100.), text: "Fill Center".to_string(), transform: Transform::from_translation(Vec3::new(500., 230., 0.)), texture: square.clone(), image_mode: SpriteImageMode::Scale(SpriteScalingMode::FillCenter), }, Rect { size: Vec2::new(100., 100.), text: "Stretched".to_string(), transform: Transform::from_translation(Vec3::new(-570., -40., 0.)), texture: banner.clone(), image_mode: SpriteImageMode::Auto, }, Rect { size: Vec2::new(200., 200.), text: "Fit Center".to_string(), transform: Transform::from_translation(Vec3::new(-400., -40., 0.)), texture: banner.clone(), image_mode: SpriteImageMode::Scale(SpriteScalingMode::FitCenter), }, Rect { size: Vec2::new(200., 200.), text: "Fit Start".to_string(), transform: Transform::from_translation(Vec3::new(-180., -40., 0.)), texture: banner.clone(), image_mode: SpriteImageMode::Scale(SpriteScalingMode::FitStart), }, Rect { size: Vec2::new(200., 200.), text: "Fit End".to_string(), transform: Transform::from_translation(Vec3::new(40., -40., 0.)), texture: banner.clone(), image_mode: SpriteImageMode::Scale(SpriteScalingMode::FitEnd), }, Rect { size: Vec2::new(100., 200.), text: "Fit Center".to_string(), transform: Transform::from_translation(Vec3::new(210., -40., 0.)), texture: banner.clone(), image_mode: SpriteImageMode::Scale(SpriteScalingMode::FitCenter), }, ]; for rect in rects { commands.spawn(( Sprite { image: rect.texture, custom_size: Some(rect.size), image_mode: rect.image_mode, ..default() }, rect.transform, children![( Text2d::new(rect.text), TextLayout::new_with_justify(Justify::Center), TextFont::from_font_size(15.), Transform::from_xyz(0., -0.5 * rect.size.y - 10., 0.), bevy::sprite::Anchor::TOP_CENTER, )], )); } } fn setup_texture_atlas( mut commands: Commands, asset_server: Res<AssetServer>, mut texture_atlas_layouts: ResMut<Assets<TextureAtlasLayout>>, ) { let gabe = asset_server.load("textures/rpg/chars/gabe/gabe-idle-run.png"); let animation_indices_gabe = AnimationIndices { first: 0, last: 6 }; let gabe_atlas = TextureAtlas { layout: texture_atlas_layouts.add(TextureAtlasLayout::from_grid( UVec2::splat(24), 7, 1, None, None, )), index: animation_indices_gabe.first, }; let sprite_sheets = [ SpriteSheet { size: Vec2::new(120., 50.), text: "Stretched".to_string(), transform: Transform::from_translation(Vec3::new(-570., -200., 0.)), texture: gabe.clone(), image_mode: SpriteImageMode::Auto, atlas: gabe_atlas.clone(), indices: animation_indices_gabe.clone(), timer: AnimationTimer(Timer::from_seconds(0.1, TimerMode::Repeating)), }, SpriteSheet { size: Vec2::new(120., 50.), text: "Fill Center".to_string(), transform: Transform::from_translation(Vec3::new(-570., -300., 0.)), texture: gabe.clone(), image_mode: SpriteImageMode::Scale(SpriteScalingMode::FillCenter), atlas: gabe_atlas.clone(), indices: animation_indices_gabe.clone(), timer: AnimationTimer(Timer::from_seconds(0.1, TimerMode::Repeating)), }, SpriteSheet { size: Vec2::new(120., 50.), text: "Fill Start".to_string(), transform: Transform::from_translation(Vec3::new(-430., -200., 0.)), texture: gabe.clone(), image_mode: SpriteImageMode::Scale(SpriteScalingMode::FillStart), atlas: gabe_atlas.clone(), indices: animation_indices_gabe.clone(), timer: AnimationTimer(Timer::from_seconds(0.1, TimerMode::Repeating)), }, SpriteSheet { size: Vec2::new(120., 50.), text: "Fill End".to_string(), transform: Transform::from_translation(Vec3::new(-430., -300., 0.)), texture: gabe.clone(), image_mode: SpriteImageMode::Scale(SpriteScalingMode::FillEnd), atlas: gabe_atlas.clone(), indices: animation_indices_gabe.clone(), timer: AnimationTimer(Timer::from_seconds(0.1, TimerMode::Repeating)), }, SpriteSheet { size: Vec2::new(50., 120.), text: "Fill Center".to_string(), transform: Transform::from_translation(Vec3::new(-300., -250., 0.)), texture: gabe.clone(), image_mode: SpriteImageMode::Scale(SpriteScalingMode::FillCenter), atlas: gabe_atlas.clone(), indices: animation_indices_gabe.clone(), timer: AnimationTimer(Timer::from_seconds(0.1, TimerMode::Repeating)), }, SpriteSheet { size: Vec2::new(50., 120.), text: "Fill Start".to_string(), transform: Transform::from_translation(Vec3::new(-190., -250., 0.)), texture: gabe.clone(), image_mode: SpriteImageMode::Scale(SpriteScalingMode::FillStart), atlas: gabe_atlas.clone(), indices: animation_indices_gabe.clone(), timer: AnimationTimer(Timer::from_seconds(0.1, TimerMode::Repeating)), }, SpriteSheet { size: Vec2::new(50., 120.), text: "Fill End".to_string(), transform: Transform::from_translation(Vec3::new(-90., -250., 0.)), texture: gabe.clone(), image_mode: SpriteImageMode::Scale(SpriteScalingMode::FillEnd), atlas: gabe_atlas.clone(), indices: animation_indices_gabe.clone(), timer: AnimationTimer(Timer::from_seconds(0.1, TimerMode::Repeating)), }, SpriteSheet { size: Vec2::new(120., 50.), text: "Fit Center".to_string(), transform: Transform::from_translation(Vec3::new(20., -200., 0.)), texture: gabe.clone(), image_mode: SpriteImageMode::Scale(SpriteScalingMode::FitCenter), atlas: gabe_atlas.clone(), indices: animation_indices_gabe.clone(), timer: AnimationTimer(Timer::from_seconds(0.1, TimerMode::Repeating)), }, SpriteSheet { size: Vec2::new(120., 50.), text: "Fit Start".to_string(), transform: Transform::from_translation(Vec3::new(20., -300., 0.)), texture: gabe.clone(), image_mode: SpriteImageMode::Scale(SpriteScalingMode::FitStart), atlas: gabe_atlas.clone(), indices: animation_indices_gabe.clone(), timer: AnimationTimer(Timer::from_seconds(0.1, TimerMode::Repeating)), }, SpriteSheet { size: Vec2::new(120., 50.), text: "Fit End".to_string(), transform: Transform::from_translation(Vec3::new(160., -200., 0.)), texture: gabe.clone(), image_mode: SpriteImageMode::Scale(SpriteScalingMode::FitEnd), atlas: gabe_atlas.clone(), indices: animation_indices_gabe.clone(), timer: AnimationTimer(Timer::from_seconds(0.1, TimerMode::Repeating)), }, ]; for sprite_sheet in sprite_sheets { commands.spawn(( Sprite { image_mode: sprite_sheet.image_mode, custom_size: Some(sprite_sheet.size), ..Sprite::from_atlas_image(sprite_sheet.texture.clone(), sprite_sheet.atlas.clone()) }, sprite_sheet.indices, sprite_sheet.timer, sprite_sheet.transform, children![( Text2d::new(sprite_sheet.text), TextLayout::new_with_justify(Justify::Center), TextFont::from_font_size(15.), Transform::from_xyz(0., -0.5 * sprite_sheet.size.y - 10., 0.), bevy::sprite::Anchor::TOP_CENTER, )], )); } } struct Rect { size: Vec2, text: String, transform: Transform, texture: Handle<Image>, image_mode: SpriteImageMode, } struct SpriteSheet { size: Vec2, text: String, transform: Transform, texture: Handle<Image>, image_mode: SpriteImageMode, atlas: TextureAtlas, indices: AnimationIndices, timer: AnimationTimer, } #[derive(Component, Clone)] struct AnimationIndices { first: usize, last: usize, } #[derive(Component, Deref, DerefMut)] struct AnimationTimer(Timer); fn animate_sprite( time: Res<Time>, mut query: Query<(&AnimationIndices, &mut AnimationTimer, &mut Sprite)>, ) { for (indices, mut timer, mut sprite) in &mut query { timer.tick(time.delta()); if timer.just_finished() && let Some(atlas) = &mut sprite.texture_atlas { atlas.index = if atlas.index == indices.last { indices.first } else { atlas.index + 1 }; } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/2d/sprite_animation.rs
examples/2d/sprite_animation.rs
//! Animates a sprite in response to a keyboard event. //! //! See `sprite_sheet.rs` for an example where the sprite animation loops indefinitely. use std::time::Duration; use bevy::{input::common_conditions::input_just_pressed, prelude::*}; fn main() { App::new() .add_plugins(DefaultPlugins.set(ImagePlugin::default_nearest())) // prevents blurry sprites .add_systems(Startup, setup) .add_systems(Update, execute_animations) .add_systems( Update, ( // Press the right arrow key to animate the right sprite trigger_animation::<RightSprite>.run_if(input_just_pressed(KeyCode::ArrowRight)), // Press the left arrow key to animate the left sprite trigger_animation::<LeftSprite>.run_if(input_just_pressed(KeyCode::ArrowLeft)), ), ) .run(); } // This system runs when the user clicks the left arrow key or right arrow key fn trigger_animation<S: Component>(mut animation: Single<&mut AnimationConfig, With<S>>) { // We create a new timer when the animation is triggered animation.frame_timer = AnimationConfig::timer_from_fps(animation.fps); } #[derive(Component)] struct AnimationConfig { first_sprite_index: usize, last_sprite_index: usize, fps: u8, frame_timer: Timer, } impl AnimationConfig { fn new(first: usize, last: usize, fps: u8) -> Self { Self { first_sprite_index: first, last_sprite_index: last, fps, frame_timer: Self::timer_from_fps(fps), } } fn timer_from_fps(fps: u8) -> Timer { Timer::new(Duration::from_secs_f32(1.0 / (fps as f32)), TimerMode::Once) } } // This system loops through all the sprites in the `TextureAtlas`, from `first_sprite_index` to // `last_sprite_index` (both defined in `AnimationConfig`). fn execute_animations(time: Res<Time>, mut query: Query<(&mut AnimationConfig, &mut Sprite)>) { for (mut config, mut sprite) in &mut query { // We track how long the current sprite has been displayed for config.frame_timer.tick(time.delta()); // If it has been displayed for the user-defined amount of time (fps)... if config.frame_timer.just_finished() && let Some(atlas) = &mut sprite.texture_atlas { if atlas.index == config.last_sprite_index { // ...and it IS the last frame, then we move back to the first frame and stop. atlas.index = config.first_sprite_index; } else { // ...and it is NOT the last frame, then we move to the next frame... atlas.index += 1; // ...and reset the frame timer to start counting all over again config.frame_timer = AnimationConfig::timer_from_fps(config.fps); } } } } #[derive(Component)] struct LeftSprite; #[derive(Component)] struct RightSprite; fn setup( mut commands: Commands, asset_server: Res<AssetServer>, mut texture_atlas_layouts: ResMut<Assets<TextureAtlasLayout>>, ) { commands.spawn(Camera2d); // Create a minimal UI explaining how to interact with the example commands.spawn(( Text::new("Left Arrow: Animate Left Sprite\nRight Arrow: Animate Right Sprite"), Node { position_type: PositionType::Absolute, top: px(12), left: px(12), ..default() }, )); // Load the sprite sheet using the `AssetServer` let texture = asset_server.load("textures/rpg/chars/gabe/gabe-idle-run.png"); // The sprite sheet has 7 sprites arranged in a row, and they are all 24px x 24px let layout = TextureAtlasLayout::from_grid(UVec2::splat(24), 7, 1, None, None); let texture_atlas_layout = texture_atlas_layouts.add(layout); // The first (left-hand) sprite runs at 10 FPS let animation_config_1 = AnimationConfig::new(1, 6, 10); // Create the first (left-hand) sprite commands.spawn(( Sprite { image: texture.clone(), texture_atlas: Some(TextureAtlas { layout: texture_atlas_layout.clone(), index: animation_config_1.first_sprite_index, }), ..default() }, Transform::from_scale(Vec3::splat(6.0)).with_translation(Vec3::new(-70.0, 0.0, 0.0)), LeftSprite, animation_config_1, )); // The second (right-hand) sprite runs at 20 FPS let animation_config_2 = AnimationConfig::new(1, 6, 20); // Create the second (right-hand) sprite commands.spawn(( Sprite { image: texture.clone(), texture_atlas: Some(TextureAtlas { layout: texture_atlas_layout.clone(), index: animation_config_2.first_sprite_index, }), ..Default::default() }, Transform::from_scale(Vec3::splat(6.0)).with_translation(Vec3::new(70.0, 0.0, 0.0)), RightSprite, animation_config_2, )); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/2d/mesh2d.rs
examples/2d/mesh2d.rs
//! Shows how to render a polygonal [`Mesh`], generated from a [`Rectangle`] primitive, in a 2D scene. use bevy::{color::palettes::basic::PURPLE, prelude::*}; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .run(); } fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<ColorMaterial>>, ) { commands.spawn(Camera2d); commands.spawn(( Mesh2d(meshes.add(Rectangle::default())), MeshMaterial2d(materials.add(Color::from(PURPLE))), Transform::default().with_scale(Vec3::splat(128.)), )); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/2d/mesh2d_repeated_texture.rs
examples/2d/mesh2d_repeated_texture.rs
//! By default Bevy loads images to textures that clamps the image to the edges //! This example shows how to configure it to repeat the image instead. use bevy::{ audio::AudioPlugin, image::{ImageAddressMode, ImageLoaderSettings, ImageSampler, ImageSamplerDescriptor}, math::Affine2, prelude::*, }; /// How much to move some rectangles away from the center const RECTANGLE_OFFSET: f32 = 250.0; /// Length of the sides of the rectangle const RECTANGLE_SIDE: f32 = 200.; /// How much to move the label away from the rectangle const LABEL_OFFSET: f32 = (RECTANGLE_SIDE / 2.) + 25.; fn main() { App::new() .add_plugins(DefaultPlugins.build().disable::<AudioPlugin>()) .add_systems(Startup, setup) .run(); } fn setup( mut commands: Commands, asset_server: Res<AssetServer>, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<ColorMaterial>>, ) { // #11111: We use a duplicated image so that it can be load with and without // settings let image_with_default_sampler = asset_server.load("textures/fantasy_ui_borders/panel-border-010.png"); let image_with_repeated_sampler = asset_server.load_with_settings( "textures/fantasy_ui_borders/panel-border-010-repeated.png", |s: &mut _| { *s = ImageLoaderSettings { sampler: ImageSampler::Descriptor(ImageSamplerDescriptor { // rewriting mode to repeat image, address_mode_u: ImageAddressMode::Repeat, address_mode_v: ImageAddressMode::Repeat, ..default() }), ..default() } }, ); // central rectangle with not repeated texture commands.spawn(( Mesh2d(meshes.add(Rectangle::new(RECTANGLE_SIDE, RECTANGLE_SIDE))), MeshMaterial2d(materials.add(ColorMaterial { texture: Some(image_with_default_sampler.clone()), ..default() })), Transform::from_translation(Vec3::ZERO), children![( Text2d::new("Control"), Transform::from_xyz(0., LABEL_OFFSET, 0.), )], )); // left rectangle with repeated texture commands.spawn(( Mesh2d(meshes.add(Rectangle::new(RECTANGLE_SIDE, RECTANGLE_SIDE))), MeshMaterial2d(materials.add(ColorMaterial { texture: Some(image_with_repeated_sampler), // uv_transform used here for proportions only, but it is full Affine2 // that's why you can use rotation and shift also uv_transform: Affine2::from_scale(Vec2::new(2., 3.)), ..default() })), Transform::from_xyz(-RECTANGLE_OFFSET, 0.0, 0.0), children![( Text2d::new("Repeat On"), Transform::from_xyz(0., LABEL_OFFSET, 0.), )], )); // right rectangle with scaled texture, but with default sampler. commands.spawn(( Mesh2d(meshes.add(Rectangle::new(RECTANGLE_SIDE, RECTANGLE_SIDE))), MeshMaterial2d(materials.add(ColorMaterial { // there is no sampler set, that's why // by default you see only one small image in a row/column // and other space is filled by image edge texture: Some(image_with_default_sampler), // uv_transform used here for proportions only, but it is full Affine2 // that's why you can use rotation and shift also uv_transform: Affine2::from_scale(Vec2::new(2., 3.)), ..default() })), Transform::from_xyz(RECTANGLE_OFFSET, 0.0, 0.0), children![( Text2d::new("Repeat Off"), Transform::from_xyz(0., LABEL_OFFSET, 0.), )], )); // camera commands.spawn(( Camera2d, Transform::default().looking_at(Vec3::ZERO, Vec3::Y), )); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/2d/sprite_tile.rs
examples/2d/sprite_tile.rs
//! Displays a single [`Sprite`] tiled in a grid, with a scaling animation use bevy::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, animate) .run(); } #[derive(Resource)] struct AnimationState { min: f32, max: f32, current: f32, speed: f32, } fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn(Camera2d); commands.insert_resource(AnimationState { min: 128.0, max: 512.0, current: 128.0, speed: 50.0, }); commands.spawn(Sprite { image: asset_server.load("branding/icon.png"), image_mode: SpriteImageMode::Tiled { tile_x: true, tile_y: true, stretch_value: 0.5, // The image will tile every 128px }, ..default() }); } fn animate(mut sprites: Query<&mut Sprite>, mut state: ResMut<AnimationState>, time: Res<Time>) { if state.current >= state.max || state.current <= state.min { state.speed = -state.speed; }; state.current += state.speed * time.delta_secs(); for mut sprite in &mut sprites { sprite.custom_size = Some(Vec2::splat(state.current)); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/2d/rotation.rs
examples/2d/rotation.rs
//! Demonstrates rotating entities in 2D using quaternions. use bevy::{math::ops, prelude::*}; const BOUNDS: Vec2 = Vec2::new(1200.0, 640.0); fn main() { App::new() .add_plugins(DefaultPlugins) .insert_resource(Time::<Fixed>::from_hz(60.0)) .add_systems(Startup, setup) .add_systems( FixedUpdate, ( player_movement_system, snap_to_player_system, rotate_to_player_system, ), ) .run(); } /// Player component #[derive(Component)] struct Player { /// Linear speed in meters per second movement_speed: f32, /// Rotation speed in radians per second rotation_speed: f32, } /// Snap to player ship behavior #[derive(Component)] struct SnapToPlayer; /// Rotate to face player ship behavior #[derive(Component)] struct RotateToPlayer { /// Rotation speed in radians per second rotation_speed: f32, } /// Add the game's entities to our world and creates an orthographic camera for 2D rendering. /// /// The Bevy coordinate system is the same for 2D and 3D, in terms of 2D this means that: /// /// * `X` axis goes from left to right (`+X` points right) /// * `Y` axis goes from bottom to top (`+Y` point up) /// * `Z` axis goes from far to near (`+Z` points towards you, out of the screen) /// /// The origin is at the center of the screen. fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { let ship_handle = asset_server.load("textures/simplespace/ship_C.png"); let enemy_a_handle = asset_server.load("textures/simplespace/enemy_A.png"); let enemy_b_handle = asset_server.load("textures/simplespace/enemy_B.png"); commands.spawn(Camera2d); // Create a minimal UI explaining how to interact with the example commands.spawn(( Text::new("Up Arrow: Move Forward\nLeft / Right Arrow: Turn"), Node { position_type: PositionType::Absolute, top: px(12), left: px(12), ..default() }, )); let horizontal_margin = BOUNDS.x / 4.0; let vertical_margin = BOUNDS.y / 4.0; // Player controlled ship commands.spawn(( Sprite::from_image(ship_handle), Player { movement_speed: 500.0, // Meters per second rotation_speed: f32::to_radians(360.0), // Degrees per second }, )); // Enemy that snaps to face the player spawns on the bottom and left commands.spawn(( Sprite::from_image(enemy_a_handle.clone()), Transform::from_xyz(0.0 - horizontal_margin, 0.0, 0.0), SnapToPlayer, )); commands.spawn(( Sprite::from_image(enemy_a_handle), Transform::from_xyz(0.0, 0.0 - vertical_margin, 0.0), SnapToPlayer, )); // Enemy that rotates to face the player enemy spawns on the top and right commands.spawn(( Sprite::from_image(enemy_b_handle.clone()), Transform::from_xyz(0.0 + horizontal_margin, 0.0, 0.0), RotateToPlayer { rotation_speed: f32::to_radians(45.0), // Degrees per second }, )); commands.spawn(( Sprite::from_image(enemy_b_handle), Transform::from_xyz(0.0, 0.0 + vertical_margin, 0.0), RotateToPlayer { rotation_speed: f32::to_radians(90.0), // Degrees per second }, )); } /// Demonstrates applying rotation and movement based on keyboard input. fn player_movement_system( time: Res<Time>, keyboard_input: Res<ButtonInput<KeyCode>>, query: Single<(&Player, &mut Transform)>, ) { let (ship, mut transform) = query.into_inner(); let mut rotation_factor = 0.0; let mut movement_factor = 0.0; if keyboard_input.pressed(KeyCode::ArrowLeft) { rotation_factor += 1.0; } if keyboard_input.pressed(KeyCode::ArrowRight) { rotation_factor -= 1.0; } if keyboard_input.pressed(KeyCode::ArrowUp) { movement_factor += 1.0; } // Update the ship rotation around the Z axis (perpendicular to the 2D plane of the screen) transform.rotate_z(rotation_factor * ship.rotation_speed * time.delta_secs()); // Get the ship's forward vector by applying the current rotation to the ships initial facing // vector let movement_direction = transform.rotation * Vec3::Y; // Get the distance the ship will move based on direction, the ship's movement speed and delta // time let movement_distance = movement_factor * ship.movement_speed * time.delta_secs(); // Create the change in translation using the new movement direction and distance let translation_delta = movement_direction * movement_distance; // Update the ship translation with our new translation delta transform.translation += translation_delta; // Bound the ship within the invisible level bounds let extents = Vec3::from((BOUNDS / 2.0, 0.0)); transform.translation = transform.translation.min(extents).max(-extents); } /// Demonstrates snapping the enemy ship to face the player ship immediately. fn snap_to_player_system( mut query: Query<&mut Transform, (With<SnapToPlayer>, Without<Player>)>, player_transform: Single<&Transform, With<Player>>, ) { // Get the player translation in 2D let player_translation = player_transform.translation.xy(); for mut enemy_transform in &mut query { // Get the vector from the enemy ship to the player ship in 2D and normalize it. let to_player = (player_translation - enemy_transform.translation.xy()).normalize(); // Get the quaternion to rotate from the initial enemy facing direction to the direction // facing the player let rotate_to_player = Quat::from_rotation_arc(Vec3::Y, to_player.extend(0.)); // Rotate the enemy to face the player enemy_transform.rotation = rotate_to_player; } } /// Demonstrates rotating an enemy ship to face the player ship at a given rotation speed. /// /// This method uses the vector dot product to determine if the enemy is facing the player and /// if not, which way to rotate to face the player. The dot product on two unit length vectors /// will return a value between -1.0 and +1.0 which tells us the following about the two vectors: /// /// * If the result is 1.0 the vectors are pointing in the same direction, the angle between them is /// 0 degrees. /// * If the result is 0.0 the vectors are perpendicular, the angle between them is 90 degrees. /// * If the result is -1.0 the vectors are parallel but pointing in opposite directions, the angle /// between them is 180 degrees. /// * If the result is positive the vectors are pointing in roughly the same direction, the angle /// between them is greater than 0 and less than 90 degrees. /// * If the result is negative the vectors are pointing in roughly opposite directions, the angle /// between them is greater than 90 and less than 180 degrees. /// /// It is possible to get the angle by taking the arc cosine (`acos`) of the dot product. It is /// often unnecessary to do this though. Beware than `acos` will return `NaN` if the input is less /// than -1.0 or greater than 1.0. This can happen even when working with unit vectors due to /// floating point precision loss, so it pays to clamp your dot product value before calling /// `acos`. fn rotate_to_player_system( time: Res<Time>, mut query: Query<(&RotateToPlayer, &mut Transform), Without<Player>>, player_transform: Single<&Transform, With<Player>>, ) { // Get the player translation in 2D let player_translation = player_transform.translation.xy(); for (config, mut enemy_transform) in &mut query { // Get the enemy ship forward vector in 2D (already unit length) let enemy_forward = (enemy_transform.rotation * Vec3::Y).xy(); // Get the vector from the enemy ship to the player ship in 2D and normalize it. let to_player = (player_translation - enemy_transform.translation.xy()).normalize(); // Get the dot product between the enemy forward vector and the direction to the player. let forward_dot_player = enemy_forward.dot(to_player); // If the dot product is approximately 1.0 then the enemy is already facing the player and // we can early out. if (forward_dot_player - 1.0).abs() < f32::EPSILON { continue; } // Get the right vector of the enemy ship in 2D (already unit length) let enemy_right = (enemy_transform.rotation * Vec3::X).xy(); // Get the dot product of the enemy right vector and the direction to the player ship. // If the dot product is negative them we need to rotate counter clockwise, if it is // positive we need to rotate clockwise. Note that `copysign` will still return 1.0 if the // dot product is 0.0 (because the player is directly behind the enemy, so perpendicular // with the right vector). let right_dot_player = enemy_right.dot(to_player); // Determine the sign of rotation from the right dot player. We need to negate the sign // here as the 2D bevy co-ordinate system rotates around +Z, which is pointing out of the // screen. Due to the right hand rule, positive rotation around +Z is counter clockwise and // negative is clockwise. let rotation_sign = -f32::copysign(1.0, right_dot_player); // Limit rotation so we don't overshoot the target. We need to convert our dot product to // an angle here so we can get an angle of rotation to clamp against. let max_angle = ops::acos(forward_dot_player.clamp(-1.0, 1.0)); // Clamp acos for safety // Calculate angle of rotation with limit let rotation_angle = rotation_sign * (config.rotation_speed * time.delta_secs()).min(max_angle); // Rotate the enemy to face the player enemy_transform.rotate_z(rotation_angle); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/2d/text2d.rs
examples/2d/text2d.rs
//! Shows text rendering with moving, rotating and scaling text. //! //! Note that this uses [`Text2d`] to display text alongside your other entities in a 2D scene. //! //! For an example on how to render text as part of a user interface, independent from the world //! viewport, you may want to look at `games/contributors.rs` or `ui/text.rs`. use bevy::{ color::palettes::css::*, math::ops, prelude::*, sprite::{Anchor, Text2dShadow}, text::{FontSmoothing, LineBreak, TextBounds}, }; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems( Update, (animate_translation, animate_rotation, animate_scale), ) .run(); } #[derive(Component)] struct AnimateTranslation; #[derive(Component)] struct AnimateRotation; #[derive(Component)] struct AnimateScale; fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { let font = asset_server.load("fonts/FiraSans-Bold.ttf"); let text_font = TextFont { font: font.clone().into(), font_size: 50.0, ..default() }; let text_justification = Justify::Center; commands.spawn(Camera2d); // Demonstrate changing translation commands.spawn(( Text2d::new(" translation "), text_font.clone(), TextLayout::new_with_justify(text_justification), TextBackgroundColor(Color::BLACK.with_alpha(0.5)), Text2dShadow::default(), AnimateTranslation, )); // Demonstrate changing rotation commands.spawn(( Text2d::new(" rotation "), text_font.clone(), TextLayout::new_with_justify(text_justification), TextBackgroundColor(Color::BLACK.with_alpha(0.5)), Text2dShadow::default(), AnimateRotation, )); // Demonstrate changing scale commands.spawn(( Text2d::new(" scale "), text_font, TextLayout::new_with_justify(text_justification), Transform::from_translation(Vec3::new(400.0, 0.0, 0.0)), TextBackgroundColor(Color::BLACK.with_alpha(0.5)), Text2dShadow::default(), AnimateScale, )); // Demonstrate text wrapping let slightly_smaller_text_font = TextFont { font: font.into(), font_size: 35.0, ..default() }; let box_size = Vec2::new(300.0, 200.0); let box_position = Vec2::new(0.0, -250.0); let box_color = Color::srgb(0.25, 0.25, 0.55); let text_shadow_color = box_color.darker(0.05); commands.spawn(( Sprite::from_color(Color::srgb(0.25, 0.25, 0.55), box_size), Transform::from_translation(box_position.extend(0.0)), children![( Text2d::new("this text wraps in the box\n(Unicode linebreaks)"), slightly_smaller_text_font.clone(), TextLayout::new(Justify::Left, LineBreak::WordBoundary), // Wrap text in the rectangle TextBounds::from(box_size), // Ensure the text is drawn on top of the box Transform::from_translation(Vec3::Z), // Add a shadow to the text Text2dShadow { color: text_shadow_color, ..default() }, Underline, )], )); let other_box_size = Vec2::new(300.0, 200.0); let other_box_position = Vec2::new(320.0, -250.0); commands.spawn(( Sprite::from_color(Color::srgb(0.25, 0.25, 0.55), other_box_size), Transform::from_translation(other_box_position.extend(0.0)), children![( Text2d::new("this text wraps in the box\n(AnyCharacter linebreaks)"), slightly_smaller_text_font.clone(), TextLayout::new(Justify::Left, LineBreak::AnyCharacter), // Wrap text in the rectangle TextBounds::from(other_box_size), // Ensure the text is drawn on top of the box Transform::from_translation(Vec3::Z), // Add a shadow to the text Text2dShadow { color: text_shadow_color, ..default() } )], )); // Demonstrate font smoothing off commands.spawn(( Text2d::new("This text has\nFontSmoothing::None\nAnd Justify::Center"), slightly_smaller_text_font .clone() .with_font_smoothing(FontSmoothing::None), TextLayout::new_with_justify(Justify::Center), Transform::from_translation(Vec3::new(-400.0, -250.0, 0.0)), // Add a black shadow to the text Text2dShadow::default(), )); let make_child = move |(text_anchor, color): (Anchor, Color)| { ( Text2d::new(" Anchor".to_string()), slightly_smaller_text_font.clone(), text_anchor, TextBackgroundColor(Color::WHITE.darker(0.8)), Transform::from_translation(-1. * Vec3::Z), children![ ( TextSpan("::".to_string()), slightly_smaller_text_font.clone(), TextColor(LIGHT_GREY.into()), TextBackgroundColor(DARK_BLUE.into()), ), ( TextSpan(format!("{text_anchor:?} ")), slightly_smaller_text_font.clone(), TextColor(color), TextBackgroundColor(color.darker(0.3)), ) ], ) }; commands.spawn(( Sprite { color: Color::Srgba(LIGHT_CYAN), custom_size: Some(Vec2::new(10., 10.)), ..Default::default() }, Transform::from_translation(250. * Vec3::Y), children![ make_child((Anchor::TOP_LEFT, Color::Srgba(LIGHT_SALMON))), make_child((Anchor::TOP_RIGHT, Color::Srgba(LIGHT_GREEN))), make_child((Anchor::BOTTOM_RIGHT, Color::Srgba(LIGHT_BLUE))), make_child((Anchor::BOTTOM_LEFT, Color::Srgba(LIGHT_YELLOW))), ], )); } fn animate_translation( time: Res<Time>, mut query: Query<&mut Transform, (With<Text2d>, With<AnimateTranslation>)>, ) { for mut transform in &mut query { transform.translation.x = 100.0 * ops::sin(time.elapsed_secs()) - 400.0; transform.translation.y = 100.0 * ops::cos(time.elapsed_secs()); } } fn animate_rotation( time: Res<Time>, mut query: Query<&mut Transform, (With<Text2d>, With<AnimateRotation>)>, ) { for mut transform in &mut query { transform.rotation = Quat::from_rotation_z(ops::cos(time.elapsed_secs())); } } fn animate_scale( time: Res<Time>, mut query: Query<&mut Transform, (With<Text2d>, With<AnimateScale>)>, ) { // Consider changing font-size instead of scaling the transform. Scaling a Text2D will scale the // rendered quad, resulting in a pixellated look. for mut transform in &mut query { let scale = (ops::sin(time.elapsed_secs()) + 1.1) * 2.0; transform.scale.x = scale; transform.scale.y = scale; } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/2d/tilemap_chunk.rs
examples/2d/tilemap_chunk.rs
//! Shows a tilemap chunk rendered with a single draw call. use bevy::{ color::palettes::tailwind::RED_400, image::{ImageArrayLayout, ImageLoaderSettings}, prelude::*, sprite_render::{TileData, TilemapChunk, TilemapChunkTileData}, }; use rand::{Rng, SeedableRng}; use rand_chacha::ChaCha8Rng; fn main() { App::new() .add_plugins(DefaultPlugins.set(ImagePlugin::default_nearest())) .add_systems(Startup, (setup, spawn_fake_player).chain()) .add_systems(Update, (update_tilemap, move_player, log_tile)) .run(); } #[derive(Component, Deref, DerefMut)] struct UpdateTimer(Timer); #[derive(Resource, Deref, DerefMut)] struct SeededRng(ChaCha8Rng); fn setup(mut commands: Commands, assets: Res<AssetServer>) { // We're seeding the PRNG here to make this example deterministic for testing purposes. // This isn't strictly required in practical use unless you need your app to be deterministic. let mut rng = ChaCha8Rng::seed_from_u64(42); let chunk_size = UVec2::splat(64); let tile_display_size = UVec2::splat(8); let tile_data: Vec<Option<TileData>> = (0..chunk_size.element_product()) .map(|_| rng.random_range(0..5)) .map(|i| { if i == 0 { None } else { Some(TileData::from_tileset_index(i - 1)) } }) .collect(); commands.spawn(( TilemapChunk { chunk_size, tile_display_size, tileset: assets.load_with_settings( "textures/array_texture.png", |settings: &mut ImageLoaderSettings| { // The tileset texture is expected to be an array of tile textures, so we tell the // `ImageLoader` that our texture is composed of 4 stacked tile images. settings.array_layout = Some(ImageArrayLayout::RowCount { rows: 4 }); }, ), ..default() }, TilemapChunkTileData(tile_data), UpdateTimer(Timer::from_seconds(0.1, TimerMode::Repeating)), )); commands.spawn(Camera2d); commands.insert_resource(SeededRng(rng)); } #[derive(Component)] struct MovePlayer; fn spawn_fake_player( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<ColorMaterial>>, chunk: Single<&TilemapChunk>, ) { let mut transform = chunk.calculate_tile_transform(UVec2::new(0, 0)); transform.translation.z = 1.; commands.spawn(( Mesh2d(meshes.add(Rectangle::new(8., 8.))), MeshMaterial2d(materials.add(Color::from(RED_400))), transform, MovePlayer, )); let mut transform = chunk.calculate_tile_transform(UVec2::new(5, 6)); transform.translation.z = 1.; // second "player" to visually test a non-zero position commands.spawn(( Mesh2d(meshes.add(Rectangle::new(8., 8.))), MeshMaterial2d(materials.add(Color::from(RED_400))), transform, )); } fn move_player( mut player: Single<&mut Transform, With<MovePlayer>>, time: Res<Time>, chunk: Single<&TilemapChunk>, ) { let t = (ops::sin(time.elapsed_secs()) + 1.) / 2.; let origin = chunk .calculate_tile_transform(UVec2::new(0, 0)) .translation .x; let destination = chunk .calculate_tile_transform(UVec2::new(63, 0)) .translation .x; player.translation.x = origin.lerp(destination, t); } fn update_tilemap( time: Res<Time>, mut query: Query<(&mut TilemapChunkTileData, &mut UpdateTimer)>, mut rng: ResMut<SeededRng>, ) { for (mut tile_data, mut timer) in query.iter_mut() { timer.tick(time.delta()); if timer.just_finished() { for _ in 0..50 { let index = rng.random_range(0..tile_data.len()); tile_data[index] = Some(TileData::from_tileset_index(rng.random_range(0..5))); } } } } // find the data for an arbitrary tile in the chunk and log its data fn log_tile(tilemap: Single<(&TilemapChunk, &TilemapChunkTileData)>, mut local: Local<u16>) { let (chunk, data) = tilemap.into_inner(); let Some(tile_data) = data.tile_data_from_tile_pos(chunk.chunk_size, UVec2::new(3, 4)) else { return; }; // log when the tile changes if tile_data.tileset_index != *local { info!(?tile_data, "tile_data changed"); *local = tile_data.tileset_index; } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/2d/mesh2d_alpha_mode.rs
examples/2d/mesh2d_alpha_mode.rs
//! This example is used to test how transforms interact with alpha modes for [`Mesh2d`] entities with a [`MeshMaterial2d`]. //! This makes sure the depth buffer is correctly being used for opaque and transparent 2d meshes use bevy::{ color::palettes::css::{BLUE, GREEN, WHITE}, prelude::*, sprite_render::AlphaMode2d, }; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .run(); } fn setup( mut commands: Commands, asset_server: Res<AssetServer>, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<ColorMaterial>>, ) { commands.spawn(Camera2d); let texture_handle = asset_server.load("branding/icon.png"); let mesh_handle = meshes.add(Rectangle::from_size(Vec2::splat(256.0))); // opaque // Each sprite should be square with the transparent parts being completely black // The blue sprite should be on top with the white and green one behind it commands.spawn(( Mesh2d(mesh_handle.clone()), MeshMaterial2d(materials.add(ColorMaterial { color: WHITE.into(), alpha_mode: AlphaMode2d::Opaque, texture: Some(texture_handle.clone()), ..default() })), Transform::from_xyz(-400.0, 0.0, 0.0), )); commands.spawn(( Mesh2d(mesh_handle.clone()), MeshMaterial2d(materials.add(ColorMaterial { color: BLUE.into(), alpha_mode: AlphaMode2d::Opaque, texture: Some(texture_handle.clone()), ..default() })), Transform::from_xyz(-300.0, 0.0, 1.0), )); commands.spawn(( Mesh2d(mesh_handle.clone()), MeshMaterial2d(materials.add(ColorMaterial { color: GREEN.into(), alpha_mode: AlphaMode2d::Opaque, texture: Some(texture_handle.clone()), ..default() })), Transform::from_xyz(-200.0, 0.0, -1.0), )); // Test the interaction between opaque/mask and transparent meshes // The white sprite should be: // - only the icon is opaque but background is transparent // - on top of the green sprite // - behind the blue sprite commands.spawn(( Mesh2d(mesh_handle.clone()), MeshMaterial2d(materials.add(ColorMaterial { color: WHITE.into(), alpha_mode: AlphaMode2d::Mask(0.5), texture: Some(texture_handle.clone()), ..default() })), Transform::from_xyz(200.0, 0.0, 0.0), )); commands.spawn(( Mesh2d(mesh_handle.clone()), MeshMaterial2d(materials.add(ColorMaterial { color: BLUE.with_alpha(0.7).into(), alpha_mode: AlphaMode2d::Blend, texture: Some(texture_handle.clone()), ..default() })), Transform::from_xyz(300.0, 0.0, 1.0), )); commands.spawn(( Mesh2d(mesh_handle.clone()), MeshMaterial2d(materials.add(ColorMaterial { color: GREEN.with_alpha(0.7).into(), alpha_mode: AlphaMode2d::Blend, texture: Some(texture_handle), ..default() })), Transform::from_xyz(400.0, 0.0, -1.0), )); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/2d/dynamic_mip_generation.rs
examples/2d/dynamic_mip_generation.rs
//! Demonstrates use of the mipmap generation plugin to generate mipmaps for a //! texture. //! //! This example demonstrates use of the [`MipGenerationJobs`] resource to //! generate mipmap levels for a texture at runtime. It generates the first //! mipmap level of a texture on CPU, which consists of two ellipses with //! randomly chosen colors. Then it invokes Bevy's mipmap generation pass to //! generate the remaining mipmap levels for the texture on the GPU. You can use //! the UI to regenerate the texture and adjust its size to prove that the //! texture, and its mipmaps, are truly being generated at runtime and aren't //! being built ahead of time. use std::array; use bevy::{ asset::RenderAssetUsages, core_pipeline::mip_generation::{MipGenerationJobs, MipGenerationNode, MipGenerationPhaseId}, prelude::*, reflect::TypePath, render::{ graph::CameraDriverLabel, render_graph::{RenderGraph, RenderLabel}, render_resource::{AsBindGroup, Extent3d, TextureDimension, TextureFormat, TextureUsages}, Extract, RenderApp, }, shader::ShaderRef, sprite::Text2dShadow, sprite_render::{AlphaMode2d, Material2d, Material2dPlugin}, window::{PrimaryWindow, WindowResized}, }; use rand::{Rng, SeedableRng}; use rand_chacha::ChaCha8Rng; use crate::widgets::{ RadioButton, RadioButtonText, WidgetClickEvent, WidgetClickSender, BUTTON_BORDER, BUTTON_BORDER_COLOR, BUTTON_BORDER_RADIUS_SIZE, BUTTON_PADDING, }; #[path = "../helpers/widgets.rs"] mod widgets; /// The time in seconds that it takes the animation of the image shrinking and /// growing to play. const ANIMATION_PERIOD: f32 = 2.0; /// The path to the single mip level 2D material shader inside the `assets` /// directory. const SINGLE_MIP_LEVEL_SHADER_ASSET_PATH: &str = "shaders/single_mip_level.wgsl"; /// The distance from the left side of the column of mipmap slices to the right /// side of the area used for the animation. const MIP_SLICES_MARGIN_LEFT: f32 = 64.0; /// The distance from the right side of the window to the right side of the /// column of mipmap slices. const MIP_SLICES_MARGIN_RIGHT: f32 = 12.0; /// The width of the column of mipmap slices, not counting the labels, as a /// fraction of the width of the window. const MIP_SLICES_WIDTH: f32 = 1.0 / 6.0; /// The size of the mipmap level label font. const FONT_SIZE: f32 = 16.0; /// All settings that the user can change via the UI. #[derive(Resource)] struct AppStatus { /// Whether mipmaps are to be generated for the image. enable_mip_generation: EnableMipGeneration, /// The width of the image. image_width: ImageSize, /// The height of the image. image_height: ImageSize, /// Seeded random generator. rng: ChaCha8Rng, } impl Default for AppStatus { fn default() -> Self { AppStatus { enable_mip_generation: EnableMipGeneration::On, image_width: ImageSize::Size640, image_height: ImageSize::Size480, rng: ChaCha8Rng::seed_from_u64(19878367467713), } } } /// Identifies one of the settings that can be changed by the user. #[derive(Clone)] enum AppSetting { /// Regenerates the top mipmap level. /// /// This is more of an *operation* than a *setting* per se, but it was /// convenient to use the `AppSetting` infrastructure for the "Regenerate /// Top Mip Level" button. RegenerateTopMipLevel, /// Whether mipmaps should be generated. EnableMipGeneration(EnableMipGeneration), /// The width of the image. ImageWidth(ImageSize), /// The height of the image. ImageHeight(ImageSize), } /// Whether mipmap levels will be generated. /// /// Turning off the generation of mipmap levels, and then regenerating the /// image, will cause all mipmap levels other than the first to be blank. This /// will in turn cause the image to fade out as it shrinks, as the GPU switches /// to rendering mipmap levels that don't have associated images. #[derive(Clone, Copy, Default, PartialEq)] enum EnableMipGeneration { /// Mipmap levels are generated for the image. #[default] On, /// Mipmap levels aren't generated for the image. Off, } /// Possible lengths for an image side from which the user can choose. #[derive(Clone, Copy, Default, PartialEq)] #[repr(u32)] enum ImageSize { /// 240px. Size240 = 240, /// 480px (the default height). Size480 = 480, /// 640px (the default width). #[default] Size640 = 640, /// 1080px. Size1080 = 1080, /// 1920px. Size1920 = 1920, } /// A 2D material that displays only one mipmap level of a texture. /// /// This is the material used for the column of mip levels on the right side of /// the window. #[derive(Clone, Asset, TypePath, AsBindGroup, Debug)] struct SingleMipLevelMaterial { /// The mip level that this material will show, starting from 0. #[uniform(0)] mip_level: u32, /// The image that is to be shown. #[texture(1)] #[sampler(2)] texture: Handle<Image>, } impl Material2d for SingleMipLevelMaterial { fn fragment_shader() -> ShaderRef { SINGLE_MIP_LEVEL_SHADER_ASSET_PATH.into() } fn alpha_mode(&self) -> AlphaMode2d { AlphaMode2d::Blend } } /// A marker component for the image on the left side of the window. /// /// This is the image that grows and shrinks to demonstrate the effect of mip /// levels' presence and absence. #[derive(Component)] struct AnimatedImage; /// A resource that stores the main image for which mipmaps are to be generated /// (or not generated, depending on the application settings). #[derive(Resource, Deref, DerefMut)] struct MipmapSourceImage(Handle<Image>); /// An iterator that yields the size of each mipmap level for an image, one /// after another. struct MipmapSizeIterator { /// The size of the previous mipmap level, or `None` if this iterator is /// finished. size: Option<UVec2>, } /// A [`RenderLabel`] for the mipmap generation render node. /// /// This is needed in order to order the mipmap generation node relative to the /// node that renders the image for which mipmaps have been generated. #[derive(Clone, Copy, Hash, PartialEq, Eq, Debug, RenderLabel)] struct MipGenerationLabel; /// A marker component for every mesh that displays the image. /// /// When the image is regenerated, we despawn and respawn all entities with this /// component. #[derive(Component)] struct ImageView; /// A message that's sent whenever the image and the corresponding views need to /// be regenerated. #[derive(Clone, Copy, Debug, Message)] struct RegenerateImage; /// The application entry point. fn main() { let mut app = App::new(); app.add_plugins(( DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "Bevy Dynamic Mipmap Generation Example".into(), ..default() }), ..default() }), Material2dPlugin::<SingleMipLevelMaterial>::default(), )) .init_resource::<AppStatus>() .init_resource::<AppAssets>() .add_message::<RegenerateImage>() .add_message::<WidgetClickEvent<AppSetting>>() .add_systems(Startup, setup) .add_systems(Update, animate_image_scale) .add_systems( Update, ( widgets::handle_ui_interactions::<AppSetting>, update_radio_buttons, ) .chain(), ) .add_systems( Update, (handle_window_resize_events, regenerate_image_when_requested).chain(), ) .add_systems( Update, handle_app_setting_change .after(widgets::handle_ui_interactions::<AppSetting>) .before(regenerate_image_when_requested), ); // Because `MipGenerationJobs` is part of the render app, we need to add the // associated systems to that app, not the main one. let render_app = app.get_sub_app_mut(RenderApp).expect("Need a render app"); // Add a `MipGenerationNode` corresponding to our phase to the render graph. let mut render_graph = render_app.world_mut().resource_mut::<RenderGraph>(); render_graph.add_node( MipGenerationLabel, MipGenerationNode(MipGenerationPhaseId(0)), ); // Add an edge so that our mip generation node will run prior to rendering // any cameras. // If your mip generation node needs to run before some cameras and after // others, you can use more complex constraints. Or, for more exotic // scenarios, you can also create a custom render node that wraps a // `MipGenerationNode` and examines properties of the camera to invoke the // node at the appropriate time. render_graph.add_node_edge(MipGenerationLabel, CameraDriverLabel); // Add the system that adds the image into the `MipGenerationJobs` list. // Note that this must run as part of the extract schedule, because it needs // access to resources from both the main world and the render world. render_app.add_systems(ExtractSchedule, extract_mipmap_source_image); app.run(); } /// Global assets used for this example. #[derive(Resource)] struct AppAssets { /// A 2D rectangle mesh, used to display the individual images. rectangle: Handle<Mesh>, /// The font used to display the mipmap level labels on the right side of /// the window. text_font: TextFont, } impl FromWorld for AppAssets { fn from_world(world: &mut World) -> Self { let mut meshes = world.resource_mut::<Assets<Mesh>>(); let rectangle = meshes.add(Rectangle::default()); let asset_server = world.resource::<AssetServer>(); let font = asset_server.load("fonts/FiraSans-Bold.ttf"); let text_font = TextFont { font: font.into(), font_size: FONT_SIZE, ..default() }; AppAssets { rectangle, text_font, } } } /// Spawns all the objects in the scene and creates the initial image and /// associated resources. fn setup( mut commands: Commands, mut regenerate_image_message_writer: MessageWriter<RegenerateImage>, ) { // Spawn the camera. commands.spawn(Camera2d); // Spawn the UI widgets at the bottom of the window. spawn_ui(&mut commands); // Schedule the image to be generated. regenerate_image_message_writer.write(RegenerateImage); } /// Spawns the UI widgets at the bottom of the window. fn spawn_ui(commands: &mut Commands) { commands.spawn(( widgets::main_ui_node(), children![ // Spawn the "Regenerate Top Mip Level" button. ( Button, Node { border: BUTTON_BORDER, justify_content: JustifyContent::Center, align_items: AlignItems::Center, padding: BUTTON_PADDING, border_radius: BorderRadius::all(BUTTON_BORDER_RADIUS_SIZE), ..default() }, BUTTON_BORDER_COLOR, BackgroundColor(Color::BLACK), WidgetClickSender(AppSetting::RegenerateTopMipLevel), children![( widgets::ui_text("Regenerate Top Mip Level", Color::WHITE), WidgetClickSender(AppSetting::RegenerateTopMipLevel), )], ), // Spawn the "Mip Generation" switch that allows the user to toggle // mip generation on and off. widgets::option_buttons( "Mip Generation", &[ ( AppSetting::EnableMipGeneration(EnableMipGeneration::On), "On" ), ( AppSetting::EnableMipGeneration(EnableMipGeneration::Off), "Off" ), ] ), // Spawn the "Image Width" control that allows the user to set the // width of the image. widgets::option_buttons( "Image Width", &[ (AppSetting::ImageWidth(ImageSize::Size240), "240"), (AppSetting::ImageWidth(ImageSize::Size480), "480"), (AppSetting::ImageWidth(ImageSize::Size640), "640"), (AppSetting::ImageWidth(ImageSize::Size1080), "1080"), (AppSetting::ImageWidth(ImageSize::Size1920), "1920"), ] ), // Spawn the "Image Height" control that allows the user to set the // height of the image. widgets::option_buttons( "Image Height", &[ (AppSetting::ImageHeight(ImageSize::Size240), "240"), (AppSetting::ImageHeight(ImageSize::Size480), "480"), (AppSetting::ImageHeight(ImageSize::Size640), "640"), (AppSetting::ImageHeight(ImageSize::Size1080), "1080"), (AppSetting::ImageHeight(ImageSize::Size1920), "1920"), ] ), ], )); } impl MipmapSizeIterator { /// Creates a [`MipmapSizeIterator`] corresponding to the size of the image /// currently being displayed. fn new(app_status: &AppStatus) -> MipmapSizeIterator { MipmapSizeIterator { size: Some(app_status.image_size_u32()), } } } impl Iterator for MipmapSizeIterator { type Item = UVec2; fn next(&mut self) -> Option<Self::Item> { // The size of mipmap level N + 1 is equal to half the size of mipmap // level N, rounding down, except that the size can never go below 1 // pixel on either axis. let result = self.size; if let Some(size) = self.size { self.size = if size == UVec2::splat(1) { None } else { Some((size / 2).max(UVec2::splat(1))) }; } result } } /// Updates the size of the image on the left side of the window each frame. /// /// Resizing the image every frame effectively cycles through all the image's /// mipmap levels, demonstrating the difference between the presence of mipmap /// levels and their absence. fn animate_image_scale( mut animated_images_query: Query<&mut Transform, With<AnimatedImage>>, windows_query: Query<&Window, With<PrimaryWindow>>, app_status: Res<AppStatus>, time: Res<Time>, ) { let window_size = windows_query.iter().next().unwrap().size(); let animated_mesh_size = app_status.animated_mesh_size(window_size); for mut animated_image_transform in &mut animated_images_query { animated_image_transform.scale = animated_mesh_size.extend(1.0) * triangle_wave(time.elapsed_secs(), ANIMATION_PERIOD); } } /// Evaluates a [triangle wave] with the given wavelength. /// /// This is used as part of [`animate_image_scale`], to derive the scale from /// the current elapsed time. /// /// [triangle wave]: https://en.wikipedia.org/wiki/Triangle_wave#Definition fn triangle_wave(time: f32, wavelength: f32) -> f32 { 2.0 * ops::abs(time / wavelength - ops::floor(time / wavelength + 0.5)) } /// Adds the top mipmap level of the image to [`MipGenerationJobs`]. /// /// Note that this must run in the render world, not the main world, as /// [`MipGenerationJobs`] is a resource that exists in the former. Consequently, /// it must use [`Extract`] to access main world resources. fn extract_mipmap_source_image( mipmap_source_image: Extract<Res<MipmapSourceImage>>, app_status: Extract<Res<AppStatus>>, mut mip_generation_jobs: ResMut<MipGenerationJobs>, ) { if app_status.enable_mip_generation == EnableMipGeneration::On { mip_generation_jobs.add(MipGenerationPhaseId(0), mipmap_source_image.id()); } } /// Updates the widgets at the bottom of the screen to reflect the settings that /// the user has chosen. fn update_radio_buttons( mut widgets: Query< ( Entity, Option<&mut BackgroundColor>, Has<Text>, &WidgetClickSender<AppSetting>, ), Or<(With<RadioButton>, With<RadioButtonText>)>, >, app_status: Res<AppStatus>, mut writer: TextUiWriter, ) { for (entity, image, has_text, sender) in widgets.iter_mut() { let selected = match **sender { AppSetting::RegenerateTopMipLevel => continue, AppSetting::EnableMipGeneration(enable_mip_generation) => { enable_mip_generation == app_status.enable_mip_generation } AppSetting::ImageWidth(image_width) => image_width == app_status.image_width, AppSetting::ImageHeight(image_height) => image_height == app_status.image_height, }; if let Some(mut bg_color) = image { widgets::update_ui_radio_button(&mut bg_color, selected); } if has_text { widgets::update_ui_radio_button_text(entity, &mut writer, selected); } } } /// Handles a request from the user to change application settings via the UI. /// /// This also handles clicks on the "Regenerate Top Mip Level" button. fn handle_app_setting_change( mut events: MessageReader<WidgetClickEvent<AppSetting>>, mut app_status: ResMut<AppStatus>, mut regenerate_image_message_writer: MessageWriter<RegenerateImage>, ) { for event in events.read() { // If this is a setting, update the setting. Fall through if, in // addition to updating the setting, we need to regenerate the image. match **event { AppSetting::EnableMipGeneration(enable_mip_generation) => { app_status.enable_mip_generation = enable_mip_generation; continue; } AppSetting::RegenerateTopMipLevel => {} AppSetting::ImageWidth(image_size) => app_status.image_width = image_size, AppSetting::ImageHeight(image_size) => app_status.image_height = image_size, } // Schedule the image to be regenerated. regenerate_image_message_writer.write(RegenerateImage); } } /// Handles resize events for the window. /// /// Resizing the window invalidates the image and repositions all image views. /// (Regenerating the image isn't strictly necessary, but it's simplest to have /// a single function that both regenerates the image and recreates the image /// views.) fn handle_window_resize_events( mut events: MessageReader<WindowResized>, mut regenerate_image_message_writer: MessageWriter<RegenerateImage>, ) { for _ in events.read() { regenerate_image_message_writer.write(RegenerateImage); } } /// Recreates the image, as well as all views that show the image, when a /// [`RegenerateImage`] message is received. /// /// The views that show the image consist of the animated mesh on the left side /// of the window and the column of mipmap level views on the right side of the /// window. fn regenerate_image_when_requested( mut commands: Commands, image_views_query: Query<Entity, With<ImageView>>, windows_query: Query<&Window, With<PrimaryWindow>>, app_assets: Res<AppAssets>, mut app_status: ResMut<AppStatus>, mut images: ResMut<Assets<Image>>, mut single_mip_level_materials: ResMut<Assets<SingleMipLevelMaterial>>, mut color_materials: ResMut<Assets<ColorMaterial>>, mut message_reader: MessageReader<RegenerateImage>, ) { // Only do this at most once per frame, or else the despawn logic below will // get confused. if message_reader.read().count() == 0 { return; } // Despawn all entities that show the image. for entity in image_views_query.iter() { commands.entity(entity).despawn(); } // Regenerate the image. let image_handle = app_status.regenerate_mipmap_source_image(&mut commands, &mut images); // Respawn the animated image view on the left side of the window. spawn_animated_mesh( &mut commands, &app_status, &app_assets, &windows_query, &mut color_materials, &image_handle, ); // Respawn the column of mip level views on the right side of the window. spawn_mip_level_views( &mut commands, &app_status, &app_assets, &windows_query, &mut single_mip_level_materials, &image_handle, ); } /// Spawns the image on the left that continually changes scale. /// /// Continually changing scale effectively cycles though each mip level, /// demonstrating the difference between mip level images being present and mip /// level image being absent. fn spawn_animated_mesh( commands: &mut Commands, app_status: &AppStatus, app_assets: &AppAssets, windows_query: &Query<&Window, With<PrimaryWindow>>, color_materials: &mut Assets<ColorMaterial>, image_handle: &Handle<Image>, ) { let window_size = windows_query.iter().next().unwrap().size(); let animated_mesh_area_size = app_status.animated_mesh_area_size(window_size); let animated_mesh_size = app_status.animated_mesh_size(window_size); commands.spawn(( Mesh2d(app_assets.rectangle.clone()), MeshMaterial2d(color_materials.add(ColorMaterial { texture: Some(image_handle.clone()), ..default() })), Transform::from_translation( (animated_mesh_area_size * 0.5 - window_size * 0.5).extend(0.0), ) .with_scale(animated_mesh_size.extend(1.0)), AnimatedImage, ImageView, )); } /// Creates the column on the right side of the window that displays each mip /// level by itself. fn spawn_mip_level_views( commands: &mut Commands, app_status: &AppStatus, app_assets: &AppAssets, windows_query: &Query<&Window, With<PrimaryWindow>>, single_mip_level_materials: &mut Assets<SingleMipLevelMaterial>, image_handle: &Handle<Image>, ) { let window_size = windows_query.iter().next().unwrap().size(); // Calculate the placement of the column of mipmap levels. let max_slice_size = app_status.max_mip_slice_size(window_size); let y_origin = app_status.vertical_mip_slice_origin(window_size); let y_spacing = app_status.vertical_mip_slice_spacing(window_size); let x_origin = app_status.horizontal_mip_slice_origin(window_size); for (mip_level, mip_size) in MipmapSizeIterator::new(app_status).enumerate() { let y_center = y_origin - y_spacing * mip_level as f32; // Size each image to fit its container, preserving aspect ratio. let mut slice_size = mip_size.as_vec2(); let ratios = max_slice_size / slice_size; let slice_scale = ratios.x.min(ratios.y).min(1.0); slice_size *= slice_scale; // Spawn the image. Use the `SingleMipLevelMaterial` with its custom // shader so that only the mip level in question is displayed. commands.spawn(( Mesh2d(app_assets.rectangle.clone()), MeshMaterial2d(single_mip_level_materials.add(SingleMipLevelMaterial { mip_level: mip_level as u32, texture: image_handle.clone(), })), Transform::from_xyz(x_origin, y_center, 0.0).with_scale(slice_size.extend(1.0)), ImageView, )); // Display a label to the side. commands.spawn(( Text2d::new(format!( "Level {}\n{}×{}", mip_level, mip_size.x, mip_size.y )), app_assets.text_font.clone(), TextLayout::new_with_justify(Justify::Center), Text2dShadow::default(), Transform::from_xyz(x_origin - max_slice_size.x * 0.5 - 64.0, y_center, 0.0), ImageView, )); } } /// Returns true if the given point is inside a 2D ellipse with the given center /// and given radii or false otherwise. fn point_in_ellipse(point: Vec2, center: Vec2, radii: Vec2) -> bool { // This can be derived from the standard equation of an ellipse: // // x² y² // ⎯⎯ + ⎯⎯ = 1 // a² b² let (nums, denoms) = (point - center, radii); let terms = (nums * nums) / (denoms * denoms); terms.x + terms.y < 1.0 } impl AppStatus { /// Returns the vertical distance between each mip slice image in the column /// on the right side of the window. fn vertical_mip_slice_spacing(&self, window_size: Vec2) -> f32 { window_size.y / self.image_mip_level_count() as f32 } /// Returns the Y position of the center of the image that represents the /// first mipmap level in the column on the right side of the window. fn vertical_mip_slice_origin(&self, window_size: Vec2) -> f32 { let spacing = self.vertical_mip_slice_spacing(window_size); window_size.y * 0.5 - spacing * 0.5 } /// Returns the maximum area that a single mipmap slice can occupy in the /// column at the right side of the window. /// /// Because the slices may be smaller than this area, and because the size /// of each slice preserves the aspect ratio of the image, the actual /// displayed size of each slice may be smaller than this. fn max_mip_slice_size(&self, window_size: Vec2) -> Vec2 { let spacing = self.vertical_mip_slice_spacing(window_size); vec2(window_size.x * MIP_SLICES_WIDTH, spacing) } /// Returns the horizontal center point of each mip slice image in the /// column at the right side of the window. fn horizontal_mip_slice_origin(&self, window_size: Vec2) -> f32 { let max_slice_size = self.max_mip_slice_size(window_size); window_size.x * 0.5 - max_slice_size.x * 0.5 - MIP_SLICES_MARGIN_RIGHT } /// Calculates and returns the area reserved for the animated image on the /// left side of the window. /// /// Note that this isn't necessarily equal to the final size of the animated /// image, because that size preserves the image's aspect ratio. fn animated_mesh_area_size(&self, window_size: Vec2) -> Vec2 { vec2( self.horizontal_mip_slice_origin(window_size) * 2.0 - MIP_SLICES_MARGIN_LEFT * 2.0, window_size.y, ) } /// Calculates and returns the actual maximum size of the animated image on /// the left side of the window. /// /// This is equal to the maximum portion of the /// [`Self::animated_mesh_area_size`] that the image can occupy while /// preserving its aspect ratio. fn animated_mesh_size(&self, window_size: Vec2) -> Vec2 { let max_image_size = self.animated_mesh_area_size(window_size); let image_size = self.image_size_f32(); let ratios = max_image_size / image_size; let image_scale = ratios.x.min(ratios.y); image_size * image_scale } /// Returns the size of the image as a [`UVec2`]. fn image_size_u32(&self) -> UVec2 { uvec2(self.image_width as u32, self.image_height as u32) } /// Returns the size of the image as a [`Vec2`]. fn image_size_f32(&self) -> Vec2 { vec2( self.image_width as u32 as f32, self.image_height as u32 as f32, ) } /// Regenerates the main image based on the image size selected by the user. fn regenerate_mipmap_source_image( &mut self, commands: &mut Commands, images: &mut Assets<Image>, ) -> Handle<Image> { let image_data = self.generate_image_data(); let mut image = Image::new_uninit( Extent3d { width: self.image_width as u32, height: self.image_height as u32, depth_or_array_layers: 1, }, TextureDimension::D2, TextureFormat::Rgba8Unorm, RenderAssetUsages::all(), ); image.texture_descriptor.mip_level_count = self.image_mip_level_count(); image.texture_descriptor.usage |= TextureUsages::STORAGE_BINDING; image.data = Some(image_data); let image_handle = images.add(image); commands.insert_resource(MipmapSourceImage(image_handle.clone())); image_handle } /// Draws the concentric ellipses that make up the image. /// /// Returns the RGBA8 image data. fn generate_image_data(&mut self) -> Vec<u8> { // Select random colors for the inner and outer ellipses. let outer_color: [u8; 3] = array::from_fn(|_| self.rng.random()); let inner_color: [u8; 3] = array::from_fn(|_| self.rng.random()); let image_byte_size = 4usize * MipmapSizeIterator::new(self) .map(|size| size.x as usize * size.y as usize) .sum::<usize>(); let mut image_data = vec![0u8; image_byte_size]; let center = self.image_size_f32() * 0.5; let inner_ellipse_radii = self.inner_ellipse_radii(); let outer_ellipse_radii = self.outer_ellipse_radii(); for y in 0..(self.image_height as u32) { for x in 0..(self.image_width as u32) { let p = vec2(x as f32, y as f32); let (color, alpha) = if point_in_ellipse(p, center, inner_ellipse_radii) { (inner_color, 255) } else if point_in_ellipse(p, center, outer_ellipse_radii) { (outer_color, 255) } else { ([0; 3], 0) }; let start = (4 * (x + y * (self.image_width as u32))) as usize; image_data[start..(start + 3)].copy_from_slice(&color); image_data[start + 3] = alpha; } } image_data } /// Returns the number of mipmap levels that the image should possess. /// /// This will be equal to the maximum number of mipmap levels that an image /// of the appropriate size can have. fn image_mip_level_count(&self) -> u32 { 32 - (self.image_width as u32) .max(self.image_height as u32) .leading_zeros() } /// Returns the X and Y radii of the outer ellipse drawn in the texture, /// respectively. fn outer_ellipse_radii(&self) -> Vec2 { self.image_size_f32() * 0.5 } /// Returns the X and Y radii of the inner ellipse drawn in the texture, /// respectively. fn inner_ellipse_radii(&self) -> Vec2 { self.image_size_f32() * 0.25 } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/2d/transparency_2d.rs
examples/2d/transparency_2d.rs
//! Demonstrates how to use transparency in 2D. //! Shows 3 bevy logos on top of each other, each with a different amount of transparency. use bevy::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .run(); } fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn(Camera2d); let sprite_handle = asset_server.load("branding/icon.png"); commands.spawn(( Sprite::from_image(sprite_handle.clone()), Transform::from_xyz(-100.0, 0.0, 0.0), )); commands.spawn(( Sprite { image: sprite_handle.clone(), // Alpha channel of the color controls transparency. color: Color::srgba(0.0, 0.0, 1.0, 0.7), ..default() }, Transform::from_xyz(0.0, 0.0, 0.1), )); commands.spawn(( Sprite { image: sprite_handle, color: Color::srgba(0.0, 1.0, 0.0, 0.3), ..default() }, Transform::from_xyz(100.0, 0.0, 0.2), )); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/2d/texture_atlas.rs
examples/2d/texture_atlas.rs
//! In this example we generate four texture atlases (sprite sheets) from a folder containing //! individual sprites. //! //! The texture atlases are generated with different padding and sampling to demonstrate the //! effect of these settings, and how bleeding issues can be resolved by padding the sprites. //! //! Only one padded and one unpadded texture atlas are rendered to the screen. //! An upscaled sprite from each of the four atlases are rendered to the screen. use bevy::{asset::LoadedFolder, image::ImageSampler, prelude::*}; fn main() { App::new() .add_plugins(DefaultPlugins.set(ImagePlugin::default_nearest())) // fallback to nearest sampling .init_state::<AppState>() .add_systems(OnEnter(AppState::Setup), load_textures) .add_systems(Update, check_textures.run_if(in_state(AppState::Setup))) .add_systems(OnEnter(AppState::Finished), setup) .run(); } #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, States)] enum AppState { #[default] Setup, Finished, } #[derive(Resource, Default)] struct RpgSpriteFolder(Handle<LoadedFolder>); fn load_textures(mut commands: Commands, asset_server: Res<AssetServer>) { // Load multiple, individual sprites from a folder commands.insert_resource(RpgSpriteFolder(asset_server.load_folder("textures/rpg"))); } fn check_textures( mut next_state: ResMut<NextState<AppState>>, rpg_sprite_folder: Res<RpgSpriteFolder>, mut events: MessageReader<AssetEvent<LoadedFolder>>, ) { // Advance the `AppState` once all sprite handles have been loaded by the `AssetServer` for event in events.read() { if event.is_loaded_with_dependencies(&rpg_sprite_folder.0) { next_state.set(AppState::Finished); } } } fn setup( mut commands: Commands, rpg_sprite_handles: Res<RpgSpriteFolder>, asset_server: Res<AssetServer>, mut texture_atlases: ResMut<Assets<TextureAtlasLayout>>, loaded_folders: Res<Assets<LoadedFolder>>, mut textures: ResMut<Assets<Image>>, ) { let loaded_folder = loaded_folders.get(&rpg_sprite_handles.0).unwrap(); // Create texture atlases with different padding and sampling let (texture_atlas_linear, linear_sources, linear_texture) = create_texture_atlas( loaded_folder, None, Some(ImageSampler::linear()), &mut textures, ); let atlas_linear_handle = texture_atlases.add(texture_atlas_linear); let (texture_atlas_nearest, nearest_sources, nearest_texture) = create_texture_atlas( loaded_folder, None, Some(ImageSampler::nearest()), &mut textures, ); let atlas_nearest_handle = texture_atlases.add(texture_atlas_nearest); let (texture_atlas_linear_padded, linear_padded_sources, linear_padded_texture) = create_texture_atlas( loaded_folder, Some(UVec2::new(6, 6)), Some(ImageSampler::linear()), &mut textures, ); let atlas_linear_padded_handle = texture_atlases.add(texture_atlas_linear_padded.clone()); let (texture_atlas_nearest_padded, nearest_padded_sources, nearest_padded_texture) = create_texture_atlas( loaded_folder, Some(UVec2::new(6, 6)), Some(ImageSampler::nearest()), &mut textures, ); let atlas_nearest_padded_handle = texture_atlases.add(texture_atlas_nearest_padded); commands.spawn(Camera2d); // Padded textures are to the right, unpadded to the left // Draw unpadded texture atlas commands.spawn(( Sprite::from_image(linear_texture.clone()), Transform { translation: Vec3::new(-250.0, -160.0, 0.0), scale: Vec3::splat(0.5), ..default() }, )); // Draw padded texture atlas commands.spawn(( Sprite::from_image(linear_padded_texture.clone()), Transform { translation: Vec3::new(250.0, -160.0, 0.0), scale: Vec3::splat(0.5), ..default() }, )); let font = asset_server.load("fonts/FiraSans-Bold.ttf"); // Padding label text style let text_style: TextFont = TextFont { font: font.clone().into(), font_size: 42.0, ..default() }; // Labels to indicate padding // No padding create_label( &mut commands, (-250.0, 250.0, 0.0), "No padding", text_style.clone(), ); // Padding create_label(&mut commands, (250.0, 250.0, 0.0), "Padding", text_style); // Get handle to a sprite to render let vendor_handle: Handle<Image> = asset_server .get_handle("textures/rpg/chars/vendor/generic-rpg-vendor.png") .unwrap(); // Configuration array to render sprites through iteration let configurations: [( &str, Handle<TextureAtlasLayout>, TextureAtlasSources, Handle<Image>, f32, ); 4] = [ ( "Linear", atlas_linear_handle, linear_sources, linear_texture, -350.0, ), ( "Nearest", atlas_nearest_handle, nearest_sources, nearest_texture, -150.0, ), ( "Linear", atlas_linear_padded_handle, linear_padded_sources, linear_padded_texture, 150.0, ), ( "Nearest", atlas_nearest_padded_handle, nearest_padded_sources, nearest_padded_texture, 350.0, ), ]; // Label text style let sampling_label_style = TextFont { font: font.into(), font_size: 25.0, ..default() }; let base_y = 80.0; // y position of the sprites for (sampling, atlas_handle, atlas_sources, atlas_texture, x) in configurations { // Render a sprite from the texture_atlas create_sprite_from_atlas( &mut commands, (x, base_y, 0.0), atlas_texture, atlas_sources, atlas_handle, &vendor_handle, ); // Render a label to indicate the sampling setting create_label( &mut commands, (x, base_y + 110.0, 0.0), // Offset to y position of the sprite sampling, sampling_label_style.clone(), ); } } /// Create a texture atlas with the given padding and sampling settings /// from the individual sprites in the given folder. fn create_texture_atlas( folder: &LoadedFolder, padding: Option<UVec2>, sampling: Option<ImageSampler>, textures: &mut ResMut<Assets<Image>>, ) -> (TextureAtlasLayout, TextureAtlasSources, Handle<Image>) { // Build a texture atlas using the individual sprites let mut texture_atlas_builder = TextureAtlasBuilder::default(); texture_atlas_builder.padding(padding.unwrap_or_default()); for handle in folder.handles.iter() { let id = handle.id().typed_unchecked::<Image>(); let Some(texture) = textures.get(id) else { warn!( "{} did not resolve to an `Image` asset.", handle.path().unwrap() ); continue; }; texture_atlas_builder.add_texture(Some(id), texture); } let (texture_atlas_layout, texture_atlas_sources, texture) = texture_atlas_builder.build().unwrap(); let texture = textures.add(texture); // Update the sampling settings of the texture atlas let image = textures.get_mut(&texture).unwrap(); image.sampler = sampling.unwrap_or_default(); (texture_atlas_layout, texture_atlas_sources, texture) } /// Create and spawn a sprite from a texture atlas fn create_sprite_from_atlas( commands: &mut Commands, translation: (f32, f32, f32), atlas_texture: Handle<Image>, atlas_sources: TextureAtlasSources, atlas_handle: Handle<TextureAtlasLayout>, vendor_handle: &Handle<Image>, ) { commands.spawn(( Transform { translation: Vec3::new(translation.0, translation.1, translation.2), scale: Vec3::splat(3.0), ..default() }, Sprite::from_atlas_image( atlas_texture, atlas_sources.handle(atlas_handle, vendor_handle).unwrap(), ), )); } /// Create and spawn a label (text) fn create_label( commands: &mut Commands, translation: (f32, f32, f32), text: &str, text_style: TextFont, ) { commands.spawn(( Text2d::new(text), text_style, TextLayout::new_with_justify(Justify::Center), Transform { translation: Vec3::new(translation.0, translation.1, translation.2), ..default() }, )); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/2d/wireframe_2d.rs
examples/2d/wireframe_2d.rs
//! Showcases wireframe rendering for 2d meshes. //! //! Wireframes currently do not work when using webgl or webgpu. //! Supported platforms: //! - DX12 //! - Vulkan //! - Metal //! //! This is a native only feature. use bevy::{ color::palettes::basic::{GREEN, RED, WHITE}, prelude::*, render::{ render_resource::WgpuFeatures, settings::{RenderCreation, WgpuSettings}, RenderPlugin, }, sprite_render::{ NoWireframe2d, Wireframe2d, Wireframe2dColor, Wireframe2dConfig, Wireframe2dPlugin, }, }; fn main() { App::new() .add_plugins(( DefaultPlugins.set(RenderPlugin { render_creation: RenderCreation::Automatic(WgpuSettings { // WARN this is a native only feature. It will not work with webgl or webgpu features: WgpuFeatures::POLYGON_MODE_LINE, ..default() }), ..default() }), // You need to add this plugin to enable wireframe rendering Wireframe2dPlugin::default(), )) // Wireframes can be configured with this resource. This can be changed at runtime. .insert_resource(Wireframe2dConfig { // The global wireframe config enables drawing of wireframes on every mesh, // except those with `NoWireframe2d`. Meshes with `Wireframe2d` will always have a wireframe, // regardless of the global configuration. global: true, // Controls the default color of all wireframes. Used as the default color for global wireframes. // Can be changed per mesh using the `Wireframe2dColor` component. default_color: WHITE.into(), }) .add_systems(Startup, setup) .add_systems(Update, update_colors) .run(); } /// Set up a simple 3D scene fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<ColorMaterial>>, ) { // Triangle: Never renders a wireframe commands.spawn(( Mesh2d(meshes.add(Triangle2d::new( Vec2::new(0.0, 50.0), Vec2::new(-50.0, -50.0), Vec2::new(50.0, -50.0), ))), MeshMaterial2d(materials.add(Color::BLACK)), Transform::from_xyz(-150.0, 0.0, 0.0), NoWireframe2d, )); // Rectangle: Follows global wireframe setting commands.spawn(( Mesh2d(meshes.add(Rectangle::new(100.0, 100.0))), MeshMaterial2d(materials.add(Color::BLACK)), Transform::from_xyz(0.0, 0.0, 0.0), )); // Circle: Always renders a wireframe commands.spawn(( Mesh2d(meshes.add(Circle::new(50.0))), MeshMaterial2d(materials.add(Color::BLACK)), Transform::from_xyz(150.0, 0.0, 0.0), Wireframe2d, // This lets you configure the wireframe color of this entity. // If not set, this will use the color in `WireframeConfig` Wireframe2dColor { color: GREEN.into(), }, )); commands.spawn(Camera2d); // Text used to show controls commands.spawn(( Text::default(), Node { position_type: PositionType::Absolute, top: px(12), left: px(12), ..default() }, )); } /// This system lets you toggle various wireframe settings fn update_colors( keyboard_input: Res<ButtonInput<KeyCode>>, mut config: ResMut<Wireframe2dConfig>, mut wireframe_colors: Query<&mut Wireframe2dColor>, mut text: Single<&mut Text>, ) { text.0 = format!( "Controls --------------- Z - Toggle global X - Change global color C - Change color of the circle wireframe Wireframe2dConfig ------------- Global: {} Color: {:?}", config.global, config.default_color.to_srgba(), ); // Toggle showing a wireframe on all meshes if keyboard_input.just_pressed(KeyCode::KeyZ) { config.global = !config.global; } // Toggle the global wireframe color if keyboard_input.just_pressed(KeyCode::KeyX) { config.default_color = if config.default_color == WHITE.into() { RED.into() } else { WHITE.into() }; } // Toggle the color of a wireframe using `Wireframe2dColor` and not the global color if keyboard_input.just_pressed(KeyCode::KeyC) { for mut color in &mut wireframe_colors { color.color = if color.color == GREEN.into() { RED.into() } else { GREEN.into() }; } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/2d/mesh2d_arcs.rs
examples/2d/mesh2d_arcs.rs
//! Demonstrates UV mappings of the [`CircularSector`] and [`CircularSegment`] primitives. //! //! Also draws the bounding boxes and circles of the primitives. use std::f32::consts::FRAC_PI_2; use bevy::{ color::palettes::css::{BLUE, GRAY, RED}, math::{ bounding::{Bounded2d, BoundingVolume}, Isometry2d, }, mesh::{CircularMeshUvMode, CircularSectorMeshBuilder, CircularSegmentMeshBuilder}, prelude::*, }; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems( Update, ( draw_bounds::<CircularSector>, draw_bounds::<CircularSegment>, ), ) .run(); } #[derive(Component, Debug)] struct DrawBounds<Shape: Bounded2d + Send + Sync + 'static>(Shape); fn setup( mut commands: Commands, asset_server: Res<AssetServer>, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<ColorMaterial>>, ) { let material = materials.add(asset_server.load("branding/icon.png")); commands.spawn(( Camera2d, Camera { clear_color: ClearColorConfig::Custom(GRAY.into()), ..default() }, )); const NUM_SLICES: i32 = 8; const SPACING_X: f32 = 100.0; const OFFSET_X: f32 = SPACING_X * (NUM_SLICES - 1) as f32 / 2.0; // This draws NUM_SLICES copies of the Bevy logo as circular sectors and segments, // with successively larger angles up to a complete circle. for i in 0..NUM_SLICES { let fraction = (i + 1) as f32 / NUM_SLICES as f32; let sector = CircularSector::from_turns(40.0, fraction); // We want to rotate the circular sector so that the sectors appear clockwise from north. // We must rotate it both in the Transform and in the mesh's UV mappings. let sector_angle = -sector.half_angle(); let sector_mesh = CircularSectorMeshBuilder::new(sector).uv_mode(CircularMeshUvMode::Mask { angle: sector_angle, }); commands.spawn(( Mesh2d(meshes.add(sector_mesh)), MeshMaterial2d(material.clone()), Transform { translation: Vec3::new(SPACING_X * i as f32 - OFFSET_X, 50.0, 0.0), rotation: Quat::from_rotation_z(sector_angle), ..default() }, DrawBounds(sector), )); let segment = CircularSegment::from_turns(40.0, fraction); // For the circular segment, we will draw Bevy charging forward, which requires rotating the // shape and texture by 90 degrees. // // Note that this may be unintuitive; it may feel like we should rotate the texture by the // opposite angle to preserve the orientation of Bevy. But the angle is not the angle of the // texture itself, rather it is the angle at which the vertices are mapped onto the texture. // so it is the negative of what you might otherwise expect. let segment_angle = -FRAC_PI_2; let segment_mesh = CircularSegmentMeshBuilder::new(segment).uv_mode(CircularMeshUvMode::Mask { angle: -segment_angle, }); commands.spawn(( Mesh2d(meshes.add(segment_mesh)), MeshMaterial2d(material.clone()), Transform { translation: Vec3::new(SPACING_X * i as f32 - OFFSET_X, -50.0, 0.0), rotation: Quat::from_rotation_z(segment_angle), ..default() }, DrawBounds(segment), )); } } fn draw_bounds<Shape: Bounded2d + Send + Sync + 'static>( q: Query<(&DrawBounds<Shape>, &GlobalTransform)>, mut gizmos: Gizmos, ) { for (shape, transform) in &q { let (_, rotation, translation) = transform.to_scale_rotation_translation(); let translation = translation.truncate(); let rotation = rotation.to_euler(EulerRot::XYZ).2; let isometry = Isometry2d::new(translation, Rot2::radians(rotation)); let aabb = shape.0.aabb_2d(isometry); gizmos.rect_2d(aabb.center(), aabb.half_size() * 2.0, RED); let bounding_circle = shape.0.bounding_circle(isometry); gizmos.circle_2d(bounding_circle.center, bounding_circle.radius(), BLUE); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/2d/sprite_slice.rs
examples/2d/sprite_slice.rs
//! Showcases sprite 9 slice scaling and tiling features, enabling usage of //! sprites in multiple resolutions while keeping it in proportion use bevy::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .run(); } fn spawn_sprites( commands: &mut Commands, texture_handle: Handle<Image>, mut position: Vec3, slice_border: f32, style: TextFont, gap: f32, ) { let cases = [ // Reference sprite ( "Original", style.clone(), Vec2::splat(100.0), SpriteImageMode::Auto, ), // Scaled regular sprite ( "Stretched", style.clone(), Vec2::new(100.0, 200.0), SpriteImageMode::Auto, ), // Stretched Scaled sliced sprite ( "With Slicing", style.clone(), Vec2::new(100.0, 200.0), SpriteImageMode::Sliced(TextureSlicer { border: BorderRect::all(slice_border), center_scale_mode: SliceScaleMode::Stretch, ..default() }), ), // Scaled sliced sprite ( "With Tiling", style.clone(), Vec2::new(100.0, 200.0), SpriteImageMode::Sliced(TextureSlicer { border: BorderRect::all(slice_border), center_scale_mode: SliceScaleMode::Tile { stretch_value: 0.5 }, sides_scale_mode: SliceScaleMode::Tile { stretch_value: 0.2 }, ..default() }), ), // Scaled sliced sprite horizontally ( "With Tiling", style.clone(), Vec2::new(300.0, 200.0), SpriteImageMode::Sliced(TextureSlicer { border: BorderRect::all(slice_border), center_scale_mode: SliceScaleMode::Tile { stretch_value: 0.2 }, sides_scale_mode: SliceScaleMode::Tile { stretch_value: 0.3 }, ..default() }), ), // Scaled sliced sprite horizontally with max scale ( "With Corners Constrained", style, Vec2::new(300.0, 200.0), SpriteImageMode::Sliced(TextureSlicer { border: BorderRect::all(slice_border), center_scale_mode: SliceScaleMode::Tile { stretch_value: 0.1 }, sides_scale_mode: SliceScaleMode::Tile { stretch_value: 0.2 }, max_corner_scale: 0.2, }), ), ]; for (label, text_style, size, scale_mode) in cases { position.x += 0.5 * size.x; commands.spawn(( Sprite { image: texture_handle.clone(), custom_size: Some(size), image_mode: scale_mode, ..default() }, Transform::from_translation(position), children![( Text2d::new(label), text_style, TextLayout::new_with_justify(Justify::Center), Transform::from_xyz(0., -0.5 * size.y - 10., 0.0), bevy::sprite::Anchor::TOP_CENTER, )], )); position.x += 0.5 * size.x + gap; } } fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn(Camera2d); let font = asset_server.load("fonts/FiraSans-Bold.ttf"); let style = TextFont { font: font.into(), ..default() }; // Load textures let handle_1 = asset_server.load("textures/slice_square.png"); let handle_2 = asset_server.load("textures/slice_square_2.png"); spawn_sprites( &mut commands, handle_1, Vec3::new(-600.0, 150.0, 0.0), 200.0, style.clone(), 40., ); spawn_sprites( &mut commands, handle_2, Vec3::new(-600.0, -150.0, 0.0), 80.0, style, 40., ); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/2d/cpu_draw.rs
examples/2d/cpu_draw.rs
//! Example of how to draw to a texture from the CPU. //! //! You can set the values of individual pixels to whatever you want. //! Bevy provides user-friendly APIs that work with [`Color`] //! values and automatically perform any necessary conversions and encoding //! into the texture's native pixel format. use bevy::asset::RenderAssetUsages; use bevy::color::{color_difference::EuclideanDistance, palettes::css}; use bevy::prelude::*; use bevy::render::render_resource::{Extent3d, TextureDimension, TextureFormat}; use rand::{Rng, SeedableRng}; use rand_chacha::ChaCha8Rng; const IMAGE_WIDTH: u32 = 256; const IMAGE_HEIGHT: u32 = 256; fn main() { App::new() .add_plugins(DefaultPlugins) // In this example, we will use a fixed timestep to draw a pattern on the screen // one pixel at a time, so the pattern will gradually emerge over time, and // the speed at which it appears is not tied to the framerate. // Let's make the fixed update very fast, so it doesn't take too long. :) .insert_resource(Time::<Fixed>::from_hz(1024.0)) .add_systems(Startup, setup) .add_systems(FixedUpdate, draw) .run(); } /// Store the image handle that we will draw to, here. #[derive(Resource)] struct MyProcGenImage(Handle<Image>); #[derive(Resource)] struct SeededRng(ChaCha8Rng); fn setup(mut commands: Commands, mut images: ResMut<Assets<Image>>) { commands.spawn(Camera2d); // Create an image that we are going to draw into let mut image = Image::new_fill( // 2D image of size 256x256 Extent3d { width: IMAGE_WIDTH, height: IMAGE_HEIGHT, depth_or_array_layers: 1, }, TextureDimension::D2, // Initialize it with a beige color &(css::BEIGE.to_u8_array()), // Use the same encoding as the color we set TextureFormat::Rgba8UnormSrgb, RenderAssetUsages::MAIN_WORLD | RenderAssetUsages::RENDER_WORLD, ); // To make it extra fancy, we can set the Alpha of each pixel, // so that it fades out in a circular fashion. for y in 0..IMAGE_HEIGHT { for x in 0..IMAGE_WIDTH { let center = Vec2::new(IMAGE_WIDTH as f32 / 2.0, IMAGE_HEIGHT as f32 / 2.0); let max_radius = IMAGE_HEIGHT.min(IMAGE_WIDTH) as f32 / 2.0; let r = Vec2::new(x as f32, y as f32).distance(center); let a = 1.0 - (r / max_radius).clamp(0.0, 1.0); // Here we will set the A value by accessing the raw data bytes. // (it is the 4th byte of each pixel, as per our `TextureFormat`) // Find our pixel by its coordinates let pixel_bytes = image.pixel_bytes_mut(UVec3::new(x, y, 0)).unwrap(); // Convert our f32 to u8 pixel_bytes[3] = (a * u8::MAX as f32) as u8; } } // Add it to Bevy's assets, so it can be used for rendering // this will give us a handle we can use // (to display it in a sprite, or as part of UI, etc.) let handle = images.add(image); // Create a sprite entity using our image commands.spawn(Sprite::from_image(handle.clone())); commands.insert_resource(MyProcGenImage(handle)); // We're seeding the PRNG here to make this example deterministic for testing purposes. // This isn't strictly required in practical use unless you need your app to be deterministic. let seeded_rng = ChaCha8Rng::seed_from_u64(19878367467712); commands.insert_resource(SeededRng(seeded_rng)); } /// Every fixed update tick, draw one more pixel to make a spiral pattern fn draw( my_handle: Res<MyProcGenImage>, mut images: ResMut<Assets<Image>>, // Used to keep track of where we are mut i: Local<u32>, mut draw_color: Local<Color>, mut seeded_rng: ResMut<SeededRng>, ) { if *i == 0 { // Generate a random color on first run. *draw_color = Color::linear_rgb( seeded_rng.0.random(), seeded_rng.0.random(), seeded_rng.0.random(), ); } // Get the image from Bevy's asset storage. let image = images.get_mut(&my_handle.0).expect("Image not found"); // Compute the position of the pixel to draw. let center = Vec2::new(IMAGE_WIDTH as f32 / 2.0, IMAGE_HEIGHT as f32 / 2.0); let max_radius = IMAGE_HEIGHT.min(IMAGE_WIDTH) as f32 / 2.0; let rot_speed = 0.0123; let period = 0.12345; let r = ops::sin(*i as f32 * period) * max_radius; let xy = Vec2::from_angle(*i as f32 * rot_speed) * r + center; let (x, y) = (xy.x as u32, xy.y as u32); // Get the old color of that pixel. let old_color = image.get_color_at(x, y).unwrap(); // If the old color is our current color, change our drawing color. let tolerance = 1.0 / 255.0; if old_color.distance(&draw_color) <= tolerance { *draw_color = Color::linear_rgb( seeded_rng.0.random(), seeded_rng.0.random(), seeded_rng.0.random(), ); } // Set the new color, but keep old alpha value from image. image .set_color_at(x, y, draw_color.with_alpha(old_color.alpha())) .unwrap(); *i += 1; }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/2d/sprite.rs
examples/2d/sprite.rs
//! Displays a single [`Sprite`], created from an image. use bevy::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .run(); } fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn(Camera2d); commands.spawn(Sprite::from_image( asset_server.load("branding/bevy_bird_dark.png"), )); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/2d/mesh2d_vertex_color_texture.rs
examples/2d/mesh2d_vertex_color_texture.rs
//! Shows how to render a polygonal [`Mesh`], generated from a [`Rectangle`] primitive, in a 2D scene. //! Adds a texture and colored vertices, giving per-vertex tinting. use bevy::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .run(); } fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<ColorMaterial>>, asset_server: Res<AssetServer>, ) { // Load the Bevy logo as a texture let texture_handle = asset_server.load("branding/banner.png"); // Build a default quad mesh let mut mesh = Mesh::from(Rectangle::default()); // Build vertex colors for the quad. One entry per vertex (the corners of the quad) let vertex_colors: Vec<[f32; 4]> = vec![ LinearRgba::RED.to_f32_array(), LinearRgba::GREEN.to_f32_array(), LinearRgba::BLUE.to_f32_array(), LinearRgba::WHITE.to_f32_array(), ]; // Insert the vertex colors as an attribute mesh.insert_attribute(Mesh::ATTRIBUTE_COLOR, vertex_colors); let mesh_handle = meshes.add(mesh); commands.spawn(Camera2d); // Spawn the quad with vertex colors commands.spawn(( Mesh2d(mesh_handle.clone()), MeshMaterial2d(materials.add(ColorMaterial::default())), Transform::from_translation(Vec3::new(-96., 0., 0.)).with_scale(Vec3::splat(128.)), )); // Spawning the quad with vertex colors and a texture results in tinting commands.spawn(( Mesh2d(mesh_handle), MeshMaterial2d(materials.add(texture_handle)), Transform::from_translation(Vec3::new(96., 0., 0.)).with_scale(Vec3::splat(128.)), )); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/2d/mesh2d_manual.rs
examples/2d/mesh2d_manual.rs
//! This example shows how to manually render 2d items using "mid level render apis" with a custom //! pipeline for 2d meshes. //! It doesn't use the [`Material2d`] abstraction, but changes the vertex buffer to include vertex color. //! Check out the "mesh2d" example for simpler / higher level 2d meshes. //! //! [`Material2d`]: bevy::sprite::Material2d use bevy::{ asset::RenderAssetUsages, color::palettes::basic::YELLOW, core_pipeline::core_2d::{Transparent2d, CORE_2D_DEPTH_FORMAT}, math::{ops, FloatOrd}, mesh::{Indices, MeshVertexAttribute, VertexBufferLayout}, prelude::*, render::{ mesh::RenderMesh, render_asset::RenderAssets, render_phase::{ AddRenderCommand, DrawFunctions, PhaseItemExtraIndex, SetItemPipeline, ViewSortedRenderPhases, }, render_resource::{ BlendState, ColorTargetState, ColorWrites, CompareFunction, DepthBiasState, DepthStencilState, Face, FragmentState, MultisampleState, PipelineCache, PrimitiveState, PrimitiveTopology, RenderPipelineDescriptor, SpecializedRenderPipeline, SpecializedRenderPipelines, StencilFaceState, StencilState, TextureFormat, VertexFormat, VertexState, VertexStepMode, }, sync_component::SyncComponentPlugin, sync_world::{MainEntityHashMap, RenderEntity}, view::{ExtractedView, RenderVisibleEntities, ViewTarget}, Extract, Render, RenderApp, RenderStartup, RenderSystems, }, sprite_render::{ extract_mesh2d, init_mesh_2d_pipeline, DrawMesh2d, Material2dBindGroupId, Mesh2dPipeline, Mesh2dPipelineKey, Mesh2dTransforms, MeshFlags, RenderMesh2dInstance, SetMesh2dBindGroup, SetMesh2dViewBindGroup, }, }; use std::f32::consts::PI; fn main() { App::new() .add_plugins((DefaultPlugins, ColoredMesh2dPlugin)) .add_systems(Startup, star) .run(); } fn star( mut commands: Commands, // We will add a new Mesh for the star being created mut meshes: ResMut<Assets<Mesh>>, ) { // Let's define the mesh for the object we want to draw: a nice star. // We will specify here what kind of topology is used to define the mesh, // that is, how triangles are built from the vertices. We will use a // triangle list, meaning that each vertex of the triangle has to be // specified. We set `RenderAssetUsages::RENDER_WORLD`, meaning this mesh // will not be accessible in future frames from the `meshes` resource, in // order to save on memory once it has been uploaded to the GPU. let mut star = Mesh::new( PrimitiveTopology::TriangleList, RenderAssetUsages::RENDER_WORLD, ); // Vertices need to have a position attribute. We will use the following // vertices (I hope you can spot the star in the schema). // // 1 // // 10 2 // 9 0 3 // 8 4 // 6 // 7 5 // // These vertices are specified in 3D space. let mut v_pos = vec![[0.0, 0.0, 0.0]]; for i in 0..10 { // The angle between each vertex is 1/10 of a full rotation. let a = i as f32 * PI / 5.0; // The radius of inner vertices (even indices) is 100. For outer vertices (odd indices) it's 200. let r = (1 - i % 2) as f32 * 100.0 + 100.0; // Add the vertex position. v_pos.push([r * ops::sin(a), r * ops::cos(a), 0.0]); } // Set the position attribute star.insert_attribute(Mesh::ATTRIBUTE_POSITION, v_pos); // And a RGB color attribute as well. A built-in `Mesh::ATTRIBUTE_COLOR` exists, but we // use a custom vertex attribute here for demonstration purposes. let mut v_color: Vec<u32> = vec![LinearRgba::BLACK.as_u32()]; v_color.extend_from_slice(&[LinearRgba::from(YELLOW).as_u32(); 10]); star.insert_attribute( MeshVertexAttribute::new("Vertex_Color", 1, VertexFormat::Uint32), v_color, ); // Now, we specify the indices of the vertex that are going to compose the // triangles in our star. Vertices in triangles have to be specified in CCW // winding (that will be the front face, colored). Since we are using // triangle list, we will specify each triangle as 3 vertices // First triangle: 0, 2, 1 // Second triangle: 0, 3, 2 // Third triangle: 0, 4, 3 // etc // Last triangle: 0, 1, 10 let mut indices = vec![0, 1, 10]; for i in 2..=10 { indices.extend_from_slice(&[0, i, i - 1]); } star.insert_indices(Indices::U32(indices)); // We can now spawn the entities for the star and the camera commands.spawn(( // We use a marker component to identify the custom colored meshes ColoredMesh2d, // The `Handle<Mesh>` needs to be wrapped in a `Mesh2d` for 2D rendering Mesh2d(meshes.add(star)), )); commands.spawn(Camera2d); } /// A marker component for colored 2d meshes #[derive(Component, Default)] pub struct ColoredMesh2d; /// Custom pipeline for 2d meshes with vertex colors #[derive(Resource)] pub struct ColoredMesh2dPipeline { /// This pipeline wraps the standard [`Mesh2dPipeline`] mesh2d_pipeline: Mesh2dPipeline, /// The shader asset handle. shader: Handle<Shader>, } fn init_colored_mesh_2d_pipeline( mut commands: Commands, mesh2d_pipeline: Res<Mesh2dPipeline>, colored_mesh2d_shader: Res<ColoredMesh2dShader>, ) { commands.insert_resource(ColoredMesh2dPipeline { mesh2d_pipeline: mesh2d_pipeline.clone(), // Clone the shader from the shader resource we inserted in the plugin. shader: colored_mesh2d_shader.0.clone(), }); } // We implement `SpecializedPipeline` to customize the default rendering from `Mesh2dPipeline` impl SpecializedRenderPipeline for ColoredMesh2dPipeline { type Key = Mesh2dPipelineKey; fn specialize(&self, key: Self::Key) -> RenderPipelineDescriptor { // Customize how to store the meshes' vertex attributes in the vertex buffer // Our meshes only have position and color let formats = vec![ // Position VertexFormat::Float32x3, // Color VertexFormat::Uint32, ]; let vertex_layout = VertexBufferLayout::from_vertex_formats(VertexStepMode::Vertex, formats); let format = match key.contains(Mesh2dPipelineKey::HDR) { true => ViewTarget::TEXTURE_FORMAT_HDR, false => TextureFormat::bevy_default(), }; RenderPipelineDescriptor { vertex: VertexState { // Use our custom shader shader: self.shader.clone(), // Use our custom vertex buffer buffers: vec![vertex_layout], ..default() }, fragment: Some(FragmentState { // Use our custom shader shader: self.shader.clone(), targets: vec![Some(ColorTargetState { format, blend: Some(BlendState::ALPHA_BLENDING), write_mask: ColorWrites::ALL, })], ..default() }), // Use the two standard uniforms for 2d meshes layout: vec![ // Bind group 0 is the view uniform self.mesh2d_pipeline.view_layout.clone(), // Bind group 1 is the mesh uniform self.mesh2d_pipeline.mesh_layout.clone(), ], primitive: PrimitiveState { cull_mode: Some(Face::Back), topology: key.primitive_topology(), ..default() }, depth_stencil: Some(DepthStencilState { format: CORE_2D_DEPTH_FORMAT, depth_write_enabled: false, depth_compare: CompareFunction::GreaterEqual, stencil: StencilState { front: StencilFaceState::IGNORE, back: StencilFaceState::IGNORE, read_mask: 0, write_mask: 0, }, bias: DepthBiasState { constant: 0, slope_scale: 0.0, clamp: 0.0, }, }), multisample: MultisampleState { count: key.msaa_samples(), mask: !0, alpha_to_coverage_enabled: false, }, label: Some("colored_mesh2d_pipeline".into()), ..default() } } } // This specifies how to render a colored 2d mesh type DrawColoredMesh2d = ( // Set the pipeline SetItemPipeline, // Set the view uniform as bind group 0 SetMesh2dViewBindGroup<0>, // Set the mesh uniform as bind group 1 SetMesh2dBindGroup<1>, // Draw the mesh DrawMesh2d, ); // The custom shader can be inline like here, included from another file at build time // using `include_str!()`, or loaded like any other asset with `asset_server.load()`. const COLORED_MESH2D_SHADER: &str = r" // Import the standard 2d mesh uniforms and set their bind groups #import bevy_sprite::mesh2d_functions // The structure of the vertex buffer is as specified in `specialize()` struct Vertex { @builtin(instance_index) instance_index: u32, @location(0) position: vec3<f32>, @location(1) color: u32, }; struct VertexOutput { // The vertex shader must set the on-screen position of the vertex @builtin(position) clip_position: vec4<f32>, // We pass the vertex color to the fragment shader in location 0 @location(0) color: vec4<f32>, }; /// Entry point for the vertex shader @vertex fn vertex(vertex: Vertex) -> VertexOutput { var out: VertexOutput; // Project the world position of the mesh into screen position let model = mesh2d_functions::get_world_from_local(vertex.instance_index); out.clip_position = mesh2d_functions::mesh2d_position_local_to_clip(model, vec4<f32>(vertex.position, 1.0)); // Unpack the `u32` from the vertex buffer into the `vec4<f32>` used by the fragment shader out.color = vec4<f32>((vec4<u32>(vertex.color) >> vec4<u32>(0u, 8u, 16u, 24u)) & vec4<u32>(255u)) / 255.0; return out; } // The input of the fragment shader must correspond to the output of the vertex shader for all `location`s struct FragmentInput { // The color is interpolated between vertices by default @location(0) color: vec4<f32>, }; /// Entry point for the fragment shader @fragment fn fragment(in: FragmentInput) -> @location(0) vec4<f32> { return in.color; } "; /// Plugin that renders [`ColoredMesh2d`]s pub struct ColoredMesh2dPlugin; /// A resource holding the shader asset handle for the pipeline to take. There are many ways to get /// the shader into the pipeline - this is just one option. #[derive(Resource)] struct ColoredMesh2dShader(Handle<Shader>); /// Our custom pipeline needs its own instance storage #[derive(Resource, Deref, DerefMut, Default)] pub struct RenderColoredMesh2dInstances(MainEntityHashMap<RenderMesh2dInstance>); impl Plugin for ColoredMesh2dPlugin { fn build(&self, app: &mut App) { // Load our custom shader let mut shaders = app.world_mut().resource_mut::<Assets<Shader>>(); // Here, we construct and add the shader asset manually. There are many ways to load this // shader, including `embedded_asset`/`load_embedded_asset`. let shader = shaders.add(Shader::from_wgsl(COLORED_MESH2D_SHADER, file!())); app.add_plugins(SyncComponentPlugin::<ColoredMesh2d>::default()); // Register our custom draw function, and add our render systems app.get_sub_app_mut(RenderApp) .unwrap() .insert_resource(ColoredMesh2dShader(shader)) .add_render_command::<Transparent2d, DrawColoredMesh2d>() .init_resource::<SpecializedRenderPipelines<ColoredMesh2dPipeline>>() .init_resource::<RenderColoredMesh2dInstances>() .add_systems( RenderStartup, init_colored_mesh_2d_pipeline.after(init_mesh_2d_pipeline), ) .add_systems( ExtractSchedule, extract_colored_mesh2d.after(extract_mesh2d), ) .add_systems( Render, queue_colored_mesh2d.in_set(RenderSystems::QueueMeshes), ); } } /// Extract the [`ColoredMesh2d`] marker component into the render app pub fn extract_colored_mesh2d( mut commands: Commands, mut previous_len: Local<usize>, // When extracting, you must use `Extract` to mark the `SystemParam`s // which should be taken from the main world. query: Extract< Query< ( Entity, RenderEntity, &ViewVisibility, &GlobalTransform, &Mesh2d, ), With<ColoredMesh2d>, >, >, mut render_mesh_instances: ResMut<RenderColoredMesh2dInstances>, ) { let mut values = Vec::with_capacity(*previous_len); for (entity, render_entity, view_visibility, transform, handle) in &query { if !view_visibility.get() { continue; } let transforms = Mesh2dTransforms { world_from_local: (&transform.affine()).into(), flags: MeshFlags::empty().bits(), }; values.push((render_entity, ColoredMesh2d)); render_mesh_instances.insert( entity.into(), RenderMesh2dInstance { mesh_asset_id: handle.0.id(), transforms, material_bind_group_id: Material2dBindGroupId::default(), automatic_batching: false, tag: 0, }, ); } *previous_len = values.len(); commands.try_insert_batch(values); } /// Queue the 2d meshes marked with [`ColoredMesh2d`] using our custom pipeline and draw function pub fn queue_colored_mesh2d( transparent_draw_functions: Res<DrawFunctions<Transparent2d>>, colored_mesh2d_pipeline: Res<ColoredMesh2dPipeline>, mut pipelines: ResMut<SpecializedRenderPipelines<ColoredMesh2dPipeline>>, pipeline_cache: Res<PipelineCache>, render_meshes: Res<RenderAssets<RenderMesh>>, render_mesh_instances: Res<RenderColoredMesh2dInstances>, mut transparent_render_phases: ResMut<ViewSortedRenderPhases<Transparent2d>>, views: Query<(&RenderVisibleEntities, &ExtractedView, &Msaa)>, ) { if render_mesh_instances.is_empty() { return; } // Iterate each view (a camera is a view) for (visible_entities, view, msaa) in &views { let Some(transparent_phase) = transparent_render_phases.get_mut(&view.retained_view_entity) else { continue; }; let draw_colored_mesh2d = transparent_draw_functions.read().id::<DrawColoredMesh2d>(); let mesh_key = Mesh2dPipelineKey::from_msaa_samples(msaa.samples()) | Mesh2dPipelineKey::from_hdr(view.hdr); // Queue all entities visible to that view for (render_entity, visible_entity) in visible_entities.iter::<Mesh2d>() { if let Some(mesh_instance) = render_mesh_instances.get(visible_entity) { let mesh2d_handle = mesh_instance.mesh_asset_id; let mesh2d_transforms = &mesh_instance.transforms; // Get our specialized pipeline let mut mesh2d_key = mesh_key; let Some(mesh) = render_meshes.get(mesh2d_handle) else { continue; }; mesh2d_key |= Mesh2dPipelineKey::from_primitive_topology(mesh.primitive_topology()); let pipeline_id = pipelines.specialize(&pipeline_cache, &colored_mesh2d_pipeline, mesh2d_key); let mesh_z = mesh2d_transforms.world_from_local.translation.z; transparent_phase.add(Transparent2d { entity: (*render_entity, *visible_entity), draw_function: draw_colored_mesh2d, pipeline: pipeline_id, // The 2d render items are sorted according to their z value before rendering, // in order to get correct transparency sort_key: FloatOrd(mesh_z), // This material is not batched batch_range: 0..1, extra_index: PhaseItemExtraIndex::None, extracted_index: usize::MAX, indexed: mesh.indexed(), }); } } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/audio/soundtrack.rs
examples/audio/soundtrack.rs
//! This example illustrates how to load and play different soundtracks, //! transitioning between them as the game state changes. use bevy::{audio::Volume, prelude::*}; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, (cycle_game_state, fade_in, fade_out)) .add_systems(Update, change_track) .run(); } // This resource simulates game states #[derive(Resource, Default)] enum GameState { #[default] Peaceful, Battle, } // This timer simulates game state changes #[derive(Resource)] struct GameStateTimer(Timer); // This resource will hold the track list for your soundtrack #[derive(Resource)] struct SoundtrackPlayer { track_list: Vec<Handle<AudioSource>>, } impl SoundtrackPlayer { fn new(track_list: Vec<Handle<AudioSource>>) -> Self { Self { track_list } } } // This component will be attached to an entity to fade the audio in #[derive(Component)] struct FadeIn; // This component will be attached to an entity to fade the audio out #[derive(Component)] struct FadeOut; fn setup(asset_server: Res<AssetServer>, mut commands: Commands) { // Instantiate the game state resources commands.insert_resource(GameState::default()); commands.insert_resource(GameStateTimer(Timer::from_seconds( 10.0, TimerMode::Repeating, ))); // Create the track list let track_1 = asset_server.load::<AudioSource>("sounds/Mysterious acoustic guitar.ogg"); let track_2 = asset_server.load::<AudioSource>("sounds/Epic orchestra music.ogg"); let track_list = vec![track_1, track_2]; commands.insert_resource(SoundtrackPlayer::new(track_list)); } // Every time the GameState resource changes, this system is run to trigger the song change. fn change_track( mut commands: Commands, soundtrack_player: Res<SoundtrackPlayer>, soundtrack: Query<Entity, With<AudioSink>>, game_state: Res<GameState>, ) { if game_state.is_changed() { // Fade out all currently running tracks for track in soundtrack.iter() { commands.entity(track).insert(FadeOut); } // Spawn a new `AudioPlayer` with the appropriate soundtrack based on // the game state. // // Volume is set to start at zero and is then increased by the fade_in system. match game_state.as_ref() { GameState::Peaceful => { commands.spawn(( AudioPlayer(soundtrack_player.track_list.first().unwrap().clone()), PlaybackSettings { mode: bevy::audio::PlaybackMode::Loop, volume: Volume::SILENT, ..default() }, FadeIn, )); } GameState::Battle => { commands.spawn(( AudioPlayer(soundtrack_player.track_list.get(1).unwrap().clone()), PlaybackSettings { mode: bevy::audio::PlaybackMode::Loop, volume: Volume::SILENT, ..default() }, FadeIn, )); } } } } // Fade effect duration const FADE_TIME: f32 = 2.0; // Fades in the audio of entities that has the FadeIn component. Removes the FadeIn component once // full volume is reached. fn fade_in( mut commands: Commands, mut audio_sink: Query<(&mut AudioSink, Entity), With<FadeIn>>, time: Res<Time>, ) { for (mut audio, entity) in audio_sink.iter_mut() { let current_volume = audio.volume(); audio.set_volume( current_volume.fade_towards(Volume::Linear(1.0), time.delta_secs() / FADE_TIME), ); if audio.volume().to_linear() >= 1.0 { audio.set_volume(Volume::Linear(1.0)); commands.entity(entity).remove::<FadeIn>(); } } } // Fades out the audio of entities that has the FadeOut component. Despawns the entities once audio // volume reaches zero. fn fade_out( mut commands: Commands, mut audio_sink: Query<(&mut AudioSink, Entity), With<FadeOut>>, time: Res<Time>, ) { for (mut audio, entity) in audio_sink.iter_mut() { let current_volume = audio.volume(); audio.set_volume( current_volume.fade_towards(Volume::Linear(0.0), time.delta_secs() / FADE_TIME), ); if audio.volume().to_linear() <= 0.0 { commands.entity(entity).despawn(); } } } // Every time the timer ends, switches between the "Peaceful" and "Battle" state. fn cycle_game_state( mut timer: ResMut<GameStateTimer>, mut game_state: ResMut<GameState>, time: Res<Time>, ) { timer.0.tick(time.delta()); if timer.0.just_finished() { match game_state.as_ref() { GameState::Battle => *game_state = GameState::Peaceful, GameState::Peaceful => *game_state = GameState::Battle, } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/audio/pitch.rs
examples/audio/pitch.rs
//! This example illustrates how to play a single-frequency sound (aka a pitch) use bevy::prelude::*; use std::time::Duration; fn main() { App::new() .add_plugins(DefaultPlugins) .add_message::<PlayPitch>() .add_systems(Startup, setup) .add_systems(Update, (play_pitch, keyboard_input_system)) .run(); } #[derive(Message, Default)] struct PlayPitch; #[derive(Resource)] struct PitchFrequency(f32); fn setup(mut commands: Commands) { commands.insert_resource(PitchFrequency(220.0)); } fn play_pitch( mut pitch_assets: ResMut<Assets<Pitch>>, frequency: Res<PitchFrequency>, mut play_pitch_reader: MessageReader<PlayPitch>, mut commands: Commands, ) { for _ in play_pitch_reader.read() { info!("playing pitch with frequency: {}", frequency.0); commands.spawn(( AudioPlayer(pitch_assets.add(Pitch::new(frequency.0, Duration::new(1, 0)))), PlaybackSettings::DESPAWN, )); info!("number of pitch assets: {}", pitch_assets.len()); } } fn keyboard_input_system( keyboard_input: Res<ButtonInput<KeyCode>>, mut frequency: ResMut<PitchFrequency>, mut play_pitch_writer: MessageWriter<PlayPitch>, ) { if keyboard_input.just_pressed(KeyCode::ArrowUp) { frequency.0 *= ops::powf(2.0f32, 1.0 / 12.0); } if keyboard_input.just_pressed(KeyCode::ArrowDown) { frequency.0 /= ops::powf(2.0f32, 1.0 / 12.0); } if keyboard_input.just_pressed(KeyCode::Space) { play_pitch_writer.write(PlayPitch); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/audio/spatial_audio_2d.rs
examples/audio/spatial_audio_2d.rs
//! This example illustrates how to load and play an audio file, and control where the sounds seems to come from. use bevy::{ audio::{AudioPlugin, SpatialScale}, color::palettes::css::*, prelude::*, time::Stopwatch, }; /// Spatial audio uses the distance to attenuate the sound volume. In 2D with the default camera, /// 1 pixel is 1 unit of distance, so we use a scale so that 100 pixels is 1 unit of distance for /// audio. const AUDIO_SCALE: f32 = 1. / 100.0; fn main() { App::new() .add_plugins(DefaultPlugins.set(AudioPlugin { default_spatial_scale: SpatialScale::new_2d(AUDIO_SCALE), ..default() })) .add_systems(Startup, setup) .add_systems(Update, update_emitters) .add_systems(Update, update_listener) .run(); } fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<ColorMaterial>>, asset_server: Res<AssetServer>, ) { // Space between the two ears let gap = 400.0; // sound emitter commands.spawn(( Mesh2d(meshes.add(Circle::new(15.0))), MeshMaterial2d(materials.add(Color::from(BLUE))), Transform::from_translation(Vec3::new(0.0, 50.0, 0.0)), Emitter::default(), AudioPlayer::new(asset_server.load("sounds/Windless Slopes.ogg")), PlaybackSettings::LOOP.with_spatial(true), )); let listener = SpatialListener::new(gap); commands.spawn(( Transform::default(), Visibility::default(), listener.clone(), children![ // left ear ( Sprite::from_color(RED, Vec2::splat(20.0)), Transform::from_xyz(-gap / 2.0, 0.0, 0.0), ), // right ear ( Sprite::from_color(LIME, Vec2::splat(20.0)), Transform::from_xyz(gap / 2.0, 0.0, 0.0), ) ], )); // example instructions commands.spawn(( Text::new("Up/Down/Left/Right: Move Listener\nSpace: Toggle Emitter Movement"), Node { position_type: PositionType::Absolute, bottom: px(12), left: px(12), ..default() }, )); // camera commands.spawn(Camera2d); } #[derive(Component, Default)] struct Emitter { stopwatch: Stopwatch, } fn update_emitters( time: Res<Time>, mut emitters: Query<(&mut Transform, &mut Emitter), With<Emitter>>, keyboard: Res<ButtonInput<KeyCode>>, ) { for (mut emitter_transform, mut emitter) in emitters.iter_mut() { if keyboard.just_pressed(KeyCode::Space) { if emitter.stopwatch.is_paused() { emitter.stopwatch.unpause(); } else { emitter.stopwatch.pause(); } } emitter.stopwatch.tick(time.delta()); if !emitter.stopwatch.is_paused() { emitter_transform.translation.x = ops::sin(emitter.stopwatch.elapsed_secs()) * 500.0; } } } fn update_listener( keyboard: Res<ButtonInput<KeyCode>>, time: Res<Time>, mut listener: Single<&mut Transform, With<SpatialListener>>, ) { let speed = 200.; if keyboard.pressed(KeyCode::ArrowRight) { listener.translation.x += speed * time.delta_secs(); } if keyboard.pressed(KeyCode::ArrowLeft) { listener.translation.x -= speed * time.delta_secs(); } if keyboard.pressed(KeyCode::ArrowUp) { listener.translation.y += speed * time.delta_secs(); } if keyboard.pressed(KeyCode::ArrowDown) { listener.translation.y -= speed * time.delta_secs(); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/audio/decodable.rs
examples/audio/decodable.rs
//! Shows how to create a custom [`Decodable`] type by implementing a Sine wave. use bevy::{ audio::{AddAudioSource, AudioPlugin, Source, Volume}, math::ops, prelude::*, reflect::TypePath, }; use core::time::Duration; // This struct usually contains the data for the audio being played. // This is where data read from an audio file would be stored, for example. // This allows the type to be registered as an asset. #[derive(Asset, TypePath)] struct SineAudio { frequency: f32, } // This decoder is responsible for playing the audio, // and so stores data about the audio being played. struct SineDecoder { // how far along one period the wave is (between 0 and 1) current_progress: f32, // how much we move along the period every frame progress_per_frame: f32, // how long a period is period: f32, sample_rate: u32, } impl SineDecoder { fn new(frequency: f32) -> Self { // standard sample rate for most recordings let sample_rate = 44_100; SineDecoder { current_progress: 0., progress_per_frame: frequency / sample_rate as f32, period: std::f32::consts::PI * 2., sample_rate, } } } // The decoder must implement iterator so that it can implement `Decodable`. impl Iterator for SineDecoder { type Item = f32; fn next(&mut self) -> Option<Self::Item> { self.current_progress += self.progress_per_frame; // we loop back round to 0 to avoid floating point inaccuracies self.current_progress %= 1.; Some(ops::sin(self.period * self.current_progress)) } } // `Source` is what allows the audio source to be played by bevy. // This trait provides information on the audio. impl Source for SineDecoder { fn current_frame_len(&self) -> Option<usize> { None } fn channels(&self) -> u16 { 1 } fn sample_rate(&self) -> u32 { self.sample_rate } fn total_duration(&self) -> Option<Duration> { None } } // Finally `Decodable` can be implemented for our `SineAudio`. impl Decodable for SineAudio { type DecoderItem = <SineDecoder as Iterator>::Item; type Decoder = SineDecoder; fn decoder(&self) -> Self::Decoder { SineDecoder::new(self.frequency) } } fn main() { let mut app = App::new(); // register the audio source so that it can be used app.add_plugins(DefaultPlugins.set(AudioPlugin { global_volume: Volume::Linear(0.2).into(), ..default() })) .add_audio_source::<SineAudio>() .add_systems(Startup, setup) .run(); } fn setup(mut assets: ResMut<Assets<SineAudio>>, mut commands: Commands) { // add a `SineAudio` to the asset server so that it can be played let audio_handle = assets.add(SineAudio { frequency: 440., // this is the frequency of A4 }); commands.spawn(AudioPlayer(audio_handle)); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/audio/audio_control.rs
examples/audio/audio_control.rs
//! This example illustrates how to load and play an audio file, and control how it's played. use bevy::{math::ops, prelude::*}; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems( Update, (update_progress_text, update_speed, pause, mute, volume), ) .run(); } fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn(( AudioPlayer::new(asset_server.load("sounds/Windless Slopes.ogg")), MyMusic, )); commands.spawn(( Text::new(""), Node { position_type: PositionType::Absolute, top: px(12), left: px(12), ..default() }, ProgressText, )); // example instructions commands.spawn(( Text::new("-/=: Volume Down/Up\nSpace: Toggle Playback\nM: Toggle Mute"), Node { position_type: PositionType::Absolute, bottom: px(12), left: px(12), ..default() }, )); // camera commands.spawn(Camera3d::default()); } #[derive(Component)] struct MyMusic; #[derive(Component)] struct ProgressText; fn update_progress_text( music_controller: Single<&AudioSink, With<MyMusic>>, mut progress_text: Single<&mut Text, With<ProgressText>>, ) { progress_text.0 = format!("Progress: {}s", music_controller.position().as_secs_f32()); } fn update_speed(music_controller: Query<&AudioSink, With<MyMusic>>, time: Res<Time>) { let Ok(sink) = music_controller.single() else { return; }; if sink.is_paused() { return; } sink.set_speed((ops::sin(time.elapsed_secs() / 5.0) + 1.0).max(0.1)); } fn pause( keyboard_input: Res<ButtonInput<KeyCode>>, music_controller: Query<&AudioSink, With<MyMusic>>, ) { let Ok(sink) = music_controller.single() else { return; }; if keyboard_input.just_pressed(KeyCode::Space) { sink.toggle_playback(); } } fn mute( keyboard_input: Res<ButtonInput<KeyCode>>, mut music_controller: Query<&mut AudioSink, With<MyMusic>>, ) { let Ok(mut sink) = music_controller.single_mut() else { return; }; if keyboard_input.just_pressed(KeyCode::KeyM) { sink.toggle_mute(); } } fn volume( keyboard_input: Res<ButtonInput<KeyCode>>, mut music_controller: Query<&mut AudioSink, With<MyMusic>>, ) { let Ok(mut sink) = music_controller.single_mut() else { return; }; if keyboard_input.just_pressed(KeyCode::Equal) { let current_volume = sink.volume(); sink.set_volume(current_volume.increase_by_percentage(10.0)); } else if keyboard_input.just_pressed(KeyCode::Minus) { let current_volume = sink.volume(); sink.set_volume(current_volume.increase_by_percentage(-10.0)); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/audio/spatial_audio_3d.rs
examples/audio/spatial_audio_3d.rs
//! This example illustrates how to load and play an audio file, and control where the sounds seems to come from. use bevy::{ color::palettes::basic::{BLUE, LIME, RED}, prelude::*, time::Stopwatch, }; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, update_positions) .add_systems(Update, update_listener) .add_systems(Update, mute) .run(); } fn setup( mut commands: Commands, asset_server: Res<AssetServer>, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { // Space between the two ears let gap = 4.0; // sound emitter commands.spawn(( Mesh3d(meshes.add(Sphere::new(0.2).mesh().uv(32, 18))), MeshMaterial3d(materials.add(Color::from(BLUE))), Transform::from_xyz(0.0, 0.0, 0.0), Emitter::default(), AudioPlayer::new(asset_server.load("sounds/Windless Slopes.ogg")), PlaybackSettings::LOOP.with_spatial(true), )); let listener = SpatialListener::new(gap); commands.spawn(( Transform::default(), Visibility::default(), listener.clone(), children![ // left ear indicator ( Mesh3d(meshes.add(Cuboid::new(0.2, 0.2, 0.2))), MeshMaterial3d(materials.add(Color::from(RED))), Transform::from_translation(listener.left_ear_offset), ), // right ear indicator ( Mesh3d(meshes.add(Cuboid::new(0.2, 0.2, 0.2))), MeshMaterial3d(materials.add(Color::from(LIME))), Transform::from_translation(listener.right_ear_offset), ) ], )); // light commands.spawn(( DirectionalLight::default(), Transform::from_xyz(4.0, 8.0, 4.0).looking_at(Vec3::ZERO, Vec3::Y), )); // example instructions commands.spawn(( Text::new( "Up/Down/Left/Right: Move Listener\nSpace: Toggle Emitter Movement\nM: Toggle Mute", ), Node { position_type: PositionType::Absolute, bottom: px(12), left: px(12), ..default() }, )); // camera commands.spawn(( Camera3d::default(), Transform::from_xyz(0.0, 5.0, 5.0).looking_at(Vec3::ZERO, Vec3::Y), )); } #[derive(Component, Default)] struct Emitter { stopwatch: Stopwatch, } fn update_positions( time: Res<Time>, mut emitters: Query<(&mut Transform, &mut Emitter), With<Emitter>>, keyboard: Res<ButtonInput<KeyCode>>, ) { for (mut emitter_transform, mut emitter) in emitters.iter_mut() { if keyboard.just_pressed(KeyCode::Space) { if emitter.stopwatch.is_paused() { emitter.stopwatch.unpause(); } else { emitter.stopwatch.pause(); } } emitter.stopwatch.tick(time.delta()); if !emitter.stopwatch.is_paused() { emitter_transform.translation.x = ops::sin(emitter.stopwatch.elapsed_secs()) * 3.0; emitter_transform.translation.z = ops::cos(emitter.stopwatch.elapsed_secs()) * 3.0; } } } fn update_listener( keyboard: Res<ButtonInput<KeyCode>>, time: Res<Time>, mut listeners: Single<&mut Transform, With<SpatialListener>>, ) { let speed = 2.; if keyboard.pressed(KeyCode::ArrowRight) { listeners.translation.x += speed * time.delta_secs(); } if keyboard.pressed(KeyCode::ArrowLeft) { listeners.translation.x -= speed * time.delta_secs(); } if keyboard.pressed(KeyCode::ArrowDown) { listeners.translation.z += speed * time.delta_secs(); } if keyboard.pressed(KeyCode::ArrowUp) { listeners.translation.z -= speed * time.delta_secs(); } } fn mute(keyboard_input: Res<ButtonInput<KeyCode>>, mut sinks: Query<&mut SpatialAudioSink>) { if keyboard_input.just_pressed(KeyCode::KeyM) { for mut sink in sinks.iter_mut() { sink.toggle_mute(); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/audio/audio.rs
examples/audio/audio.rs
//! This example illustrates how to load and play an audio file. //! For loading additional audio formats, you can enable the corresponding feature for that audio format. use bevy::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .run(); } fn setup(asset_server: Res<AssetServer>, mut commands: Commands) { commands.spawn(AudioPlayer::new( asset_server.load("sounds/Windless Slopes.ogg"), )); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/input/keyboard_input_events.rs
examples/input/keyboard_input_events.rs
//! Prints out all keyboard events. use bevy::{input::keyboard::KeyboardInput, prelude::*}; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Update, print_keyboard_event_system) .run(); } /// This system prints out all keyboard inputs as they come in fn print_keyboard_event_system(mut keyboard_inputs: MessageReader<KeyboardInput>) { for keyboard_input in keyboard_inputs.read() { info!("{:?}", keyboard_input); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/input/gamepad_input.rs
examples/input/gamepad_input.rs
//! Shows handling of gamepad input, connections, and disconnections. use bevy::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Update, gamepad_system) .run(); } fn gamepad_system(gamepads: Query<(Entity, &Gamepad)>) { for (entity, gamepad) in &gamepads { if gamepad.just_pressed(GamepadButton::South) { info!("{} just pressed South", entity); } else if gamepad.just_released(GamepadButton::South) { info!("{} just released South", entity); } let right_trigger = gamepad.get(GamepadButton::RightTrigger2).unwrap(); if right_trigger.abs() > 0.01 { info!("{} RightTrigger2 value is {}", entity, right_trigger); } let left_stick_x = gamepad.get(GamepadAxis::LeftStickX).unwrap(); if left_stick_x.abs() > 0.01 { info!("{} LeftStickX value is {}", entity, left_stick_x); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/input/gamepad_rumble.rs
examples/input/gamepad_rumble.rs
//! Shows how to trigger force-feedback, making gamepads rumble when buttons are //! pressed. use bevy::{ input::gamepad::{Gamepad, GamepadRumbleIntensity, GamepadRumbleRequest}, prelude::*, }; use core::time::Duration; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Update, gamepad_system) .run(); } fn gamepad_system( gamepads: Query<(Entity, &Gamepad)>, mut rumble_requests: MessageWriter<GamepadRumbleRequest>, ) { for (entity, gamepad) in &gamepads { if gamepad.just_pressed(GamepadButton::North) { info!( "North face button: strong (low-frequency) with low intensity for rumble for 5 seconds. Press multiple times to increase intensity." ); rumble_requests.write(GamepadRumbleRequest::Add { gamepad: entity, intensity: GamepadRumbleIntensity::strong_motor(0.1), duration: Duration::from_secs(5), }); } if gamepad.just_pressed(GamepadButton::East) { info!("East face button: maximum rumble on both motors for 5 seconds"); rumble_requests.write(GamepadRumbleRequest::Add { gamepad: entity, duration: Duration::from_secs(5), intensity: GamepadRumbleIntensity::MAX, }); } if gamepad.just_pressed(GamepadButton::South) { info!("South face button: low-intensity rumble on the weak motor for 0.5 seconds"); rumble_requests.write(GamepadRumbleRequest::Add { gamepad: entity, duration: Duration::from_secs_f32(0.5), intensity: GamepadRumbleIntensity::weak_motor(0.25), }); } if gamepad.just_pressed(GamepadButton::West) { info!("West face button: custom rumble intensity for 5 second"); rumble_requests.write(GamepadRumbleRequest::Add { gamepad: entity, intensity: GamepadRumbleIntensity { // intensity low-frequency motor, usually on the left-hand side strong_motor: 0.5, // intensity of high-frequency motor, usually on the right-hand side weak_motor: 0.25, }, duration: Duration::from_secs(5), }); } if gamepad.just_pressed(GamepadButton::Start) { info!("Start button: Interrupt the current rumble"); rumble_requests.write(GamepadRumbleRequest::Stop { gamepad: entity }); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/input/mouse_input.rs
examples/input/mouse_input.rs
//! Prints mouse button events. use bevy::{ input::mouse::{AccumulatedMouseMotion, AccumulatedMouseScroll}, prelude::*, }; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Update, (mouse_click_system, mouse_move_system)) .run(); } // This system prints messages when you press or release the left mouse button: fn mouse_click_system(mouse_button_input: Res<ButtonInput<MouseButton>>) { if mouse_button_input.pressed(MouseButton::Left) { info!("left mouse currently pressed"); } if mouse_button_input.just_pressed(MouseButton::Left) { info!("left mouse just pressed"); } if mouse_button_input.just_released(MouseButton::Left) { info!("left mouse just released"); } } // This system prints messages when you finish dragging or scrolling with your mouse fn mouse_move_system( accumulated_mouse_motion: Res<AccumulatedMouseMotion>, accumulated_mouse_scroll: Res<AccumulatedMouseScroll>, ) { if accumulated_mouse_motion.delta != Vec2::ZERO { let delta = accumulated_mouse_motion.delta; info!("mouse moved ({}, {})", delta.x, delta.y); } if accumulated_mouse_scroll.delta != Vec2::ZERO { let delta = accumulated_mouse_scroll.delta; info!("mouse scrolled ({}, {})", delta.x, delta.y); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/input/keyboard_modifiers.rs
examples/input/keyboard_modifiers.rs
//! Demonstrates using key modifiers (ctrl, shift). use bevy::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Update, keyboard_input_system) .run(); } /// This system prints when `Ctrl + Shift + A` is pressed fn keyboard_input_system(input: Res<ButtonInput<KeyCode>>) { let shift = input.any_pressed([KeyCode::ShiftLeft, KeyCode::ShiftRight]); let ctrl = input.any_pressed([KeyCode::ControlLeft, KeyCode::ControlRight]); if ctrl && shift && input.just_pressed(KeyCode::KeyA) { info!("Just pressed Ctrl + Shift + A!"); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/input/gamepad_input_events.rs
examples/input/gamepad_input_events.rs
//! Iterates and prints gamepad input and connection events. use bevy::{ input::gamepad::{ GamepadAxisChangedEvent, GamepadButtonChangedEvent, GamepadButtonStateChangedEvent, GamepadConnectionEvent, GamepadEvent, }, prelude::*, }; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Update, (gamepad_events, gamepad_ordered_events)) .run(); } fn gamepad_events( mut connection_events: MessageReader<GamepadConnectionEvent>, // Handles the continuous measure of an axis, equivalent to GamepadAxes::get. mut axis_changed_events: MessageReader<GamepadAxisChangedEvent>, // Handles the continuous measure of how far a button has been pressed down, equivalent to `GamepadButtons::get`. mut button_changed_events: MessageReader<GamepadButtonChangedEvent>, // Handles the boolean measure of whether a button is considered pressed or unpressed, as // defined by the thresholds in `GamepadSettings::button_settings`. // When the threshold is crossed and the button state changes, this event is emitted. mut button_input_events: MessageReader<GamepadButtonStateChangedEvent>, ) { for connection_event in connection_events.read() { info!("{:?}", connection_event); } for axis_changed_event in axis_changed_events.read() { info!( "{:?} of {} is changed to {}", axis_changed_event.axis, axis_changed_event.entity, axis_changed_event.value ); } for button_changed_event in button_changed_events.read() { info!( "{:?} of {} is changed to {}", button_changed_event.button, button_changed_event.entity, button_changed_event.value ); } for button_input_event in button_input_events.read() { info!("{:?}", button_input_event); } } // If you require in-frame relative event ordering, you can also read the `Gamepad` event // stream directly. For standard use-cases, reading the events individually or using the // `Input<T>` or `Axis<T>` resources is preferable. fn gamepad_ordered_events(mut gamepad_events: MessageReader<GamepadEvent>) { for gamepad_event in gamepad_events.read() { match gamepad_event { GamepadEvent::Connection(connection_event) => info!("{:?}", connection_event), GamepadEvent::Button(button_event) => info!("{:?}", button_event), GamepadEvent::Axis(axis_event) => info!("{:?}", axis_event), } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/input/text_input.rs
examples/input/text_input.rs
//! Simple text input support //! //! Return creates a new line, backspace removes the last character. //! Clicking toggle IME (Input Method Editor) support, but the font used as limited support of characters. //! You should change the provided font with another one to test other languages input. use std::mem; use bevy::{ input::keyboard::{Key, KeyboardInput}, prelude::*, }; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup_scene) .add_systems( Update, ( toggle_ime, listen_ime_events, listen_keyboard_input_events, bubbling_text, ), ) .run(); } fn setup_scene(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn(Camera2d); // The default font has a limited number of glyphs, so use the full version for // sections that will hold text input. let font = asset_server.load("fonts/FiraMono-Medium.ttf"); commands.spawn(( Text::default(), Node { position_type: PositionType::Absolute, top: px(12), left: px(12), ..default() }, children![ TextSpan::new("Click to toggle IME. Press return to start a new line.\n\n",), TextSpan::new("IME Enabled: "), TextSpan::new("false\n"), TextSpan::new("IME Active: "), TextSpan::new("false\n"), TextSpan::new("IME Buffer: "), (TextSpan::new("\n"), TextFont::from(font.clone()),), ], )); commands.spawn(( Text2d::new(""), TextFont { font: font.clone().into(), font_size: 100.0, ..default() }, )); } fn toggle_ime( input: Res<ButtonInput<MouseButton>>, mut window: Single<&mut Window>, status_text: Single<Entity, (With<Node>, With<Text>)>, mut ui_writer: TextUiWriter, ) { if input.just_pressed(MouseButton::Left) { window.ime_position = window.cursor_position().unwrap(); window.ime_enabled = !window.ime_enabled; *ui_writer.text(*status_text, 3) = format!("{}\n", window.ime_enabled); } } #[derive(Component)] struct Bubble { timer: Timer, } fn bubbling_text( mut commands: Commands, mut bubbles: Query<(Entity, &mut Transform, &mut Bubble)>, time: Res<Time>, ) { for (entity, mut transform, mut bubble) in bubbles.iter_mut() { if bubble.timer.tick(time.delta()).just_finished() { commands.entity(entity).despawn(); } transform.translation.y += time.delta_secs() * 100.0; } } fn listen_ime_events( mut ime_reader: MessageReader<Ime>, status_text: Single<Entity, (With<Node>, With<Text>)>, mut edit_text: Single<&mut Text2d, (Without<Node>, Without<Bubble>)>, mut ui_writer: TextUiWriter, ) { for ime in ime_reader.read() { match ime { Ime::Preedit { value, cursor, .. } if !cursor.is_none() => { *ui_writer.text(*status_text, 7) = format!("{value}\n"); } Ime::Preedit { cursor, .. } if cursor.is_none() => { *ui_writer.text(*status_text, 7) = "\n".to_string(); } Ime::Commit { value, .. } => { edit_text.push_str(value); } Ime::Enabled { .. } => { *ui_writer.text(*status_text, 5) = "true\n".to_string(); } Ime::Disabled { .. } => { *ui_writer.text(*status_text, 5) = "false\n".to_string(); } _ => (), } } } fn listen_keyboard_input_events( mut commands: Commands, mut keyboard_input_reader: MessageReader<KeyboardInput>, edit_text: Single<(&mut Text2d, &TextFont), (Without<Node>, Without<Bubble>)>, ) { let (mut text, style) = edit_text.into_inner(); for keyboard_input in keyboard_input_reader.read() { // Only trigger changes when the key is first pressed. if !keyboard_input.state.is_pressed() { continue; } match (&keyboard_input.logical_key, &keyboard_input.text) { (Key::Enter, _) => { if text.is_empty() { continue; } let old_value = mem::take(&mut **text); commands.spawn(( Text2d::new(old_value), style.clone(), Bubble { timer: Timer::from_seconds(5.0, TimerMode::Once), }, )); } (Key::Backspace, _) => { text.pop(); } (_, Some(inserted_text)) => { // Make sure the text doesn't have any control characters, // which can happen when keys like Escape are pressed if inserted_text.chars().all(is_printable_char) { text.push_str(inserted_text); } } _ => continue, } } } // this logic is taken from egui-winit: // https://github.com/emilk/egui/blob/adfc0bebfc6be14cee2068dee758412a5e0648dc/crates/egui-winit/src/lib.rs#L1014-L1024 fn is_printable_char(chr: char) -> bool { let is_in_private_use_area = ('\u{e000}'..='\u{f8ff}').contains(&chr) || ('\u{f0000}'..='\u{ffffd}').contains(&chr) || ('\u{100000}'..='\u{10fffd}').contains(&chr); !is_in_private_use_area && !chr.is_ascii_control() }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/input/touch_input.rs
examples/input/touch_input.rs
//! Displays touch presses, releases, and cancels. use bevy::{input::touch::*, prelude::*}; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Update, touch_system) .run(); } fn touch_system(touches: Res<Touches>) { for touch in touches.iter_just_pressed() { info!( "just pressed touch with id: {}, at: {}", touch.id(), touch.position() ); } for touch in touches.iter_just_released() { info!( "just released touch with id: {}, at: {}", touch.id(), touch.position() ); } for touch in touches.iter_just_canceled() { info!("canceled touch with id: {}", touch.id()); } // you can also iterate all current touches and retrieve their state like this: for touch in touches.iter() { info!("active touch: {touch:?}"); info!(" just_pressed: {}", touches.just_pressed(touch.id())); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/input/char_input_events.rs
examples/input/char_input_events.rs
//! Prints out all chars as they are inputted. use bevy::{ input::keyboard::{Key, KeyboardInput}, prelude::*, }; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Update, print_char_event_system) .run(); } /// This system prints out all char events as they come in. fn print_char_event_system(mut keyboard_inputs: MessageReader<KeyboardInput>) { for event in keyboard_inputs.read() { // Only check for characters when the key is pressed. if !event.state.is_pressed() { continue; } if let Key::Character(character) = &event.logical_key { info!("{:?}: '{}'", event, character); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/input/touch_input_events.rs
examples/input/touch_input_events.rs
//! Prints out all touch inputs. use bevy::{input::touch::*, prelude::*}; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Update, touch_event_system) .run(); } fn touch_event_system(mut touch_inputs: MessageReader<TouchInput>) { for touch_input in touch_inputs.read() { info!("{:?}", touch_input); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/input/keyboard_input.rs
examples/input/keyboard_input.rs
//! Demonstrates handling a key press/release. use bevy::{input::keyboard::Key, prelude::*}; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Update, keyboard_input_system) .run(); } /// This system responds to certain key presses fn keyboard_input_system( keyboard_input: Res<ButtonInput<KeyCode>>, key_input: Res<ButtonInput<Key>>, ) { // KeyCode is used when you want the key location across different keyboard layouts // See https://w3c.github.io/uievents-code/#code-value-tables for the locations if keyboard_input.pressed(KeyCode::KeyA) { info!("'A' currently pressed"); } if keyboard_input.just_pressed(KeyCode::KeyA) { info!("'A' just pressed"); } if keyboard_input.just_released(KeyCode::KeyA) { info!("'A' just released"); } // Key is used when you want a specific key, no matter where it is located. // This is useful for symbols that have a specific connotation, e.g. '?' for // a help menu or '+'/'-' for zoom let key = Key::Character("?".into()); if key_input.pressed(key.clone()) { info!("'?' currently pressed"); } if key_input.just_pressed(key.clone()) { info!("'?' just pressed"); } if key_input.just_released(key) { info!("'?' just released"); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/input/mouse_input_events.rs
examples/input/mouse_input_events.rs
//! Prints all mouse events to the console. use bevy::{ input::{ gestures::*, mouse::{MouseButtonInput, MouseMotion, MouseWheel}, }, prelude::*, }; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Update, print_mouse_events_system) .run(); } /// This system prints out all mouse events as they come in fn print_mouse_events_system( mut mouse_button_input_reader: MessageReader<MouseButtonInput>, mut mouse_motion_reader: MessageReader<MouseMotion>, mut cursor_moved_reader: MessageReader<CursorMoved>, mut mouse_wheel_reader: MessageReader<MouseWheel>, mut pinch_gesture_reader: MessageReader<PinchGesture>, mut rotation_gesture_reader: MessageReader<RotationGesture>, mut double_tap_gesture_reader: MessageReader<DoubleTapGesture>, ) { for mouse_button_input in mouse_button_input_reader.read() { info!("{:?}", mouse_button_input); } for mouse_motion in mouse_motion_reader.read() { info!("{:?}", mouse_motion); } for cursor_moved in cursor_moved_reader.read() { info!("{:?}", cursor_moved); } for mouse_wheel in mouse_wheel_reader.read() { info!("{:?}", mouse_wheel); } // This event will only fire on macOS for pinch_gesture in pinch_gesture_reader.read() { info!("{:?}", pinch_gesture); } // This event will only fire on macOS for rotation_gesture in rotation_gesture_reader.read() { info!("{:?}", rotation_gesture); } // This event will only fire on macOS for double_tap_gesture in double_tap_gesture_reader.read() { info!("{:?}", double_tap_gesture); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/input/mouse_grab.rs
examples/input/mouse_grab.rs
//! Demonstrates how to grab and hide the mouse cursor. use bevy::{ prelude::*, window::{CursorGrabMode, CursorOptions}, }; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Update, grab_mouse) .run(); } // This system grabs the mouse when the left mouse button is pressed // and releases it when the escape key is pressed fn grab_mouse( mut cursor_options: Single<&mut CursorOptions>, mouse: Res<ButtonInput<MouseButton>>, key: Res<ButtonInput<KeyCode>>, ) { if mouse.just_pressed(MouseButton::Left) { cursor_options.visible = false; cursor_options.grab_mode = CursorGrabMode::Locked; } if key.just_pressed(KeyCode::Escape) { cursor_options.visible = true; cursor_options.grab_mode = CursorGrabMode::None; } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/testbed/helpers.rs
examples/testbed/helpers.rs
#[cfg(feature = "bevy_ci_testing")] use bevy::{ dev_tools::ci_testing::{CiTestingConfig, CiTestingEvent, CiTestingEventOnFrame}, diagnostic::FrameCount, platform::collections::HashSet, prelude::*, render::view::screenshot::Captured, state::state::FreelyMutableState, }; #[cfg(feature = "bevy_ci_testing")] pub fn switch_scene_in_ci<Scene: States + FreelyMutableState + Next>( mut ci_config: ResMut<CiTestingConfig>, scene: Res<State<Scene>>, mut next_scene: ResMut<NextState<Scene>>, mut scenes_visited: Local<HashSet<Scene>>, frame_count: Res<FrameCount>, captured: RemovedComponents<Captured>, ) { if scene.is_changed() { // Changed scene! trigger a screenshot in 100 frames ci_config.events.push(CiTestingEventOnFrame( frame_count.0 + 100, CiTestingEvent::NamedScreenshot(format!("{:?}", scene.get())), )); if scenes_visited.contains(scene.get()) { // Exit once all scenes have been screenshotted ci_config.events.push(CiTestingEventOnFrame( frame_count.0 + 1, CiTestingEvent::AppExit, )); } return; } if !captured.is_empty() { // Screenshot taken! Switch to the next scene scenes_visited.insert(scene.get().clone()); next_scene.set(scene.get().next()); } } pub trait Next { fn next(&self) -> Self; }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/testbed/full_ui.rs
examples/testbed/full_ui.rs
//! This example illustrates the various features of Bevy UI. use std::f32::consts::PI; use accesskit::{Node as Accessible, Role}; use bevy::{ a11y::AccessibilityNode, color::palettes::{ basic::LIME, css::{DARK_GRAY, NAVY}, }, input::mouse::{MouseScrollUnit, MouseWheel}, picking::hover::HoverMap, prelude::*, ui::widget::NodeImageMode, ui_widgets::Scrollbar, }; fn main() { let mut app = App::new(); app.add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, update_scroll_position); #[cfg(feature = "bevy_ui_debug")] app.add_systems(Update, toggle_debug_overlay); app.run(); } fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { // Camera commands.spawn((Camera2d, IsDefaultUiCamera, BoxShadowSamples(6))); // root node commands .spawn(Node { width: percent(100), height: percent(100), justify_content: JustifyContent::SpaceBetween, ..default() }) .insert(Pickable::IGNORE) .with_children(|parent| { // left vertical fill (border) parent .spawn(( Node { width: px(200), border: UiRect::all(px(2)), ..default() }, BackgroundColor(Color::srgb(0.65, 0.65, 0.65)), )) .with_children(|parent| { // left vertical fill (content) parent .spawn(( Node { width: percent(100), flex_direction: FlexDirection::Column, padding: UiRect::all(px(5)), row_gap: px(5), ..default() }, BackgroundColor(Color::srgb(0.15, 0.15, 0.15)), Visibility::Visible, )) .with_children(|parent| { // text parent.spawn(( Text::new("Text Example"), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), font_size: 25.0, ..default() }, // Because this is a distinct label widget and // not button/list item text, this is necessary // for accessibility to treat the text accordingly. Label, )); #[cfg(feature = "bevy_ui_debug")] { // Debug overlay text parent.spawn(( Text::new("Press Space to toggle debug outlines."), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), ..default() }, Label, )); parent.spawn(( Text::new("V: toggle UI root's visibility"), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), font_size: 12., ..default() }, Label, )); parent.spawn(( Text::new("S: toggle outlines for hidden nodes"), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), font_size: 12., ..default() }, Label, )); parent.spawn(( Text::new("C: toggle outlines for clipped nodes"), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), font_size: 12., ..default() }, Label, )); } #[cfg(not(feature = "bevy_ui_debug"))] parent.spawn(( Text::new("Try enabling feature \"bevy_ui_debug\"."), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), ..default() }, Label, )); }); }); // right vertical fill parent .spawn(Node { flex_direction: FlexDirection::Column, justify_content: JustifyContent::Center, align_items: AlignItems::Center, width: px(200), ..default() }) .with_children(|parent| { // Title parent.spawn(( Text::new("Scrolling list"), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), font_size: 21., ..default() }, Label, )); // Scrolling list parent .spawn(( Node { flex_direction: FlexDirection::Column, align_self: AlignSelf::Stretch, height: percent(50), overflow: Overflow::scroll_y(), ..default() }, BackgroundColor(Color::srgb(0.10, 0.10, 0.10)), )) .with_children(|parent| { parent .spawn(( Node { flex_direction: FlexDirection::Column, ..Default::default() }, BackgroundGradient::from(LinearGradient::to_bottom(vec![ ColorStop::auto(NAVY), ColorStop::auto(Color::BLACK), ])), Pickable { should_block_lower: false, ..Default::default() }, )) .with_children(|parent| { // List items for i in 0..25 { parent .spawn(( Text(format!("Item {i}")), TextFont { font: asset_server .load("fonts/FiraSans-Bold.ttf") .into(), ..default() }, Label, AccessibilityNode(Accessible::new(Role::ListItem)), )) .insert(Pickable { should_block_lower: false, ..default() }); } }); }); }); parent .spawn(Node { left: px(210), bottom: px(10), position_type: PositionType::Absolute, ..default() }) .with_children(|parent| { parent .spawn(( Node { width: px(200), height: px(200), border: UiRect::all(px(20)), flex_direction: FlexDirection::Column, justify_content: JustifyContent::Center, ..default() }, BorderColor::all(LIME), BackgroundColor(Color::srgb(0.8, 0.8, 1.)), )) .with_children(|parent| { parent.spawn(( ImageNode::new(asset_server.load("branding/bevy_logo_light.png")), // Uses the transform to rotate the logo image by 45 degrees Node { border_radius: BorderRadius::all(px(10)), ..Default::default() }, UiTransform { rotation: Rot2::radians(0.25 * PI), ..Default::default() }, Outline { width: px(2), offset: px(4), color: DARK_GRAY.into(), }, )); }); }); let shadow_style = ShadowStyle { color: Color::BLACK.with_alpha(0.5), blur_radius: px(2), x_offset: px(10), y_offset: px(10), ..default() }; // render order test: reddest in the back, whitest in the front (flex center) parent .spawn(Node { width: percent(100), height: percent(100), position_type: PositionType::Absolute, align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..default() }) .insert(Pickable::IGNORE) .with_children(|parent| { parent .spawn(( Node { width: px(100), height: px(100), ..default() }, BackgroundColor(Color::srgb(1.0, 0.0, 0.)), BoxShadow::from(shadow_style), )) .with_children(|parent| { parent.spawn(( Node { // Take the size of the parent node. width: percent(100), height: percent(100), position_type: PositionType::Absolute, left: px(20), bottom: px(20), ..default() }, BackgroundColor(Color::srgb(1.0, 0.3, 0.3)), BoxShadow::from(shadow_style), )); parent.spawn(( Node { width: percent(100), height: percent(100), position_type: PositionType::Absolute, left: px(40), bottom: px(40), ..default() }, BackgroundColor(Color::srgb(1.0, 0.5, 0.5)), BoxShadow::from(shadow_style), )); parent.spawn(( Node { width: percent(100), height: percent(100), position_type: PositionType::Absolute, left: px(60), bottom: px(60), ..default() }, BackgroundColor(Color::srgb(0.0, 0.7, 0.7)), BoxShadow::from(shadow_style), )); // alpha test parent.spawn(( Node { width: percent(100), height: percent(100), position_type: PositionType::Absolute, left: px(80), bottom: px(80), ..default() }, BackgroundColor(Color::srgba(1.0, 0.9, 0.9, 0.4)), BoxShadow::from(ShadowStyle { color: Color::BLACK.with_alpha(0.3), ..shadow_style }), )); }); }); // bevy logo (flex center) parent .spawn(Node { width: percent(100), position_type: PositionType::Absolute, justify_content: JustifyContent::Center, align_items: AlignItems::FlexStart, ..default() }) .with_children(|parent| { // bevy logo (image) parent .spawn(( ImageNode::new(asset_server.load("branding/bevy_logo_dark_big.png")) .with_mode(NodeImageMode::Stretch), Node { width: px(500), height: px(125), margin: UiRect::top(vmin(5)), ..default() }, )) .with_children(|parent| { // alt text // This UI node takes up no space in the layout and the `Text` component is used by the accessibility module // and is not rendered. parent.spawn(( Node { display: Display::None, ..default() }, Text::new("Bevy logo"), )); }); }); // four bevy icons demonstrating image flipping parent .spawn(Node { width: percent(100), height: percent(100), position_type: PositionType::Absolute, justify_content: JustifyContent::Center, align_items: AlignItems::FlexEnd, column_gap: px(10), padding: UiRect::all(px(10)), ..default() }) .insert(Pickable::IGNORE) .with_children(|parent| { for (flip_x, flip_y) in [(false, false), (false, true), (true, true), (true, false)] { parent.spawn(( ImageNode { image: asset_server.load("branding/icon.png"), flip_x, flip_y, ..default() }, Node { // The height will be chosen automatically to preserve the image's aspect ratio width: px(75), ..default() }, )); } }); }); } #[cfg(feature = "bevy_ui_debug")] // The system that will enable/disable the debug outlines around the nodes fn toggle_debug_overlay( input: Res<ButtonInput<KeyCode>>, mut debug_options: ResMut<UiDebugOptions>, mut root_node_query: Query<&mut Visibility, (With<Node>, Without<ChildOf>)>, ) { info_once!("The debug outlines are enabled, press Space to turn them on/off"); if input.just_pressed(KeyCode::Space) { // The toggle method will enable the debug overlay if disabled and disable if enabled debug_options.toggle(); } if input.just_pressed(KeyCode::KeyS) { // Toggle debug outlines for nodes with `ViewVisibility` set to false. debug_options.show_hidden = !debug_options.show_hidden; } if input.just_pressed(KeyCode::KeyC) { // Toggle outlines for clipped UI nodes. debug_options.show_clipped = !debug_options.show_clipped; } if input.just_pressed(KeyCode::KeyV) { for mut visibility in root_node_query.iter_mut() { // Toggle the UI root node's visibility visibility.toggle_inherited_hidden(); } } } /// Updates the scroll position of scrollable nodes in response to mouse input pub fn update_scroll_position( mut mouse_wheel_reader: MessageReader<MouseWheel>, hover_map: Res<HoverMap>, mut scrolled_node_query: Query<(&mut ScrollPosition, &ComputedNode), Without<Scrollbar>>, keyboard_input: Res<ButtonInput<KeyCode>>, ) { for mouse_wheel in mouse_wheel_reader.read() { let (mut dx, mut dy) = match mouse_wheel.unit { MouseScrollUnit::Line => (mouse_wheel.x * 20., mouse_wheel.y * 20.), MouseScrollUnit::Pixel => (mouse_wheel.x, mouse_wheel.y), }; if keyboard_input.pressed(KeyCode::ShiftLeft) || keyboard_input.pressed(KeyCode::ShiftRight) { std::mem::swap(&mut dx, &mut dy); } for (_pointer, pointer_map) in hover_map.iter() { for (entity, _hit) in pointer_map.iter() { if let Ok((mut scroll_position, scroll_content)) = scrolled_node_query.get_mut(*entity) { let visible_size = scroll_content.size(); let content_size = scroll_content.content_size(); let range = (content_size.y - visible_size.y).max(0.) * scroll_content.inverse_scale_factor; scroll_position.x -= dx; scroll_position.y = (scroll_position.y - dy).clamp(0., range); } } } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/testbed/3d.rs
examples/testbed/3d.rs
//! 3d testbed //! //! You can switch scene by pressing the spacebar mod helpers; use argh::FromArgs; use bevy::prelude::*; use helpers::Next; #[derive(FromArgs)] /// 3d testbed pub struct Args { #[argh(positional)] scene: Option<Scene>, } fn main() { #[cfg(not(target_arch = "wasm32"))] let args: Args = argh::from_env(); #[cfg(target_arch = "wasm32")] let args: Args = Args::from_args(&[], &[]).unwrap(); let mut app = App::new(); app.add_plugins((DefaultPlugins,)) .add_systems(OnEnter(Scene::Light), light::setup) .add_systems(OnEnter(Scene::Bloom), bloom::setup) .add_systems(OnEnter(Scene::Gltf), gltf::setup) .add_systems(OnEnter(Scene::Animation), animation::setup) .add_systems(OnEnter(Scene::Gizmos), gizmos::setup) .add_systems( OnEnter(Scene::GltfCoordinateConversion), gltf_coordinate_conversion::setup, ) .add_systems(Update, switch_scene) .add_systems(Update, gizmos::draw_gizmos.run_if(in_state(Scene::Gizmos))) .add_systems( Update, gltf_coordinate_conversion::draw_gizmos .run_if(in_state(Scene::GltfCoordinateConversion)), ); match args.scene { None => app.init_state::<Scene>(), Some(scene) => app.insert_state(scene), }; #[cfg(feature = "bevy_ci_testing")] app.add_systems(Update, helpers::switch_scene_in_ci::<Scene>); app.run(); } #[derive(Debug, Clone, Eq, PartialEq, Hash, States, Default)] enum Scene { #[default] Light, Bloom, Gltf, Animation, Gizmos, GltfCoordinateConversion, } impl std::str::FromStr for Scene { type Err = String; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { let mut isit = Self::default(); while s.to_lowercase() != format!("{isit:?}").to_lowercase() { isit = isit.next(); if isit == Self::default() { return Err(format!("Invalid Scene name: {s}")); } } Ok(isit) } } impl Next for Scene { fn next(&self) -> Self { match self { Scene::Light => Scene::Bloom, Scene::Bloom => Scene::Gltf, Scene::Gltf => Scene::Animation, Scene::Animation => Scene::Gizmos, Scene::Gizmos => Scene::GltfCoordinateConversion, Scene::GltfCoordinateConversion => Scene::Light, } } } fn switch_scene( keyboard: Res<ButtonInput<KeyCode>>, scene: Res<State<Scene>>, mut next_scene: ResMut<NextState<Scene>>, ) { if keyboard.just_pressed(KeyCode::Space) { info!("Switching scene"); next_scene.set(scene.get().next()); } } mod light { use std::f32::consts::PI; use bevy::{ color::palettes::css::{DEEP_PINK, LIME, RED}, prelude::*, }; const CURRENT_SCENE: super::Scene = super::Scene::Light; pub fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { commands.spawn(( Mesh3d(meshes.add(Plane3d::default().mesh().size(10.0, 10.0))), MeshMaterial3d(materials.add(StandardMaterial { base_color: Color::WHITE, perceptual_roughness: 1.0, ..default() })), DespawnOnExit(CURRENT_SCENE), )); commands.spawn(( Mesh3d(meshes.add(Cuboid::default())), MeshMaterial3d(materials.add(StandardMaterial { base_color: DEEP_PINK.into(), ..default() })), Transform::from_xyz(0.0, 1.0, 0.0), DespawnOnExit(CURRENT_SCENE), )); commands.spawn(( PointLight { intensity: 100_000.0, color: RED.into(), shadows_enabled: true, ..default() }, Transform::from_xyz(1.0, 2.0, 0.0), DespawnOnExit(CURRENT_SCENE), )); commands.spawn(( SpotLight { intensity: 100_000.0, color: LIME.into(), shadows_enabled: true, inner_angle: 0.6, outer_angle: 0.8, ..default() }, Transform::from_xyz(-1.0, 2.0, 0.0).looking_at(Vec3::new(-1.0, 0.0, 0.0), Vec3::Z), DespawnOnExit(CURRENT_SCENE), )); commands.spawn(( DirectionalLight { illuminance: light_consts::lux::OVERCAST_DAY, shadows_enabled: true, ..default() }, Transform { translation: Vec3::new(0.0, 2.0, 0.0), rotation: Quat::from_rotation_x(-PI / 4.), ..default() }, DespawnOnExit(CURRENT_SCENE), )); commands.spawn(( Camera3d::default(), Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y), DespawnOnExit(CURRENT_SCENE), )); } } mod bloom { use bevy::{core_pipeline::tonemapping::Tonemapping, post_process::bloom::Bloom, prelude::*}; const CURRENT_SCENE: super::Scene = super::Scene::Bloom; pub fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { commands.spawn(( Camera3d::default(), Tonemapping::TonyMcMapface, Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y), Bloom::NATURAL, DespawnOnExit(CURRENT_SCENE), )); let material_emissive1 = materials.add(StandardMaterial { emissive: LinearRgba::rgb(13.99, 5.32, 2.0), ..default() }); let material_emissive2 = materials.add(StandardMaterial { emissive: LinearRgba::rgb(2.0, 13.99, 5.32), ..default() }); let mesh = meshes.add(Sphere::new(0.5).mesh().ico(5).unwrap()); for z in -2..3_i32 { let material = match (z % 2).abs() { 0 => material_emissive1.clone(), 1 => material_emissive2.clone(), _ => unreachable!(), }; commands.spawn(( Mesh3d(mesh.clone()), MeshMaterial3d(material), Transform::from_xyz(z as f32 * 2.0, 0.0, 0.0), DespawnOnExit(CURRENT_SCENE), )); } } } mod gltf { use bevy::prelude::*; const CURRENT_SCENE: super::Scene = super::Scene::Gltf; pub fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn(( Camera3d::default(), Transform::from_xyz(0.7, 0.7, 1.0).looking_at(Vec3::new(0.0, 0.3, 0.0), Vec3::Y), EnvironmentMapLight { diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"), specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"), intensity: 250.0, ..default() }, DespawnOnExit(CURRENT_SCENE), )); commands.spawn(( DirectionalLight { shadows_enabled: true, ..default() }, DespawnOnExit(CURRENT_SCENE), )); commands.spawn(( SceneRoot(asset_server.load( GltfAssetLabel::Scene(0).from_asset("models/FlightHelmet/FlightHelmet.gltf"), )), DespawnOnExit(CURRENT_SCENE), )); } } mod animation { use std::{f32::consts::PI, time::Duration}; use bevy::{prelude::*, scene::SceneInstanceReady}; const CURRENT_SCENE: super::Scene = super::Scene::Animation; const FOX_PATH: &str = "models/animated/Fox.glb"; #[derive(Resource)] struct Animation { animation: AnimationNodeIndex, graph: Handle<AnimationGraph>, } pub fn setup( mut commands: Commands, asset_server: Res<AssetServer>, mut graphs: ResMut<Assets<AnimationGraph>>, ) { let (graph, node) = AnimationGraph::from_clip( asset_server.load(GltfAssetLabel::Animation(2).from_asset(FOX_PATH)), ); let graph_handle = graphs.add(graph); commands.insert_resource(Animation { animation: node, graph: graph_handle, }); commands.spawn(( Camera3d::default(), Transform::from_xyz(100.0, 100.0, 150.0).looking_at(Vec3::new(0.0, 20.0, 0.0), Vec3::Y), DespawnOnExit(CURRENT_SCENE), )); commands.spawn(( Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, 1.0, -PI / 4.)), DirectionalLight { shadows_enabled: true, ..default() }, DespawnOnExit(CURRENT_SCENE), )); commands .spawn(( SceneRoot(asset_server.load(GltfAssetLabel::Scene(0).from_asset(FOX_PATH))), DespawnOnExit(CURRENT_SCENE), )) .observe(pause_animation_frame); } fn pause_animation_frame( scene_ready: On<SceneInstanceReady>, children: Query<&Children>, mut commands: Commands, animation: Res<Animation>, mut players: Query<(Entity, &mut AnimationPlayer)>, ) { for child in children.iter_descendants(scene_ready.entity) { if let Ok((entity, mut player)) = players.get_mut(child) { let mut transitions = AnimationTransitions::new(); transitions .play(&mut player, animation.animation, Duration::ZERO) .seek_to(0.5) .pause(); commands .entity(entity) .insert(AnimationGraphHandle(animation.graph.clone())) .insert(transitions); } } } } mod gizmos { use bevy::{color::palettes::css::*, prelude::*}; pub fn setup(mut commands: Commands) { commands.spawn(( Camera3d::default(), Transform::from_xyz(-1.0, 2.5, 6.5).looking_at(Vec3::ZERO, Vec3::Y), DespawnOnExit(super::Scene::Gizmos), )); } pub fn draw_gizmos(mut gizmos: Gizmos) { gizmos.cube( Transform::from_translation(Vec3::X * -1.75).with_scale(Vec3::splat(1.25)), RED, ); gizmos .sphere(Isometry3d::from_translation(Vec3::X * -3.5), 0.75, GREEN) .resolution(30_000 / 3); // 3d grids with all variations of outer edges on or off for i in 0..8 { let x = 1.5 * (i % 4) as f32; let y = 1.0 * (0.5 - (i / 4) as f32); let mut grid = gizmos.grid_3d( Isometry3d::from_translation(Vec3::new(x, y, 0.0)), UVec3::new(5, 4, 3), Vec3::splat(0.175), Color::WHITE, ); if i & 1 > 0 { grid = grid.outer_edges_x(); } if i & 2 > 0 { grid = grid.outer_edges_y(); } if i & 4 > 0 { grid.outer_edges_z(); } } } } mod gltf_coordinate_conversion { use bevy::{ color::palettes::basic::*, gltf::{convert_coordinates::GltfConvertCoordinates, GltfLoaderSettings}, prelude::*, scene::SceneInstanceReady, }; const CURRENT_SCENE: super::Scene = super::Scene::GltfCoordinateConversion; pub fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn(( Camera3d::default(), Transform::from_xyz(-4.0, 4.0, -5.0).looking_at(Vec3::ZERO, Vec3::Y), DespawnOnExit(CURRENT_SCENE), )); commands.spawn(( DirectionalLight { color: BLUE.into(), ..default() }, Transform::IDENTITY.looking_to(Dir3::Z, Dir3::Y), DespawnOnExit(CURRENT_SCENE), )); commands.spawn(( DirectionalLight { color: RED.into(), ..default() }, Transform::IDENTITY.looking_to(Dir3::X, Dir3::Y), DespawnOnExit(CURRENT_SCENE), )); commands.spawn(( DirectionalLight { color: GREEN.into(), ..default() }, Transform::IDENTITY.looking_to(Dir3::NEG_Y, Dir3::X), DespawnOnExit(CURRENT_SCENE), )); commands .spawn(( SceneRoot(asset_server.load_with_settings( GltfAssetLabel::Scene(0).from_asset("models/Faces/faces.glb"), |s: &mut GltfLoaderSettings| { s.convert_coordinates = Some(GltfConvertCoordinates { rotate_scene_entity: true, rotate_meshes: true, }); }, )), DespawnOnExit(CURRENT_SCENE), )) .observe(show_aabbs); } pub fn show_aabbs( scene_ready: On<SceneInstanceReady>, mut commands: Commands, children: Query<&Children>, meshes: Query<(), With<Mesh3d>>, ) { for child in children .iter_descendants(scene_ready.entity) .filter(|&e| meshes.contains(e)) { commands.entity(child).insert(ShowAabbGizmo { color: Some(BLACK.into()), }); } } pub fn draw_gizmos(mut gizmos: Gizmos) { gizmos.axes(Transform::IDENTITY, 1.0); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/testbed/2d.rs
examples/testbed/2d.rs
//! 2d testbed //! //! You can switch scene by pressing the spacebar mod helpers; use argh::FromArgs; use bevy::prelude::*; use helpers::Next; #[derive(FromArgs)] /// 2d testbed pub struct Args { #[argh(positional)] scene: Option<Scene>, } fn main() { #[cfg(not(target_arch = "wasm32"))] let args: Args = argh::from_env(); #[cfg(target_arch = "wasm32")] let args: Args = Args::from_args(&[], &[]).unwrap(); let mut app = App::new(); app.add_plugins((DefaultPlugins,)) .add_systems(OnEnter(Scene::Shapes), shapes::setup) .add_systems(OnEnter(Scene::Bloom), bloom::setup) .add_systems(OnEnter(Scene::Text), text::setup) .add_systems(OnEnter(Scene::Sprite), sprite::setup) .add_systems(OnEnter(Scene::SpriteSlicing), sprite_slicing::setup) .add_systems(OnEnter(Scene::Gizmos), gizmos::setup) .add_systems(Update, switch_scene) .add_systems(Update, gizmos::draw_gizmos.run_if(in_state(Scene::Gizmos))); match args.scene { None => app.init_state::<Scene>(), Some(scene) => app.insert_state(scene), }; #[cfg(feature = "bevy_ci_testing")] app.add_systems(Update, helpers::switch_scene_in_ci::<Scene>); app.run(); } #[derive(Debug, Clone, Eq, PartialEq, Hash, States, Default)] enum Scene { #[default] Shapes, Bloom, Text, Sprite, SpriteSlicing, Gizmos, } impl std::str::FromStr for Scene { type Err = String; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { let mut isit = Self::default(); while s.to_lowercase() != format!("{isit:?}").to_lowercase() { isit = isit.next(); if isit == Self::default() { return Err(format!("Invalid Scene name: {s}")); } } Ok(isit) } } impl Next for Scene { fn next(&self) -> Self { match self { Scene::Shapes => Scene::Bloom, Scene::Bloom => Scene::Text, Scene::Text => Scene::Sprite, Scene::Sprite => Scene::SpriteSlicing, Scene::SpriteSlicing => Scene::Gizmos, Scene::Gizmos => Scene::Shapes, } } } fn switch_scene( keyboard: Res<ButtonInput<KeyCode>>, scene: Res<State<Scene>>, mut next_scene: ResMut<NextState<Scene>>, ) { if keyboard.just_pressed(KeyCode::Space) { info!("Switching scene"); next_scene.set(scene.get().next()); } } mod shapes { use bevy::prelude::*; const X_EXTENT: f32 = 900.; pub fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<ColorMaterial>>, ) { commands.spawn((Camera2d, DespawnOnExit(super::Scene::Shapes))); let shapes = [ meshes.add(Circle::new(50.0)), meshes.add(CircularSector::new(50.0, 1.0)), meshes.add(CircularSegment::new(50.0, 1.25)), meshes.add(Ellipse::new(25.0, 50.0)), meshes.add(Annulus::new(25.0, 50.0)), meshes.add(Capsule2d::new(25.0, 50.0)), meshes.add(Rhombus::new(75.0, 100.0)), meshes.add(Rectangle::new(50.0, 100.0)), meshes.add(RegularPolygon::new(50.0, 6)), meshes.add(Triangle2d::new( Vec2::Y * 50.0, Vec2::new(-50.0, -50.0), Vec2::new(50.0, -50.0), )), ]; let num_shapes = shapes.len(); for (i, shape) in shapes.into_iter().enumerate() { // Distribute colors evenly across the rainbow. let color = Color::hsl(360. * i as f32 / num_shapes as f32, 0.95, 0.7); commands.spawn(( Mesh2d(shape), MeshMaterial2d(materials.add(color)), Transform::from_xyz( // Distribute shapes from -X_EXTENT/2 to +X_EXTENT/2. -X_EXTENT / 2. + i as f32 / (num_shapes - 1) as f32 * X_EXTENT, 0.0, 0.0, ), DespawnOnExit(super::Scene::Shapes), )); } } } mod bloom { use bevy::{core_pipeline::tonemapping::Tonemapping, post_process::bloom::Bloom, prelude::*}; pub fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<ColorMaterial>>, ) { commands.spawn(( Camera2d, Tonemapping::TonyMcMapface, Bloom::default(), DespawnOnExit(super::Scene::Bloom), )); commands.spawn(( Mesh2d(meshes.add(Circle::new(100.))), MeshMaterial2d(materials.add(Color::srgb(7.5, 0.0, 7.5))), Transform::from_translation(Vec3::new(-200., 0., 0.)), DespawnOnExit(super::Scene::Bloom), )); commands.spawn(( Mesh2d(meshes.add(RegularPolygon::new(100., 6))), MeshMaterial2d(materials.add(Color::srgb(6.25, 9.4, 9.1))), Transform::from_translation(Vec3::new(200., 0., 0.)), DespawnOnExit(super::Scene::Bloom), )); } } mod text { use bevy::color::palettes; use bevy::prelude::*; use bevy::sprite::Anchor; use bevy::text::TextBounds; pub fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn((Camera2d, DespawnOnExit(super::Scene::Text))); for (i, justify) in [ Justify::Left, Justify::Right, Justify::Center, Justify::Justified, ] .into_iter() .enumerate() { let y = 230. - 150. * i as f32; spawn_anchored_text(&mut commands, -300. * Vec3::X + y * Vec3::Y, justify, None); spawn_anchored_text( &mut commands, 300. * Vec3::X + y * Vec3::Y, justify, Some(TextBounds::new(150., 60.)), ); } let sans_serif = TextFont::from(asset_server.load("fonts/FiraSans-Bold.ttf")); const NUM_ITERATIONS: usize = 10; for i in 0..NUM_ITERATIONS { let fraction = i as f32 / (NUM_ITERATIONS - 1) as f32; commands.spawn(( Text2d::new("Bevy"), sans_serif.clone(), Transform::from_xyz(0.0, fraction * 200.0, i as f32) .with_scale(1.0 + Vec2::splat(fraction).extend(1.)) .with_rotation(Quat::from_rotation_z(fraction * core::f32::consts::PI)), TextColor(Color::hsla(fraction * 360.0, 0.8, 0.8, 0.8)), DespawnOnExit(super::Scene::Text), )); } commands.spawn(( Text2d::new("This text is invisible."), Visibility::Hidden, DespawnOnExit(super::Scene::Text), )); } fn spawn_anchored_text( commands: &mut Commands, dest: Vec3, justify: Justify, bounds: Option<TextBounds>, ) { commands.spawn(( Sprite { color: palettes::css::YELLOW.into(), custom_size: Some(5. * Vec2::ONE), ..Default::default() }, Transform::from_translation(dest), DespawnOnExit(super::Scene::Text), )); for anchor in [ Anchor::TOP_LEFT, Anchor::TOP_RIGHT, Anchor::BOTTOM_RIGHT, Anchor::BOTTOM_LEFT, ] { let mut text = commands.spawn(( Text2d::new("L R\n"), TextLayout::new_with_justify(justify), Transform::from_translation(dest + Vec3::Z), anchor, DespawnOnExit(super::Scene::Text), ShowAabbGizmo { color: Some(palettes::tailwind::AMBER_400.into()), }, children![ ( TextSpan::new(format!("{}, {}\n", anchor.x, anchor.y)), TextFont::from_font_size(14.0), TextColor(palettes::tailwind::BLUE_400.into()), ), ( TextSpan::new(format!("{justify:?}")), TextFont::from_font_size(14.0), TextColor(palettes::tailwind::GREEN_400.into()), ), ], )); if let Some(bounds) = bounds { text.insert(bounds); commands.spawn(( Sprite { color: palettes::tailwind::GRAY_900.into(), custom_size: Some(Vec2::new(bounds.width.unwrap(), bounds.height.unwrap())), ..Default::default() }, Transform::from_translation(dest - Vec3::Z), anchor, DespawnOnExit(super::Scene::Text), )); } } } } mod sprite { use bevy::color::palettes::css::{BLUE, LIME, RED}; use bevy::prelude::*; use bevy::sprite::Anchor; pub fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn((Camera2d, DespawnOnExit(super::Scene::Sprite))); for (anchor, flip_x, flip_y, color) in [ (Anchor::BOTTOM_LEFT, false, false, Color::WHITE), (Anchor::BOTTOM_RIGHT, true, false, RED.into()), (Anchor::TOP_LEFT, false, true, LIME.into()), (Anchor::TOP_RIGHT, true, true, BLUE.into()), ] { commands.spawn(( Sprite { image: asset_server.load("branding/bevy_logo_dark.png"), flip_x, flip_y, color, ..default() }, anchor, DespawnOnExit(super::Scene::Sprite), )); } } } mod sprite_slicing { use bevy::prelude::*; use bevy::sprite::{BorderRect, SliceScaleMode, SpriteImageMode, TextureSlicer}; pub fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn((Camera2d, DespawnOnExit(super::Scene::SpriteSlicing))); let texture = asset_server.load("textures/slice_square_2.png"); let font = asset_server.load("fonts/FiraSans-Bold.ttf"); commands.spawn(( Sprite { image: texture.clone(), ..default() }, Transform::from_translation(Vec3::new(-150.0, 50.0, 0.0)).with_scale(Vec3::splat(2.0)), DespawnOnExit(super::Scene::SpriteSlicing), )); commands.spawn(( Sprite { image: texture, image_mode: SpriteImageMode::Sliced(TextureSlicer { border: BorderRect::all(20.0), center_scale_mode: SliceScaleMode::Stretch, ..default() }), custom_size: Some(Vec2::new(200.0, 200.0)), ..default() }, Transform::from_translation(Vec3::new(150.0, 50.0, 0.0)), DespawnOnExit(super::Scene::SpriteSlicing), )); commands.spawn(( Text2d::new("Original"), TextFont { font: FontSource::from(font.clone()), font_size: 20.0, ..default() }, Transform::from_translation(Vec3::new(-150.0, -80.0, 0.0)), DespawnOnExit(super::Scene::SpriteSlicing), )); commands.spawn(( Text2d::new("Sliced"), TextFont { font: FontSource::from(font.clone()), font_size: 20.0, ..default() }, Transform::from_translation(Vec3::new(150.0, -80.0, 0.0)), DespawnOnExit(super::Scene::SpriteSlicing), )); } } mod gizmos { use bevy::{color::palettes::css::*, prelude::*}; pub fn setup(mut commands: Commands) { commands.spawn((Camera2d, DespawnOnExit(super::Scene::Gizmos))); } pub fn draw_gizmos(mut gizmos: Gizmos) { gizmos.rect_2d( Isometry2d::from_translation(Vec2::new(-200.0, 0.0)), Vec2::new(200.0, 200.0), RED, ); gizmos .circle_2d( Isometry2d::from_translation(Vec2::new(-200.0, 0.0)), 200.0, GREEN, ) .resolution(64); // 2d grids with all variations of outer edges on or off for i in 0..4 { let x = 200.0 * (1.0 + (i % 2) as f32); let y = 150.0 * (0.5 - (i / 2) as f32); let mut grid = gizmos.grid( Vec3::new(x, y, 0.0), UVec2::new(5, 4), Vec2::splat(30.), Color::WHITE, ); if i & 1 > 0 { grid = grid.outer_edges_x(); } if i & 2 > 0 { grid.outer_edges_y(); } } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/testbed/ui.rs
examples/testbed/ui.rs
//! UI testbed //! //! You can switch scene by pressing the spacebar mod helpers; use argh::FromArgs; use bevy::prelude::*; use helpers::Next; #[derive(FromArgs)] /// ui testbed pub struct Args { #[argh(positional)] scene: Option<Scene>, } fn main() { #[cfg(not(target_arch = "wasm32"))] let args: Args = argh::from_env(); #[cfg(target_arch = "wasm32")] let args: Args = Args::from_args(&[], &[]).unwrap(); let mut app = App::new(); app.add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { // The ViewportCoords scene relies on these specific viewport dimensions, // so let's explicitly define them and set resizable to false resolution: (1280, 720).into(), resizable: false, ..Default::default() }), ..Default::default() })) .add_systems(OnEnter(Scene::Image), image::setup) .add_systems(OnEnter(Scene::Text), text::setup) .add_systems(OnEnter(Scene::Grid), grid::setup) .add_systems(OnEnter(Scene::Borders), borders::setup) .add_systems(OnEnter(Scene::BoxShadow), box_shadow::setup) .add_systems(OnEnter(Scene::TextWrap), text_wrap::setup) .add_systems(OnEnter(Scene::Overflow), overflow::setup) .add_systems(OnEnter(Scene::Slice), slice::setup) .add_systems(OnEnter(Scene::LayoutRounding), layout_rounding::setup) .add_systems(OnEnter(Scene::LinearGradient), linear_gradient::setup) .add_systems(OnEnter(Scene::RadialGradient), radial_gradient::setup) .add_systems(OnEnter(Scene::Transformations), transformations::setup) .add_systems(OnEnter(Scene::ViewportCoords), viewport_coords::setup) .add_systems(Update, switch_scene); match args.scene { None => app.init_state::<Scene>(), Some(scene) => app.insert_state(scene), }; #[cfg(feature = "bevy_ui_debug")] { app.add_systems(OnEnter(Scene::DebugOutlines), debug_outlines::setup); app.add_systems(OnExit(Scene::DebugOutlines), debug_outlines::teardown); } #[cfg(feature = "bevy_ci_testing")] app.add_systems(Update, helpers::switch_scene_in_ci::<Scene>); app.run(); } #[derive(Debug, Clone, Eq, PartialEq, Hash, States, Default)] #[states(scoped_entities)] enum Scene { #[default] Image, Text, Grid, Borders, BoxShadow, TextWrap, Overflow, Slice, LayoutRounding, LinearGradient, RadialGradient, Transformations, #[cfg(feature = "bevy_ui_debug")] DebugOutlines, ViewportCoords, } impl std::str::FromStr for Scene { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { let mut isit = Self::default(); while s.to_lowercase() != format!("{isit:?}").to_lowercase() { isit = isit.next(); if isit == Self::default() { return Err(format!("Invalid Scene name: {s}")); } } Ok(isit) } } impl Next for Scene { fn next(&self) -> Self { match self { Scene::Image => Scene::Text, Scene::Text => Scene::Grid, Scene::Grid => Scene::Borders, Scene::Borders => Scene::BoxShadow, Scene::BoxShadow => Scene::TextWrap, Scene::TextWrap => Scene::Overflow, Scene::Overflow => Scene::Slice, Scene::Slice => Scene::LayoutRounding, Scene::LayoutRounding => Scene::LinearGradient, Scene::LinearGradient => Scene::RadialGradient, #[cfg(feature = "bevy_ui_debug")] Scene::RadialGradient => Scene::DebugOutlines, #[cfg(feature = "bevy_ui_debug")] Scene::DebugOutlines => Scene::Transformations, #[cfg(not(feature = "bevy_ui_debug"))] Scene::RadialGradient => Scene::Transformations, Scene::Transformations => Scene::ViewportCoords, Scene::ViewportCoords => Scene::Image, } } } fn switch_scene( keyboard: Res<ButtonInput<KeyCode>>, scene: Res<State<Scene>>, mut next_scene: ResMut<NextState<Scene>>, ) { if keyboard.just_pressed(KeyCode::Space) { info!("Switching scene"); next_scene.set(scene.get().next()); } } mod image { use bevy::prelude::*; pub fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn((Camera2d, DespawnOnExit(super::Scene::Image))); commands.spawn(( ImageNode::new(asset_server.load("branding/bevy_logo_dark.png")), DespawnOnExit(super::Scene::Image), )); } } mod text { use bevy::{color::palettes::css::*, prelude::*}; pub fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn((Camera2d, DespawnOnExit(super::Scene::Text))); commands.spawn(( Text::new("Hello World."), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), font_size: 200., ..default() }, DespawnOnExit(super::Scene::Text), )); commands.spawn(( Node { left: px(100.), top: px(230.), ..Default::default() }, Text::new("white "), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), ..default() }, DespawnOnExit(super::Scene::Text), children![ (TextSpan::new("red "), TextColor(RED.into()),), (TextSpan::new("green "), TextColor(GREEN.into()),), (TextSpan::new("blue "), TextColor(BLUE.into()),), ( TextSpan::new("black"), TextColor(Color::BLACK), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), ..default() }, TextBackgroundColor(Color::WHITE) ), ], )); commands.spawn(( Node { left: px(100.), top: px(260.), ..Default::default() }, Text::new(""), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), ..default() }, DespawnOnExit(super::Scene::Text), children![ ( TextSpan::new("white "), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), ..default() } ), (TextSpan::new("red "), TextColor(RED.into()),), (TextSpan::new("green "), TextColor(GREEN.into()),), (TextSpan::new("blue "), TextColor(BLUE.into()),), ( TextSpan::new("black"), TextColor(Color::BLACK), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), ..default() }, TextBackgroundColor(Color::WHITE) ), ], )); let mut top = 300.; commands.spawn(( Node { left: px(100.), top: px(top), ..Default::default() }, Text::new(""), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), ..default() }, DespawnOnExit(super::Scene::Text), children![ (TextSpan::new(""), TextColor(YELLOW.into()),), TextSpan::new(""), ( TextSpan::new("white "), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), ..default() } ), TextSpan::new(""), (TextSpan::new("red "), TextColor(RED.into()),), TextSpan::new(""), TextSpan::new(""), (TextSpan::new("green "), TextColor(GREEN.into()),), (TextSpan::new(""), TextColor(YELLOW.into()),), (TextSpan::new("blue "), TextColor(BLUE.into()),), TextSpan::new(""), (TextSpan::new(""), TextColor(YELLOW.into()),), ( TextSpan::new("black"), TextColor(Color::BLACK), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), ..default() }, TextBackgroundColor(Color::WHITE) ), TextSpan::new(""), ], )); top += 35.; commands.spawn(( Node { left: px(100.), top: px(top), ..Default::default() }, Text::new("FiraSans_"), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), font_size: 25., ..default() }, DespawnOnExit(super::Scene::Text), children![ ( TextSpan::new("MonaSans_"), TextFont { font: asset_server.load("fonts/MonaSans-VariableFont.ttf").into(), font_size: 25., ..default() } ), ( TextSpan::new("EBGaramond_"), TextFont { font: asset_server.load("fonts/EBGaramond12-Regular.otf").into(), font_size: 25., ..default() }, ), ( TextSpan::new("FiraMono"), TextFont { font: asset_server.load("fonts/FiraMono-Medium.ttf").into(), font_size: 25., ..default() }, ), ], )); top += 35.; commands.spawn(( Node { left: px(100.), top: px(top), ..Default::default() }, Text::new("FiraSans "), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), font_size: 25., ..default() }, DespawnOnExit(super::Scene::Text), children![ ( TextSpan::new("MonaSans "), TextFont { font: asset_server.load("fonts/MonaSans-VariableFont.ttf").into(), font_size: 25., ..default() } ), ( TextSpan::new("EBGaramond "), TextFont { font: asset_server.load("fonts/EBGaramond12-Regular.otf").into(), font_size: 25., ..default() }, ), ( TextSpan::new("FiraMono"), TextFont { font: asset_server.load("fonts/FiraMono-Medium.ttf").into(), font_size: 25., ..default() }, ), ], )); top += 35.; commands.spawn(( Node { left: px(100.), top: px(top), ..Default::default() }, Text::new("FiraSans "), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), font_size: 25., ..default() }, DespawnOnExit(super::Scene::Text), children![ ( TextSpan::new("MonaSans_"), TextFont { font: asset_server.load("fonts/MonaSans-VariableFont.ttf").into(), font_size: 25., ..default() } ), ( TextSpan::new("EBGaramond "), TextFont { font: asset_server.load("fonts/EBGaramond12-Regular.otf").into(), font_size: 25., ..default() }, ), ( TextSpan::new("FiraMono"), TextFont { font: asset_server.load("fonts/FiraMono-Medium.ttf").into(), font_size: 25., ..default() }, ), ], )); top += 35.; commands.spawn(( Node { left: px(100.), top: px(top), ..Default::default() }, Text::new("FiraSans"), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), font_size: 25., ..default() }, DespawnOnExit(super::Scene::Text), children![ TextSpan::new(" "), ( TextSpan::new("MonaSans"), TextFont { font: asset_server.load("fonts/MonaSans-VariableFont.ttf").into(), font_size: 25., ..default() } ), TextSpan::new(" "), ( TextSpan::new("EBGaramond"), TextFont { font: asset_server.load("fonts/EBGaramond12-Regular.otf").into(), font_size: 25., ..default() }, ), TextSpan::new(" "), ( TextSpan::new("FiraMono"), TextFont { font: asset_server.load("fonts/FiraMono-Medium.ttf").into(), font_size: 25., ..default() }, ), ], )); top += 35.; commands.spawn(( Node { left: px(100.), top: px(top), ..Default::default() }, Text::new("Fira Sans_"), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), font_size: 25., ..default() }, DespawnOnExit(super::Scene::Text), children![ ( TextSpan::new("Mona Sans_"), TextFont { font: asset_server.load("fonts/MonaSans-VariableFont.ttf").into(), font_size: 25., ..default() } ), ( TextSpan::new("EB Garamond_"), TextFont { font: asset_server.load("fonts/EBGaramond12-Regular.otf").into(), font_size: 25., ..default() }, ), ( TextSpan::new("Fira Mono"), TextFont { font: asset_server.load("fonts/FiraMono-Medium.ttf").into(), font_size: 25., ..default() }, ), ], )); top += 35.; commands.spawn(( Node { left: px(100.), top: px(top), ..Default::default() }, Text::new("FontWeight(100)_"), TextFont { font: asset_server.load("fonts/MonaSans-VariableFont.ttf").into(), font_size: 25., weight: FontWeight(100), ..default() }, DespawnOnExit(super::Scene::Text), children![ ( TextSpan::new("FontWeight(500)_"), TextFont { font: asset_server.load("fonts/MonaSans-VariableFont.ttf").into(), font_size: 25., weight: FontWeight(500), ..default() } ), ( TextSpan::new("FontWeight(900)"), TextFont { font: asset_server.load("fonts/MonaSans-VariableFont.ttf").into(), font_size: 25., weight: FontWeight(900), ..default() }, ), ], )); top += 35.; commands.spawn(( Node { left: px(100.), top: px(top), ..Default::default() }, Text::new("FiraSans_"), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), font_size: 25., weight: FontWeight(900), ..default() }, DespawnOnExit(super::Scene::Text), children![ ( TextSpan::new("MonaSans_"), TextFont { font: asset_server.load("fonts/MonaSans-VariableFont.ttf").into(), font_size: 25., weight: FontWeight(700), ..default() } ), ( TextSpan::new("EBGaramond_"), TextFont { font: asset_server.load("fonts/EBGaramond12-Regular.otf").into(), font_size: 25., weight: FontWeight(500), ..default() }, ), ( TextSpan::new("FiraMono"), TextFont { font: asset_server.load("fonts/FiraMono-Medium.ttf").into(), font_size: 25., weight: FontWeight(300), ..default() }, ), ], )); top += 35.; commands.spawn(( Node { left: px(100.), top: px(top), ..Default::default() }, Text::new("FiraSans\t"), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), font_size: 25., ..default() }, DespawnOnExit(super::Scene::Text), children![ ( TextSpan::new("MonaSans\t"), TextFont { font: asset_server.load("fonts/MonaSans-VariableFont.ttf").into(), font_size: 25., ..default() } ), ( TextSpan::new("EBGaramond\t"), TextFont { font: asset_server.load("fonts/EBGaramond12-Regular.otf").into(), font_size: 25., ..default() }, ), ( TextSpan::new("FiraMono"), TextFont { font: asset_server.load("fonts/FiraMono-Medium.ttf").into(), font_size: 25., ..default() }, ), ], )); } } mod grid { use bevy::{color::palettes::css::*, prelude::*}; pub fn setup(mut commands: Commands) { commands.spawn((Camera2d, DespawnOnExit(super::Scene::Grid))); // Top-level grid (app frame) commands.spawn(( Node { display: Display::Grid, width: percent(100), height: percent(100), grid_template_columns: vec![GridTrack::min_content(), GridTrack::flex(1.0)], grid_template_rows: vec![ GridTrack::auto(), GridTrack::flex(1.0), GridTrack::px(40.), ], ..default() }, BackgroundColor(Color::WHITE), DespawnOnExit(super::Scene::Grid), children![ // Header ( Node { display: Display::Grid, grid_column: GridPlacement::span(2), padding: UiRect::all(px(40)), ..default() }, BackgroundColor(RED.into()), ), // Main content grid (auto placed in row 2, column 1) ( Node { height: percent(100), aspect_ratio: Some(1.0), display: Display::Grid, grid_template_columns: RepeatedGridTrack::flex(3, 1.0), grid_template_rows: RepeatedGridTrack::flex(2, 1.0), row_gap: px(12), column_gap: px(12), ..default() }, BackgroundColor(Color::srgb(0.25, 0.25, 0.25)), children![ (Node::default(), BackgroundColor(ORANGE.into())), (Node::default(), BackgroundColor(BISQUE.into())), (Node::default(), BackgroundColor(BLUE.into())), (Node::default(), BackgroundColor(CRIMSON.into())), (Node::default(), BackgroundColor(AQUA.into())), ] ), // Right side bar (auto placed in row 2, column 2) (Node::DEFAULT, BackgroundColor(BLACK.into())), ], )); } } mod borders { use bevy::{color::palettes::css::*, prelude::*}; pub fn setup(mut commands: Commands) { commands.spawn((Camera2d, DespawnOnExit(super::Scene::Borders))); let root = commands .spawn(( Node { flex_wrap: FlexWrap::Wrap, ..default() }, DespawnOnExit(super::Scene::Borders), )) .id(); // all the different combinations of border edges let borders = [ UiRect::default(), UiRect::all(px(20)), UiRect::left(px(20)), UiRect::vertical(px(20)), UiRect { left: px(40), top: px(20), ..Default::default() }, UiRect { right: px(20), bottom: px(30), ..Default::default() }, UiRect { right: px(20), top: px(40), bottom: px(20), ..Default::default() }, UiRect { left: px(20), top: px(20), bottom: px(20), ..Default::default() }, UiRect { left: px(20), right: px(20), bottom: px(40), ..Default::default() }, ]; let non_zero = |x, y| x != px(0) && y != px(0); let border_size = |x, y| if non_zero(x, y) { f32::MAX } else { 0. }; for border in borders { for rounded in [true, false] { let border_node = commands .spawn(( Node { width: px(100), height: px(100), border, margin: UiRect::all(px(30)), align_items: AlignItems::Center, justify_content: JustifyContent::Center, border_radius: if rounded { BorderRadius::px( border_size(border.left, border.top), border_size(border.right, border.top), border_size(border.right, border.bottom), border_size(border.left, border.bottom), ) } else { BorderRadius::ZERO }, ..default() }, BackgroundColor(MAROON.into()), BorderColor::all(RED), Outline { width: px(10), offset: px(10), color: Color::WHITE, }, )) .id(); commands.entity(root).add_child(border_node); } } } } mod box_shadow { use bevy::{color::palettes::css::*, prelude::*}; pub fn setup(mut commands: Commands) { commands.spawn((Camera2d, DespawnOnExit(super::Scene::BoxShadow))); commands .spawn(( Node { width: percent(100), height: percent(100), padding: UiRect::all(px(30)), column_gap: px(200), flex_wrap: FlexWrap::Wrap, ..default() }, BackgroundColor(GREEN.into()), DespawnOnExit(super::Scene::BoxShadow), )) .with_children(|commands| { let example_nodes = [ ( Vec2::splat(100.), Vec2::ZERO, 10., 0., BorderRadius::bottom_right(px(10)), ), (Vec2::new(200., 50.), Vec2::ZERO, 10., 0., BorderRadius::MAX), ( Vec2::new(100., 50.), Vec2::ZERO, 10., 10., BorderRadius::ZERO, ), ( Vec2::splat(100.), Vec2::splat(20.), 10., 10., BorderRadius::bottom_right(px(10)), ), ( Vec2::splat(100.), Vec2::splat(50.), 0., 10., BorderRadius::ZERO, ), ( Vec2::new(50., 100.), Vec2::splat(10.), 0., 10., BorderRadius::MAX, ), ]; for (size, offset, spread, blur, border_radius) in example_nodes { commands.spawn(( Node { width: px(size.x), height: px(size.y), border: UiRect::all(px(2)), border_radius, ..default() }, BorderColor::all(WHITE), BackgroundColor(BLUE.into()), BoxShadow::new( Color::BLACK.with_alpha(0.9), percent(offset.x), percent(offset.y), percent(spread), px(blur), ), )); } }); } } mod text_wrap { use bevy::prelude::*; pub fn setup(mut commands: Commands) { commands.spawn((Camera2d, DespawnOnExit(super::Scene::TextWrap))); let root = commands .spawn(( Node { flex_direction: FlexDirection::Column, width: px(200), height: percent(100), overflow: Overflow::clip_x(), ..default() }, BackgroundColor(Color::BLACK), DespawnOnExit(super::Scene::TextWrap), )) .id(); for linebreak in [ LineBreak::AnyCharacter, LineBreak::WordBoundary, LineBreak::WordOrCharacter, LineBreak::NoWrap, ] { let messages = [ "Lorem ipsum dolor sit amet, consectetur adipiscing elit.".to_string(), "pneumonoultramicroscopicsilicovolcanoconiosis".to_string(), ]; for (j, message) in messages.into_iter().enumerate() { commands.entity(root).with_child(( Text(message.clone()), TextLayout::new(Justify::Left, linebreak), BackgroundColor(Color::srgb(0.8 - j as f32 * 0.3, 0., 0.)), )); } } } } mod overflow { use bevy::{color::palettes::css::*, prelude::*}; pub fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn((Camera2d, DespawnOnExit(super::Scene::Overflow))); let image = asset_server.load("branding/icon.png"); commands .spawn(( Node { width: percent(100), height: percent(100), align_items: AlignItems::Center, justify_content: JustifyContent::SpaceAround, ..Default::default() }, BackgroundColor(BLUE.into()), DespawnOnExit(super::Scene::Overflow), )) .with_children(|parent| { for overflow in [ Overflow::visible(), Overflow::clip_x(), Overflow::clip_y(), Overflow::clip(), ] { parent .spawn(( Node { width: px(100), height: px(100), padding: UiRect { left: px(25), top: px(25), ..Default::default() }, border: UiRect::all(px(5)), overflow, ..default() }, BorderColor::all(RED), BackgroundColor(Color::WHITE), )) .with_children(|parent| { parent.spawn(( ImageNode::new(image.clone()), Node { min_width: px(100), min_height: px(100), ..default() }, Interaction::default(), Outline { width: px(2), offset: px(2), color: Color::NONE, }, )); }); } }); } } mod slice { use bevy::prelude::*; pub fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
true
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/dev_tools/fps_overlay.rs
examples/dev_tools/fps_overlay.rs
//! Showcase how to use and configure FPS overlay. use bevy::{ dev_tools::fps_overlay::{FpsOverlayConfig, FpsOverlayPlugin, FrameTimeGraphConfig}, prelude::*, text::FontSmoothing, }; struct OverlayColor; impl OverlayColor { const RED: Color = Color::srgb(1.0, 0.0, 0.0); const GREEN: Color = Color::srgb(0.0, 1.0, 0.0); } fn main() { App::new() .add_plugins(( DefaultPlugins, FpsOverlayPlugin { config: FpsOverlayConfig { text_config: TextFont { // Here we define size of our overlay font_size: 42.0, // If we want, we can use a custom font font: default(), // We could also disable font smoothing, font_smoothing: FontSmoothing::default(), ..default() }, // We can also change color of the overlay text_color: OverlayColor::GREEN, // We can also set the refresh interval for the FPS counter refresh_interval: core::time::Duration::from_millis(100), enabled: true, frame_time_graph_config: FrameTimeGraphConfig { enabled: true, // The minimum acceptable fps min_fps: 30.0, // The target fps target_fps: 144.0, }, }, }, )) .add_systems(Startup, setup) .add_systems(Update, customize_config) .run(); } fn setup(mut commands: Commands) { // We need to spawn a camera (2d or 3d) to see the overlay commands.spawn(Camera2d); // Instruction text commands.spawn(( Text::new(concat!( "Press 1 to toggle the overlay color.\n", "Press 2 to decrease the overlay size.\n", "Press 3 to increase the overlay size.\n", "Press 4 to toggle the text visibility.\n", "Press 5 to toggle the frame time graph." )), Node { position_type: PositionType::Absolute, bottom: px(12), left: px(12), ..default() }, )); } fn customize_config(input: Res<ButtonInput<KeyCode>>, mut overlay: ResMut<FpsOverlayConfig>) { if input.just_pressed(KeyCode::Digit1) { // Changing resource will affect overlay if overlay.text_color == OverlayColor::GREEN { overlay.text_color = OverlayColor::RED; } else { overlay.text_color = OverlayColor::GREEN; } } if input.just_pressed(KeyCode::Digit2) { overlay.text_config.font_size -= 2.0; } if input.just_pressed(KeyCode::Digit3) { overlay.text_config.font_size += 2.0; } if input.just_pressed(KeyCode::Digit4) { overlay.enabled = !overlay.enabled; } if input.just_released(KeyCode::Digit5) { overlay.frame_time_graph_config.enabled = !overlay.frame_time_graph_config.enabled; } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/games/breakout.rs
examples/games/breakout.rs
//! A simplified implementation of the classic game "Breakout". //! //! Demonstrates Bevy's stepping capabilities if compiled with the `bevy_debug_stepping` feature. use bevy::{ math::bounding::{Aabb2d, BoundingCircle, BoundingVolume, IntersectsVolume}, prelude::*, }; mod stepping; // These constants are defined in `Transform` units. // Using the default 2D camera they correspond 1:1 with screen pixels. const PADDLE_SIZE: Vec2 = Vec2::new(120.0, 20.0); const GAP_BETWEEN_PADDLE_AND_FLOOR: f32 = 60.0; const PADDLE_SPEED: f32 = 500.0; // How close can the paddle get to the wall const PADDLE_PADDING: f32 = 10.0; // We set the z-value of the ball to 1 so it renders on top in the case of overlapping sprites. const BALL_STARTING_POSITION: Vec3 = Vec3::new(0.0, -50.0, 1.0); const BALL_DIAMETER: f32 = 30.; const BALL_SPEED: f32 = 400.0; const INITIAL_BALL_DIRECTION: Vec2 = Vec2::new(0.5, -0.5); const WALL_THICKNESS: f32 = 10.0; // x coordinates const LEFT_WALL: f32 = -450.; const RIGHT_WALL: f32 = 450.; // y coordinates const BOTTOM_WALL: f32 = -300.; const TOP_WALL: f32 = 300.; const BRICK_SIZE: Vec2 = Vec2::new(100., 30.); // These values are exact const GAP_BETWEEN_PADDLE_AND_BRICKS: f32 = 270.0; const GAP_BETWEEN_BRICKS: f32 = 5.0; // These values are lower bounds, as the number of bricks is computed const GAP_BETWEEN_BRICKS_AND_CEILING: f32 = 20.0; const GAP_BETWEEN_BRICKS_AND_SIDES: f32 = 20.0; const SCOREBOARD_FONT_SIZE: f32 = 33.0; const SCOREBOARD_TEXT_PADDING: Val = Val::Px(5.0); const BACKGROUND_COLOR: Color = Color::srgb(0.9, 0.9, 0.9); const PADDLE_COLOR: Color = Color::srgb(0.3, 0.3, 0.7); const BALL_COLOR: Color = Color::srgb(1.0, 0.5, 0.5); const BRICK_COLOR: Color = Color::srgb(0.5, 0.5, 1.0); const WALL_COLOR: Color = Color::srgb(0.8, 0.8, 0.8); const TEXT_COLOR: Color = Color::srgb(0.5, 0.5, 1.0); const SCORE_COLOR: Color = Color::srgb(1.0, 0.5, 0.5); fn main() { App::new() .add_plugins(DefaultPlugins) .add_plugins( stepping::SteppingPlugin::default() .add_schedule(Update) .add_schedule(FixedUpdate) .at(percent(35), percent(50)), ) .insert_resource(Score(0)) .insert_resource(ClearColor(BACKGROUND_COLOR)) .add_systems(Startup, setup) // Add our gameplay simulation systems to the fixed timestep schedule // which runs at 64 Hz by default .add_systems( FixedUpdate, (apply_velocity, move_paddle, check_for_collisions) // `chain`ing systems together runs them in order .chain(), ) .add_systems(Update, update_scoreboard) .add_observer(play_collision_sound) .run(); } #[derive(Component)] struct Paddle; #[derive(Component)] struct Ball; #[derive(Component, Deref, DerefMut)] struct Velocity(Vec2); #[derive(Event)] struct BallCollided; #[derive(Component)] struct Brick; #[derive(Resource, Deref)] struct CollisionSound(Handle<AudioSource>); // Default must be implemented to define this as a required component for the Wall component below #[derive(Component, Default)] struct Collider; // This is a collection of the components that define a "Wall" in our game #[derive(Component)] #[require(Sprite, Transform, Collider)] struct Wall; /// Which side of the arena is this wall located on? enum WallLocation { Left, Right, Bottom, Top, } impl WallLocation { /// Location of the *center* of the wall, used in `transform.translation()` fn position(&self) -> Vec2 { match self { WallLocation::Left => Vec2::new(LEFT_WALL, 0.), WallLocation::Right => Vec2::new(RIGHT_WALL, 0.), WallLocation::Bottom => Vec2::new(0., BOTTOM_WALL), WallLocation::Top => Vec2::new(0., TOP_WALL), } } /// (x, y) dimensions of the wall, used in `transform.scale()` fn size(&self) -> Vec2 { let arena_height = TOP_WALL - BOTTOM_WALL; let arena_width = RIGHT_WALL - LEFT_WALL; // Make sure we haven't messed up our constants assert!(arena_height > 0.0); assert!(arena_width > 0.0); match self { WallLocation::Left | WallLocation::Right => { Vec2::new(WALL_THICKNESS, arena_height + WALL_THICKNESS) } WallLocation::Bottom | WallLocation::Top => { Vec2::new(arena_width + WALL_THICKNESS, WALL_THICKNESS) } } } } impl Wall { // This "builder method" allows us to reuse logic across our wall entities, // making our code easier to read and less prone to bugs when we change the logic // Notice the use of Sprite and Transform alongside Wall, overwriting the default values defined for the required components fn new(location: WallLocation) -> (Wall, Sprite, Transform) { ( Wall, Sprite::from_color(WALL_COLOR, Vec2::ONE), Transform { // We need to convert our Vec2 into a Vec3, by giving it a z-coordinate // This is used to determine the order of our sprites translation: location.position().extend(0.0), // The z-scale of 2D objects must always be 1.0, // or their ordering will be affected in surprising ways. // See https://github.com/bevyengine/bevy/issues/4149 scale: location.size().extend(1.0), ..default() }, ) } } // This resource tracks the game's score #[derive(Resource, Deref, DerefMut)] struct Score(usize); #[derive(Component)] struct ScoreboardUi; // Add the game's entities to our world fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<ColorMaterial>>, asset_server: Res<AssetServer>, ) { // Camera commands.spawn(Camera2d); // Sound let ball_collision_sound = asset_server.load("sounds/breakout_collision.ogg"); commands.insert_resource(CollisionSound(ball_collision_sound)); // Paddle let paddle_y = BOTTOM_WALL + GAP_BETWEEN_PADDLE_AND_FLOOR; commands.spawn(( Sprite::from_color(PADDLE_COLOR, Vec2::ONE), Transform { translation: Vec3::new(0.0, paddle_y, 0.0), scale: PADDLE_SIZE.extend(1.0), ..default() }, Paddle, Collider, )); // Ball commands.spawn(( Mesh2d(meshes.add(Circle::default())), MeshMaterial2d(materials.add(BALL_COLOR)), Transform::from_translation(BALL_STARTING_POSITION) .with_scale(Vec2::splat(BALL_DIAMETER).extend(1.)), Ball, Velocity(INITIAL_BALL_DIRECTION.normalize() * BALL_SPEED), )); // Scoreboard commands.spawn(( Text::new("Score: "), TextFont { font_size: SCOREBOARD_FONT_SIZE, ..default() }, TextColor(TEXT_COLOR), ScoreboardUi, Node { position_type: PositionType::Absolute, top: SCOREBOARD_TEXT_PADDING, left: SCOREBOARD_TEXT_PADDING, ..default() }, children![( TextSpan::default(), TextFont { font_size: SCOREBOARD_FONT_SIZE, ..default() }, TextColor(SCORE_COLOR), )], )); // Walls commands.spawn(Wall::new(WallLocation::Left)); commands.spawn(Wall::new(WallLocation::Right)); commands.spawn(Wall::new(WallLocation::Bottom)); commands.spawn(Wall::new(WallLocation::Top)); // Bricks let total_width_of_bricks = (RIGHT_WALL - LEFT_WALL) - 2. * GAP_BETWEEN_BRICKS_AND_SIDES; let bottom_edge_of_bricks = paddle_y + GAP_BETWEEN_PADDLE_AND_BRICKS; let total_height_of_bricks = TOP_WALL - bottom_edge_of_bricks - GAP_BETWEEN_BRICKS_AND_CEILING; assert!(total_width_of_bricks > 0.0); assert!(total_height_of_bricks > 0.0); // Given the space available, compute how many rows and columns of bricks we can fit let n_columns = (total_width_of_bricks / (BRICK_SIZE.x + GAP_BETWEEN_BRICKS)).floor() as usize; let n_rows = (total_height_of_bricks / (BRICK_SIZE.y + GAP_BETWEEN_BRICKS)).floor() as usize; let n_vertical_gaps = n_columns - 1; // Because we need to round the number of columns, // the space on the top and sides of the bricks only captures a lower bound, not an exact value let center_of_bricks = (LEFT_WALL + RIGHT_WALL) / 2.0; let left_edge_of_bricks = center_of_bricks // Space taken up by the bricks - (n_columns as f32 / 2.0 * BRICK_SIZE.x) // Space taken up by the gaps - n_vertical_gaps as f32 / 2.0 * GAP_BETWEEN_BRICKS; // In Bevy, the `translation` of an entity describes the center point, // not its bottom-left corner let offset_x = left_edge_of_bricks + BRICK_SIZE.x / 2.; let offset_y = bottom_edge_of_bricks + BRICK_SIZE.y / 2.; for row in 0..n_rows { for column in 0..n_columns { let brick_position = Vec2::new( offset_x + column as f32 * (BRICK_SIZE.x + GAP_BETWEEN_BRICKS), offset_y + row as f32 * (BRICK_SIZE.y + GAP_BETWEEN_BRICKS), ); // brick commands.spawn(( Sprite { color: BRICK_COLOR, ..default() }, Transform { translation: brick_position.extend(0.0), scale: Vec3::new(BRICK_SIZE.x, BRICK_SIZE.y, 1.0), ..default() }, Brick, Collider, )); } } } fn move_paddle( keyboard_input: Res<ButtonInput<KeyCode>>, mut paddle_transform: Single<&mut Transform, With<Paddle>>, time: Res<Time>, ) { let mut direction = 0.0; if keyboard_input.pressed(KeyCode::ArrowLeft) { direction -= 1.0; } if keyboard_input.pressed(KeyCode::ArrowRight) { direction += 1.0; } // Calculate the new horizontal paddle position based on player input let new_paddle_position = paddle_transform.translation.x + direction * PADDLE_SPEED * time.delta_secs(); // Update the paddle position, // making sure it doesn't cause the paddle to leave the arena let left_bound = LEFT_WALL + WALL_THICKNESS / 2.0 + PADDLE_SIZE.x / 2.0 + PADDLE_PADDING; let right_bound = RIGHT_WALL - WALL_THICKNESS / 2.0 - PADDLE_SIZE.x / 2.0 - PADDLE_PADDING; paddle_transform.translation.x = new_paddle_position.clamp(left_bound, right_bound); } fn apply_velocity(mut query: Query<(&mut Transform, &Velocity)>, time: Res<Time>) { for (mut transform, velocity) in &mut query { transform.translation.x += velocity.x * time.delta_secs(); transform.translation.y += velocity.y * time.delta_secs(); } } fn update_scoreboard( score: Res<Score>, score_root: Single<Entity, (With<ScoreboardUi>, With<Text>)>, mut writer: TextUiWriter, ) { *writer.text(*score_root, 1) = score.to_string(); } fn check_for_collisions( mut commands: Commands, mut score: ResMut<Score>, ball_query: Single<(&mut Velocity, &Transform), With<Ball>>, collider_query: Query<(Entity, &Transform, Option<&Brick>), With<Collider>>, ) { let (mut ball_velocity, ball_transform) = ball_query.into_inner(); for (collider_entity, collider_transform, maybe_brick) in &collider_query { let collision = ball_collision( BoundingCircle::new(ball_transform.translation.truncate(), BALL_DIAMETER / 2.), Aabb2d::new( collider_transform.translation.truncate(), collider_transform.scale.truncate() / 2., ), ); if let Some(collision) = collision { // Trigger observers of the "BallCollided" event commands.trigger(BallCollided); // Bricks should be despawned and increment the scoreboard on collision if maybe_brick.is_some() { commands.entity(collider_entity).despawn(); **score += 1; } // Reflect the ball's velocity when it collides let mut reflect_x = false; let mut reflect_y = false; // Reflect only if the velocity is in the opposite direction of the collision // This prevents the ball from getting stuck inside the bar match collision { Collision::Left => reflect_x = ball_velocity.x > 0.0, Collision::Right => reflect_x = ball_velocity.x < 0.0, Collision::Top => reflect_y = ball_velocity.y < 0.0, Collision::Bottom => reflect_y = ball_velocity.y > 0.0, } // Reflect velocity on the x-axis if we hit something on the x-axis if reflect_x { ball_velocity.x = -ball_velocity.x; } // Reflect velocity on the y-axis if we hit something on the y-axis if reflect_y { ball_velocity.y = -ball_velocity.y; } } } } fn play_collision_sound( _collided: On<BallCollided>, mut commands: Commands, sound: Res<CollisionSound>, ) { commands.spawn((AudioPlayer(sound.clone()), PlaybackSettings::DESPAWN)); } #[derive(Debug, PartialEq, Eq, Copy, Clone)] enum Collision { Left, Right, Top, Bottom, } // Returns `Some` if `ball` collides with `bounding_box`. // The returned `Collision` is the side of `bounding_box` that `ball` hit. fn ball_collision(ball: BoundingCircle, bounding_box: Aabb2d) -> Option<Collision> { if !ball.intersects(&bounding_box) { return None; } let closest = bounding_box.closest_point(ball.center()); let offset = ball.center() - closest; let side = if offset.x.abs() > offset.y.abs() { if offset.x < 0. { Collision::Left } else { Collision::Right } } else if offset.y > 0. { Collision::Top } else { Collision::Bottom }; Some(side) }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/games/alien_cake_addict.rs
examples/games/alien_cake_addict.rs
//! Eat the cakes. Eat them all. An example 3D game. use std::f32::consts::PI; use bevy::prelude::*; use rand::{Rng, SeedableRng}; use rand_chacha::ChaCha8Rng; #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default, States)] enum GameState { #[default] Playing, GameOver, } #[derive(Resource)] struct BonusSpawnTimer(Timer); fn main() { App::new() .add_plugins(DefaultPlugins) .init_resource::<Game>() .insert_resource(BonusSpawnTimer(Timer::from_seconds( 5.0, TimerMode::Repeating, ))) .init_state::<GameState>() .add_systems(Startup, setup_cameras) .add_systems(OnEnter(GameState::Playing), setup) .add_systems( Update, ( move_player, focus_camera, rotate_bonus, scoreboard_system, spawn_bonus, ) .run_if(in_state(GameState::Playing)), ) .add_systems(OnEnter(GameState::GameOver), display_score) .add_systems( Update, game_over_keyboard.run_if(in_state(GameState::GameOver)), ) .run(); } struct Cell { height: f32, } #[derive(Default)] struct Player { entity: Option<Entity>, i: usize, j: usize, move_cooldown: Timer, } #[derive(Default)] struct Bonus { entity: Option<Entity>, i: usize, j: usize, handle: Handle<Scene>, } #[derive(Resource, Default)] struct Game { board: Vec<Vec<Cell>>, player: Player, bonus: Bonus, score: i32, cake_eaten: u32, camera_should_focus: Vec3, camera_is_focus: Vec3, } #[derive(Resource, Deref, DerefMut)] struct Random(ChaCha8Rng); const BOARD_SIZE_I: usize = 14; const BOARD_SIZE_J: usize = 21; const RESET_FOCUS: [f32; 3] = [ BOARD_SIZE_I as f32 / 2.0, 0.0, BOARD_SIZE_J as f32 / 2.0 - 0.5, ]; fn setup_cameras(mut commands: Commands, mut game: ResMut<Game>) { game.camera_should_focus = Vec3::from(RESET_FOCUS); game.camera_is_focus = game.camera_should_focus; commands.spawn(( Camera3d::default(), Transform::from_xyz( -(BOARD_SIZE_I as f32 / 2.0), 2.0 * BOARD_SIZE_J as f32 / 3.0, BOARD_SIZE_J as f32 / 2.0 - 0.5, ) .looking_at(game.camera_is_focus, Vec3::Y), )); } fn setup(mut commands: Commands, asset_server: Res<AssetServer>, mut game: ResMut<Game>) { let mut rng = if std::env::var("GITHUB_ACTIONS") == Ok("true".to_string()) { // We're seeding the PRNG here to make this example deterministic for testing purposes. // This isn't strictly required in practical use unless you need your app to be deterministic. ChaCha8Rng::seed_from_u64(19878367467713) } else { ChaCha8Rng::from_os_rng() }; // reset the game state game.cake_eaten = 0; game.score = 0; game.player.i = BOARD_SIZE_I / 2; game.player.j = BOARD_SIZE_J / 2; game.player.move_cooldown = Timer::from_seconds(0.3, TimerMode::Once); commands.spawn(( DespawnOnExit(GameState::Playing), PointLight { intensity: 2_000_000.0, shadows_enabled: true, range: 30.0, ..default() }, Transform::from_xyz(4.0, 10.0, 4.0), )); // spawn the game board let cell_scene = asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/AlienCake/tile.glb")); game.board = (0..BOARD_SIZE_J) .map(|j| { (0..BOARD_SIZE_I) .map(|i| { let height = rng.random_range(-0.1..0.1); commands.spawn(( DespawnOnExit(GameState::Playing), Transform::from_xyz(i as f32, height - 0.2, j as f32), SceneRoot(cell_scene.clone()), )); Cell { height } }) .collect() }) .collect(); // spawn the game character game.player.entity = Some( commands .spawn(( DespawnOnExit(GameState::Playing), Transform { translation: Vec3::new( game.player.i as f32, game.board[game.player.j][game.player.i].height, game.player.j as f32, ), rotation: Quat::from_rotation_y(-PI / 2.), ..default() }, SceneRoot( asset_server .load(GltfAssetLabel::Scene(0).from_asset("models/AlienCake/alien.glb")), ), )) .id(), ); // load the scene for the cake game.bonus.handle = asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/AlienCake/cakeBirthday.glb")); // scoreboard commands.spawn(( DespawnOnExit(GameState::Playing), Text::new("Score:"), TextFont { font_size: 33.0, ..default() }, TextColor(Color::srgb(0.5, 0.5, 1.0)), Node { position_type: PositionType::Absolute, top: px(5), left: px(5), ..default() }, )); commands.insert_resource(Random(rng)); } // control the game character fn move_player( mut commands: Commands, keyboard_input: Res<ButtonInput<KeyCode>>, mut game: ResMut<Game>, mut transforms: Query<&mut Transform>, time: Res<Time>, ) { if game.player.move_cooldown.tick(time.delta()).is_finished() { let mut moved = false; let mut rotation = 0.0; if keyboard_input.pressed(KeyCode::ArrowUp) { if game.player.i < BOARD_SIZE_I - 1 { game.player.i += 1; } rotation = -PI / 2.; moved = true; } if keyboard_input.pressed(KeyCode::ArrowDown) { if game.player.i > 0 { game.player.i -= 1; } rotation = PI / 2.; moved = true; } if keyboard_input.pressed(KeyCode::ArrowRight) { if game.player.j < BOARD_SIZE_J - 1 { game.player.j += 1; } rotation = PI; moved = true; } if keyboard_input.pressed(KeyCode::ArrowLeft) { if game.player.j > 0 { game.player.j -= 1; } rotation = 0.0; moved = true; } // move on the board if moved { game.player.move_cooldown.reset(); *transforms.get_mut(game.player.entity.unwrap()).unwrap() = Transform { translation: Vec3::new( game.player.i as f32, game.board[game.player.j][game.player.i].height, game.player.j as f32, ), rotation: Quat::from_rotation_y(rotation), ..default() }; } } // eat the cake! if let Some(entity) = game.bonus.entity && game.player.i == game.bonus.i && game.player.j == game.bonus.j { game.score += 2; game.cake_eaten += 1; commands.entity(entity).despawn(); game.bonus.entity = None; } } // change the focus of the camera fn focus_camera( time: Res<Time>, mut game: ResMut<Game>, mut transforms: ParamSet<(Query<&mut Transform, With<Camera3d>>, Query<&Transform>)>, ) { const SPEED: f32 = 2.0; // if there is both a player and a bonus, target the mid-point of them if let (Some(player_entity), Some(bonus_entity)) = (game.player.entity, game.bonus.entity) { let transform_query = transforms.p1(); if let (Ok(player_transform), Ok(bonus_transform)) = ( transform_query.get(player_entity), transform_query.get(bonus_entity), ) { game.camera_should_focus = player_transform .translation .lerp(bonus_transform.translation, 0.5); } // otherwise, if there is only a player, target the player } else if let Some(player_entity) = game.player.entity { if let Ok(player_transform) = transforms.p1().get(player_entity) { game.camera_should_focus = player_transform.translation; } // otherwise, target the middle } else { game.camera_should_focus = Vec3::from(RESET_FOCUS); } // calculate the camera motion based on the difference between where the camera is looking // and where it should be looking; the greater the distance, the faster the motion; // smooth out the camera movement using the frame time let mut camera_motion = game.camera_should_focus - game.camera_is_focus; if camera_motion.length() > 0.2 { camera_motion *= SPEED * time.delta_secs(); // set the new camera's actual focus game.camera_is_focus += camera_motion; } // look at that new camera's actual focus for mut transform in transforms.p0().iter_mut() { *transform = transform.looking_at(game.camera_is_focus, Vec3::Y); } } // despawn the bonus if there is one, then spawn a new one at a random location fn spawn_bonus( time: Res<Time>, mut timer: ResMut<BonusSpawnTimer>, mut next_state: ResMut<NextState<GameState>>, mut commands: Commands, mut game: ResMut<Game>, mut rng: ResMut<Random>, ) { // make sure we wait enough time before spawning the next cake if !timer.0.tick(time.delta()).is_finished() { return; } if let Some(entity) = game.bonus.entity { game.score -= 3; commands.entity(entity).despawn(); game.bonus.entity = None; if game.score <= -5 { next_state.set(GameState::GameOver); return; } } // ensure bonus doesn't spawn on the player loop { game.bonus.i = rng.random_range(0..BOARD_SIZE_I); game.bonus.j = rng.random_range(0..BOARD_SIZE_J); if game.bonus.i != game.player.i || game.bonus.j != game.player.j { break; } } game.bonus.entity = Some( commands .spawn(( DespawnOnExit(GameState::Playing), Transform::from_xyz( game.bonus.i as f32, game.board[game.bonus.j][game.bonus.i].height + 0.2, game.bonus.j as f32, ), SceneRoot(game.bonus.handle.clone()), children![( PointLight { color: Color::srgb(1.0, 1.0, 0.0), intensity: 500_000.0, range: 10.0, ..default() }, Transform::from_xyz(0.0, 2.0, 0.0), )], )) .id(), ); } // let the cake turn on itself fn rotate_bonus(game: Res<Game>, time: Res<Time>, mut transforms: Query<&mut Transform>) { if let Some(entity) = game.bonus.entity && let Ok(mut cake_transform) = transforms.get_mut(entity) { cake_transform.rotate_y(time.delta_secs()); cake_transform.scale = Vec3::splat(1.0 + (game.score as f32 / 10.0 * ops::sin(time.elapsed_secs())).abs()); } } // update the score displayed during the game fn scoreboard_system(game: Res<Game>, mut display: Single<&mut Text>) { display.0 = format!("Sugar Rush: {}", game.score); } // restart the game when pressing spacebar fn game_over_keyboard( mut next_state: ResMut<NextState<GameState>>, keyboard_input: Res<ButtonInput<KeyCode>>, ) { if keyboard_input.just_pressed(KeyCode::Space) { next_state.set(GameState::Playing); } } // display the number of cake eaten before losing fn display_score(mut commands: Commands, game: Res<Game>) { commands.spawn(( DespawnOnExit(GameState::GameOver), Node { width: percent(100), align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..default() }, children![( Text::new(format!("Cake eaten: {}", game.cake_eaten)), TextFont { font_size: 67.0, ..default() }, TextColor(Color::srgb(0.5, 0.5, 1.0)), )], )); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/games/loading_screen.rs
examples/games/loading_screen.rs
//! Shows how to create a loading screen that waits for assets to load and render. use bevy::{ecs::system::SystemId, prelude::*}; use pipelines_ready::*; // The way we'll go about doing this in this example is to // keep track of all assets that we want to have loaded before // we transition to the desired scene. // // In order to ensure that visual assets are fully rendered // before transitioning to the scene, we need to get the // current status of cached pipelines. // // While loading and pipelines compilation is happening, we // will show a loading screen. Once loading is complete, we // will transition to the scene we just loaded. fn main() { App::new() .add_plugins(DefaultPlugins) // `PipelinesReadyPlugin` is declared in the `pipelines_ready` module below. .add_plugins(PipelinesReadyPlugin) .insert_resource(LoadingState::default()) .insert_resource(LoadingData::new(5)) .add_systems(Startup, (setup, load_loading_screen)) .add_systems( Update, (update_loading_data, level_selection, display_loading_screen), ) .run(); } // A `Resource` that holds the current loading state. #[derive(Resource, Default)] enum LoadingState { #[default] LevelReady, LevelLoading, } // A resource that holds the current loading data. #[derive(Resource, Debug, Default)] struct LoadingData { // This will hold the currently unloaded/loading assets. loading_assets: Vec<UntypedHandle>, // Number of frames that everything needs to be ready for. // This is to prevent going into the fully loaded state in instances // where there might be a some frames between certain loading/pipelines action. confirmation_frames_target: usize, // Current number of confirmation frames. confirmation_frames_count: usize, } impl LoadingData { fn new(confirmation_frames_target: usize) -> Self { Self { loading_assets: Vec::new(), confirmation_frames_target, confirmation_frames_count: 0, } } } // This resource will hold the level related systems ID for later use. #[derive(Resource)] struct LevelData { unload_level_id: SystemId, level_1_id: SystemId, level_2_id: SystemId, } fn setup(mut commands: Commands) { let level_data = LevelData { unload_level_id: commands.register_system(unload_current_level), level_1_id: commands.register_system(load_level_1), level_2_id: commands.register_system(load_level_2), }; commands.insert_resource(level_data); // Spawns the UI that will show the user prompts. let text_style = TextFont { font_size: 42.0, ..default() }; commands .spawn(( Node { justify_self: JustifySelf::Center, align_self: AlignSelf::FlexEnd, ..default() }, BackgroundColor(Color::NONE), )) .with_child((Text::new("Press 1 or 2 to load a new scene."), text_style)); } // Selects the level you want to load. fn level_selection( mut commands: Commands, keyboard: Res<ButtonInput<KeyCode>>, level_data: Res<LevelData>, loading_state: Res<LoadingState>, ) { // Only trigger a load if the current level is fully loaded. if let LoadingState::LevelReady = loading_state.as_ref() { if keyboard.just_pressed(KeyCode::Digit1) { commands.run_system(level_data.unload_level_id); commands.run_system(level_data.level_1_id); } else if keyboard.just_pressed(KeyCode::Digit2) { commands.run_system(level_data.unload_level_id); commands.run_system(level_data.level_2_id); } } } // Marker component for easier deletion of entities. #[derive(Component)] struct LevelComponents; // Removes all currently loaded level assets from the game World. fn unload_current_level( mut commands: Commands, mut loading_state: ResMut<LoadingState>, entities: Query<Entity, With<LevelComponents>>, ) { *loading_state = LoadingState::LevelLoading; for entity in entities.iter() { commands.entity(entity).despawn(); } } fn load_level_1( mut commands: Commands, mut loading_data: ResMut<LoadingData>, asset_server: Res<AssetServer>, ) { // Spawn the camera. commands.spawn(( Camera3d::default(), Transform::from_xyz(155.0, 155.0, 155.0).looking_at(Vec3::new(0.0, 40.0, 0.0), Vec3::Y), LevelComponents, )); // Save the asset into the `loading_assets` vector. let fox = asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/animated/Fox.glb")); loading_data.loading_assets.push(fox.clone().into()); // Spawn the fox. commands.spawn(( SceneRoot(fox.clone()), Transform::from_xyz(0.0, 0.0, 0.0), LevelComponents, )); // Spawn the light. commands.spawn(( DirectionalLight { shadows_enabled: true, ..default() }, Transform::from_xyz(3.0, 3.0, 2.0).looking_at(Vec3::ZERO, Vec3::Y), LevelComponents, )); } fn load_level_2( mut commands: Commands, mut loading_data: ResMut<LoadingData>, asset_server: Res<AssetServer>, ) { // Spawn the camera. commands.spawn(( Camera3d::default(), Transform::from_xyz(1.0, 1.0, 1.0).looking_at(Vec3::new(0.0, 0.2, 0.0), Vec3::Y), LevelComponents, )); // Spawn the helmet. let helmet_scene = asset_server .load(GltfAssetLabel::Scene(0).from_asset("models/FlightHelmet/FlightHelmet.gltf")); loading_data .loading_assets .push(helmet_scene.clone().into()); commands.spawn((SceneRoot(helmet_scene.clone()), LevelComponents)); // Spawn the light. commands.spawn(( DirectionalLight { shadows_enabled: true, ..default() }, Transform::from_xyz(3.0, 3.0, 2.0).looking_at(Vec3::ZERO, Vec3::Y), LevelComponents, )); } // Monitors current loading status of assets. fn update_loading_data( mut loading_data: ResMut<LoadingData>, mut loading_state: ResMut<LoadingState>, asset_server: Res<AssetServer>, pipelines_ready: Res<PipelinesReady>, ) { if !loading_data.loading_assets.is_empty() || !pipelines_ready.0 { // If we are still loading assets / pipelines are not fully compiled, // we reset the confirmation frame count. loading_data.confirmation_frames_count = 0; loading_data.loading_assets.retain(|asset| { asset_server .get_recursive_dependency_load_state(asset) .is_none_or(|state| !state.is_loaded()) }); // If there are no more assets being monitored, and pipelines // are compiled, then start counting confirmation frames. // Once enough confirmations have passed, everything will be // considered to be fully loaded. } else { loading_data.confirmation_frames_count += 1; if loading_data.confirmation_frames_count == loading_data.confirmation_frames_target { *loading_state = LoadingState::LevelReady; } } } // Marker tag for loading screen components. #[derive(Component)] struct LoadingScreen; // Spawns the necessary components for the loading screen. fn load_loading_screen(mut commands: Commands) { let text_style = TextFont { font_size: 67.0, ..default() }; // Spawn the UI and Loading screen camera. commands.spawn(( Camera2d, Camera { order: 1, ..default() }, LoadingScreen, )); // Spawn the UI that will make up the loading screen. commands .spawn(( Node { height: percent(100), width: percent(100), justify_content: JustifyContent::Center, align_items: AlignItems::Center, ..default() }, BackgroundColor(Color::BLACK), LoadingScreen, )) .with_child((Text::new("Loading..."), text_style.clone())); } // Determines when to show the loading screen fn display_loading_screen( mut loading_screen: Single<&mut Visibility, (With<LoadingScreen>, With<Node>)>, loading_state: Res<LoadingState>, ) { let visibility = match loading_state.as_ref() { LoadingState::LevelLoading => Visibility::Visible, LoadingState::LevelReady => Visibility::Hidden, }; **loading_screen = visibility; } mod pipelines_ready { use bevy::{ prelude::*, render::{render_resource::*, *}, }; pub struct PipelinesReadyPlugin; impl Plugin for PipelinesReadyPlugin { fn build(&self, app: &mut App) { app.insert_resource(PipelinesReady::default()); // In order to gain access to the pipelines status, we have to // go into the `RenderApp`, grab the resource from the main App // and then update the pipelines status from there. // Writing between these Apps can only be done through the // `ExtractSchedule`. app.sub_app_mut(RenderApp) .add_systems(ExtractSchedule, update_pipelines_ready); } } #[derive(Resource, Debug, Default)] pub struct PipelinesReady(pub bool); fn update_pipelines_ready(mut main_world: ResMut<MainWorld>, pipelines: Res<PipelineCache>) { if let Some(mut pipelines_ready) = main_world.get_resource_mut::<PipelinesReady>() { pipelines_ready.0 = pipelines.waiting_pipelines().count() == 0; } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/games/contributors.rs
examples/games/contributors.rs
//! This example displays each contributor to the bevy source code as a bouncing bevy-ball. use bevy::{math::bounding::Aabb2d, prelude::*}; use rand::{Rng, SeedableRng}; use rand_chacha::ChaCha8Rng; use std::{ collections::HashMap, env::VarError, hash::{DefaultHasher, Hash, Hasher}, io::{self, BufRead, BufReader}, process::Stdio, }; fn main() { App::new() .add_plugins(DefaultPlugins) .init_resource::<SelectionTimer>() .init_resource::<SharedRng>() .add_systems(Startup, (setup_contributor_selection, setup)) // Systems are chained for determinism only .add_systems(Update, (gravity, movement, collisions, selection).chain()) .run(); } type Contributors = Vec<(String, usize)>; #[derive(Resource)] struct ContributorSelection { order: Vec<Entity>, idx: usize, } #[derive(Resource)] struct SelectionTimer(Timer); impl Default for SelectionTimer { fn default() -> Self { Self(Timer::from_seconds( SHOWCASE_TIMER_SECS, TimerMode::Repeating, )) } } #[derive(Component)] struct ContributorDisplay; #[derive(Component)] struct Contributor { name: String, num_commits: usize, hue: f32, } #[derive(Component)] struct Velocity { translation: Vec3, rotation: f32, } // We're using a shared seeded RNG here to make this example deterministic for testing purposes. // This isn't strictly required in practical use unless you need your app to be deterministic. #[derive(Resource, Deref, DerefMut)] struct SharedRng(ChaCha8Rng); impl Default for SharedRng { fn default() -> Self { Self(ChaCha8Rng::seed_from_u64(10223163112)) } } const GRAVITY: f32 = 9.821 * 100.0; const SPRITE_SIZE: f32 = 75.0; const SELECTED: Hsla = Hsla::hsl(0.0, 0.9, 0.7); const DESELECTED: Hsla = Hsla::new(0.0, 0.3, 0.2, 0.92); const SELECTED_Z_OFFSET: f32 = 100.0; const SHOWCASE_TIMER_SECS: f32 = 3.0; const CONTRIBUTORS_LIST: &[&str] = &["Carter Anderson", "And Many More"]; fn setup_contributor_selection( mut commands: Commands, asset_server: Res<AssetServer>, mut rng: ResMut<SharedRng>, ) { let contribs = contributors_or_fallback(); let texture_handle = asset_server.load("branding/icon.png"); let mut contributor_selection = ContributorSelection { order: Vec::with_capacity(contribs.len()), idx: 0, }; for (name, num_commits) in contribs { let transform = Transform::from_xyz( rng.random_range(-400.0..400.0), rng.random_range(0.0..400.0), rng.random(), ); let dir = rng.random_range(-1.0..1.0); let velocity = Vec3::new(dir * 500.0, 0.0, 0.0); let hue = name_to_hue(&name); // Some sprites should be flipped for variety let flipped = rng.random(); let entity = commands .spawn(( Contributor { name, num_commits, hue, }, Velocity { translation: velocity, rotation: -dir * 5.0, }, Sprite { image: texture_handle.clone(), custom_size: Some(Vec2::splat(SPRITE_SIZE)), color: DESELECTED.with_hue(hue).into(), flip_x: flipped, ..default() }, transform, )) .id(); contributor_selection.order.push(entity); } commands.insert_resource(contributor_selection); } fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn(Camera2d); let text_style = TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), font_size: 60.0, ..default() }; commands .spawn(( Text::new("Contributor showcase"), text_style.clone(), ContributorDisplay, Node { position_type: PositionType::Absolute, top: px(12), left: px(12), ..default() }, )) .with_child(( TextSpan::default(), TextFont { font_size: 30., ..text_style }, )); } /// Finds the next contributor to display and selects the entity fn selection( mut timer: ResMut<SelectionTimer>, mut contributor_selection: ResMut<ContributorSelection>, contributor_root: Single<Entity, (With<ContributorDisplay>, With<Text>)>, mut query: Query<(&Contributor, &mut Sprite, &mut Transform)>, mut writer: TextUiWriter, time: Res<Time>, ) { if !timer.0.tick(time.delta()).just_finished() { return; } // Deselect the previous contributor let entity = contributor_selection.order[contributor_selection.idx]; if let Ok((contributor, mut sprite, mut transform)) = query.get_mut(entity) { deselect(&mut sprite, contributor, &mut transform); } // Select the next contributor if (contributor_selection.idx + 1) < contributor_selection.order.len() { contributor_selection.idx += 1; } else { contributor_selection.idx = 0; } let entity = contributor_selection.order[contributor_selection.idx]; if let Ok((contributor, mut sprite, mut transform)) = query.get_mut(entity) { let entity = *contributor_root; select( &mut sprite, contributor, &mut transform, entity, &mut writer, ); } } /// Change the tint color to the "selected" color, bring the object to the front /// and display the name. fn select( sprite: &mut Sprite, contributor: &Contributor, transform: &mut Transform, entity: Entity, writer: &mut TextUiWriter, ) { sprite.color = SELECTED.with_hue(contributor.hue).into(); transform.translation.z += SELECTED_Z_OFFSET; writer.text(entity, 0).clone_from(&contributor.name); *writer.text(entity, 1) = format!( "\n{} commit{}", contributor.num_commits, if contributor.num_commits > 1 { "s" } else { "" } ); writer.color(entity, 0).0 = sprite.color; } /// Change the tint color to the "deselected" color and push /// the object to the back. fn deselect(sprite: &mut Sprite, contributor: &Contributor, transform: &mut Transform) { sprite.color = DESELECTED.with_hue(contributor.hue).into(); transform.translation.z -= SELECTED_Z_OFFSET; } /// Applies gravity to all entities with a velocity. fn gravity(time: Res<Time>, mut velocity_query: Query<&mut Velocity>) { let delta = time.delta_secs(); for mut velocity in &mut velocity_query { velocity.translation.y -= GRAVITY * delta; } } /// Checks for collisions of contributor-birbs. /// /// On collision with left-or-right wall it resets the horizontal /// velocity. On collision with the ground it applies an upwards /// force. fn collisions( window: Query<&Window>, mut query: Query<(&mut Velocity, &mut Transform), With<Contributor>>, mut rng: ResMut<SharedRng>, ) { let Ok(window) = window.single() else { return; }; let window_size = window.size(); let collision_area = Aabb2d::new(Vec2::ZERO, (window_size - SPRITE_SIZE) / 2.); // The maximum height the birbs should try to reach is one birb below the top of the window. let max_bounce_height = (window_size.y - SPRITE_SIZE * 2.0).max(0.0); let min_bounce_height = max_bounce_height * 0.4; for (mut velocity, mut transform) in &mut query { // Clamp the translation to not go out of the bounds if transform.translation.y < collision_area.min.y { transform.translation.y = collision_area.min.y; // How high this birb will bounce. let bounce_height = rng.random_range(min_bounce_height..=max_bounce_height); // Apply the velocity that would bounce the birb up to bounce_height. velocity.translation.y = (bounce_height * GRAVITY * 2.).sqrt(); } // Birbs might hit the ceiling if the window is resized. // If they do, bounce them. if transform.translation.y > collision_area.max.y { transform.translation.y = collision_area.max.y; velocity.translation.y *= -1.0; } // On side walls flip the horizontal velocity if transform.translation.x < collision_area.min.x { transform.translation.x = collision_area.min.x; velocity.translation.x *= -1.0; velocity.rotation *= -1.0; } if transform.translation.x > collision_area.max.x { transform.translation.x = collision_area.max.x; velocity.translation.x *= -1.0; velocity.rotation *= -1.0; } } } /// Apply velocity to positions and rotations. fn movement(time: Res<Time>, mut query: Query<(&Velocity, &mut Transform)>) { let delta = time.delta_secs(); for (velocity, mut transform) in &mut query { transform.translation += delta * velocity.translation; transform.rotate_z(velocity.rotation * delta); } } #[derive(Debug, thiserror::Error)] enum LoadContributorsError { #[error("An IO error occurred while reading the git log.")] Io(#[from] io::Error), #[error("The CARGO_MANIFEST_DIR environment variable was not set.")] Var(#[from] VarError), #[error("The git process did not return a stdout handle.")] Stdout, } /// Get the names and commit counts of all contributors from the git log. /// /// This function only works if `git` is installed and /// the program is run through `cargo`. fn contributors() -> Result<Contributors, LoadContributorsError> { let manifest_dir = std::env::var("CARGO_MANIFEST_DIR")?; let mut cmd = std::process::Command::new("git") .args(["--no-pager", "log", "--pretty=format:%an"]) .current_dir(manifest_dir) .stdout(Stdio::piped()) .spawn()?; let stdout = cmd.stdout.take().ok_or(LoadContributorsError::Stdout)?; // Take the list of commit author names and collect them into a HashMap, // keeping a count of how many commits they authored. let contributors = BufReader::new(stdout).lines().map_while(Result::ok).fold( HashMap::new(), |mut acc, word| { *acc.entry(word).or_insert(0) += 1; acc }, ); Ok(contributors.into_iter().collect()) } /// Get the contributors list, or fall back to a default value if /// it's unavailable or we're in CI fn contributors_or_fallback() -> Contributors { let get_default = || { CONTRIBUTORS_LIST .iter() .cycle() .take(1000) .map(|name| (name.to_string(), 1)) .collect() }; if cfg!(feature = "bevy_ci_testing") { return get_default(); } contributors().unwrap_or_else(|_| get_default()) } /// Give each unique contributor name a particular hue that is stable between runs. fn name_to_hue(s: &str) -> f32 { let mut hasher = DefaultHasher::new(); s.hash(&mut hasher); hasher.finish() as f32 / u64::MAX as f32 * 360. }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/games/game_menu.rs
examples/games/game_menu.rs
//! This example will display a simple menu using Bevy UI where you can start a new game, //! change some settings or quit. There is no actual game, it will just display the current //! settings for 5 seconds before going back to the menu. use bevy::prelude::*; const TEXT_COLOR: Color = Color::srgb(0.9, 0.9, 0.9); // Enum that will be used as a global state for the game #[derive(Clone, Copy, Default, Eq, PartialEq, Debug, Hash, States)] enum GameState { #[default] Splash, Menu, Game, } // One of the two settings that can be set through the menu. It will be a resource in the app #[derive(Resource, Debug, Component, PartialEq, Eq, Clone, Copy)] enum DisplayQuality { Low, Medium, High, } // One of the two settings that can be set through the menu. It will be a resource in the app #[derive(Resource, Debug, Component, PartialEq, Eq, Clone, Copy)] struct Volume(u32); fn main() { App::new() .add_plugins(DefaultPlugins) // Insert as resource the initial value for the settings resources .insert_resource(DisplayQuality::Medium) .insert_resource(Volume(7)) // Declare the game state, whose starting value is determined by the `Default` trait .init_state::<GameState>() .add_systems(Startup, setup) // Adds the plugins for each state .add_plugins((splash::splash_plugin, menu::menu_plugin, game::game_plugin)) .run(); } fn setup(mut commands: Commands) { commands.spawn(Camera2d); } mod splash { use bevy::prelude::*; use super::GameState; // This plugin will display a splash screen with Bevy logo for 1 second before switching to the menu pub fn splash_plugin(app: &mut App) { // As this plugin is managing the splash screen, it will focus on the state `GameState::Splash` app // When entering the state, spawn everything needed for this screen .add_systems(OnEnter(GameState::Splash), splash_setup) // While in this state, run the `countdown` system .add_systems(Update, countdown.run_if(in_state(GameState::Splash))); } // Tag component used to tag entities added on the splash screen #[derive(Component)] struct OnSplashScreen; // Newtype to use a `Timer` for this screen as a resource #[derive(Resource, Deref, DerefMut)] struct SplashTimer(Timer); fn splash_setup(mut commands: Commands, asset_server: Res<AssetServer>) { let icon = asset_server.load("branding/icon.png"); // Display the logo commands.spawn(( // This entity will be despawned when exiting the state DespawnOnExit(GameState::Splash), Node { align_items: AlignItems::Center, justify_content: JustifyContent::Center, width: percent(100), height: percent(100), ..default() }, OnSplashScreen, children![( ImageNode::new(icon), Node { // This will set the logo to be 200px wide, and auto adjust its height width: px(200), ..default() }, )], )); // Insert the timer as a resource commands.insert_resource(SplashTimer(Timer::from_seconds(1.0, TimerMode::Once))); } // Tick the timer, and change state when finished fn countdown( mut game_state: ResMut<NextState<GameState>>, time: Res<Time>, mut timer: ResMut<SplashTimer>, ) { if timer.tick(time.delta()).is_finished() { game_state.set(GameState::Menu); } } } mod game { use bevy::{ color::palettes::basic::{BLUE, LIME}, prelude::*, }; use super::{DisplayQuality, GameState, Volume, TEXT_COLOR}; // This plugin will contain the game. In this case, it's just be a screen that will // display the current settings for 5 seconds before returning to the menu pub fn game_plugin(app: &mut App) { app.add_systems(OnEnter(GameState::Game), game_setup) .add_systems(Update, game.run_if(in_state(GameState::Game))); } // Tag component used to tag entities added on the game screen #[derive(Component)] struct OnGameScreen; #[derive(Resource, Deref, DerefMut)] struct GameTimer(Timer); fn game_setup( mut commands: Commands, display_quality: Res<DisplayQuality>, volume: Res<Volume>, ) { commands.spawn(( DespawnOnExit(GameState::Game), Node { width: percent(100), height: percent(100), // center children align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..default() }, OnGameScreen, children![( Node { // This will display its children in a column, from top to bottom flex_direction: FlexDirection::Column, // `align_items` will align children on the cross axis. Here the main axis is // vertical (column), so the cross axis is horizontal. This will center the // children align_items: AlignItems::Center, ..default() }, BackgroundColor(Color::BLACK), children![ ( Text::new("Will be back to the menu shortly..."), TextFont { font_size: 67.0, ..default() }, TextColor(TEXT_COLOR), Node { margin: UiRect::all(px(50)), ..default() }, ), ( Text::default(), Node { margin: UiRect::all(px(50)), ..default() }, children![ ( TextSpan(format!("quality: {:?}", *display_quality)), TextFont { font_size: 50.0, ..default() }, TextColor(BLUE.into()), ), ( TextSpan::new(" - "), TextFont { font_size: 50.0, ..default() }, TextColor(TEXT_COLOR), ), ( TextSpan(format!("volume: {:?}", *volume)), TextFont { font_size: 50.0, ..default() }, TextColor(LIME.into()), ), ] ), ] )], )); // Spawn a 5 seconds timer to trigger going back to the menu commands.insert_resource(GameTimer(Timer::from_seconds(5.0, TimerMode::Once))); } // Tick the timer, and change state when finished fn game( time: Res<Time>, mut game_state: ResMut<NextState<GameState>>, mut timer: ResMut<GameTimer>, ) { if timer.tick(time.delta()).is_finished() { game_state.set(GameState::Menu); } } } mod menu { use bevy::{ app::AppExit, color::palettes::css::CRIMSON, ecs::spawn::{SpawnIter, SpawnWith}, prelude::*, }; use super::{DisplayQuality, GameState, Volume, TEXT_COLOR}; // This plugin manages the menu, with 5 different screens: // - a main menu with "New Game", "Settings", "Quit" // - a settings menu with two submenus and a back button // - two settings screen with a setting that can be set and a back button pub fn menu_plugin(app: &mut App) { app // At start, the menu is not enabled. This will be changed in `menu_setup` when // entering the `GameState::Menu` state. // Current screen in the menu is handled by an independent state from `GameState` .init_state::<MenuState>() .add_systems(OnEnter(GameState::Menu), menu_setup) // Systems to handle the main menu screen .add_systems(OnEnter(MenuState::Main), main_menu_setup) // Systems to handle the settings menu screen .add_systems(OnEnter(MenuState::Settings), settings_menu_setup) // Systems to handle the display settings screen .add_systems( OnEnter(MenuState::SettingsDisplay), display_settings_menu_setup, ) .add_systems( Update, (setting_button::<DisplayQuality>.run_if(in_state(MenuState::SettingsDisplay)),), ) // Systems to handle the sound settings screen .add_systems(OnEnter(MenuState::SettingsSound), sound_settings_menu_setup) .add_systems( Update, setting_button::<Volume>.run_if(in_state(MenuState::SettingsSound)), ) // Common systems to all screens that handles buttons behavior .add_systems( Update, (menu_action, button_system).run_if(in_state(GameState::Menu)), ); } // State used for the current menu screen #[derive(Clone, Copy, Default, Eq, PartialEq, Debug, Hash, States)] enum MenuState { Main, Settings, SettingsDisplay, SettingsSound, #[default] Disabled, } // Tag component used to tag entities added on the main menu screen #[derive(Component)] struct OnMainMenuScreen; // Tag component used to tag entities added on the settings menu screen #[derive(Component)] struct OnSettingsMenuScreen; // Tag component used to tag entities added on the display settings menu screen #[derive(Component)] struct OnDisplaySettingsMenuScreen; // Tag component used to tag entities added on the sound settings menu screen #[derive(Component)] struct OnSoundSettingsMenuScreen; const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15); const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25); const HOVERED_PRESSED_BUTTON: Color = Color::srgb(0.25, 0.65, 0.25); const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35); // Tag component used to mark which setting is currently selected #[derive(Component)] struct SelectedOption; // All actions that can be triggered from a button click #[derive(Component)] enum MenuButtonAction { Play, Settings, SettingsDisplay, SettingsSound, BackToMainMenu, BackToSettings, Quit, } // This system handles changing all buttons color based on mouse interaction fn button_system( mut interaction_query: Query< (&Interaction, &mut BackgroundColor, Option<&SelectedOption>), (Changed<Interaction>, With<Button>), >, ) { for (interaction, mut background_color, selected) in &mut interaction_query { *background_color = match (*interaction, selected) { (Interaction::Pressed, _) | (Interaction::None, Some(_)) => PRESSED_BUTTON.into(), (Interaction::Hovered, Some(_)) => HOVERED_PRESSED_BUTTON.into(), (Interaction::Hovered, None) => HOVERED_BUTTON.into(), (Interaction::None, None) => NORMAL_BUTTON.into(), } } } // This system updates the settings when a new value for a setting is selected, and marks // the button as the one currently selected fn setting_button<T: Resource + Component + PartialEq + Copy>( interaction_query: Query<(&Interaction, &T, Entity), (Changed<Interaction>, With<Button>)>, selected_query: Single<(Entity, &mut BackgroundColor), With<SelectedOption>>, mut commands: Commands, mut setting: ResMut<T>, ) { let (previous_button, mut previous_button_color) = selected_query.into_inner(); for (interaction, button_setting, entity) in &interaction_query { if *interaction == Interaction::Pressed && *setting != *button_setting { *previous_button_color = NORMAL_BUTTON.into(); commands.entity(previous_button).remove::<SelectedOption>(); commands.entity(entity).insert(SelectedOption); *setting = *button_setting; } } } fn menu_setup(mut menu_state: ResMut<NextState<MenuState>>) { menu_state.set(MenuState::Main); } fn main_menu_setup(mut commands: Commands, asset_server: Res<AssetServer>) { // Common style for all buttons on the screen let button_node = Node { width: px(300), height: px(65), margin: UiRect::all(px(20)), justify_content: JustifyContent::Center, align_items: AlignItems::Center, ..default() }; let button_icon_node = Node { width: px(30), // This takes the icons out of the flexbox flow, to be positioned exactly position_type: PositionType::Absolute, // The icon will be close to the left border of the button left: px(10), ..default() }; let button_text_font = TextFont { font_size: 33.0, ..default() }; let right_icon = asset_server.load("textures/Game Icons/right.png"); let wrench_icon = asset_server.load("textures/Game Icons/wrench.png"); let exit_icon = asset_server.load("textures/Game Icons/exitRight.png"); commands.spawn(( DespawnOnExit(MenuState::Main), Node { width: percent(100), height: percent(100), align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..default() }, OnMainMenuScreen, children![( Node { flex_direction: FlexDirection::Column, align_items: AlignItems::Center, ..default() }, BackgroundColor(CRIMSON.into()), children![ // Display the game name ( Text::new("Bevy Game Menu UI"), TextFont { font_size: 67.0, ..default() }, TextColor(TEXT_COLOR), Node { margin: UiRect::all(px(50)), ..default() }, ), // Display three buttons for each action available from the main menu: // - new game // - settings // - quit ( Button, button_node.clone(), BackgroundColor(NORMAL_BUTTON), MenuButtonAction::Play, children![ (ImageNode::new(right_icon), button_icon_node.clone()), ( Text::new("New Game"), button_text_font.clone(), TextColor(TEXT_COLOR), ), ] ), ( Button, button_node.clone(), BackgroundColor(NORMAL_BUTTON), MenuButtonAction::Settings, children![ (ImageNode::new(wrench_icon), button_icon_node.clone()), ( Text::new("Settings"), button_text_font.clone(), TextColor(TEXT_COLOR), ), ] ), ( Button, button_node, BackgroundColor(NORMAL_BUTTON), MenuButtonAction::Quit, children![ (ImageNode::new(exit_icon), button_icon_node), (Text::new("Quit"), button_text_font, TextColor(TEXT_COLOR),), ] ), ] )], )); } fn settings_menu_setup(mut commands: Commands) { let button_node = Node { width: px(200), height: px(65), margin: UiRect::all(px(20)), justify_content: JustifyContent::Center, align_items: AlignItems::Center, ..default() }; let button_text_style = ( TextFont { font_size: 33.0, ..default() }, TextColor(TEXT_COLOR), ); commands.spawn(( DespawnOnExit(MenuState::Settings), Node { width: percent(100), height: percent(100), align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..default() }, OnSettingsMenuScreen, children![( Node { flex_direction: FlexDirection::Column, align_items: AlignItems::Center, ..default() }, BackgroundColor(CRIMSON.into()), Children::spawn(SpawnIter( [ (MenuButtonAction::SettingsDisplay, "Display"), (MenuButtonAction::SettingsSound, "Sound"), (MenuButtonAction::BackToMainMenu, "Back"), ] .into_iter() .map(move |(action, text)| { ( Button, button_node.clone(), BackgroundColor(NORMAL_BUTTON), action, children![(Text::new(text), button_text_style.clone())], ) }) )) )], )); } fn display_settings_menu_setup(mut commands: Commands, display_quality: Res<DisplayQuality>) { fn button_node() -> Node { Node { width: px(200), height: px(65), margin: UiRect::all(px(20)), justify_content: JustifyContent::Center, align_items: AlignItems::Center, ..default() } } fn button_text_style() -> impl Bundle { ( TextFont { font_size: 33.0, ..default() }, TextColor(TEXT_COLOR), ) } let display_quality = *display_quality; commands.spawn(( DespawnOnExit(MenuState::SettingsDisplay), Node { width: percent(100), height: percent(100), align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..default() }, OnDisplaySettingsMenuScreen, children![( Node { flex_direction: FlexDirection::Column, align_items: AlignItems::Center, ..default() }, BackgroundColor(CRIMSON.into()), children![ // Create a new `Node`, this time not setting its `flex_direction`. It will // use the default value, `FlexDirection::Row`, from left to right. ( Node { align_items: AlignItems::Center, ..default() }, BackgroundColor(CRIMSON.into()), Children::spawn(( // Display a label for the current setting Spawn((Text::new("Display Quality"), button_text_style())), SpawnWith(move |parent: &mut ChildSpawner| { for quality_setting in [ DisplayQuality::Low, DisplayQuality::Medium, DisplayQuality::High, ] { let mut entity = parent.spawn(( Button, Node { width: px(150), height: px(65), ..button_node() }, BackgroundColor(NORMAL_BUTTON), quality_setting, children![( Text::new(format!("{quality_setting:?}")), button_text_style(), )], )); if display_quality == quality_setting { entity.insert(SelectedOption); } } }) )) ), // Display the back button to return to the settings screen ( Button, button_node(), BackgroundColor(NORMAL_BUTTON), MenuButtonAction::BackToSettings, children![(Text::new("Back"), button_text_style())] ) ] )], )); } fn sound_settings_menu_setup(mut commands: Commands, volume: Res<Volume>) { let button_node = Node { width: px(200), height: px(65), margin: UiRect::all(px(20)), justify_content: JustifyContent::Center, align_items: AlignItems::Center, ..default() }; let button_text_style = ( TextFont { font_size: 33.0, ..default() }, TextColor(TEXT_COLOR), ); let volume = *volume; let button_node_clone = button_node.clone(); commands.spawn(( DespawnOnExit(MenuState::SettingsSound), Node { width: percent(100), height: percent(100), align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..default() }, OnSoundSettingsMenuScreen, children![( Node { flex_direction: FlexDirection::Column, align_items: AlignItems::Center, ..default() }, BackgroundColor(CRIMSON.into()), children![ ( Node { align_items: AlignItems::Center, ..default() }, BackgroundColor(CRIMSON.into()), Children::spawn(( Spawn((Text::new("Volume"), button_text_style.clone())), SpawnWith(move |parent: &mut ChildSpawner| { for volume_setting in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] { let mut entity = parent.spawn(( Button, Node { width: px(30), height: px(65), ..button_node_clone.clone() }, BackgroundColor(NORMAL_BUTTON), Volume(volume_setting), )); if volume == Volume(volume_setting) { entity.insert(SelectedOption); } } }) )) ), ( Button, button_node, BackgroundColor(NORMAL_BUTTON), MenuButtonAction::BackToSettings, children![(Text::new("Back"), button_text_style)] ) ] )], )); } fn menu_action( interaction_query: Query< (&Interaction, &MenuButtonAction), (Changed<Interaction>, With<Button>), >, mut app_exit_writer: MessageWriter<AppExit>, mut menu_state: ResMut<NextState<MenuState>>, mut game_state: ResMut<NextState<GameState>>, ) { for (interaction, menu_button_action) in &interaction_query { if *interaction == Interaction::Pressed { match menu_button_action { MenuButtonAction::Quit => { app_exit_writer.write(AppExit::Success); } MenuButtonAction::Play => { game_state.set(GameState::Game); menu_state.set(MenuState::Disabled); } MenuButtonAction::Settings => menu_state.set(MenuState::Settings), MenuButtonAction::SettingsDisplay => { menu_state.set(MenuState::SettingsDisplay); } MenuButtonAction::SettingsSound => { menu_state.set(MenuState::SettingsSound); } MenuButtonAction::BackToMainMenu => menu_state.set(MenuState::Main), MenuButtonAction::BackToSettings => { menu_state.set(MenuState::Settings); } } } } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/games/stepping.rs
examples/games/stepping.rs
use bevy::{app::MainScheduleOrder, ecs::schedule::*, prelude::*}; /// Independent [`Schedule`] for stepping systems. /// /// The stepping systems must run in their own schedule to be able to inspect /// all the other schedules in the [`App`]. This is because the currently /// executing schedule is removed from the [`Schedules`] resource while it is /// being run. #[derive(Debug, Hash, PartialEq, Eq, Clone, ScheduleLabel)] struct DebugSchedule; /// Plugin to add a stepping UI to an example #[derive(Default)] pub struct SteppingPlugin { schedule_labels: Vec<InternedScheduleLabel>, top: Val, left: Val, } impl SteppingPlugin { /// add a schedule to be stepped when stepping is enabled pub fn add_schedule(mut self, label: impl ScheduleLabel) -> SteppingPlugin { self.schedule_labels.push(label.intern()); self } /// Set the location of the stepping UI when activated pub fn at(self, left: Val, top: Val) -> SteppingPlugin { SteppingPlugin { top, left, ..self } } } impl Plugin for SteppingPlugin { fn build(&self, app: &mut App) { app.add_systems(Startup, build_stepping_hint); if cfg!(not(feature = "bevy_debug_stepping")) { return; } // create and insert our debug schedule into the main schedule order. // We need an independent schedule so we have access to all other // schedules through the `Stepping` resource app.init_schedule(DebugSchedule); let mut order = app.world_mut().resource_mut::<MainScheduleOrder>(); order.insert_after(Update, DebugSchedule); // create our stepping resource let mut stepping = Stepping::new(); for label in &self.schedule_labels { stepping.add_schedule(*label); } app.insert_resource(stepping); // add our startup & stepping systems app.insert_resource(State { ui_top: self.top, ui_left: self.left, systems: Vec::new(), }) .add_systems( DebugSchedule, ( build_ui.run_if(not(initialized)), handle_input, update_ui.run_if(initialized), ) .chain(), ); } } /// Struct for maintaining stepping state #[derive(Resource, Debug)] struct State { // vector of schedule/node id -> text index offset systems: Vec<(InternedScheduleLabel, NodeId, usize)>, // ui positioning ui_top: Val, ui_left: Val, } /// condition to check if the stepping UI has been constructed fn initialized(state: Res<State>) -> bool { !state.systems.is_empty() } const FONT_COLOR: Color = Color::srgb(0.2, 0.2, 0.2); const FONT_BOLD: &str = "fonts/FiraSans-Bold.ttf"; #[derive(Component)] struct SteppingUi; /// Construct the stepping UI elements from the [`Schedules`] resource. /// /// This system may run multiple times before constructing the UI as all of the /// data may not be available on the first run of the system. This happens if /// one of the stepping schedules has not yet been run. fn build_ui( mut commands: Commands, asset_server: Res<AssetServer>, schedules: Res<Schedules>, mut stepping: ResMut<Stepping>, mut state: ResMut<State>, ) { let mut text_spans = Vec::new(); let mut always_run: Vec<( bevy_ecs::intern::Interned<dyn ScheduleLabel + 'static>, NodeId, )> = Vec::new(); let Ok(schedule_order) = stepping.schedules() else { return; }; // go through the stepping schedules and construct a list of systems for // each label for label in schedule_order { let schedule = schedules.get(*label).unwrap(); text_spans.push(( TextSpan(format!("{label:?}\n")), TextFont { font: asset_server.load(FONT_BOLD).into(), ..default() }, TextColor(FONT_COLOR), )); // grab the list of systems in the schedule, in the order the // single-threaded executor would run them. let Ok(systems) = schedule.systems() else { return; }; for (key, system) in systems { // skip bevy default systems; we don't want to step those #[cfg(feature = "debug")] if system.name().as_string().starts_with("bevy") { always_run.push((*label, NodeId::System(key))); continue; } // Add an entry to our systems list so we can find where to draw // the cursor when the stepping cursor is at this system // we add plus 1 to account for the empty root span state .systems .push((*label, NodeId::System(key), text_spans.len() + 1)); // Add a text section for displaying the cursor for this system text_spans.push(( TextSpan::new(" "), TextFont::default(), TextColor(FONT_COLOR), )); // add the name of the system to the ui text_spans.push(( TextSpan(format!("{}\n", system.name())), TextFont::default(), TextColor(FONT_COLOR), )); } } for (label, node) in always_run.drain(..) { stepping.always_run_node(label, node); } commands.spawn(( Text::default(), SteppingUi, Node { position_type: PositionType::Absolute, top: state.ui_top, left: state.ui_left, padding: UiRect::all(px(10)), ..default() }, BackgroundColor(Color::srgba(1.0, 1.0, 1.0, 0.33)), Visibility::Hidden, Children::spawn(text_spans), )); } fn build_stepping_hint(mut commands: Commands) { let hint_text = if cfg!(feature = "bevy_debug_stepping") { "Press ` to toggle stepping mode (S: step system, Space: step frame)" } else { "Bevy was compiled without stepping support. Run with `--features=bevy_debug_stepping` to enable stepping." }; info!("{}", hint_text); // stepping description box commands.spawn(( Text::new(hint_text), TextFont { font_size: 15.0, ..default() }, TextColor(FONT_COLOR), Node { position_type: PositionType::Absolute, bottom: px(5), left: px(5), ..default() }, )); } fn handle_input(keyboard_input: Res<ButtonInput<KeyCode>>, mut stepping: ResMut<Stepping>) { if keyboard_input.just_pressed(KeyCode::Slash) { info!("{:#?}", stepping); } // grave key to toggle stepping mode for the FixedUpdate schedule if keyboard_input.just_pressed(KeyCode::Backquote) { if stepping.is_enabled() { stepping.disable(); debug!("disabled stepping"); } else { stepping.enable(); debug!("enabled stepping"); } } if !stepping.is_enabled() { return; } // space key will step the remainder of this frame if keyboard_input.just_pressed(KeyCode::Space) { debug!("continue"); stepping.continue_frame(); } else if keyboard_input.just_pressed(KeyCode::KeyS) { debug!("stepping frame"); stepping.step_frame(); } } fn update_ui( mut commands: Commands, state: Res<State>, stepping: Res<Stepping>, ui: Single<(Entity, &Visibility), With<SteppingUi>>, mut writer: TextUiWriter, ) { // ensure the UI is only visible when stepping is enabled let (ui, vis) = *ui; match (vis, stepping.is_enabled()) { (Visibility::Hidden, true) => { commands.entity(ui).insert(Visibility::Inherited); } (Visibility::Hidden, false) | (_, true) => (), (_, false) => { commands.entity(ui).insert(Visibility::Hidden); } } // if we're not stepping, there's nothing more to be done here. if !stepping.is_enabled() { return; } // no cursor means stepping isn't enabled, so we're done here let Some((cursor_schedule, cursor_system)) = stepping.cursor() else { return; }; for (schedule, system, text_index) in &state.systems { let mark = if &cursor_schedule == schedule && *system == cursor_system { "-> " } else { " " }; *writer.text(ui, *text_index) = mark.to_string(); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/games/desk_toy.rs
examples/games/desk_toy.rs
//! Bevy logo as a desk toy using transparent windows! Now with Googly Eyes! //! //! This example demonstrates: //! - Transparent windows that can be clicked through. //! - Drag-and-drop operations in 2D. //! - Using entity hierarchy, Transform, and Visibility to create simple animations. //! - Creating simple 2D meshes based on shape primitives. use bevy::{ app::AppExit, input::common_conditions::{input_just_pressed, input_just_released}, prelude::*, window::{CursorOptions, PrimaryWindow, WindowLevel}, }; #[cfg(target_os = "macos")] use bevy::window::CompositeAlphaMode; fn main() { App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "Bevy Desk Toy".into(), transparent: true, #[cfg(target_os = "macos")] composite_alpha_mode: CompositeAlphaMode::PostMultiplied, ..default() }), ..default() })) .insert_resource(ClearColor(WINDOW_CLEAR_COLOR)) .insert_resource(WindowTransparency(false)) .insert_resource(CursorWorldPos(None)) .add_systems(Startup, setup) .add_systems( Update, ( get_cursor_world_pos, update_cursor_hit_test, ( start_drag.run_if(input_just_pressed(MouseButton::Left)), end_drag.run_if(input_just_released(MouseButton::Left)), drag.run_if(resource_exists::<DragOperation>), quit.run_if(input_just_pressed(MouseButton::Right)), toggle_transparency.run_if(input_just_pressed(KeyCode::Space)), move_pupils.after(drag), ), ) .chain(), ) .run(); } /// Whether the window is transparent #[derive(Resource)] struct WindowTransparency(bool); /// The projected 2D world coordinates of the cursor (if it's within primary window bounds). #[derive(Resource)] struct CursorWorldPos(Option<Vec2>); /// The current drag operation including the offset with which we grabbed the Bevy logo. #[derive(Resource)] struct DragOperation(Vec2); /// Marker component for the instructions text entity. #[derive(Component)] struct InstructionsText; /// Marker component for the Bevy logo entity. #[derive(Component)] struct BevyLogo; /// Component for the moving pupil entity (the moving part of the googly eye). #[derive(Component)] struct Pupil { /// Radius of the eye containing the pupil. eye_radius: f32, /// Radius of the pupil. pupil_radius: f32, /// Current velocity of the pupil. velocity: Vec2, } // Dimensions are based on: assets/branding/icon.png // Bevy logo radius const BEVY_LOGO_RADIUS: f32 = 128.0; // Birds' eyes x y (offset from the origin) and radius // These values are manually determined from the logo image const BIRDS_EYES: [(f32, f32, f32); 3] = [ (145.0 - 128.0, -(56.0 - 128.0), 12.0), (198.0 - 128.0, -(87.0 - 128.0), 10.0), (222.0 - 128.0, -(140.0 - 128.0), 8.0), ]; const WINDOW_CLEAR_COLOR: Color = Color::srgb(0.2, 0.2, 0.2); /// Spawn the scene fn setup( mut commands: Commands, asset_server: Res<AssetServer>, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<ColorMaterial>>, ) { // Spawn a 2D camera commands.spawn(Camera2d); // Spawn the text instructions let font = asset_server.load("fonts/FiraSans-Bold.ttf"); let text_style = TextFont { font: font.clone().into(), font_size: 25.0, ..default() }; commands.spawn(( Text2d::new("Press Space to play on your desktop! Press it again to return.\nRight click Bevy logo to exit."), text_style.clone(), Transform::from_xyz(0.0, -300.0, 100.0), InstructionsText, )); // Create a circle mesh. We will reuse this mesh for all our circles. let circle = meshes.add(Circle { radius: 1.0 }); // Create the different materials we will use for each part of the eyes. For this demo they are basic [`ColorMaterial`]s. let outline_material = materials.add(Color::BLACK); let sclera_material = materials.add(Color::WHITE); let pupil_material = materials.add(Color::srgb(0.2, 0.2, 0.2)); let pupil_highlight_material = materials.add(Color::srgba(1.0, 1.0, 1.0, 0.2)); // Spawn the Bevy logo sprite commands .spawn(( Sprite::from_image(asset_server.load("branding/icon.png")), BevyLogo, )) .with_children(|commands| { // For each bird eye for (x, y, radius) in BIRDS_EYES { let pupil_radius = radius * 0.6; let pupil_highlight_radius = radius * 0.3; let pupil_highlight_offset = radius * 0.3; // eye outline commands.spawn(( Mesh2d(circle.clone()), MeshMaterial2d(outline_material.clone()), Transform::from_xyz(x, y - 1.0, 1.0) .with_scale(Vec2::splat(radius + 2.0).extend(1.0)), )); // sclera commands.spawn(( Transform::from_xyz(x, y, 2.0), Visibility::default(), children![ // sclera ( Mesh2d(circle.clone()), MeshMaterial2d(sclera_material.clone()), Transform::from_scale(Vec3::new(radius, radius, 0.0)), ), // pupil ( Transform::from_xyz(0.0, 0.0, 1.0), Visibility::default(), Pupil { eye_radius: radius, pupil_radius, velocity: Vec2::ZERO, }, children![ // pupil main ( Mesh2d(circle.clone()), MeshMaterial2d(pupil_material.clone()), Transform::from_xyz(0.0, 0.0, 0.0).with_scale(Vec3::new( pupil_radius, pupil_radius, 1.0, )), ), // pupil highlight ( Mesh2d(circle.clone()), MeshMaterial2d(pupil_highlight_material.clone()), Transform::from_xyz( -pupil_highlight_offset, pupil_highlight_offset, 1.0, ) .with_scale(Vec3::new( pupil_highlight_radius, pupil_highlight_radius, 1.0, )), ) ], ) ], )); } }); } /// Project the cursor into the world coordinates and store it in a resource for easy use fn get_cursor_world_pos( mut cursor_world_pos: ResMut<CursorWorldPos>, primary_window: Single<&Window, With<PrimaryWindow>>, q_camera: Single<(&Camera, &GlobalTransform)>, ) { let (main_camera, main_camera_transform) = *q_camera; // Get the cursor position in the world cursor_world_pos.0 = primary_window.cursor_position().and_then(|cursor_pos| { main_camera .viewport_to_world_2d(main_camera_transform, cursor_pos) .ok() }); } /// Update whether the window is clickable or not fn update_cursor_hit_test( cursor_world_pos: Res<CursorWorldPos>, primary_window: Single<(&Window, &mut CursorOptions), With<PrimaryWindow>>, bevy_logo_transform: Single<&Transform, With<BevyLogo>>, ) { let (window, mut cursor_options) = primary_window.into_inner(); // If the window has decorations (e.g. a border) then it should be clickable if window.decorations { cursor_options.hit_test = true; return; } // If the cursor is not within the window we don't need to update whether the window is clickable or not let Some(cursor_world_pos) = cursor_world_pos.0 else { return; }; // If the cursor is within the radius of the Bevy logo make the window clickable otherwise the window is not clickable cursor_options.hit_test = bevy_logo_transform .translation .truncate() .distance(cursor_world_pos) < BEVY_LOGO_RADIUS; } /// Start the drag operation and record the offset we started dragging from fn start_drag( mut commands: Commands, cursor_world_pos: Res<CursorWorldPos>, bevy_logo_transform: Single<&Transform, With<BevyLogo>>, ) { // If the cursor is not within the primary window skip this system let Some(cursor_world_pos) = cursor_world_pos.0 else { return; }; // Get the offset from the cursor to the Bevy logo sprite let drag_offset = bevy_logo_transform.translation.truncate() - cursor_world_pos; // If the cursor is within the Bevy logo radius start the drag operation and remember the offset of the cursor from the origin if drag_offset.length() < BEVY_LOGO_RADIUS { commands.insert_resource(DragOperation(drag_offset)); } } /// Stop the current drag operation fn end_drag(mut commands: Commands) { commands.remove_resource::<DragOperation>(); } /// Drag the Bevy logo fn drag( drag_offset: Res<DragOperation>, cursor_world_pos: Res<CursorWorldPos>, time: Res<Time>, mut bevy_transform: Single<&mut Transform, With<BevyLogo>>, mut q_pupils: Query<&mut Pupil>, ) { // If the cursor is not within the primary window skip this system let Some(cursor_world_pos) = cursor_world_pos.0 else { return; }; // Calculate the new translation of the Bevy logo based on cursor and drag offset let new_translation = cursor_world_pos + drag_offset.0; // Calculate how fast we are dragging the Bevy logo (unit/second) let drag_velocity = (new_translation - bevy_transform.translation.truncate()) / time.delta_secs(); // Update the translation of Bevy logo transform to new translation bevy_transform.translation = new_translation.extend(bevy_transform.translation.z); // Add the cursor drag velocity in the opposite direction to each pupil. // Remember pupils are using local coordinates to move. So when the Bevy logo moves right they need to move left to // simulate inertia, otherwise they will move fixed to the parent. for mut pupil in &mut q_pupils { pupil.velocity -= drag_velocity; } } /// Quit when the user right clicks the Bevy logo fn quit( cursor_world_pos: Res<CursorWorldPos>, mut app_exit: MessageWriter<AppExit>, bevy_logo_transform: Single<&Transform, With<BevyLogo>>, ) { // If the cursor is not within the primary window skip this system let Some(cursor_world_pos) = cursor_world_pos.0 else { return; }; // If the cursor is within the Bevy logo radius send the [`AppExit`] event to quit the app if bevy_logo_transform .translation .truncate() .distance(cursor_world_pos) < BEVY_LOGO_RADIUS { app_exit.write(AppExit::Success); } } /// Enable transparency for the window and make it on top fn toggle_transparency( mut commands: Commands, mut window_transparency: ResMut<WindowTransparency>, mut q_instructions_text: Query<&mut Visibility, With<InstructionsText>>, mut primary_window: Single<&mut Window, With<PrimaryWindow>>, ) { // Toggle the window transparency resource window_transparency.0 = !window_transparency.0; // Show or hide the instructions text for mut visibility in &mut q_instructions_text { *visibility = if window_transparency.0 { Visibility::Hidden } else { Visibility::Visible }; } // Remove the primary window's decorations (e.g. borders), make it always on top of other desktop windows, and set the clear color to transparent // only if window transparency is enabled let clear_color; ( primary_window.decorations, primary_window.window_level, clear_color, ) = if window_transparency.0 { (false, WindowLevel::AlwaysOnTop, Color::NONE) } else { (true, WindowLevel::Normal, WINDOW_CLEAR_COLOR) }; // Set the clear color commands.insert_resource(ClearColor(clear_color)); } /// Move the pupils and bounce them around fn move_pupils(time: Res<Time>, mut q_pupils: Query<(&mut Pupil, &mut Transform)>) { for (mut pupil, mut transform) in &mut q_pupils { // The wiggle radius is how much the pupil can move within the eye let wiggle_radius = pupil.eye_radius - pupil.pupil_radius; // Store the Z component let z = transform.translation.z; // Truncate the Z component to make the calculations be on [`Vec2`] let mut translation = transform.translation.truncate(); // Decay the pupil velocity pupil.velocity *= ops::powf(0.04f32, time.delta_secs()); // Move the pupil translation += pupil.velocity * time.delta_secs(); // If the pupil hit the outside border of the eye, limit the translation to be within the wiggle radius and invert the velocity. // This is not physically accurate but it's good enough for the googly eyes effect. if translation.length() > wiggle_radius { translation = translation.normalize() * wiggle_radius; // Invert and decrease the velocity of the pupil when it bounces pupil.velocity *= -0.75; } // Update the entity transform with the new translation after reading the Z component transform.translation = translation.extend(z); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/shader_advanced/custom_post_processing.rs
examples/shader_advanced/custom_post_processing.rs
//! This example shows how to create a custom render pass that runs after the main pass //! and reads the texture generated by the main pass. //! //! The example shader is a very simple implementation of chromatic aberration. //! To adapt this example for 2D, replace all instances of 3D structures (such as `Core3D`, etc.) with their corresponding 2D counterparts. //! //! This is a fairly low level example and assumes some familiarity with rendering concepts and wgpu. use bevy::{ core_pipeline::{ core_3d::graph::{Core3d, Node3d}, FullscreenShader, }, ecs::query::QueryItem, prelude::*, render::{ extract_component::{ ComponentUniforms, DynamicUniformIndex, ExtractComponent, ExtractComponentPlugin, UniformComponentPlugin, }, render_graph::{ NodeRunError, RenderGraphContext, RenderGraphExt, RenderLabel, ViewNode, ViewNodeRunner, }, render_resource::{ binding_types::{sampler, texture_2d, uniform_buffer}, *, }, renderer::{RenderContext, RenderDevice}, view::ViewTarget, RenderApp, RenderStartup, }, }; /// This example uses a shader source file from the assets subdirectory const SHADER_ASSET_PATH: &str = "shaders/post_processing.wgsl"; fn main() { App::new() .add_plugins((DefaultPlugins, PostProcessPlugin)) .add_systems(Startup, setup) .add_systems(Update, (rotate, update_settings)) .run(); } /// It is generally encouraged to set up post processing effects as a plugin struct PostProcessPlugin; impl Plugin for PostProcessPlugin { fn build(&self, app: &mut App) { app.add_plugins(( // The settings will be a component that lives in the main world but will // be extracted to the render world every frame. // This makes it possible to control the effect from the main world. // This plugin will take care of extracting it automatically. // It's important to derive [`ExtractComponent`] on [`PostProcessingSettings`] // for this plugin to work correctly. ExtractComponentPlugin::<PostProcessSettings>::default(), // The settings will also be the data used in the shader. // This plugin will prepare the component for the GPU by creating a uniform buffer // and writing the data to that buffer every frame. UniformComponentPlugin::<PostProcessSettings>::default(), )); // We need to get the render app from the main app let Some(render_app) = app.get_sub_app_mut(RenderApp) else { return; }; // RenderStartup runs once on startup after all plugins are built // It is useful to initialize data that will only live in the RenderApp render_app.add_systems(RenderStartup, init_post_process_pipeline); render_app // Bevy's renderer uses a render graph which is a collection of nodes in a directed acyclic graph. // It currently runs on each view/camera and executes each node in the specified order. // It will make sure that any node that needs a dependency from another node // only runs when that dependency is done. // // Each node can execute arbitrary work, but it generally runs at least one render pass. // A node only has access to the render world, so if you need data from the main world // you need to extract it manually or with the plugin like above. // Add a [`Node`] to the [`RenderGraph`] // The Node needs to impl FromWorld // // The [`ViewNodeRunner`] is a special [`Node`] that will automatically run the node for each view // matching the [`ViewQuery`] .add_render_graph_node::<ViewNodeRunner<PostProcessNode>>( // Specify the label of the graph, in this case we want the graph for 3d Core3d, // It also needs the label of the node PostProcessLabel, ) .add_render_graph_edges( Core3d, // Specify the node ordering. // This will automatically create all required node edges to enforce the given ordering. ( Node3d::Tonemapping, PostProcessLabel, Node3d::EndMainPassPostProcessing, ), ); } } #[derive(Debug, Hash, PartialEq, Eq, Clone, RenderLabel)] struct PostProcessLabel; // The post process node used for the render graph #[derive(Default)] struct PostProcessNode; // The ViewNode trait is required by the ViewNodeRunner impl ViewNode for PostProcessNode { // The node needs a query to gather data from the ECS in order to do its rendering, // but it's not a normal system so we need to define it manually. // // This query will only run on the view entity type ViewQuery = ( &'static ViewTarget, // This makes sure the node only runs on cameras with the PostProcessSettings component &'static PostProcessSettings, // As there could be multiple post processing components sent to the GPU (one per camera), // we need to get the index of the one that is associated with the current view. &'static DynamicUniformIndex<PostProcessSettings>, ); // Runs the node logic // This is where you encode draw commands. // // This will run on every view on which the graph is running. // If you don't want your effect to run on every camera, // you'll need to make sure you have a marker component as part of [`ViewQuery`] // to identify which camera(s) should run the effect. fn run( &self, _graph: &mut RenderGraphContext, render_context: &mut RenderContext, (view_target, _post_process_settings, settings_index): QueryItem<Self::ViewQuery>, world: &World, ) -> Result<(), NodeRunError> { // Get the pipeline resource that contains the global data we need // to create the render pipeline let post_process_pipeline = world.resource::<PostProcessPipeline>(); // The pipeline cache is a cache of all previously created pipelines. // It is required to avoid creating a new pipeline each frame, // which is expensive due to shader compilation. let pipeline_cache = world.resource::<PipelineCache>(); // Get the pipeline from the cache let Some(pipeline) = pipeline_cache.get_render_pipeline(post_process_pipeline.pipeline_id) else { return Ok(()); }; // Get the settings uniform binding let settings_uniforms = world.resource::<ComponentUniforms<PostProcessSettings>>(); let Some(settings_binding) = settings_uniforms.uniforms().binding() else { return Ok(()); }; // This will start a new "post process write", obtaining two texture // views from the view target - a `source` and a `destination`. // `source` is the "current" main texture and you _must_ write into // `destination` because calling `post_process_write()` on the // [`ViewTarget`] will internally flip the [`ViewTarget`]'s main // texture to the `destination` texture. Failing to do so will cause // the current main texture information to be lost. let post_process = view_target.post_process_write(); // The bind_group gets created each frame. // // Normally, you would create a bind_group in the Queue set, // but this doesn't work with the post_process_write(). // The reason it doesn't work is because each post_process_write will alternate the source/destination. // The only way to have the correct source/destination for the bind_group // is to make sure you get it during the node execution. let bind_group = render_context.render_device().create_bind_group( "post_process_bind_group", &pipeline_cache.get_bind_group_layout(&post_process_pipeline.layout), // It's important for this to match the BindGroupLayout defined in the PostProcessPipeline &BindGroupEntries::sequential(( // Make sure to use the source view post_process.source, // Use the sampler created for the pipeline &post_process_pipeline.sampler, // Set the settings binding settings_binding.clone(), )), ); // Begin the render pass let mut render_pass = render_context.begin_tracked_render_pass(RenderPassDescriptor { label: Some("post_process_pass"), color_attachments: &[Some(RenderPassColorAttachment { // We need to specify the post process destination view here // to make sure we write to the appropriate texture. view: post_process.destination, depth_slice: None, resolve_target: None, ops: Operations::default(), })], depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, }); // This is mostly just wgpu boilerplate for drawing a fullscreen triangle, // using the pipeline/bind_group created above render_pass.set_render_pipeline(pipeline); // By passing in the index of the post process settings on this view, we ensure // that in the event that multiple settings were sent to the GPU (as would be the // case with multiple cameras), we use the correct one. render_pass.set_bind_group(0, &bind_group, &[settings_index.index()]); render_pass.draw(0..3, 0..1); Ok(()) } } // This contains global data used by the render pipeline. This will be created once on startup. #[derive(Resource)] struct PostProcessPipeline { layout: BindGroupLayoutDescriptor, sampler: Sampler, pipeline_id: CachedRenderPipelineId, } fn init_post_process_pipeline( mut commands: Commands, render_device: Res<RenderDevice>, asset_server: Res<AssetServer>, fullscreen_shader: Res<FullscreenShader>, pipeline_cache: Res<PipelineCache>, ) { // We need to define the bind group layout used for our pipeline let layout = BindGroupLayoutDescriptor::new( "post_process_bind_group_layout", &BindGroupLayoutEntries::sequential( // The layout entries will only be visible in the fragment stage ShaderStages::FRAGMENT, ( // The screen texture texture_2d(TextureSampleType::Float { filterable: true }), // The sampler that will be used to sample the screen texture sampler(SamplerBindingType::Filtering), // The settings uniform that will control the effect uniform_buffer::<PostProcessSettings>(true), ), ), ); // We can create the sampler here since it won't change at runtime and doesn't depend on the view let sampler = render_device.create_sampler(&SamplerDescriptor::default()); // Get the shader handle let shader = asset_server.load(SHADER_ASSET_PATH); // This will setup a fullscreen triangle for the vertex state. let vertex_state = fullscreen_shader.to_vertex_state(); let pipeline_id = pipeline_cache // This will add the pipeline to the cache and queue its creation .queue_render_pipeline(RenderPipelineDescriptor { label: Some("post_process_pipeline".into()), layout: vec![layout.clone()], vertex: vertex_state, fragment: Some(FragmentState { shader, // Make sure this matches the entry point of your shader. // It can be anything as long as it matches here and in the shader. targets: vec![Some(ColorTargetState { format: TextureFormat::bevy_default(), blend: None, write_mask: ColorWrites::ALL, })], ..default() }), ..default() }); commands.insert_resource(PostProcessPipeline { layout, sampler, pipeline_id, }); } // This is the component that will get passed to the shader #[derive(Component, Default, Clone, Copy, ExtractComponent, ShaderType)] struct PostProcessSettings { intensity: f32, // WebGL2 structs must be 16 byte aligned. #[cfg(feature = "webgl2")] _webgl2_padding: Vec3, } /// Set up a simple 3D scene fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { // camera commands.spawn(( Camera3d::default(), Transform::from_translation(Vec3::new(0.0, 0.0, 5.0)).looking_at(Vec3::default(), Vec3::Y), Camera { clear_color: Color::WHITE.into(), ..default() }, // Add the setting to the camera. // This component is also used to determine on which camera to run the post processing effect. PostProcessSettings { intensity: 0.02, ..default() }, )); // cube commands.spawn(( Mesh3d(meshes.add(Cuboid::default())), MeshMaterial3d(materials.add(Color::srgb(0.8, 0.7, 0.6))), Transform::from_xyz(0.0, 0.5, 0.0), Rotates, )); // light commands.spawn(DirectionalLight { illuminance: 1_000., ..default() }); } #[derive(Component)] struct Rotates; /// Rotates any entity around the x and y axis fn rotate(time: Res<Time>, mut query: Query<&mut Transform, With<Rotates>>) { for mut transform in &mut query { transform.rotate_x(0.55 * time.delta_secs()); transform.rotate_z(0.15 * time.delta_secs()); } } // Change the intensity over time to show that the effect is controlled from the main world fn update_settings(mut settings: Query<&mut PostProcessSettings>, time: Res<Time>) { for mut setting in &mut settings { let mut intensity = ops::sin(time.elapsed_secs()); // Make it loop periodically intensity = ops::sin(intensity); // Remap it to 0..1 because the intensity can't be negative intensity = intensity * 0.5 + 0.5; // Scale it to a more reasonable level intensity *= 0.015; // Set the intensity. // This will then be extracted to the render world and uploaded to the GPU automatically by the [`UniformComponentPlugin`] setting.intensity = intensity; } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/shader_advanced/custom_phase_item.rs
examples/shader_advanced/custom_phase_item.rs
//! Demonstrates how to enqueue custom draw commands in a render phase. //! //! This example shows how to use the built-in //! [`bevy_render::render_phase::BinnedRenderPhase`] functionality with a //! custom [`RenderCommand`] to allow inserting arbitrary GPU drawing logic //! into Bevy's pipeline. This is not the only way to add custom rendering code //! into Bevy—render nodes are another, lower-level method—but it does allow //! for better reuse of parts of Bevy's built-in mesh rendering logic. use bevy::{ camera::{ primitives::Aabb, visibility::{self, VisibilityClass}, }, core_pipeline::core_3d::{Opaque3d, Opaque3dBatchSetKey, Opaque3dBinKey, CORE_3D_DEPTH_FORMAT}, ecs::{ change_detection::Tick, query::ROQueryItem, system::{lifetimeless::SRes, SystemParamItem}, }, mesh::VertexBufferLayout, prelude::*, render::{ extract_component::{ExtractComponent, ExtractComponentPlugin}, render_phase::{ AddRenderCommand, BinnedRenderPhaseType, DrawFunctions, InputUniformIndex, PhaseItem, RenderCommand, RenderCommandResult, SetItemPipeline, TrackedRenderPass, ViewBinnedRenderPhases, }, render_resource::{ BufferUsages, Canonical, ColorTargetState, ColorWrites, CompareFunction, DepthStencilState, FragmentState, IndexFormat, PipelineCache, RawBufferVec, RenderPipeline, RenderPipelineDescriptor, Specializer, SpecializerKey, TextureFormat, Variants, VertexAttribute, VertexFormat, VertexState, VertexStepMode, }, renderer::{RenderDevice, RenderQueue}, view::{ExtractedView, RenderVisibleEntities}, Render, RenderApp, RenderSystems, }, }; use bytemuck::{Pod, Zeroable}; /// A marker component that represents an entity that is to be rendered using /// our custom phase item. /// /// Note the [`ExtractComponent`] trait implementation: this is necessary to /// tell Bevy that this object should be pulled into the render world. Also note /// the `on_add` hook, which is needed to tell Bevy's `check_visibility` system /// that entities with this component need to be examined for visibility. #[derive(Clone, Component, ExtractComponent)] #[require(VisibilityClass)] #[component(on_add = visibility::add_visibility_class::<CustomRenderedEntity>)] struct CustomRenderedEntity; /// A [`RenderCommand`] that binds the vertex and index buffers and issues the /// draw command for our custom phase item. struct DrawCustomPhaseItem; impl<P> RenderCommand<P> for DrawCustomPhaseItem where P: PhaseItem, { type Param = SRes<CustomPhaseItemBuffers>; type ViewQuery = (); type ItemQuery = (); fn render<'w>( _: &P, _: ROQueryItem<'w, '_, Self::ViewQuery>, _: Option<ROQueryItem<'w, '_, Self::ItemQuery>>, custom_phase_item_buffers: SystemParamItem<'w, '_, Self::Param>, pass: &mut TrackedRenderPass<'w>, ) -> RenderCommandResult { // Borrow check workaround. let custom_phase_item_buffers = custom_phase_item_buffers.into_inner(); // Tell the GPU where the vertices are. pass.set_vertex_buffer( 0, custom_phase_item_buffers .vertices .buffer() .unwrap() .slice(..), ); // Tell the GPU where the indices are. pass.set_index_buffer( custom_phase_item_buffers .indices .buffer() .unwrap() .slice(..), IndexFormat::Uint32, ); // Draw one triangle (3 vertices). pass.draw_indexed(0..3, 0, 0..1); RenderCommandResult::Success } } /// The GPU vertex and index buffers for our custom phase item. /// /// As the custom phase item is a single triangle, these are uploaded once and /// then left alone. #[derive(Resource)] struct CustomPhaseItemBuffers { /// The vertices for the single triangle. /// /// This is a [`RawBufferVec`] because that's the simplest and fastest type /// of GPU buffer, and [`Vertex`] objects are simple. vertices: RawBufferVec<Vertex>, /// The indices of the single triangle. /// /// As above, this is a [`RawBufferVec`] because `u32` values have trivial /// size and alignment. indices: RawBufferVec<u32>, } /// The CPU-side structure that describes a single vertex of the triangle. #[derive(Clone, Copy, Pod, Zeroable)] #[repr(C)] struct Vertex { /// The 3D position of the triangle vertex. position: Vec3, /// Padding. pad0: u32, /// The color of the triangle vertex. color: Vec3, /// Padding. pad1: u32, } impl Vertex { /// Creates a new vertex structure. const fn new(position: Vec3, color: Vec3) -> Vertex { Vertex { position, color, pad0: 0, pad1: 0, } } } /// The custom draw commands that Bevy executes for each entity we enqueue into /// the render phase. type DrawCustomPhaseItemCommands = (SetItemPipeline, DrawCustomPhaseItem); /// A single triangle's worth of vertices, for demonstration purposes. static VERTICES: [Vertex; 3] = [ Vertex::new(vec3(-0.866, -0.5, 0.5), vec3(1.0, 0.0, 0.0)), Vertex::new(vec3(0.866, -0.5, 0.5), vec3(0.0, 1.0, 0.0)), Vertex::new(vec3(0.0, 1.0, 0.5), vec3(0.0, 0.0, 1.0)), ]; /// The entry point. fn main() { let mut app = App::new(); app.add_plugins(DefaultPlugins) .add_plugins(ExtractComponentPlugin::<CustomRenderedEntity>::default()) .add_systems(Startup, setup); // We make sure to add these to the render app, not the main app. app.sub_app_mut(RenderApp) .init_resource::<CustomPhasePipeline>() .add_render_command::<Opaque3d, DrawCustomPhaseItemCommands>() .add_systems( Render, prepare_custom_phase_item_buffers.in_set(RenderSystems::Prepare), ) .add_systems(Render, queue_custom_phase_item.in_set(RenderSystems::Queue)); app.run(); } /// Spawns the objects in the scene. fn setup(mut commands: Commands) { // Spawn a single entity that has custom rendering. It'll be extracted into // the render world via [`ExtractComponent`]. commands.spawn(( Visibility::default(), Transform::default(), // This `Aabb` is necessary for the visibility checks to work. Aabb { center: Vec3A::ZERO, half_extents: Vec3A::splat(0.5), }, CustomRenderedEntity, )); // Spawn the camera. commands.spawn(( Camera3d::default(), Transform::from_xyz(0.0, 0.0, 1.0).looking_at(Vec3::ZERO, Vec3::Y), )); } /// Creates the [`CustomPhaseItemBuffers`] resource. /// /// This must be done in a startup system because it needs the [`RenderDevice`] /// and [`RenderQueue`] to exist, and they don't until [`App::run`] is called. fn prepare_custom_phase_item_buffers(mut commands: Commands) { commands.init_resource::<CustomPhaseItemBuffers>(); } /// A render-world system that enqueues the entity with custom rendering into /// the opaque render phases of each view. fn queue_custom_phase_item( pipeline_cache: Res<PipelineCache>, mut pipeline: ResMut<CustomPhasePipeline>, mut opaque_render_phases: ResMut<ViewBinnedRenderPhases<Opaque3d>>, opaque_draw_functions: Res<DrawFunctions<Opaque3d>>, views: Query<(&ExtractedView, &RenderVisibleEntities, &Msaa)>, mut next_tick: Local<Tick>, ) { let draw_custom_phase_item = opaque_draw_functions .read() .id::<DrawCustomPhaseItemCommands>(); // Render phases are per-view, so we need to iterate over all views so that // the entity appears in them. (In this example, we have only one view, but // it's good practice to loop over all views anyway.) for (view, view_visible_entities, msaa) in views.iter() { let Some(opaque_phase) = opaque_render_phases.get_mut(&view.retained_view_entity) else { continue; }; // Find all the custom rendered entities that are visible from this // view. for &entity in view_visible_entities.get::<CustomRenderedEntity>().iter() { // Ordinarily, the [`SpecializedRenderPipeline::Key`] would contain // some per-view settings, such as whether the view is HDR, but for // simplicity's sake we simply hard-code the view's characteristics, // with the exception of number of MSAA samples. let Ok(pipeline_id) = pipeline .variants .specialize(&pipeline_cache, CustomPhaseKey(*msaa)) else { continue; }; // Bump the change tick in order to force Bevy to rebuild the bin. let this_tick = next_tick.get() + 1; next_tick.set(this_tick); // Add the custom render item. We use the // [`BinnedRenderPhaseType::NonMesh`] type to skip the special // handling that Bevy has for meshes (preprocessing, indirect // draws, etc.) // // The asset ID is arbitrary; we simply use [`AssetId::invalid`], // but you can use anything you like. Note that the asset ID need // not be the ID of a [`Mesh`]. opaque_phase.add( Opaque3dBatchSetKey { draw_function: draw_custom_phase_item, pipeline: pipeline_id, material_bind_group_index: None, lightmap_slab: None, vertex_slab: default(), index_slab: None, }, Opaque3dBinKey { asset_id: AssetId::<Mesh>::invalid().untyped(), }, entity, InputUniformIndex::default(), BinnedRenderPhaseType::NonMesh, *next_tick, ); } } } struct CustomPhaseSpecializer; #[derive(Resource)] struct CustomPhasePipeline { /// the `variants` collection holds onto the shader handle through the base descriptor variants: Variants<RenderPipeline, CustomPhaseSpecializer>, } impl FromWorld for CustomPhasePipeline { fn from_world(world: &mut World) -> Self { let asset_server = world.resource::<AssetServer>(); let shader = asset_server.load("shaders/custom_phase_item.wgsl"); let base_descriptor = RenderPipelineDescriptor { label: Some("custom render pipeline".into()), vertex: VertexState { shader: shader.clone(), buffers: vec![VertexBufferLayout { array_stride: size_of::<Vertex>() as u64, step_mode: VertexStepMode::Vertex, // This needs to match the layout of [`Vertex`]. attributes: vec![ VertexAttribute { format: VertexFormat::Float32x3, offset: 0, shader_location: 0, }, VertexAttribute { format: VertexFormat::Float32x3, offset: 16, shader_location: 1, }, ], }], ..default() }, fragment: Some(FragmentState { shader: shader.clone(), targets: vec![Some(ColorTargetState { // Ordinarily, you'd want to check whether the view has the // HDR format and substitute the appropriate texture format // here, but we omit that for simplicity. format: TextureFormat::bevy_default(), blend: None, write_mask: ColorWrites::ALL, })], ..default() }), // Note that if your view has no depth buffer this will need to be // changed. depth_stencil: Some(DepthStencilState { format: CORE_3D_DEPTH_FORMAT, depth_write_enabled: false, depth_compare: CompareFunction::Always, stencil: default(), bias: default(), }), ..default() }; let variants = Variants::new(CustomPhaseSpecializer, base_descriptor); Self { variants } } } #[derive(Copy, Clone, PartialEq, Eq, Hash, SpecializerKey)] struct CustomPhaseKey(Msaa); impl Specializer<RenderPipeline> for CustomPhaseSpecializer { type Key = CustomPhaseKey; fn specialize( &self, key: Self::Key, descriptor: &mut RenderPipelineDescriptor, ) -> Result<Canonical<Self::Key>, BevyError> { descriptor.multisample.count = key.0.samples(); Ok(key) } } impl FromWorld for CustomPhaseItemBuffers { fn from_world(world: &mut World) -> Self { let render_device = world.resource::<RenderDevice>(); let render_queue = world.resource::<RenderQueue>(); // Create the vertex and index buffers. let mut vbo = RawBufferVec::new(BufferUsages::VERTEX); let mut ibo = RawBufferVec::new(BufferUsages::INDEX); for vertex in &VERTICES { vbo.push(*vertex); } for index in 0..3 { ibo.push(index); } // These two lines are required in order to trigger the upload to GPU. vbo.write_buffer(render_device, render_queue); ibo.write_buffer(render_device, render_queue); CustomPhaseItemBuffers { vertices: vbo, indices: ibo, } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/shader_advanced/custom_vertex_attribute.rs
examples/shader_advanced/custom_vertex_attribute.rs
//! A shader that reads a mesh's custom vertex attribute. use bevy::{ mesh::{MeshVertexAttribute, MeshVertexBufferLayoutRef}, pbr::{MaterialPipeline, MaterialPipelineKey}, prelude::*, reflect::TypePath, render::render_resource::{ AsBindGroup, RenderPipelineDescriptor, SpecializedMeshPipelineError, VertexFormat, }, shader::ShaderRef, }; /// This example uses a shader source file from the assets subdirectory const SHADER_ASSET_PATH: &str = "shaders/custom_vertex_attribute.wgsl"; fn main() { App::new() .add_plugins((DefaultPlugins, MaterialPlugin::<CustomMaterial>::default())) .add_systems(Startup, setup) .run(); } // A "high" random id should be used for custom attributes to ensure consistent sorting and avoid collisions with other attributes. // See the MeshVertexAttribute docs for more info. const ATTRIBUTE_BLEND_COLOR: MeshVertexAttribute = MeshVertexAttribute::new("BlendColor", 988540917, VertexFormat::Float32x4); /// set up a simple 3D scene fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<CustomMaterial>>, ) { let mesh = Mesh::from(Cuboid::default()) // Sets the custom attribute .with_inserted_attribute( ATTRIBUTE_BLEND_COLOR, // The cube mesh has 24 vertices (6 faces, 4 vertices per face), so we insert one BlendColor for each vec![[1.0, 0.0, 0.0, 1.0]; 24], ); // cube commands.spawn(( Mesh3d(meshes.add(mesh)), MeshMaterial3d(materials.add(CustomMaterial { color: LinearRgba::WHITE, })), Transform::from_xyz(0.0, 0.5, 0.0), )); // camera commands.spawn(( Camera3d::default(), Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y), )); } // This is the struct that will be passed to your shader #[derive(Asset, TypePath, AsBindGroup, Debug, Clone)] struct CustomMaterial { #[uniform(0)] color: LinearRgba, } impl Material for CustomMaterial { fn vertex_shader() -> ShaderRef { SHADER_ASSET_PATH.into() } fn fragment_shader() -> ShaderRef { SHADER_ASSET_PATH.into() } fn specialize( _pipeline: &MaterialPipeline, descriptor: &mut RenderPipelineDescriptor, layout: &MeshVertexBufferLayoutRef, _key: MaterialPipelineKey<Self>, ) -> Result<(), SpecializedMeshPipelineError> { let vertex_layout = layout.0.get_layout(&[ Mesh::ATTRIBUTE_POSITION.at_shader_location(0), ATTRIBUTE_BLEND_COLOR.at_shader_location(1), ])?; descriptor.vertex.buffers = vec![vertex_layout]; Ok(()) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/shader_advanced/specialized_mesh_pipeline.rs
examples/shader_advanced/specialized_mesh_pipeline.rs
//! Demonstrates how to define and use specialized mesh pipeline //! //! This example shows how to use the built-in [`SpecializedMeshPipeline`] //! functionality with a custom [`RenderCommand`] to allow custom mesh rendering with //! more flexibility than the material api. //! //! [`SpecializedMeshPipeline`] let's you customize the entire pipeline used when rendering a mesh. use bevy::{ asset::RenderAssetUsages, camera::visibility::{self, VisibilityClass}, core_pipeline::core_3d::{Opaque3d, Opaque3dBatchSetKey, Opaque3dBinKey, CORE_3D_DEPTH_FORMAT}, ecs::change_detection::Tick, math::{vec3, vec4}, mesh::{Indices, MeshVertexBufferLayoutRef, PrimitiveTopology}, pbr::{ DrawMesh, MeshPipeline, MeshPipelineKey, MeshPipelineViewLayoutKey, RenderMeshInstances, SetMeshBindGroup, SetMeshViewBindGroup, SetMeshViewEmptyBindGroup, }, prelude::*, render::{ batching::gpu_preprocessing::GpuPreprocessingSupport, extract_component::{ExtractComponent, ExtractComponentPlugin}, mesh::{allocator::MeshAllocator, RenderMesh}, render_asset::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::{ExtractedView, RenderVisibleEntities, ViewTarget}, Render, RenderApp, RenderStartup, RenderSystems, }, }; 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(); } /// Spawns the objects in the scene. fn setup(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>) { // Build a custom triangle mesh with colors // We define a custom mesh because the examples only uses a limited // set of vertex attributes for simplicity 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), ], ); // spawn 3 triangles to show that batching works for (x, y) in [-0.5, 0.0, 0.5].into_iter().zip([-0.25, 0.5, -0.25]) { // Spawn an entity with all the required components for it to be rendered with our custom pipeline commands.spawn(( // We use a marker component to identify the mesh that will be rendered // with our specialized pipeline CustomRenderedEntity, // We need to add the mesh handle to the entity Mesh3d(meshes.add(mesh.clone())), Transform::from_xyz(x, y, 0.0), )); } // Spawn the camera. commands.spawn(( Camera3d::default(), // Move the camera back a bit to see all the triangles Transform::from_xyz(0.0, 0.0, 3.0).looking_at(Vec3::ZERO, Vec3::Y), )); } // When writing custom rendering code it's generally recommended to use a plugin. // The main reason for this is that it gives you access to the finish() hook // which is called after rendering resources are initialized. struct CustomRenderedMeshPipelinePlugin; impl Plugin for CustomRenderedMeshPipelinePlugin { fn build(&self, app: &mut App) { app.add_plugins(ExtractComponentPlugin::<CustomRenderedEntity>::default()); // We make sure to add these to the render app, not the main app. let Some(render_app) = app.get_sub_app_mut(RenderApp) else { return; }; render_app // This is needed to tell bevy about your custom pipeline .init_resource::<SpecializedMeshPipelines<CustomMeshPipeline>>() // We need to use a custom draw command so we need to register it .add_render_command::<Opaque3d, DrawSpecializedPipelineCommands>() .add_systems(RenderStartup, init_custom_mesh_pipeline) .add_systems( Render, queue_custom_mesh_pipeline.in_set(RenderSystems::Queue), ); } } /// A marker component that represents an entity that is to be rendered using /// our specialized pipeline. /// /// Note the [`ExtractComponent`] trait implementation: this is necessary to /// tell Bevy that this object should be pulled into the render world. Also note /// the `on_add` hook, which is needed to tell Bevy's `check_visibility` system /// that entities with this component need to be examined for visibility. #[derive(Clone, Component, ExtractComponent)] #[require(VisibilityClass)] #[component(on_add = visibility::add_visibility_class::<CustomRenderedEntity>)] struct CustomRenderedEntity; /// The custom draw commands that Bevy executes for each entity we enqueue into /// the render phase. type DrawSpecializedPipelineCommands = ( // Set the pipeline SetItemPipeline, // Set the view uniform at bind group 0 SetMeshViewBindGroup<0>, // Set an empty material bind group at bind group 1 SetMeshViewEmptyBindGroup<1>, // Set the mesh uniform at bind group 2 SetMeshBindGroup<2>, // Draw the mesh DrawMesh, ); // This contains the state needed to specialize a mesh pipeline #[derive(Resource)] struct CustomMeshPipeline { /// The base mesh pipeline defined by bevy /// /// This isn't required, but if you want to use a bevy `Mesh` it's easier when you /// have access to the base `MeshPipeline` that bevy already defines mesh_pipeline: MeshPipeline, /// Stores the shader used for this pipeline directly on the pipeline. /// This isn't required, it's only done like this for simplicity. shader_handle: Handle<Shader>, } fn init_custom_mesh_pipeline( mut commands: Commands, asset_server: Res<AssetServer>, mesh_pipeline: Res<MeshPipeline>, ) { // Load the shader let shader_handle: Handle<Shader> = asset_server.load(SHADER_ASSET_PATH); commands.insert_resource(CustomMeshPipeline { mesh_pipeline: mesh_pipeline.clone(), shader_handle, }); } impl SpecializedMeshPipeline for CustomMeshPipeline { /// Pipeline use keys to determine how to specialize it. /// The key is also used by the pipeline cache to determine if /// it needs to create a new pipeline or not /// /// In this example we just use the base `MeshPipelineKey` defined by bevy, but this could be anything. /// For example, if you want to make a pipeline with a procedural shader you could add the Handle<Shader> to the key. type Key = MeshPipelineKey; fn specialize( &self, mesh_key: Self::Key, layout: &MeshVertexBufferLayoutRef, ) -> Result<RenderPipelineDescriptor, SpecializedMeshPipelineError> { // Define the vertex attributes based on a standard bevy [`Mesh`] let mut vertex_attributes = Vec::new(); if layout.0.contains(Mesh::ATTRIBUTE_POSITION) { // Make sure this matches the shader location vertex_attributes.push(Mesh::ATTRIBUTE_POSITION.at_shader_location(0)); } if layout.0.contains(Mesh::ATTRIBUTE_COLOR) { // Make sure this matches the shader location vertex_attributes.push(Mesh::ATTRIBUTE_COLOR.at_shader_location(1)); } // This will automatically generate the correct `VertexBufferLayout` based on the vertex attributes let vertex_buffer_layout = layout.0.get_layout(&vertex_attributes)?; let view_layout = self .mesh_pipeline .get_view_layout(MeshPipelineViewLayoutKey::from(mesh_key)); Ok(RenderPipelineDescriptor { label: Some("Specialized Mesh Pipeline".into()), layout: vec![ view_layout.main_layout.clone(), view_layout.empty_layout.clone(), self.mesh_pipeline.mesh_layouts.model_only.clone(), ], vertex: VertexState { shader: self.shader_handle.clone(), // Customize how to store the meshes' vertex attributes in the vertex buffer buffers: vec![vertex_buffer_layout], ..default() }, fragment: Some(FragmentState { shader: self.shader_handle.clone(), targets: vec![Some(ColorTargetState { // This isn't required, but bevy supports HDR and non-HDR rendering // so it's generally recommended to specialize the pipeline for that format: if mesh_key.contains(MeshPipelineKey::HDR) { ViewTarget::TEXTURE_FORMAT_HDR } else { TextureFormat::bevy_default() }, // For this example we only use opaque meshes, // but if you wanted to use alpha blending you would need to set it here blend: None, write_mask: ColorWrites::ALL, })], ..default() }), primitive: PrimitiveState { topology: mesh_key.primitive_topology(), front_face: FrontFace::Ccw, cull_mode: Some(Face::Back), polygon_mode: PolygonMode::Fill, ..default() }, // Note that if your view has no depth buffer this will need to be // changed. depth_stencil: Some(DepthStencilState { format: CORE_3D_DEPTH_FORMAT, depth_write_enabled: true, depth_compare: CompareFunction::GreaterEqual, stencil: default(), bias: default(), }), // It's generally recommended to specialize your pipeline for MSAA, // but it's not always possible multisample: MultisampleState { count: mesh_key.msaa_samples(), ..default() }, ..default() }) } } /// A render-world system that enqueues the entity with custom rendering into /// the opaque render phases of each view. fn queue_custom_mesh_pipeline( pipeline_cache: Res<PipelineCache>, custom_mesh_pipeline: Res<CustomMeshPipeline>, (mut opaque_render_phases, opaque_draw_functions): ( ResMut<ViewBinnedRenderPhases<Opaque3d>>, Res<DrawFunctions<Opaque3d>>, ), mut specialized_mesh_pipelines: ResMut<SpecializedMeshPipelines<CustomMeshPipeline>>, views: Query<(&RenderVisibleEntities, &ExtractedView, &Msaa)>, (render_meshes, render_mesh_instances): ( Res<RenderAssets<RenderMesh>>, Res<RenderMeshInstances>, ), mut change_tick: Local<Tick>, mesh_allocator: Res<MeshAllocator>, gpu_preprocessing_support: Res<GpuPreprocessingSupport>, ) { // Get the id for our custom draw function let draw_function = opaque_draw_functions .read() .id::<DrawSpecializedPipelineCommands>(); // Render phases are per-view, so we need to iterate over all views so that // the entity appears in them. (In this example, we have only one view, but // it's good practice to loop over all views anyway.) for (view_visible_entities, view, msaa) in views.iter() { let Some(opaque_phase) = opaque_render_phases.get_mut(&view.retained_view_entity) else { continue; }; // Create the key based on the view. In this case we only care about MSAA and HDR let view_key = MeshPipelineKey::from_msaa_samples(msaa.samples()) | MeshPipelineKey::from_hdr(view.hdr); // Find all the custom rendered entities that are visible from this // view. for &(render_entity, visible_entity) in view_visible_entities.get::<CustomRenderedEntity>().iter() { // Get the mesh instance let Some(mesh_instance) = render_mesh_instances.render_mesh_queue_data(visible_entity) else { continue; }; // Get the mesh data let Some(mesh) = render_meshes.get(mesh_instance.mesh_asset_id) else { continue; }; let (vertex_slab, index_slab) = mesh_allocator.mesh_slabs(&mesh_instance.mesh_asset_id); // Specialize the key for the current mesh entity // For this example we only specialize based on the mesh topology // but you could have more complex keys and that's where you'd need to create those keys let mut mesh_key = view_key; mesh_key |= MeshPipelineKey::from_primitive_topology(mesh.primitive_topology()); // Finally, we can specialize the pipeline based on the key let pipeline_id = specialized_mesh_pipelines .specialize( &pipeline_cache, &custom_mesh_pipeline, mesh_key, &mesh.layout, ) // This should never happen with this example, but if your pipeline // specialization can fail you need to handle the error here .expect("Failed to specialize mesh pipeline"); // Bump the change tick so that Bevy is forced to rebuild the bin. let next_change_tick = change_tick.get() + 1; change_tick.set(next_change_tick); // Add the mesh with our specialized pipeline opaque_phase.add( Opaque3dBatchSetKey { draw_function, pipeline: pipeline_id, material_bind_group_index: None, vertex_slab: vertex_slab.unwrap_or_default(), index_slab, lightmap_slab: None, }, // For this example we can use the mesh asset id as the bin key, // but you can use any asset_id as a key Opaque3dBinKey { asset_id: mesh_instance.mesh_asset_id.into(), }, (render_entity, visible_entity), mesh_instance.current_uniform_index, // This example supports batching and multi draw indirect, // but if your pipeline doesn't support it you can use // `BinnedRenderPhaseType::UnbatchableMesh` BinnedRenderPhaseType::mesh( mesh_instance.should_batch(), &gpu_preprocessing_support, ), *change_tick, ); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/shader_advanced/custom_shader_instancing.rs
examples/shader_advanced/custom_shader_instancing.rs
//! A shader that renders a mesh multiple times in one draw call. //! //! Bevy will automatically batch and instance your meshes assuming you use the same //! `Handle<Material>` and `Handle<Mesh>` for all of your instances. //! //! This example is intended for advanced users and shows how to make a custom instancing //! implementation using bevy's low level rendering api. //! It's generally recommended to try the built-in instancing before going with this approach. use bevy::pbr::SetMeshViewBindingArrayBindGroup; use bevy::{ camera::visibility::NoFrustumCulling, core_pipeline::core_3d::Transparent3d, ecs::{ query::QueryItem, system::{lifetimeless::*, SystemParamItem}, }, mesh::{MeshVertexBufferLayoutRef, VertexBufferLayout}, pbr::{ MeshPipeline, MeshPipelineKey, RenderMeshInstances, SetMeshBindGroup, SetMeshViewBindGroup, }, prelude::*, render::{ extract_component::{ExtractComponent, ExtractComponentPlugin}, mesh::{allocator::MeshAllocator, RenderMesh, RenderMeshBufferInfo}, render_asset::RenderAssets, render_phase::{ AddRenderCommand, DrawFunctions, PhaseItem, PhaseItemExtraIndex, RenderCommand, RenderCommandResult, SetItemPipeline, TrackedRenderPass, ViewSortedRenderPhases, }, render_resource::*, renderer::RenderDevice, sync_world::MainEntity, view::{ExtractedView, NoIndirectDrawing}, Render, RenderApp, RenderStartup, RenderSystems, }, }; use bytemuck::{Pod, Zeroable}; /// This example uses a shader source file from the assets subdirectory const SHADER_ASSET_PATH: &str = "shaders/instancing.wgsl"; fn main() { App::new() .add_plugins((DefaultPlugins, CustomMaterialPlugin)) .add_systems(Startup, setup) .run(); } fn setup(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>) { commands.spawn(( Mesh3d(meshes.add(Cuboid::new(0.5, 0.5, 0.5))), InstanceMaterialData( (1..=10) .flat_map(|x| (1..=10).map(move |y| (x as f32 / 10.0, y as f32 / 10.0))) .map(|(x, y)| InstanceData { position: Vec3::new(x * 10.0 - 5.0, y * 10.0 - 5.0, 0.0), scale: 1.0, color: LinearRgba::from(Color::hsla(x * 360., y, 0.5, 1.0)).to_f32_array(), }) .collect(), ), // NOTE: Frustum culling is done based on the Aabb of the Mesh and the GlobalTransform. // As the cube is at the origin, if its Aabb moves outside the view frustum, all the // instanced cubes will be culled. // The InstanceMaterialData contains the 'GlobalTransform' information for this custom // instancing, and that is not taken into account with the built-in frustum culling. // We must disable the built-in frustum culling by adding the `NoFrustumCulling` marker // component to avoid incorrect culling. NoFrustumCulling, )); // camera commands.spawn(( Camera3d::default(), Transform::from_xyz(0.0, 0.0, 15.0).looking_at(Vec3::ZERO, Vec3::Y), // We need this component because we use `draw_indexed` and `draw` // instead of `draw_indirect_indexed` and `draw_indirect` in // `DrawMeshInstanced::render`. NoIndirectDrawing, )); } #[derive(Component, Deref)] struct InstanceMaterialData(Vec<InstanceData>); impl ExtractComponent for InstanceMaterialData { type QueryData = &'static InstanceMaterialData; type QueryFilter = (); type Out = Self; fn extract_component(item: QueryItem<'_, '_, Self::QueryData>) -> Option<Self> { Some(InstanceMaterialData(item.0.clone())) } } struct CustomMaterialPlugin; impl Plugin for CustomMaterialPlugin { fn build(&self, app: &mut App) { app.add_plugins(ExtractComponentPlugin::<InstanceMaterialData>::default()); app.sub_app_mut(RenderApp) .add_render_command::<Transparent3d, DrawCustom>() .init_resource::<SpecializedMeshPipelines<CustomPipeline>>() .add_systems(RenderStartup, init_custom_pipeline) .add_systems( Render, ( queue_custom.in_set(RenderSystems::QueueMeshes), prepare_instance_buffers.in_set(RenderSystems::PrepareResources), ), ); } } #[derive(Clone, Copy, Pod, Zeroable)] #[repr(C)] struct InstanceData { position: Vec3, scale: f32, color: [f32; 4], } fn queue_custom( transparent_3d_draw_functions: Res<DrawFunctions<Transparent3d>>, custom_pipeline: Res<CustomPipeline>, mut pipelines: ResMut<SpecializedMeshPipelines<CustomPipeline>>, pipeline_cache: Res<PipelineCache>, meshes: Res<RenderAssets<RenderMesh>>, render_mesh_instances: Res<RenderMeshInstances>, material_meshes: Query<(Entity, &MainEntity), With<InstanceMaterialData>>, mut transparent_render_phases: ResMut<ViewSortedRenderPhases<Transparent3d>>, views: Query<(&ExtractedView, &Msaa)>, ) { let draw_custom = transparent_3d_draw_functions.read().id::<DrawCustom>(); for (view, msaa) in &views { let Some(transparent_phase) = transparent_render_phases.get_mut(&view.retained_view_entity) else { continue; }; let msaa_key = MeshPipelineKey::from_msaa_samples(msaa.samples()); let view_key = msaa_key | MeshPipelineKey::from_hdr(view.hdr); let rangefinder = view.rangefinder3d(); for (entity, main_entity) in &material_meshes { let Some(mesh_instance) = render_mesh_instances.render_mesh_queue_data(*main_entity) else { continue; }; let Some(mesh) = meshes.get(mesh_instance.mesh_asset_id) else { continue; }; let key = view_key | MeshPipelineKey::from_primitive_topology(mesh.primitive_topology()); let pipeline = pipelines .specialize(&pipeline_cache, &custom_pipeline, key, &mesh.layout) .unwrap(); transparent_phase.add(Transparent3d { entity: (entity, *main_entity), pipeline, draw_function: draw_custom, distance: rangefinder.distance(&mesh_instance.center), batch_range: 0..1, extra_index: PhaseItemExtraIndex::None, indexed: true, }); } } } #[derive(Component)] struct InstanceBuffer { buffer: Buffer, length: usize, } fn prepare_instance_buffers( mut commands: Commands, query: Query<(Entity, &InstanceMaterialData)>, render_device: Res<RenderDevice>, ) { for (entity, instance_data) in &query { let buffer = render_device.create_buffer_with_data(&BufferInitDescriptor { label: Some("instance data buffer"), contents: bytemuck::cast_slice(instance_data.as_slice()), usage: BufferUsages::VERTEX | BufferUsages::COPY_DST, }); commands.entity(entity).insert(InstanceBuffer { buffer, length: instance_data.len(), }); } } #[derive(Resource)] struct CustomPipeline { shader: Handle<Shader>, mesh_pipeline: MeshPipeline, } fn init_custom_pipeline( mut commands: Commands, asset_server: Res<AssetServer>, mesh_pipeline: Res<MeshPipeline>, ) { commands.insert_resource(CustomPipeline { shader: asset_server.load(SHADER_ASSET_PATH), mesh_pipeline: mesh_pipeline.clone(), }); } impl SpecializedMeshPipeline for CustomPipeline { type Key = MeshPipelineKey; fn specialize( &self, key: Self::Key, layout: &MeshVertexBufferLayoutRef, ) -> Result<RenderPipelineDescriptor, SpecializedMeshPipelineError> { let mut descriptor = self.mesh_pipeline.specialize(key, layout)?; descriptor.vertex.shader = self.shader.clone(); descriptor.vertex.buffers.push(VertexBufferLayout { array_stride: size_of::<InstanceData>() as u64, step_mode: VertexStepMode::Instance, attributes: vec![ VertexAttribute { format: VertexFormat::Float32x4, offset: 0, shader_location: 3, // shader locations 0-2 are taken up by Position, Normal and UV attributes }, VertexAttribute { format: VertexFormat::Float32x4, offset: VertexFormat::Float32x4.size(), shader_location: 4, }, ], }); descriptor.fragment.as_mut().unwrap().shader = self.shader.clone(); Ok(descriptor) } } type DrawCustom = ( SetItemPipeline, SetMeshViewBindGroup<0>, SetMeshViewBindingArrayBindGroup<1>, SetMeshBindGroup<2>, DrawMeshInstanced, ); struct DrawMeshInstanced; impl<P: PhaseItem> RenderCommand<P> for DrawMeshInstanced { type Param = ( SRes<RenderAssets<RenderMesh>>, SRes<RenderMeshInstances>, SRes<MeshAllocator>, ); type ViewQuery = (); type ItemQuery = Read<InstanceBuffer>; #[inline] fn render<'w>( item: &P, _view: (), instance_buffer: Option<&'w InstanceBuffer>, (meshes, render_mesh_instances, mesh_allocator): SystemParamItem<'w, '_, Self::Param>, pass: &mut TrackedRenderPass<'w>, ) -> RenderCommandResult { // A borrow check workaround. let mesh_allocator = mesh_allocator.into_inner(); let Some(mesh_instance) = render_mesh_instances.render_mesh_queue_data(item.main_entity()) else { return RenderCommandResult::Skip; }; let Some(gpu_mesh) = meshes.into_inner().get(mesh_instance.mesh_asset_id) else { return RenderCommandResult::Skip; }; let Some(instance_buffer) = instance_buffer else { return RenderCommandResult::Skip; }; let Some(vertex_buffer_slice) = mesh_allocator.mesh_vertex_slice(&mesh_instance.mesh_asset_id) else { return RenderCommandResult::Skip; }; pass.set_vertex_buffer(0, vertex_buffer_slice.buffer.slice(..)); pass.set_vertex_buffer(1, instance_buffer.buffer.slice(..)); match &gpu_mesh.buffer_info { RenderMeshBufferInfo::Indexed { index_format, count, } => { let Some(index_buffer_slice) = mesh_allocator.mesh_index_slice(&mesh_instance.mesh_asset_id) else { return RenderCommandResult::Skip; }; pass.set_index_buffer(index_buffer_slice.buffer.slice(..), *index_format); pass.draw_indexed( index_buffer_slice.range.start..(index_buffer_slice.range.start + count), vertex_buffer_slice.range.start as i32, 0..instance_buffer.length as u32, ); } RenderMeshBufferInfo::NonIndexed => { pass.draw(vertex_buffer_slice.range, 0..instance_buffer.length as u32); } } RenderCommandResult::Success } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/shader_advanced/render_depth_to_texture.rs
examples/shader_advanced/render_depth_to_texture.rs
//! Demonstrates how to use depth-only cameras. //! //! A *depth-only camera* is a camera that renders only to a depth buffer, not //! to a color buffer. That depth buffer can then be used in shaders for various //! special effects. //! //! To create a depth-only camera, we create a [`Camera3d`] and set its //! [`RenderTarget`] to [`RenderTarget::None`] to disable creation of a color //! buffer. Then we add a new node to the render graph that copies the //! [`bevy::render::view::ViewDepthTexture`] that Bevy creates for that camera //! to a texture. This texture can then be attached to a material and sampled in //! the shader. //! //! This demo consists of a rotating cube with a depth-only camera pointed at //! it. The depth texture from the depth-only camera appears on a plane. You can //! use the WASD keys to make the depth-only camera orbit around the cube. use std::f32::consts::{FRAC_PI_2, PI}; use bevy::{ asset::RenderAssetUsages, camera::RenderTarget, color::palettes::css::LIME, core_pipeline::{ core_3d::graph::{Core3d, Node3d}, prepass::DepthPrepass, }, ecs::{query::QueryItem, system::lifetimeless::Read}, image::{ImageCompareFunction, ImageSampler, ImageSamplerDescriptor}, math::ops::{acos, atan2, sin_cos}, prelude::*, render::{ camera::ExtractedCamera, extract_resource::{ExtractResource, ExtractResourcePlugin}, render_asset::RenderAssets, render_graph::{ NodeRunError, RenderGraphContext, RenderGraphExt as _, RenderLabel, ViewNode, ViewNodeRunner, }, render_resource::{ AsBindGroup, CommandEncoderDescriptor, Extent3d, Origin3d, TexelCopyTextureInfo, TextureAspect, TextureDimension, TextureFormat, }, renderer::RenderContext, texture::GpuImage, view::ViewDepthTexture, RenderApp, }, shader::ShaderRef, }; /// A marker component for a rotating cube. #[derive(Component)] struct RotatingCube; /// The material that displays the contents of the depth buffer. /// /// This material is placed on the plane. #[derive(Clone, Debug, Asset, TypePath, AsBindGroup)] struct ShowDepthTextureMaterial { /// A copy of the depth texture that the depth-only camera produced. #[texture(0, sample_type = "depth")] #[sampler(1, sampler_type = "comparison")] depth_texture: Option<Handle<Image>>, } /// A label for the render node that copies the depth buffer from that of the /// camera to the [`DemoDepthTexture`]. #[derive(Clone, PartialEq, Eq, Hash, Debug, RenderLabel)] struct CopyDepthTexturePass; /// The render node that copies the depth buffer from that of the camera to the /// [`DemoDepthTexture`]. #[derive(Default)] struct CopyDepthTextureNode; /// Holds a copy of the depth buffer that the depth-only camera produces. /// /// We need to make a copy for two reasons: /// /// 1. The Bevy renderer automatically creates and maintains depth buffers on /// its own. There's no mechanism to fetch the depth buffer for a camera outside /// the render app. Thus it can't easily be attached to a material. /// /// 2. `wgpu` doesn't allow applications to simultaneously render to and sample /// from a standard depth texture, so a copy must be made regardless. #[derive(Clone, Resource)] struct DemoDepthTexture(Handle<Image>); /// [Spherical coordinates], used to implement the camera orbiting /// functionality. /// /// Note that these are in the mathematics convention, not the physics /// convention. In a real application, one would probably use the physics /// convention, but for familiarity's sake we stick to the most common /// convention here. /// /// [Spherical coordinates]: https://en.wikipedia.org/wiki/Spherical_coordinate_system #[derive(Clone, Copy, Debug)] struct SphericalCoordinates { /// The radius, in world units. radius: f32, /// The elevation angle (latitude). inclination: f32, /// The azimuth angle (longitude). azimuth: f32, } /// The path to the shader that renders the depth texture. static SHADER_ASSET_PATH: &str = "shaders/show_depth_texture_material.wgsl"; /// The size in texels of a depth texture. const DEPTH_TEXTURE_SIZE: u32 = 256; /// The rate at which the user can move the camera, in radians per second. const CAMERA_MOVEMENT_SPEED: f32 = 2.0; /// The entry point. fn main() { let mut app = App::new(); app.add_plugins(DefaultPlugins) .add_plugins(MaterialPlugin::<ShowDepthTextureMaterial>::default()) .add_plugins(ExtractResourcePlugin::<DemoDepthTexture>::default()) .init_resource::<DemoDepthTexture>() .add_systems(Startup, setup) .add_systems(Update, rotate_cube) .add_systems(Update, draw_camera_gizmo) .add_systems(Update, move_camera); // Add the `CopyDepthTextureNode` to the render app. let render_app = app .get_sub_app_mut(RenderApp) .expect("Render app should be present"); render_app.add_render_graph_node::<ViewNodeRunner<CopyDepthTextureNode>>( Core3d, CopyDepthTexturePass, ); // We have the texture copy operation run in between the prepasses and // the opaque pass. Since the depth rendering is part of the prepass, this // is a reasonable time to perform the operation. render_app.add_render_graph_edges( Core3d, ( Node3d::EndPrepasses, CopyDepthTexturePass, Node3d::MainOpaquePass, ), ); app.run(); } /// Creates the scene. fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut standard_materials: ResMut<Assets<StandardMaterial>>, mut show_depth_texture_materials: ResMut<Assets<ShowDepthTextureMaterial>>, demo_depth_texture: Res<DemoDepthTexture>, ) { spawn_rotating_cube(&mut commands, &mut meshes, &mut standard_materials); spawn_plane( &mut commands, &mut meshes, &mut show_depth_texture_materials, &demo_depth_texture, ); spawn_light(&mut commands); spawn_depth_only_camera(&mut commands); spawn_main_camera(&mut commands); spawn_instructions(&mut commands); } /// Spawns the main rotating cube. fn spawn_rotating_cube( commands: &mut Commands, meshes: &mut Assets<Mesh>, standard_materials: &mut Assets<StandardMaterial>, ) { let cube_handle = meshes.add(Cuboid::new(3.0, 3.0, 3.0)); let rotating_cube_material_handle = standard_materials.add(StandardMaterial { base_color: Color::WHITE, unlit: false, ..default() }); commands.spawn(( Mesh3d(cube_handle.clone()), MeshMaterial3d(rotating_cube_material_handle), Transform::IDENTITY, RotatingCube, )); } // Spawns the plane that shows the depth texture. fn spawn_plane( commands: &mut Commands, meshes: &mut Assets<Mesh>, show_depth_texture_materials: &mut Assets<ShowDepthTextureMaterial>, demo_depth_texture: &DemoDepthTexture, ) { let plane_handle = meshes.add(Plane3d::new(Vec3::Z, Vec2::splat(2.0))); let show_depth_texture_material = show_depth_texture_materials.add(ShowDepthTextureMaterial { depth_texture: Some(demo_depth_texture.0.clone()), }); commands.spawn(( Mesh3d(plane_handle), MeshMaterial3d(show_depth_texture_material), Transform::from_xyz(10.0, 4.0, 0.0).with_scale(Vec3::splat(2.5)), )); } /// Spawns a light. fn spawn_light(commands: &mut Commands) { commands.spawn((PointLight::default(), Transform::from_xyz(5.0, 6.0, 7.0))); } /// Spawns the depth-only camera. fn spawn_depth_only_camera(commands: &mut Commands) { commands.spawn(( Camera3d::default(), Transform::from_xyz(-4.0, -5.0, 5.0).looking_at(Vec3::ZERO, Vec3::Y), Camera { // Make sure that we render from this depth-only camera *before* // rendering from the main camera. order: -1, ..Camera::default() }, // We specify no color render target, for maximum efficiency. RenderTarget::None { // When specifying no render target, we must manually specify // the viewport size. Otherwise, Bevy won't know how big to make // the depth buffer. size: UVec2::splat(DEPTH_TEXTURE_SIZE), }, // We need to disable multisampling or the depth texture will be // multisampled, which adds complexity we don't care about for this // demo. Msaa::Off, // Cameras with no render target render *nothing* by default. To get // them to render something, we must add a prepass that specifies what // we want to render: in this case, depth. DepthPrepass, )); } /// Spawns the main camera that renders to the window. fn spawn_main_camera(commands: &mut Commands) { commands.spawn(( Camera3d::default(), Transform::from_xyz(5.0, 2.0, 30.0).looking_at(vec3(5.0, 2.0, 0.0), Vec3::Y), // Disable antialiasing just for simplicity's sake. Msaa::Off, )); } /// Spawns the instructional text at the top of the screen. fn spawn_instructions(commands: &mut Commands) { commands.spawn(( Text::new("Use WASD to move the secondary camera"), Node { position_type: PositionType::Absolute, top: Val::Px(12.0), left: Val::Px(12.0), ..Node::default() }, )); } /// Spins the cube a bit every frame. fn rotate_cube(mut cubes: Query<&mut Transform, With<RotatingCube>>, time: Res<Time>) { for mut transform in &mut cubes { transform.rotate_x(1.5 * time.delta_secs()); transform.rotate_y(1.1 * time.delta_secs()); transform.rotate_z(-1.3 * time.delta_secs()); } } impl Material for ShowDepthTextureMaterial { fn fragment_shader() -> ShaderRef { SHADER_ASSET_PATH.into() } } impl ViewNode for CopyDepthTextureNode { type ViewQuery = (Read<ExtractedCamera>, Read<ViewDepthTexture>); fn run<'w>( &self, _: &mut RenderGraphContext, render_context: &mut RenderContext<'w>, (camera, depth_texture): QueryItem<'w, '_, Self::ViewQuery>, world: &'w World, ) -> Result<(), NodeRunError> { // Make sure we only run on the depth-only camera. // We could make a marker component for that camera and extract it to // the render world, but using `order` as a tag to tell the main camera // and the depth-only camera apart works in a pinch. if camera.order >= 0 { return Ok(()); } // Grab the texture we're going to copy to. let demo_depth_texture = world.resource::<DemoDepthTexture>(); let image_assets = world.resource::<RenderAssets<GpuImage>>(); let Some(demo_depth_image) = image_assets.get(demo_depth_texture.0.id()) else { return Ok(()); }; // Perform the copy. render_context.add_command_buffer_generation_task(move |render_device| { let mut command_encoder = render_device.create_command_encoder(&CommandEncoderDescriptor { label: Some("copy depth to demo texture command encoder"), }); command_encoder.push_debug_group("copy depth to demo texture"); // Copy from the view's depth texture to the destination depth // texture. command_encoder.copy_texture_to_texture( TexelCopyTextureInfo { texture: &depth_texture.texture, mip_level: 0, origin: Origin3d::default(), aspect: TextureAspect::DepthOnly, }, TexelCopyTextureInfo { texture: &demo_depth_image.texture, mip_level: 0, origin: Origin3d::default(), aspect: TextureAspect::DepthOnly, }, Extent3d { width: DEPTH_TEXTURE_SIZE, height: DEPTH_TEXTURE_SIZE, depth_or_array_layers: 1, }, ); command_encoder.pop_debug_group(); command_encoder.finish() }); Ok(()) } } impl FromWorld for DemoDepthTexture { fn from_world(world: &mut World) -> Self { let mut images = world.resource_mut::<Assets<Image>>(); // Create a new 32-bit floating point depth texture. let mut depth_image = Image::new_uninit( Extent3d { width: DEPTH_TEXTURE_SIZE, height: DEPTH_TEXTURE_SIZE, depth_or_array_layers: 1, }, TextureDimension::D2, TextureFormat::Depth32Float, RenderAssetUsages::default(), ); // Create a sampler. Note that this needs to specify a `compare` // function in order to be compatible with depth textures. depth_image.sampler = ImageSampler::Descriptor(ImageSamplerDescriptor { label: Some("custom depth image sampler".to_owned()), compare: Some(ImageCompareFunction::Always), ..ImageSamplerDescriptor::default() }); let depth_image_handle = images.add(depth_image); DemoDepthTexture(depth_image_handle) } } impl ExtractResource for DemoDepthTexture { type Source = Self; fn extract_resource(source: &Self::Source) -> Self { // Share the `DemoDepthTexture` resource over to the render world so // that our `CopyDepthTextureNode` can access it. (*source).clone() } } /// Draws an outline of the depth texture on the screen. fn draw_camera_gizmo(cameras: Query<(&Camera, &GlobalTransform)>, mut gizmos: Gizmos) { for (camera, transform) in &cameras { // As above, we use the order as a cheap tag to tell the depth texture // apart from the main texture. if camera.order >= 0 { continue; } // Draw a cone representing the camera. gizmos.primitive_3d( &Cone { radius: 1.0, height: 3.0, }, Isometry3d::new( transform.translation(), // We have to rotate here because `Cone` primitives are oriented // along +Y and cameras point along +Z. transform.rotation() * Quat::from_rotation_x(FRAC_PI_2), ), LIME, ); } } /// Orbits the cube when WASD is pressed. fn move_camera( mut cameras: Query<(&Camera, &mut Transform)>, keyboard: Res<ButtonInput<KeyCode>>, time: Res<Time>, ) { for (camera, mut transform) in &mut cameras { // Only affect the depth camera. if camera.order >= 0 { continue; } // Convert the camera's position from Cartesian to spherical coordinates. let mut spherical_coords = SphericalCoordinates::from_cartesian(transform.translation); // Modify those spherical coordinates as appropriate. let mut changed = false; if keyboard.pressed(KeyCode::KeyW) { spherical_coords.inclination -= time.delta_secs() * CAMERA_MOVEMENT_SPEED; changed = true; } if keyboard.pressed(KeyCode::KeyS) { spherical_coords.inclination += time.delta_secs() * CAMERA_MOVEMENT_SPEED; changed = true; } if keyboard.pressed(KeyCode::KeyA) { spherical_coords.azimuth += time.delta_secs() * CAMERA_MOVEMENT_SPEED; changed = true; } if keyboard.pressed(KeyCode::KeyD) { spherical_coords.azimuth -= time.delta_secs() * CAMERA_MOVEMENT_SPEED; changed = true; } // If they were changed, convert from spherical coordinates back to // Cartesian ones, and update the camera's transform. if changed { spherical_coords.inclination = spherical_coords.inclination.clamp(0.01, PI - 0.01); transform.translation = spherical_coords.to_cartesian(); transform.look_at(Vec3::ZERO, Vec3::Y); } } } impl SphericalCoordinates { /// [Converts] from Cartesian coordinates to spherical coordinates. /// /// [Converts]: https://en.wikipedia.org/wiki/Spherical_coordinate_system#Cartesian_coordinates fn from_cartesian(p: Vec3) -> SphericalCoordinates { let radius = p.length(); SphericalCoordinates { radius, inclination: acos(p.y / radius), azimuth: atan2(p.z, p.x), } } /// [Converts] from spherical coordinates to Cartesian coordinates. /// /// [Converts]: https://en.wikipedia.org/wiki/Spherical_coordinate_system#Cartesian_coordinates fn to_cartesian(self) -> Vec3 { let (sin_inclination, cos_inclination) = sin_cos(self.inclination); let (sin_azimuth, cos_azimuth) = sin_cos(self.azimuth); self.radius * vec3( sin_inclination * cos_azimuth, cos_inclination, sin_inclination * sin_azimuth, ) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/shader_advanced/fullscreen_material.rs
examples/shader_advanced/fullscreen_material.rs
//! Demonstrates how to write a custom fullscreen shader //! //! This is currently limited to 3d only but work is in progress to make it work in 2d use bevy::{ core_pipeline::{ core_3d::graph::Node3d, fullscreen_material::{FullscreenMaterial, FullscreenMaterialPlugin}, }, prelude::*, render::{ extract_component::ExtractComponent, render_graph::{InternedRenderLabel, RenderLabel}, render_resource::ShaderType, }, shader::ShaderRef, }; fn main() { App::new() .add_plugins(( DefaultPlugins, FullscreenMaterialPlugin::<FullscreenEffect>::default(), )) .add_systems(Startup, setup) .run(); } fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { // camera commands.spawn(( Camera3d::default(), Transform::from_translation(Vec3::new(0.0, 0.0, 5.0)).looking_at(Vec3::default(), Vec3::Y), FullscreenEffect { intensity: 0.005 }, )); // cube commands.spawn(( Mesh3d(meshes.add(Cuboid::default())), MeshMaterial3d(materials.add(Color::srgb(0.8, 0.7, 0.6))), Transform::default(), )); // light commands.spawn(DirectionalLight { illuminance: 1_000., ..default() }); } // This is the struct that will be sent to your shader // // Currently, this doesn't support AsBindGroup so you can only use it to send a struct to your // shader. We are working on adding AsBindGroup support in the future so you can bind anything you // need. #[derive(Component, ExtractComponent, Clone, Copy, ShaderType, Default)] struct FullscreenEffect { // For this example, this is used as the intensity of the effect, but you can pass in any valid // ShaderType // // In the future, you will be able to use a full bind group intensity: f32, } impl FullscreenMaterial for FullscreenEffect { // The shader that will be used fn fragment_shader() -> ShaderRef { "shaders/fullscreen_effect.wgsl".into() } // This let's you specify a list of edges used to order when your effect pass will run // // This example is a post processing effect so it will run after tonemapping but before the end // post processing pass. // // In 2d you would need to use [`Node2d`] instead of [`Node3d`] fn node_edges() -> Vec<InternedRenderLabel> { vec![ Node3d::Tonemapping.intern(), // The label is automatically generated from the name of the struct Self::node_label().intern(), Node3d::EndMainPassPostProcessing.intern(), ] } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/shader_advanced/manual_material.rs
examples/shader_advanced/manual_material.rs
//! A simple 3D scene with light shining over a cube sitting on a plane. use bevy::{ asset::{AsAssetId, AssetEventSystems}, core_pipeline::core_3d::Opaque3d, ecs::system::{ lifetimeless::{SRes, SResMut}, SystemChangeTick, SystemParamItem, }, pbr::{ late_sweep_material_instances, DrawMaterial, EntitiesNeedingSpecialization, EntitySpecializationTickPair, EntitySpecializationTicks, MainPassOpaqueDrawFunction, MaterialBindGroupAllocator, MaterialBindGroupAllocators, MaterialExtractEntitiesNeedingSpecializationSystems, MaterialExtractionSystems, MaterialFragmentShader, MaterialProperties, PreparedMaterial, RenderMaterialBindings, RenderMaterialInstance, RenderMaterialInstances, SpecializedMaterialPipelineCache, }, platform::collections::hash_map::Entry, prelude::*, render::{ erased_render_asset::{ErasedRenderAsset, ErasedRenderAssetPlugin, PrepareAssetError}, render_asset::RenderAssets, render_phase::DrawFunctions, render_resource::{ binding_types::{sampler, texture_2d}, AsBindGroup, BindGroupLayoutDescriptor, BindGroupLayoutEntries, BindingResources, OwnedBindingResource, Sampler, SamplerBindingType, SamplerDescriptor, ShaderStages, TextureSampleType, TextureViewDimension, UnpreparedBindGroup, }, renderer::RenderDevice, sync_world::MainEntity, texture::GpuImage, view::ExtractedView, Extract, RenderApp, RenderStartup, }, utils::Parallel, }; use std::{any::TypeId, sync::Arc}; const SHADER_ASSET_PATH: &str = "shaders/manual_material.wgsl"; fn main() { App::new() .add_plugins((DefaultPlugins, ImageMaterialPlugin)) .add_systems(Startup, setup) .run(); } struct ImageMaterialPlugin; impl Plugin for ImageMaterialPlugin { fn build(&self, app: &mut App) { app.init_asset::<ImageMaterial>() .add_plugins(ErasedRenderAssetPlugin::<ImageMaterial>::default()) .add_systems( PostUpdate, check_entities_needing_specialization.after(AssetEventSystems), ) .init_resource::<EntitiesNeedingSpecialization<ImageMaterial>>(); let Some(render_app) = app.get_sub_app_mut(RenderApp) else { return; }; render_app .add_systems(RenderStartup, init_image_material_resources) .add_systems( ExtractSchedule, ( extract_image_materials, extract_image_materials_needing_specialization .in_set(MaterialExtractEntitiesNeedingSpecializationSystems), sweep_image_materials_needing_specialization .after(MaterialExtractEntitiesNeedingSpecializationSystems) .after(MaterialExtractionSystems) .before(late_sweep_material_instances), ), ); } } fn init_image_material_resources( mut commands: Commands, render_device: Res<RenderDevice>, mut bind_group_allocators: ResMut<MaterialBindGroupAllocators>, ) { let bind_group_layout = BindGroupLayoutDescriptor::new( "image_material_layout", &BindGroupLayoutEntries::sequential( ShaderStages::FRAGMENT, ( texture_2d(TextureSampleType::Float { filterable: false }), sampler(SamplerBindingType::NonFiltering), ), ), ); let sampler = render_device.create_sampler(&SamplerDescriptor::default()); commands.insert_resource(ImageMaterialBindGroupLayout(bind_group_layout.clone())); commands.insert_resource(ImageMaterialBindGroupSampler(sampler)); bind_group_allocators.insert( TypeId::of::<ImageMaterial>(), MaterialBindGroupAllocator::new( &render_device, "image_material_allocator", None, bind_group_layout, None, ), ); } #[derive(Resource)] struct ImageMaterialBindGroupLayout(BindGroupLayoutDescriptor); #[derive(Resource)] struct ImageMaterialBindGroupSampler(Sampler); #[derive(Component)] struct ImageMaterial3d(Handle<ImageMaterial>); impl AsAssetId for ImageMaterial3d { type Asset = ImageMaterial; fn as_asset_id(&self) -> AssetId<Self::Asset> { self.0.id() } } #[derive(Asset, TypePath, AsBindGroup, Debug, Clone)] struct ImageMaterial { image: Handle<Image>, } impl ErasedRenderAsset for ImageMaterial { type SourceAsset = ImageMaterial; type ErasedAsset = PreparedMaterial; type Param = ( SRes<DrawFunctions<Opaque3d>>, SRes<ImageMaterialBindGroupLayout>, SRes<AssetServer>, SResMut<MaterialBindGroupAllocators>, SResMut<RenderMaterialBindings>, SRes<RenderAssets<GpuImage>>, SRes<ImageMaterialBindGroupSampler>, ); fn prepare_asset( source_asset: Self::SourceAsset, asset_id: AssetId<Self::SourceAsset>, ( opaque_draw_functions, material_layout, asset_server, bind_group_allocators, render_material_bindings, gpu_images, image_material_sampler, ): &mut SystemParamItem<Self::Param>, ) -> std::result::Result<Self::ErasedAsset, PrepareAssetError<Self::SourceAsset>> { let material_layout = material_layout.0.clone(); let draw_function_id = opaque_draw_functions.read().id::<DrawMaterial>(); let bind_group_allocator = bind_group_allocators .get_mut(&TypeId::of::<ImageMaterial>()) .unwrap(); let Some(image) = gpu_images.get(&source_asset.image) else { return Err(PrepareAssetError::RetryNextUpdate(source_asset)); }; let unprepared = UnpreparedBindGroup { bindings: BindingResources(vec![ ( 0, OwnedBindingResource::TextureView( TextureViewDimension::D2, image.texture_view.clone(), ), ), ( 1, OwnedBindingResource::Sampler( SamplerBindingType::NonFiltering, image_material_sampler.0.clone(), ), ), ]), }; let binding = match render_material_bindings.entry(asset_id.into()) { Entry::Occupied(mut occupied_entry) => { bind_group_allocator.free(*occupied_entry.get()); let new_binding = bind_group_allocator.allocate_unprepared(unprepared, &material_layout); *occupied_entry.get_mut() = new_binding; new_binding } Entry::Vacant(vacant_entry) => *vacant_entry .insert(bind_group_allocator.allocate_unprepared(unprepared, &material_layout)), }; let mut properties = MaterialProperties { material_layout: Some(material_layout), ..Default::default() }; properties.add_draw_function(MainPassOpaqueDrawFunction, draw_function_id); properties.add_shader(MaterialFragmentShader, asset_server.load(SHADER_ASSET_PATH)); Ok(PreparedMaterial { binding, properties: Arc::new(properties), }) } } /// set up a simple 3D scene fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<ImageMaterial>>, asset_server: Res<AssetServer>, ) { // cube commands.spawn(( Mesh3d(meshes.add(Cuboid::new(2.0, 2.0, 2.0))), ImageMaterial3d(materials.add(ImageMaterial { image: asset_server.load("branding/icon.png"), })), Transform::from_xyz(0.0, 0.5, 0.0), )); // light commands.spawn(( PointLight { shadows_enabled: true, ..default() }, Transform::from_xyz(4.0, 8.0, 4.0), )); // camera commands.spawn(( Camera3d::default(), Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y), )); } fn extract_image_materials( mut material_instances: ResMut<RenderMaterialInstances>, changed_meshes_query: Extract< Query< (Entity, &ViewVisibility, &ImageMaterial3d), Or<(Changed<ViewVisibility>, Changed<ImageMaterial3d>)>, >, >, ) { let last_change_tick = material_instances.current_change_tick; for (entity, view_visibility, material) in &changed_meshes_query { if view_visibility.get() { material_instances.instances.insert( entity.into(), RenderMaterialInstance { asset_id: material.0.id().untyped(), last_change_tick, }, ); } else { material_instances .instances .remove(&MainEntity::from(entity)); } } } fn check_entities_needing_specialization( needs_specialization: Query< Entity, ( Or<( Changed<Mesh3d>, AssetChanged<Mesh3d>, Changed<ImageMaterial3d>, AssetChanged<ImageMaterial3d>, )>, With<ImageMaterial3d>, ), >, mut par_local: Local<Parallel<Vec<Entity>>>, mut entities_needing_specialization: ResMut<EntitiesNeedingSpecialization<ImageMaterial>>, ) { entities_needing_specialization.clear(); needs_specialization .par_iter() .for_each(|entity| par_local.borrow_local_mut().push(entity)); par_local.drain_into(&mut entities_needing_specialization); } fn extract_image_materials_needing_specialization( entities_needing_specialization: Extract<Res<EntitiesNeedingSpecialization<ImageMaterial>>>, mut entity_specialization_ticks: ResMut<EntitySpecializationTicks>, mut removed_mesh_material_components: Extract<RemovedComponents<ImageMaterial3d>>, mut specialized_material_pipeline_cache: ResMut<SpecializedMaterialPipelineCache>, render_material_instances: Res<RenderMaterialInstances>, views: Query<&ExtractedView>, ticks: SystemChangeTick, ) { // Clean up any despawned entities, we do this first in case the removed material was re-added // the same frame, thus will appear both in the removed components list and have been added to // the `EntitiesNeedingSpecialization` collection by triggering the `Changed` filter for entity in removed_mesh_material_components.read() { entity_specialization_ticks.remove(&MainEntity::from(entity)); for view in views { if let Some(cache) = specialized_material_pipeline_cache.get_mut(&view.retained_view_entity) { cache.remove(&MainEntity::from(entity)); } } } for entity in entities_needing_specialization.iter() { // Update the entity's specialization tick with this run's tick entity_specialization_ticks.insert( (*entity).into(), EntitySpecializationTickPair { system_tick: ticks.this_run(), material_instances_tick: render_material_instances.current_change_tick, }, ); } } fn sweep_image_materials_needing_specialization( mut entity_specialization_ticks: ResMut<EntitySpecializationTicks>, mut removed_mesh_material_components: Extract<RemovedComponents<ImageMaterial3d>>, mut specialized_material_pipeline_cache: ResMut<SpecializedMaterialPipelineCache>, render_material_instances: Res<RenderMaterialInstances>, views: Query<&ExtractedView>, ) { // Clean up any despawned entities, we do this first in case the removed material was re-added // the same frame, thus will appear both in the removed components list and have been added to // the `EntitiesNeedingSpecialization` collection by triggering the `Changed` filter for entity in removed_mesh_material_components.read() { if entity_specialization_ticks .get(&MainEntity::from(entity)) .is_some_and(|ticks| { ticks.material_instances_tick == render_material_instances.current_change_tick }) { continue; } entity_specialization_ticks.remove(&MainEntity::from(entity)); for view in views { if let Some(cache) = specialized_material_pipeline_cache.get_mut(&view.retained_view_entity) { cache.remove(&MainEntity::from(entity)); } } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/shader_advanced/custom_render_phase.rs
examples/shader_advanced/custom_render_phase.rs
//! This example demonstrates how to write a custom phase //! //! Render phases in bevy are used whenever you need to draw a group of meshes in a specific way. //! For example, bevy's main pass has an opaque phase, a transparent phase for both 2d and 3d. //! Sometimes, you may want to only draw a subset of meshes before or after the builtin phase. In //! those situations you need to write your own phase. //! //! This example showcases how writing a custom phase to draw a stencil of a bevy mesh could look //! like. Some shortcuts have been used for simplicity. //! //! This example was made for 3d, but a 2d equivalent would be almost identical. use std::ops::Range; use bevy::camera::Viewport; use bevy::pbr::SetMeshViewEmptyBindGroup; use bevy::{ camera::MainPassResolutionOverride, core_pipeline::core_3d::graph::{Core3d, Node3d}, ecs::{ query::QueryItem, system::{lifetimeless::SRes, SystemParamItem}, }, math::FloatOrd, mesh::MeshVertexBufferLayoutRef, pbr::{ DrawMesh, MeshInputUniform, MeshPipeline, MeshPipelineKey, MeshPipelineViewLayoutKey, MeshUniform, RenderMeshInstances, SetMeshBindGroup, SetMeshViewBindGroup, }, platform::collections::HashSet, prelude::*, render::{ batching::{ gpu_preprocessing::{ batch_and_prepare_sorted_render_phase, IndirectParametersCpuMetadata, UntypedPhaseIndirectParametersBuffers, }, GetBatchData, GetFullBatchData, }, camera::ExtractedCamera, extract_component::{ExtractComponent, ExtractComponentPlugin}, mesh::{allocator::MeshAllocator, RenderMesh}, render_asset::RenderAssets, render_graph::{ NodeRunError, RenderGraphContext, RenderGraphExt, RenderLabel, ViewNode, ViewNodeRunner, }, render_phase::{ sort_phase_system, AddRenderCommand, CachedRenderPipelinePhaseItem, DrawFunctionId, DrawFunctions, PhaseItem, PhaseItemExtraIndex, SetItemPipeline, SortedPhaseItem, SortedRenderPhasePlugin, ViewSortedRenderPhases, }, render_resource::{ CachedRenderPipelineId, ColorTargetState, ColorWrites, Face, FragmentState, PipelineCache, PrimitiveState, RenderPassDescriptor, RenderPipelineDescriptor, SpecializedMeshPipeline, SpecializedMeshPipelineError, SpecializedMeshPipelines, TextureFormat, VertexState, }, renderer::RenderContext, sync_world::MainEntity, view::{ExtractedView, RenderVisibleEntities, RetainedViewEntity, ViewTarget}, Extract, Render, RenderApp, RenderDebugFlags, RenderStartup, RenderSystems, }, }; use nonmax::NonMaxU32; const SHADER_ASSET_PATH: &str = "shaders/custom_stencil.wgsl"; fn main() { App::new() .add_plugins((DefaultPlugins, MeshStencilPhasePlugin)) .add_systems(Startup, setup) .run(); } fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { // circular base commands.spawn(( Mesh3d(meshes.add(Circle::new(4.0))), MeshMaterial3d(materials.add(Color::WHITE)), Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)), )); // cube // This cube will be rendered by the main pass, but it will also be rendered by our custom // pass. This should result in an unlit red cube commands.spawn(( Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))), MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))), Transform::from_xyz(0.0, 0.5, 0.0), // This marker component is used to identify which mesh will be used in our custom pass // The circle doesn't have it so it won't be rendered in our pass DrawStencil, )); // light commands.spawn(( PointLight { shadows_enabled: true, ..default() }, Transform::from_xyz(4.0, 8.0, 4.0), )); // camera commands.spawn(( Camera3d::default(), Transform::from_xyz(-2.0, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y), // disable msaa for simplicity Msaa::Off, )); } #[derive(Component, ExtractComponent, Clone, Copy, Default)] struct DrawStencil; struct MeshStencilPhasePlugin; impl Plugin for MeshStencilPhasePlugin { fn build(&self, app: &mut App) { app.add_plugins(( ExtractComponentPlugin::<DrawStencil>::default(), SortedRenderPhasePlugin::<Stencil3d, MeshPipeline>::new(RenderDebugFlags::default()), )); // We need to get the render app from the main app let Some(render_app) = app.get_sub_app_mut(RenderApp) else { return; }; render_app .init_resource::<SpecializedMeshPipelines<StencilPipeline>>() .init_resource::<DrawFunctions<Stencil3d>>() .add_render_command::<Stencil3d, DrawMesh3dStencil>() .init_resource::<ViewSortedRenderPhases<Stencil3d>>() .add_systems(RenderStartup, init_stencil_pipeline) .add_systems(ExtractSchedule, extract_camera_phases) .add_systems( Render, ( queue_custom_meshes.in_set(RenderSystems::QueueMeshes), sort_phase_system::<Stencil3d>.in_set(RenderSystems::PhaseSort), batch_and_prepare_sorted_render_phase::<Stencil3d, StencilPipeline> .in_set(RenderSystems::PrepareResources), ), ); render_app .add_render_graph_node::<ViewNodeRunner<CustomDrawNode>>(Core3d, CustomDrawPassLabel) // Tell the node to run after the main pass .add_render_graph_edges(Core3d, (Node3d::MainOpaquePass, CustomDrawPassLabel)); } } #[derive(Resource)] struct StencilPipeline { /// The base mesh pipeline defined by bevy /// /// Since we want to draw a stencil of an existing bevy mesh we want to reuse the default /// pipeline as much as possible mesh_pipeline: MeshPipeline, /// Stores the shader used for this pipeline directly on the pipeline. /// This isn't required, it's only done like this for simplicity. shader_handle: Handle<Shader>, } fn init_stencil_pipeline( mut commands: Commands, mesh_pipeline: Res<MeshPipeline>, asset_server: Res<AssetServer>, ) { commands.insert_resource(StencilPipeline { mesh_pipeline: mesh_pipeline.clone(), shader_handle: asset_server.load(SHADER_ASSET_PATH), }); } // For more information on how SpecializedMeshPipeline work, please look at the // specialized_mesh_pipeline example impl SpecializedMeshPipeline for StencilPipeline { type Key = MeshPipelineKey; fn specialize( &self, key: Self::Key, layout: &MeshVertexBufferLayoutRef, ) -> Result<RenderPipelineDescriptor, SpecializedMeshPipelineError> { // We will only use the position of the mesh in our shader so we only need to specify that let mut vertex_attributes = Vec::new(); if layout.0.contains(Mesh::ATTRIBUTE_POSITION) { // Make sure this matches the shader location vertex_attributes.push(Mesh::ATTRIBUTE_POSITION.at_shader_location(0)); } // This will automatically generate the correct `VertexBufferLayout` based on the vertex attributes let vertex_buffer_layout = layout.0.get_layout(&vertex_attributes)?; let view_layout = self .mesh_pipeline .get_view_layout(MeshPipelineViewLayoutKey::from(key)); Ok(RenderPipelineDescriptor { label: Some("Specialized Mesh Pipeline".into()), // We want to reuse the data from bevy so we use the same bind groups as the default // mesh pipeline layout: vec![ // Bind group 0 is the view uniform view_layout.main_layout.clone(), // Bind group 1 is empty view_layout.empty_layout.clone(), // Bind group 2 is the mesh uniform self.mesh_pipeline.mesh_layouts.model_only.clone(), ], vertex: VertexState { shader: self.shader_handle.clone(), buffers: vec![vertex_buffer_layout], ..default() }, fragment: Some(FragmentState { shader: self.shader_handle.clone(), targets: vec![Some(ColorTargetState { format: TextureFormat::bevy_default(), blend: None, write_mask: ColorWrites::ALL, })], ..default() }), primitive: PrimitiveState { topology: key.primitive_topology(), cull_mode: Some(Face::Back), ..default() }, // It's generally recommended to specialize your pipeline for MSAA, // but it's not always possible ..default() }) } } // We will reuse render commands already defined by bevy to draw a 3d mesh type DrawMesh3dStencil = ( SetItemPipeline, // This will set the view bindings in group 0 SetMeshViewBindGroup<0>, // This will set an empty bind group in group 1 SetMeshViewEmptyBindGroup<1>, // This will set the mesh bindings in group 2 SetMeshBindGroup<2>, // This will draw the mesh DrawMesh, ); // This is the data required per entity drawn in a custom phase in bevy. More specifically this is the // data required when using a ViewSortedRenderPhase. This would look differently if we wanted a // batched render phase. Sorted phases are a bit easier to implement, but a batched phase would // look similar. // // If you want to see how a batched phase implementation looks, you should look at the Opaque2d // phase. struct Stencil3d { pub sort_key: FloatOrd, pub entity: (Entity, MainEntity), pub pipeline: CachedRenderPipelineId, pub draw_function: DrawFunctionId, pub batch_range: Range<u32>, pub extra_index: PhaseItemExtraIndex, /// Whether the mesh in question is indexed (uses an index buffer in /// addition to its vertex buffer). pub indexed: bool, } // For more information about writing a phase item, please look at the custom_phase_item example impl PhaseItem for Stencil3d { #[inline] fn entity(&self) -> Entity { self.entity.0 } #[inline] fn main_entity(&self) -> MainEntity { self.entity.1 } #[inline] fn draw_function(&self) -> DrawFunctionId { self.draw_function } #[inline] fn batch_range(&self) -> &Range<u32> { &self.batch_range } #[inline] fn batch_range_mut(&mut self) -> &mut Range<u32> { &mut self.batch_range } #[inline] fn extra_index(&self) -> PhaseItemExtraIndex { self.extra_index.clone() } #[inline] fn batch_range_and_extra_index_mut(&mut self) -> (&mut Range<u32>, &mut PhaseItemExtraIndex) { (&mut self.batch_range, &mut self.extra_index) } } impl SortedPhaseItem for Stencil3d { type SortKey = FloatOrd; #[inline] fn sort_key(&self) -> Self::SortKey { self.sort_key } #[inline] fn sort(items: &mut [Self]) { // bevy normally uses radsort instead of the std slice::sort_by_key // radsort is a stable radix sort that performed better than `slice::sort_by_key` or `slice::sort_unstable_by_key`. // Since it is not re-exported by bevy, we just use the std sort for the purpose of the example items.sort_by_key(SortedPhaseItem::sort_key); } #[inline] fn indexed(&self) -> bool { self.indexed } } impl CachedRenderPipelinePhaseItem for Stencil3d { #[inline] fn cached_pipeline(&self) -> CachedRenderPipelineId { self.pipeline } } impl GetBatchData for StencilPipeline { type Param = ( SRes<RenderMeshInstances>, SRes<RenderAssets<RenderMesh>>, SRes<MeshAllocator>, ); type CompareData = AssetId<Mesh>; type BufferData = MeshUniform; fn get_batch_data( (mesh_instances, _render_assets, mesh_allocator): &SystemParamItem<Self::Param>, (_entity, main_entity): (Entity, MainEntity), ) -> Option<(Self::BufferData, Option<Self::CompareData>)> { let RenderMeshInstances::CpuBuilding(ref mesh_instances) = **mesh_instances else { error!( "`get_batch_data` should never be called in GPU mesh uniform \ building mode" ); return None; }; let mesh_instance = mesh_instances.get(&main_entity)?; let first_vertex_index = match mesh_allocator.mesh_vertex_slice(&mesh_instance.mesh_asset_id) { Some(mesh_vertex_slice) => mesh_vertex_slice.range.start, None => 0, }; let mesh_uniform = { let mesh_transforms = &mesh_instance.transforms; let (local_from_world_transpose_a, local_from_world_transpose_b) = mesh_transforms.world_from_local.inverse_transpose_3x3(); MeshUniform { world_from_local: mesh_transforms.world_from_local.to_transpose(), previous_world_from_local: mesh_transforms.previous_world_from_local.to_transpose(), lightmap_uv_rect: UVec2::ZERO, local_from_world_transpose_a, local_from_world_transpose_b, flags: mesh_transforms.flags, first_vertex_index, current_skin_index: u32::MAX, material_and_lightmap_bind_group_slot: 0, tag: 0, pad: 0, } }; Some((mesh_uniform, None)) } } impl GetFullBatchData for StencilPipeline { type BufferInputData = MeshInputUniform; fn get_index_and_compare_data( (mesh_instances, _, _): &SystemParamItem<Self::Param>, main_entity: MainEntity, ) -> Option<(NonMaxU32, Option<Self::CompareData>)> { // This should only be called during GPU building. let RenderMeshInstances::GpuBuilding(ref mesh_instances) = **mesh_instances else { error!( "`get_index_and_compare_data` should never be called in CPU mesh uniform building \ mode" ); return None; }; let mesh_instance = mesh_instances.get(&main_entity)?; Some(( mesh_instance.current_uniform_index, mesh_instance .should_batch() .then_some(mesh_instance.mesh_asset_id), )) } fn get_binned_batch_data( (mesh_instances, _render_assets, mesh_allocator): &SystemParamItem<Self::Param>, main_entity: MainEntity, ) -> Option<Self::BufferData> { let RenderMeshInstances::CpuBuilding(ref mesh_instances) = **mesh_instances else { error!( "`get_binned_batch_data` should never be called in GPU mesh uniform building mode" ); return None; }; let mesh_instance = mesh_instances.get(&main_entity)?; let first_vertex_index = match mesh_allocator.mesh_vertex_slice(&mesh_instance.mesh_asset_id) { Some(mesh_vertex_slice) => mesh_vertex_slice.range.start, None => 0, }; Some(MeshUniform::new( &mesh_instance.transforms, first_vertex_index, mesh_instance.material_bindings_index.slot, None, None, None, )) } fn write_batch_indirect_parameters_metadata( indexed: bool, base_output_index: u32, batch_set_index: Option<NonMaxU32>, indirect_parameters_buffers: &mut UntypedPhaseIndirectParametersBuffers, indirect_parameters_offset: u32, ) { // Note that `IndirectParameters` covers both of these structures, even // though they actually have distinct layouts. See the comment above that // type for more information. let indirect_parameters = IndirectParametersCpuMetadata { base_output_index, batch_set_index: match batch_set_index { None => !0, Some(batch_set_index) => u32::from(batch_set_index), }, }; if indexed { indirect_parameters_buffers .indexed .set(indirect_parameters_offset, indirect_parameters); } else { indirect_parameters_buffers .non_indexed .set(indirect_parameters_offset, indirect_parameters); } } fn get_binned_index( _param: &SystemParamItem<Self::Param>, _query_item: MainEntity, ) -> Option<NonMaxU32> { None } } // When defining a phase, we need to extract it from the main world and add it to a resource // that will be used by the render world. We need to give that resource all views that will use // that phase fn extract_camera_phases( mut stencil_phases: ResMut<ViewSortedRenderPhases<Stencil3d>>, cameras: Extract<Query<(Entity, &Camera), With<Camera3d>>>, mut live_entities: Local<HashSet<RetainedViewEntity>>, ) { live_entities.clear(); for (main_entity, camera) in &cameras { if !camera.is_active { continue; } // This is the main camera, so we use the first subview index (0) let retained_view_entity = RetainedViewEntity::new(main_entity.into(), None, 0); stencil_phases.insert_or_clear(retained_view_entity); live_entities.insert(retained_view_entity); } // Clear out all dead views. stencil_phases.retain(|camera_entity, _| live_entities.contains(camera_entity)); } // This is a very important step when writing a custom phase. // // This system determines which meshes will be added to the phase. fn queue_custom_meshes( custom_draw_functions: Res<DrawFunctions<Stencil3d>>, mut pipelines: ResMut<SpecializedMeshPipelines<StencilPipeline>>, pipeline_cache: Res<PipelineCache>, custom_draw_pipeline: Res<StencilPipeline>, render_meshes: Res<RenderAssets<RenderMesh>>, render_mesh_instances: Res<RenderMeshInstances>, mut custom_render_phases: ResMut<ViewSortedRenderPhases<Stencil3d>>, mut views: Query<(&ExtractedView, &RenderVisibleEntities, &Msaa)>, has_marker: Query<(), With<DrawStencil>>, ) { for (view, visible_entities, msaa) in &mut views { let Some(custom_phase) = custom_render_phases.get_mut(&view.retained_view_entity) else { continue; }; let draw_custom = custom_draw_functions.read().id::<DrawMesh3dStencil>(); // Create the key based on the view. // In this case we only care about MSAA and HDR let view_key = MeshPipelineKey::from_msaa_samples(msaa.samples()) | MeshPipelineKey::from_hdr(view.hdr); let rangefinder = view.rangefinder3d(); // Since our phase can work on any 3d mesh we can reuse the default mesh 3d filter for (render_entity, visible_entity) in visible_entities.iter::<Mesh3d>() { // We only want meshes with the marker component to be queued to our phase. if has_marker.get(*render_entity).is_err() { continue; } 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; }; // Specialize the key for the current mesh entity // For this example we only specialize based on the mesh topology // but you could have more complex keys and that's where you'd need to create those keys let mut mesh_key = view_key; mesh_key |= MeshPipelineKey::from_primitive_topology(mesh.primitive_topology()); let pipeline_id = pipelines.specialize( &pipeline_cache, &custom_draw_pipeline, mesh_key, &mesh.layout, ); let pipeline_id = match pipeline_id { Ok(id) => id, Err(err) => { error!("{}", err); continue; } }; let distance = rangefinder.distance(&mesh_instance.center); // At this point we have all the data we need to create a phase item and add it to our // phase custom_phase.add(Stencil3d { // Sort the data based on the distance to the view sort_key: FloatOrd(distance), entity: (*render_entity, *visible_entity), pipeline: pipeline_id, draw_function: draw_custom, // Sorted phase items aren't batched batch_range: 0..1, extra_index: PhaseItemExtraIndex::None, indexed: mesh.indexed(), }); } } } // Render label used to order our render graph node that will render our phase #[derive(RenderLabel, Debug, Clone, Hash, PartialEq, Eq)] struct CustomDrawPassLabel; #[derive(Default)] struct CustomDrawNode; impl ViewNode for CustomDrawNode { type ViewQuery = ( &'static ExtractedCamera, &'static ExtractedView, &'static ViewTarget, Option<&'static MainPassResolutionOverride>, ); fn run<'w>( &self, graph: &mut RenderGraphContext, render_context: &mut RenderContext<'w>, (camera, view, target, resolution_override): QueryItem<'w, '_, Self::ViewQuery>, world: &'w World, ) -> Result<(), NodeRunError> { // First, we need to get our phases resource let Some(stencil_phases) = world.get_resource::<ViewSortedRenderPhases<Stencil3d>>() else { return Ok(()); }; // Get the view entity from the graph let view_entity = graph.view_entity(); // Get the phase for the current view running our node let Some(stencil_phase) = stencil_phases.get(&view.retained_view_entity) else { return Ok(()); }; // Render pass setup let mut render_pass = render_context.begin_tracked_render_pass(RenderPassDescriptor { label: Some("stencil pass"), // For the purpose of the example, we will write directly to the view target. A real // stencil pass would write to a custom texture and that texture would be used in later // passes to render custom effects using it. color_attachments: &[Some(target.get_color_attachment())], // We don't bind any depth buffer for this pass depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, }); if let Some(viewport) = Viewport::from_viewport_and_override(camera.viewport.as_ref(), resolution_override) { render_pass.set_camera_viewport(&viewport); } // Render the phase // This will execute each draw functions of each phase items queued in this phase if let Err(err) = stencil_phase.render(&mut render_pass, world, view_entity) { error!("Error encountered while rendering the stencil phase {err:?}"); } Ok(()) } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/shader_advanced/texture_binding_array.rs
examples/shader_advanced/texture_binding_array.rs
//! A shader that binds several textures onto one //! `binding_array<texture<f32>>` shader binding slot and sample non-uniformly. use bevy::{ ecs::system::{lifetimeless::SRes, SystemParamItem}, prelude::*, reflect::TypePath, render::{ render_asset::RenderAssets, render_resource::{ binding_types::{sampler, texture_2d}, *, }, renderer::RenderDevice, texture::{FallbackImage, GpuImage}, RenderApp, RenderStartup, }, shader::ShaderRef, }; use std::{num::NonZero, process::exit}; /// This example uses a shader source file from the assets subdirectory const SHADER_ASSET_PATH: &str = "shaders/texture_binding_array.wgsl"; fn main() { let mut app = App::new(); app.add_plugins(( DefaultPlugins.set(ImagePlugin::default_nearest()), GpuFeatureSupportChecker, MaterialPlugin::<BindlessMaterial>::default(), )) .add_systems(Startup, setup) .run(); } const MAX_TEXTURE_COUNT: usize = 16; const TILE_ID: [usize; 16] = [ 19, 23, 4, 33, 12, 69, 30, 48, 10, 65, 40, 47, 57, 41, 44, 46, ]; struct GpuFeatureSupportChecker; impl Plugin for GpuFeatureSupportChecker { fn build(&self, app: &mut App) { let Some(render_app) = app.get_sub_app_mut(RenderApp) else { return; }; render_app.add_systems(RenderStartup, verify_required_features); } } fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<BindlessMaterial>>, asset_server: Res<AssetServer>, ) { commands.spawn(( Camera3d::default(), Transform::from_xyz(2.0, 2.0, 2.0).looking_at(Vec3::new(0.0, 0.0, 0.0), Vec3::Y), )); // load 16 textures let textures: Vec<_> = TILE_ID .iter() .map(|id| asset_server.load(format!("textures/rpg/tiles/generic-rpg-tile{id:0>2}.png"))) .collect(); // a cube with multiple textures commands.spawn(( Mesh3d(meshes.add(Cuboid::default())), MeshMaterial3d(materials.add(BindlessMaterial { textures })), )); } fn verify_required_features(render_device: Res<RenderDevice>) { // Check if the device support the required feature. If not, exit the example. In a real // application, you should setup a fallback for the missing feature if !render_device .features() .contains(WgpuFeatures::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING) { error!( "Render device doesn't support feature \ SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING, \ which is required for texture binding arrays" ); exit(1); } } #[derive(Asset, TypePath, Debug, Clone)] struct BindlessMaterial { textures: Vec<Handle<Image>>, } impl AsBindGroup for BindlessMaterial { type Data = (); type Param = (SRes<RenderAssets<GpuImage>>, SRes<FallbackImage>); fn as_bind_group( &self, layout: &BindGroupLayoutDescriptor, render_device: &RenderDevice, pipeline_cache: &PipelineCache, (image_assets, fallback_image): &mut SystemParamItem<'_, '_, Self::Param>, ) -> Result<PreparedBindGroup, AsBindGroupError> { // retrieve the render resources from handles let mut images = vec![]; for handle in self.textures.iter().take(MAX_TEXTURE_COUNT) { match image_assets.get(handle) { Some(image) => images.push(image), None => return Err(AsBindGroupError::RetryNextUpdate), } } let fallback_image = &fallback_image.d2; let textures = vec![&fallback_image.texture_view; MAX_TEXTURE_COUNT]; // convert bevy's resource types to WGPU's references let mut textures: Vec<_> = textures.into_iter().map(|texture| &**texture).collect(); // fill in up to the first `MAX_TEXTURE_COUNT` textures and samplers to the arrays for (id, image) in images.into_iter().enumerate() { textures[id] = &*image.texture_view; } let bind_group = render_device.create_bind_group( Self::label(), &pipeline_cache.get_bind_group_layout(layout), &BindGroupEntries::sequential((&textures[..], &fallback_image.sampler)), ); Ok(PreparedBindGroup { bindings: BindingResources(vec![]), bind_group, }) } fn bind_group_data(&self) -> Self::Data {} fn unprepared_bind_group( &self, _layout: &BindGroupLayout, _render_device: &RenderDevice, _param: &mut SystemParamItem<'_, '_, Self::Param>, _force_no_bindless: bool, ) -> Result<UnpreparedBindGroup, AsBindGroupError> { // We implement `as_bind_group`` directly because bindless texture // arrays can't be owned. // Or rather, they can be owned, but then you can't make a `&'a [&'a // TextureView]` from a vec of them in `get_binding()`. Err(AsBindGroupError::CreateBindGroupDirectly) } fn bind_group_layout_entries(_: &RenderDevice, _: bool) -> Vec<BindGroupLayoutEntry> where Self: Sized, { BindGroupLayoutEntries::with_indices( // The layout entries will only be visible in the fragment stage ShaderStages::FRAGMENT, ( // Screen texture // // @group(#{MATERIAL_BIND_GROUP}) @binding(0) var textures: binding_array<texture_2d<f32>>; ( 0, texture_2d(TextureSampleType::Float { filterable: true }) .count(NonZero::<u32>::new(MAX_TEXTURE_COUNT as u32).unwrap()), ), // Sampler // // @group(#{MATERIAL_BIND_GROUP}) @binding(1) var nearest_sampler: sampler; // // Note: as with textures, multiple samplers can also be bound // onto one binding slot: // // ``` // sampler(SamplerBindingType::Filtering) // .count(NonZero::<u32>::new(MAX_TEXTURE_COUNT as u32).unwrap()), // ``` // // One may need to pay attention to the limit of sampler binding // amount on some platforms. (1, sampler(SamplerBindingType::Filtering)), ), ) .to_vec() } fn label() -> &'static str { "bindless_material_bind_group" } } impl Material for BindlessMaterial { fn fragment_shader() -> ShaderRef { SHADER_ASSET_PATH.into() } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/async_tasks/external_source_external_thread.rs
examples/async_tasks/external_source_external_thread.rs
//! How to use an external thread to run an infinite task and communicate with a channel. use bevy::prelude::*; // Using crossbeam_channel instead of std as std `Receiver` is `!Sync` use crossbeam_channel::{bounded, Receiver}; use rand::{Rng, SeedableRng}; use rand_chacha::ChaCha8Rng; fn main() { App::new() .add_message::<StreamMessage>() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, (spawn_text, move_text)) .add_systems(FixedUpdate, read_stream) .insert_resource(Time::<Fixed>::from_seconds(0.5)) .run(); } #[derive(Resource, Deref)] struct StreamReceiver(Receiver<u32>); #[derive(Message)] struct StreamMessage(u32); fn setup(mut commands: Commands) { commands.spawn(Camera2d); let (tx, rx) = bounded::<u32>(1); std::thread::spawn(move || { // We're seeding the PRNG here to make this example deterministic for testing purposes. // This isn't strictly required in practical use unless you need your app to be deterministic. let mut rng = ChaCha8Rng::seed_from_u64(19878367467713); loop { // Everything here happens in another thread // This is where you could connect to an external data source // This will block until the previous value has been read in system `read_stream` tx.send(rng.random_range(0..2000)).unwrap(); } }); commands.insert_resource(StreamReceiver(rx)); } // This system reads from the receiver and sends messages in the ECS fn read_stream(receiver: Res<StreamReceiver>, mut events: MessageWriter<StreamMessage>) { for from_stream in receiver.try_iter() { events.write(StreamMessage(from_stream)); } } fn spawn_text(mut commands: Commands, mut reader: MessageReader<StreamMessage>) { for (per_frame, message) in reader.read().enumerate() { commands.spawn(( Text2d::new(message.0.to_string()), TextLayout::new_with_justify(Justify::Center), Transform::from_xyz(per_frame as f32 * 100.0, 300.0, 0.0), )); } } fn move_text( mut commands: Commands, mut texts: Query<(Entity, &mut Transform), With<Text2d>>, time: Res<Time>, ) { for (entity, mut position) in &mut texts { position.translation -= Vec3::new(0.0, 100.0 * time.delta_secs(), 0.0); if position.translation.y < -300.0 { commands.entity(entity).despawn(); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/async_tasks/async_compute.rs
examples/async_tasks/async_compute.rs
//! This example demonstrates how to use Bevy's ECS and the [`AsyncComputeTaskPool`] //! to offload computationally intensive tasks to a background thread pool, process them //! asynchronously, and apply the results across systems and ticks. //! //! Unlike the channel-based approach (where tasks send results directly via a communication //! channel), this example uses the `AsyncComputeTaskPool` to run tasks in the background, //! check for their completion, and handle results when the task is ready. This method allows //! tasks to be processed in parallel without blocking the main thread, but requires periodically //! checking the status of each task. //! //! The channel-based approach, on the other hand, detaches tasks and communicates results //! through a channel, avoiding the need to check task statuses manually. use bevy::{ ecs::{system::SystemState, world::CommandQueue}, prelude::*, tasks::{futures::check_ready, AsyncComputeTaskPool, Task}, }; use futures_timer::Delay; use rand::Rng; use std::time::Duration; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, (setup_env, add_assets, spawn_tasks)) .add_systems(Update, handle_tasks) .run(); } // Number of cubes to spawn across the x, y, and z axis const NUM_CUBES: u32 = 6; #[derive(Resource, Deref)] struct BoxMeshHandle(Handle<Mesh>); #[derive(Resource, Deref)] struct BoxMaterialHandle(Handle<StandardMaterial>); /// Startup system which runs only once and generates our Box Mesh /// and Box Material assets, adds them to their respective Asset /// Resources, and stores their handles as resources so we can access /// them later when we're ready to render our Boxes fn add_assets( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { let box_mesh_handle = meshes.add(Cuboid::new(0.25, 0.25, 0.25)); commands.insert_resource(BoxMeshHandle(box_mesh_handle)); let box_material_handle = materials.add(Color::srgb(1.0, 0.2, 0.3)); commands.insert_resource(BoxMaterialHandle(box_material_handle)); } #[derive(Component)] struct ComputeTransform(Task<CommandQueue>); /// This system generates tasks simulating computationally intensive /// work that potentially spans multiple frames/ticks. A separate /// system, [`handle_tasks`], will track the spawned tasks on subsequent /// frames/ticks, and use the results to spawn cubes. /// /// The task is offloaded to the `AsyncComputeTaskPool`, allowing heavy computation /// to be handled asynchronously, without blocking the main game thread. fn spawn_tasks(mut commands: Commands) { let thread_pool = AsyncComputeTaskPool::get(); for x in 0..NUM_CUBES { for y in 0..NUM_CUBES { for z in 0..NUM_CUBES { // Spawn new task on the AsyncComputeTaskPool; the task will be // executed in the background, and the Task future returned by // spawn() can be used to poll for the result let entity = commands.spawn_empty().id(); let task = thread_pool.spawn(async move { let duration = Duration::from_secs_f32(rand::rng().random_range(0.05..5.0)); // Pretend this is a time-intensive function. :) Delay::new(duration).await; // Such hard work, all done! let transform = Transform::from_xyz(x as f32, y as f32, z as f32); let mut command_queue = CommandQueue::default(); // we use a raw command queue to pass a FnOnce(&mut World) back to be // applied in a deferred manner. command_queue.push(move |world: &mut World| { let (box_mesh_handle, box_material_handle) = { let mut system_state = SystemState::<( Res<BoxMeshHandle>, Res<BoxMaterialHandle>, )>::new(world); let (box_mesh_handle, box_material_handle) = system_state.get_mut(world); (box_mesh_handle.clone(), box_material_handle.clone()) }; world .entity_mut(entity) // Add our new `Mesh3d` and `MeshMaterial3d` to our tagged entity .insert(( Mesh3d(box_mesh_handle), MeshMaterial3d(box_material_handle), transform, )); }); command_queue }); // Add our new task as a component commands.entity(entity).insert(ComputeTransform(task)); } } } } /// This system queries for entities that have the `ComputeTransform` component. /// It checks if the tasks associated with those entities are complete. /// If the task is complete, it extracts the result, adds a new [`Mesh3d`] and [`MeshMaterial3d`] /// to the entity using the result from the task, and removes the task component from the entity. /// /// **Important Note:** /// - Don't use `future::block_on(poll_once)` to check if tasks are completed, as it is expensive and /// can block the main thread. Also, it leaves around a `Task<T>` which will panic if awaited again. /// - Instead, use `check_ready` for efficient polling, which does not block the main thread. fn handle_tasks( mut commands: Commands, mut transform_tasks: Query<(Entity, &mut ComputeTransform)>, ) { for (entity, mut task) in &mut transform_tasks { // Use `check_ready` to efficiently poll the task without blocking the main thread. if let Some(mut commands_queue) = check_ready(&mut task.0) { // Append the returned command queue to execute it later. commands.append(&mut commands_queue); // Task is complete, so remove the task component from the entity. commands.entity(entity).remove::<ComputeTransform>(); } } } /// This system is only used to setup light and camera for the environment fn setup_env(mut commands: Commands) { // Used to center camera on spawned cubes let offset = if NUM_CUBES.is_multiple_of(2) { (NUM_CUBES / 2) as f32 - 0.5 } else { (NUM_CUBES / 2) as f32 }; // lights commands.spawn((PointLight::default(), Transform::from_xyz(4.0, 12.0, 15.0))); // camera commands.spawn(( Camera3d::default(), Transform::from_xyz(offset, offset, 15.0) .looking_at(Vec3::new(offset, offset, 0.0), Vec3::Y), )); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/async_tasks/async_channel_pattern.rs
examples/async_tasks/async_channel_pattern.rs
//! A minimal example showing how to perform asynchronous work in Bevy //! using [`AsyncComputeTaskPool`] for parallel task execution and a crossbeam channel //! to communicate between async tasks and the main ECS thread. //! //! This example demonstrates how to spawn detached async tasks, send completion messages via channels, //! and dynamically spawn ECS entities (cubes) as results from these tasks. The system processes //! async task results in the main game loop, all without blocking or polling the main thread. use bevy::{ math::ops::{cos, sin}, prelude::*, tasks::AsyncComputeTaskPool, }; use crossbeam_channel::{Receiver, Sender}; use futures_timer::Delay; use rand::Rng; use std::time::Duration; const NUM_CUBES: i32 = 6; const LIGHT_RADIUS: f32 = 8.0; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems( Startup, ( setup_env, setup_assets, setup_channel, // Ensure the channel is set up before spawning tasks. spawn_tasks.after(setup_channel), ), ) .add_systems(Update, (handle_finished_cubes, rotate_light)) .run(); } /// Spawns async tasks on the compute task pool to simulate delayed cube creation. /// /// Each task is executed on a separate thread and sends the result (cube position) /// back through the `CubeChannel` once completed. The tasks are detached to /// run asynchronously without blocking the main thread. /// /// In this example, we don't implement task tracking or proper error handling. fn spawn_tasks(channel: Res<CubeChannel>) { let pool = AsyncComputeTaskPool::get(); for x in -NUM_CUBES..NUM_CUBES { for z in -NUM_CUBES..NUM_CUBES { let sender = channel.sender.clone(); // Spawn a task on the async compute pool pool.spawn(async move { let delay = Duration::from_secs_f32(rand::rng().random_range(2.0..8.0)); // Simulate a delay before task completion Delay::new(delay).await; let _ = sender.send(CubeFinished { transform: Transform::from_xyz(x as f32, 0.5, z as f32), }); }) .detach(); } } } /// Handles the completion of async tasks and spawns ECS entities (cubes) /// based on the received data. The function reads from the `CubeChannel`'s /// receiver to get the results (cube positions) and spawns cubes accordingly. fn handle_finished_cubes( mut commands: Commands, channel: Res<CubeChannel>, box_mesh: Res<BoxMeshHandle>, box_material: Res<BoxMaterialHandle>, ) { for msg in channel.receiver.try_iter() { // Spawn cube entity commands.spawn(( Mesh3d(box_mesh.clone()), MeshMaterial3d(box_material.clone()), msg.transform, )); } } /// Sets up a communication channel (`CubeChannel`) to send data between /// async tasks and the main ECS thread. The sender is used by async tasks /// to send the result (cube position), while the receiver is used by the /// main thread to retrieve and process the completed data. fn setup_channel(mut commands: Commands) { let (sender, receiver) = crossbeam_channel::unbounded(); commands.insert_resource(CubeChannel { sender, receiver }); } /// A channel for communicating between async tasks and the main thread. #[derive(Resource)] struct CubeChannel { sender: Sender<CubeFinished>, receiver: Receiver<CubeFinished>, } /// Represents the completion of a cube task, containing the cube's transform #[derive(Debug)] struct CubeFinished { transform: Transform, } /// Resource holding the mesh handle for the box (used for spawning cubes) #[derive(Resource, Deref)] struct BoxMeshHandle(Handle<Mesh>); /// Resource holding the material handle for the box (used for spawning cubes) #[derive(Resource, Deref)] struct BoxMaterialHandle(Handle<StandardMaterial>); /// Sets up the shared mesh and material for the cubes. fn setup_assets( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { // Create and store a cube mesh let box_mesh_handle = meshes.add(Cuboid::new(0.4, 0.4, 0.4)); commands.insert_resource(BoxMeshHandle(box_mesh_handle)); // Create and store a red material let box_material_handle = materials.add(Color::srgb(1.0, 0.2, 0.3)); commands.insert_resource(BoxMaterialHandle(box_material_handle)); } /// Sets up the environment by spawning the ground, light, and camera. fn setup_env( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { // Spawn a circular ground plane commands.spawn(( Mesh3d(meshes.add(Circle::new(1.618 * NUM_CUBES as f32))), MeshMaterial3d(materials.add(Color::WHITE)), Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)), )); // Spawn a point light with shadows enabled commands.spawn(( PointLight { shadows_enabled: true, ..default() }, Transform::from_xyz(0.0, LIGHT_RADIUS, 4.0), )); // Spawn a camera looking at the origin commands.spawn(( Camera3d::default(), Transform::from_xyz(-6.5, 5.5, 12.0).looking_at(Vec3::ZERO, Vec3::Y), )); } /// Rotates the point light around the origin (0, 0, 0) fn rotate_light(mut query: Query<&mut Transform, With<PointLight>>, time: Res<Time>) { for mut transform in query.iter_mut() { let angle = 1.618 * time.elapsed_secs(); let x = LIGHT_RADIUS * cos(angle); let z = LIGHT_RADIUS * sin(angle); // Update the light's position to rotate around the origin transform.translation = Vec3::new(x, LIGHT_RADIUS, z); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/picking/simple_picking.rs
examples/picking/simple_picking.rs
//! A simple scene to demonstrate picking events for UI and mesh entities. use bevy::prelude::*; fn main() { App::new() .add_plugins((DefaultPlugins, MeshPickingPlugin)) .add_systems(Startup, setup_scene) .run(); } fn setup_scene( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { commands .spawn(( Text::new("Click Me to get a box\nDrag cubes to rotate"), Node { position_type: PositionType::Absolute, top: percent(12), left: percent(12), ..default() }, )) .observe(on_click_spawn_cube) .observe(|out: On<Pointer<Out>>, mut texts: Query<&mut TextColor>| { let mut text_color = texts.get_mut(out.entity).unwrap(); text_color.0 = Color::WHITE; }) .observe( |over: On<Pointer<Over>>, mut texts: Query<&mut TextColor>| { let mut color = texts.get_mut(over.entity).unwrap(); color.0 = bevy::color::palettes::tailwind::CYAN_400.into(); }, ); // Base commands.spawn(( Mesh3d(meshes.add(Circle::new(4.0))), MeshMaterial3d(materials.add(Color::WHITE)), Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)), )); // Light commands.spawn(( PointLight { shadows_enabled: true, ..default() }, Transform::from_xyz(4.0, 8.0, 4.0), )); // Camera commands.spawn(( Camera3d::default(), Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y), )); } fn on_click_spawn_cube( _click: On<Pointer<Click>>, mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, mut num: Local<usize>, ) { commands .spawn(( Mesh3d(meshes.add(Cuboid::new(0.5, 0.5, 0.5))), MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))), Transform::from_xyz(0.0, 0.25 + 0.55 * *num as f32, 0.0), )) // With the MeshPickingPlugin added, you can add pointer event observers to meshes: .observe(on_drag_rotate); *num += 1; } fn on_drag_rotate(drag: On<Pointer<Drag>>, mut transforms: Query<&mut Transform>) { if let Ok(mut transform) = transforms.get_mut(drag.entity) { transform.rotate_y(drag.delta.x * 0.02); transform.rotate_x(drag.delta.y * 0.02); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/picking/dragdrop_picking.rs
examples/picking/dragdrop_picking.rs
//! Demonstrates drag and drop functionality using picking events. use bevy::prelude::*; #[derive(Component)] struct DropArea; #[derive(Component)] struct DraggableButton; #[derive(Component)] struct GhostPreview; #[derive(Component)] struct DroppedElement; const AREA_SIZE: f32 = 500.0; const BUTTON_WIDTH: f32 = 150.0; const BUTTON_HEIGHT: f32 = 50.0; const ELEMENT_SIZE: f32 = 25.0; fn main() { App::new() .add_plugins((DefaultPlugins, MeshPickingPlugin)) .add_systems(Startup, setup) .run(); } fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<ColorMaterial>>, ) { commands.spawn(Camera2d); commands .spawn(( Node { width: Val::Percent(100.0), height: Val::Percent(100.0), align_items: AlignItems::Center, justify_content: JustifyContent::Start, ..default() }, Pickable::IGNORE, )) .with_children(|parent| { parent .spawn(( DraggableButton, Node { width: Val::Px(BUTTON_WIDTH), height: Val::Px(BUTTON_HEIGHT), margin: UiRect::all(Val::Px(10.0)), justify_content: JustifyContent::Center, align_items: AlignItems::Center, ..default() }, BackgroundColor(Color::srgb(1.0, 0.0, 0.0)), )) .with_child(( Text::new("Drag from me"), TextColor(Color::WHITE), Pickable::IGNORE, )) .observe( |mut event: On<Pointer<DragStart>>, mut button_color: Single<&mut BackgroundColor, With<DraggableButton>>| { button_color.0 = Color::srgb(1.0, 0.5, 0.0); event.propagate(false); }, ) .observe( |mut event: On<Pointer<DragEnd>>, mut button_color: Single<&mut BackgroundColor, With<DraggableButton>>| { button_color.0 = Color::srgb(1.0, 0.0, 0.0); event.propagate(false); }, ); }); commands .spawn(( DropArea, Mesh2d(meshes.add(Rectangle::new(AREA_SIZE, AREA_SIZE))), MeshMaterial2d(materials.add(Color::srgb(0.1, 0.4, 0.1))), Transform::IDENTITY, children![( Text2d::new("Drop here"), TextFont::from_font_size(50.), TextColor(Color::BLACK), Pickable::IGNORE, Transform::from_translation(Vec3::Z), )], )) .observe(on_drag_enter) .observe(on_drag_over) .observe(on_drag_drop) .observe(on_drag_leave); } fn on_drag_enter( mut event: On<Pointer<DragEnter>>, button: Single<Entity, With<DraggableButton>>, mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<ColorMaterial>>, ) { if event.dragged == *button { let Some(position) = event.hit.position else { return; }; commands.spawn(( GhostPreview, Mesh2d(meshes.add(Circle::new(ELEMENT_SIZE))), MeshMaterial2d(materials.add(Color::srgba(1.0, 1.0, 0.6, 0.5))), Transform::from_translation(position + 2. * Vec3::Z), Pickable::IGNORE, )); event.propagate(false); } } fn on_drag_over( mut event: On<Pointer<DragOver>>, button: Single<Entity, With<DraggableButton>>, mut ghost_transform: Single<&mut Transform, With<GhostPreview>>, ) { if event.dragged == *button { let Some(position) = event.hit.position else { return; }; ghost_transform.translation = position; event.propagate(false); } } fn on_drag_drop( mut event: On<Pointer<DragDrop>>, button: Single<Entity, With<DraggableButton>>, mut commands: Commands, ghost: Single<Entity, With<GhostPreview>>, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<ColorMaterial>>, ) { if event.dropped == *button { commands.entity(*ghost).despawn(); let Some(position) = event.hit.position else { return; }; commands.spawn(( DroppedElement, Mesh2d(meshes.add(Circle::new(ELEMENT_SIZE))), MeshMaterial2d(materials.add(Color::srgb(1.0, 1.0, 0.6))), Transform::from_translation(position + 2. * Vec3::Z), Pickable::IGNORE, )); event.propagate(false); } } fn on_drag_leave( mut event: On<Pointer<DragLeave>>, button: Single<Entity, With<DraggableButton>>, mut commands: Commands, ghost: Single<Entity, With<GhostPreview>>, ) { if event.dragged == *button { commands.entity(*ghost).despawn(); event.propagate(false); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/picking/sprite_picking.rs
examples/picking/sprite_picking.rs
//! Demonstrates picking for sprites and sprite atlases. //! By default, the sprite picking backend considers a sprite only when a pointer is over an opaque pixel. use bevy::{prelude::*, sprite::Anchor}; use std::fmt::Debug; fn main() { App::new() .add_plugins(DefaultPlugins.set(ImagePlugin::default_nearest())) .add_systems(Startup, (setup, setup_atlas)) .add_systems(Update, (move_sprite, animate_sprite)) .run(); } fn move_sprite( time: Res<Time>, mut sprite: Query<&mut Transform, (Without<Sprite>, With<Children>)>, ) { let t = time.elapsed_secs() * 0.1; for mut transform in &mut sprite { let new = Vec2 { x: 50.0 * ops::sin(t), y: 50.0 * ops::sin(t * 2.0), }; transform.translation.x = new.x; transform.translation.y = new.y; } } /// Set up a scene that tests all sprite anchor types. fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn(Camera2d); let len = 128.0; let sprite_size = Vec2::splat(len / 2.0); commands .spawn((Transform::default(), Visibility::default())) .with_children(|commands| { for (anchor_index, anchor) in [ Anchor::TOP_LEFT, Anchor::TOP_CENTER, Anchor::TOP_RIGHT, Anchor::CENTER_LEFT, Anchor::CENTER, Anchor::CENTER_RIGHT, Anchor::BOTTOM_LEFT, Anchor::BOTTOM_CENTER, Anchor::BOTTOM_RIGHT, ] .iter() .enumerate() { let i = (anchor_index % 3) as f32; let j = (anchor_index / 3) as f32; // Spawn black square behind sprite to show anchor point commands .spawn(( Sprite::from_color(Color::BLACK, sprite_size), Transform::from_xyz(i * len - len, j * len - len, -1.0), Pickable::default(), )) .observe(recolor_on::<Pointer<Over>>(Color::srgb(0.0, 1.0, 1.0))) .observe(recolor_on::<Pointer<Out>>(Color::BLACK)) .observe(recolor_on::<Pointer<Press>>(Color::srgb(1.0, 1.0, 0.0))) .observe(recolor_on::<Pointer<Release>>(Color::srgb(0.0, 1.0, 1.0))); commands .spawn(( Sprite { image: asset_server.load("branding/bevy_bird_dark.png"), custom_size: Some(sprite_size), color: Color::srgb(1.0, 0.0, 0.0), ..default() }, anchor.to_owned(), // 3x3 grid of anchor examples by changing transform Transform::from_xyz(i * len - len, j * len - len, 0.0) .with_scale(Vec3::splat(1.0 + (i - 1.0) * 0.2)) .with_rotation(Quat::from_rotation_z((j - 1.0) * 0.2)), Pickable::default(), )) .observe(recolor_on::<Pointer<Over>>(Color::srgb(0.0, 1.0, 0.0))) .observe(recolor_on::<Pointer<Out>>(Color::srgb(1.0, 0.0, 0.0))) .observe(recolor_on::<Pointer<Press>>(Color::srgb(0.0, 0.0, 1.0))) .observe(recolor_on::<Pointer<Release>>(Color::srgb(0.0, 1.0, 0.0))); } }); } #[derive(Component)] struct AnimationIndices { first: usize, last: usize, } #[derive(Component, Deref, DerefMut)] struct AnimationTimer(Timer); fn animate_sprite( time: Res<Time>, mut query: Query<(&AnimationIndices, &mut AnimationTimer, &mut Sprite)>, ) { for (indices, mut timer, mut sprite) in &mut query { let Some(texture_atlas) = &mut sprite.texture_atlas else { continue; }; timer.tick(time.delta()); if timer.just_finished() { texture_atlas.index = if texture_atlas.index == indices.last { indices.first } else { texture_atlas.index + 1 }; } } } fn setup_atlas( mut commands: Commands, asset_server: Res<AssetServer>, mut texture_atlas_layouts: ResMut<Assets<TextureAtlasLayout>>, ) { let texture_handle = asset_server.load("textures/rpg/chars/gabe/gabe-idle-run.png"); let layout = TextureAtlasLayout::from_grid(UVec2::new(24, 24), 7, 1, None, None); let texture_atlas_layout_handle = texture_atlas_layouts.add(layout); // Use only the subset of sprites in the sheet that make up the run animation let animation_indices = AnimationIndices { first: 1, last: 6 }; commands .spawn(( Sprite::from_atlas_image( texture_handle, TextureAtlas { layout: texture_atlas_layout_handle, index: animation_indices.first, }, ), Transform::from_xyz(300.0, 0.0, 0.0).with_scale(Vec3::splat(6.0)), animation_indices, AnimationTimer(Timer::from_seconds(0.1, TimerMode::Repeating)), Pickable::default(), )) .observe(recolor_on::<Pointer<Over>>(Color::srgb(0.0, 1.0, 1.0))) .observe(recolor_on::<Pointer<Out>>(Color::srgb(1.0, 1.0, 1.0))) .observe(recolor_on::<Pointer<Press>>(Color::srgb(1.0, 1.0, 0.0))) .observe(recolor_on::<Pointer<Release>>(Color::srgb(0.0, 1.0, 1.0))); } // An observer that changes the target entity's color. fn recolor_on<E: EntityEvent + Debug + Clone + Reflect>( color: Color, ) -> impl Fn(On<E>, Query<&mut Sprite>) { move |ev, mut sprites| { let Ok(mut sprite) = sprites.get_mut(ev.event_target()) else { return; }; sprite.color = color; } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/picking/debug_picking.rs
examples/picking/debug_picking.rs
//! A simple scene to demonstrate picking events for UI and mesh entities, //! Demonstrates how to change debug settings use bevy::dev_tools::picking_debug::{DebugPickingMode, DebugPickingPlugin}; use bevy::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins.set(bevy::log::LogPlugin { filter: "bevy_dev_tools=trace".into(), // Show picking logs trace level and up ..default() })) .add_plugins((MeshPickingPlugin, DebugPickingPlugin)) .add_systems(Startup, setup_scene) .insert_resource(DebugPickingMode::Normal) // A system that cycles the debugging state when you press F3: .add_systems( PreUpdate, (|mut mode: ResMut<DebugPickingMode>| { *mode = match *mode { DebugPickingMode::Disabled => DebugPickingMode::Normal, DebugPickingMode::Normal => DebugPickingMode::Noisy, DebugPickingMode::Noisy => DebugPickingMode::Disabled, } }) .distributive_run_if(bevy::input::common_conditions::input_just_pressed( KeyCode::F3, )), ) .run(); } fn setup_scene( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { commands .spawn(( Text::new("Click Me to get a box\nDrag cubes to rotate\nPress F3 to cycle between picking debug levels"), Node { position_type: PositionType::Absolute, top: percent(12), left: percent(12), ..default() }, )) .observe(on_click_spawn_cube) .observe( |out: On<Pointer<Out>>, mut texts: Query<&mut TextColor>| { let mut text_color = texts.get_mut(out.entity).unwrap(); text_color.0 = Color::WHITE; }, ) .observe( |over: On<Pointer<Over>>, mut texts: Query<&mut TextColor>| { let mut color = texts.get_mut(over.entity).unwrap(); color.0 = bevy::color::palettes::tailwind::CYAN_400.into(); }, ); // Base commands.spawn(( Name::new("Base"), Mesh3d(meshes.add(Circle::new(4.0))), MeshMaterial3d(materials.add(Color::WHITE)), Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)), )); // Light commands.spawn(( PointLight { shadows_enabled: true, ..default() }, Transform::from_xyz(4.0, 8.0, 4.0), )); // Camera commands.spawn(( Camera3d::default(), Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y), )); } fn on_click_spawn_cube( _click: On<Pointer<Click>>, mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, mut num: Local<usize>, ) { commands .spawn(( Mesh3d(meshes.add(Cuboid::new(0.5, 0.5, 0.5))), MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))), Transform::from_xyz(0.0, 0.25 + 0.55 * *num as f32, 0.0), )) // With the MeshPickingPlugin added, you can add pointer event observers to meshes: .observe(on_drag_rotate); *num += 1; } fn on_drag_rotate(drag: On<Pointer<Drag>>, mut transforms: Query<&mut Transform>) { if let Ok(mut transform) = transforms.get_mut(drag.entity) { transform.rotate_y(drag.delta.x * 0.02); transform.rotate_x(drag.delta.y * 0.02); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/picking/mesh_picking.rs
examples/picking/mesh_picking.rs
//! A simple 3D scene to demonstrate mesh picking. //! //! [`bevy::picking::backend`] provides an API for adding picking hit tests to any entity. To get //! started with picking 3d meshes, the [`MeshPickingPlugin`] is provided as a simple starting //! point, especially useful for debugging. For your game, you may want to use a 3d picking backend //! provided by your physics engine, or a picking shader, depending on your specific use case. //! //! [`bevy::picking`] allows you to compose backends together to make any entity on screen pickable //! with pointers, regardless of how that entity is rendered. For example, `bevy_ui` and //! `bevy_sprite` provide their own picking backends that can be enabled at the same time as this //! mesh picking backend. This makes it painless to deal with cases like the UI or sprites blocking //! meshes underneath them, or vice versa. //! //! If you want to build more complex interactions than afforded by the provided pointer events, you //! may want to use [`MeshRayCast`] or a full physics engine with raycasting capabilities. //! //! By default, the mesh picking plugin will raycast against all entities, which is especially //! useful for debugging. If you want mesh picking to be opt-in, you can set //! [`MeshPickingSettings::require_markers`] to `true` and add a [`Pickable`] component to the //! desired camera and target entities. use std::f32::consts::PI; use bevy::{color::palettes::tailwind::*, picking::pointer::PointerInteraction, prelude::*}; fn main() { App::new() // MeshPickingPlugin is not a default plugin .add_plugins((DefaultPlugins, MeshPickingPlugin)) .add_systems(Startup, setup_scene) .add_systems(Update, (draw_mesh_intersections, rotate)) .run(); } /// A marker component for our shapes so we can query them separately from the ground plane. #[derive(Component)] struct Shape; const SHAPES_X_EXTENT: f32 = 14.0; const EXTRUSION_X_EXTENT: f32 = 16.0; const Z_EXTENT: f32 = 5.0; fn setup_scene( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { // Set up the materials. let white_matl = materials.add(Color::WHITE); let ground_matl = materials.add(Color::from(GRAY_300)); let hover_matl = materials.add(Color::from(CYAN_300)); let pressed_matl = materials.add(Color::from(YELLOW_300)); let shapes = [ meshes.add(Cuboid::default()), meshes.add(Tetrahedron::default()), meshes.add(Capsule3d::default()), meshes.add(Torus::default()), meshes.add(Cylinder::default()), meshes.add(Cone::default()), meshes.add(ConicalFrustum::default()), meshes.add(Sphere::default().mesh().ico(5).unwrap()), meshes.add(Sphere::default().mesh().uv(32, 18)), ]; let extrusions = [ meshes.add(Extrusion::new(Rectangle::default(), 1.)), meshes.add(Extrusion::new(Capsule2d::default(), 1.)), meshes.add(Extrusion::new(Annulus::default(), 1.)), meshes.add(Extrusion::new(Circle::default(), 1.)), meshes.add(Extrusion::new(Ellipse::default(), 1.)), meshes.add(Extrusion::new(RegularPolygon::default(), 1.)), meshes.add(Extrusion::new(Triangle2d::default(), 1.)), ]; let num_shapes = shapes.len(); // Spawn the shapes. The meshes will be pickable by default. for (i, shape) in shapes.into_iter().enumerate() { commands .spawn(( Mesh3d(shape), MeshMaterial3d(white_matl.clone()), Transform::from_xyz( -SHAPES_X_EXTENT / 2. + i as f32 / (num_shapes - 1) as f32 * SHAPES_X_EXTENT, 2.0, Z_EXTENT / 2., ) .with_rotation(Quat::from_rotation_x(-PI / 4.)), Shape, )) .observe(update_material_on::<Pointer<Over>>(hover_matl.clone())) .observe(update_material_on::<Pointer<Out>>(white_matl.clone())) .observe(update_material_on::<Pointer<Press>>(pressed_matl.clone())) .observe(update_material_on::<Pointer<Release>>(hover_matl.clone())) .observe(rotate_on_drag); } let num_extrusions = extrusions.len(); for (i, shape) in extrusions.into_iter().enumerate() { commands .spawn(( Mesh3d(shape), MeshMaterial3d(white_matl.clone()), Transform::from_xyz( -EXTRUSION_X_EXTENT / 2. + i as f32 / (num_extrusions - 1) as f32 * EXTRUSION_X_EXTENT, 2.0, -Z_EXTENT / 2., ) .with_rotation(Quat::from_rotation_x(-PI / 4.)), Shape, )) .observe(update_material_on::<Pointer<Over>>(hover_matl.clone())) .observe(update_material_on::<Pointer<Out>>(white_matl.clone())) .observe(update_material_on::<Pointer<Press>>(pressed_matl.clone())) .observe(update_material_on::<Pointer<Release>>(hover_matl.clone())) .observe(rotate_on_drag); } // Ground commands.spawn(( Mesh3d(meshes.add(Plane3d::default().mesh().size(50.0, 50.0).subdivisions(10))), MeshMaterial3d(ground_matl.clone()), Pickable::IGNORE, // Disable picking for the ground plane. )); // Light commands.spawn(( PointLight { shadows_enabled: true, intensity: 10_000_000., range: 100.0, shadow_depth_bias: 0.2, ..default() }, Transform::from_xyz(8.0, 16.0, 8.0), )); // Camera commands.spawn(( Camera3d::default(), Transform::from_xyz(0.0, 7., 14.0).looking_at(Vec3::new(0., 1., 0.), Vec3::Y), )); // Instructions commands.spawn(( Text::new("Hover over the shapes to pick them\nDrag to rotate"), Node { position_type: PositionType::Absolute, top: px(12), left: px(12), ..default() }, )); } /// Returns an observer that updates the entity's material to the one specified. fn update_material_on<E: EntityEvent>( new_material: Handle<StandardMaterial>, ) -> impl Fn(On<E>, Query<&mut MeshMaterial3d<StandardMaterial>>) { // An observer closure that captures `new_material`. We do this to avoid needing to write four // versions of this observer, each triggered by a different event and with a different hardcoded // material. Instead, the event type is a generic, and the material is passed in. move |event, mut query| { if let Ok(mut material) = query.get_mut(event.event_target()) { material.0 = new_material.clone(); } } } /// A system that draws hit indicators for every pointer. fn draw_mesh_intersections(pointers: Query<&PointerInteraction>, mut gizmos: Gizmos) { for (point, normal) in pointers .iter() .filter_map(|interaction| interaction.get_nearest_hit()) .filter_map(|(_entity, hit)| hit.position.zip(hit.normal)) { gizmos.sphere(point, 0.05, RED_500); gizmos.arrow(point, point + normal.normalize() * 0.5, PINK_100); } } /// A system that rotates all shapes. fn rotate(mut query: Query<&mut Transform, With<Shape>>, time: Res<Time>) { for mut transform in &mut query { transform.rotate_y(time.delta_secs() / 2.); } } /// An observer to rotate an entity when it is dragged fn rotate_on_drag(drag: On<Pointer<Drag>>, mut transforms: Query<&mut Transform>) { let mut transform = transforms.get_mut(drag.entity).unwrap(); transform.rotate_y(drag.delta.x * 0.02); transform.rotate_x(drag.delta.y * 0.02); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/diagnostics/enabling_disabling_diagnostic.rs
examples/diagnostics/enabling_disabling_diagnostic.rs
//! Shows how to disable/re-enable a Diagnostic during runtime use std::time::Duration; use bevy::{ diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}, prelude::*, time::common_conditions::on_timer, }; fn main() { App::new() .add_plugins(( DefaultPlugins, FrameTimeDiagnosticsPlugin::default(), LogDiagnosticsPlugin::default(), )) .add_systems( Update, toggle.run_if(on_timer(Duration::from_secs_f32(10.0))), ) .run(); } fn toggle(mut store: ResMut<DiagnosticsStore>) { for diag in store.iter_mut() { info!("toggling diagnostic {}", diag.path()); diag.is_enabled = !diag.is_enabled; } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/diagnostics/log_diagnostics.rs
examples/diagnostics/log_diagnostics.rs
//! Shows different built-in plugins that logs diagnostics, like frames per second (FPS), to the console. use bevy::{ color::palettes, diagnostic::{ DiagnosticPath, EntityCountDiagnosticsPlugin, FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin, LogDiagnosticsState, SystemInformationDiagnosticsPlugin, }, prelude::*, }; const FRAME_TIME_DIAGNOSTICS: [DiagnosticPath; 3] = [ FrameTimeDiagnosticsPlugin::FPS, FrameTimeDiagnosticsPlugin::FRAME_COUNT, FrameTimeDiagnosticsPlugin::FRAME_TIME, ]; const ENTITY_COUNT_DIAGNOSTICS: [DiagnosticPath; 1] = [EntityCountDiagnosticsPlugin::ENTITY_COUNT]; const SYSTEM_INFO_DIAGNOSTICS: [DiagnosticPath; 4] = [ SystemInformationDiagnosticsPlugin::PROCESS_CPU_USAGE, SystemInformationDiagnosticsPlugin::PROCESS_MEM_USAGE, SystemInformationDiagnosticsPlugin::SYSTEM_CPU_USAGE, SystemInformationDiagnosticsPlugin::SYSTEM_MEM_USAGE, ]; fn main() { App::new() .add_plugins(( // The diagnostics plugins need to be added after DefaultPlugins as they use e.g. the time plugin for timestamps. DefaultPlugins, // Adds a system that prints diagnostics to the console. // The other diagnostics plugins can still be used without this if you want to use them in an ingame overlay for example. LogDiagnosticsPlugin::default(), // Adds frame time, FPS and frame count diagnostics. FrameTimeDiagnosticsPlugin::default(), // Adds an entity count diagnostic. EntityCountDiagnosticsPlugin::default(), // Adds cpu and memory usage diagnostics for systems and the entire game process. SystemInformationDiagnosticsPlugin, // Forwards various diagnostics from the render app to the main app. // These are pretty verbose but can be useful to pinpoint performance issues. bevy::render::diagnostic::RenderDiagnosticsPlugin, )) // No rendering diagnostics are emitted unless something is drawn to the screen, // so we spawn a small scene. .add_systems(Startup, setup) .add_systems(Update, filters_inputs) .add_systems( Update, update_commands.run_if( resource_exists_and_changed::<LogDiagnosticsStatus> .or(resource_exists_and_changed::<LogDiagnosticsFilters>), ), ) .run(); } /// set up a simple 3D scene fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { // circular base commands.spawn(( Mesh3d(meshes.add(Circle::new(4.0))), MeshMaterial3d(materials.add(Color::WHITE)), Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)), )); // cube commands.spawn(( Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))), MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))), Transform::from_xyz(0.0, 0.5, 0.0), )); // light commands.spawn(( PointLight { shadows_enabled: true, ..default() }, Transform::from_xyz(4.0, 8.0, 4.0), )); // camera commands.spawn(( Camera3d::default(), Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y), )); commands.init_resource::<LogDiagnosticsFilters>(); commands.init_resource::<LogDiagnosticsStatus>(); commands.spawn(( LogDiagnosticsCommands, Node { top: px(5), left: px(5), flex_direction: FlexDirection::Column, ..default() }, )); } fn filters_inputs( keys: Res<ButtonInput<KeyCode>>, mut status: ResMut<LogDiagnosticsStatus>, mut filters: ResMut<LogDiagnosticsFilters>, mut log_state: ResMut<LogDiagnosticsState>, ) { if keys.just_pressed(KeyCode::KeyQ) { *status = match *status { LogDiagnosticsStatus::Enabled => { log_state.disable_filtering(); LogDiagnosticsStatus::Disabled } LogDiagnosticsStatus::Disabled => { log_state.enable_filtering(); if filters.frame_time { enable_filters(&mut log_state, FRAME_TIME_DIAGNOSTICS); } if filters.entity_count { enable_filters(&mut log_state, ENTITY_COUNT_DIAGNOSTICS); } if filters.system_info { enable_filters(&mut log_state, SYSTEM_INFO_DIAGNOSTICS); } LogDiagnosticsStatus::Enabled } }; } let enabled = *status == LogDiagnosticsStatus::Enabled; if keys.just_pressed(KeyCode::Digit1) { filters.frame_time = !filters.frame_time; if enabled { if filters.frame_time { enable_filters(&mut log_state, FRAME_TIME_DIAGNOSTICS); } else { disable_filters(&mut log_state, FRAME_TIME_DIAGNOSTICS); } } } if keys.just_pressed(KeyCode::Digit2) { filters.entity_count = !filters.entity_count; if enabled { if filters.entity_count { enable_filters(&mut log_state, ENTITY_COUNT_DIAGNOSTICS); } else { disable_filters(&mut log_state, ENTITY_COUNT_DIAGNOSTICS); } } } if keys.just_pressed(KeyCode::Digit3) { filters.system_info = !filters.system_info; if enabled { if filters.system_info { enable_filters(&mut log_state, SYSTEM_INFO_DIAGNOSTICS); } else { disable_filters(&mut log_state, SYSTEM_INFO_DIAGNOSTICS); } } } } fn enable_filters( log_state: &mut LogDiagnosticsState, diagnostics: impl IntoIterator<Item = DiagnosticPath>, ) { log_state.extend_filter(diagnostics); } fn disable_filters( log_state: &mut LogDiagnosticsState, diagnostics: impl IntoIterator<Item = DiagnosticPath>, ) { for diagnostic in diagnostics { log_state.remove_filter(&diagnostic); } } fn update_commands( mut commands: Commands, log_commands: Single<Entity, With<LogDiagnosticsCommands>>, status: Res<LogDiagnosticsStatus>, filters: Res<LogDiagnosticsFilters>, ) { let enabled = *status == LogDiagnosticsStatus::Enabled; let alpha = if enabled { 1. } else { 0.25 }; let enabled_color = |enabled| { if enabled { Color::from(palettes::tailwind::GREEN_400) } else { Color::from(palettes::tailwind::RED_400) } }; commands .entity(*log_commands) .despawn_related::<Children>() .insert(children![ ( Node { flex_direction: FlexDirection::Row, column_gap: px(5), ..default() }, children![ Text::new("[Q] Toggle filtering:"), ( Text::new(format!("{:?}", *status)), TextColor(enabled_color(enabled)) ) ] ), ( Node { flex_direction: FlexDirection::Row, column_gap: px(5), ..default() }, children![ ( Text::new("[1] Frame times:"), TextColor(Color::WHITE.with_alpha(alpha)) ), ( Text::new(format!("{:?}", filters.frame_time)), TextColor(enabled_color(filters.frame_time).with_alpha(alpha)) ) ] ), ( Node { flex_direction: FlexDirection::Row, column_gap: px(5), ..default() }, children![ ( Text::new("[2] Entity count:"), TextColor(Color::WHITE.with_alpha(alpha)) ), ( Text::new(format!("{:?}", filters.entity_count)), TextColor(enabled_color(filters.entity_count).with_alpha(alpha)) ) ] ), ( Node { flex_direction: FlexDirection::Row, column_gap: px(5), ..default() }, children![ ( Text::new("[3] System info:"), TextColor(Color::WHITE.with_alpha(alpha)) ), ( Text::new(format!("{:?}", filters.system_info)), TextColor(enabled_color(filters.system_info).with_alpha(alpha)) ) ] ), ( Node { flex_direction: FlexDirection::Row, column_gap: px(5), ..default() }, children![ ( Text::new("[4] Render diagnostics:"), TextColor(Color::WHITE.with_alpha(alpha)) ), ( Text::new("Private"), TextColor(enabled_color(false).with_alpha(alpha)) ) ] ), ]); } #[derive(Debug, Default, PartialEq, Eq, Resource)] enum LogDiagnosticsStatus { /// No filtering, showing all logs #[default] Disabled, /// Filtering enabled, showing only subset of logs Enabled, } #[derive(Default, Resource)] struct LogDiagnosticsFilters { frame_time: bool, entity_count: bool, system_info: bool, #[expect( dead_code, reason = "Currently the diagnostic paths referent to RenderDiagnosticPlugin are private" )] render_diagnostics: bool, } #[derive(Component)] /// Marks the UI node that has instructions on how to change the filtering struct LogDiagnosticsCommands;
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/diagnostics/custom_diagnostic.rs
examples/diagnostics/custom_diagnostic.rs
//! This example illustrates how to create a custom diagnostic. use bevy::{ diagnostic::{ Diagnostic, DiagnosticPath, Diagnostics, LogDiagnosticsPlugin, RegisterDiagnostic, }, prelude::*, }; fn main() { App::new() .add_plugins(( DefaultPlugins, // The "print diagnostics" plugin is optional. // It just visualizes our diagnostics in the console. LogDiagnosticsPlugin::default(), )) // Diagnostics must be initialized before measurements can be added. .register_diagnostic(Diagnostic::new(SYSTEM_ITERATION_COUNT).with_suffix(" iterations")) .add_systems(Update, my_system) .run(); } // All diagnostics should have a unique DiagnosticPath. const SYSTEM_ITERATION_COUNT: DiagnosticPath = DiagnosticPath::const_new("system_iteration_count"); fn my_system(mut diagnostics: Diagnostics) { // Add a measurement of 10.0 for our diagnostic each time this system runs. diagnostics.add_measurement(&SYSTEM_ITERATION_COUNT, || 10.0); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/usage/context_menu.rs
examples/usage/context_menu.rs
//! This example illustrates how to create a context menu that changes the clear color use bevy::{ color::palettes::basic, ecs::{relationship::RelatedSpawner, spawn::SpawnWith}, prelude::*, }; use std::fmt::Debug; /// event opening a new context menu at position `pos` #[derive(Event)] struct OpenContextMenu { pos: Vec2, } /// event will be sent to close currently open context menus #[derive(Event)] struct CloseContextMenus; /// marker component identifying root of a context menu #[derive(Component)] struct ContextMenu; /// context menu item data storing what background color `Srgba` it activates #[derive(Component)] struct ContextMenuItem(Srgba); fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_observer(on_trigger_menu) .add_observer(on_trigger_close_menus) .add_observer(text_color_on_hover::<Out>(basic::WHITE.into())) .add_observer(text_color_on_hover::<Over>(basic::RED.into())) .run(); } /// helper function to reduce code duplication when generating almost identical observers for the hover text color change effect fn text_color_on_hover<T: Debug + Clone + Reflect>( color: Color, ) -> impl FnMut(On<Pointer<T>>, Query<&mut TextColor>, Query<&Children>) { move |mut event: On<Pointer<T>>, mut text_color: Query<&mut TextColor>, children: Query<&Children>| { let Ok(children) = children.get(event.original_event_target()) else { return; }; event.propagate(false); // find the text among children and change its color for child in children.iter() { if let Ok(mut col) = text_color.get_mut(child) { col.0 = color; } } } } fn setup(mut commands: Commands) { commands.spawn(Camera2d); commands.spawn(background_and_button()).observe( // any click bubbling up here should lead to closing any open menu |_: On<Pointer<Press>>, mut commands: Commands| { commands.trigger(CloseContextMenus); }, ); } fn on_trigger_close_menus( _event: On<CloseContextMenus>, mut commands: Commands, menus: Query<Entity, With<ContextMenu>>, ) { for e in menus.iter() { commands.entity(e).despawn(); } } fn on_trigger_menu(event: On<OpenContextMenu>, mut commands: Commands) { commands.trigger(CloseContextMenus); let pos = event.pos; debug!("open context menu at: {pos}"); commands .spawn(( Name::new("context menu"), ContextMenu, Node { position_type: PositionType::Absolute, left: px(pos.x), top: px(pos.y), flex_direction: FlexDirection::Column, border_radius: BorderRadius::all(px(4)), ..default() }, BorderColor::all(Color::BLACK), BackgroundColor(Color::linear_rgb(0.1, 0.1, 0.1)), children![ context_item("fuchsia", basic::FUCHSIA), context_item("gray", basic::GRAY), context_item("maroon", basic::MAROON), context_item("purple", basic::PURPLE), context_item("teal", basic::TEAL), ], )) .observe( |event: On<Pointer<Press>>, menu_items: Query<&ContextMenuItem>, mut clear_col: ResMut<ClearColor>, mut commands: Commands| { let target = event.original_event_target(); if let Ok(item) = menu_items.get(target) { clear_col.0 = item.0.into(); commands.trigger(CloseContextMenus); } }, ); } fn context_item(text: &str, col: Srgba) -> impl Bundle { ( Name::new(format!("item-{text}")), ContextMenuItem(col), Button, Node { padding: UiRect::all(px(5)), ..default() }, children![( Pickable::IGNORE, Text::new(text), TextFont { font_size: 24.0, ..default() }, TextColor(Color::WHITE), )], ) } fn background_and_button() -> impl Bundle { ( Name::new("background"), Node { width: percent(100), height: percent(100), align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..default() }, ZIndex(-10), Children::spawn(SpawnWith(|parent: &mut RelatedSpawner<ChildOf>| { parent .spawn(( Name::new("button"), Button, Node { width: px(250), height: px(65), border: UiRect::all(px(5)), justify_content: JustifyContent::Center, align_items: AlignItems::Center, border_radius: BorderRadius::MAX, ..default() }, BorderColor::all(Color::BLACK), BackgroundColor(Color::BLACK), children![( Pickable::IGNORE, Text::new("Context Menu"), TextFont { font_size: 28.0, ..default() }, TextColor(Color::WHITE), TextShadow::default(), )], )) .observe(|mut event: On<Pointer<Press>>, mut commands: Commands| { // by default this event would bubble up further leading to the `CloseContextMenus` // event being triggered and undoing the opening of one here right away. event.propagate(false); debug!("click: {}", event.pointer_location.position); commands.trigger(OpenContextMenu { pos: event.pointer_location.position, }); }); })), ) }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/usage/cooldown.rs
examples/usage/cooldown.rs
//! Demonstrates implementing a cooldown in UI. //! //! You might want a system like this for abilities, buffs or consumables. //! We create four food buttons to eat with 2, 1, 10, and 4 seconds cooldown. use bevy::{color::palettes::tailwind, ecs::spawn::SpawnIter, prelude::*}; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems( Update, ( activate_ability, animate_cooldowns.run_if(any_with_component::<ActiveCooldown>), ), ) .run(); } fn setup( mut commands: Commands, mut texture_atlas_layouts: ResMut<Assets<TextureAtlasLayout>>, asset_server: Res<AssetServer>, ) { commands.spawn(Camera2d); let texture = asset_server.load("textures/food_kenney.png"); let layout = TextureAtlasLayout::from_grid(UVec2::splat(64), 7, 7, None, None); let texture_atlas_layout = texture_atlas_layouts.add(layout); commands.spawn(( Node { width: percent(100), height: percent(100), align_items: AlignItems::Center, justify_content: JustifyContent::Center, column_gap: px(15), ..default() }, Children::spawn(SpawnIter( [ FoodItem { name: "an apple", cooldown: 2., index: 2, }, FoodItem { name: "a burger", cooldown: 1., index: 23, }, FoodItem { name: "chocolate", cooldown: 10., index: 32, }, FoodItem { name: "cherries", cooldown: 4., index: 41, }, ] .into_iter() .map(move |food| build_ability(food, texture.clone(), texture_atlas_layout.clone())), )), )); commands.spawn(( Text::new("*Click some food to eat it*"), Node { position_type: PositionType::Absolute, top: px(12), left: px(12), ..default() }, )); } struct FoodItem { name: &'static str, cooldown: f32, index: usize, } fn build_ability( food: FoodItem, texture: Handle<Image>, layout: Handle<TextureAtlasLayout>, ) -> impl Bundle { let FoodItem { name, cooldown, index, } = food; let name = Name::new(name); // Every food item is a button with a child node. // The child node's height will be animated to be at 100% at the beginning // of a cooldown, effectively graying out the whole button, and then getting smaller over time. ( Node { width: px(80), height: px(80), flex_direction: FlexDirection::ColumnReverse, ..default() }, BackgroundColor(tailwind::SLATE_400.into()), Button, ImageNode::from_atlas_image(texture, TextureAtlas { layout, index }), Cooldown(Timer::from_seconds(cooldown, TimerMode::Once)), name, children![( Node { width: percent(100), height: percent(0), ..default() }, BackgroundColor(tailwind::SLATE_50.with_alpha(0.5).into()), )], ) } #[derive(Component)] struct Cooldown(Timer); #[derive(Component)] #[component(storage = "SparseSet")] struct ActiveCooldown; fn activate_ability( mut commands: Commands, mut interaction_query: Query< ( Entity, &Interaction, &mut Cooldown, &Name, Option<&ActiveCooldown>, ), (Changed<Interaction>, With<Button>), >, mut text: Query<&mut Text>, ) -> Result { for (entity, interaction, mut cooldown, name, on_cooldown) in &mut interaction_query { if *interaction == Interaction::Pressed { if on_cooldown.is_none() { cooldown.0.reset(); commands.entity(entity).insert(ActiveCooldown); **text.single_mut()? = format!("You ate {name}"); } else { **text.single_mut()? = format!( "You can eat {name} again in {} seconds.", cooldown.0.remaining_secs().ceil() ); } } } Ok(()) } fn animate_cooldowns( time: Res<Time>, mut commands: Commands, buttons: Query<(Entity, &mut Cooldown, &Children), With<ActiveCooldown>>, mut nodes: Query<&mut Node>, ) -> Result { for (entity, mut timer, children) in buttons { timer.0.tick(time.delta()); let cooldown = children.first().ok_or("No child")?; if timer.0.just_finished() { commands.entity(entity).remove::<ActiveCooldown>(); nodes.get_mut(*cooldown)?.height = percent(0); } else { nodes.get_mut(*cooldown)?.height = percent((1. - timer.0.fraction()) * 100.); } } Ok(()) }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/button.rs
examples/ui/button.rs
//! This example illustrates how to create a button that changes color and text based on its //! interaction state. use bevy::{color::palettes::basic::*, input_focus::InputFocus, prelude::*}; fn main() { App::new() .add_plugins(DefaultPlugins) // `InputFocus` must be set for accessibility to recognize the button. .init_resource::<InputFocus>() .add_systems(Startup, setup) .add_systems(Update, button_system) .run(); } const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15); const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25); const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35); fn button_system( mut input_focus: ResMut<InputFocus>, mut interaction_query: Query< ( Entity, &Interaction, &mut BackgroundColor, &mut BorderColor, &mut Button, &Children, ), Changed<Interaction>, >, mut text_query: Query<&mut Text>, ) { for (entity, interaction, mut color, mut border_color, mut button, children) in &mut interaction_query { let mut text = text_query.get_mut(children[0]).unwrap(); match *interaction { Interaction::Pressed => { input_focus.set(entity); **text = "Press".to_string(); *color = PRESSED_BUTTON.into(); *border_color = BorderColor::all(RED); // The accessibility system's only update the button's state when the `Button` component is marked as changed. button.set_changed(); } Interaction::Hovered => { input_focus.set(entity); **text = "Hover".to_string(); *color = HOVERED_BUTTON.into(); *border_color = BorderColor::all(Color::WHITE); button.set_changed(); } Interaction::None => { input_focus.clear(); **text = "Button".to_string(); *color = NORMAL_BUTTON.into(); *border_color = BorderColor::all(Color::BLACK); } } } } fn setup(mut commands: Commands, assets: Res<AssetServer>) { // ui camera commands.spawn(Camera2d); commands.spawn(button(&assets)); } fn button(asset_server: &AssetServer) -> impl Bundle { ( Node { width: percent(100), height: percent(100), align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..default() }, children![( Button, Node { width: px(150), height: px(65), border: UiRect::all(px(5)), // horizontally center child text justify_content: JustifyContent::Center, // vertically center child text align_items: AlignItems::Center, border_radius: BorderRadius::MAX, ..default() }, BorderColor::all(Color::WHITE), BackgroundColor(Color::BLACK), children![( Text::new("Button"), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), font_size: 33.0, ..default() }, TextColor(Color::srgb(0.9, 0.9, 0.9)), TextShadow::default(), )] )], ) }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/ui_target_camera.rs
examples/ui/ui_target_camera.rs
//! Demonstrates how to use `UiTargetCamera` and camera ordering. use bevy::color::palettes::css::BLUE; use bevy::color::palettes::css::GREEN; use bevy::color::palettes::css::RED; use bevy::color::palettes::css::YELLOW; use bevy::log::LogPlugin; use bevy::log::DEFAULT_FILTER; use bevy::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins.set(LogPlugin { // Disable camera order ambiguity warnings filter: format!("{DEFAULT_FILTER},bevy_render::camera=off"), ..Default::default() })) .add_systems(Startup, setup) .run(); } const BOX_SIZE: f32 = 100.; fn setup(mut commands: Commands) { // Root UI node displaying instructions. // Has no `UiTargetCamera`; the highest-order camera rendering to the primary window will be chosen automatically. commands.spawn(( Node { align_self: AlignSelf::Center, justify_self: JustifySelf::Center, justify_content: JustifyContent::Center, bottom: px(2. * BOX_SIZE), ..default() }, Text::new("Each box is rendered by a different camera\n* left-click: increase the camera's order\n* right-click: decrease the camera's order") )); for (i, color) in [RED, GREEN, BLUE].into_iter().enumerate() { let camera_entity = commands .spawn(( // Ordering behavior is the same using `Camera3d`. Camera2d, Camera { // The viewport will be cleared according to the `ClearColorConfig` of the camera with the lowest order, skipping cameras set to `ClearColorConfig::NONE`. // If all are set to `ClearColorConfig::NONE`, no clear color is used. clear_color: ClearColorConfig::Custom(color.into()), order: i as isize, ..Default::default() }, )) .id(); // Label each box with the order of its camera target let label_entity = commands .spawn(( Text(format!("{i}")), TextFont::from_font_size(50.), TextColor(color.into()), )) .id(); commands .spawn(( Node { align_self: AlignSelf::Center, justify_self: JustifySelf::Center, justify_content: JustifyContent::Center, align_items: AlignItems::Center, left: px(0.67 * BOX_SIZE * (i as f32 - 1.)), top: px(0.67 * BOX_SIZE * (i as f32 - 1.)), width: px(BOX_SIZE), height: px(BOX_SIZE), border: px(0.1 * BOX_SIZE).into(), ..default() }, // Bevy UI doesn't support `RenderLayers`. Each UI layout can only have one render target, selected using `UiTargetCamera`. UiTargetCamera(camera_entity), BackgroundColor(Color::BLACK), BorderColor::all(YELLOW), )) .observe( move |on_pressed: On<Pointer<Press>>, mut label_query: Query<&mut Text>, mut camera_query: Query<&mut Camera>| { let Ok(mut label_text) = label_query.get_mut(label_entity) else { return; }; let Ok(mut camera) = camera_query.get_mut(camera_entity) else { return; }; camera.order += match on_pressed.button { PointerButton::Primary => 1, _ => -1, }; label_text.0 = format!("{}", camera.order); }, ) .add_child(label_entity); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/ui_texture_atlas_slice.rs
examples/ui/ui_texture_atlas_slice.rs
//! This example illustrates how to create buttons with their texture atlases sliced //! and kept in proportion instead of being stretched by the button dimensions use bevy::{ color::palettes::css::{GOLD, ORANGE}, prelude::*, ui::widget::NodeImageMode, }; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, button_system) .run(); } fn button_system( mut interaction_query: Query< (&Interaction, &Children, &mut ImageNode), (Changed<Interaction>, With<Button>), >, mut text_query: Query<&mut Text>, ) { for (interaction, children, mut image) in &mut interaction_query { let mut text = text_query.get_mut(children[0]).unwrap(); match *interaction { Interaction::Pressed => { **text = "Press".to_string(); if let Some(atlas) = &mut image.texture_atlas { atlas.index = (atlas.index + 1) % 30; } image.color = GOLD.into(); } Interaction::Hovered => { **text = "Hover".to_string(); image.color = ORANGE.into(); } Interaction::None => { **text = "Button".to_string(); image.color = Color::WHITE; } } } } fn setup( mut commands: Commands, asset_server: Res<AssetServer>, mut texture_atlases: ResMut<Assets<TextureAtlasLayout>>, ) { let texture_handle = asset_server.load("textures/fantasy_ui_borders/border_sheet.png"); let atlas_layout = TextureAtlasLayout::from_grid(UVec2::new(50, 50), 6, 6, Some(UVec2::splat(2)), None); let atlas_layout_handle = texture_atlases.add(atlas_layout); let slicer = TextureSlicer { border: BorderRect::all(24.0), center_scale_mode: SliceScaleMode::Stretch, sides_scale_mode: SliceScaleMode::Stretch, max_corner_scale: 1.0, }; // ui camera commands.spawn(Camera2d); commands .spawn(Node { width: percent(100), height: percent(100), align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..default() }) .with_children(|parent| { for (idx, [w, h]) in [ (0, [150.0, 150.0]), (7, [300.0, 150.0]), (13, [150.0, 300.0]), ] { parent .spawn(( Button, ImageNode::from_atlas_image( texture_handle.clone(), TextureAtlas { index: idx, layout: atlas_layout_handle.clone(), }, ) .with_mode(NodeImageMode::Sliced(slicer.clone())), Node { width: px(w), height: px(h), // horizontally center child text justify_content: JustifyContent::Center, // vertically center child text align_items: AlignItems::Center, margin: UiRect::all(px(20)), ..default() }, )) .with_children(|parent| { parent.spawn(( Text::new("Button"), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), font_size: 33.0, ..default() }, TextColor(Color::srgb(0.9, 0.9, 0.9)), )); }); } }); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/text_background_colors.rs
examples/ui/text_background_colors.rs
//! This example demonstrates UI text with a background color use bevy::{ color::palettes::css::{BLUE, GREEN, PURPLE, RED, YELLOW}, prelude::*, }; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, cycle_text_background_colors) .run(); } const PALETTE: [Color; 5] = [ Color::Srgba(RED), Color::Srgba(GREEN), Color::Srgba(BLUE), Color::Srgba(YELLOW), Color::Srgba(PURPLE), ]; fn setup(mut commands: Commands) { // UI camera commands.spawn(Camera2d); let message_text = [ "T", "e", "x", "t\n", "B", "a", "c", "k", "g", "r", "o", "u", "n", "d\n", "C", "o", "l", "o", "r", "s", "!", ]; commands .spawn(Node { width: percent(100), height: percent(100), justify_content: JustifyContent::Center, align_items: AlignItems::Center, ..Default::default() }) .with_children(|commands| { commands .spawn(( Text::default(), TextLayout { justify: Justify::Center, ..Default::default() }, )) .with_children(|commands| { for (i, section_str) in message_text.iter().enumerate() { commands .spawn(( TextSpan::new(*section_str), TextColor::BLACK, TextFont { font_size: 100., ..default() }, TextBackgroundColor(PALETTE[i % PALETTE.len()]), )) .observe( |event: On<Pointer<Over>>, mut query: Query<&mut TextColor>| { if let Ok(mut text_color) = query.get_mut(event.entity) { text_color.0 = Color::WHITE; } }, ) .observe( |event: On<Pointer<Out>>, mut query: Query<&mut TextColor>| { if let Ok(mut text_color) = query.get_mut(event.entity) { text_color.0 = Color::BLACK; } }, ); } }); }); } fn cycle_text_background_colors( time: Res<Time>, children_query: Query<&Children, With<Text>>, mut text_background_colors_query: Query<&mut TextBackgroundColor>, ) { let n = time.elapsed_secs() as usize; let children = children_query.single().unwrap(); for (i, child) in children.iter().enumerate() { text_background_colors_query.get_mut(child).unwrap().0 = PALETTE[(i + n) % PALETTE.len()]; } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/scroll.rs
examples/ui/scroll.rs
//! This example illustrates scrolling in Bevy UI. use accesskit::{Node as Accessible, Role}; use bevy::{ a11y::AccessibilityNode, color::palettes::css::{BLACK, BLUE, RED}, ecs::spawn::SpawnIter, input::mouse::{MouseScrollUnit, MouseWheel}, picking::hover::HoverMap, prelude::*, }; fn main() { let mut app = App::new(); app.add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, send_scroll_events) .add_observer(on_scroll_handler); app.run(); } const LINE_HEIGHT: f32 = 21.; /// Injects scroll events into the UI hierarchy. fn send_scroll_events( mut mouse_wheel_reader: MessageReader<MouseWheel>, hover_map: Res<HoverMap>, keyboard_input: Res<ButtonInput<KeyCode>>, mut commands: Commands, ) { for mouse_wheel in mouse_wheel_reader.read() { let mut delta = -Vec2::new(mouse_wheel.x, mouse_wheel.y); if mouse_wheel.unit == MouseScrollUnit::Line { delta *= LINE_HEIGHT; } if keyboard_input.any_pressed([KeyCode::ControlLeft, KeyCode::ControlRight]) { std::mem::swap(&mut delta.x, &mut delta.y); } for pointer_map in hover_map.values() { for entity in pointer_map.keys().copied() { commands.trigger(Scroll { entity, delta }); } } } } /// UI scrolling event. #[derive(EntityEvent, Debug)] #[entity_event(propagate, auto_propagate)] struct Scroll { entity: Entity, /// Scroll delta in logical coordinates. delta: Vec2, } fn on_scroll_handler( mut scroll: On<Scroll>, mut query: Query<(&mut ScrollPosition, &Node, &ComputedNode)>, ) { let Ok((mut scroll_position, node, computed)) = query.get_mut(scroll.entity) else { return; }; let max_offset = (computed.content_size() - computed.size()) * computed.inverse_scale_factor(); let delta = &mut scroll.delta; if node.overflow.x == OverflowAxis::Scroll && delta.x != 0. { // Is this node already scrolled all the way in the direction of the scroll? let max = if delta.x > 0. { scroll_position.x >= max_offset.x } else { scroll_position.x <= 0. }; if !max { scroll_position.x += delta.x; // Consume the X portion of the scroll delta. delta.x = 0.; } } if node.overflow.y == OverflowAxis::Scroll && delta.y != 0. { // Is this node already scrolled all the way in the direction of the scroll? let max = if delta.y > 0. { scroll_position.y >= max_offset.y } else { scroll_position.y <= 0. }; if !max { scroll_position.y += delta.y; // Consume the Y portion of the scroll delta. delta.y = 0.; } } // Stop propagating when the delta is fully consumed. if *delta == Vec2::ZERO { scroll.propagate(false); } } const FONT_SIZE: f32 = 20.; fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { // Camera commands.spawn((Camera2d, IsDefaultUiCamera)); // Font let font_handle = asset_server.load("fonts/FiraSans-Bold.ttf"); // root node commands .spawn(Node { width: percent(100), height: percent(100), justify_content: JustifyContent::SpaceBetween, flex_direction: FlexDirection::Column, ..default() }) .with_children(|parent| { // horizontal scroll example parent .spawn(Node { width: percent(100), flex_direction: FlexDirection::Column, ..default() }) .with_children(|parent| { // header parent.spawn(( Text::new("Horizontally Scrolling list (Ctrl + MouseWheel)"), TextFont { font: font_handle.clone().into(), font_size: FONT_SIZE, ..default() }, Label, )); // horizontal scroll container parent .spawn(( Node { width: percent(80), margin: UiRect::all(px(10)), flex_direction: FlexDirection::Row, overflow: Overflow::scroll_x(), // n.b. ..default() }, BackgroundColor(Color::srgb(0.10, 0.10, 0.10)), )) .with_children(|parent| { for i in 0..100 { parent .spawn(( Text(format!("Item {i}")), TextFont { font: font_handle.clone().into(), ..default() }, Label, AccessibilityNode(Accessible::new(Role::ListItem)), Node { min_width: px(200), align_content: AlignContent::Center, ..default() }, )) .observe( |press: On<Pointer<Press>>, mut commands: Commands| { if press.event().button == PointerButton::Primary { commands.entity(press.entity).despawn(); } }, ); } }); }); // container for all other examples parent.spawn(( Node { width: percent(100), height: percent(100), flex_direction: FlexDirection::Row, justify_content: JustifyContent::SpaceBetween, ..default() }, children![ vertically_scrolling_list(asset_server.load("fonts/FiraSans-Bold.ttf")), bidirectional_scrolling_list(asset_server.load("fonts/FiraSans-Bold.ttf")), bidirectional_scrolling_list_with_sticky( asset_server.load("fonts/FiraSans-Bold.ttf") ), nested_scrolling_list(asset_server.load("fonts/FiraSans-Bold.ttf")), ], )); }); } fn vertically_scrolling_list(font_handle: Handle<Font>) -> impl Bundle { ( Node { flex_direction: FlexDirection::Column, justify_content: JustifyContent::Center, align_items: AlignItems::Center, width: px(200), ..default() }, children![ ( // Title Text::new("Vertically Scrolling List"), TextFont { font: font_handle.clone().into(), font_size: FONT_SIZE, ..default() }, Label, ), ( // Scrolling list Node { flex_direction: FlexDirection::Column, align_self: AlignSelf::Stretch, height: percent(50), overflow: Overflow::scroll_y(), // n.b. scrollbar_width: 20., ..default() }, #[cfg(feature = "bevy_ui_debug")] UiDebugOptions { enabled: true, outline_border_box: false, outline_padding_box: false, outline_content_box: false, outline_scrollbars: true, line_width: 2., line_color_override: None, show_hidden: false, show_clipped: true, ignore_border_radius: true, }, BackgroundColor(Color::srgb(0.10, 0.10, 0.10)), Children::spawn(SpawnIter((0..25).map(move |i| { ( Node { min_height: px(LINE_HEIGHT), max_height: px(LINE_HEIGHT), ..default() }, children![( Text(format!("Item {i}")), TextFont { font: font_handle.clone().into(), ..default() }, Label, AccessibilityNode(Accessible::new(Role::ListItem)), )], ) }))) ), ], ) } fn bidirectional_scrolling_list(font_handle: Handle<Font>) -> impl Bundle { ( Node { flex_direction: FlexDirection::Column, justify_content: JustifyContent::Center, align_items: AlignItems::Center, width: px(200), ..default() }, children![ ( Text::new("Bidirectionally Scrolling List"), TextFont { font: font_handle.clone().into(), font_size: FONT_SIZE, ..default() }, Label, ), ( Node { flex_direction: FlexDirection::Column, align_self: AlignSelf::Stretch, height: percent(50), overflow: Overflow::scroll(), // n.b. ..default() }, BackgroundColor(Color::srgb(0.10, 0.10, 0.10)), Children::spawn(SpawnIter((0..25).map(move |oi| { ( Node { flex_direction: FlexDirection::Row, ..default() }, Children::spawn(SpawnIter((0..10).map({ let value = font_handle.clone(); move |i| { ( Text(format!("Item {}", (oi * 10) + i)), TextFont::from(value.clone()), Label, AccessibilityNode(Accessible::new(Role::ListItem)), ) } }))), ) }))) ) ], ) } fn bidirectional_scrolling_list_with_sticky(font_handle: Handle<Font>) -> impl Bundle { ( Node { flex_direction: FlexDirection::Column, justify_content: JustifyContent::Center, align_items: AlignItems::Center, width: px(200), ..default() }, children![ ( Text::new("Bidirectionally Scrolling List With Sticky Nodes"), TextFont { font: font_handle.clone().into(), font_size: FONT_SIZE, ..default() }, Label, ), ( Node { display: Display::Grid, align_self: AlignSelf::Stretch, height: percent(50), overflow: Overflow::scroll(), // n.b. grid_template_columns: RepeatedGridTrack::auto(30), ..default() }, Children::spawn(SpawnIter( (0..30) .flat_map(|y| (0..30).map(move |x| (y, x))) .map(move |(y, x)| { let value = font_handle.clone(); // Simple sticky nodes at top and left sides of UI node // can be achieved by combining such effects as // IgnoreScroll, ZIndex, BackgroundColor for child UI nodes. let ignore_scroll = BVec2 { x: x == 0, y: y == 0, }; let (z_index, background_color, role) = match (x == 0, y == 0) { (true, true) => (2, RED, Role::RowHeader), (true, false) => (1, BLUE, Role::RowHeader), (false, true) => (1, BLUE, Role::ColumnHeader), (false, false) => (0, BLACK, Role::Cell), }; ( Text(format!("|{},{}|", y, x)), TextFont::from(value.clone()), TextLayout { linebreak: LineBreak::NoWrap, ..default() }, Label, AccessibilityNode(Accessible::new(role)), IgnoreScroll(ignore_scroll), ZIndex(z_index), BackgroundColor(Color::Srgba(background_color)), ) }) )) ) ], ) } fn nested_scrolling_list(font_handle: Handle<Font>) -> impl Bundle { ( Node { flex_direction: FlexDirection::Column, justify_content: JustifyContent::Center, align_items: AlignItems::Center, width: px(200), ..default() }, children![ ( // Title Text::new("Nested Scrolling Lists"), TextFont { font: font_handle.clone().into(), font_size: FONT_SIZE, ..default() }, Label, ), ( // Outer, bi-directional scrolling container Node { column_gap: px(20), flex_direction: FlexDirection::Row, align_self: AlignSelf::Stretch, height: percent(50), overflow: Overflow::scroll(), ..default() }, BackgroundColor(Color::srgb(0.10, 0.10, 0.10)), // Inner, scrolling columns Children::spawn(SpawnIter((0..5).map(move |oi| { ( Node { flex_direction: FlexDirection::Column, align_self: AlignSelf::Stretch, height: percent(200. / 5. * (oi as f32 + 1.)), overflow: Overflow::scroll_y(), ..default() }, BackgroundColor(Color::srgb(0.05, 0.05, 0.05)), Children::spawn(SpawnIter((0..20).map({ let value = font_handle.clone(); move |i| { ( Text(format!("Item {}", (oi * 20) + i)), TextFont::from(value.clone()), Label, AccessibilityNode(Accessible::new(Role::ListItem)), ) } }))), ) }))) ) ], ) }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/overflow_clip_margin.rs
examples/ui/overflow_clip_margin.rs
//! Simple example demonstrating the `OverflowClipMargin` style property. use bevy::{color::palettes::css::*, prelude::*}; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .run(); } fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn(Camera2d); let image = asset_server.load("branding/icon.png"); commands .spawn(( Node { width: percent(100), height: percent(100), align_items: AlignItems::Center, justify_content: JustifyContent::Center, row_gap: px(40), flex_direction: FlexDirection::Column, ..default() }, BackgroundColor(ANTIQUE_WHITE.into()), )) .with_children(|parent| { for overflow_clip_margin in [ OverflowClipMargin::border_box().with_margin(25.), OverflowClipMargin::border_box(), OverflowClipMargin::padding_box(), OverflowClipMargin::content_box(), ] { parent .spawn(Node { flex_direction: FlexDirection::Row, column_gap: px(20), ..default() }) .with_children(|parent| { parent .spawn(( Node { padding: UiRect::all(px(10)), margin: UiRect::bottom(px(25)), ..default() }, BackgroundColor(Color::srgb(0.25, 0.25, 0.25)), )) .with_child(Text(format!("{overflow_clip_margin:#?}"))); parent .spawn(( Node { margin: UiRect::top(px(10)), width: px(100), height: px(100), padding: UiRect::all(px(20)), border: UiRect::all(px(5)), overflow: Overflow::clip(), overflow_clip_margin, ..default() }, BackgroundColor(GRAY.into()), BorderColor::all(Color::BLACK), )) .with_children(|parent| { parent .spawn(( Node { min_width: px(50), min_height: px(50), ..default() }, BackgroundColor(LIGHT_CYAN.into()), )) .with_child(( ImageNode::new(image.clone()), Node { min_width: px(100), min_height: px(100), ..default() }, )); }); }); } }); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/virtual_keyboard.rs
examples/ui/virtual_keyboard.rs
//! Virtual keyboard example use bevy::{ color::palettes::css::NAVY, feathers::{ controls::{virtual_keyboard, VirtualKeyPressed}, dark_theme::create_dark_theme, theme::UiTheme, FeathersPlugins, }, prelude::*, ui_widgets::observe, }; fn main() { App::new() .add_plugins((DefaultPlugins, FeathersPlugins)) .insert_resource(UiTheme(create_dark_theme())) .add_systems(Startup, setup) .run(); } fn on_virtual_key_pressed(virtual_key_pressed: On<VirtualKeyPressed<&'static str>>) { println!("key pressed: {}", virtual_key_pressed.key); } fn setup(mut commands: Commands) { // ui camera commands.spawn(Camera2d); let layout = [ vec!["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ".", ","], vec!["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"], vec!["A", "S", "D", "F", "G", "H", "J", "K", "L", "'"], vec!["Z", "X", "C", "V", "B", "N", "M", "-", "/"], vec!["space", "enter", "backspace"], vec!["left", "right", "up", "down", "home", "end"], ]; commands.spawn(( Node { width: percent(100), height: percent(100), align_items: AlignItems::End, justify_content: JustifyContent::Center, ..default() }, children![( Node { flex_direction: FlexDirection::Column, border: px(5).into(), row_gap: px(5), padding: px(5).into(), align_items: AlignItems::Center, margin: px(25).into(), border_radius: BorderRadius::all(px(10)), ..Default::default() }, BackgroundColor(NAVY.into()), BorderColor::all(Color::WHITE), children![ Text::new("virtual keyboard"), ( virtual_keyboard(layout.into_iter()), observe(on_virtual_key_pressed) ) ] )], )); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/vertical_slider.rs
examples/ui/vertical_slider.rs
//! Simple example showing vertical and horizontal slider widgets with snap behavior and value labels use bevy::{ input_focus::{ tab_navigation::{TabGroup, TabIndex, TabNavigationPlugin}, InputDispatchPlugin, }, picking::hover::Hovered, prelude::*, ui_widgets::{ observe, slider_self_update, CoreSliderDragState, Slider, SliderRange, SliderThumb, SliderValue, TrackClick, UiWidgetsPlugins, }, }; const SLIDER_TRACK: Color = Color::srgb(0.05, 0.05, 0.05); const SLIDER_THUMB: Color = Color::srgb(0.35, 0.75, 0.35); fn main() { App::new() .add_plugins(( DefaultPlugins, UiWidgetsPlugins, InputDispatchPlugin, TabNavigationPlugin, )) .add_systems(Startup, setup) .add_systems(Update, (update_slider_visuals, update_value_labels)) .run(); } #[derive(Component)] struct ValueLabel(Entity); #[derive(Component)] struct DemoSlider; #[derive(Component)] struct DemoSliderThumb; #[derive(Component)] struct VerticalSlider; fn setup(mut commands: Commands, assets: Res<AssetServer>) { commands.spawn(Camera2d); commands .spawn(( Node { width: percent(100), height: percent(100), align_items: AlignItems::Center, justify_content: JustifyContent::Center, display: Display::Flex, flex_direction: FlexDirection::Row, column_gap: px(50), ..default() }, TabGroup::default(), )) .with_children(|parent| { // Vertical slider parent .spawn(Node { display: Display::Flex, flex_direction: FlexDirection::Column, align_items: AlignItems::Center, row_gap: px(10), ..default() }) .with_children(|parent| { parent.spawn(( Text::new("Vertical"), TextFont { font: assets.load("fonts/FiraSans-Bold.ttf").into(), font_size: 20.0, ..default() }, TextColor(Color::srgb(0.9, 0.9, 0.9)), )); let label_id = parent .spawn(( Text::new("50"), TextFont { font: assets.load("fonts/FiraSans-Bold.ttf").into(), font_size: 24.0, ..default() }, TextColor(Color::srgb(0.9, 0.9, 0.9)), )) .id(); parent.spawn(( vertical_slider(), ValueLabel(label_id), observe(slider_self_update), )); }); // Horizontal slider parent .spawn(Node { display: Display::Flex, flex_direction: FlexDirection::Column, align_items: AlignItems::Center, row_gap: px(10), ..default() }) .with_children(|parent| { parent.spawn(( Text::new("Horizontal"), TextFont { font: assets.load("fonts/FiraSans-Bold.ttf").into(), font_size: 20.0, ..default() }, TextColor(Color::srgb(0.9, 0.9, 0.9)), )); let label_id = parent .spawn(( Text::new("50"), TextFont { font: assets.load("fonts/FiraSans-Bold.ttf").into(), font_size: 24.0, ..default() }, TextColor(Color::srgb(0.9, 0.9, 0.9)), )) .id(); parent.spawn(( horizontal_slider(), ValueLabel(label_id), observe(slider_self_update), )); }); }); } fn vertical_slider() -> impl Bundle { ( Node { display: Display::Flex, flex_direction: FlexDirection::Row, justify_content: JustifyContent::Center, align_items: AlignItems::Stretch, column_gap: px(4), width: px(12), height: px(200), ..default() }, DemoSlider, VerticalSlider, Hovered::default(), Slider { track_click: TrackClick::Snap, }, SliderValue(50.0), SliderRange::new(0.0, 100.0), TabIndex(0), Children::spawn(( Spawn(( Node { width: px(6), border_radius: BorderRadius::all(px(3)), ..default() }, BackgroundColor(SLIDER_TRACK), )), Spawn(( Node { display: Display::Flex, position_type: PositionType::Absolute, top: px(12), bottom: px(0), left: px(0), right: px(0), ..default() }, children![( DemoSliderThumb, SliderThumb, Node { display: Display::Flex, width: px(12), height: px(12), position_type: PositionType::Absolute, bottom: percent(0), border_radius: BorderRadius::MAX, ..default() }, BackgroundColor(SLIDER_THUMB), )], )), )), ) } fn horizontal_slider() -> impl Bundle { ( Node { display: Display::Flex, flex_direction: FlexDirection::Column, justify_content: JustifyContent::Center, align_items: AlignItems::Stretch, column_gap: px(4), height: px(12), width: px(200), ..default() }, DemoSlider, Hovered::default(), Slider { track_click: TrackClick::Snap, }, SliderValue(50.0), SliderRange::new(0.0, 100.0), TabIndex(0), Children::spawn(( Spawn(( Node { height: px(6), border_radius: BorderRadius::all(px(3)), ..default() }, BackgroundColor(SLIDER_TRACK), )), Spawn(( Node { display: Display::Flex, position_type: PositionType::Absolute, left: px(0), right: px(12), top: px(0), bottom: px(0), ..default() }, children![( DemoSliderThumb, SliderThumb, Node { display: Display::Flex, width: px(12), height: px(12), position_type: PositionType::Absolute, left: percent(0), border_radius: BorderRadius::MAX, ..default() }, BackgroundColor(SLIDER_THUMB), )], )), )), ) } fn update_slider_visuals( sliders: Query< ( Entity, &SliderValue, &SliderRange, &Hovered, &CoreSliderDragState, Has<VerticalSlider>, ), ( Or<( Changed<SliderValue>, Changed<Hovered>, Changed<CoreSliderDragState>, )>, With<DemoSlider>, ), >, children: Query<&Children>, mut thumbs: Query<(&mut Node, &mut BackgroundColor, Has<DemoSliderThumb>), Without<DemoSlider>>, ) { for (slider_ent, value, range, hovered, drag_state, is_vertical) in sliders.iter() { for child in children.iter_descendants(slider_ent) { if let Ok((mut thumb_node, mut thumb_bg, is_thumb)) = thumbs.get_mut(child) && is_thumb { let position = range.thumb_position(value.0) * 100.0; if is_vertical { thumb_node.bottom = percent(position); } else { thumb_node.left = percent(position); } let is_active = hovered.0 | drag_state.dragging; thumb_bg.0 = if is_active { SLIDER_THUMB.lighter(0.3) } else { SLIDER_THUMB }; } } } } fn update_value_labels( sliders: Query<(&SliderValue, &ValueLabel), (Changed<SliderValue>, With<DemoSlider>)>, mut texts: Query<&mut Text>, ) { for (value, label) in sliders.iter() { if let Ok(mut text) = texts.get_mut(label.0) { **text = format!("{:.0}", value.0); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/ui_transform.rs
examples/ui/ui_transform.rs
//! An example demonstrating how to translate, rotate and scale UI elements. use bevy::color::palettes::css::DARK_GRAY; use bevy::color::palettes::css::RED; use bevy::color::palettes::css::YELLOW; use bevy::prelude::*; use core::f32::consts::FRAC_PI_8; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, button_system) .add_systems(Update, translation_system) .run(); } const NORMAL_BUTTON: Color = Color::WHITE; const HOVERED_BUTTON: Color = Color::Srgba(YELLOW); const PRESSED_BUTTON: Color = Color::Srgba(RED); /// A button that rotates the target node #[derive(Component)] pub struct RotateButton(pub Rot2); /// A button that scales the target node #[derive(Component)] pub struct ScaleButton(pub f32); /// Marker component so the systems know which entities to translate, rotate and scale #[derive(Component)] pub struct TargetNode; /// Handles button interactions fn button_system( mut interaction_query: Query< ( &Interaction, &mut BackgroundColor, Option<&RotateButton>, Option<&ScaleButton>, ), (Changed<Interaction>, With<Button>), >, mut rotator_query: Query<&mut UiTransform, With<TargetNode>>, ) { for (interaction, mut color, maybe_rotate, maybe_scale) in &mut interaction_query { match *interaction { Interaction::Pressed => { *color = PRESSED_BUTTON.into(); if let Some(step) = maybe_rotate { for mut transform in rotator_query.iter_mut() { transform.rotation *= step.0; } } if let Some(step) = maybe_scale { for mut transform in rotator_query.iter_mut() { transform.scale += step.0; transform.scale = transform.scale.clamp(Vec2::splat(0.25), Vec2::splat(3.0)); } } } Interaction::Hovered => { *color = HOVERED_BUTTON.into(); } Interaction::None => { *color = NORMAL_BUTTON.into(); } } } } // move the rotating panel when the arrow keys are pressed fn translation_system( time: Res<Time>, input: Res<ButtonInput<KeyCode>>, mut translation_query: Query<&mut UiTransform, With<TargetNode>>, ) { let controls = [ (KeyCode::ArrowLeft, -Vec2::X), (KeyCode::ArrowRight, Vec2::X), (KeyCode::ArrowUp, -Vec2::Y), (KeyCode::ArrowDown, Vec2::Y), ]; for &(key_code, direction) in &controls { if input.pressed(key_code) { for mut transform in translation_query.iter_mut() { let d = direction * 50.0 * time.delta_secs(); let (Val::Px(x), Val::Px(y)) = (transform.translation.x, transform.translation.y) else { continue; }; let x = (x + d.x).clamp(-150., 150.); let y = (y + d.y).clamp(-150., 150.); transform.translation = Val2::px(x, y); } } } } fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { // UI camera commands.spawn(Camera2d); // Root node filling the whole screen commands.spawn(( Node { width: percent(100), height: percent(100), align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..default() }, BackgroundColor(Color::BLACK), children![( Node { align_items: AlignItems::Center, justify_content: JustifyContent::SpaceEvenly, column_gap: px(25), row_gap: px(25), ..default() }, BackgroundColor(Color::BLACK), children![ ( Node { flex_direction: FlexDirection::Column, justify_content: JustifyContent::Center, row_gap: px(10), column_gap: px(10), padding: UiRect::all(px(10)), ..default() }, BackgroundColor(Color::BLACK), GlobalZIndex(1), children![ ( Button, Node { height: px(50), width: px(50), align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..default() }, BackgroundColor(Color::WHITE), RotateButton(Rot2::radians(-FRAC_PI_8)), children![(Text::new("<--"), TextColor(Color::BLACK),)] ), ( Button, Node { height: px(50), width: px(50), align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..default() }, BackgroundColor(Color::WHITE), ScaleButton(-0.25), children![(Text::new("-"), TextColor(Color::BLACK),)] ), ] ), // Target node with its own set of buttons ( Node { flex_direction: FlexDirection::Column, justify_content: JustifyContent::SpaceBetween, align_items: AlignItems::Center, width: px(300), height: px(300), ..default() }, BackgroundColor(DARK_GRAY.into()), TargetNode, children![ ( Button, Node { width: px(80), height: px(80), align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..default() }, BackgroundColor(Color::WHITE), children![(Text::new("Top"), TextColor(Color::BLACK))] ), ( Node { align_self: AlignSelf::Stretch, justify_content: JustifyContent::SpaceBetween, align_items: AlignItems::Center, ..default() }, children![ ( Button, Node { width: px(80), height: px(80), align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..default() }, BackgroundColor(Color::WHITE), UiTransform::from_rotation(Rot2::radians( -std::f32::consts::FRAC_PI_2 )), children![(Text::new("Left"), TextColor(Color::BLACK),)] ), ( Node { width: px(100), height: px(100), ..Default::default() }, ImageNode { image: asset_server.load("branding/icon.png"), image_mode: NodeImageMode::Stretch, ..default() } ), ( Button, Node { width: px(80), height: px(80), align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..default() }, UiTransform::from_rotation(Rot2::radians( core::f32::consts::FRAC_PI_2 )), BackgroundColor(Color::WHITE), children![(Text::new("Right"), TextColor(Color::BLACK))] ), ] ), ( Button, Node { width: px(80), height: px(80), align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..default() }, BackgroundColor(Color::WHITE), UiTransform::from_rotation(Rot2::radians(std::f32::consts::PI)), children![(Text::new("Bottom"), TextColor(Color::BLACK),)] ), ] ), // Right column of controls ( Node { flex_direction: FlexDirection::Column, justify_content: JustifyContent::Center, row_gap: px(10), column_gap: px(10), padding: UiRect::all(px(10)), ..default() }, BackgroundColor(Color::BLACK), GlobalZIndex(1), children![ ( Button, Node { height: px(50), width: px(50), align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..default() }, BackgroundColor(Color::WHITE), RotateButton(Rot2::radians(FRAC_PI_8)), children![(Text::new("-->"), TextColor(Color::BLACK),)] ), ( Button, Node { height: px(50), width: px(50), align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..default() }, BackgroundColor(Color::WHITE), ScaleButton(0.25), children![(Text::new("+"), TextColor(Color::BLACK),)] ), ] ) ] )], )); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/auto_directional_navigation.rs
examples/ui/auto_directional_navigation.rs
//! Demonstrates automatic directional navigation with zero configuration. //! //! Unlike the manual `directional_navigation` example, this shows how to use automatic //! navigation by simply adding the `AutoDirectionalNavigation` component to UI elements. //! The navigation graph is automatically built and maintained based on screen positions. //! //! This is especially useful for: //! - Dynamic UIs where elements may be added, removed, or repositioned //! - Irregular layouts that don't fit a simple grid pattern //! - Prototyping where you want navigation without tedious manual setup //! //! The automatic system finds the nearest neighbor in each compass direction for every node, //! completely eliminating the need to manually specify navigation relationships. use core::time::Duration; use bevy::{ camera::NormalizedRenderTarget, input_focus::{ directional_navigation::{ AutoDirectionalNavigation, AutoNavigationConfig, DirectionalNavigation, DirectionalNavigationPlugin, }, InputDispatchPlugin, InputFocus, InputFocusVisible, }, math::{CompassOctant, Dir2}, picking::{ backend::HitData, pointer::{Location, PointerId}, }, platform::collections::HashSet, prelude::*, }; fn main() { App::new() // Input focus is not enabled by default, so we need to add the corresponding plugins .add_plugins(( DefaultPlugins, InputDispatchPlugin, DirectionalNavigationPlugin, )) // This resource is canonically used to track whether or not to render a focus indicator // It starts as false, but we set it to true here as we would like to see the focus indicator .insert_resource(InputFocusVisible(true)) // Configure auto-navigation behavior .insert_resource(AutoNavigationConfig { // Require at least 10% overlap in perpendicular axis for cardinal directions min_alignment_factor: 0.1, // Don't connect nodes more than 500 pixels apart max_search_distance: Some(500.0), // Prefer nodes that are well-aligned prefer_aligned: true, }) .init_resource::<ActionState>() .add_systems(Startup, setup_scattered_ui) // Navigation graph is automatically maintained by DirectionalNavigationPlugin! // No manual system needed - just add AutoDirectionalNavigation to entities. // Input is generally handled during PreUpdate .add_systems(PreUpdate, (process_inputs, navigate).chain()) .add_systems( Update, ( highlight_focused_element, interact_with_focused_button, reset_button_after_interaction, update_focus_display, update_key_display, ), ) .add_observer(universal_button_click_behavior) .run(); } const NORMAL_BUTTON: Srgba = bevy::color::palettes::tailwind::BLUE_400; const PRESSED_BUTTON: Srgba = bevy::color::palettes::tailwind::BLUE_500; const FOCUSED_BORDER: Srgba = bevy::color::palettes::tailwind::BLUE_50; /// Marker component for the text that displays the currently focused button #[derive(Component)] struct FocusDisplay; /// Marker component for the text that displays the last key pressed #[derive(Component)] struct KeyDisplay; // Observer for button clicks fn universal_button_click_behavior( mut click: On<Pointer<Click>>, mut button_query: Query<(&mut BackgroundColor, &mut ResetTimer)>, ) { let button_entity = click.entity; if let Ok((mut color, mut reset_timer)) = button_query.get_mut(button_entity) { color.0 = PRESSED_BUTTON.into(); reset_timer.0 = Timer::from_seconds(0.3, TimerMode::Once); click.propagate(false); } } #[derive(Component, Default, Deref, DerefMut)] struct ResetTimer(Timer); fn reset_button_after_interaction( time: Res<Time>, mut query: Query<(&mut ResetTimer, &mut BackgroundColor)>, ) { for (mut reset_timer, mut color) in query.iter_mut() { reset_timer.tick(time.delta()); if reset_timer.just_finished() { color.0 = NORMAL_BUTTON.into(); } } } /// Spawn a scattered layout of buttons to demonstrate automatic navigation. /// /// Unlike a regular grid, these buttons are irregularly positioned, /// but auto-navigation will still figure out the correct connections! fn setup_scattered_ui(mut commands: Commands, mut input_focus: ResMut<InputFocus>) { commands.spawn(Camera2d); // Create a full-screen background node let root_node = commands .spawn(Node { width: percent(100), height: percent(100), ..default() }) .id(); // Instructions let instructions = commands .spawn(( Text::new( "Automatic Navigation Demo\n\n\ Use arrow keys or D-pad to navigate.\n\ Press Enter or A button to interact.\n\n\ Buttons are scattered irregularly,\n\ but navigation is automatic!", ), Node { position_type: PositionType::Absolute, left: px(20), top: px(20), width: px(280), padding: UiRect::all(px(12)), border_radius: BorderRadius::all(px(8)), ..default() }, BackgroundColor(Color::srgba(0.1, 0.1, 0.1, 0.8)), )) .id(); // Focus display - shows which button is currently focused commands.spawn(( Text::new("Focused: None"), FocusDisplay, Node { position_type: PositionType::Absolute, left: px(20), bottom: px(80), width: px(280), padding: UiRect::all(px(12)), border_radius: BorderRadius::all(px(8)), ..default() }, BackgroundColor(Color::srgba(0.1, 0.5, 0.1, 0.8)), TextFont { font_size: 20.0, ..default() }, )); // Key display - shows the last key pressed commands.spawn(( Text::new("Last Key: None"), KeyDisplay, Node { position_type: PositionType::Absolute, left: px(20), bottom: px(20), width: px(280), padding: UiRect::all(px(12)), border_radius: BorderRadius::all(px(8)), ..default() }, BackgroundColor(Color::srgba(0.5, 0.1, 0.5, 0.8)), TextFont { font_size: 20.0, ..default() }, )); // Spawn buttons in a scattered/irregular pattern // The auto-navigation system will figure out the connections! let button_positions = [ // Top row (irregular spacing) (350.0, 100.0), (520.0, 120.0), (700.0, 90.0), // Middle-top row (380.0, 220.0), (600.0, 240.0), // Center (450.0, 340.0), (620.0, 360.0), // Lower row (360.0, 480.0), (540.0, 460.0), (720.0, 490.0), ]; let mut first_button = None; for (i, (x, y)) in button_positions.iter().enumerate() { let button_entity = commands .spawn(( Button, Node { position_type: PositionType::Absolute, left: px(*x), top: px(*y), width: px(140), height: px(80), border: UiRect::all(px(4)), justify_content: JustifyContent::Center, align_items: AlignItems::Center, border_radius: BorderRadius::all(px(12)), ..default() }, // This is the key: just add this component for automatic navigation! AutoDirectionalNavigation::default(), ResetTimer::default(), BackgroundColor::from(NORMAL_BUTTON), Name::new(format!("Button {}", i + 1)), )) .with_child(( Text::new(format!("Button {}", i + 1)), TextLayout { justify: Justify::Center, ..default() }, )) .id(); if first_button.is_none() { first_button = Some(button_entity); } } commands.entity(root_node).add_children(&[instructions]); // Set initial focus if let Some(button) = first_button { input_focus.set(button); } } // Action state and input handling (same as the manual navigation example) #[derive(Debug, PartialEq, Eq, Hash)] enum DirectionalNavigationAction { Up, Down, Left, Right, Select, } impl DirectionalNavigationAction { fn variants() -> Vec<Self> { vec![ DirectionalNavigationAction::Up, DirectionalNavigationAction::Down, DirectionalNavigationAction::Left, DirectionalNavigationAction::Right, DirectionalNavigationAction::Select, ] } fn keycode(&self) -> KeyCode { match self { DirectionalNavigationAction::Up => KeyCode::ArrowUp, DirectionalNavigationAction::Down => KeyCode::ArrowDown, DirectionalNavigationAction::Left => KeyCode::ArrowLeft, DirectionalNavigationAction::Right => KeyCode::ArrowRight, DirectionalNavigationAction::Select => KeyCode::Enter, } } fn gamepad_button(&self) -> GamepadButton { match self { DirectionalNavigationAction::Up => GamepadButton::DPadUp, DirectionalNavigationAction::Down => GamepadButton::DPadDown, DirectionalNavigationAction::Left => GamepadButton::DPadLeft, DirectionalNavigationAction::Right => GamepadButton::DPadRight, DirectionalNavigationAction::Select => GamepadButton::South, } } } #[derive(Default, Resource)] struct ActionState { pressed_actions: HashSet<DirectionalNavigationAction>, } fn process_inputs( mut action_state: ResMut<ActionState>, keyboard_input: Res<ButtonInput<KeyCode>>, gamepad_input: Query<&Gamepad>, ) { action_state.pressed_actions.clear(); for action in DirectionalNavigationAction::variants() { if keyboard_input.just_pressed(action.keycode()) { action_state.pressed_actions.insert(action); } } for gamepad in gamepad_input.iter() { for action in DirectionalNavigationAction::variants() { if gamepad.just_pressed(action.gamepad_button()) { action_state.pressed_actions.insert(action); } } } } fn navigate(action_state: Res<ActionState>, mut directional_navigation: DirectionalNavigation) { let net_east_west = action_state .pressed_actions .contains(&DirectionalNavigationAction::Right) as i8 - action_state .pressed_actions .contains(&DirectionalNavigationAction::Left) as i8; let net_north_south = action_state .pressed_actions .contains(&DirectionalNavigationAction::Up) as i8 - action_state .pressed_actions .contains(&DirectionalNavigationAction::Down) as i8; // Use Dir2::from_xy to convert input to direction, then convert to CompassOctant let maybe_direction = Dir2::from_xy(net_east_west as f32, net_north_south as f32) .ok() .map(CompassOctant::from); if let Some(direction) = maybe_direction { match directional_navigation.navigate(direction) { Ok(_entity) => { // Successfully navigated } Err(_e) => { // Navigation failed (no neighbor in that direction) } } } } fn update_focus_display( input_focus: Res<InputFocus>, button_query: Query<&Name, With<Button>>, mut display_query: Query<&mut Text, With<FocusDisplay>>, ) { if let Ok(mut text) = display_query.single_mut() { if let Some(focused_entity) = input_focus.0 { if let Ok(name) = button_query.get(focused_entity) { **text = format!("Focused: {}", name); } else { **text = "Focused: Unknown".to_string(); } } else { **text = "Focused: None".to_string(); } } } fn update_key_display( keyboard_input: Res<ButtonInput<KeyCode>>, gamepad_input: Query<&Gamepad>, mut display_query: Query<&mut Text, With<KeyDisplay>>, ) { if let Ok(mut text) = display_query.single_mut() { // Check for keyboard inputs for action in DirectionalNavigationAction::variants() { if keyboard_input.just_pressed(action.keycode()) { let key_name = match action { DirectionalNavigationAction::Up => "Up Arrow", DirectionalNavigationAction::Down => "Down Arrow", DirectionalNavigationAction::Left => "Left Arrow", DirectionalNavigationAction::Right => "Right Arrow", DirectionalNavigationAction::Select => "Enter", }; **text = format!("Last Key: {}", key_name); return; } } // Check for gamepad inputs for gamepad in gamepad_input.iter() { for action in DirectionalNavigationAction::variants() { if gamepad.just_pressed(action.gamepad_button()) { let button_name = match action { DirectionalNavigationAction::Up => "D-Pad Up", DirectionalNavigationAction::Down => "D-Pad Down", DirectionalNavigationAction::Left => "D-Pad Left", DirectionalNavigationAction::Right => "D-Pad Right", DirectionalNavigationAction::Select => "A Button", }; **text = format!("Last Key: {}", button_name); return; } } } } } fn highlight_focused_element( input_focus: Res<InputFocus>, input_focus_visible: Res<InputFocusVisible>, mut query: Query<(Entity, &mut BorderColor)>, ) { for (entity, mut border_color) in query.iter_mut() { if input_focus.0 == Some(entity) && input_focus_visible.0 { *border_color = BorderColor::all(FOCUSED_BORDER); } else { *border_color = BorderColor::DEFAULT; } } } fn interact_with_focused_button( action_state: Res<ActionState>, input_focus: Res<InputFocus>, mut commands: Commands, ) { if action_state .pressed_actions .contains(&DirectionalNavigationAction::Select) && let Some(focused_entity) = input_focus.0 { commands.trigger(Pointer::<Click> { entity: focused_entity, pointer_id: PointerId::Mouse, pointer_location: Location { target: NormalizedRenderTarget::None { width: 0, height: 0, }, position: Vec2::ZERO, }, event: Click { button: PointerButton::Primary, hit: HitData { camera: Entity::PLACEHOLDER, depth: 0.0, position: None, normal: None, }, duration: Duration::from_secs_f32(0.1), }, }); } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/overflow.rs
examples/ui/overflow.rs
//! Simple example demonstrating overflow behavior. use bevy::{color::palettes::css::*, prelude::*}; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, update_outlines) .run(); } fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn(Camera2d); let text_style = TextFont::default(); let image = asset_server.load("branding/icon.png"); commands .spawn(( Node { width: percent(100), height: percent(100), align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..Default::default() }, BackgroundColor(ANTIQUE_WHITE.into()), )) .with_children(|parent| { for overflow in [ Overflow::visible(), Overflow::clip_x(), Overflow::clip_y(), Overflow::clip(), ] { parent .spawn(Node { flex_direction: FlexDirection::Column, align_items: AlignItems::Center, margin: UiRect::horizontal(px(25)), ..Default::default() }) .with_children(|parent| { let label = format!("{overflow:#?}"); parent .spawn(( Node { padding: UiRect::all(px(10)), margin: UiRect::bottom(px(25)), ..Default::default() }, BackgroundColor(Color::srgb(0.25, 0.25, 0.25)), )) .with_children(|parent| { parent.spawn((Text::new(label), text_style.clone())); }); parent .spawn(( Node { width: px(100), height: px(100), padding: UiRect { left: px(25), top: px(25), ..Default::default() }, border: UiRect::all(px(5)), overflow, ..default() }, BorderColor::all(Color::BLACK), BackgroundColor(GRAY.into()), )) .with_children(|parent| { parent.spawn(( ImageNode::new(image.clone()), Node { min_width: px(100), min_height: px(100), ..default() }, Interaction::default(), Outline { width: px(2), offset: px(2), color: Color::NONE, }, )); }); }); } }); } fn update_outlines(mut outlines_query: Query<(&mut Outline, Ref<Interaction>)>) { for (mut outline, interaction) in outlines_query.iter_mut() { if interaction.is_changed() { outline.color = match *interaction { Interaction::Pressed => RED.into(), Interaction::Hovered => WHITE.into(), Interaction::None => Color::NONE, }; } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/flex_layout.rs
examples/ui/flex_layout.rs
//! Demonstrates how the `AlignItems` and `JustifyContent` properties can be composed to layout text. use bevy::prelude::*; const ALIGN_ITEMS_COLOR: Color = Color::srgb(1., 0.066, 0.349); const JUSTIFY_CONTENT_COLOR: Color = Color::srgb(0.102, 0.522, 1.); const MARGIN: Val = Val::Px(12.); fn main() { App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "Bevy Flex Layout Example".to_string(), ..Default::default() }), ..Default::default() })) .add_systems(Startup, spawn_layout) .run(); } fn spawn_layout(mut commands: Commands, asset_server: Res<AssetServer>) { let font = asset_server.load("fonts/FiraSans-Bold.ttf"); commands.spawn(Camera2d); commands .spawn(( Node { // fill the entire window width: percent(100), height: percent(100), flex_direction: FlexDirection::Column, align_items: AlignItems::Center, padding: UiRect::all(MARGIN), row_gap: MARGIN, ..Default::default() }, BackgroundColor(Color::BLACK), )) .with_children(|builder| { // spawn the key builder .spawn(Node { flex_direction: FlexDirection::Row, ..default() }) .with_children(|builder| { spawn_nested_text_bundle( builder, font.clone(), ALIGN_ITEMS_COLOR, UiRect::right(MARGIN), "AlignItems", ); spawn_nested_text_bundle( builder, font.clone(), JUSTIFY_CONTENT_COLOR, UiRect::default(), "JustifyContent", ); }); builder .spawn(Node { width: percent(100), height: percent(100), flex_direction: FlexDirection::Column, row_gap: MARGIN, ..default() }) .with_children(|builder| { // spawn one child node for each combination of `AlignItems` and `JustifyContent` let justifications = [ JustifyContent::FlexStart, JustifyContent::Center, JustifyContent::FlexEnd, JustifyContent::SpaceEvenly, JustifyContent::SpaceAround, JustifyContent::SpaceBetween, ]; let alignments = [ AlignItems::Baseline, AlignItems::FlexStart, AlignItems::Center, AlignItems::FlexEnd, AlignItems::Stretch, ]; for align_items in alignments { builder .spawn(Node { width: percent(100), height: percent(100), flex_direction: FlexDirection::Row, column_gap: MARGIN, ..Default::default() }) .with_children(|builder| { for justify_content in justifications { spawn_child_node( builder, font.clone(), align_items, justify_content, ); } }); } }); }); } fn spawn_child_node( builder: &mut ChildSpawnerCommands, font: Handle<Font>, align_items: AlignItems, justify_content: JustifyContent, ) { builder .spawn(( Node { flex_direction: FlexDirection::Column, align_items, justify_content, width: percent(100), height: percent(100), ..default() }, BackgroundColor(Color::srgb(0.25, 0.25, 0.25)), )) .with_children(|builder| { let labels = [ (format!("{align_items:?}"), ALIGN_ITEMS_COLOR, 0.), (format!("{justify_content:?}"), JUSTIFY_CONTENT_COLOR, 3.), ]; for (text, color, top_margin) in labels { // We nest the text within a parent node because margins and padding can't be directly applied to text nodes currently. spawn_nested_text_bundle( builder, font.clone(), color, UiRect::top(px(top_margin)), &text, ); } }); } fn spawn_nested_text_bundle( builder: &mut ChildSpawnerCommands, font: Handle<Font>, background_color: Color, margin: UiRect, text: &str, ) { builder .spawn(( Node { margin, padding: UiRect::axes(px(5), px(1)), ..default() }, BackgroundColor(background_color), )) .with_children(|builder| { builder.spawn((Text::new(text), TextFont::from(font), TextColor::BLACK)); }); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/anchor_layout.rs
examples/ui/anchor_layout.rs
//! Shows an "anchor layout" style of ui layout use bevy::prelude::*; const MARGIN: Val = Val::Px(12.); fn main() { App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "Bevy Anchor Layout Example".to_string(), ..default() }), ..default() })) .add_systems(Startup, spawn_layout) .run(); } fn spawn_layout(mut commands: Commands, asset_server: Res<AssetServer>) { let font = asset_server.load("fonts/FiraSans-Bold.ttf"); commands.spawn(Camera2d); let rows = [ ( "left: 10px\ntop: 10px", Node { left: px(10), top: px(10), ..default() }, ), ( "center: 10px\ntop: 10px", Node { margin: auto().horizontal(), top: px(10), ..default() }, ), ( "right: 10px\ntop: 10px", Node { right: px(10), top: px(10), ..default() }, ), ( "left: 10px\ncenter: 10px", Node { left: px(10), margin: UiRect::vertical(Val::Auto), ..default() }, ), ( "center: 10px\ncenter: 10px", Node { margin: UiRect::all(Val::Auto), ..default() }, ), ( "right: 10px\ncenter: 10px", Node { right: px(10), margin: UiRect::vertical(Val::Auto), ..default() }, ), ( "left: 10px\nbottom: 10px", Node { left: px(10), bottom: px(10), ..default() }, ), ( "center: 10px\nbottom: 10px", Node { margin: UiRect::horizontal(Val::Auto), bottom: px(10), ..default() }, ), ( "right: 10px\nbottom: 10px", Node { right: px(10), bottom: px(10), ..default() }, ), ]; // let font = font.clone(); commands.spawn(( Node { // fill the entire window width: percent(100), height: percent(100), padding: MARGIN.all(), row_gap: MARGIN, column_gap: MARGIN, display: Display::Grid, grid_template_columns: RepeatedGridTrack::fr(3, 1.), grid_template_rows: RepeatedGridTrack::fr(3, 1.), ..default() }, BackgroundColor(Color::BLACK), Children::spawn(SpawnIter( rows.into_iter() .map(move |v| anchored_node(font.clone(), v.1, v.0)), )), )); } fn anchored_node(font: Handle<Font>, node: Node, label: &str) -> impl Bundle { ( // outer gray box Node { grid_column: GridPlacement::span(1), grid_row: GridPlacement::span(1), ..default() }, BackgroundColor(Color::srgb(0.25, 0.25, 0.25)), children![ // inner label box ( Node { display: Display::Block, padding: UiRect::axes(px(5), px(1)), position_type: PositionType::Absolute, ..node }, BackgroundColor(Color::srgb(1., 0.066, 0.349)), children![(Text::new(label), TextFont::from(font), TextColor::BLACK,)], ) ], ) }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/drag_to_scroll.rs
examples/ui/drag_to_scroll.rs
//! This example tests scale factor, dragging and scrolling use bevy::color::palettes::css::RED; use bevy::prelude::*; #[derive(Component)] struct ScrollableNode; #[derive(Component)] struct TileColor(Color); fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .run(); } #[derive(Component)] struct ScrollStart(Vec2); fn setup(mut commands: Commands) { let w = 60; let h = 40; commands.spawn(Camera2d); commands.insert_resource(UiScale(0.5)); commands .spawn(( Node { width: percent(100), height: percent(100), overflow: Overflow::scroll(), ..Default::default() }, ScrollPosition(Vec2::ZERO), ScrollableNode, ScrollStart(Vec2::ZERO), )) .observe( |drag: On<Pointer<Drag>>, ui_scale: Res<UiScale>, mut scroll_position_query: Query< (&mut ScrollPosition, &ScrollStart), With<ScrollableNode>, >| { if let Ok((mut scroll_position, start)) = scroll_position_query.single_mut() { scroll_position.0 = (start.0 - drag.distance / ui_scale.0).max(Vec2::ZERO); } }, ) .observe( |_: On<Pointer<DragStart>>, mut scroll_position_query: Query< (&ComputedNode, &mut ScrollStart), With<ScrollableNode>, >| { if let Ok((computed_node, mut start)) = scroll_position_query.single_mut() { start.0 = computed_node.scroll_position * computed_node.inverse_scale_factor; } }, ) .with_children(|commands| { commands .spawn(( Node { display: Display::Grid, grid_template_rows: RepeatedGridTrack::px(w as i32, 100.), grid_template_columns: RepeatedGridTrack::px(h as i32, 100.), ..default() }, Pickable { is_hoverable: false, should_block_lower: true, } )) .with_children(|commands| { for y in 0..h { for x in 0..w { let tile_color = if (x + y) % 2 == 1 { let hue = ((x as f32 / w as f32) * 270.0) + ((y as f32 / h as f32) * 90.0); Color::hsl(hue, 1., 0.5) } else { Color::BLACK }; commands.spawn(( Node { grid_row: GridPlacement::start(y + 1), grid_column: GridPlacement::start(x + 1), ..default() }, Pickable { should_block_lower: false, is_hoverable: true, }, TileColor(tile_color), BackgroundColor(tile_color), )) .observe(|over: On<Pointer<Over>>, mut query: Query<&mut BackgroundColor>,| { if let Ok(mut background_color) = query.get_mut(over.entity) { background_color.0 = RED.into(); } }) .observe(|out: On<Pointer<Out>>, mut query: Query<(&mut BackgroundColor, &TileColor)>| { if let Ok((mut background_color, tile_color)) = query.get_mut(out.entity) { background_color.0 = tile_color.0; } }); } } }); }); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/render_ui_to_texture.rs
examples/ui/render_ui_to_texture.rs
//! Shows how to render UI to a texture. Useful for displaying UI in 3D space. use std::f32::consts::PI; use bevy::picking::PickingSystems; use bevy::{ asset::{uuid::Uuid, RenderAssetUsages}, camera::RenderTarget, color::palettes::css::{BLUE, GRAY, RED}, input::ButtonState, picking::{ backend::ray::RayMap, pointer::{Location, PointerAction, PointerId, PointerInput}, }, prelude::*, render::render_resource::{Extent3d, TextureDimension, TextureFormat, TextureUsages}, window::{PrimaryWindow, WindowEvent}, }; const CUBE_POINTER_ID: PointerId = PointerId::Custom(Uuid::from_u128(90870987)); fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, rotator_system) .add_systems(First, drive_diegetic_pointer.in_set(PickingSystems::Input)) .run(); } // Marks the cube, to which the UI texture is applied. #[derive(Component)] struct Cube; fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, mut images: ResMut<Assets<Image>>, ) { let size = Extent3d { width: 512, height: 512, ..default() }; // This is the texture that will be rendered to. let mut image = Image::new_fill( size, TextureDimension::D2, &[0, 0, 0, 0], TextureFormat::Bgra8UnormSrgb, RenderAssetUsages::default(), ); // You need to set these texture usage flags in order to use the image as a render target image.texture_descriptor.usage = TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_DST | TextureUsages::RENDER_ATTACHMENT; let image_handle = images.add(image); // Light commands.spawn(DirectionalLight::default()); let texture_camera = commands .spawn(( Camera2d, Camera { // render before the "main pass" camera order: -1, ..default() }, RenderTarget::Image(image_handle.clone().into()), )) .id(); commands .spawn(( Node { // Cover the whole image width: percent(100), height: percent(100), flex_direction: FlexDirection::Column, justify_content: JustifyContent::Center, align_items: AlignItems::Center, ..default() }, BackgroundColor(GRAY.into()), UiTargetCamera(texture_camera), )) .with_children(|parent| { parent .spawn(( Node { position_type: PositionType::Absolute, width: Val::Auto, height: Val::Auto, align_items: AlignItems::Center, padding: UiRect::all(Val::Px(20.)), border_radius: BorderRadius::all(Val::Px(10.)), ..default() }, BackgroundColor(BLUE.into()), )) .observe( |drag: On<Pointer<Drag>>, mut nodes: Query<(&mut Node, &ComputedNode)>| { let (mut node, computed) = nodes.get_mut(drag.entity).unwrap(); node.left = Val::Px(drag.pointer_location.position.x - computed.size.x / 2.0); node.top = Val::Px(drag.pointer_location.position.y - 50.0); }, ) .observe( |over: On<Pointer<Over>>, mut colors: Query<&mut BackgroundColor>| { colors.get_mut(over.entity).unwrap().0 = RED.into(); }, ) .observe( |out: On<Pointer<Out>>, mut colors: Query<&mut BackgroundColor>| { colors.get_mut(out.entity).unwrap().0 = BLUE.into(); }, ) .with_children(|parent| { parent.spawn(( Text::new("Drag Me!"), TextFont { font_size: 40.0, ..default() }, TextColor::WHITE, )); }); }); let mesh_handle = meshes.add(Cuboid::default()); // This material has the texture that has been rendered. let material_handle = materials.add(StandardMaterial { base_color_texture: Some(image_handle), reflectance: 0.02, unlit: false, ..default() }); // Cube with material containing the rendered UI texture. commands.spawn(( Mesh3d(mesh_handle), MeshMaterial3d(material_handle), Transform::from_xyz(0.0, 0.0, 1.5).with_rotation(Quat::from_rotation_x(PI)), Cube, )); // The main pass camera. commands.spawn(( Camera3d::default(), Transform::from_xyz(0.0, 0.0, 5.0).looking_at(Vec3::ZERO, Vec3::Y), )); commands.spawn(CUBE_POINTER_ID); } const ROTATION_SPEED: f32 = 0.1; fn rotator_system(time: Res<Time>, mut query: Query<&mut Transform, With<Cube>>) { for mut transform in &mut query { transform.rotate_x(1.0 * time.delta_secs() * ROTATION_SPEED); transform.rotate_y(0.7 * time.delta_secs() * ROTATION_SPEED); } } /// Because bevy has no way to know how to map a mouse input to the UI texture, we need to write a /// system that tells it there is a pointer on the UI texture. We cast a ray into the scene and find /// the UV (2D texture) coordinates of the raycast hit. This UV coordinate is effectively the same /// as a pointer coordinate on a 2D UI rect. fn drive_diegetic_pointer( mut cursor_last: Local<Vec2>, mut raycast: MeshRayCast, rays: Res<RayMap>, cubes: Query<&Mesh3d, With<Cube>>, ui_camera: Query<&RenderTarget, With<Camera2d>>, primary_window: Query<Entity, With<PrimaryWindow>>, windows: Query<(Entity, &Window)>, images: Res<Assets<Image>>, manual_texture_views: Res<ManualTextureViews>, mut window_events: MessageReader<WindowEvent>, mut pointer_inputs: MessageWriter<PointerInput>, ) -> Result { // Get the size of the texture, so we can convert from dimensionless UV coordinates that span // from 0 to 1, to pixel coordinates. let target = ui_camera .single()? .normalize(primary_window.single().ok()) .unwrap(); let target_info = target .get_render_target_info(windows, &images, &manual_texture_views) .unwrap(); let size = target_info.physical_size.as_vec2(); // Find raycast hits and update the virtual pointer. let raycast_settings = MeshRayCastSettings { visibility: RayCastVisibility::VisibleInView, filter: &|entity| cubes.contains(entity), early_exit_test: &|_| false, }; for (_id, ray) in rays.iter() { for (_cube, hit) in raycast.cast_ray(*ray, &raycast_settings) { let position = size * hit.uv.unwrap(); if position != *cursor_last { pointer_inputs.write(PointerInput::new( CUBE_POINTER_ID, Location { target: target.clone(), position, }, PointerAction::Move { delta: position - *cursor_last, }, )); *cursor_last = position; } } } // Pipe pointer button presses to the virtual pointer on the UI texture. for window_event in window_events.read() { if let WindowEvent::MouseButtonInput(input) = window_event { let button = match input.button { MouseButton::Left => PointerButton::Primary, MouseButton::Right => PointerButton::Secondary, MouseButton::Middle => PointerButton::Middle, _ => continue, }; let action = match input.state { ButtonState::Pressed => PointerAction::Press(button), ButtonState::Released => PointerAction::Release(button), }; pointer_inputs.write(PointerInput::new( CUBE_POINTER_ID, Location { target: target.clone(), position: *cursor_last, }, action, )); } } Ok(()) }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/font_query.rs
examples/ui/font_query.rs
//! This example demonstrates how to use font weights, widths and styles. use bevy::prelude::*; use bevy::text::FontSource; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .run(); } fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { let family = FontSource::from(asset_server.load("fonts/MonaSans-VariableFont.ttf")); commands.spawn(Camera2d); commands.spawn(( Node { flex_direction: FlexDirection::Column, align_self: AlignSelf::Center, justify_self: JustifySelf::Center, align_items: AlignItems::Center, padding: px(16.).all(), row_gap: px(16.), ..default() }, children![ ( Text::new("Font Weights, Widths & Styles"), TextFont { font: family.clone(), font_size: 32.0, ..default() }, Underline, ), ( // Two columns side-by-side Node { flex_direction: FlexDirection::Row, column_gap: px(32.), ..default() }, children![ ( // Left column: Weights Node { flex_direction: FlexDirection::Column, padding: px(8.).all(), row_gap: px(8.), ..default() }, children![ ( Text::new("Weight 100 (Thin)"), TextFont { font: family.clone(), weight: FontWeight::THIN, ..default() }, ), ( Text::new("Weight 200 (Extra Light)"), TextFont { font: family.clone(), weight: FontWeight::EXTRA_LIGHT, ..default() }, ), ( Text::new("Weight 300 (Light)"), TextFont { font: family.clone(), weight: FontWeight::LIGHT, ..default() }, ), ( Text::new("Weight 400 (Normal)"), TextFont { font: family.clone(), weight: FontWeight::NORMAL, ..default() }, ), ( Text::new("Weight 500 (Medium)"), TextFont { font: family.clone(), weight: FontWeight::MEDIUM, ..default() }, ), ( Text::new("Weight 600 (Semibold)"), TextFont { font: family.clone(), weight: FontWeight::SEMIBOLD, ..default() }, ), ( Text::new("Weight 700 (Bold)"), TextFont { font: family.clone(), weight: FontWeight::BOLD, ..default() }, ), ( Text::new("Weight 800 (Extra Bold)"), TextFont { font: family.clone(), weight: FontWeight::EXTRA_BOLD, ..default() }, ), ( Text::new("Weight 900 (Black)"), TextFont { font: family.clone(), weight: FontWeight::BLACK, ..default() }, ), ] ), ( // Right column: Widths Node { flex_direction: FlexDirection::Column, padding: px(8.).all(), row_gap: px(8.), ..default() }, children![ ( Text::new("FontWidth::ULTRA_CONDENSED"), TextFont { font: family.clone(), width: FontWidth::ULTRA_CONDENSED, ..default() }, ), ( Text::new("FontWidth::EXTRA_CONDENSED"), TextFont { font: family.clone(), width: FontWidth::EXTRA_CONDENSED, ..default() }, ), ( Text::new("FontWidth::CONDENSED"), TextFont { font: family.clone(), width: FontWidth::CONDENSED, ..default() }, ), ( Text::new("FontWidth::SEMI_CONDENSED"), TextFont { font: family.clone(), width: FontWidth::SEMI_CONDENSED, ..default() }, ), ( Text::new("FontWidth::NORMAL"), TextFont { font: family.clone(), width: FontWidth::NORMAL, ..default() }, ), ( Text::new("FontWidth::SEMI_EXPANDED"), TextFont { font: family.clone(), width: FontWidth::SEMI_EXPANDED, ..default() }, ), ( Text::new("FontWidth::EXPANDED"), TextFont { font: family.clone(), width: FontWidth::EXPANDED, ..default() }, ), ( Text::new("FontWidth::EXTRA_EXPANDED"), TextFont { font: family.clone(), width: FontWidth::EXTRA_EXPANDED, ..default() }, ), ( Text::new("FontWidth::ULTRA_EXPANDED"), TextFont { font: family.clone(), width: FontWidth::ULTRA_EXPANDED, ..default() }, ), ], ), ( // Right column: Style Node { flex_direction: FlexDirection::Column, padding: px(8.).all(), row_gap: px(8.), ..default() }, children![ ( Text::new("FontStyle::Normal"), TextFont { font: family.clone(), style: FontStyle::Normal, ..default() }, ), ( Text::new("FontStyle::Oblique"), TextFont { font: family.clone(), style: FontStyle::Oblique, ..default() }, ), ( Text::new("FontStyle::Italic"), TextFont { font: family.clone(), style: FontStyle::Italic, ..default() }, ), ] ), ] ), ], )); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/box_shadow.rs
examples/ui/box_shadow.rs
//! This example shows how to create a node with a shadow and adjust its settings interactively. use bevy::{color::palettes::css::*, prelude::*, time::Time, window::RequestRedraw}; const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15); const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25); const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35); const SHAPE_DEFAULT_SETTINGS: ShapeSettings = ShapeSettings { index: 0 }; const SHADOW_DEFAULT_SETTINGS: ShadowSettings = ShadowSettings { x_offset: 20.0, y_offset: 20.0, blur: 10.0, spread: 15.0, count: 1, samples: 6, }; const SHAPES: &[(&str, fn(&mut Node))] = &[ ("1", |node| { node.width = px(164); node.height = px(164); node.border_radius = BorderRadius::ZERO; }), ("2", |node| { node.width = px(164); node.height = px(164); node.border_radius = BorderRadius::all(px(41)); }), ("3", |node| { node.width = px(164); node.height = px(164); node.border_radius = BorderRadius::MAX; }), ("4", |node| { node.width = px(240); node.height = px(80); node.border_radius = BorderRadius::all(px(32)); }), ("5", |node| { node.width = px(80); node.height = px(240); node.border_radius = BorderRadius::all(px(32)); }), ]; #[derive(Resource, Default)] struct ShapeSettings { index: usize, } #[derive(Resource, Default)] struct ShadowSettings { x_offset: f32, y_offset: f32, blur: f32, spread: f32, count: usize, samples: u32, } #[derive(Component)] struct ShadowNode; #[derive(Component, PartialEq, Clone, Copy)] enum SettingsButton { XOffsetInc, XOffsetDec, YOffsetInc, YOffsetDec, BlurInc, BlurDec, SpreadInc, SpreadDec, CountInc, CountDec, ShapePrev, ShapeNext, Reset, SamplesInc, SamplesDec, } #[derive(Component, Clone, Copy, PartialEq, Eq, Debug)] enum SettingType { XOffset, YOffset, Blur, Spread, Count, Shape, Samples, } impl SettingType { fn label(&self) -> &str { match self { SettingType::XOffset => "X Offset", SettingType::YOffset => "Y Offset", SettingType::Blur => "Blur", SettingType::Spread => "Spread", SettingType::Count => "Count", SettingType::Shape => "Shape", SettingType::Samples => "Samples", } } } #[derive(Resource, Default)] struct HeldButton { button: Option<SettingsButton>, pressed_at: Option<f64>, last_repeat: Option<f64>, } fn main() { App::new() .add_plugins(DefaultPlugins) .insert_resource(SHADOW_DEFAULT_SETTINGS) .insert_resource(SHAPE_DEFAULT_SETTINGS) .insert_resource(HeldButton::default()) .add_systems(Startup, setup) .add_systems( Update, ( button_system, button_color_system, update_shape.run_if(resource_changed::<ShapeSettings>), update_shadow.run_if(resource_changed::<ShadowSettings>), update_shadow_samples.run_if(resource_changed::<ShadowSettings>), button_repeat_system, ), ) .run(); } // --- UI Setup --- fn setup( mut commands: Commands, asset_server: Res<AssetServer>, shadow: Res<ShadowSettings>, shape: Res<ShapeSettings>, ) { commands.spawn((Camera2d, BoxShadowSamples(shadow.samples))); // Spawn shape node commands .spawn(( Node { width: percent(100), height: percent(100), align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..default() }, BackgroundColor(GRAY.into()), )) .insert(children![{ let mut node = Node { width: px(164), height: px(164), border: UiRect::all(px(1)), align_items: AlignItems::Center, justify_content: JustifyContent::Center, border_radius: BorderRadius::ZERO, ..default() }; SHAPES[shape.index % SHAPES.len()].1(&mut node); ( node, BorderColor::all(WHITE), BackgroundColor(Color::srgb(0.21, 0.21, 0.21)), BoxShadow(vec![ShadowStyle { color: Color::BLACK.with_alpha(0.8), x_offset: px(shadow.x_offset), y_offset: px(shadow.y_offset), spread_radius: px(shadow.spread), blur_radius: px(shadow.blur), }]), ShadowNode, ) }]); // Settings Panel commands .spawn(( Node { flex_direction: FlexDirection::Column, position_type: PositionType::Absolute, left: px(24), bottom: px(24), width: px(270), padding: UiRect::all(px(16)), border_radius: BorderRadius::all(px(12)), ..default() }, BackgroundColor(Color::srgb(0.12, 0.12, 0.12).with_alpha(0.85)), BorderColor::all(Color::WHITE.with_alpha(0.15)), ZIndex(10), )) .insert(children![ build_setting_row( SettingType::Shape, SettingsButton::ShapePrev, SettingsButton::ShapeNext, shape.index as f32, &asset_server, ), build_setting_row( SettingType::XOffset, SettingsButton::XOffsetDec, SettingsButton::XOffsetInc, shadow.x_offset, &asset_server, ), build_setting_row( SettingType::YOffset, SettingsButton::YOffsetDec, SettingsButton::YOffsetInc, shadow.y_offset, &asset_server, ), build_setting_row( SettingType::Blur, SettingsButton::BlurDec, SettingsButton::BlurInc, shadow.blur, &asset_server, ), build_setting_row( SettingType::Spread, SettingsButton::SpreadDec, SettingsButton::SpreadInc, shadow.spread, &asset_server, ), build_setting_row( SettingType::Count, SettingsButton::CountDec, SettingsButton::CountInc, shadow.count as f32, &asset_server, ), // Add BoxShadowSamples as a setting row build_setting_row( SettingType::Samples, SettingsButton::SamplesDec, SettingsButton::SamplesInc, shadow.samples as f32, &asset_server, ), // Reset button ( Node { flex_direction: FlexDirection::Row, align_items: AlignItems::Center, height: px(36), margin: UiRect::top(px(12)), ..default() }, children![( Button, Node { width: px(90), height: px(32), justify_content: JustifyContent::Center, align_items: AlignItems::Center, border_radius: BorderRadius::all(px(8)), ..default() }, BackgroundColor(NORMAL_BUTTON), SettingsButton::Reset, children![( Text::new("Reset"), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), font_size: 16.0, ..default() }, )], )], ), ]); } // --- UI Helper Functions --- // Helper to return an input to the children! macro for a setting row fn build_setting_row( setting_type: SettingType, dec: SettingsButton, inc: SettingsButton, value: f32, asset_server: &Res<AssetServer>, ) -> impl Bundle { let value_text = match setting_type { SettingType::Shape => SHAPES[value as usize % SHAPES.len()].0.to_string(), SettingType::Count => format!("{}", value as usize), _ => format!("{value:.1}"), }; ( Node { flex_direction: FlexDirection::Row, align_items: AlignItems::Center, height: px(32), ..default() }, children![ ( Node { width: px(80), justify_content: JustifyContent::FlexEnd, align_items: AlignItems::Center, ..default() }, // Attach SettingType to the value label node, not the parent row children![( Text::new(setting_type.label()), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), font_size: 16.0, ..default() }, )], ), ( Button, Node { width: px(28), height: px(28), margin: UiRect::left(px(8)), justify_content: JustifyContent::Center, align_items: AlignItems::Center, border_radius: BorderRadius::all(px(6)), ..default() }, BackgroundColor(Color::WHITE), dec, children![( Text::new(if setting_type == SettingType::Shape { "<" } else { "-" }), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), font_size: 18.0, ..default() }, )], ), ( Node { width: px(48), height: px(28), margin: UiRect::horizontal(px(8)), justify_content: JustifyContent::Center, align_items: AlignItems::Center, border_radius: BorderRadius::all(px(6)), ..default() }, children![{ ( Text::new(value_text), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), font_size: 16.0, ..default() }, setting_type, ) }], ), ( Button, Node { width: px(28), height: px(28), justify_content: JustifyContent::Center, align_items: AlignItems::Center, border_radius: BorderRadius::all(px(6)), ..default() }, BackgroundColor(Color::WHITE), inc, children![( Text::new(if setting_type == SettingType::Shape { ">" } else { "+" }), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), font_size: 18.0, ..default() }, )], ), ], ) } // --- SYSTEMS --- // Update the shadow node's BoxShadow on resource changes fn update_shadow( shadow: Res<ShadowSettings>, mut query: Query<&mut BoxShadow, With<ShadowNode>>, mut label_query: Query<(&mut Text, &SettingType)>, ) { for mut box_shadow in &mut query { *box_shadow = BoxShadow(generate_shadows(&shadow)); } // Update value labels for shadow settings for (mut text, setting) in &mut label_query { let value = match setting { SettingType::XOffset => format!("{:.1}", shadow.x_offset), SettingType::YOffset => format!("{:.1}", shadow.y_offset), SettingType::Blur => format!("{:.1}", shadow.blur), SettingType::Spread => format!("{:.1}", shadow.spread), SettingType::Count => format!("{}", shadow.count), SettingType::Shape => continue, SettingType::Samples => format!("{}", shadow.samples), }; *text = Text::new(value); } } fn update_shadow_samples( shadow: Res<ShadowSettings>, mut query: Query<&mut BoxShadowSamples, With<Camera2d>>, ) { for mut samples in &mut query { samples.0 = shadow.samples; } } fn generate_shadows(shadow: &ShadowSettings) -> Vec<ShadowStyle> { match shadow.count { 1 => vec![make_shadow( BLACK.into(), shadow.x_offset, shadow.y_offset, shadow.spread, shadow.blur, )], 2 => vec![ make_shadow( BLUE.into(), shadow.x_offset, shadow.y_offset, shadow.spread, shadow.blur, ), make_shadow( YELLOW.into(), -shadow.x_offset, -shadow.y_offset, shadow.spread, shadow.blur, ), ], 3 => vec![ make_shadow( BLUE.into(), shadow.x_offset, shadow.y_offset, shadow.spread, shadow.blur, ), make_shadow( YELLOW.into(), -shadow.x_offset, -shadow.y_offset, shadow.spread, shadow.blur, ), make_shadow( RED.into(), shadow.y_offset, -shadow.x_offset, shadow.spread, shadow.blur, ), ], _ => vec![], } } fn make_shadow(color: Color, x_offset: f32, y_offset: f32, spread: f32, blur: f32) -> ShadowStyle { ShadowStyle { color: color.with_alpha(0.8), x_offset: px(x_offset), y_offset: px(y_offset), spread_radius: px(spread), blur_radius: px(blur), } } // Update shape of ShadowNode if shape selection changed fn update_shape( shape: Res<ShapeSettings>, mut query: Query<&mut Node, With<ShadowNode>>, mut label_query: Query<(&mut Text, &SettingType)>, ) { for mut node in &mut query { SHAPES[shape.index % SHAPES.len()].1(&mut node); } for (mut text, kind) in &mut label_query { if *kind == SettingType::Shape { *text = Text::new(SHAPES[shape.index % SHAPES.len()].0); } } } // Handles button interactions for all settings fn button_system( mut interaction_query: Query< (&Interaction, &SettingsButton), (Changed<Interaction>, With<Button>), >, mut shadow: ResMut<ShadowSettings>, mut shape: ResMut<ShapeSettings>, mut held: ResMut<HeldButton>, time: Res<Time>, ) { let now = time.elapsed_secs_f64(); for (interaction, btn) in &mut interaction_query { match *interaction { Interaction::Pressed => { trigger_button_action(btn, &mut shadow, &mut shape); held.button = Some(*btn); held.pressed_at = Some(now); held.last_repeat = Some(now); } Interaction::None | Interaction::Hovered => { if held.button == Some(*btn) { held.button = None; held.pressed_at = None; held.last_repeat = None; } } } } } fn trigger_button_action( btn: &SettingsButton, shadow: &mut ShadowSettings, shape: &mut ShapeSettings, ) { match btn { SettingsButton::XOffsetInc => shadow.x_offset += 1.0, SettingsButton::XOffsetDec => shadow.x_offset -= 1.0, SettingsButton::YOffsetInc => shadow.y_offset += 1.0, SettingsButton::YOffsetDec => shadow.y_offset -= 1.0, SettingsButton::BlurInc => shadow.blur = (shadow.blur + 1.0).max(0.0), SettingsButton::BlurDec => shadow.blur = (shadow.blur - 1.0).max(0.0), SettingsButton::SpreadInc => shadow.spread += 1.0, SettingsButton::SpreadDec => shadow.spread -= 1.0, SettingsButton::CountInc => { if shadow.count < 3 { shadow.count += 1; } } SettingsButton::CountDec => { if shadow.count > 1 { shadow.count -= 1; } } SettingsButton::ShapePrev => { if shape.index == 0 { shape.index = SHAPES.len() - 1; } else { shape.index -= 1; } } SettingsButton::ShapeNext => { shape.index = (shape.index + 1) % SHAPES.len(); } SettingsButton::Reset => { *shape = SHAPE_DEFAULT_SETTINGS; *shadow = SHADOW_DEFAULT_SETTINGS; } SettingsButton::SamplesInc => shadow.samples += 1, SettingsButton::SamplesDec => { if shadow.samples > 1 { shadow.samples -= 1; } } } } // System to repeat button action while held fn button_repeat_system( time: Res<Time>, mut held: ResMut<HeldButton>, mut shadow: ResMut<ShadowSettings>, mut shape: ResMut<ShapeSettings>, mut request_redraw_writer: MessageWriter<RequestRedraw>, ) { if held.button.is_some() { request_redraw_writer.write(RequestRedraw); } const INITIAL_DELAY: f64 = 0.15; const REPEAT_RATE: f64 = 0.08; if let (Some(btn), Some(pressed_at)) = (held.button, held.pressed_at) { let now = time.elapsed_secs_f64(); let since_pressed = now - pressed_at; let last_repeat = held.last_repeat.unwrap_or(pressed_at); let since_last = now - last_repeat; if since_pressed > INITIAL_DELAY && since_last > REPEAT_RATE { trigger_button_action(&btn, &mut shadow, &mut shape); held.last_repeat = Some(now); } } } // Changes color of button on hover and on pressed fn button_color_system( mut query: Query< (&Interaction, &mut BackgroundColor), (Changed<Interaction>, With<Button>, With<SettingsButton>), >, ) { for (interaction, mut color) in &mut query { match *interaction { Interaction::Pressed => *color = PRESSED_BUTTON.into(), Interaction::Hovered => *color = HOVERED_BUTTON.into(), Interaction::None => *color = NORMAL_BUTTON.into(), } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/text.rs
examples/ui/text.rs
//! This example illustrates how to create UI text and update it in a system. //! //! It displays the current FPS in the top left corner, as well as text that changes color //! in the bottom right. For text within a scene, please see the text2d example. use bevy::{ color::palettes::css::GOLD, diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin}, prelude::*, text::{CosmicFontSystem, FontFeatureTag, FontFeatures, Underline}, }; fn main() { let mut app = App::new(); app.add_plugins((DefaultPlugins, FrameTimeDiagnosticsPlugin::default())) .add_systems(Startup, setup) .add_systems(Update, (text_update_system, text_color_system)); let mut f = app.world_mut().resource_mut::<CosmicFontSystem>(); f.db_mut().load_system_fonts(); app.run(); } // Marker struct to help identify the FPS UI component, since there may be many Text components #[derive(Component)] struct FpsText; // Marker struct to help identify the color-changing Text component #[derive(Component)] struct AnimatedText; fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { // UI camera commands.spawn(Camera2d); // Text with one section commands.spawn(( // Accepts a `String` or any type that converts into a `String`, such as `&str` Text::new("hello\nbevy!"), Underline, TextFont { // This font is loaded and will be used instead of the default font. font: "Comic Sans MS".into(), font_size: 67.0, ..default() }, Strikethrough, TextShadow::default(), // Set the justification of the Text TextLayout::new_with_justify(Justify::Center), // Set the style of the Node itself. Node { position_type: PositionType::Absolute, bottom: px(5), right: px(5), ..default() }, AnimatedText, )); // Text with multiple sections commands .spawn(( // Create a Text with multiple child spans. Text::new("FPS: "), TextFont { // This font is loaded and will be used instead of the default font. font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), font_size: 42.0, ..default() }, )) .with_child(( TextSpan::default(), ( TextFont { // If the "default_font" feature is unavailable, load a font to use instead. #[cfg(not(feature = "default_font"))] font: asset_server.load("fonts/FiraMono-Medium.ttf").into(), font_size: 33.0, ..Default::default() }, TextColor(GOLD.into()), ), FpsText, )); // Text with OpenType features let opentype_font_handle: FontSource = asset_server.load("fonts/EBGaramond12-Regular.otf").into(); commands .spawn(( Node { margin: UiRect::all(Val::Px(12.0)), position_type: PositionType::Absolute, top: Val::Px(5.0), right: Val::Px(5.0), ..default() }, Text::new("Opentype features:\n"), TextFont { font: opentype_font_handle.clone(), font_size: 32.0, ..default() }, )) .with_children(|parent| { let text_rows = [ ("Smallcaps: ", FontFeatureTag::SMALL_CAPS, "Hello World"), ( "Ligatures: ", FontFeatureTag::STANDARD_LIGATURES, "fi fl ff ffi ffl", ), ("Fractions: ", FontFeatureTag::FRACTIONS, "12/134"), ("Superscript: ", FontFeatureTag::SUPERSCRIPT, "Up here!"), ("Subscript: ", FontFeatureTag::SUBSCRIPT, "Down here!"), ( "Oldstyle figures: ", FontFeatureTag::OLDSTYLE_FIGURES, "1234567890", ), ( "Lining figures: ", FontFeatureTag::LINING_FIGURES, "1234567890", ), ]; for (title, feature, text) in text_rows { parent.spawn(( TextSpan::new(title), TextFont { font: opentype_font_handle.clone(), font_size: 24.0, ..default() }, )); parent.spawn(( TextSpan::new(format!("{text}\n")), TextFont { font: opentype_font_handle.clone(), font_size: 24.0, font_features: FontFeatures::builder().enable(feature).build(), ..default() }, )); } }); #[cfg(feature = "default_font")] commands.spawn(( // Here we are able to call the `From` method instead of creating a new `TextSection`. // This will use the default font (a minimal subset of FiraMono) and apply the default styling. Text::new("From an &str into a Text with the default font!"), Node { position_type: PositionType::Absolute, bottom: px(5), left: px(15), ..default() }, )); #[cfg(not(feature = "default_font"))] commands.spawn(( Text::new("Default font disabled"), TextFont { font: asset_server.load("fonts/FiraMono-Medium.ttf"), ..default() }, Node { position_type: PositionType::Absolute, bottom: px(5), left: px(15), ..default() }, )); } fn text_color_system(time: Res<Time>, mut query: Query<&mut TextColor, With<AnimatedText>>) { for mut text_color in &mut query { let seconds = time.elapsed_secs(); // Update the color of the ColorText span. text_color.0 = Color::srgb( ops::sin(1.25 * seconds) / 2.0 + 0.5, ops::sin(0.75 * seconds) / 2.0 + 0.5, ops::sin(0.50 * seconds) / 2.0 + 0.5, ); } } fn text_update_system( diagnostics: Res<DiagnosticsStore>, mut query: Query<&mut TextSpan, With<FpsText>>, ) { for mut span in &mut query { if let Some(fps) = diagnostics.get(&FrameTimeDiagnosticsPlugin::FPS) && let Some(value) = fps.smoothed() { // Update the value of the second section **span = format!("{value:.2}"); } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/window_fallthrough.rs
examples/ui/window_fallthrough.rs
//! This example illustrates how have a mouse's clicks/wheel/movement etc fall through the spawned transparent window to a window below. //! If you build this, and hit 'P' it should toggle on/off the mouse's passthrough. //! Note: this example will not work on following platforms: iOS / Android / Web / X11. Window fall through is not supported there. use bevy::{prelude::*, window::CursorOptions}; fn main() { App::new() .insert_resource(ClearColor(Color::NONE)) // Use a transparent window, to make effects obvious. .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { // Set the window's parameters, note we're setting the window to always be on top. transparent: true, decorations: true, window_level: bevy::window::WindowLevel::AlwaysOnTop, ..default() }), ..default() })) .add_systems(Startup, setup) .add_systems(Update, toggle_mouse_passthrough) // This allows us to hit 'P' to toggle on/off the mouse's passthrough .run(); } fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { // UI camera commands.spawn(Camera2d); // Text with one span commands.spawn(( // Accepts a `String` or any type that converts into a `String`, such as `&str` Text::new("Hit 'P' then scroll/click around!"), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf").into(), font_size: 83.0, // Nice and big so you can see it! ..default() }, // Set the style of the TextBundle itself. Node { position_type: PositionType::Absolute, bottom: px(5), right: px(10), ..default() }, )); } // A simple system to handle some keyboard input and toggle on/off the hit test. fn toggle_mouse_passthrough( keyboard_input: Res<ButtonInput<KeyCode>>, mut cursor_options: Single<&mut CursorOptions>, ) { if keyboard_input.just_pressed(KeyCode::KeyP) { cursor_options.hit_test = !cursor_options.hit_test; } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/font_atlas_debug.rs
examples/ui/font_atlas_debug.rs
//! This example illustrates how `FontAtlas`'s are populated. //! Bevy uses `FontAtlas`'s under the hood to optimize text rendering. use bevy::{color::palettes::basic::YELLOW, prelude::*, text::FontAtlasSet}; use rand::{Rng, SeedableRng}; use rand_chacha::ChaCha8Rng; fn main() { App::new() .init_resource::<State>() .insert_resource(ClearColor(Color::BLACK)) .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, (text_update_system, atlas_render_system)) .run(); } #[derive(Resource)] struct State { atlas_count: u32, handle: Handle<Font>, timer: Timer, } impl Default for State { fn default() -> Self { Self { atlas_count: 0, handle: Handle::default(), timer: Timer::from_seconds(0.05, TimerMode::Repeating), } } } #[derive(Resource, Deref, DerefMut)] struct SeededRng(ChaCha8Rng); fn atlas_render_system( mut commands: Commands, mut state: ResMut<State>, font_atlas_set: Res<FontAtlasSet>, images: Res<Assets<Image>>, ) { if let Some(font_atlases) = font_atlas_set.values().next() { let x_offset = state.atlas_count as f32; if state.atlas_count == font_atlases.len() as u32 { return; } let font_atlas = &font_atlases[state.atlas_count as usize]; let image = images.get(&font_atlas.texture).unwrap(); state.atlas_count += 1; commands.spawn(( ImageNode::new(font_atlas.texture.clone()), Node { position_type: PositionType::Absolute, top: Val::ZERO, left: px(image.width() as f32 * x_offset), ..default() }, )); } } fn text_update_system( mut state: ResMut<State>, time: Res<Time>, mut query: Query<&mut Text>, mut seeded_rng: ResMut<SeededRng>, ) { if !state.timer.tick(time.delta()).just_finished() { return; } for mut text in &mut query { let c = seeded_rng.random::<u8>() as char; let string = &mut **text; if !string.contains(c) { string.push(c); } } } fn setup(mut commands: Commands, asset_server: Res<AssetServer>, mut state: ResMut<State>) { state.handle = asset_server.load("fonts/FiraSans-Bold.ttf"); let font = FontSource::from(state.handle.clone()); commands.spawn(Camera2d); commands .spawn(( Node { position_type: PositionType::Absolute, bottom: Val::ZERO, ..default() }, BackgroundColor(Color::NONE), )) .with_children(|parent| { parent.spawn(( Text::new("a"), TextFont { font, font_size: 50.0, ..default() }, TextColor(YELLOW.into()), )); }); // We're seeding the PRNG here to make this example deterministic for testing purposes. // This isn't strictly required in practical use unless you need your app to be deterministic. commands.insert_resource(SeededRng(ChaCha8Rng::seed_from_u64(19878367467713))); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/stacked_gradients.rs
examples/ui/stacked_gradients.rs
//! An example demonstrating overlaid gradients use bevy::color::palettes::css::BLUE; use bevy::color::palettes::css::RED; use bevy::color::palettes::css::YELLOW; use bevy::prelude::*; use core::f32::consts::TAU; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .run(); } fn setup(mut commands: Commands) { commands.spawn(Camera2d); commands .spawn(Node { display: Display::Grid, width: percent(100), height: percent(100), ..Default::default() }) .with_children(|commands| { commands.spawn(( Node { width: percent(100), height: percent(100), ..Default::default() }, BackgroundColor(Color::BLACK), BackgroundGradient(vec![ LinearGradient::to_top_right(vec![ ColorStop::auto(RED), ColorStop::auto(RED.with_alpha(0.)), ]) .into(), LinearGradient::to_top_left(vec![ ColorStop::auto(BLUE), ColorStop::auto(BLUE.with_alpha(0.)), ]) .into(), ConicGradient { start: 0., position: UiPosition::CENTER, stops: vec![ AngularColorStop::auto(YELLOW.with_alpha(0.)), AngularColorStop::auto(YELLOW.with_alpha(0.)), AngularColorStop::auto(YELLOW), AngularColorStop::auto(YELLOW.with_alpha(0.)), AngularColorStop::auto(YELLOW.with_alpha(0.)), ], ..Default::default() } .into(), RadialGradient { position: UiPosition::TOP.at_x(percent(5)), shape: RadialGradientShape::Circle(vh(30)), stops: vec![ ColorStop::auto(Color::WHITE), ColorStop::auto(YELLOW), ColorStop::auto(YELLOW.with_alpha(0.1)), ColorStop::auto(YELLOW.with_alpha(0.)), ], ..Default::default() } .into(), LinearGradient { angle: TAU / 16., stops: vec![ ColorStop::auto(Color::BLACK), ColorStop::auto(Color::BLACK.with_alpha(0.)), ], ..Default::default() } .into(), LinearGradient { angle: 15. * TAU / 16., stops: vec![ ColorStop::auto(Color::BLACK), ColorStop::auto(Color::BLACK.with_alpha(0.)), ], ..Default::default() } .into(), ]), )); }); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/grid.rs
examples/ui/grid.rs
//! Demonstrates how CSS Grid layout can be used to lay items out in a 2D grid use bevy::{color::palettes::css::*, prelude::*}; fn main() { App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { resolution: (800, 600).into(), title: "Bevy CSS Grid Layout Example".to_string(), ..default() }), ..default() })) .add_systems(Startup, spawn_layout) .run(); } fn spawn_layout(mut commands: Commands, asset_server: Res<AssetServer>) { let font = asset_server.load("fonts/FiraSans-Bold.ttf"); commands.spawn(Camera2d); // Top-level grid (app frame) commands .spawn(( Node { // Use the CSS Grid algorithm for laying out this node display: Display::Grid, // Make node fill the entirety of its parent (in this case the window) width: percent(100), height: percent(100), // Set the grid to have 2 columns with sizes [min-content, minmax(0, 1fr)] // - The first column will size to the size of its contents // - The second column will take up the remaining available space grid_template_columns: vec![GridTrack::min_content(), GridTrack::flex(1.0)], // Set the grid to have 3 rows with sizes [auto, minmax(0, 1fr), 20px] // - The first row will size to the size of its contents // - The second row take up remaining available space (after rows 1 and 3 have both been sized) // - The third row will be exactly 20px high grid_template_rows: vec![ GridTrack::auto(), GridTrack::flex(1.0), GridTrack::px(20.), ], ..default() }, BackgroundColor(Color::WHITE), )) .with_children(|builder| { // Header builder .spawn( Node { display: Display::Grid, // Make this node span two grid columns so that it takes up the entire top tow grid_column: GridPlacement::span(2), padding: UiRect::all(px(6)), ..default() }, ) .with_children(|builder| { spawn_nested_text_bundle(builder, font.clone(), "Bevy CSS Grid Layout Example"); }); // Main content grid (auto placed in row 2, column 1) builder .spawn(( Node { // Make the height of the node fill its parent height: percent(100), // Make the grid have a 1:1 aspect ratio meaning it will scale as an exact square // As the height is set explicitly, this means the width will adjust to match the height aspect_ratio: Some(1.0), // Use grid layout for this node display: Display::Grid, // Add 24px of padding around the grid padding: UiRect::all(px(24)), // Set the grid to have 4 columns all with sizes minmax(0, 1fr) // This creates 4 exactly evenly sized columns grid_template_columns: RepeatedGridTrack::flex(4, 1.0), // Set the grid to have 4 rows all with sizes minmax(0, 1fr) // This creates 4 exactly evenly sized rows grid_template_rows: RepeatedGridTrack::flex(4, 1.0), // Set a 12px gap/gutter between rows and columns row_gap: px(12), column_gap: px(12), ..default() }, BackgroundColor(Color::srgb(0.25, 0.25, 0.25)), )) .with_children(|builder| { // Note there is no need to specify the position for each grid item. Grid items that are // not given an explicit position will be automatically positioned into the next available // grid cell. The order in which this is performed can be controlled using the grid_auto_flow // style property. item_rect(builder, ORANGE); item_rect(builder, BISQUE); item_rect(builder, BLUE); item_rect(builder, CRIMSON); item_rect(builder, AQUA); item_rect(builder, ORANGE_RED); item_rect(builder, DARK_GREEN); item_rect(builder, FUCHSIA); item_rect(builder, TEAL); item_rect(builder, ALICE_BLUE); item_rect(builder, CRIMSON); item_rect(builder, ANTIQUE_WHITE); item_rect(builder, YELLOW); item_rect(builder, DEEP_PINK); item_rect(builder, YELLOW_GREEN); item_rect(builder, SALMON); }); // Right side bar (auto placed in row 2, column 2) builder .spawn(( Node { display: Display::Grid, // Align content towards the start (top) in the vertical axis align_items: AlignItems::Start, // Align content towards the center in the horizontal axis justify_items: JustifyItems::Center, // Add 10px padding padding: UiRect::all(px(10)), // Add an fr track to take up all the available space at the bottom of the column so that the text nodes // can be top-aligned. Normally you'd use flexbox for this, but this is the CSS Grid example so we're using grid. grid_template_rows: vec![GridTrack::auto(), GridTrack::auto(), GridTrack::fr(1.0)], // Add a 10px gap between rows row_gap: px(10), ..default() }, BackgroundColor(BLACK.into()), )) .with_children(|builder| { builder.spawn((Text::new("Sidebar"), TextFont::from(font.clone()), )); builder.spawn((Text::new("A paragraph of text which ought to wrap nicely. A paragraph of text which ought to wrap nicely. A paragraph of text which ought to wrap nicely. A paragraph of text which ought to wrap nicely. A paragraph of text which ought to wrap nicely. A paragraph of text which ought to wrap nicely. A paragraph of text which ought to wrap nicely."), TextFont { font: font.clone().into(), font_size: 13.0, ..default() }, )); builder.spawn(Node::default()); }); // Footer / status bar builder.spawn(( Node { // Make this node span two grid column so that it takes up the entire bottom row grid_column: GridPlacement::span(2), ..default() }, BackgroundColor(WHITE.into()), )); // Modal (absolutely positioned on top of content - currently hidden: to view it, change its visibility) builder.spawn(( Node { position_type: PositionType::Absolute, margin: UiRect { top: px(100), bottom: auto(), left: auto(), right: auto(), }, width: percent(60), height: px(300), max_width: px(600), ..default() }, Visibility::Hidden, BackgroundColor(Color::WHITE.with_alpha(0.8)), )); }); } /// Create a colored rectangle node. The node has size as it is assumed that it will be /// spawned as a child of a Grid container with `AlignItems::Stretch` and `JustifyItems::Stretch` /// which will allow it to take its size from the size of the grid area it occupies. fn item_rect(builder: &mut ChildSpawnerCommands, color: Srgba) { builder .spawn(( Node { display: Display::Grid, padding: UiRect::all(px(3)), ..default() }, BackgroundColor(BLACK.into()), )) .with_children(|builder| { builder.spawn((Node::default(), BackgroundColor(color.into()))); }); } fn spawn_nested_text_bundle(builder: &mut ChildSpawnerCommands, font: Handle<Font>, text: &str) { builder.spawn(( Text::new(text), TextFont::from(font.clone()), TextColor::BLACK, )); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/ui_texture_atlas.rs
examples/ui/ui_texture_atlas.rs
//! This example illustrates how to use `TextureAtlases` within ui use bevy::{color::palettes::css::*, prelude::*}; fn main() { App::new() .add_plugins(DefaultPlugins.set( // This sets image filtering to nearest // This is done to prevent textures with low resolution (e.g. pixel art) from being blurred // by linear filtering. ImagePlugin::default_nearest(), )) .add_systems(Startup, setup) .add_systems(Update, increment_atlas_index) .run(); } fn setup( mut commands: Commands, asset_server: Res<AssetServer>, mut texture_atlases: ResMut<Assets<TextureAtlasLayout>>, ) { // Camera commands.spawn(Camera2d); let text_font = TextFont::default(); let texture_handle = asset_server.load("textures/rpg/chars/gabe/gabe-idle-run.png"); let texture_atlas = TextureAtlasLayout::from_grid(UVec2::splat(24), 7, 1, None, None); let texture_atlas_handle = texture_atlases.add(texture_atlas); // root node commands .spawn(Node { width: percent(100), height: percent(100), flex_direction: FlexDirection::Column, justify_content: JustifyContent::Center, align_items: AlignItems::Center, row_gap: px(text_font.font_size * 2.), ..default() }) .with_children(|parent| { parent.spawn(( ImageNode::from_atlas_image( texture_handle, TextureAtlas::from(texture_atlas_handle), ), Node { width: px(256), height: px(256), ..default() }, BackgroundColor(ANTIQUE_WHITE.into()), Outline::new(px(8), Val::ZERO, CRIMSON.into()), )); parent .spawn((Text::new("press "), text_font.clone())) .with_child(( TextSpan::new("space"), TextColor(YELLOW.into()), text_font.clone(), )) .with_child((TextSpan::new(" to advance frames"), text_font)); }); } fn increment_atlas_index( mut image_nodes: Query<&mut ImageNode>, keyboard: Res<ButtonInput<KeyCode>>, ) { if keyboard.just_pressed(KeyCode::Space) { for mut image_node in &mut image_nodes { if let Some(atlas) = &mut image_node.texture_atlas { atlas.index = (atlas.index + 1) % 6; } } } }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false
bevyengine/bevy
https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/scrollbars.rs
examples/ui/scrollbars.rs
//! Demonstrations of scrolling and scrollbars. use bevy::{ ecs::{relationship::RelatedSpawner, spawn::SpawnWith}, input_focus::{ tab_navigation::{TabGroup, TabNavigationPlugin}, InputDispatchPlugin, }, picking::hover::Hovered, prelude::*, ui_widgets::{ ControlOrientation, CoreScrollbarDragState, CoreScrollbarThumb, Scrollbar, ScrollbarPlugin, }, }; fn main() { App::new() .add_plugins(( DefaultPlugins, ScrollbarPlugin, InputDispatchPlugin, TabNavigationPlugin, )) .insert_resource(UiScale(1.25)) .add_systems(Startup, setup_view_root) .add_systems(Update, update_scrollbar_thumb) .run(); } fn setup_view_root(mut commands: Commands) { let camera = commands.spawn((Camera::default(), Camera2d)).id(); commands.spawn(( Node { display: Display::Flex, flex_direction: FlexDirection::Column, position_type: PositionType::Absolute, left: px(0), top: px(0), right: px(0), bottom: px(0), padding: UiRect::all(px(3)), row_gap: px(6), ..Default::default() }, BackgroundColor(Color::srgb(0.1, 0.1, 0.1)), UiTargetCamera(camera), TabGroup::default(), Children::spawn((Spawn(Text::new("Scrolling")), Spawn(scroll_area_demo()))), )); } /// Create a scrolling area. /// /// The "scroll area" is a container that can be scrolled. It has a nested structure which is /// three levels deep: /// - The outermost node is a grid that contains the scroll area and the scrollbars. /// - The scroll area is a flex container that contains the scrollable content. This /// is the element that has the `overflow: scroll` property. /// - The scrollable content consists of the elements actually displayed in the scrolling area. fn scroll_area_demo() -> impl Bundle { ( // Frame element which contains the scroll area and scrollbars. Node { display: Display::Grid, width: px(200), height: px(150), grid_template_columns: vec![RepeatedGridTrack::flex(1, 1.), RepeatedGridTrack::auto(1)], grid_template_rows: vec![RepeatedGridTrack::flex(1, 1.), RepeatedGridTrack::auto(1)], row_gap: px(2), column_gap: px(2), ..default() }, Children::spawn((SpawnWith(|parent: &mut RelatedSpawner<ChildOf>| { // The actual scrolling area. // Note that we're using `SpawnWith` here because we need to get the entity id of the // scroll area in order to set the target of the scrollbars. let scroll_area_id = parent .spawn(( Node { display: Display::Flex, flex_direction: FlexDirection::Column, padding: UiRect::all(px(4)), overflow: Overflow::scroll(), ..default() }, BackgroundColor(colors::GRAY1.into()), ScrollPosition(Vec2::new(0.0, 10.0)), Children::spawn(( // The actual content of the scrolling area Spawn(text_row("Alpha Wolf")), Spawn(text_row("Beta Blocker")), Spawn(text_row("Delta Sleep")), Spawn(text_row("Gamma Ray")), Spawn(text_row("Epsilon Eridani")), Spawn(text_row("Zeta Function")), Spawn(text_row("Lambda Calculus")), Spawn(text_row("Nu Metal")), Spawn(text_row("Pi Day")), Spawn(text_row("Chi Pants")), Spawn(text_row("Psi Powers")), Spawn(text_row("Omega Fatty Acid")), )), )) .id(); // Vertical scrollbar parent.spawn(( Node { min_width: px(8), grid_row: GridPlacement::start(1), grid_column: GridPlacement::start(2), ..default() }, Scrollbar { orientation: ControlOrientation::Vertical, target: scroll_area_id, min_thumb_length: 8.0, }, Children::spawn(Spawn(( Node { position_type: PositionType::Absolute, border_radius: BorderRadius::all(px(4)), ..default() }, Hovered::default(), BackgroundColor(colors::GRAY2.into()), CoreScrollbarThumb, ))), )); // Horizontal scrollbar parent.spawn(( Node { min_height: px(8), grid_row: GridPlacement::start(2), grid_column: GridPlacement::start(1), ..default() }, Scrollbar { orientation: ControlOrientation::Horizontal, target: scroll_area_id, min_thumb_length: 8.0, }, Children::spawn(Spawn(( Node { position_type: PositionType::Absolute, border_radius: BorderRadius::all(px(4)), ..default() }, Hovered::default(), BackgroundColor(colors::GRAY2.into()), CoreScrollbarThumb, ))), )); }),)), ) } /// Create a list row fn text_row(caption: &str) -> impl Bundle { ( Text::new(caption), TextFont { font_size: 14.0, ..default() }, ) } // Update the color of the scrollbar thumb. fn update_scrollbar_thumb( mut q_thumb: Query< (&mut BackgroundColor, &Hovered, &CoreScrollbarDragState), ( With<CoreScrollbarThumb>, Or<(Changed<Hovered>, Changed<CoreScrollbarDragState>)>, ), >, ) { for (mut thumb_bg, Hovered(is_hovering), drag) in q_thumb.iter_mut() { let color: Color = if *is_hovering || drag.dragging { // If hovering, use a lighter color colors::GRAY3 } else { // Default color for the slider colors::GRAY2 } .into(); if thumb_bg.0 != color { // Update the color of the thumb thumb_bg.0 = color; } } } mod colors { use bevy::color::Srgba; pub const GRAY1: Srgba = Srgba::new(0.224, 0.224, 0.243, 1.0); pub const GRAY2: Srgba = Srgba::new(0.486, 0.486, 0.529, 1.0); pub const GRAY3: Srgba = Srgba::new(1.0, 1.0, 1.0, 1.0); }
rust
Apache-2.0
51a6fedb06a022ab5d39e099413caa882e1b022d
2026-01-04T15:31:59.438636Z
false