### Setup Resources in App Builder Source: https://bevy-cheatbook.github.io/programming/res.html Set up resources that should always exist from the start using the `App` builder. Use `insert_resource` for custom values and `init_resource` for default values. ```rust __ App::new() .add_plugins(DefaultPlugins) .insert_resource(StartingLevel(3)) .init_resource::() // ... ``` -------------------------------- ### Install rust-analyzer Component Source: https://bevy-cheatbook.github.io/setup/editor/kak.html Installs the rust-analyzer component using rustup. This is a prerequisite for using rust-analyzer with Kakoune. ```bash rustup component add rust-analyzer ``` -------------------------------- ### Install wasm-server-runner Source: https://bevy-cheatbook.github.io/platforms/wasm.html Install the `wasm-server-runner` tool, which simplifies testing Bevy web applications during development by automatically serving and opening the game in a browser. ```bash cargo install wasm-server-runner ``` -------------------------------- ### VSCode Debug Configuration for Bevy Example Source: https://bevy-cheatbook.github.io/setup/editor/vscode.html Create a VSCode launch configuration for debugging a specific Bevy example, such as 'breakout', ensuring correct build arguments and environment variables are set. ```json { "type": "lldb", "request": "launch", "name": "Debug example 'breakout'", "cargo": { "args": [ "build", "--example=breakout", "--package=bevy" ], "filter": { "name": "breakout", "kind": "example" } }, "args": [], "cwd": "${workspaceFolder}", "env": { "CARGO_MANIFEST_DIR": "${workspaceFolder}", } } ``` -------------------------------- ### Verify Vulkan Installation Source: https://bevy-cheatbook.github.io/platforms/linux.html Run this command to confirm that Vulkan is installed and working correctly on your system. This is crucial for Bevy apps to run with optimal performance and features. ```bash vulkaninfo ``` -------------------------------- ### Install xwin for Windows MSVC Toolchain Source: https://bevy-cheatbook.github.io/setup/cross/linux-windows.html Installs the `xwin` utility, which automates the download and installation of Microsoft Windows SDKs required for the MSVC toolchain on non-Windows systems. This is necessary for cross-compiling with MSVC. ```bash cargo install xwin ``` -------------------------------- ### Install xwin Tool Source: https://bevy-cheatbook.github.io/setup/cross/macos-windows.html Installs the 'xwin' cargo subcommand, a utility that automates the download and installation of Microsoft Windows SDKs required for MSVC toolchain development. ```bash cargo install xwin ``` -------------------------------- ### Configure xwin for Windows SDK Installation Source: https://bevy-cheatbook.github.io/setup/cross/macos-windows.html Uses the 'xwin' tool to accept the Microsoft license, download necessary SDK files, and install them to a specified output directory. The `--disable-symlinks` option is recommended for macOS. ```bash xwin --accept-license splat --disable-symlinks --output /Users/me/.xwin ``` -------------------------------- ### Creating Systems with Constructor Functions in Bevy Source: https://bevy-cheatbook.github.io/programming/local.html Illustrates creating a system using a constructor function that initializes data and returns a closure. This allows for more complex system setup. ```rust #[derive(Default)] struct MyConfig { magic: usize, } // create a "constructor" function, which can initialize // our data and move it into a closure that Bevy can run as a system fn my_system_constructor() -> impl FnMut(Commands, Res) { // create the `MyConfig` let config = MyConfig { magic: 420, }; // this is the actual system that bevy will run move |mut commands, res| { // we can use `config` here, the value from above will be "moved in" // we can also use our system params: `commands`, `res` } } fn main() { App::new() .add_plugins(DefaultPlugins) // note the parentheses `()` // we are calling the "constructor" we made above, // which will return the actual system that gets added to bevy .add_systems(Update, my_system_constructor()) .run(); } ``` -------------------------------- ### Configure xwin for Windows SDK Installation Source: https://bevy-cheatbook.github.io/setup/cross/linux-windows.html Uses `xwin` to accept the Microsoft license and download/install the Windows SDKs to a specified output directory. Ensure the path is correct for your system. ```bash xwin --accept-license splat --output /home/me/.xwin ``` -------------------------------- ### Install create-dmg using Homebrew Source: https://bevy-cheatbook.github.io/platforms/macos.html Use this command to install the `create-dmg` tool if you are using Homebrew on macOS. This tool allows for creating customized DMG files. ```bash brew install create-dmg ``` -------------------------------- ### Compile and Install LLD from Source Source: https://bevy-cheatbook.github.io/setup/cross/macos-windows.html Clones the LLVM project, builds the LLD linker using CMake, and installs it to /usr/local. This is necessary for linking on macOS when targeting Windows with MSVC. Adjust '-j10' based on your CPU cores. ```bash git clone --depth=1 https://github.com/llvm/llvm-project cd llvm-project mkdir build cd build cmake -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_PROJECTS=lld -DCMAKE_INSTALL_PREFIX=/usr/local ../llvm sudo make -j10 install # adjust `-j10` based on your number of CPU cores cd ../../; rm -rf llvm-project # delete the git repo and build files to free disk space ``` -------------------------------- ### Setup and Update FPS Counter Systems Source: https://bevy-cheatbook.github.io/cookbook/print-framerate.html Adds the systems for setting up and updating the FPS counter to the Bevy application. ```rust app.add_systems(Startup, setup_fps_counter); app.add_systems(Update, ( fps_text_update_system, fps_counter_showhide, )); ``` -------------------------------- ### Run Bevy WASM Project Source: https://bevy-cheatbook.github.io/platforms/wasm.html Build and run your Bevy game for the `wasm32-unknown-unknown` target. This command will automatically start a local webserver and open the game in your default browser. ```bash cargo run --target wasm32-unknown-unknown ``` -------------------------------- ### Configuring Bevy App with Systems Source: https://bevy-cheatbook.github.io/programming/systems.html Demonstrates how to build a Bevy application by adding plugins and registering systems to specific schedules. Systems added to `Startup` run once at launch, while systems added to `Update` run every frame. ```rust __ fn main() { App::new() .add_plugins(DefaultPlugins) // run these only once at launch .add_systems(Startup, (setup_camera, debug_start)) // run these every frame update .add_systems(Update, (move_player, enemies_ai)) // ... .run(); } ``` -------------------------------- ### Accessing Assets with Handles Source: https://bevy-cheatbook.github.io/assets/data.html Use the `Assets` resource to access asset data from systems. Untyped handles must be upgraded to typed handles. This example shows how to get a texture atlas. ```rust #[derive(Resource)] struct SpriteSheets { map_tiles: Handle, } fn use_sprites( handles: Res, atlases: Res>, images: Res>, ) { // Could be `None` if the asset isn't loaded yet if let Some(atlas) = atlases.get(&handles.map_tiles) { // do something with the texture atlas } } ``` -------------------------------- ### Basic Bevy App Setup Source: https://bevy-cheatbook.github.io/programming/app-builder.html Configure a Bevy application by adding default plugins, custom plugins, events, and systems for startup and updates. This is the typical entry point for a Bevy game. ```rust __ fn main() { App::new() // Bevy itself: .add_plugins(DefaultPlugins) // Plugins from our game/project: .add_plugins(ui::MyUiPlugin) // events: .add_event::() // systems to run once at startup: .add_systems(Startup, spawn_things) // systems to run each frame: .add_systems(Update, ( camera_follow_player, debug_levelups, debug_stats_change, )) // ... // launch the app! .run(); } ``` -------------------------------- ### Track Touches with the Touches Resource Source: https://bevy-cheatbook.github.io/input/touch.html Use the `Touches` resource to iterate over currently active fingers, check for new presses, and get touch details like position and start position. This is useful for continuous tracking of multi-touch gestures. ```rust fn touches( touches: Res, ) { // There is a lot more information available, see the API docs. // This example only shows some very basic things. for finger in touches.iter() { if touches.just_pressed(finger.id()) { println!("A new touch with ID {} just began.", finger.id()); } println!( "Finger {} is at position ({},{}), started from ({},{}).", finger.id(), finger.position().x, finger.position().y, finger.start_position().x, finger.start_position().y, ); } for finger in touches.iter_just_released() { println!("Touch with ID {} just ended.", finger.id()); } for finger in touches.iter_just_canceled() { println!("Touch with ID {} was canceled.", finger.id()); } } ``` -------------------------------- ### Registering Systems with Bevy App Source: https://bevy-cheatbook.github.io/fundamentals/async-compute.html Registers the `setup_net_session` system to run at startup and the `tell_the_net_task_what_to_do` and `handle_net_updates` systems for fixed-update intervals. ```rust app.add_systems(Startup, setup_net_session); app.add_systems(FixedUpdate, ( tell_the_net_task_what_to_do, handle_net_updates, )); ``` -------------------------------- ### Install MINGW-w64 via Homebrew Source: https://bevy-cheatbook.github.io/setup/cross/macos-windows.html Installs the MINGW-w64 environment, which is required by the GNU toolchain for Windows development. This command assumes you have Homebrew installed. ```bash brew install mingw-w64 ``` -------------------------------- ### Install GNOME Character Map in WSL2 Source: https://bevy-cheatbook.github.io/platforms/windows/wsl2.html Installs the GNOME Character Map application using apt. This is recommended to ensure all necessary dependencies for a Linux GUI environment, including OpenGL support, are installed in WSL2. ```shell sudo apt install gucharmap # the GNOME Character Map app ``` -------------------------------- ### Setting Up GPU Resources in Bevy's Prepare Stage Source: https://bevy-cheatbook.github.io/gpu/stages.html Shows how to use the Prepare stage for setting up GPU resources such as buffers and textures. This stage is essential for any custom rendering that requires GPU-side data. ```rust // Example of preparing GPU resources // In the Prepare stage, create GPU buffers, textures, bind groups, etc. fn prepare_gpu_resources(mut gpu_buffers: ResMut, render_device: Res) { let buffer = render_device.create_buffer(...); gpu_buffers.add(buffer); } ``` -------------------------------- ### Runtime Panic Example Source: https://bevy-cheatbook.github.io/programming/paramset.html This is an example of the runtime panic message that occurs when a Bevy ECS system has conflicting mutable system parameters. ```text thread 'main' panicked at bevy_ecs/src/system/system_param.rs:225:5: error[B0001]: Query<&mut game::Health, bevy_ecs::query::filter::With> in system game::reset_health accesses component(s) game::Health in a way that conflicts with a previous system parameter. Consider using `Without` to create disjoint Queries or merging conflicting Queries into a `ParamSet`. ``` -------------------------------- ### Install CMake via Homebrew Source: https://bevy-cheatbook.github.io/setup/cross/macos-windows.html Installs CMake, a build system generator, using Homebrew. CMake is a dependency for compiling LLD from source. ```bash brew install cmake ``` -------------------------------- ### Manually Add Apply Deferred Systems Source: https://bevy-cheatbook.github.io/programming/schedules.html Demonstrates how to manually create sync points by adding `apply_deferred` systems within the Update schedule, specifying their order relative to other systems. ```rust app.add_systems( Update, apply_deferred .after(MyGameplaySet) .before(MyUiSet) ); app.add_systems(Update, ( ( system_a, apply_deferred, system_b, ).chain(), )); ``` -------------------------------- ### Generate and open local Bevy documentation Source: https://bevy-cheatbook.github.io/setup/getting-started.html Generates all HTML documentation for your project and its dependencies, then opens it in your web browser. This is useful for offline API searching. ```bash cargo doc --open ``` -------------------------------- ### Install WASM Target for Rust Source: https://bevy-cheatbook.github.io/platforms/wasm.html Add WASM support to your Rust installation using rustup. This is a prerequisite for building Bevy projects for the web. ```bash rustup target install wasm32-unknown-unknown ``` -------------------------------- ### Install wasm-bindgen-cli Source: https://bevy-cheatbook.github.io/platforms/wasm/webpage.html Install the wasm-bindgen command-line interface using cargo. This tool is necessary for preparing Rust WASM binaries for web integration. ```bash cargo install wasm-bindgen-cli ``` -------------------------------- ### Example Log Messages Source: https://bevy-cheatbook.github.io/fundamentals/log.html This is an example of log messages that can appear in the console when running a Bevy project. These messages can originate from Bevy itself, its dependencies, or your own code. ```text 2022-06-12T13:28:25.445644Z WARN wgpu_hal::vulkan::instance: Unable to find layer: VK_LAYER_KHRONOS_validation 2022-06-12T13:28:25.565795Z INFO bevy_render::renderer: AdapterInfo { name: "AMD Radeon RX 6600 XT", vendor: 4098, device: 29695, device_type: DiscreteGpu, backend: Vulkan } 2022-06-12T13:28:25.565795Z INFO mygame: Entered new map area. ``` -------------------------------- ### Update Rust Installation Source: https://bevy-cheatbook.github.io/pitfalls/build-errors.html Ensure your Rust installation is up-to-date using rustup. Bevy officially supports the latest stable or nightly versions of Rust. ```bash rustup update ``` -------------------------------- ### Initializing System Data with Closures in Bevy Source: https://bevy-cheatbook.github.io/programming/local.html Shows how to use a closure to initialize and pass custom data into a Bevy system. This is useful when `Local`'s default initialization is insufficient. ```rust #[derive(Default)] struct MyConfig { magic: usize, } fn my_system( mut cmd: Commands, my_res: Res, // note this isn't a valid system parameter config: &MyConfig, ) { // TODO: do stuff } fn main() { let config = MyConfig { magic: 420, }; App::new() .add_plugins(DefaultPlugins) // create a "move closure", so we can use the `config` // variable that we created above // Note: we specify the regular system parameters we need. // The closure needs to be a valid Bevy system. .add_systems(Update, move |cmd: Commands, res: Res| { // call our function from inside the closure, // passing in the system params + our custom value my_system(cmd, res, &config); }) .run(); } ``` -------------------------------- ### Create a custom DMG with create-dmg Source: https://bevy-cheatbook.github.io/platforms/macos.html This command demonstrates how to create a DMG file with custom volume name, icon, background, and application placement. Ensure the specified files and paths exist. ```bash create-dmg \ --volname "My Bevy Game" \ --volicon "AppIcon.icns" \ --background "DMG-background.png" \ --window-size 800 400 \ --icon-size 128 \ --icon "MyGame.app" 200 200 \ --hide-extension "MyGame.app" \ --app-drop-link 600 200 \ "mybevygame_release_mac.dmg" \ "build/mac/" ``` -------------------------------- ### Set Custom Window Icon in Bevy Source: https://bevy-cheatbook.github.io/window/icon.html This example demonstrates how to set a custom window icon from a PNG file using Bevy's startup system and the winit crate. It bypasses Bevy's asset system for direct file loading. Ensure 'winit' and 'image' are added to your project's dependencies with versions compatible with your Bevy version. ```rust use bevy::winit::WinitWindows; use winit::window::Icon; fn set_window_icon( // we have to use `NonSend` here windows: NonSend, ) { // here we use the `image` crate to load our icon data from a png file // this is not a very bevy-native solution, but it will do let (icon_rgba, icon_width, icon_height) = { let image = image::open("my_icon.png") .expect("Failed to open icon path") .into_rgba8(); let (width, height) = image.dimensions(); let rgba = image.into_raw(); (rgba, width, height) }; let icon = Icon::from_rgba(icon_rgba, icon_width, icon_height).unwrap(); // do it for all windows for window in windows.windows.values() { window.set_window_icon(Some(icon.clone())); } } fn main() { App::new() .add_plugins(DefaultPlugins) .add_systems(Startup, set_window_icon) .run(); } ``` -------------------------------- ### System to Spawn the Pan-Orbit Camera Source: https://bevy-cheatbook.github.io/cookbook/pan-orbit-camera.html A Bevy startup system that spawns a `PanOrbitCameraBundle` with custom initial state values for its center, radius, pitch, and yaw. This system should be added to the Bevy app's startup schedule. ```rust fn spawn_camera(mut commands: Commands) { let mut camera = PanOrbitCameraBundle::default(); // Position our camera using our component, // not Transform (it would get overwritten) camera.state.center = Vec3::new(1.0, 2.0, 3.0); camera.state.radius = 50.0; camera.state.pitch = 15.0f32.to_radians(); camera.state.yaw = 30.0f32.to_radians(); commands.spawn(camera); } ``` -------------------------------- ### Create a new Rust project Source: https://bevy-cheatbook.github.io/setup/getting-started.html Use this command to create a new Rust project for your Bevy game. ```bash cargo new --bin my_game ``` -------------------------------- ### Get Mouse Cursor World Position (Single Window) Source: https://bevy-cheatbook.github.io/print.html Use this system to get the mouse cursor's world position when you have only one window. It requires the `PrimaryWindow` component and a `MainCamera` component. ```rust use bevy::window::PrimaryWindow; /// We will store the world position of the mouse cursor here. #[derive(Resource, Default)] struct MyWorldCoords(Vec2); /// Used to help identify our main camera #[derive(Component)] struct MainCamera; fn setup(mut commands: Commands) { // Make sure to add the marker component when you set up your camera commands.spawn((Camera2dBundle::default(), MainCamera)); } fn my_cursor_system( mut mycoords: ResMut, // query to get the window (so we can read the current cursor position) q_window: Query<&Window, With>, // query to get camera transform q_camera: Query<(&Camera, &GlobalTransform), With>, ) { // get the camera info and transform // assuming there is exactly one main camera entity, so Query::single() is OK let (camera, camera_transform) = q_camera.single(); // There is only one primary window, so we can similarly get it from the query: let window = q_window.single(); // check if the cursor is inside the window and get its position // then, ask bevy to convert into world coordinates, and truncate to discard Z if let Some(world_position) = window.cursor_position() .and_then(|cursor| camera.viewport_to_world(camera_transform, cursor)) .map(|ray| ray.origin.truncate()) { mycoords.0 = world_position; eprintln!("World coords: {}/{}", world_position.x, world_position.y); } } ``` ```rust app.init_resource::(); app.add_systems(Startup, setup); app.add_systems(Update, my_cursor_system); ``` -------------------------------- ### Enable LSP Auto-Highlight and Signature Help Source: https://bevy-cheatbook.github.io/setup/editor/kak.html Enables automatic highlighting of symbols under the cursor and automatic display of function signature help. Add these to your ~/.config/kak/kakrc file. ```kakoune # automatically highlight the symbol under the cursor to show where it is used set global lsp_auto_highlight_references true # automatically show help for function signatures lsp-auto-signature-help-enable ``` -------------------------------- ### Get Mouse Cursor World Coordinates (Single Window) Source: https://bevy-cheatbook.github.io/cookbook/cursor2world.html Use this system to get the mouse cursor's position in world coordinates for the primary window. Ensure `MyWorldCoords` resource and `MainCamera` component are initialized. ```rust use bevy::window::PrimaryWindow; /// We will store the world position of the mouse cursor here. #[derive(Resource, Default)] struct MyWorldCoords(Vec2); /// Used to help identify our main camera #[derive(Component)] struct MainCamera; fn setup(mut commands: Commands) { // Make sure to add the marker component when you set up your camera commands.spawn((Camera2dBundle::default(), MainCamera)); } fn my_cursor_system( mut mycoords: ResMut, // query to get the window (so we can read the current cursor position) q_window: Query<&Window, With>, // query to get camera transform q_camera: Query<(&Camera, &GlobalTransform), With>, ) { // get the camera info and transform // assuming there is exactly one main camera entity, so Query::single() is OK let (camera, camera_transform) = q_camera.single(); // There is only one primary window, so we can similarly get it from the query: let window = q_window.single(); // check if the cursor is inside the window and get its position // then, ask bevy to convert into world coordinates, and truncate to discard Z if let Some(world_position) = window.cursor_position() .and_then(|cursor| camera.viewport_to_world(camera_transform, cursor)) .map(|ray| ray.origin.truncate()) { mycoords.0 = world_position; eprintln!("World coords: {}/{}", world_position.x, world_position.y); } } ``` ```rust app.init_resource::(); app.add_systems(Startup, setup); app.add_systems(Update, my_cursor_system); ``` -------------------------------- ### Manage Resources with Commands Source: https://bevy-cheatbook.github.io/programming/res.html Use the `Commands` struct to insert, initialize, or remove resources at runtime. `insert_resource` adds or overwrites, `init_resource` creates if it doesn't exist, and `remove_resource` deletes it. ```rust __ fn my_setup(mut commands: Commands, /* ... */) { // add (or overwrite if existing) a resource, with the given value commands.insert_resource(GoalsReached { main_goal: false, bonus: 100 }); // ensure resource exists (create it with its default value if necessary) commands.init_resource::(); // remove a resource (if it exists) commands.remove_resource::(); } ``` -------------------------------- ### Get Mouse Cursor World Coordinates (Multi-Window) Source: https://bevy-cheatbook.github.io/cookbook/cursor2world.html This system handles getting mouse cursor world coordinates for multiple windows by iterating through cameras and checking their associated render target. It requires adding the `WorldCursorCoords` component to each camera. ```rust use bevy::render::camera::RenderTarget; use bevy::window::WindowRef; /// We will add this to each camera we want to compute cursor position for. /// Add the component to the camera that renders to each window. #[derive(Component, Default)] struct WorldCursorCoords(Vec2); fn setup_multiwindow(mut commands: Commands) { // TODO: set up multiple cameras for multiple windows. // See bevy's example code for how to do that. // Make sure we add our component to each camera commands.spawn((Camera2dBundle::default(), WorldCursorCoords::default())); } fn my_cursor_system_multiwindow( // query to get the primary window q_window_primary: Query<&Window, With>, // query to get other windows q_window: Query<&Window>, // query to get camera transform mut q_camera: Query<(&Camera, &GlobalTransform, &mut WorldCursorCoords)>, ) { for (camera, camera_transform, mut worldcursor) in &mut q_camera { // get the window the camera is rendering to let window = match camera.target { // the camera is rendering to the primary window RenderTarget::Window(WindowRef::Primary) => { q_window_primary.single() }, // the camera is rendering to some other window RenderTarget::Window(WindowRef::Entity(e_window)) => { q_window.get(e_window).unwrap() }, // the camera is rendering to something else (like a texture), not a window _ => { // skip this camera continue; } }; // check if the cursor is inside the window and get its position // then, ask bevy to convert into world coordinates, and truncate to discard Z if let Some(world_position) = window.cursor_position() .and_then(|cursor| camera.viewport_to_world(camera_transform, cursor)) .map(|ray| ray.origin.truncate()) { worldcursor.0 = world_position; } } } ``` ```rust app.add_systems(Startup, setup_multiwindow); app.add_systems(Update, my_cursor_system_multiwindow); ``` -------------------------------- ### Using Local Resources in Bevy Systems Source: https://bevy-cheatbook.github.io/programming/local.html Demonstrates how to use `Local` to manage per-system data. Each system receives a separate instance of the `Local` data. ```rust #[derive(Default)] struct MyState { // ... } fn my_system1(mut local: Local) { // you can do anything you want with the local here } fn my_system2(mut local: Local) { // the local in this system is a different instance } ``` -------------------------------- ### Install Vulkan Tools and Mesa Drivers in WSL2 Source: https://bevy-cheatbook.github.io/platforms/windows/wsl2.html Configures the system to use an updated version of Mesa graphics drivers via a PPA and installs Vulkan tools. This is necessary for Bevy applications that require Vulkan support beyond basic OpenGL. ```shell sudo add-apt-repository ppa:kisak/kisak-mesa sudo apt update sudo apt upgrade sudo apt install vulkan-tools ``` -------------------------------- ### Cargo.toml with Bevy dependency Source: https://bevy-cheatbook.github.io/setup/getting-started.html Example of how your Cargo.toml file should look after adding Bevy as a dependency with the 'wayland' feature. ```toml [package] name = "my_game" version = "0.1.0" edition = "2021" [dependencies] bevy = { version = "0.16", features = ["wayland"] } ``` -------------------------------- ### Configure Bevy Dependencies Source: https://bevy-cheatbook.github.io/setup/bevy-config.html Specify Bevy version in Cargo.toml to manage dependencies. This is a common setup for Bevy projects. ```toml __ [dependencies.bevy] version = "0.12" ``` -------------------------------- ### Set Winit Backend to X11 Source: https://bevy-cheatbook.github.io/platforms/linux.html Use this environment variable to force Bevy applications to run using the X11 or XWayland compatibility layer, even on a Wayland desktop. Useful for troubleshooting or when native Wayland support is not required. ```bash export WINIT_UNIX_BACKEND=x11 ```