### Setup for Clearcoat Example Source: https://docs.rs/bevy/latest/src/clearcoat/clearcoat.rs.html Initializes the Bevy application, sets up resources, and defines systems for the Clearcoat PBR example. Includes startup and update systems for scene setup, light animation, sphere animation, and input handling. ```rust pub fn main() { App::new() .init_resource::() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, animate_light) .add_systems(Update, animate_spheres) .add_systems(Update, (handle_input, update_help_text).chain()) .run(); } ``` -------------------------------- ### Bevy Irradiance Volumes Example Setup Source: https://docs.rs/bevy/latest/src/irradiance_volumes/irradiance_volumes.rs.html Initializes the Bevy application with default plugins and sets up the primary window. This is the starting point for the irradiance volume example. ```rust use bevy::prelude::*; use bevy::window::WindowPlugin; fn main() { App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { ``` -------------------------------- ### Setup Bevy App with Text Systems Source: https://docs.rs/bevy/latest/src/text/text.rs.html Initializes the Bevy application, adds default plugins, and registers systems for text setup and updates. This is the entry point for the text example. ```rust use bevy::prelude::*; use bevy::diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin}; 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)); app.run(); } ``` -------------------------------- ### Setup for Asset Generation Example Source: https://docs.rs/bevy/latest/bevy/asset/prelude/struct.Assets.html Demonstrates setting up Bevy resources and spawning entities for asset generation examples. It shows how to add assets directly, use `add_async` for deferred generation, and reserve handles for later insertion. ```rust fn setup( mut commands: Commands, asset_server: Res, mut materials: ResMut>, meshes: Res>, ) { commands.spawn((Camera3d::default(), Transform::from_xyz(0.0, 0.0, 5.0))); commands.spawn(( DirectionalLight::default(), Transform::default().looking_to(Dir3::new(Vec3::new(-1.0, -1.0, -1.0)).unwrap(), Dir3::Y), )); // The simplest way to generate an asset is to add it directly to the `Assets`. let material_handle = materials.add(StandardMaterial::default()); commands.spawn(( Transform::from_xyz(-2.0, 0.0, 0.0), MeshMaterial3d(material_handle.clone()), // Alternatively, `add_async` creates a task that runs your async function. Once it // completes, the asset is added to the `Assets`. This is "deferred" meaning that the asset // may take a frame to be added after the task completes. Mesh3d(asset_server.add_async(generate_mesh_async())), )); // The last way to generate assets is to reserve a handle, and then use `Assets::insert` to // populate the asset later. In this example, the `generate_mesh_system` system runs to populate // the mesh. let mesh_handle = meshes.reserve_handle(); commands.insert_resource(HandleToGenerate(mesh_handle.clone())); commands.spawn(( Transform::from_xyz(2.0, 0.0, 0.0) .with_rotation(Quat::from_rotation_x(50.0f32.to_radians())), Mesh3d(mesh_handle), MeshMaterial3d(material_handle), )); } ``` -------------------------------- ### Bevy App Setup for Rotation Example Source: https://docs.rs/bevy/latest/src/rotation/rotation.rs.html Sets up a Bevy application with default plugins, a fixed time step, and systems for startup, player movement, snapping, and rotation. This is the main entry point for the rotation example. ```rust use bevy::math::ops; use bevy::prelude::*; const BOUNDS: Vec2 = Vec2::new(1200.0, 640.0); fn main() { App::new() .add_plugins(DefaultPlugins) .insert_resource(Time::::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) { 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 }, )); } ``` -------------------------------- ### Bevy App Initialization and System Setup Source: https://docs.rs/bevy/latest/bevy/app/struct.App.html This snippet shows the basic setup of a Bevy App, including adding plugins and defining system schedules. It's a foundational example for structuring Bevy applications. ```rust fn main() { let mut app = App::new(); app // to display log messages from Stepping resource .add_plugins(LogPlugin::default()) .add_systems( Update, ( update_system_one, // establish a dependency here to simplify descriptions below update_system_two.after(update_system_one), update_system_three.after(update_system_two), update_system_four, ), ) .add_systems(PreUpdate, pre_update_system); // For the simplicity of this example, we directly modify the `Stepping` // resource here and run the systems with `App::update()`. Each call to // `App::update()` is the equivalent of a single frame render when using // `App::run()`. // // In a real-world situation, the `Stepping` resource would be modified by // a system based on input from the user. A full demonstration of this can // be found in the breakout example. println!( r#"" Actions: call app.update() Result: All systems run normally"# ); app.update(); println!( r#"" Actions: Add the Stepping resource then call app.update() Result: All systems run normally. Stepping has no effect unless explicitly configured for a Schedule, and Stepping has been enabled." ); app.insert_resource(Stepping::new()); app.update(); println!( r#"" Actions: Add the Update Schedule to Stepping; enable Stepping; call app.update() Result: Only the systems in PreUpdate run. When Stepping is enabled, systems in the configured schedules will not run unless: * Stepping::step_frame() is called * Stepping::continue_frame() is called * System has been configured to always run"# ); let mut stepping = app.world_mut().resource_mut::(); stepping.add_schedule(Update).enable(); app.update(); println!( r#"" Actions: call Stepping.step_frame(); call app.update() Result: The PreUpdate systems run, and one Update system will run. In Stepping, step means run the next system across all the schedules that have been added to the Stepping resource." ); let mut stepping = app.world_mut().resource_mut::(); stepping.step_frame(); app.update(); println!( r#"" Actions: call app.update() Result: Only the PreUpdate systems run. The previous call to Stepping::step_frame() only applies for the next call to app.update()/the next frame rendered. "# ); app.update(); println!( r#"" Actions: call Stepping::continue_frame(); call app.update() Result: PreUpdate system will run, and all remaining Update systems will run. Stepping::continue_frame() tells stepping to run all systems ``` -------------------------------- ### Setup UI with Transformations Source: https://docs.rs/bevy/latest/bevy/ui/prelude/struct.UiTransform.html This example demonstrates setting up a UI hierarchy with various transformations applied to child nodes. It includes examples of rotation, scaling, and translation. ```rust pub fn setup(mut commands: Commands) { commands.spawn((Camera2d, DespawnOnExit(super::Scene::Transformations))); commands .spawn(( Node { width: percent(100), height: percent(100), display: Display::Block, ..default() }, DespawnOnExit(super::Scene::Transformations), )) .with_children(|parent| { for (transformation, label, background) in [ ( UiTransform::from_rotation(Rot2::degrees(45.)), "Rotate 45 degrees", RED, ), ( UiTransform::from_scale(Vec2::new(2., 0.5)), "Scale 2.x 0.5y", GREEN, ), ( UiTransform::from_translation(Val2::px(-50., 50.)), "Translate -50px x +50px y", BLUE, ), ( UiTransform { translation: Val2::px(50., 0.), scale: Vec2::new(-1., 1.), rotation: Rot2::degrees(30.), }, "T 50px x\nS -1.x (refl)\nR 30deg", DARK_CYAN, ), ] { parent .spawn((Node { width: percent(100), margin: UiRect { top: px(50), bottom: px(50), ..default() }, align_items: AlignItems::Center, justify_content: JustifyContent::SpaceAround, ..default() },)) .with_children(|row| { row.spawn(( Text::new("Before Tf"), Node { width: px(100), height: px(100), border_radius: BorderRadius::bottom_right(px(25.)), ..default() }, BackgroundColor(background.into()), TextFont::default(), )); row.spawn(( Text::new(label), Node { width: px(100), height: px(100), border_radius: BorderRadius::bottom_right(px(25.)), ..default() }, BackgroundColor(background.into()), transformation, TextFont::default(), )); }); } }); } ``` -------------------------------- ### PCSS Example Setup Source: https://docs.rs/bevy/latest/src/pcss/pcss.rs.html Sets up the Bevy application with necessary plugins, resources, and systems for the PCSS example. Includes optional free camera support and UI interaction handling. ```rust 1//! Demonstrates percentage-closer soft shadows (PCSS). 2 3use std::f32::consts::PI; 4 5#[cfg(feature = "free_camera")] 6use bevy::camera_controller::free_camera::{FreeCamera, FreeCameraPlugin}; 7use bevy::{ 8 anti_alias::taa::TemporalAntiAliasing, 9 camera::{ 10 primitives::{CubemapFrusta, Frustum}, 11 visibility::{CubemapVisibleEntities, VisibleMeshEntities}, 12 }, 13 core_pipeline::prepass::{DepthPrepass, MotionVectorPrepass}, 14 light::{ShadowFilteringMethod, Skybox}, 15 math::vec3, 16 prelude::*, 17 render::camera::TemporalJitter, 18}; 19 20use crate::widgets::{RadioButton, RadioButtonText, WidgetClickEvent, WidgetClickSender}; 21 22#[path = "../helpers/widgets.rs"] 23mod widgets; 24 25/// The size of the light, which affects the size of the penumbras. 26const LIGHT_RADIUS: f32 = 10.0; 27 28/// The intensity of the point and spot lights. 29const POINT_LIGHT_INTENSITY: f32 = 1_000_000_000.0; 30 31/// The range in meters of the point and spot lights. 32const POINT_LIGHT_RANGE: f32 = 110.0; 33 34/// The depth bias for directional and spot lights. This value is set higher 35/// than the default to avoid shadow acne. 36const DIRECTIONAL_SHADOW_DEPTH_BIAS: f32 = 0.20; 37 38/// The depth bias for point lights. This value is set higher than the default to 39/// avoid shadow acne. 40/// 41/// Unfortunately, there is a bit of Peter Panning with this value, because of 42/// the distance and angle of the light. This can't be helped in this scene 43/// without increasing the shadow map size beyond reasonable limits. 44const POINT_SHADOW_DEPTH_BIAS: f32 = 0.35; 45 46/// The near Z value for the shadow map, in meters. This is set higher than the 47/// default in order to achieve greater resolution in the shadow map for point 48/// and spot lights. 49const SHADOW_MAP_NEAR_Z: f32 = 50.0; 50 51/// The current application settings (light type, shadow filter, and the status 52/// of PCSS). 53#[derive(Resource)] 54struct AppStatus { 55 /// The type of light presently in the scene: either directional or point. 56 light_type: LightType, 57 /// The type of shadow filter: Gaussian or temporal. 58 shadow_filter: ShadowFilter, 59 /// Whether soft shadows are enabled. 60 soft_shadows: bool, 61} 62 63impl Default for AppStatus { 64 fn default() -> Self { 65 Self { 66 light_type: default(), 67 shadow_filter: default(), 68 soft_shadows: true, 69 } 70 } 71} 72 73/// The type of light presently in the scene: directional, point, or spot. 74#[derive(Clone, Copy, Default, PartialEq)] 75enum LightType { 76 /// A directional light, with a cascaded shadow map. 77 #[default] 78 Directional, 79 /// A point light, with a cube shadow map. 80 Point, 81 /// A spot light, with a cube shadow map. 82 Spot, 83} 84 85/// The type of shadow filter. 86/// 87/// Generally, `Gaussian` is preferred when temporal antialiasing isn't in use, 88/// while `Temporal` is preferred when TAA is in use. In this example, this 89/// setting also turns TAA on and off. 90#[derive(Clone, Copy, Default, PartialEq)] 91enum ShadowFilter { 92 /// The non-temporal Gaussian filter (Castano '13 for directional lights, an 93 /// analogous alternative for point and spot lights). 94 #[default] 95 NonTemporal, 96 /// The temporal Gaussian filter (Jimenez '14 for directional lights, an 97 /// analogous alternative for point and spot lights). 98 Temporal, 99} 100 101/// Each example setting that can be toggled in the UI. 102#[derive(Clone, Copy, PartialEq)] 103enum AppSetting { 104 /// The type of light presently in the scene: directional, point, or spot. 105 LightType(LightType), 106 /// The type of shadow filter. 107 ShadowFilter(ShadowFilter), 108 /// Whether PCSS is enabled or disabled. 109 SoftShadows(bool), 110} 111 112/// The example application entry point. 113fn main() { 114 #[cfg(not(feature = "free_camera"))] 115 println!("Enable feature free_camera to add a free camera to this example"); 116 117 App::new() 118 .init_resource::() 119 .add_plugins(( 120 DefaultPlugins.set(WindowPlugin { 121 primary_window: Some(Window { 122 title: "Bevy Percentage Closer Soft Shadows Example".into(), 123 ..default() 124 }), 125 ..default() 126 }), 127 #[cfg(feature = "free_camera")] 128 FreeCameraPlugin, 129 )) 130 .add_message::>() 131 .add_systems(Startup, setup) 132 .add_systems(Update, widgets::handle_ui_interactions::) 133 .add_systems( 134 Update, ``` -------------------------------- ### Bevy UI Scaling Example Setup Source: https://docs.rs/bevy/latest/src/ui_scaling/ui_scaling.rs.html Initializes a Bevy application with default plugins, sets up a TargetScale resource for managing UI scaling animations, and defines startup and update systems for UI setup and scaling logic. ```rust use bevy::{color::palettes::css::*, prelude::*}; use core::time::Duration; const SCALE_TIME: u64 = 400; fn main() { App::new() .add_plugins(DefaultPlugins) .insert_resource(TargetScale { start_scale: 1.0, target_scale: 1.0, target_time: Timer::new(Duration::from_millis(SCALE_TIME), TimerMode::Once), }) .add_systems(Startup, setup) .add_systems( Update, (change_scaling, apply_scaling.after(change_scaling)), ) .run(); } ``` -------------------------------- ### Setup for Asset Saving Example Source: https://docs.rs/bevy/latest/bevy/prelude/fn.vh.html Initializes the Bevy application with a camera, text instructions, a sprite with a loaded image, and a color palette for selection. This setup is crucial for the asset saving functionality. ```rust fn setup( mut commands: Commands, asset_server: Res, mut images: ResMut>, ) { commands.spawn(( Camera2d, Projection::Orthographic(OrthographicProjection { scaling_mode: ScalingMode::FixedVertical { viewport_height: 125.0, }, ..OrthographicProjection::default_2d() }), )); commands.spawn(Text( r"Select a color from the palette at the bottom LMB - Draw with selected color F5 - Save image" .into(), )); let handle = asset_server .load_builder() .with_settings(|settings: &mut ImageLoaderSettings| { settings.sampler = ImageSampler::nearest(); }) .load(ASSET_PATH); commands.spawn(( Sprite { image: handle.clone(), ..Default::default() }, SpriteToSave, Pickable::default(), )); // We're doing something a little cursed here: we initiate a load, and then insert a default // image into that handle. If the load succeeds, the image will be replaced with the loaded // contents. If it fails, the default image will remain. In real code, you likely want to poll // `AssetServer::load_state` and only insert this on load failure. images .insert(&handle, { let mut image = Image::new_fill( Extent3d { width: 100, height: 100, depth_or_array_layers: 1, }, TextureDimension::D2, &[0, 0, 0, 255], TextureFormat::Rgba8Unorm, RenderAssetUsages::all(), ); image.sampler = ImageSampler::nearest(); image }) .unwrap(); commands.insert_resource(ImageToSave(handle)); let container = commands .spawn(( Node { width: percent(100), height: percent(100), align_items: AlignItems::End, justify_content: JustifyContent::Center, ..Default::default() }, Pickable::IGNORE, )) .id(); for color in [ Color::WHITE, Color::Srgba(tailwind::RED_500), Color::Srgba(tailwind::ORANGE_500), Color::Srgba(tailwind::YELLOW_500), Color::Srgba(tailwind::GREEN_500), Color::Srgba(tailwind::BLUE_500), Color::Srgba(tailwind::INDIGO_500), Color::Srgba(tailwind::VIOLET_500), Color::BLACK, ] { let mut entity = commands.spawn(( Node { width: vw(5), height: vh(5), border: px(5).all(), ..Default::default() }, SelectableColor, BackgroundColor(color), BorderColor::all(NORMAL_COLOR), ChildOf(container), )); if color == Color::WHITE { entity.insert((Selected, BorderColor::all(SELECTED_COLOR))); } } } ``` -------------------------------- ### Basic App Setup with SubApp Access Source: https://docs.rs/bevy/latest/bevy/prelude/struct.App.html This example shows a typical Bevy application setup, including adding default plugins and systems, and then accessing a sub-app (RenderApp) to add further systems. It also demonstrates initializing a resource. ```rust 20fn main() { 21 let mut app = App::new(); 22 app.add_plugins(( 23 DefaultPlugins, 24 ExtractResourcePlugin::::default(), 25 )) 26 .add_systems(Startup, setup) 27 .add_systems(Update, (update_camera, input)) 28 .init_resource::() 29 .sub_app_mut(RenderApp) 30 .add_systems(Render, cause_error); 31 app.run(); 32} ``` -------------------------------- ### Setup Bevy App with Mesh2d Alpha Mode Example Source: https://docs.rs/bevy/latest/src/mesh2d_alpha_mode/mesh2d_alpha_mode.rs.html Initializes a Bevy application and sets up the startup system for the mesh alpha mode test. This includes adding default plugins and defining the setup function. ```rust use bevy::prelude::*; use bevy::sprite_render::AlphaMode2d; fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .run(); } fn setup( mut commands: Commands, asset_server: Res, mut meshes: ResMut>, mut materials: ResMut>, ) { 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 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 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), )); } ``` -------------------------------- ### Bi-directional Scrollbar Example Source: https://docs.rs/bevy/latest/bevy/math/prelude/struct.Rot2.html Shows a bi-directional scrollbar setup with initial scroll position. This example is also non-functional and serves as a visual guide. ```rust parent.spawn(( Node { flex_direction: FlexDirection::Column, width: px(230), height: px(125), overflow: Overflow::scroll(), scrollbar_width: 20., ..default() }, ScrollPosition(Vec2::new(300., 0.)), UiDebugOptions { line_width: 3., outline_scrollbars: true, show_hidden: false, show_clipped: false, ..debug_options }, Children::spawn(SpawnIter((0..6).map(move |i| { ( Node { flex_direction: FlexDirection::Row, ..default() }, Children::spawn(SpawnIter((0..6).map({ move |j| { ( Text(format!("Item {}", (i * 5) + j)), UiDebugOptions { enabled: false, ..default() }, ) } }))), UiDebugOptions { enabled: false, ..default() }, ) }))), )); ``` -------------------------------- ### Main Application Setup Source: https://docs.rs/bevy/latest/src/projection_zoom/projection_zoom.rs.html Initializes the Bevy application, inserts camera settings as a resource, and sets up startup and update systems. ```rust fn main() { App::new() .add_plugins(DefaultPlugins) .insert_resource(CameraSettings { orthographic_viewport_height: 5., // In orthographic projections, we specify camera scale relative to a default value of 1, // in which one unit in world space corresponds to one pixel. orthographic_zoom_range: 0.1..10.0, // This value was hand-tuned to ensure that zooming in and out feels smooth but not slow. orthographic_zoom_speed: 0.2, // Changes in FOV are much more noticeable due to its limited range in radians perspective_zoom_range: (PI / 5.)..(PI - 0.2), // Multiply mouse wheel inputs by this factor when using the perspective camera perspective_zoom_speed: 0.05, }) .add_systems(Startup, (setup, instructions)) .add_systems(Update, (switch_projection, zoom)) .run(); } ``` -------------------------------- ### Custom Gizmo Clearing Context Setup Source: https://docs.rs/bevy/latest/bevy/gizmos/gizmos/struct.Gizmos.html This example demonstrates how to set up a custom clearing context for Gizmos, which is useful for custom scheduling similar to `FixedMain`. Ensure the context starts and ends cleanly within its parent context. ```rust use bevy_gizmos::{prelude::*, *, gizmos::GizmoStorage}; struct ClearContextSetup; impl Plugin for ClearContextSetup { fn build(&self, app: &mut App) { app.init_resource::>() // Make sure this context starts/ends cleanly if inside another context. E.g. it // should start after the parent context starts and end after the parent context ends. .add_systems(StartOfMyContext, start_gizmo_context::) // If not running multiple times, put this with [`start_gizmo_context`]. .add_systems(StartOfRun, clear_gizmo_context::) // If not running multiple times, put this with [`end_gizmo_context`]. .add_systems(EndOfRun, collect_requested_gizmos::) .add_systems(EndOfMyContext, end_gizmo_context::) .add_systems( Last, propagate_gizmos::.before(GizmoMeshSystems), ); } } ``` -------------------------------- ### Main Application Setup Source: https://docs.rs/bevy/latest/src/spotlight/spotlight.rs.html Initializes the Bevy application, sets up global ambient light, and registers startup and update systems. This is the entry point for the spotlight example. ```rust fn main() { App::new() .insert_resource(GlobalAmbientLight { brightness: 20.0, ..default() }) .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(Update, (light_sway, movement, rotation)) .run(); } ``` -------------------------------- ### Spawning a Ground Plane with Rotation in Async Task Setup Source: https://docs.rs/bevy/latest/bevy/prelude/struct.Quat.html This example shows spawning a circular ground plane with a specific rotation, similar to other scene setup examples. It's part of an asynchronous task setup. ```rust 131fn setup_env( 132 mut commands: Commands, 133 mut meshes: ResMut>, 134 mut materials: ResMut>, 135) { 136 // Spawn a circular ground plane 137 commands.spawn(( 138 Mesh3d(meshes.add(Circle::new(1.618 * NUM_CUBES as f32))), 139 MeshMaterial3d(materials.add(Color::WHITE)), 140 Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)), 141 )); 142 143 // Spawn a point light with shadows enabled 144 commands.spawn(( 145 PointLight { 146 shadow_maps_enabled: true, 147 ..default() 148 }, 149 Transform::from_xyz(0.0, LIGHT_RADIUS, 4.0), 150 )); 151 152 // Spawn a camera looking at the origin 153 commands.spawn(( 154 Camera3d::default(), 155 Transform::from_xyz(-6.5, 5.5, 12.0).looking_at(Vec3::ZERO, Vec3::Y), 156 )); 157} ``` -------------------------------- ### Basic App Setup with Startup and Update Systems Source: https://docs.rs/bevy/latest/bevy/ecs/prelude/trait.IntoScheduleConfigs.html Demonstrates a typical Bevy application setup, including adding default plugins, defining startup systems, and scheduling update systems. ```rust fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, setup) .add_systems(FixedUpdate, controls) .add_systems(PostUpdate, draw_cursor.after(TransformSystems::Propagate)) .run(); } ``` -------------------------------- ### Bounding 2D Setup with RegularPolygon Source: https://docs.rs/bevy/latest/bevy/math/primitives/struct.RegularPolygon.html Illustrates the setup for a bounding box 2D example, spawning multiple shapes including a RegularPolygon. This snippet is from Bevy's bounding box example. ```rust 253 Shape::Polygon(RegularPolygon::new(50., 6)), ``` -------------------------------- ### Example usage of into_inner in setup Source: https://docs.rs/bevy/latest/bevy/ecs/system/struct.Res.html Shows how into_inner() can be used to access and manipulate resource data during system setup. This example extracts mutable access to assets like images and materials. ```rust 191fn setup( 192 mut commands: Commands, 193 args: Res, 194 asset_server: Res, 195 mut meshes: ResMut>, 196 material_assets: ResMut>, 197 images: ResMut>, 198 counter: ResMut, 199){ 200 let args = args.into_inner(); 201 let images = images.into_inner(); 202 203 let mut textures = Vec::with_capacity(args.material_texture_count.max(1)); 204 if args.material_texture_count > 0 { 205 textures.push(asset_server.load("branding/icon.png")); 206 } 207 init_textures(&mut textures, args, images); 208 209 let material_assets = material_assets.into_inner(); 210 let materials = init_materials(args, &textures, material_assets); 211 212 let mut cube_resources = CubeResources { 213 _textures: textures, 214 materials, 215 cube_mesh: meshes.add(Cuboid::from_size(Vec3::splat(CUBE_SCALE))), 216 color_rng: ChaCha8Rng::seed_from_u64(42), 217 material_rng: ChaCha8Rng::seed_from_u64(12), 218 velocity_rng: ChaCha8Rng::seed_from_u64(97), 219 transform_rng: ChaCha8Rng::seed_from_u64(26), 220 }; 221 222 let font = TextFont { 223 font_size: FontSize::Px(40.0), 224 ..Default::default() 225 }; 226 227 commands.spawn(( 228 Camera3d::default(), 229 Transform::from_translation(VOLUME_SIZE * 1.3).looking_at(Vec3::ZERO, Vec3::Y), 230 )); 231 232 commands.spawn(( 233 DirectionalLight { 234 illuminance: 10000.0, 235 shadow_maps_enabled: false, 236 ..default() 237 }, 238 Transform::from_xyz(1.0, 2.0, 3.0).looking_at(Vec3::ZERO, Vec3::Y), 239 )); 240 241 commands.spawn(( 242 Node { 243 position_type: PositionType::Absolute, 244 padding: UiRect::all(px(5)), 245 ..default() 246 }, 247 BackgroundColor(Color::BLACK.with_alpha(0.75)), 248 GlobalZIndex(i32::MAX), 249 children![( 250 Text::default(), 251 StatsText, 252 children![ 253 ( 254 TextSpan::new("Cube Count: "), 255 font.clone(), 256 TextColor(LIME.into()), 257 ), 258 (TextSpan::new(""), font.clone(), TextColor(AQUA.into())), 259 ( 260 TextSpan::new("\nFPS (raw): "), 261 font.clone(), 262 TextColor(LIME.into()), 263 ), 264 (TextSpan::new(""), font.clone(), TextColor(AQUA.into())), 265 ( 266 TextSpan::new("\nFPS (SMA): "), ``` -------------------------------- ### Basic App Setup with Resources and States Source: https://docs.rs/bevy/latest/bevy/prelude/enum.Color.html Demonstrates setting up a Bevy application with initial resources and states. Resources like `DisplayQuality` and `Volume` are inserted, and game states are initialized and managed. ```rust enum GameState { #[default] Splash, Menu, Game, } #[derive(Resource, Debug, PartialEq, Eq, Clone, Copy)] enum DisplayQuality { Low, Medium, High, } #[derive(Component)] struct Setting(T); #[derive(Resource, Debug, PartialEq, Eq, Clone, Copy)] struct Volume(u32); fn main() { App::new() .add_plugins(DefaultPlugins) .insert_resource(DisplayQuality::Medium) .insert_resource(Volume(7)) .init_state::() .add_systems(Startup, setup) .add_plugins((splash::splash_plugin, menu::menu_plugin, game::game_plugin)) .run(); } fn setup(mut commands: Commands) { commands.spawn(Camera2d); } ``` -------------------------------- ### Main Application Setup Source: https://docs.rs/bevy/latest/src/atmospheric_fog/atmospheric_fog.rs.html Initializes the Bevy application, adds default plugins, and sets up startup and update systems for camera, scene, instructions, and input toggles. ```rust fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems( Startup, (setup_camera_fog, setup_terrain_scene, setup_instructions), ) .add_systems(Update, toggle_system) .run(); } ``` -------------------------------- ### Bevy UI Setup for Dragging Example Source: https://docs.rs/bevy/latest/src/window_drag_move/window_drag_move.rs.html Spawns a 3D camera and a UI node with text to display instructions and current controls. This setup is part of the window drag move and resize example. ```rust fn setup(mut commands: Commands) { // Camera commands.spawn(Camera3d::default()); // UI commands.spawn(( Node { position_type: PositionType::Absolute, padding: UiRect::all(px(5)), ..default() }, BackgroundColor(Color::BLACK.with_alpha(0.75)), GlobalZIndex(i32::MAX), children![( Text::default(), children![ TextSpan::new( "Demonstrate drag move and drag resize without window decorations.\n\n", ), TextSpan::new("Controls:\n"), TextSpan::new("A - change left click action ["), TextSpan::new("Move"), TextSpan::new("]\n"), TextSpan::new("S / D - change resize direction ["), TextSpan::new("NorthWest"), TextSpan::new("]\n"), ] )], )); } ``` -------------------------------- ### Setup for Many Materials Example Source: https://docs.rs/bevy/latest/bevy/ecs/prelude/struct.Res.html This snippet demonstrates setting up a 3D scene with a camera, light, and numerous cubes, each with a white material. It's useful for stress-testing material rendering performance. ```rust fn setup( mut commands: Commands, args: Res, mesh_assets: ResMut>, material_assets: ResMut>, ) { let args = args.into_inner(); let material_assets = material_assets.into_inner(); let mesh_assets = mesh_assets.into_inner(); let n = args.grid_size; // Camera let w = n as f32; commands.spawn(( Camera3d::default(), Transform::from_xyz(w * 1.25, w + 1.0, w * 1.25) .looking_at(Vec3::new(0.0, (w * -1.1) + 1.0, 0.0), Vec3::Y), )); // Light commands.spawn(( Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, 1.0, -PI / 4.)), DirectionalLight { illuminance: 3000.0, shadow_maps_enabled: true, ..default() }, )); // Cubes let mesh_handle = mesh_assets.add(Cuboid::from_size(Vec3::ONE)); for x in 0..n { for z in 0..n { commands.spawn(( Mesh3d(mesh_handle.clone()), MeshMaterial3d(material_assets.add(Color::WHITE)), Transform::from_translation(Vec3::new(x as f32, 0.0, z as f32)), )); } } } ``` -------------------------------- ### JSON Payload Example for World Get Components Source: https://docs.rs/bevy/latest/bevy/remote/struct.BrpRequest.html An example of a JSON payload for a 'world.get_components' request. ```json { "jsonrpc": "2.0", "method": "world.get_components", "id": 0, "params": { "entity": 4294967298, "components": [ "bevy_transform::components::transform::Transform" ] } } ``` -------------------------------- ### Basic Bevy Setup and Game State Management Source: https://docs.rs/bevy/latest/bevy/ecs/system/lifetimeless/type.SCommands.html This example shows fundamental Bevy setup functions, including spawning a camera, loading assets, and despawning entities. It illustrates the use of `Commands` for entity manipulation and `Res` for accessing resources. ```rust fn setup(mut commands: Commands) { commands.spawn(Camera2d); } fn setup_game(mut commands: Commands, asset_server: Res) { commands.spawn(Sprite::from_image(asset_server.load("branding/icon.png"))); info!("Setup game"); } fn teardown_game(mut commands: Commands, player: Single>) { commands.entity(*player).despawn(); info!("Teardown game"); } ``` -------------------------------- ### Bevy Game of Life Shader Setup with UVec2 Source: https://docs.rs/bevy/latest/bevy/math/prelude/struct.UVec2.html Example of using UVec2.as_vec2() to set the custom size of a Sprite in a Bevy shader example. This code is part of the game of life compute shader setup. ```rust 54fn setup(mut commands: Commands, mut images: ResMut>) { let mut image = Image::new_target_texture(SIZE.x, SIZE.y, TextureFormat::Rgba32Float, None); image.asset_usage = RenderAssetUsages::RENDER_WORLD; image.texture_descriptor.usage = TextureUsages::COPY_DST | TextureUsages::STORAGE_BINDING | TextureUsages::TEXTURE_BINDING; let image0 = images.add(image.clone()); let image1 = images.add(image); commands.spawn(( Sprite { image: image0.clone(), custom_size: Some(SIZE.as_vec2()), ..default() }, Transform::from_scale(Vec3::splat(DISPLAY_FACTOR as f32)), )); commands.spawn(Camera2d); commands.insert_resource(GameOfLifeImages { texture_a: image0, texture_b: image1, }); commands.insert_resource(GameOfLifeUniforms { alive_color: LinearRgba::RED, }); } ``` -------------------------------- ### Main Application Setup Source: https://docs.rs/bevy/latest/src/color_grading/color_grading.rs.html Sets up the Bevy application, including adding default plugins, initializing the `SelectedColorGradingOption` resource, and chaining update systems for handling input and UI state. ```rust fn main() { App::new() .add_plugins(DefaultPlugins) .init_resource::() .add_systems(Startup, setup) .add_systems( Update, ( handle_button_presses, adjust_color_grading_option, update_ui_state, ) .chain(), ) .run(); } ``` -------------------------------- ### Getting SliderRange Start Value Source: https://docs.rs/bevy/latest/bevy/ui_widgets/struct.SliderRange.html Retrieve the minimum allowed value for the slider using the `start()` method. ```rust pub fn start(&self) -> f32 ``` -------------------------------- ### Main Application Setup Source: https://docs.rs/bevy/latest/src/many_sprite_meshes/many_sprite_meshes.rs.html Sets up the Bevy application with necessary plugins, resources, and systems for the many sprite meshes example. Includes diagnostic plugins and window configuration. ```rust use bevy::{ color::palettes::css::*, diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}, prelude::*, window::{PresentMode, WindowResolution}, winit::WinitSettings, }; use rand::RngExt; const CAMERA_SPEED: f32 = 1000.0; const COLORS: [Color; 3] = [Color::Srgba(BLUE), Color::Srgba(WHITE), Color::Srgba(RED)]; #[derive(Resource)] struct ColorTint(bool); fn main() { App::new() .insert_resource(ColorTint( std::env::args().nth(1).unwrap_or_default() == "--colored", )) // Since this is also used as a benchmark, we want it to display performance data. .add_plugins(( LogDiagnosticsPlugin::default(), FrameTimeDiagnosticsPlugin::default(), DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { present_mode: PresentMode::AutoNoVsync, resolution: WindowResolution::new(1920, 1080).with_scale_factor_override(1.0), ..default() }), ..default() }), )) .insert_resource(WinitSettings::continuous()) .add_systems(Startup, setup) .add_systems( Update, (print_sprite_count, move_camera.after(print_sprite_count)), ) .run(); } ```