Skip to content

Commit 958c9bb

Browse files
Add no_std Library Example (bevyengine#18333)
# Objective - Fixes bevyengine#17506 - Fixes bevyengine#16258 ## Solution - Added a new folder of examples, `no_std`, similar to the `mobile` folder. - Added a single example, `no_std_library`, which demonstrates how to make a `no_std` compatible Bevy library. - Added a new CI task, `check-compiles-no-std-examples`, which checks that `no_std` examples compile on `no_std` targets. - Added `bevy_platform_support::prelude` to `bevy::prelude`. ## Testing - CI --- ## Notes - I've structured the folders here to permit further `no_std` examples (e.g., GameBoy Games, ESP32 firmware, etc.), but I am starting with the simplest and least controversial example. - I've tried to be as clear as possible with the documentation for this example, catering to an audience who may not have even heard of `no_std` before. --------- Co-authored-by: Greeble <[email protected]>
1 parent 4fca331 commit 958c9bb

File tree

8 files changed

+312
-2
lines changed

8 files changed

+312
-2
lines changed

.github/workflows/ci.yml

+25
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,31 @@ jobs:
177177
- name: Check Compile
178178
run: cargo check -p bevy --no-default-features --features default_no_std --target thumbv6m-none-eabi
179179

180+
check-compiles-no-std-examples:
181+
runs-on: ubuntu-latest
182+
timeout-minutes: 30
183+
needs: ci
184+
steps:
185+
- uses: actions/checkout@v4
186+
- uses: actions/cache@v4
187+
with:
188+
path: |
189+
~/.cargo/bin/
190+
~/.cargo/registry/index/
191+
~/.cargo/registry/cache/
192+
~/.cargo/git/db/
193+
target/
194+
crates/bevy_ecs_compile_fail_tests/target/
195+
crates/bevy_reflect_compile_fail_tests/target/
196+
key: ${{ runner.os }}-cargo-check-compiles-no-std-examples-${{ hashFiles('**/Cargo.toml') }}
197+
- uses: dtolnay/rust-toolchain@stable
198+
with:
199+
targets: x86_64-unknown-none
200+
- name: Install Linux dependencies
201+
uses: ./.github/actions/install-linux-deps
202+
- name: Check Compile
203+
run: cd examples/no_std/library && cargo check --no-default-features --features libm,critical-section --target x86_64-unknown-none
204+
180205
build-wasm:
181206
runs-on: ubuntu-latest
182207
timeout-minutes: 30

Cargo.toml

+14
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ members = [
2626
"crates/bevy_reflect/compile_fail",
2727
# Examples of compiling Bevy for mobile platforms.
2828
"examples/mobile",
29+
# Examples of using Bevy on no_std platforms.
30+
"examples/no_std/*",
2931
# Benchmarks
3032
"benches",
3133
# Internal tools that are not published.
@@ -4287,3 +4289,15 @@ name = "Widgets"
42874289
description = "Example UI Widgets"
42884290
category = "Helpers"
42894291
wasm = true
4292+
4293+
[[example]]
4294+
name = "no_std_library"
4295+
path = "examples/no_std/library/src/lib.rs"
4296+
doc-scrape-examples = true
4297+
crate-type = ["lib"]
4298+
4299+
[package.metadata.example.no_std_library]
4300+
name = "`no_std` Compatible Library"
4301+
description = "Example library compatible with `std` and `no_std` targets"
4302+
category = "Embedded"
4303+
wasm = true

crates/bevy_internal/src/prelude.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#[doc(hidden)]
22
pub use crate::{
3-
app::prelude::*, ecs::prelude::*, reflect::prelude::*, time::prelude::*, utils::prelude::*,
4-
DefaultPlugins, MinimalPlugins,
3+
app::prelude::*, ecs::prelude::*, platform_support::prelude::*, reflect::prelude::*,
4+
time::prelude::*, utils::prelude::*, DefaultPlugins, MinimalPlugins,
55
};
66

77
#[doc(hidden)]

examples/README.md

+7
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ git checkout v0.4.0
4949
- [Dev tools](#dev-tools)
5050
- [Diagnostics](#diagnostics)
5151
- [ECS (Entity Component System)](#ecs-entity-component-system)
52+
- [Embedded](#embedded)
5253
- [Games](#games)
5354
- [Gizmos](#gizmos)
5455
- [Helpers](#helpers)
@@ -333,6 +334,12 @@ Example | Description
333334
[System Piping](../examples/ecs/system_piping.rs) | Pipe the output of one system into a second, allowing you to handle any errors gracefully
334335
[System Stepping](../examples/ecs/system_stepping.rs) | Demonstrate stepping through systems in order of execution.
335336

337+
## Embedded
338+
339+
Example | Description
340+
--- | ---
341+
[`no_std` Compatible Library](../examples/no_std/library/src/lib.rs) | Example library compatible with `std` and `no_std` targets
342+
336343
## Games
337344

338345
Example | Description

examples/no_std/README.md

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# `no_std` Examples
2+
3+
This folder contains examples for how to work with `no_std` targets and Bevy.
4+
Refer to each example individually for details around how it works and what features you may need to enable/disable to allow a particular target to work.
5+
6+
## What is `no_std`?
7+
8+
`no_std` is a Rust term for software which doesn't rely on the standard library, [`std`](https://doc.rust-lang.org/stable/std/).
9+
The typical use for `no_std` is in embedded software, where the device simply doesn't support the standard library.
10+
For example, a [Raspberry Pi Pico](https://www.raspberrypi.com/documentation/microcontrollers/pico-series.html) has no operating system to support threads or filesystem operations.
11+
12+
For these platforms, Rust has a more fundamental alternative to `std`, [`core`](https://doc.rust-lang.org/stable/core/).
13+
A large portion of Rust's `std` actually just re-exports items from `core`, such as iterators, `Result`, and `Option`.
14+
15+
In addition, `std` also re-exports from another crate, [`alloc`](https://doc.rust-lang.org/stable/alloc/).
16+
This crate is similar to `core` in that it's generally available on all platforms.
17+
Where it differs is that its inclusion requires access to a [global allocator](https://doc.rust-lang.org/stable/std/alloc/trait.GlobalAlloc.html).
18+
Currently, Bevy relies heavily on allocation, so we consider `alloc` to be just as available, since without it, Bevy will not compile.

examples/no_std/library/Cargo.toml

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
[package]
2+
name = "no_std_library"
3+
version = "0.1.0"
4+
edition = "2024"
5+
6+
# Normally we'd put all dependencies in [dependencies], but this syntax is easier to document
7+
[dependencies.bevy]
8+
# In your library you'd use version = "x.y.z", but since this is an example inside the Bevy
9+
# repository we use a path instead.
10+
path = "../../../"
11+
# Since `std` is a default feature, first we disable default features
12+
default-features = false
13+
# We're free to enable any features our library needs.
14+
# Note that certain Bevy features rely on `std`.
15+
features = [
16+
# "bevy_color",
17+
# "bevy_state",
18+
]
19+
20+
[features]
21+
# `no_std` is relatively niche, so we choose defaults to cater for the majority of our users.
22+
default = ["std"]
23+
24+
# Below are some features we recommend libraries expose to assist with their usage and their own testing.
25+
26+
# Uses the Rust standard library.
27+
std = ["bevy/std"]
28+
29+
# Uses `libm` for floating point functions.
30+
libm = ["bevy/libm"]
31+
32+
# Rely on `critical-section` for synchronization primitives.
33+
critical-section = ["bevy/critical-section"]
34+
35+
# Enables access to browser APIs in a web context.
36+
web = ["bevy/web"]
37+
38+
[lints.clippy]
39+
# These lints are very helpful when working on a library with `no_std` support.
40+
# They will warn you if you import from `std` when you could've imported from `core` or `alloc`
41+
# instead.
42+
# Since `core` and `alloc` are available on any target that has `std`, there is no downside to this.
43+
std_instead_of_core = "warn"
44+
std_instead_of_alloc = "warn"
45+
alloc_instead_of_core = "warn"

examples/no_std/library/README.md

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# Bevy `no_std` Compatible Library
2+
3+
This example demonstrates how to create a `no_std`-compatible library crate for use with Bevy.
4+
For the sake of demonstration, this library adds a way for a component to be added to an entity after a certain delay has elapsed.
5+
Check the [Cargo.toml](Cargo.toml) and [lib.rs](src/lib.rs) for details around how this is implemented, and how we're able to make a library compatible for all users in the Bevy community.
6+
7+
## Testing `no_std` Compatibility
8+
9+
To check if your library is `no_std` compatible, it's not enough to just compile with your `std` feature disabled.
10+
The problem is dependencies can still include `std` even if the top-most crate is declared as `#![no_std]`.
11+
Instead, you need to compile your library without the standard library at all.
12+
13+
The simplest way to compile Rust code while ensuring `std` isn't linked is to simply use a target without the standard library.
14+
Targets with [Tier 2](https://doc.rust-lang.org/beta/rustc/platform-support.html#tier-2-without-host-tools) or [Tier 3](https://doc.rust-lang.org/beta/rustc/platform-support.html#tier-3) support often do not have access to `std`, and therefore can _only_ compile if `no_std` compatible.
15+
16+
Some recommended targets you can check against are:
17+
18+
* [`x86_64-unknown-none`](https://doc.rust-lang.org/beta/rustc/platform-support/x86_64-unknown-none.html)
19+
* Representative of desktop architectures.
20+
* Should be the most similar to typical `std` targets so it's a good starting point when porting existing libraries.
21+
* [`wasm32v1-none`](https://doc.rust-lang.org/beta/rustc/platform-support/wasm32v1-none.html)
22+
* Newer WebAssembly target with the bare minimum functionality for broad compatibility.
23+
* Similar to `wasm32-unknown-unknown`, which is typically used for web builds.
24+
* [`thumbv6m-none-eabi`](https://doc.rust-lang.org/beta/rustc/platform-support/thumbv6m-none-eabi.html)
25+
* Representative of embedded platforms.
26+
* Has only partial support for atomics, making this target a good indicator for atomic incompatibility in your code.
27+
28+
Note that the first time you attempt to compile for a new target, you will need to install the supporting components via `rustup`:
29+
30+
```sh
31+
rustup target add x86_64-unknown-none
32+
```
33+
34+
Once installed, you can check your library by specifying the appropriate features and target:
35+
36+
```sh
37+
cargo check --no-default-features --features libm,critical-section --target x86_64-unknown-none
38+
```
39+
40+
### CI
41+
42+
Checking `no_std` compatibility can be tedious and easy to forget if you're not actively using it yourself.
43+
To avoid accidentally breaking that compatibility, we recommend adding these checks to your CI pipeline.
44+
For example, here is a [GitHub Action](https://github.com/features/actions) you could use as a starting point:
45+
46+
```yml
47+
jobs:
48+
check-compiles-no-std:
49+
runs-on: ubuntu-latest
50+
strategy:
51+
fail-fast: false
52+
matrix:
53+
target:
54+
- "x86_64-unknown-none"
55+
- "wasm32v1-none"
56+
- "thumbv6m-none-eabi"
57+
steps:
58+
- uses: actions/checkout@v4
59+
- uses: dtolnay/rust-toolchain@stable
60+
with:
61+
targets: ${{ matrix.target }}
62+
- name: Check Compile
63+
run: cargo check --no-default-features --features libm,critical-section --target ${{ matrix.target }}
64+
```

examples/no_std/library/src/lib.rs

+137
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
//! Example `no_std` compatible Bevy library.
2+
3+
// The first step to a `no_std` library is to add this annotation:
4+
5+
#![no_std]
6+
7+
// This does 2 things to your crate:
8+
// 1. It prevents automatically linking the `std` crate with yours.
9+
// 2. It switches to `core::prelude` instead of `std::prelude` for what is implicitly
10+
// imported in all modules in your crate.
11+
12+
// It is common to want to use `std` when it's available, and fall-back to an alternative
13+
// implementation which may make compromises for the sake of compatibility.
14+
// To do this, you can conditionally re-include the standard library:
15+
16+
#[cfg(feature = "std")]
17+
extern crate std;
18+
19+
// This still uses the `core` prelude, so items such as `std::println` aren't implicitly included
20+
// in all your modules, but it does make them available to import.
21+
22+
// Because Bevy requires access to an allocator anyway, you are free to include `alloc` regardless
23+
// of what features are enabled.
24+
// This gives you access to `Vec`, `String`, `Box`, and many other allocation primitives.
25+
26+
extern crate alloc;
27+
28+
// Here's our first example of using something from `core` instead of `std`.
29+
// Since `std` re-exports `core` items, they are the same type just with a different name.
30+
// This means any 3rd party code written for `std::time::Duration` will work identically for
31+
// `core::time::Duration`.
32+
33+
use core::time::Duration;
34+
35+
// With the above boilerplate out of the way, everything below should look very familiar to those
36+
// who have worked with Bevy before.
37+
38+
use bevy::prelude::*;
39+
40+
// While this example doesn't need it, a lot of fundamental types which are exclusively in `std`
41+
// have alternatives in `bevy::platform_support`.
42+
// If you find yourself needing a `HashMap`, `RwLock`, or `Instant`, check there first!
43+
44+
#[expect(unused_imports, reason = "demonstrating some available items")]
45+
use bevy::platform_support::{
46+
collections::{HashMap, HashSet},
47+
hash::DefaultHasher,
48+
sync::{
49+
atomic::{AtomicBool, AtomicUsize},
50+
Arc, Barrier, LazyLock, Mutex, Once, OnceLock, RwLock, Weak,
51+
},
52+
time::Instant,
53+
};
54+
55+
// Note that `bevy::platform_support::sync::Arc` exists, despite `alloc::sync::Arc` being available.
56+
// The reason is not every platform has full support for atomic operations, so `Arc`, `AtomicBool`,
57+
// etc. aren't always available.
58+
// You can test for their inclusion with `#[cfg(target_has_atomic = "ptr")]` and other related flags.
59+
// You can get a more cross-platform alternative from `portable-atomic`, but Bevy handles this for you!
60+
// Simply use `bevy::platform_support::sync` instead of `core::sync` and `alloc::sync` when possible,
61+
// and Bevy will handle selecting the fallback from `portable-atomic` when it is required.
62+
63+
/// Plugin for working with delayed components.
64+
///
65+
/// You can delay the insertion of a component by using [`insert_delayed`](EntityCommandsExt::insert_delayed).
66+
pub struct DelayedComponentPlugin;
67+
68+
impl Plugin for DelayedComponentPlugin {
69+
fn build(&self, app: &mut App) {
70+
app.register_type::<DelayedComponentTimer>()
71+
.add_systems(Update, tick_timers);
72+
}
73+
}
74+
75+
/// Extension trait providing [`insert_delayed`](EntityCommandsExt::insert_delayed).
76+
pub trait EntityCommandsExt {
77+
/// Insert the provided [`Bundle`] `B` with a provided `delay`.
78+
fn insert_delayed<B: Bundle>(&mut self, bundle: B, delay: Duration) -> &mut Self;
79+
}
80+
81+
impl EntityCommandsExt for EntityCommands<'_> {
82+
fn insert_delayed<B: Bundle>(&mut self, bundle: B, delay: Duration) -> &mut Self {
83+
self.insert((
84+
DelayedComponentTimer(Timer::new(delay, TimerMode::Once)),
85+
DelayedComponent(bundle),
86+
))
87+
.observe(unwrap::<B>)
88+
}
89+
}
90+
91+
impl EntityCommandsExt for EntityWorldMut<'_> {
92+
fn insert_delayed<B: Bundle>(&mut self, bundle: B, delay: Duration) -> &mut Self {
93+
self.insert((
94+
DelayedComponentTimer(Timer::new(delay, TimerMode::Once)),
95+
DelayedComponent(bundle),
96+
))
97+
.observe(unwrap::<B>)
98+
}
99+
}
100+
101+
#[derive(Component, Deref, DerefMut, Reflect, Debug)]
102+
#[reflect(Component)]
103+
struct DelayedComponentTimer(Timer);
104+
105+
#[derive(Component)]
106+
#[component(immutable)]
107+
struct DelayedComponent<B: Bundle>(B);
108+
109+
#[derive(Event)]
110+
struct Unwrap;
111+
112+
fn tick_timers(
113+
mut commands: Commands,
114+
mut query: Query<(Entity, &mut DelayedComponentTimer)>,
115+
time: Res<Time>,
116+
) {
117+
for (entity, mut timer) in &mut query {
118+
timer.tick(time.delta());
119+
120+
if timer.just_finished() {
121+
commands
122+
.entity(entity)
123+
.remove::<DelayedComponentTimer>()
124+
.trigger(Unwrap);
125+
}
126+
}
127+
}
128+
129+
fn unwrap<B: Bundle>(trigger: Trigger<Unwrap>, world: &mut World) {
130+
if let Ok(mut target) = world.get_entity_mut(trigger.target()) {
131+
if let Some(DelayedComponent(bundle)) = target.take::<DelayedComponent<B>>() {
132+
target.insert(bundle);
133+
}
134+
}
135+
136+
world.despawn(trigger.observer());
137+
}

0 commit comments

Comments
 (0)