bevy/examples
Alice Cecile 206c7ce219 Migrate engine to Schedule v3 (#7267)
Huge thanks to @maniwani, @devil-ira, @hymm, @cart, @superdump and @jakobhellermann for the help with this PR.

# Objective

- Followup #6587.
- Minimal integration for the Stageless Scheduling RFC: https://github.com/bevyengine/rfcs/pull/45

## Solution

- [x]  Remove old scheduling module
- [x] Migrate new methods to no longer use extension methods
- [x] Fix compiler errors
- [x] Fix benchmarks
- [x] Fix examples
- [x] Fix docs
- [x] Fix tests

## Changelog

### Added

- a large number of methods on `App` to work with schedules ergonomically
- the `CoreSchedule` enum
- `App::add_extract_system` via the `RenderingAppExtension` trait extension method
- the private `prepare_view_uniforms` system now has a public system set for scheduling purposes, called `ViewSet::PrepareUniforms`

### Removed

- stages, and all code that mentions stages
- states have been dramatically simplified, and no longer use a stack
- `RunCriteriaLabel`
- `AsSystemLabel` trait
- `on_hierarchy_reports_enabled` run criteria (now just uses an ad hoc resource checking run condition)
- systems in `RenderSet/Stage::Extract` no longer warn when they do not read data from the main world
- `RunCriteriaLabel`
- `transform_propagate_system_set`: this was a nonstandard pattern that didn't actually provide enough control. The systems are already `pub`: the docs have been updated to ensure that the third-party usage is clear.

### Changed

- `System::default_labels` is now `System::default_system_sets`.
- `App::add_default_labels` is now `App::add_default_sets`
- `CoreStage` and `StartupStage` enums are now `CoreSet` and `StartupSet`
- `App::add_system_set` was renamed to `App::add_systems`
- The `StartupSchedule` label is now defined as part of the `CoreSchedules` enum
-  `.label(SystemLabel)` is now referred to as `.in_set(SystemSet)`
- `SystemLabel` trait was replaced by `SystemSet`
- `SystemTypeIdLabel<T>` was replaced by `SystemSetType<T>`
- The `ReportHierarchyIssue` resource now has a public constructor (`new`), and implements `PartialEq`
- Fixed time steps now use a schedule (`CoreSchedule::FixedTimeStep`) rather than a run criteria.
- Adding rendering extraction systems now panics rather than silently failing if no subapp with the `RenderApp` label is found.
- the `calculate_bounds` system, with the `CalculateBounds` label, is now in `CoreSet::Update`, rather than in `CoreSet::PostUpdate` before commands are applied. 
- `SceneSpawnerSystem` now runs under `CoreSet::Update`, rather than `CoreStage::PreUpdate.at_end()`.
- `bevy_pbr::add_clusters` is no longer an exclusive system
- the top level `bevy_ecs::schedule` module was replaced with `bevy_ecs::scheduling`
- `tick_global_task_pools_on_main_thread` is no longer run as an exclusive system. Instead, it has been replaced by `tick_global_task_pools`, which uses a `NonSend` resource to force running on the main thread.

## Migration Guide

- Calls to `.label(MyLabel)` should be replaced with `.in_set(MySet)`
- Stages have been removed. Replace these with system sets, and then add command flushes using the `apply_system_buffers` exclusive system where needed.
- The `CoreStage`, `StartupStage, `RenderStage` and `AssetStage`  enums have been replaced with `CoreSet`, `StartupSet, `RenderSet` and `AssetSet`. The same scheduling guarantees have been preserved.
  - Systems are no longer added to `CoreSet::Update` by default. Add systems manually if this behavior is needed, although you should consider adding your game logic systems to `CoreSchedule::FixedTimestep` instead for more reliable framerate-independent behavior.
  - Similarly, startup systems are no longer part of `StartupSet::Startup` by default. In most cases, this won't matter to you.
  - For example, `add_system_to_stage(CoreStage::PostUpdate, my_system)` should be replaced with 
  - `add_system(my_system.in_set(CoreSet::PostUpdate)`
- When testing systems or otherwise running them in a headless fashion, simply construct and run a schedule using `Schedule::new()` and `World::run_schedule` rather than constructing stages
- Run criteria have been renamed to run conditions. These can now be combined with each other and with states.
- Looping run criteria and state stacks have been removed. Use an exclusive system that runs a schedule if you need this level of control over system control flow.
- For app-level control flow over which schedules get run when (such as for rollback networking), create your own schedule and insert it under the `CoreSchedule::Outer` label.
- Fixed timesteps are now evaluated in a schedule, rather than controlled via run criteria. The `run_fixed_timestep` system runs this schedule between `CoreSet::First` and `CoreSet::PreUpdate` by default.
- Command flush points introduced by `AssetStage` have been removed. If you were relying on these, add them back manually.
- Adding extract systems is now typically done directly on the main app. Make sure the `RenderingAppExtension` trait is in scope, then call `app.add_extract_system(my_system)`.
- the `calculate_bounds` system, with the `CalculateBounds` label, is now in `CoreSet::Update`, rather than in `CoreSet::PostUpdate` before commands are applied. You may need to order your movement systems to occur before this system in order to avoid system order ambiguities in culling behavior.
- the `RenderLabel` `AppLabel` was renamed to `RenderApp` for clarity
- `App::add_state` now takes 0 arguments: the starting state is set based on the `Default` impl.
- Instead of creating `SystemSet` containers for systems that run in stages, simply use `.on_enter::<State::Variant>()` or its `on_exit` or `on_update` siblings.
- `SystemLabel` derives should be replaced with `SystemSet`. You will also need to add the `Debug`, `PartialEq`, `Eq`, and `Hash` traits to satisfy the new trait bounds.
- `with_run_criteria` has been renamed to `run_if`. Run criteria have been renamed to run conditions for clarity, and should now simply return a bool.
- States have been dramatically simplified: there is no longer a "state stack". To queue a transition to the next state, call `NextState::set`

## TODO

- [x] remove dead methods on App and World
- [x] add `App::add_system_to_schedule` and `App::add_systems_to_schedule`
- [x] avoid adding the default system set at inappropriate times
- [x] remove any accidental cycles in the default plugins schedule
- [x] migrate benchmarks
- [x] expose explicit labels for the built-in command flush points
- [x] migrate engine code
- [x] remove all mentions of stages from the docs
- [x] verify docs for States
- [x] fix uses of exclusive systems that use .end / .at_start / .before_commands
- [x] migrate RenderStage and AssetStage
- [x] migrate examples
- [x] ensure that transform propagation is exported in a sufficiently public way (the systems are already pub)
- [x] ensure that on_enter schedules are run at least once before the main app
- [x] re-enable opt-in to execution order ambiguities
- [x] revert change to `update_bounds` to ensure it runs in `PostUpdate`
- [x] test all examples
  - [x] unbreak directional lights
  - [x] unbreak shadows (see 3d_scene, 3d_shape, lighting, transparaency_3d examples)
  - [x] game menu example shows loading screen and menu simultaneously
  - [x] display settings menu is a blank screen
  - [x] `without_winit` example panics
- [x] ensure all tests pass
  - [x] SubApp doc test fails
  - [x] runs_spawn_local tasks fails
  - [x] [Fix panic_when_hierachy_cycle test hanging](https://github.com/alice-i-cecile/bevy/pull/120)

## Points of Difficulty and Controversy

**Reviewers, please give feedback on these and look closely**

1.  Default sets, from the RFC, have been removed. These added a tremendous amount of implicit complexity and result in hard to debug scheduling errors. They're going to be tackled in the form of "base sets" by @cart in a followup.
2. The outer schedule controls which schedule is run when `App::update` is called.
3. I implemented `Label for `Box<dyn Label>` for our label types. This enables us to store schedule labels in concrete form, and then later run them. I ran into the same set of problems when working with one-shot systems. We've previously investigated this pattern in depth, and it does not appear to lead to extra indirection with nested boxes.
4. `SubApp::update` simply runs the default schedule once. This sucks, but this whole API is incomplete and this was the minimal changeset.
5. `time_system` and `tick_global_task_pools_on_main_thread` no longer use exclusive systems to attempt to force scheduling order
6. Implemetnation strategy for fixed timesteps
7. `AssetStage` was migrated to `AssetSet` without reintroducing command flush points. These did not appear to be used, and it's nice to remove these bottlenecks.
8. Migration of `bevy_render/lib.rs` and pipelined rendering. The logic here is unusually tricky, as we have complex scheduling requirements.

## Future Work (ideally before 0.10)

- Rename schedule_v3 module to schedule or scheduling
- Add a derive macro to states, and likely a `EnumIter` trait of some form
- Figure out what exactly to do with the "systems added should basically work by default" problem
- Improve ergonomics for working with fixed timesteps and states
- Polish FixedTime API to match Time
- Rebase and merge #7415
- Resolve all internal ambiguities (blocked on better tools, especially #7442)
- Add "base sets" to replace the removed default sets.
2023-02-06 02:04:50 +00:00
..
2d Migrate engine to Schedule v3 (#7267) 2023-02-06 02:04:50 +00:00
3d Migrate engine to Schedule v3 (#7267) 2023-02-06 02:04:50 +00:00
android Move 'startup' Resource WgpuSettings into the RenderPlugin (#6946) 2022-12-20 16:17:11 +00:00
animation Migrate engine to Schedule v3 (#7267) 2023-02-06 02:04:50 +00:00
app Windows as Entities (#5589) 2023-01-19 00:38:28 +00:00
asset Plugins own their settings. Rework PluginGroup trait. (#6336) 2022-10-24 21:20:33 +00:00
async_tasks Remove VerticalAlign from TextAlignment (#6807) 2023-01-18 02:19:17 +00:00
audio Add AddAudioSource trait and improve Decodable docs (#6649) 2023-01-17 22:42:00 +00:00
diagnostics add system information plugin and update relevant examples (#5911) 2023-01-02 20:49:43 +00:00
ecs Migrate engine to Schedule v3 (#7267) 2023-02-06 02:04:50 +00:00
games Migrate engine to Schedule v3 (#7267) 2023-02-06 02:04:50 +00:00
input add Input Method Editor support (#7325) 2023-01-29 20:27:29 +00:00
ios Migrate engine to Schedule v3 (#7267) 2023-02-06 02:04:50 +00:00
reflection bevy_reflect: Improve serialization format even more (#5723) 2022-09-20 19:38:18 +00:00
scene [Fixes #6059] `Entity`'s “ID” should be named “index” instead (#6107) 2022-11-02 15:19:50 +00:00
shader Migrate engine to Schedule v3 (#7267) 2023-02-06 02:04:50 +00:00
stress_tests Migrate engine to Schedule v3 (#7267) 2023-02-06 02:04:50 +00:00
tools Migrate engine to Schedule v3 (#7267) 2023-02-06 02:04:50 +00:00
transforms Migrate engine to Schedule v3 (#7267) 2023-02-06 02:04:50 +00:00
ui Migrate engine to Schedule v3 (#7267) 2023-02-06 02:04:50 +00:00
wasm Remove wasm specific examples (#3705) 2022-01-17 22:38:05 +00:00
window Migrate engine to Schedule v3 (#7267) 2023-02-06 02:04:50 +00:00
hello_world.rs Add upstream bevy_ecs and prepare for custom-shaders merge (#2815) 2021-09-14 06:14:19 +00:00
README.md Migrate engine to Schedule v3 (#7267) 2023-02-06 02:04:50 +00:00
README.md.tpl Fix minor typos in code and docs (#7378) 2023-01-27 12:12:53 +00:00

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!

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 Rotation Demonstrates rotating entities in 2D with quaternions
2D Shapes Renders a rectangle, circle, and hexagon
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
Move Sprite Changes the transform of a sprite
Pixel Perfect Demonstrates pixel perfect in 2d
Sprite Renders a sprite
Sprite Flipping Renders a sprite flipped along an axis
Sprite Sheet Renders an animated sprite
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 Scene Simple 3D scene with basic shapes and lighting
3D Shapes A scene showcasing the built-in 3D shapes
Atmospheric Fog A scene showcasing the atmospheric fog effect
Blend Modes Showcases different blend modes
Bloom Illustrates bloom configuration using HDR and emissive materials
FXAA Compares MSAA (Multi-Sample Anti-Aliasing) and FXAA (Fast Approximate Anti-Aliasing)
Fog A scene showcasing the distance fog effect
Lighting Illustrates various lighting options in a simple scene
Lines Create a custom material to draw 3d lines
Load glTF Loads and renders a glTF file as a scene
MSAA Configures MSAA (Multi-Sample Anti-Aliasing) for smoother edges
Orthographic View Shows how to create a 3D orthographic view (for isometric-look in games or CAD applications)
Parenting Demonstrates parent->child relationships and relative transformations
Physically Based Rendering Demonstrates use of Physically Based Rendering (PBR) properties
Render to Texture Shows how to render to a texture, useful for mirrors, UI, or exporting images
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
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
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
Custom Skinned Mesh Skinned mesh example with mesh and joints data defined in code
glTF Skinned Mesh Skinned mesh example with mesh and joints data loaded from a glTF file

Application

Example Description
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
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
Asset Loading Demonstrates various methods to load assets
Custom Asset Implements a custom asset loader
Custom Asset IO Implements a custom asset io loader
Hot Reloading of Assets Demonstrates automatic reloading of assets when modified on disk

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.

Diagnostics

Example Description
Custom Diagnostic Shows how to create a custom diagnostic
Log Diagnostics Add a plugin that logs diagnostics, like frames per second (FPS), to the console

ECS (Entity Component System)

Example Description
Component Change Detection Change detection on components
Custom Query Parameters Groups commonly used compound queries and query filters into a single type
ECS Guide Full guide to Bevy's ECS
Event Illustrates event creation, activation, and reception
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 paralell, but their order isn't always deteriministic. Here's how to detect and fix this.
Parallel Query Illustrates parallel queries with ParallelIterator
Removal Detection Query for entities that had a specific component removed earlier in the current frame
Startup System Demonstrates a startup system (one that runs once when the app starts up)
State Illustrates how to use States to control transitioning from a Menu state to an InGame state
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
Timers Illustrates ticking Timer resources inside systems and handling their state

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!
Game Menu A simple game menu

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
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

Reflection

Example Description
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
Trait Reflection Allows reflection with trait objects

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
Instancing A shader that renders a mesh multiple times in one draw call
Material A shader and a material that uses it
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 depth texture generated in a prepass
Post Processing A custom post processing effect, using two cameras, with one reusing the render texture of the first one
Shader Defs A shader that uses "shaders defs" (a bevy tool to selectively toggle parts of a shader)
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).

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 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.
Transform Hierarchy Various test cases for hierarchy and transform propagation performance

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
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
Button Illustrates creating and updating a button
Font Atlas Debug Illustrates how FontAtlases are populated (used to optimize text rendering internally)
Relative Cursor Position Showcases the RelativeCursorPosition component
Text Illustrates creating and updating text
Text Debug An example for debugging text layout
Text Layout Demonstrates how the AlignItems and JustifyContent properties can be composed to layout text
Transparency UI Demonstrates transparency for UI
UI Illustrates various features of Bevy UI
UI Scaling Illustrates how to scale the UI
UI Z-Index Demonstrates how to control the relative depth (z-position) of UI elements
Window Fallthrough Illustrates how to access winit::window::Window's hittest functionality.

Window

Example Description
Clear Color Creates a solid color window
Low Power Demonstrates settings to reduce power use for bevy applications
Multiple Windows Demonstrates creating multiple windows, and rendering to them
Scale Factor Override Illustrates how to customize the default window settings
Transparent Window Illustrates making the window transparent and hiding the 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 armv7-linux-androideabi
cargo install cargo-apk

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].

Build & Run

To run on a device setup for Android development, run:

cargo apk run --example android_example

When using Bevy as a library, the following fields must be added to Cargo.toml:

[package.metadata.android]
build_targets = ["aarch64-linux-android", "armv7-linux-androideabi"]

[package.metadata.android.sdk]
target_sdk_version = 31

Please reference cargo-apk README for other Android Manifest fields.

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

Bevy by default targets Android API level 31 in its examples which is the Play Store's minimum API to upload or update apps. Users of older phones may want to use an older API when testing.

To use a different API, the following fields must be updated in Cargo.toml:

[package.metadata.android.sdk]
target_sdk_version = >>API<<
min_sdk_version = >>API or less<<
Example File Description
android android/android.rs The 3d/3d_scene.rs example for Android

iOS

Setup

You need to install the correct rust targets:

  • aarch64-apple-ios: iOS devices
  • x86_64-apple-ios: iOS simulator on x86 processors
  • aarch64-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/ios
make run

In an ideal world, this will boot up, install and run the app for the first iOS simulator in your xcrun simctl devices list. 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_ios_example.xcodeproj/

which will open xcode. You then must push the zoom zoom play button and wait for the magic.

Example File Description
ios ios/src/lib.rs The 3d/3d_scene.rs example for iOS

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, 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

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. Here are some.

1. Tweak your Cargo.toml

Add a new profile to your Cargo.toml:

[profile.wasm-release]
# Use release profile as default values
inherits = "release"

# Optimize with size in mind, also try "s", sometimes it is better.
# This doesn't increase compilation times compared to -O3, great improvements
opt-level = "z"

# Do a second optimization pass removing duplicate or unused code from dependencies.
# Slows compile times, marginal improvements
lto = "fat"

# When building crates, optimize larger chunks at a time
# Slows compile times, marginal improvements
codegen-units = 1

Now, when building the final executable, use the wasm-release profile by replacing --release by --profile wasm-release in the cargo command.

cargo build --profile wasm-release --example lighting --target wasm32-unknown-unknown

Make sure your final executable size is smaller, some of those optimizations may not be worth keeping, due to compilation time increases.

2. Use wasm-opt from the binaryen package

Binaryen is a set of tools for working with wasm. It has a wasm-opt CLI tool.

First download the binaryen package, then locate the .wasm file generated by wasm-bindgen. It should be in the --out-dir you specified in the command line, the file name should end in _bg.wasm.

Then run wasm-opt with the -Oz flag. Note that wasm-opt is very slow.

Note that wasm-opt optimizations might not be as effective if you didn't apply the optimizations from the previous section.

wasm-opt -Oz --output optimized.wasm examples/wasm/target/lighting_bg.wasm
mv optimized.wasm examples/wasm/target/lighting_bg.wasm

For a small project with a basic 3d model and two lights, the generated file sizes are, as of Jully 2022 as following:

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

There are more advanced optimization options available, check the following pages for more info:

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.