fb607b1bd1
# Objective - Fixes #16292 ## Solution - Renames the `ColorText` marker to `AnimatedText`, which is more distinct from the `TextColor` Bevy component. - Changes the comment language from `A unit struct` to `Marker struct` for better consistency with other Bevy docs. ## Testing - Locally, example still runs just fine |
||
---|---|---|
.. | ||
2d | ||
3d | ||
animation | ||
app | ||
asset | ||
async_tasks | ||
audio | ||
camera | ||
dev_tools | ||
diagnostics | ||
ecs | ||
games | ||
gizmos | ||
helpers | ||
input | ||
math | ||
mobile | ||
movement | ||
picking | ||
reflection | ||
remote | ||
scene | ||
shader | ||
state | ||
stress_tests | ||
testbed | ||
time | ||
tools | ||
transforms | ||
ui | ||
wasm | ||
window | ||
hello_world.rs | ||
README.md |
Examples
These examples demonstrate the main features of Bevy and how to use them.
To run an example, use the command cargo run --example <Example>
, and add the option --features x11
or --features wayland
to force the example to run on a specific window compositor, e.g.
cargo run --features wayland --example hello_world
⚠️ Note: for users of releases on crates.io!
There are often large differences and incompatible API changes between the latest crates.io release and the development version of Bevy in the git main branch!
If you are using a released version of bevy, you need to make sure you are viewing the correct version of the examples!
- Latest release: https://github.com/bevyengine/bevy/tree/latest/examples
- Specific version, such as
0.4
: https://github.com/bevyengine/bevy/tree/v0.4.0/examples
When you clone the repo locally to run the examples, use git checkout
to get the correct version:
# `latest` always points to the newest release
git checkout latest
# or use a specific version
git checkout v0.4.0
Table of Contents
The Bare Minimum
Hello, World!
Example | Description |
---|---|
hello_world.rs |
Runs a minimal example that outputs "hello world" |
Cross-Platform Examples
2D Rendering
Example | Description |
---|---|
2D Bloom | Illustrates bloom post-processing in 2d |
2D Bounding Volume Intersections | Showcases bounding volumes and intersection tests |
2D Rotation | Demonstrates rotating entities in 2D with quaternions |
2D Shapes | Renders simple 2D primitive shapes like circles and polygons |
2D Viewport To World | Demonstrates how to use the Camera::viewport_to_world_2d method |
2D Wireframe | Showcases wireframes for 2d meshes |
Arc 2D Meshes | Demonstrates UV-mapping of the circular segment and sector primitives |
CPU Drawing | Manually read/write the pixels of a texture |
Custom glTF vertex attribute 2D | Renders a glTF mesh in 2D with a custom vertex attribute |
Manual Mesh 2D | Renders a custom mesh "manually" with "mid-level" renderer apis |
Mesh 2D | Renders a 2d mesh |
Mesh 2D With Vertex Colors | Renders a 2d mesh with vertex color attributes |
Mesh2d Alpha Mode | Used to test alpha modes with mesh2d |
Move Sprite | Changes the transform of a sprite |
Pixel Grid Snapping | Shows how to create graphics that snap to the pixel grid by rendering to a texture in 2D |
Sprite | Renders a sprite |
Sprite Animation | Animates a sprite in response to an event |
Sprite Flipping | Renders a sprite flipped along an axis |
Sprite Sheet | Renders an animated sprite |
Sprite Slice | Showcases slicing sprites into sections that can be scaled independently via the 9-patch technique |
Sprite Tile | Renders a sprite tiled in a grid |
Text 2D | Generates text in 2D |
Texture Atlas | Generates a texture atlas (sprite sheet) from individual sprites |
Transparency in 2D | Demonstrates transparency in 2d |
3D Rendering
Example | Description |
---|---|
3D Bloom | Illustrates bloom configuration using HDR and emissive materials |
3D Scene | Simple 3D scene with basic shapes and lighting |
3D Shapes | A scene showcasing the built-in 3D shapes |
3D Viewport To World | Demonstrates how to use the Camera::viewport_to_world method |
Animated Material | Shows how to animate material properties |
Anisotropy | Displays an example model with anisotropy |
Anti-aliasing | Compares different anti-aliasing methods |
Atmospheric Fog | A scene showcasing the atmospheric fog effect |
Auto Exposure | A scene showcasing auto exposure |
Blend Modes | Showcases different blend modes |
Built-in postprocessing | Demonstrates the built-in postprocessing features |
Camera sub view | Demonstrates using different sub view effects on a camera |
Clearcoat | Demonstrates the clearcoat PBR feature |
Color grading | Demonstrates color grading |
Deferred Rendering | Renders meshes with both forward and deferred pipelines |
Depth of field | Demonstrates depth of field |
Fog | A scene showcasing the distance fog effect |
Fog volumes | Demonstrates fog volumes |
Generate Custom Mesh | Simple showcase of how to generate a custom mesh with a custom texture |
Irradiance Volumes | Demonstrates irradiance volumes |
Lighting | Illustrates various lighting options in a simple scene |
Lightmaps | Rendering a scene with baked lightmaps |
Lines | Create a custom material to draw 3d lines |
Load glTF | Loads and renders a glTF file as a scene |
Load glTF extras | Loads and renders a glTF file as a scene, including the gltf extras |
Mesh Ray Cast | Demonstrates ray casting with the MeshRayCast system parameter |
Meshlet | Meshlet rendering for dense high-poly scenes (experimental) |
Motion Blur | Demonstrates per-pixel motion blur |
Order Independent Transparency | Demonstrates how to use OIT |
Orthographic View | Shows how to create a 3D orthographic view (for isometric-look in games or CAD applications) |
Parallax Mapping | Demonstrates use of a normal map and depth map for parallax mapping |
Parenting | Demonstrates parent->child relationships and relative transformations |
Percentage-closer soft shadows | Demonstrates percentage-closer soft shadows (PCSS) |
Physically Based Rendering | Demonstrates use of Physically Based Rendering (PBR) properties |
Query glTF primitives | Query primitives in a glTF scene |
Reflection Probes | Demonstrates reflection probes |
Render to Texture | Shows how to render to a texture, useful for mirrors, UI, or exporting images |
Rotate Environment Map | Demonstrates how to rotate the skybox and the environment map simultaneously |
Screen Space Ambient Occlusion | A scene showcasing screen space ambient occlusion |
Screen Space Reflections | Demonstrates screen space reflections with water ripples |
Scrolling fog | Demonstrates how to create the effect of fog moving in the wind |
Shadow Biases | Demonstrates how shadow biases affect shadows in a 3d scene |
Shadow Caster and Receiver | Demonstrates how to prevent meshes from casting/receiving shadows in a 3d scene |
Skybox | Load a cubemap texture onto a cube like a skybox and cycle through different compressed texture formats. |
Spherical Area Lights | Demonstrates how point light radius values affect light behavior |
Split Screen | Demonstrates how to render two cameras to the same window to accomplish "split screen" |
Spotlight | Illustrates spot lights |
Texture | Shows configuration of texture materials |
Tonemapping | Compares tonemapping options |
Transmission | Showcases light transmission in the PBR material |
Transparency in 3D | Demonstrates transparency in 3d |
Two Passes | Renders two 3d passes to the same window from different perspectives |
Update glTF Scene | Update a scene from a glTF file, either by spawning the scene as a child of another entity, or by accessing the entities of the scene |
Vertex Colors | Shows the use of vertex colors |
Visibility range | Demonstrates visibility ranges |
Volumetric fog | Demonstrates volumetric fog and lighting |
Wireframe | Showcases wireframe rendering |
Animation
Example | Description |
---|---|
Animated Fox | Plays an animation from a skinned glTF |
Animated Transform | Create and play an animation defined by code that operates on the Transform component |
Animated UI | Shows how to use animation clips to animate UI properties |
Animation Events | Demonstrate how to use animation events |
Animation Graph | Blends multiple animations together with a graph |
Animation Masks | Demonstrates animation masks |
Color animation | Demonstrates how to animate colors using mixing and splines in different color spaces |
Custom Skinned Mesh | Skinned mesh example with mesh and joints data defined in code |
Eased Motion | Demonstrates the application of easing curves to animate an object |
Easing Functions | Showcases the built-in easing functions |
Morph Targets | Plays an animation from a glTF file with meshes with morph targets |
glTF Skinned Mesh | Skinned mesh example with mesh and joints data loaded from a glTF file |
Application
Example | Description |
---|---|
Advanced log layers | Illustrate how to transfer data between log layers and Bevy's ECS |
Custom Loop | Demonstrates how to create a custom runner (to update an app manually) |
Drag and Drop | An example that shows how to handle drag and drop in an app |
Empty | An empty application (does nothing) |
Empty with Defaults | An empty application with default plugins |
Headless | An application that runs without default plugins |
Headless Renderer | An application that runs with no window, but renders into image file |
Log layers | Illustrate how to add custom log layers |
Logs | Illustrate how to use generate log output |
No Renderer | An application that runs with default plugins and displays an empty window, but without an actual renderer |
Plugin | Demonstrates the creation and registration of a custom plugin |
Plugin Group | Demonstrates the creation and registration of a custom plugin group |
Return after Run | Show how to return to main after the Bevy app has exited |
Thread Pool Resources | Creates and customizes the internal thread pool |
Without Winit | Create an application without winit (runs single time, no event loop) |
Assets
Example | Description |
---|---|
Alter Mesh | Shows how to modify the underlying asset of a Mesh after spawning. |
Alter Sprite | Shows how to modify texture assets after spawning. |
Asset Decompression | Demonstrates loading a compressed asset |
Asset Loading | Demonstrates various methods to load assets |
Asset Processing | Demonstrates how to process and load custom assets |
Asset Settings | Demonstrates various methods of applying settings when loading an asset |
Custom Asset | Implements a custom asset loader |
Custom Asset IO | Implements a custom AssetReader |
Embedded Asset | Embed an asset in the application binary and load it |
Extra asset source | Load an asset from a non-standard asset source |
Hot Reloading of Assets | Demonstrates automatic reloading of assets when modified on disk |
Mult-asset synchronization | Demonstrates how to wait for multiple assets to be loaded. |
Repeated texture configuration | How to configure the texture to repeat instead of the default clamp to edges |
Async Tasks
Example | Description |
---|---|
Async Compute | How to use AsyncComputeTaskPool to complete longer running tasks |
External Source of Data on an External Thread | How to use an external thread to run an infinite task and communicate with a channel |
Audio
Example | Description |
---|---|
Audio | Shows how to load and play an audio file |
Audio Control | Shows how to load and play an audio file, and control how it's played |
Decodable | Shows how to create and register a custom audio source by implementing the Decodable type. |
Pitch | Shows how to directly play a simple pitch |
Soundtrack | Shows how to play different soundtracks based on game state |
Spatial Audio 2D | Shows how to play spatial audio, and moving the emitter in 2D |
Spatial Audio 3D | Shows how to play spatial audio, and moving the emitter in 3D |
Camera
Example | Description |
---|---|
2D top-down camera | A 2D top-down camera smoothly following player movements |
Camera Orbit | Shows how to orbit a static scene using pitch, yaw, and roll. |
First person view model | A first-person camera that uses a world model and a view model with different field of views (FOV) |
Projection Zoom | Shows how to zoom orthographic and perspective projection cameras. |
Screen Shake | A simple 2D screen shake effect |
Dev tools
Example | Description |
---|---|
FPS overlay | Demonstrates FPS overlay |
Diagnostics
Example | Description |
---|---|
Custom Diagnostic | Shows how to create a custom diagnostic |
Enabling/disabling diagnostic | Shows how to disable/re-enable a Diagnostic during runtime |
Log Diagnostics | Add a plugin that logs diagnostics, like frames per second (FPS), to the console |
ECS (Entity Component System)
Example | Description |
---|---|
Change Detection | Change detection on components and resources |
Component Hooks | Define component hooks to manage component lifecycle events |
Custom Query Parameters | Groups commonly used compound queries and query filters into a single type |
Custom Schedule | Demonstrates how to add custom schedules |
Dynamic ECS | Dynamically create components, spawn entities with those components and query those components |
ECS Guide | Full guide to Bevy's ECS |
Event | Illustrates event creation, activation, and reception |
Fallible System Parameters | Systems are skipped if their parameters cannot be acquired |
Fixed Timestep | Shows how to create systems that run every fixed timestep, rather than every tick |
Generic System | Shows how to create systems that can be reused with different types |
Hierarchy | Creates a hierarchy of parents and children entities |
Iter Combinations | Shows how to iterate over combinations of query results |
Nondeterministic System Order | Systems run in parallel, but their order isn't always deterministic. Here's how to detect and fix this. |
Observer Propagation | Demonstrates event propagation with observers |
Observers | Demonstrates observers that react to events (both built-in life-cycle events and custom events) |
One Shot Systems | Shows how to flexibly run systems without scheduling them |
Parallel Query | Illustrates parallel queries with ParallelIterator |
Removal Detection | Query for entities that had a specific component removed earlier in the current frame |
Run Conditions | Run systems only when one or multiple conditions are met |
Send and receive events | Demonstrates how to send and receive events of the same type in a single system |
Startup System | Demonstrates a startup system (one that runs once when the app starts up) |
System Closure | Show how to use closures as systems, and how to configure Local variables by capturing external state |
System Parameter | Illustrates creating custom system parameters with SystemParam |
System Piping | Pipe the output of one system into a second, allowing you to handle any errors gracefully |
System Stepping | Demonstrate stepping through systems in order of execution. |
Games
Example | Description |
---|---|
Alien Cake Addict | Eat the cakes. Eat them all. An example 3D game |
Breakout | An implementation of the classic game "Breakout". |
Contributors | Displays each contributor as a bouncy bevy-ball! |
Desk Toy | Bevy logo as a desk toy using transparent windows! Now with Googly Eyes! |
Game Menu | A simple game menu |
Loading Screen | Demonstrates how to create a loading screen that waits for all assets to be loaded and render pipelines to be compiled. |
Gizmos
Example | Description |
---|---|
2D Gizmos | A scene showcasing 2D gizmos |
3D Gizmos | A scene showcasing 3D gizmos |
Axes | Demonstrates the function of axes gizmos |
Light Gizmos | A scene showcasing light gizmos |
Input
Example | Description |
---|---|
Char Input Events | Prints out all chars as they are inputted |
Gamepad Input | Shows handling of gamepad input, connections, and disconnections |
Gamepad Input Events | Iterates and prints gamepad input and connection events |
Gamepad Rumble | Shows how to rumble a gamepad using force feedback |
Keyboard Input | Demonstrates handling a key press/release |
Keyboard Input Events | Prints out all keyboard events |
Keyboard Modifiers | Demonstrates using key modifiers (ctrl, shift) |
Mouse Grab | Demonstrates how to grab the mouse, locking the cursor to the app's screen |
Mouse Input | Demonstrates handling a mouse button press/release |
Mouse Input Events | Prints out all mouse events (buttons, movement, etc.) |
Text Input | Simple text input with IME support |
Touch Input | Displays touch presses, releases, and cancels |
Touch Input Events | Prints out all touch inputs |
Math
Example | Description |
---|---|
Cubic Splines | Exhibits different modes of constructing cubic curves using splines |
Custom Primitives | Demonstrates how to add custom primitives and useful traits for them. |
Random Sampling | Demonstrates how to sample random points from mathematical primitives |
Rendering Primitives | Shows off rendering for all math primitives as both Meshes and Gizmos |
Sampling Primitives | Demonstrates all the primitives which can be sampled. |
Smooth Follow | Demonstrates how to make an entity smoothly follow another using interpolation |
Movement
Example | Description |
---|---|
Run physics in a fixed timestep | Handles input, physics, and rendering in an industry-standard way by using a fixed timestep |
Picking
Example | Description |
---|---|
Mesh Picking | Demonstrates picking meshes |
Showcases simple picking events and usage | Demonstrates how to use picking events to spawn simple objects |
Sprite Picking | Demonstrates picking sprites and sprite atlases |
Reflection
Example | Description |
---|---|
Custom Attributes | Registering and accessing custom attributes on reflected types |
Dynamic Types | How dynamic types are used with reflection |
Function Reflection | Demonstrates how functions can be called dynamically using reflection |
Generic Reflection | Registers concrete instances of generic types that may be used with reflection |
Reflection | Demonstrates how reflection in Bevy provides a way to dynamically interact with Rust types |
Reflection Types | Illustrates the various reflection types available |
Type Data | Demonstrates how to create and use type data |
Remote Protocol
Example | Description |
---|---|
client | A simple command line client that can control Bevy apps via the BRP |
server | A Bevy app that you can connect to with the BRP and edit |
Scene
Example | Description |
---|---|
Scene | Demonstrates loading from and saving scenes to files |
Shaders
These examples demonstrate how to implement different shaders in user code.
A shader in its most common usage is a small program that is run by the GPU per-vertex in a mesh (a vertex shader) or per-affected-screen-fragment (a fragment shader.) The GPU executes these programs in a highly parallel way.
There are also compute shaders which are used for more general processing leveraging the GPU's parallelism.
Example | Description |
---|---|
Animated | A shader that uses dynamic data like the time since startup |
Array Texture | A shader that shows how to reuse the core bevy PBR shading functionality in a custom material that obtains the base color from an array texture. |
Compute - Game of Life | A compute shader that simulates Conway's Game of Life |
Custom Vertex Attribute | A shader that reads a mesh's custom vertex attribute |
Custom phase item | Demonstrates how to enqueue custom draw commands in a render phase |
Extended Material | A custom shader that builds on the standard material |
GPU readback | A very simple compute shader that writes to a buffer that is read by the cpu |
Instancing | A shader that renders a mesh multiple times in one draw call using low level rendering api |
Instancing | Shows that multiple instances of a cube are automatically instanced in one draw call |
Material | A shader and a material that uses it |
Material | A shader and a material that uses it on a 2d mesh |
Material - GLSL | A shader that uses the GLSL shading language |
Material - Screenspace Texture | A shader that samples a texture with view-independent UV coordinates |
Material Prepass | A shader that uses the various textures generated by the prepass |
Post Processing - Custom Render Pass | A custom post processing effect, using a custom render pass that runs after the main pass |
Shader Defs | A shader that uses "shaders defs" (a bevy tool to selectively toggle parts of a shader) |
Specialized Mesh Pipeline | Demonstrates how to write a specialized mesh pipeline |
Storage Buffer | A shader that shows how to bind a storage buffer using a custom material. |
Texture Binding Array (Bindless Textures) | A shader that shows how to bind and sample multiple textures as a binding array (a.k.a. bindless textures). |
State
Example | Description |
---|---|
Computed States | Advanced state patterns using Computed States. |
Custom State Transition Behavior | Creating and working with custom state transition schedules. |
States | Illustrates how to use States to control transitioning from a Menu state to an InGame state. |
Sub States | Using Sub States for hierarchical state handling. |
Stress Tests
These examples are used to test the performance and stability of various parts of the engine in an isolated way.
Due to the focus on performance it's recommended to run the stress tests in release mode:
cargo run --release --example <example name>
Example | Description |
---|---|
Bevymark | A heavy sprite rendering workload to benchmark your system with Bevy |
Many Animated Sprites | Displays many animated sprites in a grid arrangement with slight offsets to their animation timers. Used for performance testing. |
Many Buttons | Test rendering of many UI elements |
Many Cubes | Simple benchmark to test per-entity draw overhead. Run with the sphere argument to test frustum culling |
Many Foxes | Loads an animated fox model and spawns lots of them. Good for testing skinned mesh performance. Takes an unsigned integer argument for the number of foxes to spawn. Defaults to 1000 |
Many Gizmos | Test rendering of many gizmos |
Many Glyphs | Simple benchmark to test text rendering. |
Many Lights | Simple benchmark to test rendering many point lights. Run with WGPU_SETTINGS_PRIO=webgl2 to restrict to uniform buffers and max 256 lights |
Many Sprites | Displays many sprites in a grid arrangement! Used for performance testing. Use --colored to enable color tinted sprites. |
Text Pipeline | Text Pipeline benchmark |
Transform Hierarchy | Various test cases for hierarchy and transform propagation performance |
Time
Example | Description |
---|---|
Time handling | Explains how Time is handled in ECS |
Timers | Illustrates ticking Timer resources inside systems and handling their state |
Virtual time | Shows how Time<Virtual> can be used to pause, resume, slow down and speed up a game. |
Tools
Example | Description |
---|---|
Gamepad Viewer | Shows a visualization of gamepad buttons, sticks, and triggers |
Scene Viewer | A simple way to view glTF models with Bevy. Just run cargo run --release --example scene_viewer /path/to/model.gltf#Scene0 , replacing the path as appropriate. With no arguments it will load the FieldHelmet glTF model from the repository assets subdirectory |
Transforms
Example | Description |
---|---|
3D Rotation | Illustrates how to (constantly) rotate an object around an axis |
Alignment | A demonstration of Transform's axis-alignment feature |
Scale | Illustrates how to scale an object in each direction |
Transform | Shows multiple transformations of objects |
Translation | Illustrates how to move an object along an axis |
UI (User Interface)
Example | Description |
---|---|
Borders | Demonstrates how to create a node with a border |
Box Shadow | Demonstrates how to create a node with a shadow |
Button | Illustrates creating and updating a button |
CSS Grid | An example for CSS Grid layout |
Display and Visibility | Demonstrates how Display and Visibility work in the UI. |
Flex Layout | Demonstrates how the AlignItems and JustifyContent properties can be composed to layout nodes and position text |
Font Atlas Debug | Illustrates how FontAtlases are populated (used to optimize text rendering internally) |
Ghost Nodes | Demonstrates the use of Ghost Nodes to skip entities in the UI layout hierarchy |
Overflow | Simple example demonstrating overflow behavior |
Overflow Clip Margin | Simple example demonstrating the OverflowClipMargin style property |
Overflow and Clipping Debug | An example to debug overflow and clipping behavior |
Relative Cursor Position | Showcases the RelativeCursorPosition component |
Render UI to Texture | An example of rendering UI as a part of a 3D world |
Scroll | Demonstrates scrolling UI containers |
Size Constraints | Demonstrates how the to use the size constraints to control the size of a UI node. |
Text | Illustrates creating and updating text |
Text Debug | An example for debugging text layout |
Text Wrap Debug | Demonstrates text wrapping |
Transparency UI | Demonstrates transparency for UI |
UI Material | Demonstrates creating and using custom Ui materials |
UI Scaling | Illustrates how to scale the UI |
UI Texture Atlas | Illustrates how to use TextureAtlases in UI |
UI Texture Atlas Slice | Illustrates how to use 9 Slicing for TextureAtlases in UI |
UI Texture Slice | Illustrates how to use 9 Slicing in UI |
UI Texture Slice Flipping and Tiling | Illustrates how to flip and tile images with 9 Slicing in UI |
UI Z-Index | Demonstrates how to control the relative depth (z-position) of UI elements |
Viewport Debug | An example for debugging viewport coordinates |
Window Fallthrough | Illustrates how to access winit::window::Window 's hittest functionality. |
Window
Example | Description |
---|---|
Clear Color | Creates a solid color window |
Custom User Event | Handles custom user events within the event loop |
Low Power | Demonstrates settings to reduce power use for bevy applications |
Monitor info | Displays information about available monitors (displays). |
Multiple Windows | Demonstrates creating multiple windows, and rendering to them |
Scale Factor Override | Illustrates how to customize the default window settings |
Screenshot | Shows how to save screenshots to disk |
Transparent Window | Illustrates making the window transparent and hiding the window decoration |
Window Drag Move | Demonstrates drag move and drag resize without window decoration |
Window Resizing | Demonstrates resizing and responding to resizing a window |
Window Settings | Demonstrates customizing default window settings |
Tests
Example | Description |
---|---|
How to Test Systems | How to test systems with commands, queries or resources |
Platform-Specific Examples
Android
Setup
rustup target add aarch64-linux-android
cargo install cargo-ndk
The Android SDK must be installed, and the environment variable ANDROID_SDK_ROOT
set to the root Android sdk
folder.
When using NDK (Side by side)
, the environment variable ANDROID_NDK_ROOT
must also be set to one of the NDKs in sdk\ndk\[NDK number]
.
Alternatively, you can install Android Studio.
Build & Run
To build an Android app, you first need to build shared object files for the target architecture with cargo-ndk
:
cargo ndk -t <target_name> -o <project_name>/app/src/main/jniLibs build
For example, to compile to a 64-bit ARM platform:
cargo ndk -t arm64-v8a -o android_example/app/src/main/jniLibs build
Setting the output path ensures the shared object files can be found in target-specific directories under jniLibs
where the JNI can find them.
See the cargo-ndk
README for other options.
After this you can build it with gradlew
:
./gradlew build
Or build it with Android Studio.
Then you can test it in your Android project.
About libc++_shared.so
Bevy may require libc++_shared.so
to run on Android, as it is needed by the oboe
crate, but typically cargo-ndk
does not copy this file automatically.
To include it, you can manually obtain it from NDK source or use a build.rs
script for automation, as described in the cargo-ndk
README.
Alternatively, you can modify project files to include it when building an APK. To understand the specific steps taken in this project, please refer to the comments within the project files for detailed instructions(app/CMakeList.txt
, app/build.gradle
, app/src/main/cpp/dummy.cpp
).
Debugging
You can view the logs with the following command:
adb logcat | grep 'RustStdoutStderr\|bevy\|wgpu'
In case of an error getting a GPU or setting it up, you can try settings logs of wgpu_hal
to DEBUG
to get more information.
Sometimes, running the app complains about an unknown activity. This may be fixed by uninstalling the application:
adb uninstall org.bevyengine.example
Old phones
In its examples, Bevy targets the minimum Android API that Play Store
requires to upload and update apps.
Users of older phones may want to use an older API when testing. By default, Bevy uses GameAvtivity
, which only works for Android API level 31 and higher, so if you want to use older API, you need to switch to NativeActivity
.
To use NativeActivity
, you need to edit it in cargo.toml
manually like this:
bevy = { version = "0.14", default-features = false, features = ["android-native-activity", ...] }
Then build it as the Build & Run section stated above.
About cargo-apk
You can also build an APK with cargo-apk
, a simpler and deprecated tool which doesn't support GameActivity
. If you want to use this, there is a folder inside the mobile example with instructions.
Example | File | Description |
---|---|---|
android |
mobile/src/lib.rs |
A 3d Scene with a button and playing sound |
iOS
Setup
You need to install the correct rust targets:
aarch64-apple-ios
: iOS devicesx86_64-apple-ios
: iOS simulator on x86 processorsaarch64-apple-ios-sim
: iOS simulator on Apple processors
rustup target add aarch64-apple-ios x86_64-apple-ios aarch64-apple-ios-sim
Build & Run
Using bash:
cd examples/mobile
make run
In an ideal world, this will boot up, install and run the app for the first
iOS simulator in your xcrun simctl list devices
. If this fails, you can
specify the simulator device UUID via:
DEVICE_ID=${YOUR_DEVICE_ID} make run
If you'd like to see xcode do stuff, you can run
open bevy_mobile_example.xcodeproj/
which will open xcode. You then must push the zoom zoom play button and wait for the magic.
Example | File | Description |
---|---|---|
ios |
mobile/src/lib.rs |
A 3d Scene with a button and playing sound |
Wasm
Setup
rustup target add wasm32-unknown-unknown
cargo install wasm-bindgen-cli
Build & Run
Following is an example for lighting
. For other examples, change the lighting
in the
following commands.
cargo build --release --example lighting --target wasm32-unknown-unknown
wasm-bindgen --out-name wasm_example \
--out-dir examples/wasm/target \
--target web target/wasm32-unknown-unknown/release/examples/lighting.wasm
The first command will build the example for the wasm target, creating a binary. Then,
wasm-bindgen-cli is used to create
javascript bindings to this wasm file in the output file examples/wasm/target/wasm_example.js
, which can be loaded using this
example HTML file.
Then serve examples/wasm
directory to browser. i.e.
# cargo install basic-http-server
basic-http-server examples/wasm
# with python
python3 -m http.server --directory examples/wasm
# with ruby
ruby -run -ehttpd examples/wasm
WebGL2 and WebGPU
Bevy support for WebGPU is being worked on, but is currently experimental.
To build for WebGPU, you'll need to enable the webgpu
feature. This will override the webgl2
feature, and builds with the webgpu
feature enabled won't be able to run on browsers that don't support WebGPU.
Bevy has an helper to build its examples:
- Build for WebGL2:
cargo run -p build-wasm-example -- --api webgl2 load_gltf
- Build for WebGPU:
cargo run -p build-wasm-example -- --api webgpu load_gltf
This helper will log the command used to build the examples.
Audio in the browsers
For the moment, everything is single threaded, this can lead to stuttering when playing audio in browsers. Not all browsers react the same way for all games, you will have to experiment for your game.
In browsers, audio is not authorized to start without being triggered by an user interaction. This is to avoid multiple tabs all starting to auto play some sounds. You can find more context and explanation for this on Google Chrome blog. This page also describes a JS workaround to resume audio as soon as the user interact with your game.
Optimizing
On the web, it's useful to reduce the size of the files that are distributed. With rust, there are many ways to improve your executable sizes, starting with the steps described in the quick-start guide.
Now, when building the executable, use --profile wasm-release
instead of --release
:
cargo build --profile wasm-release --example lighting --target wasm32-unknown-unknown
To apply wasm-opt
, first locate the .wasm
file generated in the --out-dir
of the
earlier wasm-bindgen-cli
command (the filename should end with _bg.wasm
), then run:
wasm-opt -Oz --output optimized.wasm examples/wasm/target/lighting_bg.wasm
mv optimized.wasm examples/wasm/target/lighting_bg.wasm
Make sure your final executable size is actually smaller. Some optimizations may not be worth keeping due to compilation time increases.
For a small project with a basic 3d model and two lights, the generated file sizes are, as of July 2022, as follows:
profile | wasm-opt | no wasm-opt |
---|---|---|
Default | 8.5M | 13.0M |
opt-level = "z" | 6.1M | 12.7M |
"z" + lto = "thin" | 5.9M | 12M |
"z" + lto = "fat" | 5.1M | 9.4M |
"z" + "thin" + codegen-units = 1 | 5.3M | 11M |
"z" + "fat" + codegen-units = 1 | 4.8M | 8.5M |
Loading Assets
To load assets, they need to be available in the folder examples/wasm/assets. Cloning this repository will set it up as a symlink on Linux and macOS, but you will need to manually move the assets on Windows.