repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tests/window/change_window_mode.rs | tests/window/change_window_mode.rs | //! a test that confirms that 'bevy' does not panic while changing from Windowed to Fullscreen when viewport is set
use bevy::{prelude::*, render::camera::Viewport, window::WindowMode};
//Having a viewport set to the same size as a window used to cause panic on some occasions when switching to Fullscreen
const WINDOW_WIDTH: f32 = 1366.0;
const WINDOW_HEIGHT: f32 = 768.0;
fn main() {
//Specify Window Size.
let window = Window {
resolution: (WINDOW_WIDTH, WINDOW_HEIGHT).into(),
..default()
};
let primary_window = Some(window);
App::new()
.add_plugins(DefaultPlugins.set(WindowPlugin {
primary_window,
..default()
}))
.add_systems(Startup, startup)
.add_systems(Update, toggle_window_mode)
.run();
}
fn startup(mut cmds: Commands) {
//Match viewport to Window size.
let physical_position = UVec2::new(0, 0);
let physical_size = Vec2::new(WINDOW_WIDTH, WINDOW_HEIGHT).as_uvec2();
let viewport = Some(Viewport {
physical_position,
physical_size,
..default()
});
cmds.spawn(Camera2d).insert(Camera {
viewport,
..default()
});
}
fn toggle_window_mode(mut qry_window: Query<&mut Window>) {
let Ok(mut window) = qry_window.single_mut() else {
return;
};
window.mode = match window.mode {
WindowMode::Windowed => {
// it takes a while for the window to change from `Windowed` to `Fullscreen` and back
std::thread::sleep(std::time::Duration::from_secs(4));
WindowMode::Fullscreen(
MonitorSelection::Entity(entity),
VideoModeSelection::Current,
)
}
_ => {
std::thread::sleep(std::time::Duration::from_secs(4));
WindowMode::Windowed
}
};
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tests/window/minimizing.rs | tests/window/minimizing.rs | //! A test to confirm that `bevy` allows minimizing the window
//! This is run in CI to ensure that this doesn't regress again.
use bevy::{diagnostic::FrameCount, prelude::*};
fn main() {
// TODO: Combine this with `resizing` once multiple_windows is simpler than
// it is currently.
App::new()
.add_plugins(DefaultPlugins.set(WindowPlugin {
primary_window: Some(Window {
title: "Minimizing".into(),
..default()
}),
..default()
}))
.add_systems(Startup, (setup_3d, setup_2d))
.add_systems(Update, minimize_automatically)
.run();
}
fn minimize_automatically(mut window: Single<&mut Window>, frames: Res<FrameCount>) {
if frames.0 != 60 {
return;
}
window.set_minimized(true);
}
/// A simple 3d scene, taken from the `3d_scene` example
fn setup_3d(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// plane
commands.spawn((
Mesh3d(meshes.add(Plane3d::default().mesh().size(5.0, 5.0))),
MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))),
));
// cube
commands.spawn((
Mesh3d(meshes.add(Cuboid::default())),
MeshMaterial3d(materials.add(Color::srgb(0.8, 0.7, 0.6))),
Transform::from_xyz(0.0, 0.5, 0.0),
));
// light
commands.spawn((
PointLight {
shadows_enabled: true,
..default()
},
Transform::from_xyz(4.0, 8.0, 4.0),
));
// camera
commands.spawn((
Camera3d::default(),
Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
));
}
/// A simple 2d scene, taken from the `rect` example
fn setup_2d(mut commands: Commands) {
commands.spawn((
Camera2d,
Camera {
// render the 2d camera after the 3d camera
order: 1,
// do not use a clear color
clear_color: ClearColorConfig::None,
..default()
},
));
commands.spawn(Sprite::from_color(
Color::srgb(0.25, 0.25, 0.75),
Vec2::new(50.0, 50.0),
));
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tests/window/desktop_request_redraw.rs | tests/window/desktop_request_redraw.rs | //! Desktop request redraw
use bevy::{
dev_tools::fps_overlay::{FpsOverlayConfig, FpsOverlayPlugin},
prelude::*,
window::RequestRedraw,
winit::WinitSettings,
};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(MeshPickingPlugin)
// Enable the FPS overlay with a high resolution refresh interval. This makes it
// easier to validate that UpdateMode is behaving correctly when desktop_app is used.
// The FPS counter should essentially pause when the cube is not rotating and should
// update rapidly when the cube is rotating or there is input (e.g. moving the mouse).
//
// Left and Right clicking the cube should roggle rotation on/off.
.add_plugins(FpsOverlayPlugin {
config: FpsOverlayConfig {
text_config: TextFont {
font_size: 12.0,
..default()
},
text_color: Color::srgb(0.0, 1.0, 0.0),
refresh_interval: core::time::Duration::from_millis(16),
..default()
},
})
.insert_resource(WinitSettings::desktop_app())
.add_systems(Startup, setup)
.add_systems(Update, (update, redraw.after(update)))
.run();
}
#[derive(Component)]
struct AnimationActive;
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
commands.spawn((
Camera3d::default(),
Transform::from_xyz(0.0, 5.0, 0.0).looking_at(Vec3::ZERO, Vec3::Y),
));
commands.spawn((
PointLight {
intensity: 1e6,
..Default::default()
},
Transform::from_xyz(-1.0, 5.0, 1.0),
));
let node = Node {
display: Display::Block,
padding: UiRect::all(Val::Px(10.0)),
row_gap: Val::Px(10.0),
..Default::default()
};
commands.spawn((
node.clone(),
children![
(
node.clone(),
children![Text::new("Right click cube to pause animation")]
),
(
node.clone(),
children![Text::new("Left click cube to start animation")]
)
],
));
commands
.spawn((
Mesh3d(meshes.add(Cuboid::from_length(1.0))),
MeshMaterial3d(materials.add(Color::WHITE)),
AnimationActive,
))
.observe(
|click: On<Pointer<Click>>, mut commands: Commands| match click.button {
PointerButton::Primary => {
commands.entity(click.entity).insert(AnimationActive);
}
PointerButton::Secondary => {
commands.entity(click.entity).remove::<AnimationActive>();
}
_ => {}
},
);
}
fn update(time: Res<Time>, mut query: Query<&mut Transform, With<AnimationActive>>) {
if let Ok(mut transform) = query.single_mut() {
transform.rotate_x(time.delta_secs().min(1.0 / 60.0));
}
}
fn redraw(mut commands: Commands, query: Query<Entity, With<AnimationActive>>) {
if query.iter().next().is_some() {
commands.write_message(RequestRedraw);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/tests/ecs/ambiguity_detection.rs | tests/ecs/ambiguity_detection.rs | //! A test to confirm that `bevy` doesn't regress its system ambiguities count when using [`DefaultPlugins`].
//! This is run in CI.
//!
//! Note that because this test requires rendering, it isn't actually an integration test!
//! Instead, it's secretly an example: you can run this test manually using `cargo run --example ambiguity_detection`.
use bevy::{
ecs::schedule::{InternedScheduleLabel, LogLevel, ScheduleBuildSettings},
platform::collections::HashMap,
prelude::*,
render::{pipelined_rendering::PipelinedRenderingPlugin, RenderPlugin},
};
fn main() {
let mut app = App::new();
app.add_plugins(
DefaultPlugins
.build()
.set(RenderPlugin {
// llvmpipe driver can cause segfaults when aborting the binary while pipelines are being
// compiled (which happens very quickly in this example since we only run for a single
// frame). Synchronous pipeline compilation helps prevent these segfaults as the
// rendering thread blocks on these pipeline compilations.
synchronous_pipeline_compilation: true,
..Default::default()
})
// We also have to disable pipelined rendering to ensure the test doesn't end while the
// rendering frame is still executing in another thread.
.disable::<PipelinedRenderingPlugin>(),
);
let main_app = app.main_mut();
configure_ambiguity_detection(main_app);
// Ambiguities in the RenderApp are currently allowed.
// Eventually, we should forbid these: see https://github.com/bevyengine/bevy/issues/7386
// Uncomment the lines below to show the current ambiguities in the RenderApp.
// let sub_app = app.sub_app_mut(bevy_render::RenderApp);
// configure_ambiguity_detection(sub_app);
app.finish();
app.cleanup();
app.update();
let main_app_ambiguities = count_ambiguities(app.main());
assert_eq!(
main_app_ambiguities.total(),
0,
"Main app has unexpected ambiguities among the following schedules: \n{main_app_ambiguities:#?}.",
);
}
/// Contains the number of conflicting systems per schedule.
#[derive(Debug, Deref, DerefMut)]
struct AmbiguitiesCount(pub HashMap<InternedScheduleLabel, usize>);
impl AmbiguitiesCount {
fn total(&self) -> usize {
self.values().sum()
}
}
fn configure_ambiguity_detection(sub_app: &mut SubApp) {
let mut schedules = sub_app.world_mut().resource_mut::<Schedules>();
for (_, schedule) in schedules.iter_mut() {
schedule.set_build_settings(ScheduleBuildSettings {
// NOTE: you can change this to `LogLevel::Ignore` to easily see the current number of ambiguities.
ambiguity_detection: LogLevel::Warn,
use_shortnames: false,
..default()
});
}
}
/// Returns the number of conflicting systems per schedule.
fn count_ambiguities(sub_app: &SubApp) -> AmbiguitiesCount {
let schedules = sub_app.world().resource::<Schedules>();
let mut ambiguities = <HashMap<_, _>>::default();
for (_, schedule) in schedules.iter() {
let ambiguities_in_schedule = schedule.graph().conflicting_systems().len();
ambiguities.insert(schedule.label(), ambiguities_in_schedule);
}
AmbiguitiesCount(ambiguities)
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/src/lib.rs | benches/src/lib.rs | /// Automatically generates the qualified name of a benchmark given its function name and module
/// path.
///
/// This macro takes a single string literal as input and returns a [`&'static str`](str). Its
/// result is determined at compile-time. If you need to create variations of a benchmark name
/// based on its input, use this in combination with [`BenchmarkId`](criterion::BenchmarkId).
///
/// # When to use this
///
/// Use this macro to name benchmarks that are not within a group and benchmark groups themselves.
/// You'll most commonly use this macro with:
///
/// - [`Criterion::bench_function()`](criterion::Criterion::bench_function)
/// - [`Criterion::bench_with_input()`](criterion::Criterion::bench_with_input)
/// - [`Criterion::benchmark_group()`](criterion::Criterion::benchmark_group)
///
/// You do not want to use this macro with
/// [`BenchmarkGroup::bench_function()`](criterion::BenchmarkGroup::bench_function) or
/// [`BenchmarkGroup::bench_with_input()`](criterion::BenchmarkGroup::bench_with_input), because
/// the group they are in already has the qualified path in it.
///
/// # Example
///
/// ```
/// mod ecs {
/// mod query {
/// use criterion::Criterion;
/// use benches::bench;
///
/// fn iter(c: &mut Criterion) {
/// // Benchmark name ends in `ecs::query::iter`.
/// c.bench_function(bench!("iter"), |b| {
/// // ...
/// });
/// }
/// }
/// }
/// ```
#[macro_export]
macro_rules! bench {
($name:literal) => {
concat!(module_path!(), "::", $name)
};
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_render/torus.rs | benches/benches/bevy_render/torus.rs | use core::hint::black_box;
use criterion::{criterion_group, Criterion};
use bevy_mesh::TorusMeshBuilder;
fn torus(c: &mut Criterion) {
c.bench_function("build_torus", |b| {
b.iter(|| black_box(TorusMeshBuilder::new(black_box(0.5), black_box(1.0))));
});
}
criterion_group!(benches, torus);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_render/render_layers.rs | benches/benches/bevy_render/render_layers.rs | use core::hint::black_box;
use criterion::{criterion_group, Criterion};
use bevy_camera::visibility::RenderLayers;
fn render_layers(c: &mut Criterion) {
c.bench_function("layers_intersect", |b| {
let layer_a = RenderLayers::layer(1).with(2);
let layer_b = RenderLayers::layer(1);
b.iter(|| black_box(layer_a.intersects(&layer_b)));
});
}
criterion_group!(benches, render_layers);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_render/compute_normals.rs | benches/benches/bevy_render/compute_normals.rs | use core::hint::black_box;
use criterion::{criterion_group, Criterion};
use rand::random;
use std::time::{Duration, Instant};
use bevy_asset::RenderAssetUsages;
use bevy_mesh::{Indices, Mesh, PrimitiveTopology};
const GRID_SIZE: usize = 256;
fn compute_normals(c: &mut Criterion) {
let indices = Indices::U32(
(0..GRID_SIZE - 1)
.flat_map(|i| std::iter::repeat(i).zip(0..GRID_SIZE - 1))
.flat_map(|(i, j)| {
let tl = ((GRID_SIZE * j) + i) as u32;
let tr = tl + 1;
let bl = ((GRID_SIZE * (j + 1)) + i) as u32;
let br = bl + 1;
[tl, bl, tr, tr, bl, br]
})
.collect(),
);
let new_mesh = || {
let positions = (0..GRID_SIZE)
.flat_map(|i| std::iter::repeat(i).zip(0..GRID_SIZE))
.map(|(i, j)| [i as f32, j as f32, random::<f32>()])
.collect::<Vec<_>>();
Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::MAIN_WORLD,
)
.with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions)
.with_inserted_indices(indices.clone())
};
c.bench_function("smooth_normals", |b| {
b.iter_custom(|iters| {
let mut total = Duration::default();
for _ in 0..iters {
let mut mesh = new_mesh();
black_box(mesh.attribute(Mesh::ATTRIBUTE_NORMAL));
let start = Instant::now();
mesh.compute_smooth_normals();
let end = Instant::now();
black_box(mesh.attribute(Mesh::ATTRIBUTE_NORMAL));
total += end.duration_since(start);
}
total
});
});
c.bench_function("angle_weighted_normals", |b| {
b.iter_custom(|iters| {
let mut total = Duration::default();
for _ in 0..iters {
let mut mesh = new_mesh();
black_box(mesh.attribute(Mesh::ATTRIBUTE_NORMAL));
let start = Instant::now();
mesh.compute_smooth_normals();
let end = Instant::now();
black_box(mesh.attribute(Mesh::ATTRIBUTE_NORMAL));
total += end.duration_since(start);
}
total
});
});
c.bench_function("face_weighted_normals", |b| {
b.iter_custom(|iters| {
let mut total = Duration::default();
for _ in 0..iters {
let mut mesh = new_mesh();
black_box(mesh.attribute(Mesh::ATTRIBUTE_NORMAL));
let start = Instant::now();
mesh.compute_area_weighted_normals();
let end = Instant::now();
black_box(mesh.attribute(Mesh::ATTRIBUTE_NORMAL));
total += end.duration_since(start);
}
total
});
});
let new_mesh = || new_mesh().with_duplicated_vertices();
c.bench_function("flat_normals", |b| {
b.iter_custom(|iters| {
let mut total = Duration::default();
for _ in 0..iters {
let mut mesh = new_mesh();
black_box(mesh.attribute(Mesh::ATTRIBUTE_NORMAL));
let start = Instant::now();
mesh.compute_flat_normals();
let end = Instant::now();
black_box(mesh.attribute(Mesh::ATTRIBUTE_NORMAL));
total += end.duration_since(start);
}
total
});
});
}
criterion_group!(benches, compute_normals);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_render/main.rs | benches/benches/bevy_render/main.rs | use criterion::criterion_main;
mod compute_normals;
mod render_layers;
mod torus;
criterion_main!(
render_layers::benches,
compute_normals::benches,
torus::benches
);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_picking/ray_mesh_intersection.rs | benches/benches/bevy_picking/ray_mesh_intersection.rs | use core::hint::black_box;
use std::time::Duration;
use benches::bench;
use bevy_math::{Affine3A, Dir3, Ray3d, Vec3};
use bevy_picking::mesh_picking::ray_cast::{self, Backfaces};
use criterion::{criterion_group, AxisScale, BenchmarkId, Criterion, PlotConfiguration};
criterion_group!(benches, bench);
/// A mesh that can be passed to [`ray_cast::ray_mesh_intersection()`].
struct SimpleMesh {
positions: Vec<[f32; 3]>,
normals: Vec<[f32; 3]>,
indices: Vec<u32>,
}
/// Selects a point within a normal square.
///
/// `p` is an index within `0..vertices_per_side.pow(2)`. The returned value is a coordinate where
/// both `x` and `z` are within `0..1`.
fn p_to_xz_norm(p: u32, vertices_per_side: u32) -> (f32, f32) {
let x = (p / vertices_per_side) as f32;
let z = (p % vertices_per_side) as f32;
let vertices_per_side = vertices_per_side as f32;
// Scale `x` and `z` to be between 0 and 1.
(x / vertices_per_side, z / vertices_per_side)
}
fn create_mesh(vertices_per_side: u32) -> SimpleMesh {
let mut positions = Vec::new();
let mut normals = Vec::new();
let mut indices = Vec::new();
for p in 0..vertices_per_side.pow(2) {
let (x, z) = p_to_xz_norm(p, vertices_per_side);
// Push a new vertex to the mesh. We translate all vertices so the final square is
// centered at (0, 0), instead of (0.5, 0.5).
positions.push([x - 0.5, 0.0, z - 0.5]);
// All vertices have the same normal.
normals.push([0.0, 1.0, 0.0]);
// Extend the indices for all vertices except for the final row and column, since
// indices are "between" points.
if p % vertices_per_side != vertices_per_side - 1
&& p / vertices_per_side != vertices_per_side - 1
{
indices.extend_from_slice(&[p, p + 1, p + vertices_per_side]);
indices.extend_from_slice(&[p + vertices_per_side, p + 1, p + vertices_per_side + 1]);
}
}
SimpleMesh {
positions,
normals,
indices,
}
}
/// An enum that represents the configuration for all variations of the ray mesh intersection
/// benchmarks.
enum Benchmarks {
/// The ray intersects the mesh, and culling is enabled.
CullHit,
/// The ray intersects the mesh, and culling is disabled.
NoCullHit,
/// The ray does not intersect the mesh, and culling is enabled.
CullMiss,
}
impl Benchmarks {
const WARM_UP_TIME: Duration = Duration::from_millis(500);
const VERTICES_PER_SIDE: [u32; 3] = [10, 100, 1000];
/// Returns an iterator over every variant in this enum.
fn iter() -> impl Iterator<Item = Self> {
[Self::CullHit, Self::NoCullHit, Self::CullMiss].into_iter()
}
/// Returns the benchmark group name.
fn name(&self) -> &'static str {
match *self {
Self::CullHit => bench!("cull_intersect"),
Self::NoCullHit => bench!("no_cull_intersect"),
Self::CullMiss => bench!("cull_no_intersect"),
}
}
fn ray(&self) -> Ray3d {
Ray3d::new(
Vec3::new(0.0, 1.0, 0.0),
match *self {
Self::CullHit | Self::NoCullHit => Dir3::NEG_Y,
// `NoIntersection` should not hit the mesh, so it goes an orthogonal direction.
Self::CullMiss => Dir3::X,
},
)
}
fn mesh_to_world(&self) -> Affine3A {
Affine3A::IDENTITY
}
fn backface_culling(&self) -> Backfaces {
match *self {
Self::CullHit | Self::CullMiss => Backfaces::Cull,
Self::NoCullHit => Backfaces::Include,
}
}
/// Returns whether the ray should intersect with the mesh.
#[cfg(test)]
fn should_intersect(&self) -> bool {
match *self {
Self::CullHit | Self::NoCullHit => true,
Self::CullMiss => false,
}
}
}
/// A benchmark that times [`ray_cast::ray_mesh_intersection()`].
///
/// There are multiple different scenarios that are tracked, which are described by the
/// [`Benchmarks`] enum. Each scenario has its own benchmark group, where individual benchmarks
/// track a ray intersecting a square mesh of an increasing amount of vertices.
fn bench(c: &mut Criterion) {
for benchmark in Benchmarks::iter() {
let mut group = c.benchmark_group(benchmark.name());
group
.warm_up_time(Benchmarks::WARM_UP_TIME)
// Make the scale logarithmic, to match `VERTICES_PER_SIDE`.
.plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic));
for vertices_per_side in Benchmarks::VERTICES_PER_SIDE {
group.bench_with_input(
BenchmarkId::from_parameter(format!("{}_vertices", vertices_per_side.pow(2))),
&vertices_per_side,
|b, &vertices_per_side| {
let ray = black_box(benchmark.ray());
let mesh_to_world = black_box(benchmark.mesh_to_world());
let mesh = black_box(create_mesh(vertices_per_side));
let backface_culling = black_box(benchmark.backface_culling());
b.iter(|| {
let intersected = ray_cast::ray_mesh_intersection(
ray,
&mesh_to_world,
&mesh.positions,
Some(&mesh.normals),
Some(&mesh.indices),
None,
backface_culling,
);
#[cfg(test)]
assert_eq!(intersected.is_some(), benchmark.should_intersect());
intersected
});
},
);
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_picking/main.rs | benches/benches/bevy_picking/main.rs | use criterion::criterion_main;
mod ray_mesh_intersection;
criterion_main!(ray_mesh_intersection::benches);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_tasks/main.rs | benches/benches/bevy_tasks/main.rs | use criterion::criterion_main;
mod iter;
criterion_main!(iter::benches);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_tasks/iter.rs | benches/benches/bevy_tasks/iter.rs | use core::hint::black_box;
use bevy_tasks::{ParallelIterator, TaskPoolBuilder};
use criterion::{criterion_group, BenchmarkId, Criterion};
struct ParChunks<'a, T>(core::slice::Chunks<'a, T>);
impl<'a, T> ParallelIterator<core::slice::Iter<'a, T>> for ParChunks<'a, T>
where
T: 'a + Send + Sync,
{
fn next_batch(&mut self) -> Option<core::slice::Iter<'a, T>> {
self.0.next().map(|s| s.iter())
}
}
struct ParChunksMut<'a, T>(core::slice::ChunksMut<'a, T>);
impl<'a, T> ParallelIterator<core::slice::IterMut<'a, T>> for ParChunksMut<'a, T>
where
T: 'a + Send + Sync,
{
fn next_batch(&mut self) -> Option<core::slice::IterMut<'a, T>> {
self.0.next().map(|s| s.iter_mut())
}
}
fn bench_overhead(c: &mut Criterion) {
fn noop(_: &mut usize) {}
let mut v = (0..10000).collect::<Vec<usize>>();
c.bench_function("overhead_iter", |b| {
b.iter(|| {
v.iter_mut().for_each(noop);
});
});
let mut v = (0..10000).collect::<Vec<usize>>();
let mut group = c.benchmark_group("overhead_par_iter");
for thread_count in &[1, 2, 4, 8, 16, 32] {
let pool = TaskPoolBuilder::new().num_threads(*thread_count).build();
group.bench_with_input(
BenchmarkId::new("threads", thread_count),
thread_count,
|b, _| {
b.iter(|| {
ParChunksMut(v.chunks_mut(100)).for_each(&pool, noop);
});
},
);
}
group.finish();
}
fn bench_for_each(c: &mut Criterion) {
fn busy_work(n: usize) {
let mut i = n;
while i > 0 {
i = black_box(i - 1);
}
}
let mut v = (0..10000).collect::<Vec<usize>>();
c.bench_function("for_each_iter", |b| {
b.iter(|| {
v.iter_mut().for_each(|x| {
busy_work(10000);
*x = x.wrapping_mul(*x);
});
});
});
let mut v = (0..10000).collect::<Vec<usize>>();
let mut group = c.benchmark_group("for_each_par_iter");
for thread_count in &[1, 2, 4, 8, 16, 32] {
let pool = TaskPoolBuilder::new().num_threads(*thread_count).build();
group.bench_with_input(
BenchmarkId::new("threads", thread_count),
thread_count,
|b, _| {
b.iter(|| {
ParChunksMut(v.chunks_mut(100)).for_each(&pool, |x| {
busy_work(10000);
*x = x.wrapping_mul(*x);
});
});
},
);
}
group.finish();
}
fn bench_many_maps(c: &mut Criterion) {
fn busy_doubles(mut x: usize, n: usize) -> usize {
for _ in 0..n {
x = black_box(x.wrapping_mul(2));
}
x
}
let v = (0..10000).collect::<Vec<usize>>();
c.bench_function("many_maps_iter", |b| {
b.iter(|| {
v.iter()
.map(|x| busy_doubles(*x, 1000))
.map(|x| busy_doubles(x, 1000))
.map(|x| busy_doubles(x, 1000))
.map(|x| busy_doubles(x, 1000))
.map(|x| busy_doubles(x, 1000))
.map(|x| busy_doubles(x, 1000))
.map(|x| busy_doubles(x, 1000))
.map(|x| busy_doubles(x, 1000))
.map(|x| busy_doubles(x, 1000))
.map(|x| busy_doubles(x, 1000))
.for_each(drop);
});
});
let v = (0..10000).collect::<Vec<usize>>();
let mut group = c.benchmark_group("many_maps_par_iter");
for thread_count in &[1, 2, 4, 8, 16, 32] {
let pool = TaskPoolBuilder::new().num_threads(*thread_count).build();
group.bench_with_input(
BenchmarkId::new("threads", thread_count),
thread_count,
|b, _| {
b.iter(|| {
ParChunks(v.chunks(100))
.map(|x| busy_doubles(*x, 1000))
.map(|x| busy_doubles(x, 1000))
.map(|x| busy_doubles(x, 1000))
.map(|x| busy_doubles(x, 1000))
.map(|x| busy_doubles(x, 1000))
.map(|x| busy_doubles(x, 1000))
.map(|x| busy_doubles(x, 1000))
.map(|x| busy_doubles(x, 1000))
.map(|x| busy_doubles(x, 1000))
.map(|x| busy_doubles(x, 1000))
.for_each(&pool, drop);
});
},
);
}
group.finish();
}
criterion_group!(benches, bench_overhead, bench_for_each, bench_many_maps);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/change_detection.rs | benches/benches/bevy_ecs/change_detection.rs | use core::hint::black_box;
use bevy_ecs::{
component::{Component, Mutable},
entity::Entity,
prelude::{Added, Changed, EntityWorldMut, QueryState},
query::QueryFilter,
world::World,
};
use criterion::{criterion_group, Criterion};
use rand::{prelude::SliceRandom, SeedableRng};
use rand_chacha::ChaCha8Rng;
criterion_group!(
benches,
all_added_detection,
all_changed_detection,
few_changed_detection,
none_changed_detection,
multiple_archetype_none_changed_detection
);
macro_rules! modify {
($components:ident;$($index:tt),*) => {
$(
$components.$index.map(|mut v| {
v.0+=1.
});
)*
};
}
#[derive(Component, Default)]
#[component(storage = "Table")]
struct Table(f32);
#[derive(Component, Default)]
#[component(storage = "SparseSet")]
struct Sparse(f32);
#[derive(Component, Default)]
#[component(storage = "Table")]
struct Data<const X: u16>(f32);
trait BenchModify {
fn bench_modify(&mut self) -> f32;
}
impl BenchModify for Table {
fn bench_modify(&mut self) -> f32 {
self.0 += 1f32;
black_box(self.0)
}
}
impl BenchModify for Sparse {
fn bench_modify(&mut self) -> f32 {
self.0 += 1f32;
black_box(self.0)
}
}
const ENTITIES_TO_BENCH_COUNT: &[u32] = &[5000, 50000];
type BenchGroup<'a> = criterion::BenchmarkGroup<'a, criterion::measurement::WallTime>;
fn deterministic_rand() -> ChaCha8Rng {
ChaCha8Rng::seed_from_u64(42)
}
fn setup<T: Component + Default>(entity_count: u32) -> World {
let mut world = World::default();
world.spawn_batch((0..entity_count).map(|_| T::default()));
black_box(world)
}
// create a cached query in setup to avoid extra costs in each iter
fn generic_filter_query<F: QueryFilter>(world: &mut World) -> QueryState<Entity, F> {
world.query_filtered::<Entity, F>()
}
fn generic_bench<P: Copy>(
bench_group: &mut BenchGroup,
mut benches: Vec<Box<dyn FnMut(&mut BenchGroup, P)>>,
bench_parameters: P,
) {
for b in &mut benches {
b(bench_group, bench_parameters);
}
}
fn all_added_detection_generic<T: Component + Default>(group: &mut BenchGroup, entity_count: u32) {
group.bench_function(
format!("{}_entities_{}", entity_count, core::any::type_name::<T>()),
|bencher| {
bencher.iter_batched_ref(
|| {
let mut world = setup::<T>(entity_count);
let query = generic_filter_query::<Added<T>>(&mut world);
(world, query)
},
|(world, query)| {
let mut count = 0;
for entity in query.iter(world) {
black_box(entity);
count += 1;
}
assert_eq!(entity_count, count);
},
criterion::BatchSize::LargeInput,
);
},
);
}
fn all_added_detection(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("all_added_detection");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
for &entity_count in ENTITIES_TO_BENCH_COUNT {
generic_bench(
&mut group,
vec![
Box::new(all_added_detection_generic::<Table>),
Box::new(all_added_detection_generic::<Sparse>),
],
entity_count,
);
}
}
fn all_changed_detection_generic<T: Component<Mutability = Mutable> + Default + BenchModify>(
group: &mut BenchGroup,
entity_count: u32,
) {
group.bench_function(
format!("{}_entities_{}", entity_count, core::any::type_name::<T>()),
|bencher| {
bencher.iter_batched_ref(
|| {
let mut world = setup::<T>(entity_count);
world.clear_trackers();
let mut query = world.query::<&mut T>();
for mut component in query.iter_mut(&mut world) {
black_box(component.bench_modify());
}
let query = generic_filter_query::<Changed<T>>(&mut world);
(world, query)
},
|(world, query)| {
let mut count = 0;
for entity in query.iter(world) {
black_box(entity);
count += 1;
}
assert_eq!(entity_count, count);
},
criterion::BatchSize::LargeInput,
);
},
);
}
fn all_changed_detection(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("all_changed_detection");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
for &entity_count in ENTITIES_TO_BENCH_COUNT {
generic_bench(
&mut group,
vec![
Box::new(all_changed_detection_generic::<Table>),
Box::new(all_changed_detection_generic::<Sparse>),
],
entity_count,
);
}
}
fn few_changed_detection_generic<T: Component<Mutability = Mutable> + Default + BenchModify>(
group: &mut BenchGroup,
entity_count: u32,
) {
let ratio_to_modify = 0.1;
let amount_to_modify = (entity_count as f32 * ratio_to_modify) as usize;
group.bench_function(
format!("{}_entities_{}", entity_count, core::any::type_name::<T>()),
|bencher| {
bencher.iter_batched_ref(
|| {
let mut world = setup::<T>(entity_count);
world.clear_trackers();
let mut query = world.query::<&mut T>();
let mut to_modify: Vec<bevy_ecs::prelude::Mut<T>> =
query.iter_mut(&mut world).collect();
to_modify.shuffle(&mut deterministic_rand());
for component in to_modify[0..amount_to_modify].iter_mut() {
black_box(component.bench_modify());
}
let query = generic_filter_query::<Changed<T>>(&mut world);
(world, query)
},
|(world, query)| {
for entity in query.iter(world) {
black_box(entity);
}
},
criterion::BatchSize::LargeInput,
);
},
);
}
fn few_changed_detection(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("few_changed_detection");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
for &entity_count in ENTITIES_TO_BENCH_COUNT {
generic_bench(
&mut group,
vec![
Box::new(few_changed_detection_generic::<Table>),
Box::new(few_changed_detection_generic::<Sparse>),
],
entity_count,
);
}
}
fn none_changed_detection_generic<T: Component<Mutability = Mutable> + Default>(
group: &mut BenchGroup,
entity_count: u32,
) {
group.bench_function(
format!("{}_entities_{}", entity_count, core::any::type_name::<T>()),
|bencher| {
bencher.iter_batched_ref(
|| {
let mut world = setup::<T>(entity_count);
world.clear_trackers();
let query = generic_filter_query::<Changed<T>>(&mut world);
(world, query)
},
|(world, query)| {
let mut count = 0;
for entity in query.iter(world) {
black_box(entity);
count += 1;
}
assert_eq!(0, count);
},
criterion::BatchSize::LargeInput,
);
},
);
}
fn none_changed_detection(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("none_changed_detection");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
for &entity_count in ENTITIES_TO_BENCH_COUNT {
generic_bench(
&mut group,
vec![
Box::new(none_changed_detection_generic::<Table>),
Box::new(none_changed_detection_generic::<Sparse>),
],
entity_count,
);
}
}
fn insert_if_bit_enabled<const B: u16>(entity: &mut EntityWorldMut, i: u16) {
if i & (1 << B) != 0 {
entity.insert(Data::<B>(1.0));
}
}
fn add_archetypes_entities<T: Component<Mutability = Mutable> + Default>(
world: &mut World,
archetype_count: u16,
entity_count: u32,
) {
for i in 0..archetype_count {
for _j in 0..entity_count {
let mut e = world.spawn(T::default());
insert_if_bit_enabled::<0>(&mut e, i);
insert_if_bit_enabled::<1>(&mut e, i);
insert_if_bit_enabled::<2>(&mut e, i);
insert_if_bit_enabled::<3>(&mut e, i);
insert_if_bit_enabled::<4>(&mut e, i);
insert_if_bit_enabled::<5>(&mut e, i);
insert_if_bit_enabled::<6>(&mut e, i);
insert_if_bit_enabled::<7>(&mut e, i);
insert_if_bit_enabled::<8>(&mut e, i);
insert_if_bit_enabled::<9>(&mut e, i);
insert_if_bit_enabled::<10>(&mut e, i);
insert_if_bit_enabled::<11>(&mut e, i);
insert_if_bit_enabled::<12>(&mut e, i);
insert_if_bit_enabled::<13>(&mut e, i);
insert_if_bit_enabled::<14>(&mut e, i);
insert_if_bit_enabled::<15>(&mut e, i);
}
}
}
fn multiple_archetype_none_changed_detection_generic<
T: Component<Mutability = Mutable> + Default + BenchModify,
>(
group: &mut BenchGroup,
archetype_count: u16,
entity_count: u32,
) {
group.bench_function(
format!(
"{}_archetypes_{}_entities_{}",
archetype_count,
entity_count,
core::any::type_name::<T>()
),
|bencher| {
bencher.iter_batched_ref(
|| {
let mut world = World::new();
add_archetypes_entities::<T>(&mut world, archetype_count, entity_count);
world.clear_trackers();
let mut query = world.query::<(
Option<&mut Data<0>>,
Option<&mut Data<1>>,
Option<&mut Data<2>>,
Option<&mut Data<3>>,
Option<&mut Data<4>>,
Option<&mut Data<5>>,
Option<&mut Data<6>>,
Option<&mut Data<7>>,
Option<&mut Data<8>>,
Option<&mut Data<9>>,
Option<&mut Data<10>>,
Option<&mut Data<11>>,
Option<&mut Data<12>>,
Option<&mut Data<13>>,
Option<&mut Data<14>>,
)>();
for components in query.iter_mut(&mut world) {
// change Data<X> while keeping T unchanged
modify!(components;0,1,2,3,4,5,6,7,8,9,10,11,12,13,14);
}
let query = generic_filter_query::<Changed<T>>(&mut world);
(world, query)
},
|(world, query)| {
let mut count = 0;
for entity in query.iter(world) {
black_box(entity);
count += 1;
}
assert_eq!(0, count);
},
criterion::BatchSize::LargeInput,
);
},
);
}
fn multiple_archetype_none_changed_detection(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("multiple_archetypes_none_changed_detection");
group.warm_up_time(core::time::Duration::from_millis(800));
group.measurement_time(core::time::Duration::from_secs(8));
for archetype_count in [5, 20, 100] {
for entity_count in [10, 100, 1000, 10000] {
multiple_archetype_none_changed_detection_generic::<Table>(
&mut group,
archetype_count,
entity_count,
);
multiple_archetype_none_changed_detection_generic::<Sparse>(
&mut group,
archetype_count,
entity_count,
);
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/empty_archetypes.rs | benches/benches/bevy_ecs/empty_archetypes.rs | use core::hint::black_box;
use bevy_ecs::{component::Component, prelude::*, schedule::ExecutorKind, world::World};
use criterion::{criterion_group, BenchmarkId, Criterion};
criterion_group!(benches, empty_archetypes);
#[derive(Component)]
struct A<const N: u16>(f32);
fn iter(
query: Query<(
&A<0>,
&A<1>,
&A<2>,
&A<3>,
&A<4>,
&A<5>,
&A<6>,
&A<7>,
&A<8>,
&A<9>,
&A<10>,
&A<11>,
&A<12>,
)>,
) {
for comp in query.iter() {
black_box(comp);
}
}
fn for_each(
query: Query<(
&A<0>,
&A<1>,
&A<2>,
&A<3>,
&A<4>,
&A<5>,
&A<6>,
&A<7>,
&A<8>,
&A<9>,
&A<10>,
&A<11>,
&A<12>,
)>,
) {
query.iter().for_each(|comp| {
black_box(comp);
});
}
fn par_for_each(
query: Query<(
&A<0>,
&A<1>,
&A<2>,
&A<3>,
&A<4>,
&A<5>,
&A<6>,
&A<7>,
&A<8>,
&A<9>,
&A<10>,
&A<11>,
&A<12>,
)>,
) {
query.par_iter().for_each(|comp| {
black_box(comp);
});
}
fn setup(parallel: bool, setup: impl FnOnce(&mut Schedule)) -> (World, Schedule) {
let world = World::new();
let mut schedule = Schedule::default();
schedule.set_executor_kind(match parallel {
true => ExecutorKind::MultiThreaded,
false => ExecutorKind::SingleThreaded,
});
setup(&mut schedule);
(world, schedule)
}
/// create `count` entities with distinct archetypes
fn add_archetypes(world: &mut World, count: u16) {
for i in 0..count {
let mut e = world.spawn_empty();
e.insert(A::<0>(1.0));
e.insert(A::<1>(1.0));
e.insert(A::<2>(1.0));
e.insert(A::<3>(1.0));
e.insert(A::<4>(1.0));
e.insert(A::<5>(1.0));
e.insert(A::<6>(1.0));
e.insert(A::<7>(1.0));
e.insert(A::<8>(1.0));
e.insert(A::<9>(1.0));
e.insert(A::<10>(1.0));
e.insert(A::<11>(1.0));
e.insert(A::<12>(1.0));
if i & (1 << 1) != 0 {
e.insert(A::<13>(1.0));
}
if i & (1 << 2) != 0 {
e.insert(A::<14>(1.0));
}
if i & (1 << 3) != 0 {
e.insert(A::<15>(1.0));
}
if i & (1 << 4) != 0 {
e.insert(A::<16>(1.0));
}
if i & (1 << 5) != 0 {
e.insert(A::<18>(1.0));
}
if i & (1 << 6) != 0 {
e.insert(A::<19>(1.0));
}
if i & (1 << 7) != 0 {
e.insert(A::<20>(1.0));
}
if i & (1 << 8) != 0 {
e.insert(A::<21>(1.0));
}
if i & (1 << 9) != 0 {
e.insert(A::<22>(1.0));
}
if i & (1 << 10) != 0 {
e.insert(A::<23>(1.0));
}
if i & (1 << 11) != 0 {
e.insert(A::<24>(1.0));
}
if i & (1 << 12) != 0 {
e.insert(A::<25>(1.0));
}
if i & (1 << 13) != 0 {
e.insert(A::<26>(1.0));
}
if i & (1 << 14) != 0 {
e.insert(A::<27>(1.0));
}
if i & (1 << 15) != 0 {
e.insert(A::<28>(1.0));
}
}
}
fn empty_archetypes(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("empty_archetypes");
for archetype_count in [10, 100, 1_000, 10_000] {
let (mut world, mut schedule) = setup(true, |schedule| {
schedule.add_systems(iter);
});
add_archetypes(&mut world, archetype_count);
world.clear_entities();
let mut e = world.spawn_empty();
e.insert(A::<0>(1.0));
e.insert(A::<1>(1.0));
e.insert(A::<2>(1.0));
e.insert(A::<3>(1.0));
e.insert(A::<4>(1.0));
e.insert(A::<5>(1.0));
e.insert(A::<6>(1.0));
e.insert(A::<7>(1.0));
e.insert(A::<8>(1.0));
e.insert(A::<9>(1.0));
e.insert(A::<10>(1.0));
e.insert(A::<11>(1.0));
e.insert(A::<12>(1.0));
schedule.run(&mut world);
group.bench_with_input(
BenchmarkId::new("iter", archetype_count),
&archetype_count,
|bencher, &_| {
bencher.iter(|| {
schedule.run(&mut world);
});
},
);
}
for archetype_count in [10, 100, 1_000, 10_000] {
let (mut world, mut schedule) = setup(true, |schedule| {
schedule.add_systems(for_each);
});
add_archetypes(&mut world, archetype_count);
world.clear_entities();
let mut e = world.spawn_empty();
e.insert(A::<0>(1.0));
e.insert(A::<1>(1.0));
e.insert(A::<2>(1.0));
e.insert(A::<3>(1.0));
e.insert(A::<4>(1.0));
e.insert(A::<5>(1.0));
e.insert(A::<6>(1.0));
e.insert(A::<7>(1.0));
e.insert(A::<8>(1.0));
e.insert(A::<9>(1.0));
e.insert(A::<10>(1.0));
e.insert(A::<11>(1.0));
e.insert(A::<12>(1.0));
schedule.run(&mut world);
group.bench_with_input(
BenchmarkId::new("for_each", archetype_count),
&archetype_count,
|bencher, &_| {
bencher.iter(|| {
schedule.run(&mut world);
});
},
);
}
for archetype_count in [10, 100, 1_000, 10_000] {
let (mut world, mut schedule) = setup(true, |schedule| {
schedule.add_systems(par_for_each);
});
add_archetypes(&mut world, archetype_count);
world.clear_entities();
let mut e = world.spawn_empty();
e.insert(A::<0>(1.0));
e.insert(A::<1>(1.0));
e.insert(A::<2>(1.0));
e.insert(A::<3>(1.0));
e.insert(A::<4>(1.0));
e.insert(A::<5>(1.0));
e.insert(A::<6>(1.0));
e.insert(A::<7>(1.0));
e.insert(A::<8>(1.0));
e.insert(A::<9>(1.0));
e.insert(A::<10>(1.0));
e.insert(A::<11>(1.0));
e.insert(A::<12>(1.0));
schedule.run(&mut world);
group.bench_with_input(
BenchmarkId::new("par_for_each", archetype_count),
&archetype_count,
|bencher, &_| {
bencher.iter(|| {
schedule.run(&mut world);
});
},
);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/entity_cloning.rs | benches/benches/bevy_ecs/entity_cloning.rs | use core::hint::black_box;
use benches::bench;
use bevy_ecs::bundle::{Bundle, InsertMode};
use bevy_ecs::component::ComponentCloneBehavior;
use bevy_ecs::entity::EntityCloner;
use bevy_ecs::hierarchy::ChildOf;
use bevy_ecs::reflect::AppTypeRegistry;
use bevy_ecs::{component::Component, world::World};
use bevy_math::Mat4;
use bevy_reflect::{GetTypeRegistration, Reflect};
use criterion::{criterion_group, Bencher, Criterion, Throughput};
criterion_group!(
benches,
single,
hierarchy_tall,
hierarchy_wide,
hierarchy_many,
filter
);
#[derive(Component, Reflect, Default, Clone)]
struct C<const N: usize>(Mat4);
type ComplexBundle = (C<1>, C<2>, C<3>, C<4>, C<5>, C<6>, C<7>, C<8>, C<9>, C<10>);
/// Sets the [`ComponentCloneBehavior`] for all explicit and required components in a bundle `B` to
/// use the [`Reflect`] trait instead of [`Clone`].
fn reflection_cloner<B: Bundle + GetTypeRegistration>(
world: &mut World,
linked_cloning: bool,
) -> EntityCloner {
// Get mutable access to the type registry, creating it if it does not exist yet.
let registry = world.get_resource_or_init::<AppTypeRegistry>();
// Recursively register all components in the bundle to the reflection type registry.
{
let mut r = registry.write();
r.register::<B>();
}
// Recursively register all components in the bundle, then save the component IDs to a list.
// This uses `contributed_components()`, meaning both explicit and required component IDs in
// this bundle are saved.
let component_ids: Vec<_> = world.register_bundle::<B>().contributed_components().into();
let mut builder = EntityCloner::build_opt_out(world);
// Overwrite the clone handler for all components in the bundle to use `Reflect`, not `Clone`.
for component in component_ids {
builder.override_clone_behavior_with_id(component, ComponentCloneBehavior::reflect());
}
builder.linked_cloning(linked_cloning);
builder.finish()
}
/// A helper function that benchmarks running [`EntityCloner::spawn_clone`] with a bundle `B`.
///
/// The bundle must implement [`Default`], which is used to create the first entity that gets cloned
/// in the benchmark.
///
/// If `clone_via_reflect` is false, this will use the default [`ComponentCloneBehavior`] for all
/// components (which is usually [`ComponentCloneBehavior::clone()`]). If `clone_via_reflect`
/// is true, it will overwrite the handler for all components in the bundle to be
/// [`ComponentCloneBehavior::reflect()`].
fn bench_clone<B: Bundle + Default + GetTypeRegistration>(
b: &mut Bencher,
clone_via_reflect: bool,
) {
let mut world = World::default();
let mut cloner = if clone_via_reflect {
reflection_cloner::<B>(&mut world, false)
} else {
EntityCloner::default()
};
// Spawn the first entity, which will be cloned in the benchmark routine.
let id = world.spawn(B::default()).id();
b.iter(|| {
// clones the given entity
cloner.spawn_clone(&mut world, black_box(id));
world.flush();
});
}
/// A helper function that benchmarks running [`EntityCloner::spawn_clone`] with a bundle `B`.
///
/// As compared to [`bench_clone()`], this benchmarks recursively cloning an entity with several
/// children. It does so by setting up an entity tree with a given `height` where each entity has a
/// specified number of `children`.
///
/// For example, setting `height` to 5 and `children` to 1 creates a single chain of entities with
/// no siblings. Alternatively, setting `height` to 1 and `children` to 5 will spawn 5 direct
/// children of the root entity.
fn bench_clone_hierarchy<B: Bundle + Default + GetTypeRegistration>(
b: &mut Bencher,
height: usize,
children: usize,
clone_via_reflect: bool,
) {
let mut world = World::default();
let mut cloner = if clone_via_reflect {
reflection_cloner::<B>(&mut world, true)
} else {
let mut builder = EntityCloner::build_opt_out(&mut world);
builder.linked_cloning(true);
builder.finish()
};
// Make the clone command recursive, so children are cloned as well.
// Spawn the first entity, which will be cloned in the benchmark routine.
let id = world.spawn(B::default()).id();
let mut hierarchy_level = vec![id];
// Set up the hierarchy tree by spawning all children.
for _ in 0..height {
let current_hierarchy_level = hierarchy_level.clone();
hierarchy_level.clear();
for parent in current_hierarchy_level {
for _ in 0..children {
let child_id = world.spawn((B::default(), ChildOf(parent))).id();
hierarchy_level.push(child_id);
}
}
}
b.iter(|| {
cloner.spawn_clone(&mut world, black_box(id));
world.flush();
});
}
// Each benchmark runs twice: using either the `Clone` or `Reflect` traits to clone entities. This
// constant represents this as an easy array that can be used in a `for` loop.
const CLONE_SCENARIOS: [(&str, bool); 2] = [("clone", false), ("reflect", true)];
/// Benchmarks cloning a single entity with 10 components and no children.
fn single(c: &mut Criterion) {
let mut group = c.benchmark_group(bench!("single"));
// We're cloning 1 entity.
group.throughput(Throughput::Elements(1));
for (id, clone_via_reflect) in CLONE_SCENARIOS {
group.bench_function(id, |b| {
bench_clone::<ComplexBundle>(b, clone_via_reflect);
});
}
group.finish();
}
/// Benchmarks cloning an entity and its 50 descendents, each with only 1 component.
fn hierarchy_tall(c: &mut Criterion) {
let mut group = c.benchmark_group(bench!("hierarchy_tall"));
// We're cloning both the root entity and its 50 descendents.
group.throughput(Throughput::Elements(51));
for (id, clone_via_reflect) in CLONE_SCENARIOS {
group.bench_function(id, |b| {
bench_clone_hierarchy::<C<1>>(b, 50, 1, clone_via_reflect);
});
}
group.finish();
}
/// Benchmarks cloning an entity and its 50 direct children, each with only 1 component.
fn hierarchy_wide(c: &mut Criterion) {
let mut group = c.benchmark_group(bench!("hierarchy_wide"));
// We're cloning both the root entity and its 50 direct children.
group.throughput(Throughput::Elements(51));
for (id, clone_via_reflect) in CLONE_SCENARIOS {
group.bench_function(id, |b| {
bench_clone_hierarchy::<C<1>>(b, 1, 50, clone_via_reflect);
});
}
group.finish();
}
/// Benchmarks cloning a large hierarchy of entities with several children each. Each entity has 10
/// components.
fn hierarchy_many(c: &mut Criterion) {
let mut group = c.benchmark_group(bench!("hierarchy_many"));
// We're cloning 364 entities total. This number was calculated by manually counting the number
// of entities spawned in `bench_clone_hierarchy()` with a `println!()` statement. :)
group.throughput(Throughput::Elements(364));
for (id, clone_via_reflect) in CLONE_SCENARIOS {
group.bench_function(id, |b| {
bench_clone_hierarchy::<ComplexBundle>(b, 5, 3, clone_via_reflect);
});
}
group.finish();
}
/// Filter scenario variant for bot opt-in and opt-out filters
#[derive(Clone, Copy)]
#[expect(
clippy::enum_variant_names,
reason = "'Opt' is not understood as an prefix but `OptOut'/'OptIn' are"
)]
enum FilterScenario {
OptOutNone,
OptOutNoneKeep(bool),
OptOutAll,
OptInNone,
OptInAll,
OptInAllWithoutRequired,
OptInAllKeep(bool),
OptInAllKeepWithoutRequired(bool),
}
impl From<FilterScenario> for String {
fn from(value: FilterScenario) -> Self {
match value {
FilterScenario::OptOutNone => "opt_out_none",
FilterScenario::OptOutNoneKeep(true) => "opt_out_none_keep_none",
FilterScenario::OptOutNoneKeep(false) => "opt_out_none_keep_all",
FilterScenario::OptOutAll => "opt_out_all",
FilterScenario::OptInNone => "opt_in_none",
FilterScenario::OptInAll => "opt_in_all",
FilterScenario::OptInAllWithoutRequired => "opt_in_all_without_required",
FilterScenario::OptInAllKeep(true) => "opt_in_all_keep_none",
FilterScenario::OptInAllKeep(false) => "opt_in_all_keep_all",
FilterScenario::OptInAllKeepWithoutRequired(true) => {
"opt_in_all_keep_none_without_required"
}
FilterScenario::OptInAllKeepWithoutRequired(false) => {
"opt_in_all_keep_all_without_required"
}
}
.into()
}
}
/// Common scenarios for different filter to be benchmarked.
const FILTER_SCENARIOS: [FilterScenario; 11] = [
FilterScenario::OptOutNone,
FilterScenario::OptOutNoneKeep(true),
FilterScenario::OptOutNoneKeep(false),
FilterScenario::OptOutAll,
FilterScenario::OptInNone,
FilterScenario::OptInAll,
FilterScenario::OptInAllWithoutRequired,
FilterScenario::OptInAllKeep(true),
FilterScenario::OptInAllKeep(false),
FilterScenario::OptInAllKeepWithoutRequired(true),
FilterScenario::OptInAllKeepWithoutRequired(false),
];
/// A helper function that benchmarks running [`EntityCloner::clone_entity`] with a bundle `B`.
///
/// The bundle must implement [`Default`], which is used to create the first entity that gets its components cloned
/// in the benchmark. It may also be used to populate the target entity depending on the scenario.
fn bench_filter<B: Bundle + Default>(b: &mut Bencher, scenario: FilterScenario) {
let mut world = World::default();
let mut spawn = |empty| match empty {
false => world.spawn(B::default()).id(),
true => world.spawn_empty().id(),
};
let source = spawn(false);
let (target, mut cloner);
match scenario {
FilterScenario::OptOutNone => {
target = spawn(true);
cloner = EntityCloner::default();
}
FilterScenario::OptOutNoneKeep(is_new) => {
target = spawn(is_new);
let mut builder = EntityCloner::build_opt_out(&mut world);
builder.insert_mode(InsertMode::Keep);
cloner = builder.finish();
}
FilterScenario::OptOutAll => {
target = spawn(true);
let mut builder = EntityCloner::build_opt_out(&mut world);
builder.deny::<B>();
cloner = builder.finish();
}
FilterScenario::OptInNone => {
target = spawn(true);
let builder = EntityCloner::build_opt_in(&mut world);
cloner = builder.finish();
}
FilterScenario::OptInAll => {
target = spawn(true);
let mut builder = EntityCloner::build_opt_in(&mut world);
builder.allow::<B>();
cloner = builder.finish();
}
FilterScenario::OptInAllWithoutRequired => {
target = spawn(true);
let mut builder = EntityCloner::build_opt_in(&mut world);
builder.without_required_components(|builder| {
builder.allow::<B>();
});
cloner = builder.finish();
}
FilterScenario::OptInAllKeep(is_new) => {
target = spawn(is_new);
let mut builder = EntityCloner::build_opt_in(&mut world);
builder.allow_if_new::<B>();
cloner = builder.finish();
}
FilterScenario::OptInAllKeepWithoutRequired(is_new) => {
target = spawn(is_new);
let mut builder = EntityCloner::build_opt_in(&mut world);
builder.without_required_components(|builder| {
builder.allow_if_new::<B>();
});
cloner = builder.finish();
}
}
b.iter(|| {
// clones the given entity into the target
cloner.clone_entity(&mut world, black_box(source), black_box(target));
world.flush();
});
}
/// Benchmarks filtering of cloning a single entity with 5 unclonable components (each requiring 1 unclonable component) into a target.
fn filter(c: &mut Criterion) {
#[derive(Component, Default)]
#[component(clone_behavior = Ignore)]
struct C<const N: usize>;
#[derive(Component, Default)]
#[component(clone_behavior = Ignore)]
#[require(C::<N>)]
struct R<const N: usize>;
type RequiringBundle = (R<1>, R<2>, R<3>, R<4>, R<5>);
let mut group = c.benchmark_group(bench!("filter"));
// We're cloning 1 entity into a target.
group.throughput(Throughput::Elements(1));
for scenario in FILTER_SCENARIOS {
group.bench_function(scenario, |b| {
bench_filter::<RequiringBundle>(b, scenario);
});
}
group.finish();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/main.rs | benches/benches/bevy_ecs/main.rs | #![expect(
dead_code,
reason = "Many fields are unused/unread as they are just for benchmarking purposes."
)]
use criterion::criterion_main;
mod bundles;
mod change_detection;
mod components;
mod empty_archetypes;
mod entity_cloning;
mod events;
mod fragmentation;
mod iteration;
mod observers;
mod param;
mod scheduling;
mod world;
criterion_main!(
bundles::benches,
change_detection::benches,
components::benches,
empty_archetypes::benches,
entity_cloning::benches,
events::benches,
iteration::benches,
fragmentation::benches,
observers::benches,
scheduling::benches,
world::benches,
param::benches,
);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/fragmentation.rs | benches/benches/bevy_ecs/fragmentation.rs | use bevy_ecs::prelude::*;
use bevy_ecs::system::SystemState;
use core::hint::black_box;
use criterion::*;
use glam::*;
criterion_group!(benches, iter_frag_empty);
#[derive(Component, Default)]
struct Table<const X: usize = 0>(usize);
#[derive(Component, Default)]
#[component(storage = "SparseSet")]
struct Sparse<const X: usize = 0>(usize);
fn flip_coin() -> bool {
rand::random::<bool>()
}
fn iter_frag_empty(c: &mut Criterion) {
let mut group = c.benchmark_group("iter_fragmented(4096)_empty");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
group.bench_function("foreach_table", |b| {
let mut world = World::new();
spawn_empty_frag_archetype::<Table>(&mut world);
let mut q: SystemState<Query<(Entity, &Table)>> =
SystemState::<Query<(Entity, &Table<0>)>>::new(&mut world);
let query = q.get(&world);
b.iter(move || {
let mut res = 0;
query.iter().for_each(|(e, t)| {
res += e.to_bits();
black_box(t);
});
});
});
group.bench_function("foreach_sparse", |b| {
let mut world = World::new();
spawn_empty_frag_archetype::<Sparse>(&mut world);
let mut q: SystemState<Query<(Entity, &Sparse)>> =
SystemState::<Query<(Entity, &Sparse<0>)>>::new(&mut world);
let query = q.get(&world);
b.iter(move || {
let mut res = 0;
query.iter().for_each(|(e, t)| {
res += e.to_bits();
black_box(t);
});
});
});
group.finish();
fn spawn_empty_frag_archetype<T: Component + Default>(world: &mut World) {
for i in 0..65536 {
let mut e = world.spawn_empty();
if flip_coin() {
e.insert(Table::<1>(0));
}
if flip_coin() {
e.insert(Table::<2>(0));
}
if flip_coin() {
e.insert(Table::<3>(0));
}
if flip_coin() {
e.insert(Table::<4>(0));
}
if flip_coin() {
e.insert(Table::<5>(0));
}
if flip_coin() {
e.insert(Table::<6>(0));
}
if flip_coin() {
e.insert(Table::<7>(0));
}
if flip_coin() {
e.insert(Table::<8>(0));
}
if flip_coin() {
e.insert(Table::<9>(0));
}
if flip_coin() {
e.insert(Table::<10>(0));
}
if flip_coin() {
e.insert(Table::<11>(0));
}
if flip_coin() {
e.insert(Table::<12>(0));
}
e.insert(T::default());
if i != 0 {
e.despawn();
}
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/observers/propagation.rs | benches/benches/bevy_ecs/observers/propagation.rs | use core::hint::black_box;
use bevy_ecs::prelude::*;
use criterion::Criterion;
use rand::SeedableRng;
use rand::{seq::IteratorRandom, Rng};
use rand_chacha::ChaCha8Rng;
const DENSITY: usize = 20; // percent of nodes with listeners
const ENTITY_DEPTH: usize = 64;
const ENTITY_WIDTH: usize = 200;
const N_EVENTS: usize = 500;
fn deterministic_rand() -> ChaCha8Rng {
ChaCha8Rng::seed_from_u64(42)
}
pub fn event_propagation(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("event_propagation");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
group.bench_function("single_event_type", |bencher| {
let mut world = World::new();
let (roots, leaves, nodes) = spawn_listener_hierarchy(&mut world);
add_listeners_to_hierarchy::<DENSITY, 1>(&roots, &leaves, &nodes, &mut world);
bencher.iter(|| {
send_events::<1, N_EVENTS>(&mut world, &leaves);
});
});
group.bench_function("single_event_type_no_listeners", |bencher| {
let mut world = World::new();
let (roots, leaves, nodes) = spawn_listener_hierarchy(&mut world);
add_listeners_to_hierarchy::<DENSITY, 1>(&roots, &leaves, &nodes, &mut world);
bencher.iter(|| {
// no listeners to observe TestEvent<9>
send_events::<9, N_EVENTS>(&mut world, &leaves);
});
});
group.bench_function("four_event_types", |bencher| {
let mut world = World::new();
let (roots, leaves, nodes) = spawn_listener_hierarchy(&mut world);
const FRAC_N_EVENTS_4: usize = N_EVENTS / 4;
const FRAC_DENSITY_4: usize = DENSITY / 4;
add_listeners_to_hierarchy::<FRAC_DENSITY_4, 1>(&roots, &leaves, &nodes, &mut world);
add_listeners_to_hierarchy::<FRAC_DENSITY_4, 2>(&roots, &leaves, &nodes, &mut world);
add_listeners_to_hierarchy::<FRAC_DENSITY_4, 3>(&roots, &leaves, &nodes, &mut world);
add_listeners_to_hierarchy::<FRAC_DENSITY_4, 4>(&roots, &leaves, &nodes, &mut world);
bencher.iter(|| {
send_events::<1, FRAC_N_EVENTS_4>(&mut world, &leaves);
send_events::<2, FRAC_N_EVENTS_4>(&mut world, &leaves);
send_events::<3, FRAC_N_EVENTS_4>(&mut world, &leaves);
send_events::<4, FRAC_N_EVENTS_4>(&mut world, &leaves);
});
});
group.finish();
}
#[derive(EntityEvent, Clone, Component)]
#[entity_event(propagate, auto_propagate)]
struct TestEvent<const N: usize> {
entity: Entity,
}
fn send_events<const N: usize, const N_EVENTS: usize>(world: &mut World, leaves: &[Entity]) {
let entity = *leaves.iter().choose(&mut rand::rng()).unwrap();
(0..N_EVENTS).for_each(|_| {
world.trigger(TestEvent::<N> { entity });
});
}
fn spawn_listener_hierarchy(world: &mut World) -> (Vec<Entity>, Vec<Entity>, Vec<Entity>) {
let mut roots = vec![];
let mut leaves = vec![];
let mut nodes = vec![];
for _ in 0..ENTITY_WIDTH {
let mut parent = world.spawn_empty().id();
roots.push(parent);
for _ in 0..ENTITY_DEPTH {
let child = world.spawn_empty().id();
nodes.push(child);
world.entity_mut(parent).add_child(child);
parent = child;
}
nodes.pop();
leaves.push(parent);
}
(roots, leaves, nodes)
}
fn add_listeners_to_hierarchy<const DENSITY: usize, const N: usize>(
roots: &[Entity],
leaves: &[Entity],
nodes: &[Entity],
world: &mut World,
) {
for e in roots.iter() {
world.entity_mut(*e).observe(empty_listener::<N>);
}
for e in leaves.iter() {
world.entity_mut(*e).observe(empty_listener::<N>);
}
let mut rng = deterministic_rand();
for e in nodes.iter() {
if rng.random_bool(DENSITY as f64 / 100.0) {
world.entity_mut(*e).observe(empty_listener::<N>);
}
}
}
fn empty_listener<const N: usize>(event: On<TestEvent<N>>) {
black_box(event);
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/observers/lifecycle.rs | benches/benches/bevy_ecs/observers/lifecycle.rs | use bevy_ecs::{component::Component, lifecycle::Insert, observer::On, world::World};
use core::hint::black_box;
use criterion::Criterion;
use rand::SeedableRng;
use rand_chacha::ChaCha8Rng;
fn deterministic_rand() -> ChaCha8Rng {
ChaCha8Rng::seed_from_u64(42)
}
pub fn observer_lifecycle(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("observe");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
group.bench_function("observer_lifecycle_insert", |bencher| {
let mut world = World::new();
world.add_observer(on_insert);
let mut entity = world.spawn(A);
bencher.iter(|| {
for _ in 0..10000 {
entity.insert(A);
}
});
});
group.finish();
}
#[derive(Component)]
struct A;
fn on_insert(event: On<Insert, A>) {
black_box(event);
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/observers/mod.rs | benches/benches/bevy_ecs/observers/mod.rs | mod custom;
mod lifecycle;
mod propagation;
use criterion::criterion_group;
use custom::*;
use lifecycle::*;
use propagation::*;
criterion_group!(
benches,
event_propagation,
observer_custom,
observer_lifecycle
);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/observers/custom.rs | benches/benches/bevy_ecs/observers/custom.rs | use core::hint::black_box;
use bevy_ecs::{
entity::Entity,
event::{EntityEvent, Event},
observer::On,
world::World,
};
use criterion::Criterion;
use rand::{prelude::SliceRandom, SeedableRng};
use rand_chacha::ChaCha8Rng;
fn deterministic_rand() -> ChaCha8Rng {
ChaCha8Rng::seed_from_u64(42)
}
#[derive(Clone, Event)]
struct A;
pub fn observer_custom(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("observe");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
group.bench_function("observer_custom", |bencher| {
let mut world = World::new();
world.add_observer(on_a);
bencher.iter(|| {
for _ in 0..10000 {
world.trigger(A);
}
});
});
group.bench_function("observer_custom/10000_entity", |bencher| {
let mut world = World::new();
let mut entities = vec![];
for _ in 0..10000 {
entities.push(world.spawn_empty().observe(on_b).id());
}
entities.shuffle(&mut deterministic_rand());
bencher.iter(|| {
for entity in entities.iter().copied() {
world.trigger(B { entity });
}
});
});
group.finish();
}
fn on_a(event: On<A>) {
black_box(event);
}
#[derive(Clone, EntityEvent)]
struct B {
entity: Entity,
}
fn on_b(event: On<B>) {
black_box(event);
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/scheduling/schedule.rs | benches/benches/bevy_ecs/scheduling/schedule.rs | use bevy_app::{App, Update};
use bevy_ecs::prelude::*;
use criterion::Criterion;
pub fn schedule(c: &mut Criterion) {
#[derive(Component)]
struct A(f32);
#[derive(Component)]
struct B(f32);
#[derive(Component)]
struct C(f32);
#[derive(Component)]
struct D(f32);
#[derive(Component)]
struct E(f32);
fn ab(mut query: Query<(&mut A, &mut B)>) {
query.iter_mut().for_each(|(mut a, mut b)| {
core::mem::swap(&mut a.0, &mut b.0);
});
}
fn cd(mut query: Query<(&mut C, &mut D)>) {
query.iter_mut().for_each(|(mut c, mut d)| {
core::mem::swap(&mut c.0, &mut d.0);
});
}
fn ce(mut query: Query<(&mut C, &mut E)>) {
query.iter_mut().for_each(|(mut c, mut e)| {
core::mem::swap(&mut c.0, &mut e.0);
});
}
let mut group = c.benchmark_group("schedule");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
group.bench_function("base", |b| {
let mut world = World::default();
world.spawn_batch((0..10000).map(|_| (A(0.0), B(0.0))));
world.spawn_batch((0..10000).map(|_| (A(0.0), B(0.0), C(0.0))));
world.spawn_batch((0..10000).map(|_| (A(0.0), B(0.0), C(0.0), D(0.0))));
world.spawn_batch((0..10000).map(|_| (A(0.0), B(0.0), C(0.0), E(0.0))));
let mut schedule = Schedule::default();
schedule.add_systems((ab, cd, ce));
schedule.run(&mut world);
b.iter(move || schedule.run(&mut world));
});
group.finish();
}
pub fn build_schedule(criterion: &mut Criterion) {
// empty system
fn empty_system() {}
// Use multiple different kinds of label to ensure that dynamic dispatch
// doesn't somehow get optimized away.
#[derive(SystemSet, Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct NumSet(usize);
#[derive(SystemSet, Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct DummySet;
let mut group = criterion.benchmark_group("build_schedule");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(15));
// Method: generate a set of `graph_size` systems which have a One True Ordering.
// Add system to the schedule with full constraints. Hopefully this should be maximally
// difficult for bevy to figure out.
let labels: Vec<_> = (0..1000).map(NumSet).collect();
// Benchmark graphs of different sizes.
for graph_size in [100, 500, 1000] {
// Basic benchmark without constraints.
group.bench_function(format!("{graph_size}_schedule_no_constraints"), |bencher| {
bencher.iter(|| {
let mut app = App::new();
for _ in 0..graph_size {
app.add_systems(Update, empty_system);
}
app.update();
});
});
// Benchmark with constraints.
group.bench_function(format!("{graph_size}_schedule"), |bencher| {
bencher.iter(|| {
let mut app = App::new();
app.add_systems(Update, empty_system.in_set(DummySet));
// Build a fully-connected dependency graph describing the One True Ordering.
// Not particularly realistic but this can be refined later.
for i in 0..graph_size {
let mut sys = empty_system.in_set(labels[i]).before(DummySet);
for label in labels.iter().take(i) {
sys = sys.after(*label);
}
for label in &labels[i + 1..graph_size] {
sys = sys.before(*label);
}
app.add_systems(Update, sys);
}
// Run the app for a single frame.
// This is necessary since dependency resolution does not occur until the game runs.
// FIXME: Running the game clutters up the benchmarks, so ideally we'd be
// able to benchmark the dependency resolution directly.
app.update();
});
});
}
group.finish();
}
pub fn empty_schedule_run(criterion: &mut Criterion) {
let mut app = App::default();
let mut group = criterion.benchmark_group("run_empty_schedule");
let mut schedule = Schedule::default();
schedule.set_executor_kind(bevy_ecs::schedule::ExecutorKind::SingleThreaded);
group.bench_function("SingleThreaded", |bencher| {
bencher.iter(|| schedule.run(app.world_mut()));
});
let mut schedule = Schedule::default();
schedule.set_executor_kind(bevy_ecs::schedule::ExecutorKind::MultiThreaded);
group.bench_function("MultiThreaded", |bencher| {
bencher.iter(|| schedule.run(app.world_mut()));
});
group.finish();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/scheduling/mod.rs | benches/benches/bevy_ecs/scheduling/mod.rs | mod run_condition;
mod running_systems;
mod schedule;
use criterion::criterion_group;
use run_condition::*;
use running_systems::*;
use schedule::*;
criterion_group!(
benches,
run_condition_yes,
run_condition_no,
run_condition_yes_with_query,
run_condition_yes_with_resource,
empty_systems,
busy_systems,
contrived,
schedule,
build_schedule,
empty_schedule_run,
);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/scheduling/running_systems.rs | benches/benches/bevy_ecs/scheduling/running_systems.rs | use bevy_ecs::{component::Component, schedule::Schedule, system::Query, world::World};
use criterion::Criterion;
#[derive(Component)]
struct A(f32);
#[derive(Component)]
struct B(f32);
#[derive(Component)]
struct C(f32);
#[derive(Component)]
struct D(f32);
#[derive(Component)]
struct E(f32);
const ENTITY_BUNCH: usize = 5000;
pub fn empty_systems(criterion: &mut Criterion) {
let mut world = World::new();
let mut group = criterion.benchmark_group("empty_systems");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(3));
fn empty() {}
for amount in [0, 2, 4] {
let mut schedule = Schedule::default();
for _ in 0..amount {
schedule.add_systems(empty);
}
schedule.run(&mut world);
group.bench_function(format!("{amount}_systems"), |bencher| {
bencher.iter(|| {
schedule.run(&mut world);
});
});
}
for amount in [10, 100, 1_000] {
let mut schedule = Schedule::default();
for _ in 0..(amount / 5) {
schedule.add_systems((empty, empty, empty, empty, empty));
}
schedule.run(&mut world);
group.bench_function(format!("{amount}_systems"), |bencher| {
bencher.iter(|| {
schedule.run(&mut world);
});
});
}
group.finish();
}
pub fn busy_systems(criterion: &mut Criterion) {
fn ab(mut q: Query<(&mut A, &mut B)>) {
q.iter_mut().for_each(|(mut a, mut b)| {
core::mem::swap(&mut a.0, &mut b.0);
});
}
fn cd(mut q: Query<(&mut C, &mut D)>) {
q.iter_mut().for_each(|(mut c, mut d)| {
core::mem::swap(&mut c.0, &mut d.0);
});
}
fn ce(mut q: Query<(&mut C, &mut E)>) {
q.iter_mut().for_each(|(mut c, mut e)| {
core::mem::swap(&mut c.0, &mut e.0);
});
}
let mut world = World::new();
let mut group = criterion.benchmark_group("busy_systems");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(3));
for entity_bunches in [1, 3, 5] {
world.spawn_batch((0..4 * ENTITY_BUNCH).map(|_| (A(0.0), B(0.0))));
world.spawn_batch((0..4 * ENTITY_BUNCH).map(|_| (A(0.0), B(0.0), C(0.0))));
world.spawn_batch((0..ENTITY_BUNCH).map(|_| (A(0.0), B(0.0), C(0.0), D(0.0))));
world.spawn_batch((0..ENTITY_BUNCH).map(|_| (A(0.0), B(0.0), C(0.0), E(0.0))));
for system_amount in [3, 9, 15] {
let mut schedule = Schedule::default();
for _ in 0..(system_amount / 3) {
schedule.add_systems((ab, cd, ce));
}
schedule.run(&mut world);
group.bench_function(
format!("{entity_bunches:02}x_entities_{system_amount:02}_systems"),
|bencher| {
bencher.iter(|| {
schedule.run(&mut world);
});
},
);
}
}
group.finish();
}
pub fn contrived(criterion: &mut Criterion) {
fn s_0(mut q_0: Query<(&mut A, &mut B)>) {
q_0.iter_mut().for_each(|(mut c_0, mut c_1)| {
core::mem::swap(&mut c_0.0, &mut c_1.0);
});
}
fn s_1(mut q_0: Query<(&mut A, &mut C)>, mut q_1: Query<(&mut B, &mut D)>) {
q_0.iter_mut().for_each(|(mut c_0, mut c_1)| {
core::mem::swap(&mut c_0.0, &mut c_1.0);
});
q_1.iter_mut().for_each(|(mut c_0, mut c_1)| {
core::mem::swap(&mut c_0.0, &mut c_1.0);
});
}
fn s_2(mut q_0: Query<(&mut C, &mut D)>) {
q_0.iter_mut().for_each(|(mut c_0, mut c_1)| {
core::mem::swap(&mut c_0.0, &mut c_1.0);
});
}
let mut world = World::new();
let mut group = criterion.benchmark_group("contrived");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(3));
for entity_bunches in [1, 3, 5] {
world.spawn_batch((0..ENTITY_BUNCH).map(|_| (A(0.0), B(0.0), C(0.0), D(0.0))));
world.spawn_batch((0..ENTITY_BUNCH).map(|_| (A(0.0), B(0.0))));
world.spawn_batch((0..ENTITY_BUNCH).map(|_| (C(0.0), D(0.0))));
for system_amount in [3, 9, 15] {
let mut schedule = Schedule::default();
for _ in 0..(system_amount / 3) {
schedule.add_systems((s_0, s_1, s_2));
}
schedule.run(&mut world);
group.bench_function(
format!("{entity_bunches:02}x_entities_{system_amount:02}_systems"),
|bencher| {
bencher.iter(|| {
schedule.run(&mut world);
});
},
);
}
}
group.finish();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/scheduling/run_condition.rs | benches/benches/bevy_ecs/scheduling/run_condition.rs | use bevy_ecs::prelude::*;
use criterion::Criterion;
/// A run `Condition` that always returns true
fn yes() -> bool {
true
}
/// A run `Condition` that always returns false
fn no() -> bool {
false
}
pub fn run_condition_yes(criterion: &mut Criterion) {
let mut world = World::new();
let mut group = criterion.benchmark_group("run_condition/yes");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(3));
fn empty() {}
for amount in [10, 100, 1_000] {
let mut schedule = Schedule::default();
for _ in 0..(amount / 5) {
schedule.add_systems((empty, empty, empty, empty, empty).distributive_run_if(yes));
}
// run once to initialize systems
schedule.run(&mut world);
group.bench_function(format!("{amount}_systems"), |bencher| {
bencher.iter(|| {
schedule.run(&mut world);
});
});
}
group.finish();
}
pub fn run_condition_no(criterion: &mut Criterion) {
let mut world = World::new();
let mut group = criterion.benchmark_group("run_condition/no");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(3));
fn empty() {}
for amount in [10, 100, 1_000] {
let mut schedule = Schedule::default();
for _ in 0..(amount / 5) {
schedule.add_systems((empty, empty, empty, empty, empty).distributive_run_if(no));
}
// run once to initialize systems
schedule.run(&mut world);
group.bench_function(format!("{amount}_systems"), |bencher| {
bencher.iter(|| {
schedule.run(&mut world);
});
});
}
group.finish();
}
#[derive(Component)]
struct TestBool(pub bool);
pub fn run_condition_yes_with_query(criterion: &mut Criterion) {
let mut world = World::new();
world.spawn(TestBool(true));
let mut group = criterion.benchmark_group("run_condition/yes_using_query");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(3));
fn empty() {}
fn yes_with_query(query: Single<&TestBool>) -> bool {
query.0
}
for amount in [10, 100, 1_000] {
let mut schedule = Schedule::default();
for _ in 0..(amount / 5) {
schedule.add_systems(
(empty, empty, empty, empty, empty).distributive_run_if(yes_with_query),
);
}
// run once to initialize systems
schedule.run(&mut world);
group.bench_function(format!("{amount}_systems"), |bencher| {
bencher.iter(|| {
schedule.run(&mut world);
});
});
}
group.finish();
}
#[derive(Resource)]
struct TestResource(pub bool);
pub fn run_condition_yes_with_resource(criterion: &mut Criterion) {
let mut world = World::new();
world.insert_resource(TestResource(true));
let mut group = criterion.benchmark_group("run_condition/yes_using_resource");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(3));
fn empty() {}
fn yes_with_resource(res: Res<TestResource>) -> bool {
res.0
}
for amount in [10, 100, 1_000] {
let mut schedule = Schedule::default();
for _ in 0..(amount / 5) {
schedule.add_systems(
(empty, empty, empty, empty, empty).distributive_run_if(yes_with_resource),
);
}
// run once to initialize systems
schedule.run(&mut world);
group.bench_function(format!("{amount}_systems"), |bencher| {
bencher.iter(|| {
schedule.run(&mut world);
});
});
}
group.finish();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/bundles/spawn_one_zst.rs | benches/benches/bevy_ecs/bundles/spawn_one_zst.rs | use benches::bench;
use bevy_ecs::{component::Component, world::World};
use criterion::Criterion;
const ENTITY_COUNT: usize = 10_000;
#[derive(Component)]
struct A;
pub fn spawn_one_zst(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group(bench!("spawn_one_zst"));
group.bench_function("static", |bencher| {
let mut world = World::new();
bencher.iter(|| {
for _ in 0..ENTITY_COUNT {
world.spawn(A);
}
world.clear_entities();
});
});
group.finish();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/bundles/mod.rs | benches/benches/bevy_ecs/bundles/mod.rs | use criterion::criterion_group;
mod insert_many;
mod spawn_many;
mod spawn_many_zst;
mod spawn_one_zst;
criterion_group!(
benches,
spawn_one_zst::spawn_one_zst,
spawn_many_zst::spawn_many_zst,
spawn_many::spawn_many,
insert_many::insert_many,
);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/bundles/insert_many.rs | benches/benches/bevy_ecs/bundles/insert_many.rs | use benches::bench;
use bevy_ecs::{component::Component, world::World};
use criterion::Criterion;
const ENTITY_COUNT: usize = 2_000;
#[derive(Component)]
struct C<const N: usize>(usize);
pub fn insert_many(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group(bench!("insert_many"));
group.bench_function("all", |bencher| {
let mut world = World::new();
bencher.iter(|| {
for _ in 0..ENTITY_COUNT {
world
.spawn_empty()
.insert(C::<0>(1))
.insert(C::<1>(1))
.insert(C::<2>(1))
.insert(C::<3>(1))
.insert(C::<4>(1))
.insert(C::<5>(1))
.insert(C::<6>(1))
.insert(C::<7>(1))
.insert(C::<8>(1))
.insert(C::<9>(1))
.insert(C::<10>(1))
.insert(C::<11>(1))
.insert(C::<12>(1))
.insert(C::<13>(1))
.insert(C::<14>(1));
}
world.clear_entities();
});
});
group.bench_function("only_last", |bencher| {
let mut world = World::new();
bencher.iter(|| {
for _ in 0..ENTITY_COUNT {
world
.spawn((
C::<0>(1),
C::<1>(1),
C::<2>(1),
C::<3>(1),
C::<4>(1),
C::<5>(1),
C::<6>(1),
C::<7>(1),
C::<8>(1),
C::<9>(1),
C::<10>(1),
C::<11>(1),
C::<12>(1),
C::<13>(1),
))
.insert(C::<14>(1));
}
world.clear_entities();
});
});
group.finish();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/bundles/spawn_many.rs | benches/benches/bevy_ecs/bundles/spawn_many.rs | use benches::bench;
use bevy_ecs::{component::Component, world::World};
use criterion::Criterion;
const ENTITY_COUNT: usize = 2_000;
#[derive(Component)]
struct C<const N: usize>(usize);
pub fn spawn_many(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group(bench!("spawn_many"));
group.bench_function("static", |bencher| {
let mut world = World::new();
bencher.iter(|| {
for _ in 0..ENTITY_COUNT {
world.spawn((
C::<0>(1),
C::<1>(1),
C::<2>(1),
C::<3>(1),
C::<4>(1),
C::<5>(1),
C::<6>(1),
C::<7>(1),
C::<8>(1),
C::<9>(1),
C::<10>(1),
C::<11>(1),
C::<12>(1),
C::<13>(1),
C::<14>(1),
));
}
world.clear_entities();
});
});
group.finish();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/bundles/spawn_many_zst.rs | benches/benches/bevy_ecs/bundles/spawn_many_zst.rs | use benches::bench;
use bevy_ecs::{component::Component, world::World};
use criterion::Criterion;
const ENTITY_COUNT: usize = 2_000;
#[derive(Component)]
struct C<const N: usize>;
pub fn spawn_many_zst(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group(bench!("spawn_many_zst"));
group.bench_function("static", |bencher| {
let mut world = World::new();
bencher.iter(|| {
for _ in 0..ENTITY_COUNT {
world.spawn((
C::<0>, C::<1>, C::<2>, C::<3>, C::<4>, C::<5>, C::<6>, C::<7>, C::<8>, C::<9>,
C::<10>, C::<11>, C::<12>, C::<13>, C::<14>,
));
}
world.clear_entities();
});
});
group.finish();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/iteration/iter_simple_foreach_sparse_set.rs | benches/benches/bevy_ecs/iteration/iter_simple_foreach_sparse_set.rs | use bevy_ecs::prelude::*;
use glam::*;
#[derive(Component, Copy, Clone)]
struct Transform(Mat4);
#[derive(Component, Copy, Clone)]
#[component(storage = "SparseSet")]
struct Position(Vec3);
#[derive(Component, Copy, Clone)]
struct Rotation(Vec3);
#[derive(Component, Copy, Clone)]
#[component(storage = "SparseSet")]
struct Velocity(Vec3);
pub struct Benchmark<'w>(World, QueryState<(&'w Velocity, &'w mut Position)>);
impl<'w> Benchmark<'w> {
pub fn new() -> Self {
let mut world = World::new();
world.spawn_batch(core::iter::repeat_n(
(
Transform(Mat4::from_scale(Vec3::ONE)),
Position(Vec3::X),
Rotation(Vec3::X),
Velocity(Vec3::X),
),
10_000,
));
let query = world.query::<(&Velocity, &mut Position)>();
Self(world, query)
}
#[inline(never)]
pub fn run(&mut self) {
self.1
.iter_mut(&mut self.0)
.for_each(|(velocity, mut position)| {
position.0 += velocity.0;
});
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/iteration/iter_frag_wide.rs | benches/benches/bevy_ecs/iteration/iter_frag_wide.rs | use bevy_ecs::prelude::*;
macro_rules! create_entities {
($world:ident; $( $variants:ident ),*) => {
$(
#[derive(Component)]
struct $variants(f32);
for _ in 0..20 {
$world.spawn((
$variants(0.0),
Data::<0>(1.0),
Data::<1>(1.0),
Data::<2>(1.0),
Data::<3>(1.0),
Data::<4>(1.0),
Data::<5>(1.0),
Data::<6>(1.0),
Data::<7>(1.0),
Data::<8>(1.0),
Data::<9>(1.0),
Data::<10>(1.0),
));
}
)*
};
}
#[derive(Component)]
struct Data<const X: usize>(f32);
pub struct Benchmark<'w>(
World,
QueryState<(
&'w mut Data<0>,
&'w mut Data<1>,
&'w mut Data<2>,
&'w mut Data<3>,
&'w mut Data<4>,
&'w mut Data<5>,
&'w mut Data<6>,
&'w mut Data<7>,
&'w mut Data<8>,
&'w mut Data<9>,
&'w mut Data<10>,
)>,
);
impl<'w> Benchmark<'w> {
pub fn new() -> Self {
let mut world = World::new();
create_entities!(world; A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z);
let query = world.query();
Self(world, query)
}
#[inline(never)]
pub fn run(&mut self) {
for mut data in self.1.iter_mut(&mut self.0) {
data.0 .0 *= 2.0;
data.1 .0 *= 2.0;
data.2 .0 *= 2.0;
data.3 .0 *= 2.0;
data.4 .0 *= 2.0;
data.5 .0 *= 2.0;
data.6 .0 *= 2.0;
data.7 .0 *= 2.0;
data.8 .0 *= 2.0;
data.9 .0 *= 2.0;
data.10 .0 *= 2.0;
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/iteration/iter_frag_foreach.rs | benches/benches/bevy_ecs/iteration/iter_frag_foreach.rs | use bevy_ecs::prelude::*;
macro_rules! create_entities {
($world:ident; $( $variants:ident ),*) => {
$(
#[derive(Component)]
struct $variants(f32);
for _ in 0..20 {
$world.spawn(($variants(0.0), Data(1.0)));
}
)*
};
}
#[derive(Component)]
struct Data(f32);
pub struct Benchmark<'w>(World, QueryState<&'w mut Data>);
impl<'w> Benchmark<'w> {
pub fn new() -> Self {
let mut world = World::new();
create_entities!(world; A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z);
let query = world.query::<&mut Data>();
Self(world, query)
}
#[inline(never)]
pub fn run(&mut self) {
self.1.iter_mut(&mut self.0).for_each(|mut data| {
data.0 *= 2.0;
});
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/iteration/iter_simple.rs | benches/benches/bevy_ecs/iteration/iter_simple.rs | use bevy_ecs::prelude::*;
use glam::*;
#[derive(Component, Copy, Clone)]
struct Transform(Mat4);
#[derive(Component, Copy, Clone)]
struct Position(Vec3);
#[derive(Component, Copy, Clone)]
struct Rotation(Vec3);
#[derive(Component, Copy, Clone)]
struct Velocity(Vec3);
pub struct Benchmark<'w>(World, QueryState<(&'w Velocity, &'w mut Position)>);
impl<'w> Benchmark<'w> {
pub fn new() -> Self {
let mut world = World::new();
world.spawn_batch(core::iter::repeat_n(
(
Transform(Mat4::from_scale(Vec3::ONE)),
Position(Vec3::X),
Rotation(Vec3::X),
Velocity(Vec3::X),
),
10_000,
));
let query = world.query::<(&Velocity, &mut Position)>();
Self(world, query)
}
#[inline(never)]
pub fn run(&mut self) {
for (velocity, mut position) in self.1.iter_mut(&mut self.0) {
position.0 += velocity.0;
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/iteration/iter_simple_foreach_hybrid.rs | benches/benches/bevy_ecs/iteration/iter_simple_foreach_hybrid.rs | use bevy_ecs::prelude::*;
use rand::{prelude::SliceRandom, SeedableRng};
use rand_chacha::ChaCha8Rng;
#[derive(Component, Copy, Clone)]
struct TableData(f32);
#[derive(Component, Copy, Clone)]
#[component(storage = "SparseSet")]
struct SparseData(f32);
fn deterministic_rand() -> ChaCha8Rng {
ChaCha8Rng::seed_from_u64(42)
}
pub struct Benchmark<'w>(World, QueryState<(&'w mut TableData, &'w SparseData)>);
impl<'w> Benchmark<'w> {
pub fn new() -> Self {
let mut world = World::new();
let mut v = vec![];
for _ in 0..10000 {
world.spawn((TableData(0.0), SparseData(0.0)));
v.push(world.spawn(TableData(0.)).id());
}
// by shuffling ,randomize the archetype iteration order to significantly deviate from the table order. This maximizes the loss of cache locality during archetype-based iteration.
v.shuffle(&mut deterministic_rand());
for e in v.into_iter() {
world.entity_mut(e).despawn();
}
let query = world.query::<(&mut TableData, &SparseData)>();
Self(world, query)
}
#[inline(never)]
pub fn run(&mut self) {
self.1
.iter_mut(&mut self.0)
.for_each(|(mut v1, v2)| v1.0 += v2.0);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/iteration/iter_simple_foreach.rs | benches/benches/bevy_ecs/iteration/iter_simple_foreach.rs | use bevy_ecs::prelude::*;
use glam::*;
#[derive(Component, Copy, Clone)]
struct Transform(Mat4);
#[derive(Component, Copy, Clone)]
struct Position(Vec3);
#[derive(Component, Copy, Clone)]
struct Rotation(Vec3);
#[derive(Component, Copy, Clone)]
struct Velocity(Vec3);
pub struct Benchmark<'w>(World, QueryState<(&'w Velocity, &'w mut Position)>);
impl<'w> Benchmark<'w> {
pub fn new() -> Self {
let mut world = World::new();
world.spawn_batch(core::iter::repeat_n(
(
Transform(Mat4::from_scale(Vec3::ONE)),
Position(Vec3::X),
Rotation(Vec3::X),
Velocity(Vec3::X),
),
10_000,
));
let query = world.query::<(&Velocity, &mut Position)>();
Self(world, query)
}
#[inline(never)]
pub fn run(&mut self) {
self.1
.iter_mut(&mut self.0)
.for_each(|(velocity, mut position)| {
position.0 += velocity.0;
});
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/iteration/iter_simple_wide_sparse_set.rs | benches/benches/bevy_ecs/iteration/iter_simple_wide_sparse_set.rs | use bevy_ecs::prelude::*;
use glam::*;
#[derive(Component, Copy, Clone)]
struct Transform(Mat4);
#[derive(Component, Copy, Clone)]
#[component(storage = "SparseSet")]
struct Position<const X: usize>(Vec3);
#[derive(Component, Copy, Clone)]
struct Rotation(Vec3);
#[derive(Component, Copy, Clone)]
#[component(storage = "SparseSet")]
struct Velocity<const X: usize>(Vec3);
pub struct Benchmark<'w>(
World,
QueryState<(
&'w Velocity<0>,
&'w mut Position<0>,
&'w Velocity<1>,
&'w mut Position<1>,
&'w Velocity<2>,
&'w mut Position<2>,
&'w Velocity<3>,
&'w mut Position<3>,
&'w Velocity<4>,
&'w mut Position<4>,
)>,
);
impl<'w> Benchmark<'w> {
pub fn new() -> Self {
let mut world = World::new();
world.spawn_batch(core::iter::repeat_n(
(
Transform(Mat4::from_scale(Vec3::ONE)),
Rotation(Vec3::X),
Position::<0>(Vec3::X),
Velocity::<0>(Vec3::X),
Position::<1>(Vec3::X),
Velocity::<1>(Vec3::X),
Position::<2>(Vec3::X),
Velocity::<2>(Vec3::X),
Position::<3>(Vec3::X),
Velocity::<3>(Vec3::X),
Position::<4>(Vec3::X),
Velocity::<4>(Vec3::X),
),
10_000,
));
let query = world.query();
Self(world, query)
}
#[inline(never)]
pub fn run(&mut self) {
for mut item in self.1.iter_mut(&mut self.0) {
item.1 .0 += item.0 .0;
item.3 .0 += item.2 .0;
item.5 .0 += item.4 .0;
item.7 .0 += item.6 .0;
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/iteration/iter_simple_foreach_wide_sparse_set.rs | benches/benches/bevy_ecs/iteration/iter_simple_foreach_wide_sparse_set.rs | use bevy_ecs::prelude::*;
use glam::*;
#[derive(Component, Copy, Clone)]
struct Transform(Mat4);
#[derive(Component, Copy, Clone)]
#[component(storage = "SparseSet")]
struct Position<const X: usize>(Vec3);
#[derive(Component, Copy, Clone)]
struct Rotation(Vec3);
#[derive(Component, Copy, Clone)]
#[component(storage = "SparseSet")]
struct Velocity<const X: usize>(Vec3);
pub struct Benchmark<'w>(
World,
QueryState<(
&'w Velocity<0>,
&'w mut Position<0>,
&'w Velocity<1>,
&'w mut Position<1>,
&'w Velocity<2>,
&'w mut Position<2>,
&'w Velocity<3>,
&'w mut Position<3>,
&'w Velocity<4>,
&'w mut Position<4>,
)>,
);
impl<'w> Benchmark<'w> {
pub fn new() -> Self {
let mut world = World::new();
world.spawn_batch(core::iter::repeat_n(
(
Transform(Mat4::from_scale(Vec3::ONE)),
Rotation(Vec3::X),
Position::<0>(Vec3::X),
Velocity::<0>(Vec3::X),
Position::<1>(Vec3::X),
Velocity::<1>(Vec3::X),
Position::<2>(Vec3::X),
Velocity::<2>(Vec3::X),
Position::<3>(Vec3::X),
Velocity::<3>(Vec3::X),
Position::<4>(Vec3::X),
Velocity::<4>(Vec3::X),
),
10_000,
));
let query = world.query();
Self(world, query)
}
#[inline(never)]
pub fn run(&mut self) {
self.1.iter_mut(&mut self.0).for_each(|mut item| {
item.1 .0 += item.0 .0;
item.3 .0 += item.2 .0;
item.5 .0 += item.4 .0;
item.7 .0 += item.6 .0;
});
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/iteration/par_iter_simple_foreach_hybrid.rs | benches/benches/bevy_ecs/iteration/par_iter_simple_foreach_hybrid.rs | use bevy_ecs::prelude::*;
use bevy_tasks::{ComputeTaskPool, TaskPool};
use rand::{prelude::SliceRandom, SeedableRng};
use rand_chacha::ChaCha8Rng;
#[derive(Component, Copy, Clone)]
struct TableData(f32);
#[derive(Component, Copy, Clone)]
#[component(storage = "SparseSet")]
struct SparseData(f32);
fn deterministic_rand() -> ChaCha8Rng {
ChaCha8Rng::seed_from_u64(42)
}
pub struct Benchmark<'w>(World, QueryState<(&'w mut TableData, &'w SparseData)>);
impl<'w> Benchmark<'w> {
pub fn new() -> Self {
let mut world = World::new();
ComputeTaskPool::get_or_init(TaskPool::default);
let mut v = vec![];
for _ in 0..100000 {
world.spawn((TableData(0.0), SparseData(0.0)));
v.push(world.spawn(TableData(0.)).id());
}
// by shuffling ,randomize the archetype iteration order to significantly deviate from the table order. This maximizes the loss of cache locality during archetype-based iteration.
v.shuffle(&mut deterministic_rand());
for e in v.into_iter() {
world.entity_mut(e).despawn();
}
let query = world.query::<(&mut TableData, &SparseData)>();
Self(world, query)
}
#[inline(never)]
pub fn run(&mut self) {
self.1
.par_iter_mut(&mut self.0)
.for_each(|(mut v1, v2)| v1.0 += v2.0);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/iteration/mod.rs | benches/benches/bevy_ecs/iteration/mod.rs | mod heavy_compute;
mod iter_frag;
mod iter_frag_foreach;
mod iter_frag_foreach_sparse;
mod iter_frag_foreach_wide;
mod iter_frag_foreach_wide_sparse;
mod iter_frag_sparse;
mod iter_frag_wide;
mod iter_frag_wide_sparse;
mod iter_simple;
mod iter_simple_foreach;
mod iter_simple_foreach_hybrid;
mod iter_simple_foreach_sparse_set;
mod iter_simple_foreach_wide;
mod iter_simple_foreach_wide_sparse_set;
mod iter_simple_sparse_set;
mod iter_simple_system;
mod iter_simple_wide;
mod iter_simple_wide_sparse_set;
mod par_iter_simple;
mod par_iter_simple_foreach_hybrid;
use criterion::{criterion_group, Criterion};
use heavy_compute::*;
criterion_group!(
benches,
iter_frag,
iter_frag_sparse,
iter_simple,
heavy_compute,
par_iter_simple,
);
fn iter_simple(c: &mut Criterion) {
let mut group = c.benchmark_group("iter_simple");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
group.bench_function("base", |b| {
let mut bench = iter_simple::Benchmark::new();
b.iter(move || bench.run());
});
group.bench_function("wide", |b| {
let mut bench = iter_simple_wide::Benchmark::new();
b.iter(move || bench.run());
});
group.bench_function("system", |b| {
let mut bench = iter_simple_system::Benchmark::new();
b.iter(move || bench.run());
});
group.bench_function("sparse_set", |b| {
let mut bench = iter_simple_sparse_set::Benchmark::new();
b.iter(move || bench.run());
});
group.bench_function("wide_sparse_set", |b| {
let mut bench = iter_simple_wide_sparse_set::Benchmark::new();
b.iter(move || bench.run());
});
group.bench_function("foreach", |b| {
let mut bench = iter_simple_foreach::Benchmark::new();
b.iter(move || bench.run());
});
group.bench_function("foreach_wide", |b| {
let mut bench = iter_simple_foreach_wide::Benchmark::new();
b.iter(move || bench.run());
});
group.bench_function("foreach_sparse_set", |b| {
let mut bench = iter_simple_foreach_sparse_set::Benchmark::new();
b.iter(move || bench.run());
});
group.bench_function("foreach_wide_sparse_set", |b| {
let mut bench = iter_simple_foreach_wide_sparse_set::Benchmark::new();
b.iter(move || bench.run());
});
group.bench_function("foreach_hybrid", |b| {
let mut bench = iter_simple_foreach_hybrid::Benchmark::new();
b.iter(move || bench.run());
});
group.finish();
}
fn iter_frag(c: &mut Criterion) {
let mut group = c.benchmark_group("iter_fragmented");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
group.bench_function("base", |b| {
let mut bench = iter_frag::Benchmark::new();
b.iter(move || bench.run());
});
group.bench_function("wide", |b| {
let mut bench = iter_frag_wide::Benchmark::new();
b.iter(move || bench.run());
});
group.bench_function("foreach", |b| {
let mut bench = iter_frag_foreach::Benchmark::new();
b.iter(move || bench.run());
});
group.bench_function("foreach_wide", |b| {
let mut bench = iter_frag_foreach_wide::Benchmark::new();
b.iter(move || bench.run());
});
group.finish();
}
fn iter_frag_sparse(c: &mut Criterion) {
let mut group = c.benchmark_group("iter_fragmented_sparse");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
group.bench_function("base", |b| {
let mut bench = iter_frag_sparse::Benchmark::new();
b.iter(move || bench.run());
});
group.bench_function("wide", |b| {
let mut bench = iter_frag_wide_sparse::Benchmark::new();
b.iter(move || bench.run());
});
group.bench_function("foreach", |b| {
let mut bench = iter_frag_foreach_sparse::Benchmark::new();
b.iter(move || bench.run());
});
group.bench_function("foreach_wide", |b| {
let mut bench = iter_frag_foreach_wide_sparse::Benchmark::new();
b.iter(move || bench.run());
});
group.finish();
}
fn par_iter_simple(c: &mut Criterion) {
let mut group = c.benchmark_group("par_iter_simple");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
for f in [0, 10, 100, 1000] {
group.bench_function(format!("with_{f}_fragment"), |b| {
let mut bench = par_iter_simple::Benchmark::new(f);
b.iter(move || bench.run());
});
}
group.bench_function("hybrid".to_string(), |b| {
let mut bench = par_iter_simple_foreach_hybrid::Benchmark::new();
b.iter(move || bench.run());
});
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/iteration/iter_frag_sparse.rs | benches/benches/bevy_ecs/iteration/iter_frag_sparse.rs | use bevy_ecs::prelude::*;
macro_rules! create_entities {
($world:ident; $( $variants:ident ),*) => {
$(
#[derive(Component)]
struct $variants(f32);
for _ in 0..5 {
$world.spawn($variants(0.0));
}
)*
};
}
#[derive(Component)]
struct Data(f32);
pub struct Benchmark<'w>(World, QueryState<&'w mut Data>);
impl<'w> Benchmark<'w> {
pub fn new() -> Self {
let mut world = World::new();
for _ in 0..5 {
world.spawn(Data(1.0));
}
create_entities!(world; C00, C01, C02, C03, C04, C05, C06, C07, C08, C09);
create_entities!(world; C10, C11, C12, C13, C14, C15, C16, C17, C18, C19);
create_entities!(world; C20, C21, C22, C23, C24, C25, C26, C27, C28, C29);
create_entities!(world; C30, C31, C32, C33, C34, C35, C36, C37, C38, C39);
create_entities!(world; C40, C41, C42, C43, C44, C45, C46, C47, C48, C49);
create_entities!(world; C50, C51, C52, C53, C54, C55, C56, C57, C58, C59);
create_entities!(world; C60, C61, C62, C63, C64, C65, C66, C67, C68, C69);
create_entities!(world; C70, C71, C72, C73, C74, C75, C76, C77, C78, C79);
create_entities!(world; C80, C81, C82, C83, C84, C85, C86, C87, C88, C89);
create_entities!(world; C90, C91, C92, C93, C94, C95, C96, C97, C98, C99);
let query = world.query::<&mut Data>();
Self(world, query)
}
#[inline(never)]
pub fn run(&mut self) {
for mut data in self.1.iter_mut(&mut self.0) {
data.0 *= 2.0;
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/iteration/iter_simple_wide.rs | benches/benches/bevy_ecs/iteration/iter_simple_wide.rs | use bevy_ecs::prelude::*;
use glam::*;
#[derive(Component, Copy, Clone)]
struct Transform(Mat4);
#[derive(Component, Copy, Clone)]
struct Position<const X: usize>(Vec3);
#[derive(Component, Copy, Clone)]
struct Rotation(Vec3);
#[derive(Component, Copy, Clone)]
struct Velocity<const X: usize>(Vec3);
pub struct Benchmark<'w>(
World,
QueryState<(
&'w Velocity<0>,
&'w mut Position<0>,
&'w Velocity<1>,
&'w mut Position<1>,
&'w Velocity<2>,
&'w mut Position<2>,
&'w Velocity<3>,
&'w mut Position<3>,
&'w Velocity<4>,
&'w mut Position<4>,
)>,
);
impl<'w> Benchmark<'w> {
pub fn new() -> Self {
let mut world = World::new();
world.spawn_batch(core::iter::repeat_n(
(
Transform(Mat4::from_scale(Vec3::ONE)),
Rotation(Vec3::X),
Position::<0>(Vec3::X),
Velocity::<0>(Vec3::X),
Position::<1>(Vec3::X),
Velocity::<1>(Vec3::X),
Position::<2>(Vec3::X),
Velocity::<2>(Vec3::X),
Position::<3>(Vec3::X),
Velocity::<3>(Vec3::X),
Position::<4>(Vec3::X),
Velocity::<4>(Vec3::X),
),
10_000,
));
let query = world.query();
Self(world, query)
}
#[inline(never)]
pub fn run(&mut self) {
for mut item in self.1.iter_mut(&mut self.0) {
item.1 .0 += item.0 .0;
item.3 .0 += item.2 .0;
item.5 .0 += item.4 .0;
item.7 .0 += item.6 .0;
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/iteration/heavy_compute.rs | benches/benches/bevy_ecs/iteration/heavy_compute.rs | use bevy_ecs::prelude::*;
use bevy_tasks::{ComputeTaskPool, TaskPool};
use criterion::Criterion;
use glam::*;
pub fn heavy_compute(c: &mut Criterion) {
#[derive(Component, Copy, Clone)]
struct Position(Vec3);
#[derive(Component, Copy, Clone)]
struct Rotation(Vec3);
#[derive(Component, Copy, Clone)]
struct Velocity(Vec3);
#[derive(Component, Copy, Clone)]
struct Transform(Mat4);
let mut group = c.benchmark_group("heavy_compute");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
group.bench_function("base", |b| {
ComputeTaskPool::get_or_init(TaskPool::default);
let mut world = World::default();
world.spawn_batch((0..1000).map(|_| {
(
Transform(Mat4::from_axis_angle(Vec3::X, 1.2)),
Position(Vec3::X),
Rotation(Vec3::X),
Velocity(Vec3::X),
)
}));
fn sys(mut query: Query<(&mut Position, &mut Transform)>) {
query.par_iter_mut().for_each(|(mut pos, mut mat)| {
for _ in 0..100 {
mat.0 = mat.0.inverse();
}
pos.0 = mat.0.transform_vector3(pos.0);
});
}
let mut system = IntoSystem::into_system(sys);
system.initialize(&mut world);
b.iter(move || system.run((), &mut world));
});
group.finish();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/iteration/iter_frag_foreach_wide.rs | benches/benches/bevy_ecs/iteration/iter_frag_foreach_wide.rs | use bevy_ecs::prelude::*;
macro_rules! create_entities {
($world:ident; $( $variants:ident ),*) => {
$(
#[derive(Component)]
struct $variants(f32);
for _ in 0..20 {
$world.spawn((
$variants(0.0),
Data::<0>(1.0),
Data::<1>(1.0),
Data::<2>(1.0),
Data::<3>(1.0),
Data::<4>(1.0),
Data::<5>(1.0),
Data::<6>(1.0),
Data::<7>(1.0),
Data::<8>(1.0),
Data::<9>(1.0),
Data::<10>(1.0),
));
}
)*
};
}
#[derive(Component)]
struct Data<const X: usize>(f32);
pub struct Benchmark<'w>(
World,
QueryState<(
&'w mut Data<0>,
&'w mut Data<1>,
&'w mut Data<2>,
&'w mut Data<3>,
&'w mut Data<4>,
&'w mut Data<5>,
&'w mut Data<6>,
&'w mut Data<7>,
&'w mut Data<8>,
&'w mut Data<9>,
&'w mut Data<10>,
)>,
);
impl<'w> Benchmark<'w> {
pub fn new() -> Self {
let mut world = World::new();
create_entities!(world; A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z);
let query = world.query();
Self(world, query)
}
#[inline(never)]
pub fn run(&mut self) {
self.1.iter_mut(&mut self.0).for_each(|mut data| {
data.0 .0 *= 2.0;
data.1 .0 *= 2.0;
data.2 .0 *= 2.0;
data.3 .0 *= 2.0;
data.4 .0 *= 2.0;
data.5 .0 *= 2.0;
data.6 .0 *= 2.0;
data.7 .0 *= 2.0;
data.8 .0 *= 2.0;
data.9 .0 *= 2.0;
data.10 .0 *= 2.0;
});
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/iteration/iter_frag_foreach_sparse.rs | benches/benches/bevy_ecs/iteration/iter_frag_foreach_sparse.rs | use bevy_ecs::prelude::*;
macro_rules! create_entities {
($world:ident; $( $variants:ident ),*) => {
$(
#[derive(Component)]
struct $variants(f32);
for _ in 0..5 {
$world.spawn($variants(0.0));
}
)*
};
}
#[derive(Component)]
struct Data(f32);
pub struct Benchmark<'w>(World, QueryState<&'w mut Data>);
impl<'w> Benchmark<'w> {
pub fn new() -> Self {
let mut world = World::new();
for _ in 0..5 {
world.spawn(Data(1.0));
}
create_entities!(world; C00, C01, C02, C03, C04, C05, C06, C07, C08, C09);
create_entities!(world; C10, C11, C12, C13, C14, C15, C16, C17, C18, C19);
create_entities!(world; C20, C21, C22, C23, C24, C25, C26, C27, C28, C29);
create_entities!(world; C30, C31, C32, C33, C34, C35, C36, C37, C38, C39);
create_entities!(world; C40, C41, C42, C43, C44, C45, C46, C47, C48, C49);
create_entities!(world; C50, C51, C52, C53, C54, C55, C56, C57, C58, C59);
create_entities!(world; C60, C61, C62, C63, C64, C65, C66, C67, C68, C69);
create_entities!(world; C70, C71, C72, C73, C74, C75, C76, C77, C78, C79);
create_entities!(world; C80, C81, C82, C83, C84, C85, C86, C87, C88, C89);
create_entities!(world; C90, C91, C92, C93, C94, C95, C96, C97, C98, C99);
let query = world.query::<&mut Data>();
Self(world, query)
}
#[inline(never)]
pub fn run(&mut self) {
self.1.iter_mut(&mut self.0).for_each(|mut data| {
data.0 *= 2.0;
});
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/iteration/iter_simple_system.rs | benches/benches/bevy_ecs/iteration/iter_simple_system.rs | use bevy_ecs::prelude::*;
use glam::*;
#[derive(Component, Copy, Clone)]
struct Transform(Mat4);
#[derive(Component, Copy, Clone)]
struct Position(Vec3);
#[derive(Component, Copy, Clone)]
struct Rotation(Vec3);
#[derive(Component, Copy, Clone)]
struct Velocity(Vec3);
pub struct Benchmark(World, Box<dyn System<In = (), Out = ()>>);
impl Benchmark {
pub fn new() -> Self {
let mut world = World::new();
world.spawn_batch(core::iter::repeat_n(
(
Transform(Mat4::from_scale(Vec3::ONE)),
Position(Vec3::X),
Rotation(Vec3::X),
Velocity(Vec3::X),
),
10_000,
));
fn query_system(mut query: Query<(&Velocity, &mut Position)>) {
for (velocity, mut position) in &mut query {
position.0 += velocity.0;
}
}
let mut system = IntoSystem::into_system(query_system);
system.initialize(&mut world);
Self(world, Box::new(system))
}
#[inline(never)]
pub fn run(&mut self) {
self.1.run((), &mut self.0).unwrap();
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/iteration/iter_simple_foreach_wide.rs | benches/benches/bevy_ecs/iteration/iter_simple_foreach_wide.rs | use bevy_ecs::prelude::*;
use glam::*;
#[derive(Component, Copy, Clone)]
struct Transform(Mat4);
#[derive(Component, Copy, Clone)]
struct Position<const X: usize>(Vec3);
#[derive(Component, Copy, Clone)]
struct Rotation(Vec3);
#[derive(Component, Copy, Clone)]
struct Velocity<const X: usize>(Vec3);
pub struct Benchmark<'w>(
World,
QueryState<(
&'w Velocity<0>,
&'w mut Position<0>,
&'w Velocity<1>,
&'w mut Position<1>,
&'w Velocity<2>,
&'w mut Position<2>,
&'w Velocity<3>,
&'w mut Position<3>,
&'w Velocity<4>,
&'w mut Position<4>,
)>,
);
impl<'w> Benchmark<'w> {
pub fn new() -> Self {
let mut world = World::new();
world.spawn_batch(core::iter::repeat_n(
(
Transform(Mat4::from_scale(Vec3::ONE)),
Rotation(Vec3::X),
Position::<0>(Vec3::X),
Velocity::<0>(Vec3::X),
Position::<1>(Vec3::X),
Velocity::<1>(Vec3::X),
Position::<2>(Vec3::X),
Velocity::<2>(Vec3::X),
Position::<3>(Vec3::X),
Velocity::<3>(Vec3::X),
Position::<4>(Vec3::X),
Velocity::<4>(Vec3::X),
),
10_000,
));
let query = world.query();
Self(world, query)
}
#[inline(never)]
pub fn run(&mut self) {
self.1.iter_mut(&mut self.0).for_each(|mut item| {
item.1 .0 += item.0 .0;
item.3 .0 += item.2 .0;
item.5 .0 += item.4 .0;
item.7 .0 += item.6 .0;
});
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/iteration/par_iter_simple.rs | benches/benches/bevy_ecs/iteration/par_iter_simple.rs | use bevy_ecs::prelude::*;
use bevy_tasks::{ComputeTaskPool, TaskPool};
use glam::*;
#[derive(Component, Copy, Clone)]
struct Transform(Mat4);
#[derive(Component, Copy, Clone)]
struct Position(Vec3);
#[derive(Component, Copy, Clone)]
struct Rotation(Vec3);
#[derive(Component, Copy, Clone)]
struct Velocity(Vec3);
#[derive(Component, Copy, Clone, Default)]
struct Data<const X: u16>(f32);
pub struct Benchmark<'w>(World, QueryState<(&'w Velocity, &'w mut Position)>);
fn insert_if_bit_enabled<const B: u16>(entity: &mut EntityWorldMut, i: u16) {
if i & (1 << B) != 0 {
entity.insert(Data::<B>(1.0));
}
}
impl<'w> Benchmark<'w> {
pub fn new(fragment: u16) -> Self {
ComputeTaskPool::get_or_init(TaskPool::default);
let mut world = World::new();
let iter = world.spawn_batch(core::iter::repeat_n(
(
Transform(Mat4::from_scale(Vec3::ONE)),
Position(Vec3::X),
Rotation(Vec3::X),
Velocity(Vec3::X),
),
100_000,
));
let entities = iter.into_iter().collect::<Vec<Entity>>();
for i in 0..fragment {
let mut e = world.entity_mut(entities[i as usize]);
insert_if_bit_enabled::<0>(&mut e, i);
insert_if_bit_enabled::<1>(&mut e, i);
insert_if_bit_enabled::<2>(&mut e, i);
insert_if_bit_enabled::<3>(&mut e, i);
insert_if_bit_enabled::<4>(&mut e, i);
insert_if_bit_enabled::<5>(&mut e, i);
insert_if_bit_enabled::<6>(&mut e, i);
insert_if_bit_enabled::<7>(&mut e, i);
insert_if_bit_enabled::<8>(&mut e, i);
insert_if_bit_enabled::<9>(&mut e, i);
insert_if_bit_enabled::<10>(&mut e, i);
insert_if_bit_enabled::<11>(&mut e, i);
insert_if_bit_enabled::<12>(&mut e, i);
insert_if_bit_enabled::<13>(&mut e, i);
insert_if_bit_enabled::<14>(&mut e, i);
insert_if_bit_enabled::<15>(&mut e, i);
}
let query = world.query::<(&Velocity, &mut Position)>();
Self(world, query)
}
#[inline(never)]
pub fn run(&mut self) {
self.1
.par_iter_mut(&mut self.0)
.for_each(|(v, mut p)| p.0 += v.0);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/iteration/iter_frag_wide_sparse.rs | benches/benches/bevy_ecs/iteration/iter_frag_wide_sparse.rs | use bevy_ecs::prelude::*;
macro_rules! create_entities {
($world:ident; $( $variants:ident ),*) => {
$(
#[derive(Component)]
struct $variants(f32);
for _ in 0..5 {
$world.spawn($variants(0.0));
}
)*
};
}
#[derive(Component)]
struct Data<const X: usize>(f32);
pub struct Benchmark<'w>(
World,
QueryState<(
&'w mut Data<0>,
&'w mut Data<1>,
&'w mut Data<2>,
&'w mut Data<3>,
&'w mut Data<4>,
&'w mut Data<5>,
&'w mut Data<6>,
&'w mut Data<7>,
&'w mut Data<8>,
&'w mut Data<9>,
&'w mut Data<10>,
)>,
);
impl<'w> Benchmark<'w> {
pub fn new() -> Self {
let mut world = World::new();
for _ in 0..5 {
world.spawn((
Data::<0>(1.0),
Data::<1>(1.0),
Data::<2>(1.0),
Data::<3>(1.0),
Data::<4>(1.0),
Data::<5>(1.0),
Data::<6>(1.0),
Data::<7>(1.0),
Data::<8>(1.0),
Data::<9>(1.0),
Data::<10>(1.0),
));
}
create_entities!(world; C00, C01, C02, C03, C04, C05, C06, C07, C08, C09);
create_entities!(world; C10, C11, C12, C13, C14, C15, C16, C17, C18, C19);
create_entities!(world; C20, C21, C22, C23, C24, C25, C26, C27, C28, C29);
create_entities!(world; C30, C31, C32, C33, C34, C35, C36, C37, C38, C39);
create_entities!(world; C40, C41, C42, C43, C44, C45, C46, C47, C48, C49);
create_entities!(world; C50, C51, C52, C53, C54, C55, C56, C57, C58, C59);
create_entities!(world; C60, C61, C62, C63, C64, C65, C66, C67, C68, C69);
create_entities!(world; C70, C71, C72, C73, C74, C75, C76, C77, C78, C79);
create_entities!(world; C80, C81, C82, C83, C84, C85, C86, C87, C88, C89);
create_entities!(world; C90, C91, C92, C93, C94, C95, C96, C97, C98, C99);
let query = world.query();
Self(world, query)
}
#[inline(never)]
pub fn run(&mut self) {
for mut data in self.1.iter_mut(&mut self.0) {
data.0 .0 *= 2.0;
data.1 .0 *= 2.0;
data.2 .0 *= 2.0;
data.3 .0 *= 2.0;
data.4 .0 *= 2.0;
data.5 .0 *= 2.0;
data.6 .0 *= 2.0;
data.7 .0 *= 2.0;
data.8 .0 *= 2.0;
data.9 .0 *= 2.0;
data.10 .0 *= 2.0;
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/iteration/iter_frag_foreach_wide_sparse.rs | benches/benches/bevy_ecs/iteration/iter_frag_foreach_wide_sparse.rs | use bevy_ecs::prelude::*;
macro_rules! create_entities {
($world:ident; $( $variants:ident ),*) => {
$(
#[derive(Component)]
struct $variants(f32);
for _ in 0..5 {
$world.spawn($variants(0.0));
}
)*
};
}
#[derive(Component)]
struct Data<const X: usize>(f32);
pub struct Benchmark<'w>(
World,
QueryState<(
&'w mut Data<0>,
&'w mut Data<1>,
&'w mut Data<2>,
&'w mut Data<3>,
&'w mut Data<4>,
&'w mut Data<5>,
&'w mut Data<6>,
&'w mut Data<7>,
&'w mut Data<8>,
&'w mut Data<9>,
&'w mut Data<10>,
)>,
);
impl<'w> Benchmark<'w> {
pub fn new() -> Self {
let mut world = World::new();
for _ in 0..5 {
world.spawn((
Data::<0>(1.0),
Data::<1>(1.0),
Data::<2>(1.0),
Data::<3>(1.0),
Data::<4>(1.0),
Data::<5>(1.0),
Data::<6>(1.0),
Data::<7>(1.0),
Data::<8>(1.0),
Data::<9>(1.0),
Data::<10>(1.0),
));
}
create_entities!(world; C00, C01, C02, C03, C04, C05, C06, C07, C08, C09);
create_entities!(world; C10, C11, C12, C13, C14, C15, C16, C17, C18, C19);
create_entities!(world; C20, C21, C22, C23, C24, C25, C26, C27, C28, C29);
create_entities!(world; C30, C31, C32, C33, C34, C35, C36, C37, C38, C39);
create_entities!(world; C40, C41, C42, C43, C44, C45, C46, C47, C48, C49);
create_entities!(world; C50, C51, C52, C53, C54, C55, C56, C57, C58, C59);
create_entities!(world; C60, C61, C62, C63, C64, C65, C66, C67, C68, C69);
create_entities!(world; C70, C71, C72, C73, C74, C75, C76, C77, C78, C79);
create_entities!(world; C80, C81, C82, C83, C84, C85, C86, C87, C88, C89);
create_entities!(world; C90, C91, C92, C93, C94, C95, C96, C97, C98, C99);
let query = world.query();
Self(world, query)
}
#[inline(never)]
pub fn run(&mut self) {
self.1.iter_mut(&mut self.0).for_each(|mut data| {
data.0 .0 *= 2.0;
data.1 .0 *= 2.0;
data.2 .0 *= 2.0;
data.3 .0 *= 2.0;
data.4 .0 *= 2.0;
data.5 .0 *= 2.0;
data.6 .0 *= 2.0;
data.7 .0 *= 2.0;
data.8 .0 *= 2.0;
data.9 .0 *= 2.0;
data.10 .0 *= 2.0;
});
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/iteration/iter_frag.rs | benches/benches/bevy_ecs/iteration/iter_frag.rs | use bevy_ecs::prelude::*;
macro_rules! create_entities {
($world:ident; $( $variants:ident ),*) => {
$(
#[derive(Component)]
struct $variants(f32);
for _ in 0..20 {
$world.spawn(($variants(0.0), Data(1.0)));
}
)*
};
}
#[derive(Component)]
struct Data(f32);
pub struct Benchmark<'w>(World, QueryState<&'w mut Data>);
impl<'w> Benchmark<'w> {
pub fn new() -> Self {
let mut world = World::new();
create_entities!(world; A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z);
let query = world.query::<&mut Data>();
Self(world, query)
}
#[inline(never)]
pub fn run(&mut self) {
for mut data in self.1.iter_mut(&mut self.0) {
data.0 *= 2.0;
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/iteration/iter_simple_sparse_set.rs | benches/benches/bevy_ecs/iteration/iter_simple_sparse_set.rs | use bevy_ecs::prelude::*;
use glam::*;
#[derive(Component, Copy, Clone)]
struct Transform(Mat4);
#[derive(Component, Copy, Clone)]
#[component(storage = "SparseSet")]
struct Position(Vec3);
#[derive(Component, Copy, Clone)]
struct Rotation(Vec3);
#[derive(Component, Copy, Clone)]
#[component(storage = "SparseSet")]
struct Velocity(Vec3);
pub struct Benchmark<'w>(World, QueryState<(&'w Velocity, &'w mut Position)>);
impl<'w> Benchmark<'w> {
pub fn new() -> Self {
let mut world = World::new();
world.spawn_batch(core::iter::repeat_n(
(
Transform(Mat4::from_scale(Vec3::ONE)),
Position(Vec3::X),
Rotation(Vec3::X),
Velocity(Vec3::X),
),
10_000,
));
let query = world.query::<(&Velocity, &mut Position)>();
Self(world, query)
}
#[inline(never)]
pub fn run(&mut self) {
for (velocity, mut position) in self.1.iter_mut(&mut self.0) {
position.0 += velocity.0;
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/components/add_remove_very_big_table.rs | benches/benches/bevy_ecs/components/add_remove_very_big_table.rs | #![expect(
dead_code,
reason = "The `Mat4`s in the structs are used to bloat the size of the structs for benchmarking purposes."
)]
use bevy_ecs::prelude::*;
use glam::*;
#[derive(Component, Copy, Clone)]
struct A<const N: usize>(Mat4);
#[derive(Component, Copy, Clone)]
struct B<const N: usize>(Mat4);
#[derive(Component, Copy, Clone)]
struct C<const N: usize>(Mat4);
#[derive(Component, Copy, Clone)]
struct D<const N: usize>(Mat4);
#[derive(Component, Copy, Clone)]
struct E<const N: usize>(Mat4);
#[derive(Component, Copy, Clone)]
struct F<const N: usize>(Mat4);
#[derive(Component, Copy, Clone)]
struct Z<const N: usize>;
pub struct Benchmark(World, Vec<Entity>);
impl Benchmark {
pub fn new() -> Self {
let mut world = World::default();
let mut entities = Vec::with_capacity(10_000);
for _ in 0..10_000 {
entities.push(
world
.spawn((
(
A::<1>(Mat4::from_scale(Vec3::ONE)),
B::<1>(Mat4::from_scale(Vec3::ONE)),
C::<1>(Mat4::from_scale(Vec3::ONE)),
D::<1>(Mat4::from_scale(Vec3::ONE)),
E::<1>(Mat4::from_scale(Vec3::ONE)),
A::<2>(Mat4::from_scale(Vec3::ONE)),
B::<2>(Mat4::from_scale(Vec3::ONE)),
C::<2>(Mat4::from_scale(Vec3::ONE)),
D::<2>(Mat4::from_scale(Vec3::ONE)),
E::<2>(Mat4::from_scale(Vec3::ONE)),
),
(
A::<3>(Mat4::from_scale(Vec3::ONE)),
B::<3>(Mat4::from_scale(Vec3::ONE)),
C::<3>(Mat4::from_scale(Vec3::ONE)),
D::<3>(Mat4::from_scale(Vec3::ONE)),
E::<3>(Mat4::from_scale(Vec3::ONE)),
A::<4>(Mat4::from_scale(Vec3::ONE)),
B::<4>(Mat4::from_scale(Vec3::ONE)),
C::<4>(Mat4::from_scale(Vec3::ONE)),
D::<4>(Mat4::from_scale(Vec3::ONE)),
E::<4>(Mat4::from_scale(Vec3::ONE)),
),
(
A::<5>(Mat4::from_scale(Vec3::ONE)),
B::<5>(Mat4::from_scale(Vec3::ONE)),
C::<5>(Mat4::from_scale(Vec3::ONE)),
D::<5>(Mat4::from_scale(Vec3::ONE)),
E::<5>(Mat4::from_scale(Vec3::ONE)),
A::<6>(Mat4::from_scale(Vec3::ONE)),
B::<6>(Mat4::from_scale(Vec3::ONE)),
C::<6>(Mat4::from_scale(Vec3::ONE)),
D::<6>(Mat4::from_scale(Vec3::ONE)),
E::<6>(Mat4::from_scale(Vec3::ONE)),
),
(
A::<7>(Mat4::from_scale(Vec3::ONE)),
B::<7>(Mat4::from_scale(Vec3::ONE)),
C::<7>(Mat4::from_scale(Vec3::ONE)),
D::<7>(Mat4::from_scale(Vec3::ONE)),
E::<7>(Mat4::from_scale(Vec3::ONE)),
Z::<1>,
Z::<2>,
Z::<3>,
Z::<4>,
Z::<5>,
Z::<6>,
Z::<7>,
),
))
.id(),
);
}
Self(world, entities)
}
pub fn run(&mut self) {
for entity in &self.1 {
self.0.entity_mut(*entity).insert((
F::<1>(Mat4::from_scale(Vec3::ONE)),
F::<2>(Mat4::from_scale(Vec3::ONE)),
F::<3>(Mat4::from_scale(Vec3::ONE)),
F::<4>(Mat4::from_scale(Vec3::ONE)),
F::<5>(Mat4::from_scale(Vec3::ONE)),
F::<6>(Mat4::from_scale(Vec3::ONE)),
F::<7>(Mat4::from_scale(Vec3::ONE)),
));
}
for entity in &self.1 {
self.0
.entity_mut(*entity)
.remove::<(F<1>, F<2>, F<3>, F<4>, F<5>, F<6>, F<7>)>();
self.0
.entity_mut(*entity)
.remove::<(Z<1>, Z<2>, Z<3>, Z<4>, Z<5>, Z<6>, Z<7>)>();
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/components/archetype_updates.rs | benches/benches/bevy_ecs/components/archetype_updates.rs | use bevy_ecs::{
component::Component,
prelude::EntityWorldMut,
schedule::{ExecutorKind, Schedule},
world::World,
};
use criterion::{BenchmarkId, Criterion};
#[derive(Component)]
struct A<const N: u16>(f32);
fn setup(system_count: usize) -> (World, Schedule) {
let mut world = World::new();
fn empty() {}
let mut schedule = Schedule::default();
schedule.set_executor_kind(ExecutorKind::SingleThreaded);
for _ in 0..system_count {
schedule.add_systems(empty);
}
schedule.run(&mut world);
(world, schedule)
}
fn insert_if_bit_enabled<const B: u16>(entity: &mut EntityWorldMut, i: u16) {
if i & (1 << B) != 0 {
entity.insert(A::<B>(1.0));
}
}
/// create `count` entities with distinct archetypes
fn add_archetypes(world: &mut World, count: u16) {
for i in 0..count {
let mut e = world.spawn_empty();
insert_if_bit_enabled::<0>(&mut e, i);
insert_if_bit_enabled::<1>(&mut e, i);
insert_if_bit_enabled::<2>(&mut e, i);
insert_if_bit_enabled::<3>(&mut e, i);
insert_if_bit_enabled::<4>(&mut e, i);
insert_if_bit_enabled::<5>(&mut e, i);
insert_if_bit_enabled::<6>(&mut e, i);
insert_if_bit_enabled::<7>(&mut e, i);
insert_if_bit_enabled::<8>(&mut e, i);
insert_if_bit_enabled::<9>(&mut e, i);
insert_if_bit_enabled::<10>(&mut e, i);
insert_if_bit_enabled::<11>(&mut e, i);
insert_if_bit_enabled::<12>(&mut e, i);
insert_if_bit_enabled::<13>(&mut e, i);
insert_if_bit_enabled::<14>(&mut e, i);
insert_if_bit_enabled::<15>(&mut e, i);
}
}
pub fn no_archetypes(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("no_archetypes");
for system_count in [0, 10, 100] {
let (mut world, mut schedule) = setup(system_count);
group.bench_with_input(
BenchmarkId::new("system_count", system_count),
&system_count,
|bencher, &_system_count| {
bencher.iter(|| {
schedule.run(&mut world);
});
},
);
}
}
pub fn added_archetypes(criterion: &mut Criterion) {
const SYSTEM_COUNT: usize = 100;
let mut group = criterion.benchmark_group("added_archetypes");
for archetype_count in [100, 1_000, 10_000] {
group.bench_with_input(
BenchmarkId::new("archetype_count", archetype_count),
&archetype_count,
|bencher, &archetype_count| {
bencher.iter_batched(
|| {
let (mut world, schedule) = setup(SYSTEM_COUNT);
add_archetypes(&mut world, archetype_count);
(world, schedule)
},
|(mut world, mut schedule)| {
schedule.run(&mut world);
},
criterion::BatchSize::LargeInput,
);
},
);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/components/add_remove_sparse_set.rs | benches/benches/bevy_ecs/components/add_remove_sparse_set.rs | use bevy_ecs::prelude::*;
#[derive(Component)]
struct A(f32);
#[derive(Component)]
#[component(storage = "SparseSet")]
struct B(f32);
pub struct Benchmark(World, Vec<Entity>);
impl Benchmark {
pub fn new() -> Self {
let mut world = World::default();
let mut entities = Vec::with_capacity(10_000);
for _ in 0..10_000 {
entities.push(world.spawn(A(0.0)).id());
}
Self(world, entities)
}
pub fn run(&mut self) {
for entity in &self.1 {
self.0.entity_mut(*entity).insert(B(0.0));
}
for entity in &self.1 {
self.0.entity_mut(*entity).remove::<B>();
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/components/add_remove.rs | benches/benches/bevy_ecs/components/add_remove.rs | use bevy_ecs::prelude::*;
#[derive(Component, Clone)]
struct A(f32);
#[derive(Component)]
struct B(f32);
pub struct Benchmark(World, Vec<Entity>);
impl Benchmark {
pub fn new() -> Self {
let mut world = World::default();
let entities = world
.spawn_batch(core::iter::repeat_n(A(0.), 10_000))
.collect();
Self(world, entities)
}
pub fn run(&mut self) {
for entity in &self.1 {
self.0.entity_mut(*entity).insert(B(0.));
}
for entity in &self.1 {
self.0.entity_mut(*entity).remove::<B>();
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/components/insert_simple_unbatched.rs | benches/benches/bevy_ecs/components/insert_simple_unbatched.rs | use bevy_ecs::prelude::*;
use glam::*;
#[derive(Component, Copy, Clone)]
struct Transform(Mat4);
#[derive(Component, Copy, Clone)]
struct Position(Vec3);
#[derive(Component, Copy, Clone)]
struct Rotation(Vec3);
#[derive(Component, Copy, Clone)]
struct Velocity(Vec3);
pub struct Benchmark;
impl Benchmark {
pub fn new() -> Self {
Self
}
pub fn run(&mut self) {
let mut world = World::new();
for _ in 0..10_000 {
world.spawn((
Transform(Mat4::from_scale(Vec3::ONE)),
Position(Vec3::X),
Rotation(Vec3::X),
Velocity(Vec3::X),
));
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/components/add_remove_table.rs | benches/benches/bevy_ecs/components/add_remove_table.rs | use bevy_ecs::prelude::*;
#[derive(Component)]
struct A(f32);
#[derive(Component)]
struct B(f32);
pub struct Benchmark(World, Vec<Entity>);
impl Benchmark {
pub fn new() -> Self {
let mut world = World::default();
let mut entities = Vec::with_capacity(10_000);
for _ in 0..10_000 {
entities.push(world.spawn(A(0.0)).id());
}
Self(world, entities)
}
pub fn run(&mut self) {
for entity in &self.1 {
self.0.entity_mut(*entity).insert(B(0.0));
}
for entity in &self.1 {
self.0.entity_mut(*entity).remove::<B>();
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/components/mod.rs | benches/benches/bevy_ecs/components/mod.rs | mod add_remove;
mod add_remove_big_sparse_set;
mod add_remove_big_table;
mod add_remove_sparse_set;
mod add_remove_table;
mod add_remove_very_big_table;
mod archetype_updates;
mod insert_simple;
mod insert_simple_unbatched;
use archetype_updates::*;
use criterion::{criterion_group, Criterion};
criterion_group!(
benches,
add_remove,
add_remove_big,
add_remove_very_big,
insert_simple,
no_archetypes,
added_archetypes,
);
fn add_remove(c: &mut Criterion) {
let mut group = c.benchmark_group("add_remove");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
group.bench_function("table", |b| {
let mut bench = add_remove_table::Benchmark::new();
b.iter(move || bench.run());
});
group.bench_function("sparse_set", |b| {
let mut bench = add_remove_sparse_set::Benchmark::new();
b.iter(move || bench.run());
});
group.finish();
}
fn add_remove_big(c: &mut Criterion) {
let mut group = c.benchmark_group("add_remove_big");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
group.bench_function("table", |b| {
let mut bench = add_remove_big_table::Benchmark::new();
b.iter(move || bench.run());
});
group.bench_function("sparse_set", |b| {
let mut bench = add_remove_big_sparse_set::Benchmark::new();
b.iter(move || bench.run());
});
group.finish();
}
fn add_remove_very_big(c: &mut Criterion) {
let mut group = c.benchmark_group("add_remove_very_big");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
group.bench_function("table", |b| {
let mut bench = add_remove_very_big_table::Benchmark::new();
b.iter(move || bench.run());
});
group.finish();
}
fn insert_simple(c: &mut Criterion) {
let mut group = c.benchmark_group("insert_simple");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
group.bench_function("base", |b| {
let mut bench = insert_simple::Benchmark::new();
b.iter(move || bench.run());
});
group.bench_function("unbatched", |b| {
let mut bench = insert_simple_unbatched::Benchmark::new();
b.iter(move || bench.run());
});
group.finish();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/components/insert_simple.rs | benches/benches/bevy_ecs/components/insert_simple.rs | use bevy_ecs::prelude::*;
use glam::*;
#[derive(Component, Copy, Clone)]
struct Transform(Mat4);
#[derive(Component, Copy, Clone)]
struct Position(Vec3);
#[derive(Component, Copy, Clone)]
struct Rotation(Vec3);
#[derive(Component, Copy, Clone)]
struct Velocity(Vec3);
pub struct Benchmark;
impl Benchmark {
pub fn new() -> Self {
Self
}
pub fn run(&mut self) {
let mut world = World::new();
world.spawn_batch((0..10_000).map(|_| {
(
Transform(Mat4::from_scale(Vec3::ONE)),
Position(Vec3::X),
Rotation(Vec3::X),
Velocity(Vec3::X),
)
}));
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/components/add_remove_big_table.rs | benches/benches/bevy_ecs/components/add_remove_big_table.rs | use bevy_ecs::prelude::*;
use glam::*;
#[derive(Component, Copy, Clone)]
struct A(Mat4);
#[derive(Component, Copy, Clone)]
struct B(Mat4);
#[derive(Component, Copy, Clone)]
struct C(Mat4);
#[derive(Component, Copy, Clone)]
struct D(Mat4);
#[derive(Component, Copy, Clone)]
struct E(Mat4);
#[derive(Component, Copy, Clone)]
struct F(Mat4);
pub struct Benchmark(World, Vec<Entity>);
impl Benchmark {
pub fn new() -> Self {
let mut world = World::default();
let mut entities = Vec::with_capacity(10_000);
for _ in 0..10_000 {
entities.push(
world
.spawn((
A(Mat4::from_scale(Vec3::ONE)),
B(Mat4::from_scale(Vec3::ONE)),
C(Mat4::from_scale(Vec3::ONE)),
D(Mat4::from_scale(Vec3::ONE)),
E(Mat4::from_scale(Vec3::ONE)),
))
.id(),
);
}
Self(world, entities)
}
pub fn run(&mut self) {
for entity in &self.1 {
self.0
.entity_mut(*entity)
.insert(F(Mat4::from_scale(Vec3::ONE)));
}
for entity in &self.1 {
self.0.entity_mut(*entity).remove::<F>();
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/components/add_remove_big_sparse_set.rs | benches/benches/bevy_ecs/components/add_remove_big_sparse_set.rs | use bevy_ecs::prelude::*;
use glam::*;
#[derive(Component, Copy, Clone)]
struct A(Mat4);
#[derive(Component, Copy, Clone)]
struct B(Mat4);
#[derive(Component, Copy, Clone)]
struct C(Mat4);
#[derive(Component, Copy, Clone)]
struct D(Mat4);
#[derive(Component, Copy, Clone)]
struct E(Mat4);
#[derive(Component, Copy, Clone)]
#[component(storage = "SparseSet")]
struct F(Mat4);
pub struct Benchmark(World, Vec<Entity>);
impl Benchmark {
pub fn new() -> Self {
let mut world = World::default();
let mut entities = Vec::with_capacity(10_000);
for _ in 0..10_000 {
entities.push(
world
.spawn((
A(Mat4::from_scale(Vec3::ONE)),
B(Mat4::from_scale(Vec3::ONE)),
C(Mat4::from_scale(Vec3::ONE)),
D(Mat4::from_scale(Vec3::ONE)),
E(Mat4::from_scale(Vec3::ONE)),
))
.id(),
);
}
Self(world, entities)
}
pub fn run(&mut self) {
for entity in &self.1 {
self.0
.entity_mut(*entity)
.insert(F(Mat4::from_scale(Vec3::ONE)));
}
for entity in &self.1 {
self.0.entity_mut(*entity).remove::<F>();
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/world/spawn.rs | benches/benches/bevy_ecs/world/spawn.rs | use bevy_ecs::prelude::*;
use criterion::Criterion;
use glam::*;
#[derive(Component)]
struct A(Mat4);
#[derive(Component)]
struct B(Vec4);
pub fn world_spawn(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("spawn_world");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
for entity_count in [1, 100, 10_000] {
group.bench_function(format!("{entity_count}_entities"), |bencher| {
let mut world = World::default();
bencher.iter(|| {
for _ in 0..entity_count {
world.spawn((A(Mat4::default()), B(Vec4::default())));
}
});
});
}
group.finish();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/world/world_get.rs | benches/benches/bevy_ecs/world/world_get.rs | use benches::bench;
use core::hint::black_box;
use bevy_ecs::{
bundle::{Bundle, NoBundleEffect},
component::Component,
entity::Entity,
system::{Query, SystemState},
world::{EntityMut, World},
};
use criterion::Criterion;
use rand::{prelude::SliceRandom, SeedableRng};
use rand_chacha::ChaCha8Rng;
use seq_macro::seq;
#[derive(Component, Default)]
#[component(storage = "Table")]
struct Table(f32);
#[derive(Component, Default)]
#[component(storage = "SparseSet")]
struct Sparse(f32);
#[derive(Component, Default)]
#[component(storage = "Table")]
struct WideTable<const X: usize>(f32);
#[derive(Component, Default)]
#[component(storage = "SparseSet")]
struct WideSparse<const X: usize>(f32);
const RANGE: core::ops::Range<u32> = 5..6;
fn deterministic_rand() -> ChaCha8Rng {
ChaCha8Rng::seed_from_u64(42)
}
fn setup<T: Component + Default>(entity_count: u32) -> (World, Vec<Entity>) {
let mut world = World::default();
let entities: Vec<Entity> = world
.spawn_batch((0..entity_count).map(|_| T::default()))
.collect();
black_box((world, entities))
}
fn setup_wide<T: Bundle<Effect: NoBundleEffect> + Default>(
entity_count: u32,
) -> (World, Vec<Entity>) {
let mut world = World::default();
let entities: Vec<Entity> = world
.spawn_batch((0..entity_count).map(|_| T::default()))
.collect();
black_box((world, entities))
}
pub fn world_entity(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("world_entity");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
for entity_count in RANGE.map(|i| i * 10_000) {
group.bench_function(format!("{entity_count}_entities"), |bencher| {
let (world, entities) = setup::<Table>(entity_count);
bencher.iter(|| {
for entity in &entities {
black_box(world.entity(*entity));
}
});
});
}
group.finish();
}
pub fn world_get(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("world_get");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
for entity_count in RANGE.map(|i| i * 10_000) {
group.bench_function(format!("{entity_count}_entities_table"), |bencher| {
let (world, entities) = setup::<Table>(entity_count);
bencher.iter(|| {
for entity in &entities {
assert!(world.get::<Table>(*entity).is_some());
}
});
});
group.bench_function(format!("{entity_count}_entities_sparse"), |bencher| {
let (world, entities) = setup::<Sparse>(entity_count);
bencher.iter(|| {
for entity in &entities {
assert!(world.get::<Sparse>(*entity).is_some());
}
});
});
}
group.finish();
}
pub fn world_query_get(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("world_query_get");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
for entity_count in RANGE.map(|i| i * 10_000) {
group.bench_function(format!("{entity_count}_entities_table"), |bencher| {
let (mut world, entities) = setup::<Table>(entity_count);
let mut query = world.query::<&Table>();
bencher.iter(|| {
for entity in &entities {
assert!(query.get(&world, *entity).is_ok());
}
});
});
group.bench_function(format!("{entity_count}_entities_table_wide"), |bencher| {
let (mut world, entities) = setup_wide::<(
WideTable<0>,
WideTable<1>,
WideTable<2>,
WideTable<3>,
WideTable<4>,
WideTable<5>,
)>(entity_count);
let mut query = world.query::<(
&WideTable<0>,
&WideTable<1>,
&WideTable<2>,
&WideTable<3>,
&WideTable<4>,
&WideTable<5>,
)>();
bencher.iter(|| {
for entity in &entities {
assert!(query.get(&world, *entity).is_ok());
}
});
});
group.bench_function(format!("{entity_count}_entities_sparse"), |bencher| {
let (mut world, entities) = setup::<Sparse>(entity_count);
let mut query = world.query::<&Sparse>();
bencher.iter(|| {
for entity in &entities {
assert!(query.get(&world, *entity).is_ok());
}
});
});
group.bench_function(format!("{entity_count}_entities_sparse_wide"), |bencher| {
let (mut world, entities) = setup_wide::<(
WideSparse<0>,
WideSparse<1>,
WideSparse<2>,
WideSparse<3>,
WideSparse<4>,
WideSparse<5>,
)>(entity_count);
let mut query = world.query::<(
&WideSparse<0>,
&WideSparse<1>,
&WideSparse<2>,
&WideSparse<3>,
&WideSparse<4>,
&WideSparse<5>,
)>();
bencher.iter(|| {
for entity in &entities {
assert!(query.get(&world, *entity).is_ok());
}
});
});
}
group.finish();
}
pub fn world_query_iter(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("world_query_iter");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
for entity_count in RANGE.map(|i| i * 10_000) {
group.bench_function(format!("{entity_count}_entities_table"), |bencher| {
let (mut world, _) = setup::<Table>(entity_count);
let mut query = world.query::<&Table>();
bencher.iter(|| {
let mut count = 0;
for comp in query.iter(&world) {
black_box(comp);
count += 1;
black_box(count);
}
assert_eq!(black_box(count), entity_count);
});
});
group.bench_function(format!("{entity_count}_entities_sparse"), |bencher| {
let (mut world, _) = setup::<Sparse>(entity_count);
let mut query = world.query::<&Sparse>();
bencher.iter(|| {
let mut count = 0;
for comp in query.iter(&world) {
black_box(comp);
count += 1;
black_box(count);
}
assert_eq!(black_box(count), entity_count);
});
});
}
group.finish();
}
pub fn world_query_for_each(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("world_query_for_each");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
for entity_count in RANGE.map(|i| i * 10_000) {
group.bench_function(format!("{entity_count}_entities_table"), |bencher| {
let (mut world, _) = setup::<Table>(entity_count);
let mut query = world.query::<&Table>();
bencher.iter(|| {
let mut count = 0;
query.iter(&world).for_each(|comp| {
black_box(comp);
count += 1;
black_box(count);
});
assert_eq!(black_box(count), entity_count);
});
});
group.bench_function(format!("{entity_count}_entities_sparse"), |bencher| {
let (mut world, _) = setup::<Sparse>(entity_count);
let mut query = world.query::<&Sparse>();
bencher.iter(|| {
let mut count = 0;
query.iter(&world).for_each(|comp| {
black_box(comp);
count += 1;
black_box(count);
});
assert_eq!(black_box(count), entity_count);
});
});
}
group.finish();
}
pub fn query_get(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("query_get");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
for entity_count in RANGE.map(|i| i * 10_000) {
group.bench_function(format!("{entity_count}_entities_table"), |bencher| {
let mut world = World::default();
let mut entities: Vec<_> = world
.spawn_batch((0..entity_count).map(|_| Table::default()))
.collect();
entities.shuffle(&mut deterministic_rand());
let mut query = SystemState::<Query<&Table>>::new(&mut world);
let query = query.get(&world);
bencher.iter(|| {
let mut count = 0;
for comp in entities.iter().flat_map(|&e| query.get(e)) {
black_box(comp);
count += 1;
black_box(count);
}
assert_eq!(black_box(count), entity_count);
});
});
group.bench_function(format!("{entity_count}_entities_sparse"), |bencher| {
let mut world = World::default();
let mut entities: Vec<_> = world
.spawn_batch((0..entity_count).map(|_| Sparse::default()))
.collect();
entities.shuffle(&mut deterministic_rand());
let mut query = SystemState::<Query<&Sparse>>::new(&mut world);
let query = query.get(&world);
bencher.iter(|| {
let mut count = 0;
for comp in entities.iter().flat_map(|&e| query.get(e)) {
black_box(comp);
count += 1;
black_box(count);
}
assert_eq!(black_box(count), entity_count);
});
});
}
group.finish();
}
pub fn query_get_many<const N: usize>(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group(format!("query_get_many_{N}"));
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(2 * N as u64));
for entity_count in RANGE.map(|i| i * 10_000) {
group.bench_function(format!("{entity_count}_calls_table"), |bencher| {
let mut world = World::default();
let mut entity_groups: Vec<_> = (0..entity_count)
.map(|_| [(); N].map(|_| world.spawn(Table::default()).id()))
.collect();
entity_groups.shuffle(&mut deterministic_rand());
let mut query = SystemState::<Query<&Table>>::new(&mut world);
let query = query.get(&world);
bencher.iter(|| {
let mut count = 0;
for comp in entity_groups
.iter()
.filter_map(|&ids| query.get_many(ids).ok())
{
black_box(comp);
count += 1;
black_box(count);
}
assert_eq!(black_box(count), entity_count);
});
});
group.bench_function(format!("{entity_count}_calls_sparse"), |bencher| {
let mut world = World::default();
let mut entity_groups: Vec<_> = (0..entity_count)
.map(|_| [(); N].map(|_| world.spawn(Sparse::default()).id()))
.collect();
entity_groups.shuffle(&mut deterministic_rand());
let mut query = SystemState::<Query<&Sparse>>::new(&mut world);
let query = query.get(&world);
bencher.iter(|| {
let mut count = 0;
for comp in entity_groups
.iter()
.filter_map(|&ids| query.get_many(ids).ok())
{
black_box(comp);
count += 1;
black_box(count);
}
assert_eq!(black_box(count), entity_count);
});
});
}
}
macro_rules! query_get_components_mut {
($function_name:ident, $val:literal) => {
pub fn $function_name(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group(bench!("world_query_get_components_mut"));
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
for entity_count in RANGE.map(|i| i * 10_000) {
seq!(N in 0..$val {
let (mut world, entities) = setup_wide::<(
#(WideTable<N>,)*
)>(entity_count);
});
let mut query = world.query::<EntityMut>();
group.bench_function(format!("{}_components_{entity_count}_entities", $val), |bencher| {
bencher.iter(|| {
for entity in &entities {
seq!(N in 0..$val {
assert!(query
.get_mut(&mut world, *entity)
.unwrap()
.get_components_mut::<(
#(&mut WideTable<N>,)*
)>()
.is_ok());
});
}
});
});
group.bench_function(
format!("unchecked_{}_components_{entity_count}_entities", $val),
|bencher| {
bencher.iter(|| {
for entity in &entities {
// SAFETY: no duplicate components are listed
unsafe {
seq!(N in 0..$val {
assert!(query
.get_mut(&mut world, *entity)
.unwrap()
.get_components_mut_unchecked::<(
#(&mut WideTable<N>,)*
)>()
.is_ok());
});
}
}
});
},
);
}
group.finish();
}
};
}
query_get_components_mut!(query_get_components_mut_2, 2);
query_get_components_mut!(query_get_components_mut_5, 5);
query_get_components_mut!(query_get_components_mut_10, 10);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/world/despawn_recursive.rs | benches/benches/bevy_ecs/world/despawn_recursive.rs | use bevy_ecs::prelude::*;
use criterion::{BatchSize, Criterion};
use glam::*;
#[derive(Component)]
struct A(Mat4);
#[derive(Component)]
struct B(Vec4);
pub fn world_despawn_recursive(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("despawn_world_recursive");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
for entity_count in [1, 100, 10_000] {
group.bench_function(format!("{entity_count}_entities"), |bencher| {
bencher.iter_batched_ref(
|| {
let mut world = World::default();
let parent_ents = (0..entity_count)
.map(|_| {
world
.spawn((A(Mat4::default()), B(Vec4::default())))
.with_children(|parent| {
parent.spawn((A(Mat4::default()), B(Vec4::default())));
})
.id()
})
.collect::<Vec<_>>();
(world, parent_ents)
},
|(world, parent_ents)| {
parent_ents.iter().for_each(|e| {
world.despawn(*e);
});
},
BatchSize::SmallInput,
);
});
}
group.finish();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/world/commands.rs | benches/benches/bevy_ecs/world/commands.rs | use core::hint::black_box;
use bevy_ecs::{
component::Component,
system::{Command, Commands},
world::{CommandQueue, World},
};
use criterion::Criterion;
#[derive(Component)]
struct A;
#[derive(Component)]
struct B;
#[derive(Component)]
struct C;
pub fn empty_commands(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("empty_commands");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
group.bench_function("0_entities", |bencher| {
let mut world = World::default();
let mut command_queue = CommandQueue::default();
bencher.iter(|| {
command_queue.apply(&mut world);
});
});
group.finish();
}
pub fn spawn_commands(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("spawn_commands");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
for entity_count in [100, 1_000, 10_000] {
group.bench_function(format!("{entity_count}_entities"), |bencher| {
let mut world = World::default();
let mut command_queue = CommandQueue::default();
bencher.iter(|| {
let mut commands = Commands::new(&mut command_queue, &world);
for i in 0..entity_count {
let mut entity = commands.spawn_empty();
entity
.insert_if(A, || black_box(i % 2 == 0))
.insert_if(B, || black_box(i % 3 == 0))
.insert_if(C, || black_box(i % 4 == 0));
if black_box(i % 5 == 0) {
entity.despawn();
}
}
command_queue.apply(&mut world);
});
});
}
group.finish();
}
pub fn nonempty_spawn_commands(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("nonempty_spawn_commands");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
for entity_count in [100, 1_000, 10_000] {
group.bench_function(format!("{entity_count}_entities"), |bencher| {
let mut world = World::default();
let mut command_queue = CommandQueue::default();
bencher.iter(|| {
let mut commands = Commands::new(&mut command_queue, &world);
for i in 0..entity_count {
if black_box(i % 2 == 0) {
commands.spawn(A);
}
}
command_queue.apply(&mut world);
});
});
}
group.finish();
}
#[derive(Default, Component)]
struct Matrix([[f32; 4]; 4]);
#[derive(Default, Component)]
struct Vec3([f32; 3]);
pub fn insert_commands(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("insert_commands");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
let entity_count = 10_000;
group.bench_function("insert", |bencher| {
let mut world = World::default();
let mut command_queue = CommandQueue::default();
let mut entities = Vec::new();
for _ in 0..entity_count {
entities.push(world.spawn_empty().id());
}
bencher.iter(|| {
let mut commands = Commands::new(&mut command_queue, &world);
for entity in &entities {
commands
.entity(*entity)
.insert((Matrix::default(), Vec3::default()));
}
command_queue.apply(&mut world);
});
});
group.bench_function("insert_batch", |bencher| {
let mut world = World::default();
let mut command_queue = CommandQueue::default();
let mut entities = Vec::new();
for _ in 0..entity_count {
entities.push(world.spawn_empty().id());
}
bencher.iter(|| {
let mut commands = Commands::new(&mut command_queue, &world);
let mut values = Vec::with_capacity(entity_count);
for entity in &entities {
values.push((*entity, (Matrix::default(), Vec3::default())));
}
commands.insert_batch(values);
command_queue.apply(&mut world);
});
});
group.finish();
}
struct FakeCommandA;
struct FakeCommandB(u64);
impl Command for FakeCommandA {
fn apply(self, world: &mut World) {
black_box(self);
black_box(world);
}
}
impl Command for FakeCommandB {
fn apply(self, world: &mut World) {
black_box(self);
black_box(world);
}
}
pub fn fake_commands(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("fake_commands");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
for command_count in [100, 1_000, 10_000] {
group.bench_function(format!("{command_count}_commands"), |bencher| {
let mut world = World::default();
let mut command_queue = CommandQueue::default();
bencher.iter(|| {
let mut commands = Commands::new(&mut command_queue, &world);
for i in 0..command_count {
if black_box(i % 2 == 0) {
commands.queue(FakeCommandA);
} else {
commands.queue(FakeCommandB(0));
}
}
command_queue.apply(&mut world);
});
});
}
group.finish();
}
#[derive(Default)]
struct SizedCommand<T: Default + Send + Sync + 'static>(T);
impl<T: Default + Send + Sync + 'static> Command for SizedCommand<T> {
fn apply(self, world: &mut World) {
black_box(self);
black_box(world);
}
}
struct LargeStruct([u64; 64]);
impl Default for LargeStruct {
fn default() -> Self {
Self([0; 64])
}
}
pub fn sized_commands_impl<T: Default + Command>(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group(format!("sized_commands_{}_bytes", size_of::<T>()));
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
for command_count in [100, 1_000, 10_000] {
group.bench_function(format!("{command_count}_commands"), |bencher| {
let mut world = World::default();
let mut command_queue = CommandQueue::default();
bencher.iter(|| {
let mut commands = Commands::new(&mut command_queue, &world);
for _ in 0..command_count {
commands.queue(T::default());
}
command_queue.apply(&mut world);
});
});
}
group.finish();
}
pub fn zero_sized_commands(criterion: &mut Criterion) {
sized_commands_impl::<SizedCommand<()>>(criterion);
}
pub fn medium_sized_commands(criterion: &mut Criterion) {
sized_commands_impl::<SizedCommand<(u32, u32, u32)>>(criterion);
}
pub fn large_sized_commands(criterion: &mut Criterion) {
sized_commands_impl::<SizedCommand<LargeStruct>>(criterion);
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/world/mod.rs | benches/benches/bevy_ecs/world/mod.rs | mod commands;
mod despawn;
mod despawn_recursive;
mod entity_hash;
mod spawn;
mod world_get;
use commands::*;
use criterion::criterion_group;
use despawn::*;
use despawn_recursive::*;
use entity_hash::*;
use spawn::*;
use world_get::*;
criterion_group!(
benches,
empty_commands,
spawn_commands,
nonempty_spawn_commands,
insert_commands,
fake_commands,
zero_sized_commands,
medium_sized_commands,
large_sized_commands,
world_entity,
world_get,
world_query_get,
world_query_iter,
world_query_for_each,
world_spawn,
world_despawn,
world_despawn_recursive,
query_get,
query_get_many::<2>,
query_get_many::<5>,
query_get_many::<10>,
query_get_components_mut_2,
query_get_components_mut_5,
query_get_components_mut_10,
entity_set_build_and_lookup,
);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/world/despawn.rs | benches/benches/bevy_ecs/world/despawn.rs | use bevy_ecs::prelude::*;
use criterion::{BatchSize, Criterion};
use glam::*;
#[derive(Component)]
struct A(Mat4);
#[derive(Component)]
struct B(Vec4);
pub fn world_despawn(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("despawn_world");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
for entity_count in [1, 100, 10_000] {
group.bench_function(format!("{entity_count}_entities"), |bencher| {
bencher.iter_batched_ref(
|| {
let mut world = World::default();
let entities: Vec<Entity> = world
.spawn_batch(
(0..entity_count).map(|_| (A(Mat4::default()), B(Vec4::default()))),
)
.collect();
(world, entities)
},
|(world, entities)| {
entities.iter().for_each(|e| {
world.despawn(*e);
});
},
BatchSize::SmallInput,
);
});
}
group.finish();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/world/entity_hash.rs | benches/benches/bevy_ecs/world/entity_hash.rs | use bevy_ecs::entity::{Entity, EntityGeneration, EntityHashSet};
use criterion::{BenchmarkId, Criterion, Throughput};
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
const SIZES: [usize; 5] = [100, 316, 1000, 3162, 10000];
fn make_entity(rng: &mut impl Rng, size: usize) -> Entity {
// -log₂(1-x) gives an exponential distribution with median 1.0
// That lets us get values that are mostly small, but some are quite large
// * For ids, half are in [0, size), half are unboundedly larger.
// * For generations, half are in [1, 3), half are unboundedly larger.
let x: f64 = rng.random();
let id = -(1.0 - x).log2() * (size as f64);
let x: f64 = rng.random();
let generation = 1.0 + -(1.0 - x).log2() * 2.0;
// this is not reliable, but we're internal so a hack is ok
let id = id as u64 + 1;
let bits = ((generation as u64) << 32) | id;
let e = Entity::from_bits(bits);
assert_eq!(e.index_u32(), !(id as u32));
assert_eq!(
e.generation(),
EntityGeneration::FIRST.after_versions(generation as u32)
);
e
}
pub fn entity_set_build_and_lookup(c: &mut Criterion) {
let mut group = c.benchmark_group("entity_hash");
for size in SIZES {
// Get some random-but-consistent entities to use for all the benches below.
let mut rng = ChaCha8Rng::seed_from_u64(size as u64);
let entities =
Vec::from_iter(core::iter::repeat_with(|| make_entity(&mut rng, size)).take(size));
group.throughput(Throughput::Elements(size as u64));
group.bench_function(BenchmarkId::new("entity_set_build", size), |bencher| {
bencher.iter_with_large_drop(|| EntityHashSet::from_iter(entities.iter().copied()));
});
group.bench_function(BenchmarkId::new("entity_set_lookup_hit", size), |bencher| {
let set = EntityHashSet::from_iter(entities.iter().copied());
bencher.iter(|| entities.iter().copied().filter(|e| set.contains(e)).count());
});
group.bench_function(
BenchmarkId::new("entity_set_lookup_miss_id", size),
|bencher| {
let set = EntityHashSet::from_iter(entities.iter().copied());
bencher.iter(|| {
entities
.iter()
.copied()
.map(|e| Entity::from_bits(e.to_bits() + 1))
.filter(|e| set.contains(e))
.count()
});
},
);
group.bench_function(
BenchmarkId::new("entity_set_lookup_miss_gen", size),
|bencher| {
let set = EntityHashSet::from_iter(entities.iter().copied());
bencher.iter(|| {
entities
.iter()
.copied()
.map(|e| Entity::from_bits(e.to_bits() + (1 << 32)))
.filter(|e| set.contains(e))
.count()
});
},
);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/events/write.rs | benches/benches/bevy_ecs/events/write.rs | use bevy_ecs::prelude::*;
#[derive(Message)]
struct BenchEvent<const SIZE: usize>([u8; SIZE]);
impl<const SIZE: usize> Default for BenchEvent<SIZE> {
fn default() -> Self {
BenchEvent([0; SIZE])
}
}
pub struct Benchmark<const SIZE: usize> {
events: Messages<BenchEvent<SIZE>>,
count: usize,
}
impl<const SIZE: usize> Benchmark<SIZE> {
pub fn new(count: usize) -> Self {
let mut events = Messages::default();
// Force both internal buffers to be allocated.
for _ in 0..2 {
for _ in 0..count {
events.write(BenchEvent([0u8; SIZE]));
}
events.update();
}
Self { events, count }
}
pub fn run(&mut self) {
for _ in 0..self.count {
self.events
.write(core::hint::black_box(BenchEvent([0u8; SIZE])));
}
self.events.update();
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/events/mod.rs | benches/benches/bevy_ecs/events/mod.rs | mod iter;
mod write;
use criterion::{criterion_group, Criterion};
criterion_group!(benches, send, iter);
fn send(c: &mut Criterion) {
let mut group = c.benchmark_group("events_send");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
for count in [100, 1_000, 10_000] {
group.bench_function(format!("size_4_events_{count}"), |b| {
let mut bench = write::Benchmark::<4>::new(count);
b.iter(move || bench.run());
});
}
for count in [100, 1_000, 10_000] {
group.bench_function(format!("size_16_events_{count}"), |b| {
let mut bench = write::Benchmark::<16>::new(count);
b.iter(move || bench.run());
});
}
for count in [100, 1_000, 10_000] {
group.bench_function(format!("size_512_events_{count}"), |b| {
let mut bench = write::Benchmark::<512>::new(count);
b.iter(move || bench.run());
});
}
group.finish();
}
fn iter(c: &mut Criterion) {
let mut group = c.benchmark_group("events_iter");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(4));
for count in [100, 1_000, 10_000] {
group.bench_function(format!("size_4_events_{count}"), |b| {
let mut bench = iter::Benchmark::<4>::new(count);
b.iter(move || bench.run());
});
}
for count in [100, 1_000, 10_000] {
group.bench_function(format!("size_16_events_{count}"), |b| {
let mut bench = iter::Benchmark::<4>::new(count);
b.iter(move || bench.run());
});
}
for count in [100, 1_000, 10_000] {
group.bench_function(format!("size_512_events_{count}"), |b| {
let mut bench = iter::Benchmark::<512>::new(count);
b.iter(move || bench.run());
});
}
group.finish();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/events/iter.rs | benches/benches/bevy_ecs/events/iter.rs | use bevy_ecs::prelude::*;
#[derive(Message)]
struct BenchEvent<const SIZE: usize>([u8; SIZE]);
pub struct Benchmark<const SIZE: usize>(Messages<BenchEvent<SIZE>>);
impl<const SIZE: usize> Benchmark<SIZE> {
pub fn new(count: usize) -> Self {
let mut events = Messages::default();
for _ in 0..count {
events.write(BenchEvent([0u8; SIZE]));
}
Self(events)
}
pub fn run(&mut self) {
let mut reader = self.0.get_cursor();
for evt in reader.read(&self.0) {
core::hint::black_box(evt);
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/param/combinator_system.rs | benches/benches/bevy_ecs/param/combinator_system.rs | use bevy_ecs::prelude::*;
use criterion::Criterion;
pub fn combinator_system(criterion: &mut Criterion) {
let mut world = World::new();
let mut group = criterion.benchmark_group("param/combinator_system");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(3));
let mut schedule = Schedule::default();
schedule.add_systems(
(|| {})
.pipe(|| {})
.pipe(|| {})
.pipe(|| {})
.pipe(|| {})
.pipe(|| {})
.pipe(|| {})
.pipe(|| {}),
);
// run once to initialize systems
schedule.run(&mut world);
group.bench_function("8_piped_systems", |bencher| {
bencher.iter(|| {
schedule.run(&mut world);
});
});
group.finish();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/param/param_set.rs | benches/benches/bevy_ecs/param/param_set.rs | use bevy_ecs::prelude::*;
use criterion::Criterion;
pub fn param_set(criterion: &mut Criterion) {
let mut world = World::new();
let mut group = criterion.benchmark_group("param/combinator_system");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(3));
#[derive(Resource)]
struct R;
world.insert_resource(R);
let mut schedule = Schedule::default();
schedule.add_systems(
|_: ParamSet<(
ResMut<R>,
ResMut<R>,
ResMut<R>,
ResMut<R>,
ResMut<R>,
ResMut<R>,
ResMut<R>,
ResMut<R>,
)>| {},
);
// run once to initialize systems
schedule.run(&mut world);
group.bench_function("8_variant_param_set_system", |bencher| {
bencher.iter(|| {
schedule.run(&mut world);
});
});
group.finish();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/param/mod.rs | benches/benches/bevy_ecs/param/mod.rs | mod combinator_system;
mod dyn_param;
mod param_set;
use combinator_system::*;
use criterion::criterion_group;
use dyn_param::*;
use param_set::*;
criterion_group!(benches, combinator_system, dyn_param, param_set);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_ecs/param/dyn_param.rs | benches/benches/bevy_ecs/param/dyn_param.rs | use bevy_ecs::{
prelude::*,
system::{DynParamBuilder, DynSystemParam, ParamBuilder},
};
use criterion::Criterion;
pub fn dyn_param(criterion: &mut Criterion) {
let mut world = World::new();
let mut group = criterion.benchmark_group("param/combinator_system");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(3));
#[derive(Resource)]
struct R;
world.insert_resource(R);
let mut schedule = Schedule::default();
let system = (
DynParamBuilder::new::<Res<R>>(ParamBuilder),
DynParamBuilder::new::<Res<R>>(ParamBuilder),
DynParamBuilder::new::<Res<R>>(ParamBuilder),
DynParamBuilder::new::<Res<R>>(ParamBuilder),
DynParamBuilder::new::<Res<R>>(ParamBuilder),
DynParamBuilder::new::<Res<R>>(ParamBuilder),
DynParamBuilder::new::<Res<R>>(ParamBuilder),
DynParamBuilder::new::<Res<R>>(ParamBuilder),
)
.build_state(&mut world)
.build_system(
|_: DynSystemParam,
_: DynSystemParam,
_: DynSystemParam,
_: DynSystemParam,
_: DynSystemParam,
_: DynSystemParam,
_: DynSystemParam,
_: DynSystemParam| {},
);
schedule.add_systems(system);
// run once to initialize systems
schedule.run(&mut world);
group.bench_function("8_dyn_params_system", |bencher| {
bencher.iter(|| {
schedule.run(&mut world);
});
});
group.finish();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_reflect/struct.rs | benches/benches/bevy_reflect/struct.rs | use core::{hint::black_box, time::Duration};
use benches::bench;
use bevy_reflect::{DynamicStruct, GetField, PartialReflect, Reflect, Struct};
use criterion::{
criterion_group, measurement::Measurement, AxisScale, BatchSize, BenchmarkGroup, BenchmarkId,
Criterion, PlotConfiguration, Throughput,
};
criterion_group!(
benches,
concrete_struct_apply,
concrete_struct_field,
concrete_struct_type_info,
concrete_struct_to_dynamic_struct,
dynamic_struct_to_dynamic_struct,
dynamic_struct_apply,
dynamic_struct_get_field,
dynamic_struct_insert,
);
const WARM_UP_TIME: Duration = Duration::from_millis(500);
const MEASUREMENT_TIME: Duration = Duration::from_secs(4);
const SIZES: [usize; 4] = [16, 32, 64, 128];
/// Creates a [`BenchmarkGroup`] with common configuration shared by all benchmarks within this
/// module.
fn create_group<'a, M: Measurement>(c: &'a mut Criterion<M>, name: &str) -> BenchmarkGroup<'a, M> {
let mut group = c.benchmark_group(name);
group
.warm_up_time(WARM_UP_TIME)
.measurement_time(MEASUREMENT_TIME)
// Make the plots logarithmic, matching `SIZES`' scale.
.plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic));
group
}
fn concrete_struct_field(criterion: &mut Criterion) {
let mut group = create_group(criterion, bench!("concrete_struct_field"));
let structs: [Box<dyn Struct>; 4] = [
Box::new(Struct16::default()),
Box::new(Struct32::default()),
Box::new(Struct64::default()),
Box::new(Struct128::default()),
];
for s in structs {
let field_count = s.field_len();
group.bench_with_input(
BenchmarkId::from_parameter(field_count),
&s,
|bencher, s| {
let field_names = (0..field_count)
.map(|i| format!("field_{i}"))
.collect::<Vec<_>>();
bencher.iter(|| {
for name in &field_names {
black_box(s.field(black_box(name)));
}
});
},
);
}
}
fn concrete_struct_apply(criterion: &mut Criterion) {
let mut group = create_group(criterion, bench!("concrete_struct_apply"));
// Use functions that produce trait objects of varying concrete types as the
// input to the benchmark.
let inputs: &[fn() -> (Box<dyn Struct>, Box<dyn PartialReflect>)] = &[
|| (Box::new(Struct16::default()), Box::new(Struct16::default())),
|| (Box::new(Struct32::default()), Box::new(Struct32::default())),
|| (Box::new(Struct64::default()), Box::new(Struct64::default())),
|| {
(
Box::new(Struct128::default()),
Box::new(Struct128::default()),
)
},
];
for input in inputs {
let field_count = input().0.field_len();
group.throughput(Throughput::Elements(field_count as u64));
group.bench_with_input(
BenchmarkId::new("apply_concrete", field_count),
input,
|bencher, input| {
bencher.iter_batched(
input,
|(mut obj, patch)| obj.apply(black_box(patch.as_ref())),
BatchSize::SmallInput,
);
},
);
}
for input in inputs {
let field_count = input().0.field_len();
group.throughput(Throughput::Elements(field_count as u64));
group.bench_with_input(
BenchmarkId::new("apply_dynamic", field_count),
input,
|bencher, input| {
bencher.iter_batched(
|| {
let (obj, _) = input();
let patch = obj.to_dynamic_struct();
(obj, patch)
},
|(mut obj, patch)| obj.apply(black_box(&patch)),
BatchSize::SmallInput,
);
},
);
}
}
fn concrete_struct_type_info(criterion: &mut Criterion) {
let mut group = create_group(criterion, bench!("concrete_struct_type_info"));
let structs: [(Box<dyn Struct>, Box<dyn Struct>); 5] = [
(
Box::new(Struct1::default()),
Box::new(GenericStruct1::<u32>::default()),
),
(
Box::new(Struct16::default()),
Box::new(GenericStruct16::<u32>::default()),
),
(
Box::new(Struct32::default()),
Box::new(GenericStruct32::<u32>::default()),
),
(
Box::new(Struct64::default()),
Box::new(GenericStruct64::<u32>::default()),
),
(
Box::new(Struct128::default()),
Box::new(GenericStruct128::<u32>::default()),
),
];
for (standard, generic) in structs {
let field_count = standard.field_len();
group.bench_with_input(
BenchmarkId::new("NonGeneric", field_count),
&standard,
|bencher, s| {
bencher.iter(|| s.get_represented_type_info());
},
);
group.bench_with_input(
BenchmarkId::new("Generic", field_count),
&generic,
|bencher, s| {
bencher.iter(|| s.get_represented_type_info());
},
);
}
}
fn concrete_struct_to_dynamic_struct(criterion: &mut Criterion) {
let mut group = create_group(criterion, bench!("concrete_struct_to_dynamic_struct"));
let structs: [(Box<dyn Struct>, Box<dyn Struct>); 5] = [
(
Box::new(Struct1::default()),
Box::new(GenericStruct1::<u32>::default()),
),
(
Box::new(Struct16::default()),
Box::new(GenericStruct16::<u32>::default()),
),
(
Box::new(Struct32::default()),
Box::new(GenericStruct32::<u32>::default()),
),
(
Box::new(Struct64::default()),
Box::new(GenericStruct64::<u32>::default()),
),
(
Box::new(Struct128::default()),
Box::new(GenericStruct128::<u32>::default()),
),
];
for (standard, generic) in structs {
let field_count = standard.field_len();
group.bench_with_input(
BenchmarkId::new("NonGeneric", field_count),
&standard,
|bencher, s| {
bencher.iter(|| s.to_dynamic_struct());
},
);
group.bench_with_input(
BenchmarkId::new("Generic", field_count),
&generic,
|bencher, s| {
bencher.iter(|| s.to_dynamic_struct());
},
);
}
}
fn dynamic_struct_to_dynamic_struct(criterion: &mut Criterion) {
let mut group = create_group(criterion, bench!("dynamic_struct_to_dynamic_struct"));
let structs: [Box<dyn Struct>; 5] = [
Box::new(Struct1::default().to_dynamic_struct()),
Box::new(Struct16::default().to_dynamic_struct()),
Box::new(Struct32::default().to_dynamic_struct()),
Box::new(Struct64::default().to_dynamic_struct()),
Box::new(Struct128::default().to_dynamic_struct()),
];
for s in structs {
let field_count = s.field_len();
group.bench_with_input(
BenchmarkId::from_parameter(field_count),
&s,
|bencher, s| {
bencher.iter(|| s.to_dynamic_struct());
},
);
}
}
fn dynamic_struct_apply(criterion: &mut Criterion) {
let mut group = create_group(criterion, bench!("dynamic_struct_apply"));
let patches: &[(fn() -> Box<dyn PartialReflect>, usize)] = &[
(|| Box::new(Struct16::default()), 16),
(|| Box::new(Struct32::default()), 32),
(|| Box::new(Struct64::default()), 64),
(|| Box::new(Struct128::default()), 128),
];
for (patch, field_count) in patches {
let field_count = *field_count;
group.throughput(Throughput::Elements(field_count as u64));
let mut base = DynamicStruct::default();
for i in 0..field_count {
let field_name = format!("field_{i}");
base.insert(&field_name, 1u32);
}
group.bench_with_input(
BenchmarkId::new("apply_concrete", field_count),
&patch,
|bencher, patch| {
bencher.iter_batched(
|| (base.to_dynamic_struct(), patch()),
|(mut base, patch)| base.apply(black_box(&*patch)),
BatchSize::SmallInput,
);
},
);
}
for field_count in SIZES {
group.throughput(Throughput::Elements(field_count as u64));
group.bench_with_input(
BenchmarkId::new("apply_dynamic", field_count),
&field_count,
|bencher, &field_count| {
let mut base = DynamicStruct::default();
let mut patch = DynamicStruct::default();
for i in 0..field_count {
let field_name = format!("field_{i}");
base.insert(&field_name, 0u32);
patch.insert(&field_name, 1u32);
}
bencher.iter_batched(
|| base.to_dynamic_struct(),
|mut base| base.apply(black_box(&patch)),
BatchSize::SmallInput,
);
},
);
}
}
fn dynamic_struct_insert(criterion: &mut Criterion) {
let mut group = create_group(criterion, bench!("dynamic_struct_insert"));
for field_count in SIZES {
group.throughput(Throughput::Elements(field_count as u64));
group.bench_with_input(
BenchmarkId::from_parameter(field_count),
&field_count,
|bencher, field_count| {
let mut s = DynamicStruct::default();
for i in 0..*field_count {
let field_name = format!("field_{i}");
s.insert(&field_name, ());
}
let field = format!("field_{field_count}");
bencher.iter_batched(
|| s.to_dynamic_struct(),
|mut s| {
s.insert(black_box(&field), ());
},
BatchSize::SmallInput,
);
},
);
}
group.finish();
}
fn dynamic_struct_get_field(criterion: &mut Criterion) {
let mut group = create_group(criterion, bench!("dynamic_struct_get_field"));
for field_count in SIZES {
group.throughput(Throughput::Elements(field_count as u64));
group.bench_with_input(
BenchmarkId::from_parameter(field_count),
&field_count,
|bencher, field_count| {
let mut s = DynamicStruct::default();
for i in 0..*field_count {
let field_name = format!("field_{i}");
s.insert(&field_name, ());
}
let field = black_box("field_63");
bencher.iter(|| s.get_field::<()>(field));
},
);
}
}
#[derive(Clone, Default, Reflect)]
struct Struct1 {
field_0: u32,
}
#[derive(Clone, Default, Reflect)]
struct Struct16 {
field_0: u32,
field_1: u32,
field_2: u32,
field_3: u32,
field_4: u32,
field_5: u32,
field_6: u32,
field_7: u32,
field_8: u32,
field_9: u32,
field_10: u32,
field_11: u32,
field_12: u32,
field_13: u32,
field_14: u32,
field_15: u32,
}
#[derive(Clone, Default, Reflect)]
struct Struct32 {
field_0: u32,
field_1: u32,
field_2: u32,
field_3: u32,
field_4: u32,
field_5: u32,
field_6: u32,
field_7: u32,
field_8: u32,
field_9: u32,
field_10: u32,
field_11: u32,
field_12: u32,
field_13: u32,
field_14: u32,
field_15: u32,
field_16: u32,
field_17: u32,
field_18: u32,
field_19: u32,
field_20: u32,
field_21: u32,
field_22: u32,
field_23: u32,
field_24: u32,
field_25: u32,
field_26: u32,
field_27: u32,
field_28: u32,
field_29: u32,
field_30: u32,
field_31: u32,
}
#[derive(Clone, Default, Reflect)]
struct Struct64 {
field_0: u32,
field_1: u32,
field_2: u32,
field_3: u32,
field_4: u32,
field_5: u32,
field_6: u32,
field_7: u32,
field_8: u32,
field_9: u32,
field_10: u32,
field_11: u32,
field_12: u32,
field_13: u32,
field_14: u32,
field_15: u32,
field_16: u32,
field_17: u32,
field_18: u32,
field_19: u32,
field_20: u32,
field_21: u32,
field_22: u32,
field_23: u32,
field_24: u32,
field_25: u32,
field_26: u32,
field_27: u32,
field_28: u32,
field_29: u32,
field_30: u32,
field_31: u32,
field_32: u32,
field_33: u32,
field_34: u32,
field_35: u32,
field_36: u32,
field_37: u32,
field_38: u32,
field_39: u32,
field_40: u32,
field_41: u32,
field_42: u32,
field_43: u32,
field_44: u32,
field_45: u32,
field_46: u32,
field_47: u32,
field_48: u32,
field_49: u32,
field_50: u32,
field_51: u32,
field_52: u32,
field_53: u32,
field_54: u32,
field_55: u32,
field_56: u32,
field_57: u32,
field_58: u32,
field_59: u32,
field_60: u32,
field_61: u32,
field_62: u32,
field_63: u32,
}
#[derive(Clone, Default, Reflect)]
struct Struct128 {
field_0: u32,
field_1: u32,
field_2: u32,
field_3: u32,
field_4: u32,
field_5: u32,
field_6: u32,
field_7: u32,
field_8: u32,
field_9: u32,
field_10: u32,
field_11: u32,
field_12: u32,
field_13: u32,
field_14: u32,
field_15: u32,
field_16: u32,
field_17: u32,
field_18: u32,
field_19: u32,
field_20: u32,
field_21: u32,
field_22: u32,
field_23: u32,
field_24: u32,
field_25: u32,
field_26: u32,
field_27: u32,
field_28: u32,
field_29: u32,
field_30: u32,
field_31: u32,
field_32: u32,
field_33: u32,
field_34: u32,
field_35: u32,
field_36: u32,
field_37: u32,
field_38: u32,
field_39: u32,
field_40: u32,
field_41: u32,
field_42: u32,
field_43: u32,
field_44: u32,
field_45: u32,
field_46: u32,
field_47: u32,
field_48: u32,
field_49: u32,
field_50: u32,
field_51: u32,
field_52: u32,
field_53: u32,
field_54: u32,
field_55: u32,
field_56: u32,
field_57: u32,
field_58: u32,
field_59: u32,
field_60: u32,
field_61: u32,
field_62: u32,
field_63: u32,
field_64: u32,
field_65: u32,
field_66: u32,
field_67: u32,
field_68: u32,
field_69: u32,
field_70: u32,
field_71: u32,
field_72: u32,
field_73: u32,
field_74: u32,
field_75: u32,
field_76: u32,
field_77: u32,
field_78: u32,
field_79: u32,
field_80: u32,
field_81: u32,
field_82: u32,
field_83: u32,
field_84: u32,
field_85: u32,
field_86: u32,
field_87: u32,
field_88: u32,
field_89: u32,
field_90: u32,
field_91: u32,
field_92: u32,
field_93: u32,
field_94: u32,
field_95: u32,
field_96: u32,
field_97: u32,
field_98: u32,
field_99: u32,
field_100: u32,
field_101: u32,
field_102: u32,
field_103: u32,
field_104: u32,
field_105: u32,
field_106: u32,
field_107: u32,
field_108: u32,
field_109: u32,
field_110: u32,
field_111: u32,
field_112: u32,
field_113: u32,
field_114: u32,
field_115: u32,
field_116: u32,
field_117: u32,
field_118: u32,
field_119: u32,
field_120: u32,
field_121: u32,
field_122: u32,
field_123: u32,
field_124: u32,
field_125: u32,
field_126: u32,
field_127: u32,
}
#[derive(Clone, Default, Reflect)]
struct GenericStruct1<T: Reflect + Default> {
field_0: T,
}
#[derive(Clone, Default, Reflect)]
struct GenericStruct16<T: Reflect + Default> {
field_0: T,
field_1: T,
field_2: T,
field_3: T,
field_4: T,
field_5: T,
field_6: T,
field_7: T,
field_8: T,
field_9: T,
field_10: T,
field_11: T,
field_12: T,
field_13: T,
field_14: T,
field_15: T,
}
#[derive(Clone, Default, Reflect)]
struct GenericStruct32<T: Reflect + Default> {
field_0: T,
field_1: T,
field_2: T,
field_3: T,
field_4: T,
field_5: T,
field_6: T,
field_7: T,
field_8: T,
field_9: T,
field_10: T,
field_11: T,
field_12: T,
field_13: T,
field_14: T,
field_15: T,
field_16: T,
field_17: T,
field_18: T,
field_19: T,
field_20: T,
field_21: T,
field_22: T,
field_23: T,
field_24: T,
field_25: T,
field_26: T,
field_27: T,
field_28: T,
field_29: T,
field_30: T,
field_31: T,
}
#[derive(Clone, Default, Reflect)]
struct GenericStruct64<T: Reflect + Default> {
field_0: T,
field_1: T,
field_2: T,
field_3: T,
field_4: T,
field_5: T,
field_6: T,
field_7: T,
field_8: T,
field_9: T,
field_10: T,
field_11: T,
field_12: T,
field_13: T,
field_14: T,
field_15: T,
field_16: T,
field_17: T,
field_18: T,
field_19: T,
field_20: T,
field_21: T,
field_22: T,
field_23: T,
field_24: T,
field_25: T,
field_26: T,
field_27: T,
field_28: T,
field_29: T,
field_30: T,
field_31: T,
field_32: T,
field_33: T,
field_34: T,
field_35: T,
field_36: T,
field_37: T,
field_38: T,
field_39: T,
field_40: T,
field_41: T,
field_42: T,
field_43: T,
field_44: T,
field_45: T,
field_46: T,
field_47: T,
field_48: T,
field_49: T,
field_50: T,
field_51: T,
field_52: T,
field_53: T,
field_54: T,
field_55: T,
field_56: T,
field_57: T,
field_58: T,
field_59: T,
field_60: T,
field_61: T,
field_62: T,
field_63: T,
}
#[derive(Clone, Default, Reflect)]
struct GenericStruct128<T: Reflect + Default> {
field_0: T,
field_1: T,
field_2: T,
field_3: T,
field_4: T,
field_5: T,
field_6: T,
field_7: T,
field_8: T,
field_9: T,
field_10: T,
field_11: T,
field_12: T,
field_13: T,
field_14: T,
field_15: T,
field_16: T,
field_17: T,
field_18: T,
field_19: T,
field_20: T,
field_21: T,
field_22: T,
field_23: T,
field_24: T,
field_25: T,
field_26: T,
field_27: T,
field_28: T,
field_29: T,
field_30: T,
field_31: T,
field_32: T,
field_33: T,
field_34: T,
field_35: T,
field_36: T,
field_37: T,
field_38: T,
field_39: T,
field_40: T,
field_41: T,
field_42: T,
field_43: T,
field_44: T,
field_45: T,
field_46: T,
field_47: T,
field_48: T,
field_49: T,
field_50: T,
field_51: T,
field_52: T,
field_53: T,
field_54: T,
field_55: T,
field_56: T,
field_57: T,
field_58: T,
field_59: T,
field_60: T,
field_61: T,
field_62: T,
field_63: T,
field_64: T,
field_65: T,
field_66: T,
field_67: T,
field_68: T,
field_69: T,
field_70: T,
field_71: T,
field_72: T,
field_73: T,
field_74: T,
field_75: T,
field_76: T,
field_77: T,
field_78: T,
field_79: T,
field_80: T,
field_81: T,
field_82: T,
field_83: T,
field_84: T,
field_85: T,
field_86: T,
field_87: T,
field_88: T,
field_89: T,
field_90: T,
field_91: T,
field_92: T,
field_93: T,
field_94: T,
field_95: T,
field_96: T,
field_97: T,
field_98: T,
field_99: T,
field_100: T,
field_101: T,
field_102: T,
field_103: T,
field_104: T,
field_105: T,
field_106: T,
field_107: T,
field_108: T,
field_109: T,
field_110: T,
field_111: T,
field_112: T,
field_113: T,
field_114: T,
field_115: T,
field_116: T,
field_117: T,
field_118: T,
field_119: T,
field_120: T,
field_121: T,
field_122: T,
field_123: T,
field_124: T,
field_125: T,
field_126: T,
field_127: T,
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_reflect/path.rs | benches/benches/bevy_reflect/path.rs | use core::{fmt::Write, hint::black_box, str, time::Duration};
use benches::bench;
use bevy_reflect::ParsedPath;
use criterion::{criterion_group, BatchSize, BenchmarkId, Criterion, Throughput};
use rand::{distr::Uniform, Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
criterion_group!(benches, parse_reflect_path);
const WARM_UP_TIME: Duration = Duration::from_millis(500);
const MEASUREMENT_TIME: Duration = Duration::from_secs(2);
const SAMPLE_SIZE: usize = 500;
const NOISE_THRESHOLD: f64 = 0.03;
const SIZES: [usize; 6] = [100, 316, 1_000, 3_162, 10_000, 24_000];
fn deterministic_rand() -> ChaCha8Rng {
ChaCha8Rng::seed_from_u64(42)
}
fn random_ident(rng: &mut ChaCha8Rng, f: &mut dyn Write) {
let between = Uniform::new_inclusive(b'a', b'z').unwrap();
let ident_size = rng.random_range(1..128);
let ident: Vec<u8> = rng.sample_iter(between).take(ident_size).collect();
let ident = str::from_utf8(&ident).unwrap();
let _ = write!(f, "{ident}");
}
fn random_index(rng: &mut ChaCha8Rng, f: &mut dyn Write) {
let index = rng.random_range(1..128);
let _ = write!(f, "{index}");
}
fn write_random_access(rng: &mut ChaCha8Rng, f: &mut dyn Write) {
match rng.random_range(0..4) {
0 => {
// Access::Field
f.write_char('.').unwrap();
random_ident(rng, f);
}
1 => {
// Access::FieldIndex
f.write_char('#').unwrap();
random_index(rng, f);
}
2 => {
// Access::Index
f.write_char('[').unwrap();
random_index(rng, f);
f.write_char(']').unwrap();
}
3 => {
// Access::TupleIndex
f.write_char('.').unwrap();
random_index(rng, f);
}
_ => unreachable!(),
}
}
fn mk_paths(size: usize) -> impl FnMut() -> String {
let mut rng = deterministic_rand();
move || {
let mut ret = String::new();
(0..size).for_each(|_| write_random_access(&mut rng, &mut ret));
ret
}
}
fn parse_reflect_path(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group(bench!("parse_reflect_path"));
group.warm_up_time(WARM_UP_TIME);
group.measurement_time(MEASUREMENT_TIME);
group.sample_size(SAMPLE_SIZE);
group.noise_threshold(NOISE_THRESHOLD);
for size in SIZES {
group.throughput(Throughput::Elements(size as u64));
group.bench_with_input(
BenchmarkId::from_parameter(size),
&size,
|bencher, &size| {
let mk_paths = mk_paths(size);
bencher.iter_batched(
mk_paths,
|path| {
let parsed_path = black_box(ParsedPath::parse(black_box(&path)));
// When `cargo test --benches` is run, each benchmark is run once. This
// verifies that we are benchmarking a successful parse without it
// affecting the recorded time.
#[cfg(test)]
assert!(parsed_path.is_ok());
},
BatchSize::SmallInput,
);
},
);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_reflect/list.rs | benches/benches/bevy_reflect/list.rs | use core::{hint::black_box, iter, time::Duration};
use benches::bench;
use bevy_reflect::{DynamicList, List};
use criterion::{
criterion_group, measurement::Measurement, AxisScale, BatchSize, BenchmarkGroup, BenchmarkId,
Criterion, PlotConfiguration, Throughput,
};
criterion_group!(
benches,
concrete_list_apply,
concrete_list_to_dynamic_list,
dynamic_list_apply,
dynamic_list_push
);
// Use a shorter warm-up time (from 3 to 0.5 seconds) and measurement time (from 5 to 4) because we
// have so many combinations (>50) to benchmark.
const WARM_UP_TIME: Duration = Duration::from_millis(500);
const MEASUREMENT_TIME: Duration = Duration::from_secs(4);
/// An array of list sizes used in benchmarks.
///
/// This scales logarithmically.
const SIZES: [usize; 5] = [100, 316, 1000, 3162, 10000];
/// Creates a [`BenchmarkGroup`] with common configuration shared by all benchmarks within this
/// module.
fn create_group<'a, M: Measurement>(c: &'a mut Criterion<M>, name: &str) -> BenchmarkGroup<'a, M> {
let mut group = c.benchmark_group(name);
group
.warm_up_time(WARM_UP_TIME)
.measurement_time(MEASUREMENT_TIME)
// Make the plots logarithmic, matching `SIZES`' scale.
.plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic));
group
}
fn list_apply<M, LBase, LPatch, F1, F2, F3>(
group: &mut BenchmarkGroup<M>,
bench_name: &str,
f_base: F1,
f_patch: F3,
) where
M: Measurement,
LBase: List,
LPatch: List,
F1: Fn(usize) -> F2,
F2: Fn() -> LBase,
F3: Fn(usize) -> LPatch,
{
for size in SIZES {
group.throughput(Throughput::Elements(size as u64));
group.bench_with_input(
BenchmarkId::new(bench_name, size),
&size,
|bencher, &size| {
let f_base = f_base(size);
let patch = f_patch(size);
bencher.iter_batched(
f_base,
|mut base| base.apply(black_box(&patch)),
BatchSize::SmallInput,
);
},
);
}
}
fn concrete_list_apply(criterion: &mut Criterion) {
let mut group = create_group(criterion, bench!("concrete_list_apply"));
let empty_base = |_: usize| Vec::<u64>::new;
let full_base = |size: usize| move || iter::repeat_n(0, size).collect::<Vec<u64>>();
let patch = |size: usize| iter::repeat_n(1, size).collect::<Vec<u64>>();
list_apply(&mut group, "empty_base_concrete_patch", empty_base, patch);
list_apply(&mut group, "empty_base_dynamic_patch", empty_base, |size| {
patch(size).to_dynamic_list()
});
list_apply(&mut group, "same_len_concrete_patch", full_base, patch);
list_apply(&mut group, "same_len_dynamic_patch", full_base, |size| {
patch(size).to_dynamic_list()
});
group.finish();
}
fn concrete_list_to_dynamic_list(criterion: &mut Criterion) {
let mut group = create_group(criterion, bench!("concrete_list_to_dynamic_list"));
for size in SIZES {
group.throughput(Throughput::Elements(size as u64));
group.bench_with_input(
BenchmarkId::from_parameter(size),
&size,
|bencher, &size| {
let v = iter::repeat_n(0, size).collect::<Vec<_>>();
bencher.iter(|| black_box(&v).to_dynamic_list());
},
);
}
group.finish();
}
fn dynamic_list_push(criterion: &mut Criterion) {
let mut group = create_group(criterion, bench!("dynamic_list_push"));
for size in SIZES {
group.throughput(Throughput::Elements(size as u64));
group.bench_with_input(
BenchmarkId::from_parameter(size),
&size,
|bencher, &size| {
let src = iter::repeat_n((), size).collect::<Vec<_>>();
let dst = DynamicList::default();
bencher.iter_batched(
|| (src.clone(), dst.to_dynamic_list()),
|(src, mut dst)| {
for item in src {
dst.push(item);
}
},
BatchSize::SmallInput,
);
},
);
}
group.finish();
}
fn dynamic_list_apply(criterion: &mut Criterion) {
let mut group = create_group(criterion, bench!("dynamic_list_apply"));
let empty_base = |_: usize| || Vec::<u64>::new().to_dynamic_list();
let full_base = |size: usize| move || iter::repeat_n(0, size).collect::<Vec<u64>>();
let patch = |size: usize| iter::repeat_n(1, size).collect::<Vec<u64>>();
list_apply(&mut group, "empty_base_concrete_patch", empty_base, patch);
list_apply(&mut group, "empty_base_dynamic_patch", empty_base, |size| {
patch(size).to_dynamic_list()
});
list_apply(&mut group, "same_len_concrete_patch", full_base, patch);
list_apply(&mut group, "same_len_dynamic_patch", full_base, |size| {
patch(size).to_dynamic_list()
});
group.finish();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_reflect/function.rs | benches/benches/bevy_reflect/function.rs | use core::hint::black_box;
use benches::bench;
use bevy_reflect::func::{ArgList, IntoFunction, IntoFunctionMut, TypedFunction};
use criterion::{criterion_group, BatchSize, BenchmarkId, Criterion};
criterion_group!(
benches,
typed,
into,
call,
clone,
with_overload,
call_overload,
);
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn typed(c: &mut Criterion) {
c.benchmark_group(bench!("typed"))
.bench_function("function", |b| {
b.iter(|| add.get_function_info());
})
.bench_function("closure", |b| {
let capture = 25;
let closure = |a: i32| a + capture;
b.iter(|| closure.get_function_info());
})
.bench_function("closure_mut", |b| {
let mut capture = 25;
let closure = |a: i32| capture += a;
b.iter(|| closure.get_function_info());
});
}
fn into(c: &mut Criterion) {
c.benchmark_group(bench!("into"))
.bench_function("function", |b| {
b.iter(|| add.into_function());
})
.bench_function("closure", |b| {
let capture = 25;
let closure = |a: i32| a + capture;
b.iter(|| closure.into_function());
})
.bench_function("closure_mut", |b| {
let mut _capture = 25;
// `move` is required here because `into_function_mut()` takes ownership of `self`.
#[expect(
unused_assignments,
reason = "rustc bug https://github.com/rust-lang/rust/issues/149889"
)]
let closure = move |a: i32| _capture += a;
b.iter(|| closure.into_function_mut());
});
}
fn call(c: &mut Criterion) {
c.benchmark_group(bench!("call"))
.bench_function("trait_object", |b| {
b.iter_batched(
|| Box::new(add) as Box<dyn Fn(i32, i32) -> i32>,
|func| func(black_box(75), black_box(25)),
BatchSize::SmallInput,
);
})
.bench_function("function", |b| {
let add = add.into_function();
b.iter_batched(
|| ArgList::new().with_owned(75_i32).with_owned(25_i32),
|args| add.call(args),
BatchSize::SmallInput,
);
})
.bench_function("closure", |b| {
let capture = 25;
let add = (|a: i32| a + capture).into_function();
b.iter_batched(
|| ArgList::new().with_owned(75_i32),
|args| add.call(args),
BatchSize::SmallInput,
);
})
.bench_function("closure_mut", |b| {
let mut capture = 25;
let mut add = (|a: i32| capture += a).into_function_mut();
b.iter_batched(
|| ArgList::new().with_owned(75_i32),
|args| add.call(args),
BatchSize::SmallInput,
);
});
}
fn clone(c: &mut Criterion) {
c.benchmark_group(bench!("clone"))
.bench_function("function", |b| {
let add = add.into_function();
b.iter(|| add.clone());
});
}
fn simple<T: std::ops::Add<Output = T>>(a: T, b: T) -> T {
a + b
}
fn complex<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>(
_: T0,
_: T1,
_: T2,
_: T3,
_: T4,
_: T5,
_: T6,
_: T7,
_: T8,
_: T9,
) {
}
fn with_overload(c: &mut Criterion) {
c.benchmark_group(bench!("with_overload"))
.bench_function(BenchmarkId::new("simple_overload", 1), |b| {
b.iter_batched(
|| simple::<i8>.into_function(),
|func| func.with_overload(simple::<i16>),
BatchSize::SmallInput,
);
})
.bench_function(BenchmarkId::new("complex_overload", 1), |b| {
b.iter_batched(
|| complex::<i8, i16, i32, i64, i128, u8, u16, u32, u64, u128>.into_function(),
|func| {
func.with_overload(complex::<i16, i32, i64, i128, u8, u16, u32, u64, u128, i8>)
},
BatchSize::SmallInput,
);
})
.bench_function(BenchmarkId::new("simple_overload", 3), |b| {
b.iter_batched(
|| simple::<i8>.into_function(),
|func| {
func.with_overload(simple::<i16>)
.with_overload(simple::<i32>)
.with_overload(simple::<i64>)
},
BatchSize::SmallInput,
);
})
.bench_function(BenchmarkId::new("complex_overload", 3), |b| {
b.iter_batched(
|| complex::<i8, i16, i32, i64, i128, u8, u16, u32, u64, u128>.into_function(),
|func| {
func.with_overload(complex::<i16, i32, i64, i128, u8, u16, u32, u64, u128, i8>)
.with_overload(complex::<i32, i64, i128, u8, u16, u32, u64, u128, i8, i16>)
.with_overload(complex::<i64, i128, u8, u16, u32, u64, u128, i8, i16, i32>)
},
BatchSize::SmallInput,
);
})
.bench_function(BenchmarkId::new("simple_overload", 10), |b| {
b.iter_batched(
|| simple::<i8>.into_function(),
|func| {
func.with_overload(simple::<i16>)
.with_overload(simple::<i32>)
.with_overload(simple::<i64>)
.with_overload(simple::<i128>)
.with_overload(simple::<u8>)
.with_overload(simple::<u16>)
.with_overload(simple::<u32>)
.with_overload(simple::<u64>)
.with_overload(simple::<u128>)
},
BatchSize::SmallInput,
);
})
.bench_function(BenchmarkId::new("complex_overload", 10), |b| {
b.iter_batched(
|| complex::<i8, i16, i32, i64, i128, u8, u16, u32, u64, u128>.into_function(),
|func| {
func.with_overload(complex::<i16, i32, i64, i128, u8, u16, u32, u64, u128, i8>)
.with_overload(complex::<i32, i64, i128, u8, u16, u32, u64, u128, i8, i16>)
.with_overload(complex::<i64, i128, u8, u16, u32, u64, u128, i8, i16, i32>)
.with_overload(complex::<i128, u8, u16, u32, u64, u128, i8, i16, i32, i64>)
.with_overload(complex::<u8, u16, u32, u64, u128, i8, i16, i32, i64, i128>)
.with_overload(complex::<u16, u32, u64, u128, i8, i16, i32, i64, i128, u8>)
.with_overload(complex::<u32, u64, u128, i8, i16, i32, i64, i128, u8, u16>)
.with_overload(complex::<u64, u128, i8, i16, i32, i64, i128, u8, u16, u32>)
.with_overload(complex::<u128, i8, i16, i32, i64, i128, u8, u16, u32, u64>)
},
BatchSize::SmallInput,
);
})
.bench_function(BenchmarkId::new("nested_simple_overload", 1), |b| {
b.iter_batched(
|| simple::<i8>.into_function(),
|func| func.with_overload(simple::<i16>),
BatchSize::SmallInput,
);
})
.bench_function(BenchmarkId::new("nested_simple_overload", 3), |b| {
b.iter_batched(
|| simple::<i8>.into_function(),
|func| {
func.with_overload(
simple::<i16>.into_function().with_overload(
simple::<i32>.into_function().with_overload(simple::<i64>),
),
)
},
BatchSize::SmallInput,
);
})
.bench_function(BenchmarkId::new("nested_simple_overload", 10), |b| {
b.iter_batched(
|| simple::<i8>.into_function(),
|func| {
func.with_overload(
simple::<i16>.into_function().with_overload(
simple::<i32>.into_function().with_overload(
simple::<i64>.into_function().with_overload(
simple::<i128>.into_function().with_overload(
simple::<u8>.into_function().with_overload(
simple::<u16>.into_function().with_overload(
simple::<u32>.into_function().with_overload(
simple::<u64>
.into_function()
.with_overload(simple::<u128>),
),
),
),
),
),
),
),
)
},
BatchSize::SmallInput,
);
});
}
fn call_overload(c: &mut Criterion) {
c.benchmark_group(bench!("call_overload"))
.bench_function(BenchmarkId::new("simple_overload", 1), |b| {
b.iter_batched(
|| {
(
simple::<i8>.into_function().with_overload(simple::<i16>),
ArgList::new().with_owned(75_i8).with_owned(25_i8),
)
},
|(func, args)| func.call(args),
BatchSize::SmallInput,
);
})
.bench_function(BenchmarkId::new("complex_overload", 1), |b| {
b.iter_batched(
|| {
(
complex::<i8, i16, i32, i64, i128, u8, u16, u32, u64, u128>
.into_function()
.with_overload(
complex::<i16, i32, i64, i128, u8, u16, u32, u64, u128, i8>,
),
ArgList::new()
.with_owned(1_i8)
.with_owned(2_i16)
.with_owned(3_i32)
.with_owned(4_i64)
.with_owned(5_i128)
.with_owned(6_u8)
.with_owned(7_u16)
.with_owned(8_u32)
.with_owned(9_u64)
.with_owned(10_u128),
)
},
|(func, args)| func.call(args),
BatchSize::SmallInput,
);
})
.bench_function(BenchmarkId::new("simple_overload", 3), |b| {
b.iter_batched(
|| {
(
simple::<i8>
.into_function()
.with_overload(simple::<i16>)
.with_overload(simple::<i32>)
.with_overload(simple::<i64>),
ArgList::new().with_owned(75_i32).with_owned(25_i32),
)
},
|(func, args)| func.call(args),
BatchSize::SmallInput,
);
})
.bench_function(BenchmarkId::new("complex_overload", 3), |b| {
b.iter_batched(
|| {
(
complex::<i8, i16, i32, i64, i128, u8, u16, u32, u64, u128>
.into_function()
.with_overload(
complex::<i16, i32, i64, i128, u8, u16, u32, u64, u128, i8>,
)
.with_overload(
complex::<i32, i64, i128, u8, u16, u32, u64, u128, i8, i16>,
)
.with_overload(
complex::<i64, i128, u8, u16, u32, u64, u128, i8, i16, i32>,
),
ArgList::new()
.with_owned(1_i32)
.with_owned(2_i64)
.with_owned(3_i128)
.with_owned(4_u8)
.with_owned(5_u16)
.with_owned(6_u32)
.with_owned(7_u64)
.with_owned(8_u128)
.with_owned(9_i8)
.with_owned(10_i16),
)
},
|(func, args)| func.call(args),
BatchSize::SmallInput,
);
})
.bench_function(BenchmarkId::new("simple_overload", 10), |b| {
b.iter_batched(
|| {
(
simple::<i8>
.into_function()
.with_overload(simple::<i16>)
.with_overload(simple::<i32>)
.with_overload(simple::<i64>)
.with_overload(simple::<i128>)
.with_overload(simple::<u8>)
.with_overload(simple::<u16>)
.with_overload(simple::<u32>)
.with_overload(simple::<u64>)
.with_overload(simple::<u128>),
ArgList::new().with_owned(75_u8).with_owned(25_u8),
)
},
|(func, args)| func.call(args),
BatchSize::SmallInput,
);
})
.bench_function(BenchmarkId::new("complex_overload", 10), |b| {
b.iter_batched(
|| {
(
complex::<i8, i16, i32, i64, i128, u8, u16, u32, u64, u128>
.into_function()
.with_overload(
complex::<i16, i32, i64, i128, u8, u16, u32, u64, u128, i8>,
)
.with_overload(
complex::<i32, i64, i128, u8, u16, u32, u64, u128, i8, i16>,
)
.with_overload(
complex::<i64, i128, u8, u16, u32, u64, u128, i8, i16, i32>,
)
.with_overload(
complex::<i128, u8, u16, u32, u64, u128, i8, i16, i32, i64>,
)
.with_overload(
complex::<u8, u16, u32, u64, u128, i8, i16, i32, i64, i128>,
)
.with_overload(
complex::<u16, u32, u64, u128, i8, i16, i32, i64, i128, u8>,
)
.with_overload(
complex::<u32, u64, u128, i8, i16, i32, i64, i128, u8, u16>,
)
.with_overload(
complex::<u64, u128, i8, i16, i32, i64, i128, u8, u16, u32>,
)
.with_overload(
complex::<u128, i8, i16, i32, i64, i128, u8, u16, u32, u64>,
),
ArgList::new()
.with_owned(1_u8)
.with_owned(2_u16)
.with_owned(3_u32)
.with_owned(4_u64)
.with_owned(5_u128)
.with_owned(6_i8)
.with_owned(7_i16)
.with_owned(8_i32)
.with_owned(9_i64)
.with_owned(10_i128),
)
},
|(func, args)| func.call(args),
BatchSize::SmallInput,
);
});
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_reflect/map.rs | benches/benches/bevy_reflect/map.rs | use core::{fmt::Write, hint::black_box, iter, time::Duration};
use benches::bench;
use bevy_platform::collections::HashMap;
use bevy_reflect::{DynamicMap, Map};
use criterion::{
criterion_group, measurement::Measurement, AxisScale, BatchSize, BenchmarkGroup, BenchmarkId,
Criterion, PlotConfiguration, Throughput,
};
criterion_group!(
benches,
concrete_map_apply,
dynamic_map_apply,
dynamic_map_get,
dynamic_map_insert
);
// Use a shorter warm-up time (from 3 to 0.5 seconds) and measurement time (from 5 to 4) because we
// have so many combinations (>50) to benchmark.
const WARM_UP_TIME: Duration = Duration::from_millis(500);
const MEASUREMENT_TIME: Duration = Duration::from_secs(4);
/// An array of list sizes used in benchmarks.
///
/// This scales logarithmically.
const SIZES: [usize; 5] = [100, 316, 1000, 3162, 10000];
/// Creates a [`BenchmarkGroup`] with common configuration shared by all benchmarks within this
/// module.
fn create_group<'a, M: Measurement>(c: &'a mut Criterion<M>, name: &str) -> BenchmarkGroup<'a, M> {
let mut group = c.benchmark_group(name);
group
.warm_up_time(WARM_UP_TIME)
.measurement_time(MEASUREMENT_TIME)
// Make the plots logarithmic, matching `SIZES`' scale.
.plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic));
group
}
/// Generic benchmark for applying one `Map` to another.
///
/// `f_base` is a function which takes an input size and produces a generator
/// for new base maps. `f_patch` is a function which produces a map to be
/// applied to the base map.
fn map_apply<M, MBase, MPatch, F1, F2, F3>(
group: &mut BenchmarkGroup<M>,
bench_name: &str,
f_base: F1,
f_patch: F3,
) where
M: Measurement,
MBase: Map,
MPatch: Map,
F1: Fn(usize) -> F2,
F2: Fn() -> MBase,
F3: Fn(usize) -> MPatch,
{
for size in SIZES {
group.throughput(Throughput::Elements(size as u64));
group.bench_with_input(
BenchmarkId::new(bench_name, size),
&size,
|bencher, &size| {
let f_base = f_base(size);
bencher.iter_batched(
|| (f_base(), f_patch(size)),
|(mut base, patch)| base.apply(black_box(&patch)),
BatchSize::SmallInput,
);
},
);
}
}
fn concrete_map_apply(criterion: &mut Criterion) {
let mut group = create_group(criterion, bench!("concrete_map_apply"));
let empty_base = |_: usize| HashMap::<u64, u64>::default;
let key_range_base = |size: usize| {
move || {
(0..size as u64)
.zip(iter::repeat(0))
.collect::<HashMap<u64, u64>>()
}
};
let key_range_patch = |size: usize| {
(0..size as u64)
.zip(iter::repeat(1))
.collect::<HashMap<u64, u64>>()
};
let disjoint_patch = |size: usize| {
(size as u64..2 * size as u64)
.zip(iter::repeat(1))
.collect::<HashMap<u64, u64>>()
};
map_apply(
&mut group,
"empty_base_concrete_patch",
empty_base,
key_range_patch,
);
map_apply(&mut group, "empty_base_dynamic_patch", empty_base, |size| {
key_range_patch(size).to_dynamic_map()
});
map_apply(
&mut group,
"same_keys_concrete_patch",
key_range_base,
key_range_patch,
);
map_apply(
&mut group,
"same_keys_dynamic_patch",
key_range_base,
|size| key_range_patch(size).to_dynamic_map(),
);
map_apply(
&mut group,
"disjoint_keys_concrete_patch",
key_range_base,
disjoint_patch,
);
map_apply(
&mut group,
"disjoint_keys_dynamic_patch",
key_range_base,
|size| disjoint_patch(size).to_dynamic_map(),
);
}
fn u64_to_n_byte_key(k: u64, n: usize) -> String {
let mut key = String::with_capacity(n);
write!(&mut key, "{k}").unwrap();
// Pad key to n bytes.
key.extend(iter::repeat_n('\0', n - key.len()));
key
}
fn dynamic_map_apply(criterion: &mut Criterion) {
let mut group = create_group(criterion, bench!("dynamic_map_apply"));
let empty_base = |_: usize| DynamicMap::default;
let key_range_base = |size: usize| {
move || {
(0..size as u64)
.zip(iter::repeat(0))
.collect::<HashMap<u64, u64>>()
.to_dynamic_map()
}
};
let key_range_patch = |size: usize| {
(0..size as u64)
.zip(iter::repeat(1))
.collect::<HashMap<u64, u64>>()
};
let disjoint_patch = |size: usize| {
(size as u64..2 * size as u64)
.zip(iter::repeat(1))
.collect::<HashMap<u64, u64>>()
};
map_apply(
&mut group,
"empty_base_concrete_patch",
empty_base,
key_range_patch,
);
map_apply(&mut group, "empty_base_dynamic_patch", empty_base, |size| {
key_range_patch(size).to_dynamic_map()
});
map_apply(
&mut group,
"same_keys_concrete_patch",
key_range_base,
key_range_patch,
);
map_apply(
&mut group,
"same_keys_dynamic_patch",
key_range_base,
|size| key_range_patch(size).to_dynamic_map(),
);
map_apply(
&mut group,
"disjoint_keys_concrete_patch",
key_range_base,
disjoint_patch,
);
map_apply(
&mut group,
"disjoint_keys_dynamic_patch",
key_range_base,
|size| disjoint_patch(size).to_dynamic_map(),
);
}
fn dynamic_map_get(criterion: &mut Criterion) {
let mut group = create_group(criterion, bench!("dynamic_map_get"));
for size in SIZES {
group.throughput(Throughput::Elements(size as u64));
group.bench_with_input(
BenchmarkId::new("u64_keys", size),
&size,
|bencher, &size| {
let mut map = DynamicMap::default();
for i in 0..size as u64 {
map.insert(i, i);
}
bencher.iter(|| {
for i in 0..size as u64 {
let key = black_box(i);
black_box(map.get(&key));
}
});
},
);
}
for size in SIZES {
group.throughput(Throughput::Elements(size as u64));
group.bench_with_input(
BenchmarkId::new("64_byte_keys", size),
&size,
|bencher, &size| {
let mut map = DynamicMap::default();
let mut keys = Vec::with_capacity(size);
for i in 0..size as u64 {
let key = u64_to_n_byte_key(i, 64);
map.insert(key.clone(), i);
keys.push(key);
}
bencher.iter(|| {
for key in keys.iter().take(size) {
let key = black_box(key);
assert!(map.get(key).is_some());
}
});
},
);
}
}
fn dynamic_map_insert(criterion: &mut Criterion) {
let mut group = create_group(criterion, bench!("dynamic_map_insert"));
for size in SIZES {
group.throughput(Throughput::Elements(size as u64));
group.bench_with_input(
BenchmarkId::new("u64_keys", size),
&size,
|bencher, &size| {
bencher.iter_batched(
DynamicMap::default,
|mut map| {
for i in 0..size as u64 {
let key = black_box(i);
map.insert(key, black_box(i));
}
},
BatchSize::SmallInput,
);
},
);
}
for size in SIZES {
group.throughput(Throughput::Elements(size as u64));
group.bench_with_input(
BenchmarkId::new("64_byte_keys", size),
&size,
|bencher, &size| {
let mut keys = Vec::with_capacity(size);
for i in 0..size {
let key = u64_to_n_byte_key(i as u64, 64);
keys.push(key);
}
bencher.iter_batched(
|| (DynamicMap::default(), keys.clone()),
|(mut map, keys)| {
for (i, key) in keys.into_iter().enumerate() {
let key = black_box(key);
map.insert(key, i);
}
},
BatchSize::SmallInput,
);
},
);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_reflect/main.rs | benches/benches/bevy_reflect/main.rs | use criterion::criterion_main;
mod function;
mod list;
mod map;
mod path;
mod r#struct;
criterion_main!(
function::benches,
list::benches,
map::benches,
path::benches,
r#struct::benches,
);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_math/bounding.rs | benches/benches/bevy_math/bounding.rs | use benches::bench;
use bevy_math::{
bounding::{Aabb3d, BoundingSphere, BoundingVolume},
prelude::*,
};
use core::hint::black_box;
use criterion::{criterion_group, Criterion};
use rand::{
distr::{Distribution, StandardUniform, Uniform},
rngs::StdRng,
Rng, SeedableRng,
};
criterion_group!(benches, bounding);
struct PointCloud {
points: Vec<Vec3A>,
isometry: Isometry3d,
}
impl PointCloud {
fn aabb(&self) -> Aabb3d {
Aabb3d::from_point_cloud(self.isometry, self.points.iter().copied())
}
fn sphere(&self) -> BoundingSphere {
BoundingSphere::from_point_cloud(self.isometry, &self.points)
}
}
fn bounding(c: &mut Criterion) {
// Create point clouds of various sizes, then benchmark two different ways
// of finding the bounds of each cloud and merging them together.
let mut rng1 = StdRng::seed_from_u64(123);
let mut rng2 = StdRng::seed_from_u64(456);
let point_clouds = Uniform::<usize>::new(black_box(3), black_box(30))
.unwrap()
.sample_iter(&mut rng1)
.take(black_box(1000))
.map(|num_points| PointCloud {
points: StandardUniform
.sample_iter(&mut rng2)
.take(num_points)
.collect::<Vec<Vec3A>>(),
isometry: Isometry3d::new(rng2.random::<Vec3>(), rng2.random::<Quat>()),
})
.collect::<Vec<_>>();
c.bench_function(bench!("bounding"), |b| {
b.iter(|| {
let aabb = point_clouds
.iter()
.map(PointCloud::aabb)
.reduce(|l, r| l.merge(&r));
let sphere = point_clouds
.iter()
.map(PointCloud::sphere)
.reduce(|l, r| l.merge(&r));
black_box(aabb);
black_box(sphere);
});
});
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_math/bezier.rs | benches/benches/bevy_math/bezier.rs | use benches::bench;
use bevy_math::{prelude::*, VectorSpace};
use core::hint::black_box;
use criterion::{
criterion_group, measurement::Measurement, BatchSize, BenchmarkGroup, BenchmarkId, Criterion,
};
criterion_group!(benches, segment_ease, curve_position, curve_iter_positions);
fn segment_ease(c: &mut Criterion) {
let segment = black_box(CubicSegment::new_bezier_easing(
vec2(0.25, 0.1),
vec2(0.25, 1.0),
));
c.bench_function(bench!("segment_ease"), |b| {
let mut t = 0;
b.iter_batched(
|| {
// Increment `t` by 1, but use modulo to constrain it to `0..=1000`.
t = (t + 1) % 1001;
// Return time as a decimal between 0 and 1, inclusive.
t as f32 / 1000.0
},
|t| segment.ease(t),
BatchSize::SmallInput,
);
});
}
fn curve_position(c: &mut Criterion) {
/// A helper function that benchmarks calling [`CubicCurve::position()`] over a generic [`VectorSpace`].
fn bench_curve<M: Measurement, P: VectorSpace<Scalar = f32>>(
group: &mut BenchmarkGroup<M>,
name: &str,
curve: CubicCurve<P>,
) {
group.bench_with_input(BenchmarkId::from_parameter(name), &curve, |b, curve| {
b.iter(|| curve.position(black_box(0.5)));
});
}
let mut group = c.benchmark_group(bench!("curve_position"));
let bezier_2 = CubicBezier::new([[
vec2(0.0, 0.0),
vec2(0.0, 1.0),
vec2(1.0, 0.0),
vec2(1.0, 1.0),
]])
.to_curve()
.unwrap();
bench_curve(&mut group, "vec2", bezier_2);
let bezier_3 = CubicBezier::new([[
vec3(0.0, 0.0, 0.0),
vec3(0.0, 1.0, 0.0),
vec3(1.0, 0.0, 0.0),
vec3(1.0, 1.0, 1.0),
]])
.to_curve()
.unwrap();
bench_curve(&mut group, "vec3", bezier_3);
let bezier_3a = CubicBezier::new([[
vec3a(0.0, 0.0, 0.0),
vec3a(0.0, 1.0, 0.0),
vec3a(1.0, 0.0, 0.0),
vec3a(1.0, 1.0, 1.0),
]])
.to_curve()
.unwrap();
bench_curve(&mut group, "vec3a", bezier_3a);
group.finish();
}
fn curve_iter_positions(c: &mut Criterion) {
let bezier = CubicBezier::new([[
vec3a(0.0, 0.0, 0.0),
vec3a(0.0, 1.0, 0.0),
vec3a(1.0, 0.0, 0.0),
vec3a(1.0, 1.0, 1.0),
]])
.to_curve()
.unwrap();
c.bench_function(bench!("curve_iter_positions"), |b| {
b.iter(|| {
for x in bezier.iter_positions(black_box(100)) {
// Discard `x`, since we just care about `iter_positions()` being consumed, but make
// the compiler believe `x` is being used so it doesn't eliminate the iterator.
black_box(x);
}
});
});
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/benches/benches/bevy_math/main.rs | benches/benches/bevy_math/main.rs | use criterion::criterion_main;
mod bezier;
mod bounding;
criterion_main!(bezier::benches, bounding::benches);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_ptr/src/lib.rs | crates/bevy_ptr/src/lib.rs | #![doc = include_str!("../README.md")]
#![no_std]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![expect(unsafe_code, reason = "Raw pointers are inherently unsafe.")]
#![doc(
html_logo_url = "https://bevy.org/assets/icon.png",
html_favicon_url = "https://bevy.org/assets/icon.png"
)]
use core::{
cell::UnsafeCell,
fmt::{self, Debug, Formatter, Pointer},
marker::PhantomData,
mem::{self, ManuallyDrop, MaybeUninit},
ops::{Deref, DerefMut},
ptr::{self, NonNull},
};
/// Used as a type argument to [`Ptr`], [`PtrMut`], [`OwningPtr`], and [`MovingPtr`] to specify that the pointer is guaranteed
/// to be [aligned].
///
/// [aligned]: https://doc.rust-lang.org/std/ptr/index.html#alignment
#[derive(Debug, Copy, Clone)]
pub struct Aligned;
/// Used as a type argument to [`Ptr`], [`PtrMut`], [`OwningPtr`], and [`MovingPtr`] to specify that the pointer may not [aligned].
///
/// [aligned]: https://doc.rust-lang.org/std/ptr/index.html#alignment
#[derive(Debug, Copy, Clone)]
pub struct Unaligned;
/// Trait that is only implemented for [`Aligned`] and [`Unaligned`] to work around the lack of ability
/// to have const generics of an enum.
pub trait IsAligned: sealed::Sealed {
/// Reads the value pointed to by `ptr`.
///
/// # Safety
/// - `ptr` must be valid for reads.
/// - `ptr` must point to a valid instance of type `T`
/// - If this type is [`Aligned`], then `ptr` must be [properly aligned] for type `T`.
///
/// [properly aligned]: https://doc.rust-lang.org/std/ptr/index.html#alignment
#[doc(hidden)]
unsafe fn read_ptr<T>(ptr: *const T) -> T;
/// Copies `count * size_of::<T>()` bytes from `src` to `dst`. The source
/// and destination must *not* overlap.
///
/// # Safety
/// - `src` must be valid for reads of `count * size_of::<T>()` bytes.
/// - `dst` must be valid for writes of `count * size_of::<T>()` bytes.
/// - The region of memory beginning at `src` with a size of `count *
/// size_of::<T>()` bytes must *not* overlap with the region of memory
/// beginning at `dst` with the same size.
/// - If this type is [`Aligned`], then both `src` and `dst` must properly
/// be aligned for values of type `T`.
#[doc(hidden)]
unsafe fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize);
/// Reads the value pointed to by `ptr`.
///
/// # Safety
/// - `ptr` must be valid for reads and writes.
/// - `ptr` must point to a valid instance of type `T`
/// - If this type is [`Aligned`], then `ptr` must be [properly aligned] for type `T`.
/// - The value pointed to by `ptr` must be valid for dropping.
/// - While `drop_in_place` is executing, the only way to access parts of `ptr` is through
/// the `&mut Self` supplied to it's `Drop::drop` impl.
///
/// [properly aligned]: https://doc.rust-lang.org/std/ptr/index.html#alignment
#[doc(hidden)]
unsafe fn drop_in_place<T>(ptr: *mut T);
}
impl IsAligned for Aligned {
#[inline]
unsafe fn read_ptr<T>(ptr: *const T) -> T {
// SAFETY:
// - The caller is required to ensure that `src` must be valid for reads.
// - The caller is required to ensure that `src` points to a valid instance of type `T`.
// - This type is `Aligned` so the caller must ensure that `src` is properly aligned for type `T`.
unsafe { ptr.read() }
}
#[inline]
unsafe fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize) {
// SAFETY:
// - The caller is required to ensure that `src` must be valid for reads.
// - The caller is required to ensure that `dst` must be valid for writes.
// - The caller is required to ensure that `src` and `dst` are aligned.
// - The caller is required to ensure that the memory region covered by `src`
// and `dst`, fitting up to `count` elements do not overlap.
unsafe {
ptr::copy_nonoverlapping(src, dst, count);
}
}
#[inline]
unsafe fn drop_in_place<T>(ptr: *mut T) {
// SAFETY:
// - The caller is required to ensure that `ptr` must be valid for reads and writes.
// - The caller is required to ensure that `ptr` points to a valid instance of type `T`.
// - This type is `Aligned` so the caller must ensure that `ptr` is properly aligned for type `T`.
// - The caller is required to ensure that `ptr` points must be valid for dropping.
// - The caller is required to ensure that the value `ptr` points must not be used after this function
// call.
unsafe {
ptr::drop_in_place(ptr);
}
}
}
impl IsAligned for Unaligned {
#[inline]
unsafe fn read_ptr<T>(ptr: *const T) -> T {
// SAFETY:
// - The caller is required to ensure that `src` must be valid for reads.
// - The caller is required to ensure that `src` points to a valid instance of type `T`.
unsafe { ptr.read_unaligned() }
}
#[inline]
unsafe fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize) {
// SAFETY:
// - The caller is required to ensure that `src` must be valid for reads.
// - The caller is required to ensure that `dst` must be valid for writes.
// - This is doing a byte-wise copy. `src` and `dst` are always guaranteed to be
// aligned.
// - The caller is required to ensure that the memory region covered by `src`
// and `dst`, fitting up to `count` elements do not overlap.
unsafe {
ptr::copy_nonoverlapping::<u8>(
src.cast::<u8>(),
dst.cast::<u8>(),
count * size_of::<T>(),
);
}
}
#[inline]
unsafe fn drop_in_place<T>(ptr: *mut T) {
// SAFETY:
// - The caller is required to ensure that `ptr` must be valid for reads and writes.
// - The caller is required to ensure that `ptr` points to a valid instance of type `T`.
// - This type is not `Aligned` so the caller does not need to ensure that `ptr` is properly aligned for type `T`.
// - The caller is required to ensure that `ptr` points must be valid for dropping.
// - The caller is required to ensure that the value `ptr` points must not be used after this function
// call.
unsafe {
drop(ptr.read_unaligned());
}
}
}
mod sealed {
pub trait Sealed {}
impl Sealed for super::Aligned {}
impl Sealed for super::Unaligned {}
}
/// A newtype around [`NonNull`] that only allows conversion to read-only borrows or pointers.
///
/// This type can be thought of as the `*const T` to [`NonNull<T>`]'s `*mut T`.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct ConstNonNull<T: ?Sized>(NonNull<T>);
impl<T: ?Sized> ConstNonNull<T> {
/// Creates a new `ConstNonNull` if `ptr` is non-null.
///
/// # Examples
///
/// ```
/// use bevy_ptr::ConstNonNull;
///
/// let x = 0u32;
/// let ptr = ConstNonNull::<u32>::new(&x as *const _).expect("ptr is null!");
///
/// if let Some(ptr) = ConstNonNull::<u32>::new(core::ptr::null()) {
/// unreachable!();
/// }
/// ```
pub fn new(ptr: *const T) -> Option<Self> {
NonNull::new(ptr.cast_mut()).map(Self)
}
/// Creates a new `ConstNonNull`.
///
/// # Safety
///
/// `ptr` must be non-null.
///
/// # Examples
///
/// ```
/// use bevy_ptr::ConstNonNull;
///
/// let x = 0u32;
/// let ptr = unsafe { ConstNonNull::new_unchecked(&x as *const _) };
/// ```
///
/// *Incorrect* usage of this function:
///
/// ```rust,no_run
/// use bevy_ptr::ConstNonNull;
///
/// // NEVER DO THAT!!! This is undefined behavior. ⚠️
/// let ptr = unsafe { ConstNonNull::<u32>::new_unchecked(core::ptr::null()) };
/// ```
pub const unsafe fn new_unchecked(ptr: *const T) -> Self {
// SAFETY: This function's safety invariants are identical to `NonNull::new_unchecked`
// The caller must satisfy all of them.
unsafe { Self(NonNull::new_unchecked(ptr.cast_mut())) }
}
/// Returns a shared reference to the value.
///
/// # Safety
///
/// When calling this method, you have to ensure that all of the following is true:
///
/// * The pointer must be [properly aligned].
///
/// * It must be "dereferenceable" in the sense defined in [the module documentation].
///
/// * The pointer must point to an initialized instance of `T`.
///
/// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
/// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
/// In particular, while this reference exists, the memory the pointer points to must
/// not get mutated (except inside `UnsafeCell`).
///
/// This applies even if the result of this method is unused!
/// (The part about being initialized is not yet fully decided, but until
/// it is, the only safe approach is to ensure that they are indeed initialized.)
///
/// # Examples
///
/// ```
/// use bevy_ptr::ConstNonNull;
///
/// let mut x = 0u32;
/// let ptr = ConstNonNull::new(&mut x as *mut _).expect("ptr is null!");
///
/// let ref_x = unsafe { ptr.as_ref() };
/// println!("{ref_x}");
/// ```
///
/// [the module documentation]: core::ptr#safety
/// [properly aligned]: https://doc.rust-lang.org/std/ptr/index.html#alignment
#[inline]
pub unsafe fn as_ref<'a>(&self) -> &'a T {
// SAFETY: This function's safety invariants are identical to `NonNull::as_ref`
// The caller must satisfy all of them.
unsafe { self.0.as_ref() }
}
}
impl<T: ?Sized> From<NonNull<T>> for ConstNonNull<T> {
fn from(value: NonNull<T>) -> ConstNonNull<T> {
ConstNonNull(value)
}
}
impl<'a, T: ?Sized> From<&'a T> for ConstNonNull<T> {
fn from(value: &'a T) -> ConstNonNull<T> {
ConstNonNull(NonNull::from(value))
}
}
impl<'a, T: ?Sized> From<&'a mut T> for ConstNonNull<T> {
fn from(value: &'a mut T) -> ConstNonNull<T> {
ConstNonNull(NonNull::from(value))
}
}
/// Type-erased borrow of some unknown type chosen when constructing this type.
///
/// This type tries to act "borrow-like" which means that:
/// - It should be considered immutable: its target must not be changed while this pointer is alive.
/// - It must always point to a valid value of whatever the pointee type is.
/// - The lifetime `'a` accurately represents how long the pointer is valid for.
/// - If `A` is [`Aligned`], the pointer must always be [properly aligned] for the unknown pointee type.
///
/// It may be helpful to think of this type as similar to `&'a dyn Any` but without
/// the metadata and able to point to data that does not correspond to a Rust type.
///
/// [properly aligned]: https://doc.rust-lang.org/std/ptr/index.html#alignment
#[derive(Copy, Clone)]
#[repr(transparent)]
pub struct Ptr<'a, A: IsAligned = Aligned>(NonNull<u8>, PhantomData<(&'a u8, A)>);
/// Type-erased mutable borrow of some unknown type chosen when constructing this type.
///
/// This type tries to act "borrow-like" which means that:
/// - Pointer is considered exclusive and mutable. It cannot be cloned as this would lead to
/// aliased mutability.
/// - It must always point to a valid value of whatever the pointee type is.
/// - The lifetime `'a` accurately represents how long the pointer is valid for.
/// - If `A` is [`Aligned`], the pointer must always be [properly aligned] for the unknown pointee type.
///
/// It may be helpful to think of this type as similar to `&'a mut dyn Any` but without
/// the metadata and able to point to data that does not correspond to a Rust type.
///
/// [properly aligned]: https://doc.rust-lang.org/std/ptr/index.html#alignment
#[repr(transparent)]
pub struct PtrMut<'a, A: IsAligned = Aligned>(NonNull<u8>, PhantomData<(&'a mut u8, A)>);
/// Type-erased [`Box`]-like pointer to some unknown type chosen when constructing this type.
///
/// Conceptually represents ownership of whatever data is being pointed to and so is
/// responsible for calling its `Drop` impl. This pointer is _not_ responsible for freeing
/// the memory pointed to by this pointer as it may be pointing to an element in a `Vec` or
/// to a local in a function etc.
///
/// This type tries to act "borrow-like" which means that:
/// - Pointer should be considered exclusive and mutable. It cannot be cloned as this would lead
/// to aliased mutability and potentially use after free bugs.
/// - It must always point to a valid value of whatever the pointee type is.
/// - The lifetime `'a` accurately represents how long the pointer is valid for.
/// - If `A` is [`Aligned`], the pointer must always be [properly aligned] for the unknown pointee type.
///
/// It may be helpful to think of this type as similar to `&'a mut ManuallyDrop<dyn Any>` but
/// without the metadata and able to point to data that does not correspond to a Rust type.
///
/// [properly aligned]: https://doc.rust-lang.org/std/ptr/index.html#alignment
/// [`Box`]: https://doc.rust-lang.org/std/boxed/struct.Box.html
#[repr(transparent)]
pub struct OwningPtr<'a, A: IsAligned = Aligned>(NonNull<u8>, PhantomData<(&'a mut u8, A)>);
/// A [`Box`]-like pointer for moving a value to a new memory location without needing to pass by
/// value.
///
/// Conceptually represents ownership of whatever data is being pointed to and will call its
/// [`Drop`] impl upon being dropped. This pointer is _not_ responsible for freeing
/// the memory pointed to by this pointer as it may be pointing to an element in a `Vec` or
/// to a local in a function etc.
///
/// This type tries to act "borrow-like" which means that:
/// - Pointer should be considered exclusive and mutable. It cannot be cloned as this would lead
/// to aliased mutability and potentially use after free bugs.
/// - It must always point to a valid value of whatever the pointee type is.
/// - The lifetime `'a` accurately represents how long the pointer is valid for.
/// - It does not support pointer arithmetic in any way.
/// - If `A` is [`Aligned`], the pointer must always be [properly aligned] for the type `T`.
///
/// A value can be deconstructed into its fields via [`deconstruct_moving_ptr`], see it's documentation
/// for an example on how to use it.
///
/// [properly aligned]: https://doc.rust-lang.org/std/ptr/index.html#alignment
/// [`Box`]: https://doc.rust-lang.org/std/boxed/struct.Box.html
#[repr(transparent)]
pub struct MovingPtr<'a, T, A: IsAligned = Aligned>(NonNull<T>, PhantomData<(&'a mut T, A)>);
macro_rules! impl_ptr {
($ptr:ident) => {
impl<'a> $ptr<'a, Aligned> {
/// Removes the alignment requirement of this pointer
pub fn to_unaligned(self) -> $ptr<'a, Unaligned> {
$ptr(self.0, PhantomData)
}
}
impl<'a, A: IsAligned> From<$ptr<'a, A>> for NonNull<u8> {
fn from(ptr: $ptr<'a, A>) -> Self {
ptr.0
}
}
impl<A: IsAligned> $ptr<'_, A> {
/// Calculates the offset from a pointer.
/// As the pointer is type-erased, there is no size information available. The provided
/// `count` parameter is in raw bytes.
///
/// *See also: [`ptr::offset`][ptr_offset]*
///
/// # Safety
/// - The offset cannot make the existing ptr null, or take it out of bounds for its allocation.
/// - If the `A` type parameter is [`Aligned`] then the offset must not make the resulting pointer
/// be unaligned for the pointee type.
/// - The value pointed by the resulting pointer must outlive the lifetime of this pointer.
///
/// [ptr_offset]: https://doc.rust-lang.org/std/primitive.pointer.html#method.offset
#[inline]
pub unsafe fn byte_offset(self, count: isize) -> Self {
Self(
// SAFETY: The caller upholds safety for `offset` and ensures the result is not null.
unsafe { NonNull::new_unchecked(self.as_ptr().offset(count)) },
PhantomData,
)
}
/// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
/// As the pointer is type-erased, there is no size information available. The provided
/// `count` parameter is in raw bytes.
///
/// *See also: [`ptr::add`][ptr_add]*
///
/// # Safety
/// - The offset cannot make the existing ptr null, or take it out of bounds for its allocation.
/// - If the `A` type parameter is [`Aligned`] then the offset must not make the resulting pointer
/// be unaligned for the pointee type.
/// - The value pointed by the resulting pointer must outlive the lifetime of this pointer.
///
/// [ptr_add]: https://doc.rust-lang.org/std/primitive.pointer.html#method.add
#[inline]
pub unsafe fn byte_add(self, count: usize) -> Self {
Self(
// SAFETY: The caller upholds safety for `add` and ensures the result is not null.
unsafe { NonNull::new_unchecked(self.as_ptr().add(count)) },
PhantomData,
)
}
}
impl<A: IsAligned> Pointer for $ptr<'_, A> {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
Pointer::fmt(&self.0, f)
}
}
impl Debug for $ptr<'_, Aligned> {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}<Aligned>({:?})", stringify!($ptr), self.0)
}
}
impl Debug for $ptr<'_, Unaligned> {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}<Unaligned>({:?})", stringify!($ptr), self.0)
}
}
};
}
impl_ptr!(Ptr);
impl_ptr!(PtrMut);
impl_ptr!(OwningPtr);
impl<'a, T> MovingPtr<'a, T, Aligned> {
/// Removes the alignment requirement of this pointer
#[inline]
pub fn to_unaligned(self) -> MovingPtr<'a, T, Unaligned> {
let value = MovingPtr(self.0, PhantomData);
mem::forget(self);
value
}
/// Creates a [`MovingPtr`] from a provided value of type `T`.
///
/// For a safer alternative, it is strongly advised to use [`move_as_ptr`] where possible.
///
/// # Safety
/// - `value` must store a properly initialized value of type `T`.
/// - Once the returned [`MovingPtr`] has been used, `value` must be treated as
/// it were uninitialized unless it was explicitly leaked via [`core::mem::forget`].
#[inline]
pub unsafe fn from_value(value: &'a mut MaybeUninit<T>) -> Self {
// SAFETY:
// - MaybeUninit<T> has the same memory layout as T
// - The caller guarantees that `value` must point to a valid instance of type `T`.
MovingPtr(NonNull::from(value).cast::<T>(), PhantomData)
}
}
impl<'a, T, A: IsAligned> MovingPtr<'a, T, A> {
/// Creates a new instance from a raw pointer.
///
/// For a safer alternative, it is strongly advised to use [`move_as_ptr`] where possible.
///
/// # Safety
/// - `inner` must point to valid value of `T`.
/// - If the `A` type parameter is [`Aligned`] then `inner` must be [properly aligned] for `T`.
/// - `inner` must have correct provenance to allow read and writes of the pointee type.
/// - The lifetime `'a` must be constrained such that this [`MovingPtr`] will stay valid and nothing
/// else can read or mutate the pointee while this [`MovingPtr`] is live.
///
/// [properly aligned]: https://doc.rust-lang.org/std/ptr/index.html#alignment
#[inline]
pub unsafe fn new(inner: NonNull<T>) -> Self {
Self(inner, PhantomData)
}
/// Partially moves out some fields inside of `self`.
///
/// The partially returned value is returned back pointing to [`MaybeUninit<T>`].
///
/// While calling this function is safe, care must be taken with the returned `MovingPtr` as it
/// points to a value that may no longer be completely valid.
///
/// # Example
///
/// ```
/// use core::mem::{offset_of, MaybeUninit, forget};
/// use bevy_ptr::{MovingPtr, move_as_ptr};
/// # struct FieldAType(usize);
/// # struct FieldBType(usize);
/// # struct FieldCType(usize);
/// # fn insert<T>(_ptr: MovingPtr<'_, T>) {}
///
/// struct Parent {
/// field_a: FieldAType,
/// field_b: FieldBType,
/// field_c: FieldCType,
/// }
///
/// # let parent = Parent {
/// # field_a: FieldAType(0),
/// # field_b: FieldBType(0),
/// # field_c: FieldCType(0),
/// # };
///
/// // Converts `parent` into a `MovingPtr`
/// move_as_ptr!(parent);
///
/// // SAFETY:
/// // - `field_a` and `field_b` are both unique.
/// let (partial_parent, ()) = MovingPtr::partial_move(parent, |parent_ptr| unsafe {
/// bevy_ptr::deconstruct_moving_ptr!({
/// let Parent { field_a, field_b, field_c } = parent_ptr;
/// });
///
/// insert(field_a);
/// insert(field_b);
/// forget(field_c);
/// });
///
/// // Move the rest of fields out of the parent.
/// // SAFETY:
/// // - `field_c` is by itself unique and does not conflict with the previous accesses
/// // inside `partial_move`.
/// unsafe {
/// bevy_ptr::deconstruct_moving_ptr!({
/// let MaybeUninit::<Parent> { field_a: _, field_b: _, field_c } = partial_parent;
/// });
///
/// insert(field_c);
/// }
/// ```
///
/// [`forget`]: core::mem::forget
#[inline]
pub fn partial_move<R>(
self,
f: impl FnOnce(MovingPtr<'_, T, A>) -> R,
) -> (MovingPtr<'a, MaybeUninit<T>, A>, R) {
let partial_ptr = self.0;
let ret = f(self);
(
MovingPtr(partial_ptr.cast::<MaybeUninit<T>>(), PhantomData),
ret,
)
}
/// Reads the value pointed to by this pointer.
#[inline]
pub fn read(self) -> T {
// SAFETY:
// - `self.0` must be valid for reads as this type owns the value it points to.
// - `self.0` must always point to a valid instance of type `T`
// - If `A` is [`Aligned`], then `ptr` must be properly aligned for type `T`.
let value = unsafe { A::read_ptr(self.0.as_ptr()) };
mem::forget(self);
value
}
/// Writes the value pointed to by this pointer to a provided location.
///
/// This does *not* drop the value stored at `dst` and it's the caller's responsibility
/// to ensure that it's properly dropped.
///
/// # Safety
/// - `dst` must be valid for writes.
/// - If the `A` type parameter is [`Aligned`] then `dst` must be [properly aligned] for `T`.
///
/// [properly aligned]: https://doc.rust-lang.org/std/ptr/index.html#alignment
#[inline]
pub unsafe fn write_to(self, dst: *mut T) {
let src = self.0.as_ptr();
mem::forget(self);
// SAFETY:
// - `src` must be valid for reads as this pointer is considered to own the value it points to.
// - The caller is required to ensure that `dst` must be valid for writes.
// - As `A` is `Aligned`, the caller is required to ensure that `dst` is aligned and `src` must
// be aligned by the type's invariants.
unsafe { A::copy_nonoverlapping(src, dst, 1) };
}
/// Writes the value pointed to by this pointer into `dst`.
///
/// The value previously stored at `dst` will be dropped.
#[inline]
pub fn assign_to(self, dst: &mut T) {
// SAFETY:
// - `dst` is a mutable borrow, it must point to a valid instance of `T`.
// - `dst` is a mutable borrow, it must point to value that is valid for dropping.
// - `dst` is a mutable borrow, it must not alias any other access.
unsafe {
ptr::drop_in_place(dst);
}
// SAFETY:
// - `dst` is a mutable borrow, it must be valid for writes.
// - `dst` is a mutable borrow, it must always be aligned.
unsafe {
self.write_to(dst);
}
}
/// Creates a [`MovingPtr`] for a specific field within `self`.
///
/// This function is explicitly made for deconstructive moves.
///
/// The correct `byte_offset` for a field can be obtained via [`core::mem::offset_of`].
///
/// # Safety
/// - `f` must return a non-null pointer to a valid field inside `T`
/// - If `A` is [`Aligned`], then `T` must not be `repr(packed)`
/// - `self` should not be accessed or dropped as if it were a complete value after this function returns.
/// Other fields that have not been moved out of may still be accessed or dropped separately.
/// - This function cannot alias the field with any other access, including other calls to [`move_field`]
/// for the same field, without first calling [`forget`] on it first.
///
/// A result of the above invariants means that any operation that could cause `self` to be dropped while
/// the pointers to the fields are held will result in undefined behavior. This requires extra caution
/// around code that may panic. See the example below for an example of how to safely use this function.
///
/// # Example
///
/// ```
/// use core::mem::offset_of;
/// use bevy_ptr::{MovingPtr, move_as_ptr};
/// # struct FieldAType(usize);
/// # struct FieldBType(usize);
/// # struct FieldCType(usize);
/// # fn insert<T>(_ptr: MovingPtr<'_, T>) {}
///
/// struct Parent {
/// field_a: FieldAType,
/// field_b: FieldBType,
/// field_c: FieldCType,
/// }
///
/// let parent = Parent {
/// field_a: FieldAType(0),
/// field_b: FieldBType(0),
/// field_c: FieldCType(0),
/// };
///
/// // Converts `parent` into a `MovingPtr`.
/// move_as_ptr!(parent);
///
/// unsafe {
/// let field_a = parent.move_field(|ptr| &raw mut (*ptr).field_a);
/// let field_b = parent.move_field(|ptr| &raw mut (*ptr).field_b);
/// let field_c = parent.move_field(|ptr| &raw mut (*ptr).field_c);
/// // Each call to insert may panic! Ensure that `parent_ptr` cannot be dropped before
/// // calling them!
/// core::mem::forget(parent);
/// insert(field_a);
/// insert(field_b);
/// insert(field_c);
/// }
/// ```
///
/// [`forget`]: core::mem::forget
/// [`move_field`]: Self::move_field
#[inline(always)]
pub unsafe fn move_field<U>(&self, f: impl Fn(*mut T) -> *mut U) -> MovingPtr<'a, U, A> {
MovingPtr(
// SAFETY: The caller must ensure that `U` is the correct type for the field at `byte_offset`.
unsafe { NonNull::new_unchecked(f(self.0.as_ptr())) },
PhantomData,
)
}
}
impl<'a, T, A: IsAligned> MovingPtr<'a, MaybeUninit<T>, A> {
/// Creates a [`MovingPtr`] for a specific field within `self`.
///
/// This function is explicitly made for deconstructive moves.
///
/// The correct `byte_offset` for a field can be obtained via [`core::mem::offset_of`].
///
/// # Safety
/// - `f` must return a non-null pointer to a valid field inside `T`
/// - If `A` is [`Aligned`], then `T` must not be `repr(packed)`
/// - `self` should not be accessed or dropped as if it were a complete value after this function returns.
/// Other fields that have not been moved out of may still be accessed or dropped separately.
/// - This function cannot alias the field with any other access, including other calls to [`move_field`]
/// for the same field, without first calling [`forget`] on it first.
///
/// [`forget`]: core::mem::forget
/// [`move_field`]: Self::move_field
#[inline(always)]
pub unsafe fn move_maybe_uninit_field<U>(
&self,
f: impl Fn(*mut T) -> *mut U,
) -> MovingPtr<'a, MaybeUninit<U>, A> {
let self_ptr = self.0.as_ptr().cast::<T>();
// SAFETY:
// - The caller must ensure that `U` is the correct type for the field at `byte_offset` and thus
// cannot be null.
// - `MaybeUninit<T>` is `repr(transparent)` and thus must have the same memory layout as `T``
let field_ptr = unsafe { NonNull::new_unchecked(f(self_ptr)) };
MovingPtr(field_ptr.cast::<MaybeUninit<U>>(), PhantomData)
}
}
impl<'a, T, A: IsAligned> MovingPtr<'a, MaybeUninit<T>, A> {
/// Creates a [`MovingPtr`] pointing to a valid instance of `T`.
///
/// See also: [`MaybeUninit::assume_init`].
///
/// # Safety
/// It's up to the caller to ensure that the value pointed to by `self`
/// is really in an initialized state. Calling this when the content is not yet
/// fully initialized causes immediate undefined behavior.
#[inline]
pub unsafe fn assume_init(self) -> MovingPtr<'a, T, A> {
let value = MovingPtr(self.0.cast::<T>(), PhantomData);
mem::forget(self);
value
}
}
impl<T, A: IsAligned> Pointer for MovingPtr<'_, T, A> {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
Pointer::fmt(&self.0, f)
}
}
impl<T> Debug for MovingPtr<'_, T, Aligned> {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "MovingPtr<Aligned>({:?})", self.0)
}
}
impl<T> Debug for MovingPtr<'_, T, Unaligned> {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "MovingPtr<Unaligned>({:?})", self.0)
}
}
impl<'a, T, A: IsAligned> From<MovingPtr<'a, T, A>> for OwningPtr<'a, A> {
#[inline]
fn from(value: MovingPtr<'a, T, A>) -> Self {
// SAFETY:
// - `value.0` must always point to valid value of type `T`.
// - The type parameter `A` is mirrored from input to output, keeping the same alignment guarantees.
// - `value.0` by construction must have correct provenance to allow read and writes of type `T`.
// - The lifetime `'a` is mirrored from input to output, keeping the same lifetime guarantees.
// - `OwningPtr` maintains the same aliasing invariants as `MovingPtr`.
let ptr = unsafe { OwningPtr::new(value.0.cast::<u8>()) };
mem::forget(value);
ptr
}
}
impl<'a, T> TryFrom<MovingPtr<'a, T, Unaligned>> for MovingPtr<'a, T, Aligned> {
type Error = MovingPtr<'a, T, Unaligned>;
#[inline]
fn try_from(value: MovingPtr<'a, T, Unaligned>) -> Result<Self, Self::Error> {
let ptr = value.0;
if ptr.as_ptr().is_aligned() {
mem::forget(value);
Ok(MovingPtr(ptr, PhantomData))
} else {
Err(value)
}
}
}
impl<T> Deref for MovingPtr<'_, T, Aligned> {
type Target = T;
#[inline]
fn deref(&self) -> &Self::Target {
let ptr = self.0.as_ptr().debug_ensure_aligned();
// SAFETY: This type owns the value it points to and the generic type parameter is `A` so this pointer must be aligned.
unsafe { &*ptr }
}
}
impl<T> DerefMut for MovingPtr<'_, T, Aligned> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
let ptr = self.0.as_ptr().debug_ensure_aligned();
// SAFETY: This type owns the value it points to and the generic type parameter is `A` so this pointer must be aligned.
unsafe { &mut *ptr }
}
}
impl<T, A: IsAligned> Drop for MovingPtr<'_, T, A> {
fn drop(&mut self) {
// SAFETY:
// - `self.0` must be valid for reads and writes as this pointer type owns the value it points to.
// - `self.0` must always point to a valid instance of type `T`
// - If `A` is `Aligned`, then `ptr` must be properly aligned for type `T` by construction.
// - `self.0` owns the value it points to so it must always be valid for dropping until this pointer is dropped.
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_state/macros/src/lib.rs | crates/bevy_state/macros/src/lib.rs | #![cfg_attr(docsrs, feature(doc_cfg))]
//! Macros for deriving `States` and `SubStates` traits.
extern crate proc_macro;
mod states;
use bevy_macro_utils::BevyManifest;
use proc_macro::TokenStream;
/// Implements the `States` trait for a type - see the trait
/// docs for an example usage.
#[proc_macro_derive(States, attributes(states))]
pub fn derive_states(input: TokenStream) -> TokenStream {
states::derive_states(input)
}
/// Implements the `SubStates` trait for a type - see the trait
/// docs for an example usage.
#[proc_macro_derive(SubStates, attributes(states, source))]
pub fn derive_substates(input: TokenStream) -> TokenStream {
states::derive_substates(input)
}
pub(crate) fn bevy_state_path() -> syn::Path {
BevyManifest::shared(|manifest| manifest.get_path("bevy_state"))
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_state/macros/src/states.rs | crates/bevy_state/macros/src/states.rs | use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{parse_macro_input, spanned::Spanned, DeriveInput, Pat, Path, Result};
use crate::bevy_state_path;
pub fn derive_states(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
let generics = ast.generics;
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
let mut base_trait_path = bevy_state_path();
base_trait_path.segments.push(format_ident!("state").into());
let mut trait_path = base_trait_path.clone();
trait_path.segments.push(format_ident!("States").into());
let mut state_mutation_trait_path = base_trait_path.clone();
state_mutation_trait_path
.segments
.push(format_ident!("FreelyMutableState").into());
let struct_name = &ast.ident;
quote! {
impl #impl_generics #trait_path for #struct_name #ty_generics #where_clause {
}
impl #impl_generics #state_mutation_trait_path for #struct_name #ty_generics #where_clause {
}
}
.into()
}
struct Source {
source_type: Path,
source_value: Pat,
}
fn parse_sources_attr(ast: &DeriveInput) -> Result<Source> {
let mut result = ast
.attrs
.iter()
.filter(|a| a.path().is_ident("source"))
.map(|meta| {
let mut source = None;
let value = meta.parse_nested_meta(|nested| {
let source_type = nested.path.clone();
let source_value = Pat::parse_multi(nested.value()?)?;
source = Some(Source {
source_type,
source_value,
});
Ok(())
});
match source {
Some(value) => Ok(value),
None => match value {
Ok(_) => Err(syn::Error::new(
ast.span(),
"Couldn't parse SubStates source",
)),
Err(e) => Err(e),
},
}
})
.collect::<Result<Vec<_>>>()?;
if result.len() > 1 {
return Err(syn::Error::new(
ast.span(),
"Only one source is allowed for SubStates",
));
}
let Some(result) = result.pop() else {
return Err(syn::Error::new(ast.span(), "SubStates require a source"));
};
Ok(result)
}
pub fn derive_substates(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
let sources = parse_sources_attr(&ast).expect("Failed to parse substate sources");
let generics = ast.generics;
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
let mut base_trait_path = bevy_state_path();
base_trait_path.segments.push(format_ident!("state").into());
let mut trait_path = base_trait_path.clone();
trait_path.segments.push(format_ident!("SubStates").into());
let mut state_set_trait_path = base_trait_path.clone();
state_set_trait_path
.segments
.push(format_ident!("StateSet").into());
let mut state_trait_path = base_trait_path.clone();
state_trait_path
.segments
.push(format_ident!("States").into());
let mut state_mutation_trait_path = base_trait_path.clone();
state_mutation_trait_path
.segments
.push(format_ident!("FreelyMutableState").into());
let struct_name = &ast.ident;
let source_state_type = sources.source_type;
let source_state_value = sources.source_value;
let result = quote! {
impl #impl_generics #trait_path for #struct_name #ty_generics #where_clause {
type SourceStates = #source_state_type;
fn should_exist(sources: #source_state_type) -> Option<Self> {
matches!(sources, #source_state_value).then_some(Self::default())
}
}
impl #impl_generics #state_trait_path for #struct_name #ty_generics #where_clause {
const DEPENDENCY_DEPTH : usize = <Self as #trait_path>::SourceStates::SET_DEPENDENCY_DEPTH + 1;
}
impl #impl_generics #state_mutation_trait_path for #struct_name #ty_generics #where_clause {
}
};
// panic!("Got Result\n{}", result.to_string());
result.into()
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_state/src/app.rs | crates/bevy_state/src/app.rs | use bevy_app::{App, MainScheduleOrder, Plugin, PreStartup, PreUpdate, SubApp};
use bevy_ecs::{message::Messages, schedule::IntoScheduleConfigs, world::FromWorld};
use bevy_utils::once;
use log::warn;
use crate::{
state::{
setup_state_transitions_in_world, ComputedStates, FreelyMutableState, NextState,
PreviousState, State, StateTransition, StateTransitionEvent, StateTransitionSystems,
States, SubStates,
},
state_scoped::{despawn_entities_on_enter_state, despawn_entities_on_exit_state},
};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::{FromReflect, GetTypeRegistration, Typed};
/// State installation methods for [`App`] and [`SubApp`].
pub trait AppExtStates {
/// Initializes a [`State`] with standard starting values.
///
/// This method is idempotent: it has no effect when called again using the same generic type.
///
/// Adds [`State<S>`] and [`NextState<S>`] resources, and enables use of the [`OnEnter`](crate::state::OnEnter),
/// [`OnTransition`](crate::state::OnTransition) and [`OnExit`](crate::state::OnExit) schedules.
/// These schedules are triggered before [`Update`](bevy_app::Update) and at startup.
///
/// If you would like to control how other systems run based on the current state, you can
/// emulate this behavior using the [`in_state`](crate::condition::in_state) [`SystemCondition`](bevy_ecs::prelude::SystemCondition).
///
/// Note that you can also apply state transitions at other points in the schedule
/// by triggering the [`StateTransition`](struct@StateTransition) schedule manually.
///
/// The use of any states requires the presence of [`StatesPlugin`] (which is included in `DefaultPlugins`).
fn init_state<S: FreelyMutableState + FromWorld>(&mut self) -> &mut Self;
/// Inserts a specific [`State`] to the current [`App`] and overrides any [`State`] previously
/// added of the same type.
///
/// Adds [`State<S>`] and [`NextState<S>`] resources, and enables use of the [`OnEnter`](crate::state::OnEnter),
/// [`OnTransition`](crate::state::OnTransition) and [`OnExit`](crate::state::OnExit) schedules.
/// These schedules are triggered before [`Update`](bevy_app::Update) and at startup.
///
/// If you would like to control how other systems run based on the current state, you can
/// emulate this behavior using the [`in_state`](crate::condition::in_state) [`SystemCondition`](bevy_ecs::prelude::SystemCondition).
///
/// Note that you can also apply state transitions at other points in the schedule
/// by triggering the [`StateTransition`](struct@StateTransition) schedule manually.
fn insert_state<S: FreelyMutableState>(&mut self, state: S) -> &mut Self;
/// Sets up a type implementing [`ComputedStates`].
///
/// This method is idempotent: it has no effect when called again using the same generic type.
fn add_computed_state<S: ComputedStates>(&mut self) -> &mut Self;
/// Sets up a type implementing [`SubStates`].
///
/// This method is idempotent: it has no effect when called again using the same generic type.
fn add_sub_state<S: SubStates>(&mut self) -> &mut Self;
#[cfg(feature = "bevy_reflect")]
/// Registers the state type `T` using [`App::register_type`],
/// and adds [`ReflectState`](crate::reflect::ReflectState) type data to `T` in the type registry.
///
/// This enables reflection code to access the state. For detailed information, see the docs on [`crate::reflect::ReflectState`] .
fn register_type_state<S>(&mut self) -> &mut Self
where
S: States + FromReflect + GetTypeRegistration + Typed;
#[cfg(feature = "bevy_reflect")]
/// Registers the state type `T` using [`App::register_type`],
/// and adds [`crate::reflect::ReflectState`] and [`crate::reflect::ReflectFreelyMutableState`] type data to `T` in the type registry.
///
/// This enables reflection code to access and modify the state.
/// For detailed information, see the docs on [`crate::reflect::ReflectState`] and [`crate::reflect::ReflectFreelyMutableState`].
fn register_type_mutable_state<S>(&mut self) -> &mut Self
where
S: FreelyMutableState + FromReflect + GetTypeRegistration + Typed;
}
/// Separate function to only warn once for all state installation methods.
fn warn_if_no_states_plugin_installed(app: &SubApp) {
if !app.is_plugin_added::<StatesPlugin>() {
once!(warn!(
"States were added to the app, but `StatesPlugin` is not installed."
));
}
}
impl AppExtStates for SubApp {
fn init_state<S: FreelyMutableState + FromWorld>(&mut self) -> &mut Self {
warn_if_no_states_plugin_installed(self);
if !self.world().contains_resource::<State<S>>() {
self.init_resource::<State<S>>()
.init_resource::<NextState<S>>()
.add_message::<StateTransitionEvent<S>>();
let schedule = self.get_schedule_mut(StateTransition).expect(
"The `StateTransition` schedule is missing. Did you forget to add StatesPlugin or DefaultPlugins before calling init_state?"
);
S::register_state(schedule);
let state = self.world().resource::<State<S>>().get().clone();
self.world_mut().write_message(StateTransitionEvent {
exited: None,
entered: Some(state),
// makes no difference: the state didn't exist before anyways
allow_same_state_transitions: true,
});
enable_state_scoped_entities::<S>(self);
} else {
let name = core::any::type_name::<S>();
warn!("State {name} is already initialized.");
}
self
}
fn insert_state<S: FreelyMutableState>(&mut self, state: S) -> &mut Self {
warn_if_no_states_plugin_installed(self);
if !self.world().contains_resource::<State<S>>() {
self.insert_resource::<State<S>>(State::new(state.clone()))
.init_resource::<NextState<S>>()
.add_message::<StateTransitionEvent<S>>();
let schedule = self.get_schedule_mut(StateTransition).expect(
"The `StateTransition` schedule is missing. Did you forget to add StatesPlugin or DefaultPlugins before calling insert_state?"
);
S::register_state(schedule);
self.world_mut().write_message(StateTransitionEvent {
exited: None,
entered: Some(state),
// makes no difference: the state didn't exist before anyways
allow_same_state_transitions: true,
});
enable_state_scoped_entities::<S>(self);
} else {
// Overwrite previous state and initial event
self.insert_resource::<State<S>>(State::new(state.clone()));
self.world_mut()
.resource_mut::<Messages<StateTransitionEvent<S>>>()
.clear();
self.world_mut().write_message(StateTransitionEvent {
exited: None,
entered: Some(state),
// Not configurable for the moment. This controls whether inserting a state with the same value as a pre-existing state should run state transitions.
// Leaving it at `true` makes state insertion idempotent. Neat!
allow_same_state_transitions: true,
});
}
self
}
fn add_computed_state<S: ComputedStates>(&mut self) -> &mut Self {
warn_if_no_states_plugin_installed(self);
if !self
.world()
.contains_resource::<Messages<StateTransitionEvent<S>>>()
{
self.add_message::<StateTransitionEvent<S>>();
let schedule = self.get_schedule_mut(StateTransition).expect(
"The `StateTransition` schedule is missing. Did you forget to add StatesPlugin or DefaultPlugins before calling add_computed_state?"
);
S::register_computed_state_systems(schedule);
let state = self
.world()
.get_resource::<State<S>>()
.map(|s| s.get().clone());
self.world_mut().write_message(StateTransitionEvent {
exited: None,
entered: state,
allow_same_state_transitions: S::ALLOW_SAME_STATE_TRANSITIONS,
});
enable_state_scoped_entities::<S>(self);
} else {
let name = core::any::type_name::<S>();
warn!("Computed state {name} is already initialized.");
}
self
}
fn add_sub_state<S: SubStates>(&mut self) -> &mut Self {
warn_if_no_states_plugin_installed(self);
if !self
.world()
.contains_resource::<Messages<StateTransitionEvent<S>>>()
{
self.init_resource::<NextState<S>>();
self.add_message::<StateTransitionEvent<S>>();
let schedule = self.get_schedule_mut(StateTransition).expect(
"The `StateTransition` schedule is missing. Did you forget to add StatesPlugin or DefaultPlugins before calling add_sub_state?"
);
S::register_sub_state_systems(schedule);
let state = self
.world()
.get_resource::<State<S>>()
.map(|s| s.get().clone());
self.world_mut().write_message(StateTransitionEvent {
exited: None,
entered: state,
// makes no difference: the state didn't exist before anyways
allow_same_state_transitions: true,
});
enable_state_scoped_entities::<S>(self);
} else {
let name = core::any::type_name::<S>();
warn!("Sub state {name} is already initialized.");
}
self
}
#[cfg(feature = "bevy_reflect")]
fn register_type_state<S>(&mut self) -> &mut Self
where
S: States + FromReflect + GetTypeRegistration + Typed,
{
self.register_type::<S>();
self.register_type::<State<S>>();
self.register_type::<PreviousState<S>>();
self.register_type_data::<S, crate::reflect::ReflectState>();
self
}
#[cfg(feature = "bevy_reflect")]
fn register_type_mutable_state<S>(&mut self) -> &mut Self
where
S: FreelyMutableState + FromReflect + GetTypeRegistration + Typed,
{
self.register_type::<S>();
self.register_type::<State<S>>();
self.register_type::<NextState<S>>();
self.register_type::<PreviousState<S>>();
self.register_type_data::<S, crate::reflect::ReflectState>();
self.register_type_data::<S, crate::reflect::ReflectFreelyMutableState>();
self
}
}
fn enable_state_scoped_entities<S: States>(app: &mut SubApp) {
if !app
.world()
.contains_resource::<Messages<StateTransitionEvent<S>>>()
{
let name = core::any::type_name::<S>();
warn!("State scoped entities are enabled for state `{name}`, but the state wasn't initialized in the app!");
}
// Note: We work with `StateTransition` in set
// `StateTransitionSystems::ExitSchedules` rather than `OnExit`, because
// `OnExit` only runs for one specific variant of the state.
app.add_systems(
StateTransition,
despawn_entities_on_exit_state::<S>.in_set(StateTransitionSystems::ExitSchedules),
)
// Note: We work with `StateTransition` in set
// `StateTransitionSystems::EnterSchedules` rather than `OnEnter`, because
// `OnEnter` only runs for one specific variant of the state.
.add_systems(
StateTransition,
despawn_entities_on_enter_state::<S>.in_set(StateTransitionSystems::EnterSchedules),
);
}
impl AppExtStates for App {
fn init_state<S: FreelyMutableState + FromWorld>(&mut self) -> &mut Self {
self.main_mut().init_state::<S>();
self
}
fn insert_state<S: FreelyMutableState>(&mut self, state: S) -> &mut Self {
self.main_mut().insert_state::<S>(state);
self
}
fn add_computed_state<S: ComputedStates>(&mut self) -> &mut Self {
self.main_mut().add_computed_state::<S>();
self
}
fn add_sub_state<S: SubStates>(&mut self) -> &mut Self {
self.main_mut().add_sub_state::<S>();
self
}
#[cfg(feature = "bevy_reflect")]
fn register_type_state<S>(&mut self) -> &mut Self
where
S: States + FromReflect + GetTypeRegistration + Typed,
{
self.main_mut().register_type_state::<S>();
self
}
#[cfg(feature = "bevy_reflect")]
fn register_type_mutable_state<S>(&mut self) -> &mut Self
where
S: FreelyMutableState + FromReflect + GetTypeRegistration + Typed,
{
self.main_mut().register_type_mutable_state::<S>();
self
}
}
/// Registers the [`StateTransition`] schedule in the [`MainScheduleOrder`] to enable state processing.
#[derive(Default)]
pub struct StatesPlugin;
impl Plugin for StatesPlugin {
fn build(&self, app: &mut App) {
let mut schedule = app.world_mut().resource_mut::<MainScheduleOrder>();
schedule.insert_after(PreUpdate, StateTransition);
schedule.insert_startup_before(PreStartup, StateTransition);
setup_state_transitions_in_world(app.world_mut());
}
}
#[cfg(test)]
mod tests {
use crate::{
app::StatesPlugin,
state::{State, StateTransition, StateTransitionEvent},
};
use bevy_app::App;
use bevy_ecs::message::Messages;
use bevy_state_macros::States;
use super::AppExtStates;
#[derive(States, Default, PartialEq, Eq, Hash, Debug, Clone)]
enum TestState {
#[default]
A,
B,
C,
}
#[test]
fn insert_state_can_overwrite_init_state() {
let mut app = App::new();
app.add_plugins(StatesPlugin);
app.init_state::<TestState>();
app.insert_state(TestState::B);
let world = app.world_mut();
world.run_schedule(StateTransition);
assert_eq!(world.resource::<State<TestState>>().0, TestState::B);
let events = world.resource::<Messages<StateTransitionEvent<TestState>>>();
assert_eq!(events.len(), 1);
let mut reader = events.get_cursor();
let last = reader.read(events).last().unwrap();
assert_eq!(last.exited, None);
assert_eq!(last.entered, Some(TestState::B));
}
#[test]
fn insert_state_can_overwrite_insert_state() {
let mut app = App::new();
app.add_plugins(StatesPlugin);
app.insert_state(TestState::B);
app.insert_state(TestState::C);
let world = app.world_mut();
world.run_schedule(StateTransition);
assert_eq!(world.resource::<State<TestState>>().0, TestState::C);
let events = world.resource::<Messages<StateTransitionEvent<TestState>>>();
assert_eq!(events.len(), 1);
let mut reader = events.get_cursor();
let last = reader.read(events).last().unwrap();
assert_eq!(last.exited, None);
assert_eq!(last.entered, Some(TestState::C));
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_state/src/lib.rs | crates/bevy_state/src/lib.rs | #![no_std]
//! In Bevy, states are app-wide interdependent, finite state machines that are generally used to model the large scale structure of your program: whether a game is paused, if the player is in combat, if assets are loaded and so on.
//!
//! This module provides 3 distinct types of state, all of which implement the [`States`](state::States) trait:
//!
//! - Standard [`States`](state::States) can only be changed by manually setting the [`NextState<S>`](state::NextState) resource.
//! These states are the baseline on which the other state types are built, and can be used on
//! their own for many simple patterns. See the [states example](https://github.com/bevyengine/bevy/blob/latest/examples/state/states.rs)
//! for a simple use case.
//! - [`SubStates`](state::SubStates) are children of other states - they can be changed manually using [`NextState<S>`](state::NextState),
//! but are removed from the [`World`](bevy_ecs::prelude::World) if the source states aren't in the right state. See the [sub_states example](https://github.com/bevyengine/bevy/blob/latest/examples/state/sub_states.rs)
//! for a simple use case based on the derive macro, or read the trait docs for more complex scenarios.
//! - [`ComputedStates`](state::ComputedStates) are fully derived from other states - they provide a [`compute`](state::ComputedStates::compute) method
//! that takes in the source states and returns their derived value. They are particularly useful for situations
//! where a simplified view of the source states is necessary - such as having an `InAMenu` computed state, derived
//! from a source state that defines multiple distinct menus. See the [computed state example](https://github.com/bevyengine/bevy/blob/latest/examples/state/computed_states.rs)
//! to see usage samples for these states.
//!
//! Most of the utilities around state involve running systems during transitions between states, or
//! determining whether to run certain systems, though they can be used more directly as well. This
//! makes it easier to transition between menus, add loading screens, pause games, and more.
//!
//! Specifically, Bevy provides the following utilities:
//!
//! - 3 Transition Schedules - [`OnEnter<S>`](crate::state::OnEnter), [`OnExit<S>`](crate::state::OnExit) and [`OnTransition<S>`](crate::state::OnTransition) - which are used
//! to trigger systems specifically during matching transitions.
//! - A [`StateTransitionEvent<S>`](crate::state::StateTransitionEvent) that gets fired when a given state changes.
//! - The [`in_state<S>`](crate::condition::in_state) and [`state_changed<S>`](crate::condition::state_changed) run conditions - which are used
//! to determine whether a system should run based on the current state.
//!
//! Bevy also provides functionality for managing the lifetime of entities in the context of game states, using the [`state_scoped`] module.
//! Specifically, the marker components [`DespawnOnEnter<S>`](crate::state_scoped::DespawnOnEnter) and [`DespawnOnExit<S>`](crate::state_scoped::DespawnOnExit) are provided for despawning entities on state transition.
//! This, especially in combination with system scheduling, enables a flexible and expressive way to manage spawning and despawning entities.
#![cfg_attr(
any(docsrs, docsrs_dep),
expect(
internal_features,
reason = "rustdoc_internals is needed for fake_variadic"
)
)]
#![cfg_attr(any(docsrs, docsrs_dep), feature(rustdoc_internals))]
#[cfg(feature = "std")]
extern crate std;
extern crate alloc;
// Required to make proc macros work in bevy itself.
extern crate self as bevy_state;
#[cfg(feature = "bevy_app")]
/// Provides [`App`](bevy_app::App) and [`SubApp`](bevy_app::SubApp) with state installation methods
pub mod app;
/// Provides extension methods for [`Commands`](bevy_ecs::prelude::Commands).
pub mod commands;
/// Provides definitions for the runtime conditions that interact with the state system
pub mod condition;
/// Provides definitions for the basic traits required by the state system
pub mod state;
/// Provides tools for managing the lifetime of entities based on state transitions.
pub mod state_scoped;
#[cfg(feature = "bevy_app")]
/// Provides [`App`](bevy_app::App) and [`SubApp`](bevy_app::SubApp) with methods for registering
/// state-scoped events.
pub mod state_scoped_events;
#[cfg(feature = "bevy_reflect")]
/// Provides definitions for the basic traits required by the state system
pub mod reflect;
/// The state prelude.
///
/// This includes the most common types in this crate, re-exported for your convenience.
pub mod prelude {
#[cfg(feature = "bevy_app")]
#[doc(hidden)]
pub use crate::{app::AppExtStates, state_scoped_events::StateScopedMessagesAppExt};
#[cfg(feature = "bevy_reflect")]
#[doc(hidden)]
pub use crate::reflect::{ReflectFreelyMutableState, ReflectState};
#[doc(hidden)]
pub use crate::{
commands::CommandsStatesExt,
condition::*,
state::{
last_transition, ComputedStates, EnterSchedules, ExitSchedules, NextState, OnEnter,
OnExit, OnTransition, PreviousState, State, StateSet, StateTransition,
StateTransitionEvent, States, SubStates, TransitionSchedules,
},
state_scoped::{DespawnOnEnter, DespawnOnExit},
};
}
#[cfg(test)]
mod tests {
use bevy_app::{App, PreStartup};
use bevy_ecs::{
resource::Resource,
system::{Commands, ResMut},
};
use bevy_state_macros::States;
use crate::{
app::{AppExtStates, StatesPlugin},
state::OnEnter,
};
#[test]
fn state_transition_runs_before_pre_startup() {
// This test is not really a "requirement" of states (we could run state transitions after
// PreStartup), but this is the current policy and it is useful to ensure we are following
// it if we ever change how we initialize stuff.
let mut app = App::new();
app.add_plugins(StatesPlugin);
#[derive(States, Default, PartialEq, Eq, Hash, Debug, Clone)]
enum TestState {
#[default]
A,
#[expect(
dead_code,
reason = "This struct is used as a compilation test to test the derive macros, and as such is intentionally never constructed."
)]
B,
}
#[derive(Resource, Default, PartialEq, Eq, Debug)]
struct Thingy(usize);
app.init_state::<TestState>();
app.add_systems(OnEnter(TestState::A), move |mut commands: Commands| {
commands.init_resource::<Thingy>();
});
app.add_systems(PreStartup, move |mut thingy: ResMut<Thingy>| {
// This system will fail if it runs before OnEnter.
thingy.0 += 1;
});
app.update();
// This assert only succeeds if first OnEnter(TestState::A) runs, followed by PreStartup.
assert_eq!(app.world().resource::<Thingy>(), &Thingy(1));
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_state/src/reflect.rs | crates/bevy_state/src/reflect.rs | use crate::state::{FreelyMutableState, NextState, State, States};
use bevy_ecs::{reflect::from_reflect_with_fallback, world::World};
use bevy_reflect::{FromType, Reflect, TypePath, TypeRegistry};
/// A struct used to operate on the reflected [`States`] trait of a type.
///
/// A [`ReflectState`] for type `T` can be obtained via
/// [`bevy_reflect::TypeRegistration::data`].
#[derive(Clone)]
pub struct ReflectState(ReflectStateFns);
/// The raw function pointers needed to make up a [`ReflectState`].
#[derive(Clone)]
pub struct ReflectStateFns {
/// Function pointer implementing [`ReflectState::reflect()`].
pub reflect: fn(&World) -> Option<&dyn Reflect>,
}
impl ReflectStateFns {
/// Get the default set of [`ReflectStateFns`] for a specific component type using its
/// [`FromType`] implementation.
///
/// This is useful if you want to start with the default implementation before overriding some
/// of the functions to create a custom implementation.
pub fn new<T: States + Reflect>() -> Self {
<ReflectState as FromType<T>>::from_type().0
}
}
impl ReflectState {
/// Gets the value of this [`States`] type from the world as a reflected reference.
pub fn reflect<'a>(&self, world: &'a World) -> Option<&'a dyn Reflect> {
(self.0.reflect)(world)
}
}
impl<S: States + Reflect> FromType<S> for ReflectState {
fn from_type() -> Self {
ReflectState(ReflectStateFns {
reflect: |world| {
world
.get_resource::<State<S>>()
.map(|res| res.get() as &dyn Reflect)
},
})
}
}
/// A struct used to operate on the reflected [`FreelyMutableState`] trait of a type.
///
/// A [`ReflectFreelyMutableState`] for type `T` can be obtained via
/// [`bevy_reflect::TypeRegistration::data`].
#[derive(Clone)]
pub struct ReflectFreelyMutableState(ReflectFreelyMutableStateFns);
/// The raw function pointers needed to make up a [`ReflectFreelyMutableState`].
#[derive(Clone)]
pub struct ReflectFreelyMutableStateFns {
/// Function pointer implementing [`ReflectFreelyMutableState::set_next_state()`].
pub set_next_state: fn(&mut World, &dyn Reflect, &TypeRegistry),
/// Function pointer implementing [`ReflectFreelyMutableState::set_next_state_if_neq()`].
pub set_next_state_if_neq: fn(&mut World, &dyn Reflect, &TypeRegistry),
}
impl ReflectFreelyMutableStateFns {
/// Get the default set of [`ReflectFreelyMutableStateFns`] for a specific component type using its
/// [`FromType`] implementation.
///
/// This is useful if you want to start with the default implementation before overriding some
/// of the functions to create a custom implementation.
pub fn new<T: FreelyMutableState + Reflect + TypePath>() -> Self {
<ReflectFreelyMutableState as FromType<T>>::from_type().0
}
}
impl ReflectFreelyMutableState {
/// Tentatively set a pending state transition to a reflected [`ReflectFreelyMutableState`].
pub fn set_next_state(&self, world: &mut World, state: &dyn Reflect, registry: &TypeRegistry) {
(self.0.set_next_state)(world, state, registry);
}
/// Tentatively set a pending state transition to a reflected [`ReflectFreelyMutableState`], skipping state transitions if the target state is the same as the current state.
pub fn set_next_state_if_neq(
&self,
world: &mut World,
state: &dyn Reflect,
registry: &TypeRegistry,
) {
(self.0.set_next_state_if_neq)(world, state, registry);
}
}
impl<S: FreelyMutableState + Reflect + TypePath> FromType<S> for ReflectFreelyMutableState {
fn from_type() -> Self {
ReflectFreelyMutableState(ReflectFreelyMutableStateFns {
set_next_state: |world, reflected_state, registry| {
let new_state: S = from_reflect_with_fallback(
reflected_state.as_partial_reflect(),
world,
registry,
);
if let Some(mut next_state) = world.get_resource_mut::<NextState<S>>() {
next_state.set(new_state);
}
},
set_next_state_if_neq: |world, reflected_state, registry| {
let new_state: S = from_reflect_with_fallback(
reflected_state.as_partial_reflect(),
world,
registry,
);
if let Some(mut next_state) = world.get_resource_mut::<NextState<S>>() {
next_state.set_if_neq(new_state);
}
},
})
}
}
#[cfg(test)]
mod tests {
use crate::{
app::{AppExtStates, StatesPlugin},
reflect::{ReflectFreelyMutableState, ReflectState},
state::State,
};
use bevy_app::App;
use bevy_ecs::prelude::AppTypeRegistry;
use bevy_reflect::Reflect;
use bevy_state_macros::States;
use core::any::TypeId;
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, States, Reflect)]
enum StateTest {
A,
B,
}
#[test]
fn test_reflect_state_operations() {
let mut app = App::new();
app.add_plugins(StatesPlugin)
.insert_state(StateTest::A)
.register_type_mutable_state::<StateTest>();
let type_registry = app.world_mut().resource::<AppTypeRegistry>().0.clone();
let type_registry = type_registry.read();
let (reflect_state, reflect_mutable_state) = (
type_registry
.get_type_data::<ReflectState>(TypeId::of::<StateTest>())
.unwrap()
.clone(),
type_registry
.get_type_data::<ReflectFreelyMutableState>(TypeId::of::<StateTest>())
.unwrap()
.clone(),
);
let current_value = reflect_state.reflect(app.world()).unwrap();
assert_eq!(
current_value.downcast_ref::<StateTest>().unwrap(),
&StateTest::A
);
reflect_mutable_state.set_next_state(app.world_mut(), &StateTest::B, &type_registry);
assert_ne!(
app.world().resource::<State<StateTest>>().get(),
&StateTest::B
);
app.update();
assert_eq!(
app.world().resource::<State<StateTest>>().get(),
&StateTest::B
);
let current_value = reflect_state.reflect(app.world()).unwrap();
assert_eq!(
current_value.downcast_ref::<StateTest>().unwrap(),
&StateTest::B
);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_state/src/state_scoped_events.rs | crates/bevy_state/src/state_scoped_events.rs | use alloc::vec::Vec;
use core::marker::PhantomData;
use bevy_app::{App, SubApp};
use bevy_ecs::{
message::{Message, MessageReader, Messages},
resource::Resource,
system::Commands,
world::World,
};
use bevy_platform::collections::HashMap;
use crate::state::{OnEnter, OnExit, StateTransitionEvent, States};
fn clear_message_queue<M: Message>(w: &mut World) {
if let Some(mut queue) = w.get_resource_mut::<Messages<M>>() {
queue.clear();
}
}
#[derive(Copy, Clone)]
enum TransitionType {
OnExit,
OnEnter,
}
#[derive(Resource)]
struct StateScopedMessages<S: States> {
/// Keeps track of which messages need to be reset when the state is exited.
on_exit: HashMap<S, Vec<fn(&mut World)>>,
/// Keeps track of which messages need to be reset when the state is entered.
on_enter: HashMap<S, Vec<fn(&mut World)>>,
}
impl<S: States> StateScopedMessages<S> {
fn add_message<M: Message>(&mut self, state: S, transition_type: TransitionType) {
let map = match transition_type {
TransitionType::OnExit => &mut self.on_exit,
TransitionType::OnEnter => &mut self.on_enter,
};
map.entry(state).or_default().push(clear_message_queue::<M>);
}
fn cleanup(&self, w: &mut World, state: S, transition_type: TransitionType) {
let map = match transition_type {
TransitionType::OnExit => &self.on_exit,
TransitionType::OnEnter => &self.on_enter,
};
let Some(fns) = map.get(&state) else {
return;
};
for callback in fns {
(*callback)(w);
}
}
}
impl<S: States> Default for StateScopedMessages<S> {
fn default() -> Self {
Self {
on_exit: HashMap::default(),
on_enter: HashMap::default(),
}
}
}
fn clear_messages_on_exit<S: States>(
mut c: Commands,
mut transitions: MessageReader<StateTransitionEvent<S>>,
) {
let Some(transition) = transitions.read().last() else {
return;
};
if transition.entered == transition.exited {
return;
}
let Some(exited) = transition.exited.clone() else {
return;
};
c.queue(move |w: &mut World| {
w.resource_scope::<StateScopedMessages<S>, ()>(|w, messages| {
messages.cleanup(w, exited, TransitionType::OnExit);
});
});
}
fn clear_messages_on_enter<S: States>(
mut c: Commands,
mut transitions: MessageReader<StateTransitionEvent<S>>,
) {
let Some(transition) = transitions.read().last() else {
return;
};
if transition.entered == transition.exited {
return;
}
let Some(entered) = transition.entered.clone() else {
return;
};
c.queue(move |w: &mut World| {
w.resource_scope::<StateScopedMessages<S>, ()>(|w, messages| {
messages.cleanup(w, entered, TransitionType::OnEnter);
});
});
}
fn clear_messages_on_state_transition<M: Message, S: States>(
app: &mut SubApp,
_p: PhantomData<M>,
state: S,
transition_type: TransitionType,
) {
if !app.world().contains_resource::<StateScopedMessages<S>>() {
app.init_resource::<StateScopedMessages<S>>();
}
app.world_mut()
.resource_mut::<StateScopedMessages<S>>()
.add_message::<M>(state.clone(), transition_type);
match transition_type {
TransitionType::OnExit => app.add_systems(OnExit(state), clear_messages_on_exit::<S>),
TransitionType::OnEnter => app.add_systems(OnEnter(state), clear_messages_on_enter::<S>),
};
}
/// Extension trait for [`App`] adding methods for registering state scoped messages.
pub trait StateScopedMessagesAppExt {
/// Clears a [`Message`] when exiting the specified `state`.
///
/// Note that message cleanup is ambiguously ordered relative to
/// [`DespawnOnExit`](crate::prelude::DespawnOnExit) entity cleanup,
/// and the [`OnExit`] schedule for the target state.
/// All of these (state scoped entities and messages cleanup, and `OnExit`)
/// occur within schedule [`StateTransition`](crate::prelude::StateTransition)
/// and system set `StateTransitionSystems::ExitSchedules`.
fn clear_messages_on_exit<M: Message>(&mut self, state: impl States) -> &mut Self;
/// Clears a [`Message`] when entering the specified `state`.
///
/// Note that message cleanup is ambiguously ordered relative to
/// [`DespawnOnEnter`](crate::prelude::DespawnOnEnter) entity cleanup,
/// and the [`OnEnter`] schedule for the target state.
/// All of these (state scoped entities and messages cleanup, and `OnEnter`)
/// occur within schedule [`StateTransition`](crate::prelude::StateTransition)
/// and system set `StateTransitionSystems::EnterSchedules`.
fn clear_messages_on_enter<M: Message>(&mut self, state: impl States) -> &mut Self;
}
impl StateScopedMessagesAppExt for App {
fn clear_messages_on_exit<M: Message>(&mut self, state: impl States) -> &mut Self {
clear_messages_on_state_transition(
self.main_mut(),
PhantomData::<M>,
state,
TransitionType::OnExit,
);
self
}
fn clear_messages_on_enter<M: Message>(&mut self, state: impl States) -> &mut Self {
clear_messages_on_state_transition(
self.main_mut(),
PhantomData::<M>,
state,
TransitionType::OnEnter,
);
self
}
}
impl StateScopedMessagesAppExt for SubApp {
fn clear_messages_on_exit<M: Message>(&mut self, state: impl States) -> &mut Self {
clear_messages_on_state_transition(self, PhantomData::<M>, state, TransitionType::OnExit);
self
}
fn clear_messages_on_enter<M: Message>(&mut self, state: impl States) -> &mut Self {
clear_messages_on_state_transition(self, PhantomData::<M>, state, TransitionType::OnEnter);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::app::StatesPlugin;
use bevy_ecs::message::Message;
use bevy_state::prelude::*;
#[derive(States, Default, Clone, Hash, Eq, PartialEq, Debug)]
enum TestState {
#[default]
A,
B,
}
#[derive(Message, Debug)]
struct StandardMessage;
#[derive(Message, Debug)]
struct StateScopedMessage;
#[test]
fn clear_message_on_exit_state() {
let mut app = App::new();
app.add_plugins(StatesPlugin);
app.init_state::<TestState>();
app.add_message::<StandardMessage>();
app.add_message::<StateScopedMessage>()
.clear_messages_on_exit::<StateScopedMessage>(TestState::A);
app.world_mut().write_message(StandardMessage).unwrap();
app.world_mut().write_message(StateScopedMessage).unwrap();
assert!(!app
.world()
.resource::<Messages<StandardMessage>>()
.is_empty());
assert!(!app
.world()
.resource::<Messages<StateScopedMessage>>()
.is_empty());
app.world_mut()
.resource_mut::<NextState<TestState>>()
.set(TestState::B);
app.update();
assert!(!app
.world()
.resource::<Messages<StandardMessage>>()
.is_empty());
assert!(app
.world()
.resource::<Messages<StateScopedMessage>>()
.is_empty());
}
#[test]
fn clear_message_on_enter_state() {
let mut app = App::new();
app.add_plugins(StatesPlugin);
app.init_state::<TestState>();
app.add_message::<StandardMessage>();
app.add_message::<StateScopedMessage>()
.clear_messages_on_enter::<StateScopedMessage>(TestState::B);
app.world_mut().write_message(StandardMessage).unwrap();
app.world_mut().write_message(StateScopedMessage).unwrap();
assert!(!app
.world()
.resource::<Messages<StandardMessage>>()
.is_empty());
assert!(!app
.world()
.resource::<Messages<StateScopedMessage>>()
.is_empty());
app.world_mut()
.resource_mut::<NextState<TestState>>()
.set(TestState::B);
app.update();
assert!(!app
.world()
.resource::<Messages<StandardMessage>>()
.is_empty());
assert!(app
.world()
.resource::<Messages<StateScopedMessage>>()
.is_empty());
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_state/src/state_scoped.rs | crates/bevy_state/src/state_scoped.rs | #[cfg(feature = "bevy_reflect")]
use bevy_ecs::reflect::ReflectComponent;
use bevy_ecs::{
component::Component,
entity::Entity,
entity_disabling::Disabled,
message::MessageReader,
query::Allow,
system::{Commands, Query},
};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::prelude::*;
use crate::state::{StateTransitionEvent, States};
/// Entities marked with this component will be removed
/// when the world's state of the matching type no longer matches the supplied value.
///
/// If you need to disable this behavior, add the attribute `#[states(scoped_entities = false)]` when deriving [`States`].
///
/// ```
/// use bevy_state::prelude::*;
/// use bevy_ecs::prelude::*;
/// use bevy_ecs::system::ScheduleSystem;
///
/// #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default, States)]
/// enum GameState {
/// #[default]
/// MainMenu,
/// SettingsMenu,
/// InGame,
/// }
///
/// # #[derive(Component)]
/// # struct Player;
///
/// fn spawn_player(mut commands: Commands) {
/// commands.spawn((
/// DespawnOnExit(GameState::InGame),
/// Player
/// ));
/// }
///
/// # struct AppMock;
/// # impl AppMock {
/// # fn init_state<S>(&mut self) {}
/// # fn add_systems<S, M>(&mut self, schedule: S, systems: impl IntoScheduleConfigs<ScheduleSystem, M>) {}
/// # }
/// # struct Update;
/// # let mut app = AppMock;
///
/// app.init_state::<GameState>();
/// app.add_systems(OnEnter(GameState::InGame), spawn_player);
/// ```
#[derive(Component, Clone)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Component, Clone))]
pub struct DespawnOnExit<S: States>(pub S);
impl<S> Default for DespawnOnExit<S>
where
S: States + Default,
{
fn default() -> Self {
Self(S::default())
}
}
/// Despawns entities marked with [`DespawnOnExit<S>`] when their state no
/// longer matches the world state.
///
/// If the entity has already been despawned no warning will be emitted.
pub fn despawn_entities_on_exit_state<S: States>(
mut commands: Commands,
mut transitions: MessageReader<StateTransitionEvent<S>>,
query: Query<(Entity, &DespawnOnExit<S>), Allow<Disabled>>,
) {
// We use the latest event, because state machine internals generate at most 1
// transition event (per type) each frame. No event means no change happened
// and we skip iterating all entities.
let Some(transition) = transitions.read().last() else {
return;
};
if transition.entered == transition.exited {
return;
}
let Some(exited) = &transition.exited else {
return;
};
for (entity, binding) in &query {
if binding.0 == *exited {
commands.entity(entity).try_despawn();
}
}
}
/// Entities marked with this component will be despawned
/// upon entering the given state.
///
/// ```
/// use bevy_state::prelude::*;
/// use bevy_ecs::{prelude::*, system::ScheduleSystem};
///
/// #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default, States)]
/// enum GameState {
/// #[default]
/// MainMenu,
/// SettingsMenu,
/// InGame,
/// }
///
/// # #[derive(Component)]
/// # struct Player;
///
/// fn spawn_player(mut commands: Commands) {
/// commands.spawn((
/// DespawnOnEnter(GameState::MainMenu),
/// Player
/// ));
/// }
///
/// # struct AppMock;
/// # impl AppMock {
/// # fn init_state<S>(&mut self) {}
/// # fn add_systems<S, M>(&mut self, schedule: S, systems: impl IntoScheduleConfigs<ScheduleSystem, M>) {}
/// # }
/// # struct Update;
/// # let mut app = AppMock;
///
/// app.init_state::<GameState>();
/// app.add_systems(OnEnter(GameState::InGame), spawn_player);
/// ```
#[derive(Component, Clone)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Component))]
pub struct DespawnOnEnter<S: States>(pub S);
/// Despawns entities marked with [`DespawnOnEnter<S>`] when their state
/// matches the world state.
///
/// If the entity has already been despawned no warning will be emitted.
pub fn despawn_entities_on_enter_state<S: States>(
mut commands: Commands,
mut transitions: MessageReader<StateTransitionEvent<S>>,
query: Query<(Entity, &DespawnOnEnter<S>), Allow<Disabled>>,
) {
// We use the latest event, because state machine internals generate at most 1
// transition event (per type) each frame. No event means no change happened
// and we skip iterating all entities.
let Some(transition) = transitions.read().last() else {
return;
};
if transition.entered == transition.exited {
return;
}
let Some(entered) = &transition.entered else {
return;
};
for (entity, binding) in &query {
if binding.0 == *entered {
commands.entity(entity).try_despawn();
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_state/src/commands.rs | crates/bevy_state/src/commands.rs | use bevy_ecs::{system::Commands, world::World};
use log::debug;
use crate::state::{FreelyMutableState, NextState};
/// Extension trait for [`Commands`] adding `bevy_state` helpers.
pub trait CommandsStatesExt {
/// Sets the next state the app should move to.
///
/// Internally this schedules a command that updates the [`NextState<S>`](crate::prelude::NextState)
/// resource with `state`.
///
/// Note that commands introduce sync points to the ECS schedule, so modifying `NextState`
/// directly may be more efficient depending on your use-case.
fn set_state<S: FreelyMutableState>(&mut self, state: S);
/// Sets the next state the app should move to, skipping any state transitions if the next state is the same as the current state.
///
/// Internally this schedules a command that updates the [`NextState<S>`](crate::prelude::NextState)
/// resource with `state`.
///
/// Note that commands introduce sync points to the ECS schedule, so modifying `NextState`
/// directly may be more efficient depending on your use-case.
fn set_state_if_neq<S: FreelyMutableState>(&mut self, state: S);
}
impl CommandsStatesExt for Commands<'_, '_> {
fn set_state<S: FreelyMutableState>(&mut self, state: S) {
self.queue(move |w: &mut World| {
let mut next = w.resource_mut::<NextState<S>>();
if let NextState::PendingIfNeq(prev) = &*next {
debug!("overwriting next state {prev:?} with {state:?}");
}
next.set(state);
});
}
fn set_state_if_neq<S: FreelyMutableState>(&mut self, state: S) {
self.queue(move |w: &mut World| {
let mut next = w.resource_mut::<NextState<S>>();
if let NextState::PendingIfNeq(prev) = &*next
&& *prev != state
{
debug!("overwriting next state {prev:?} with {state:?} if not equal");
}
next.set_if_neq(state);
});
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_state/src/condition.rs | crates/bevy_state/src/condition.rs | use crate::state::{State, States};
use bevy_ecs::{change_detection::DetectChanges, system::Res};
/// A [`SystemCondition`](bevy_ecs::prelude::SystemCondition)-satisfying system that returns `true`
/// if the state machine exists.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # use bevy_state::prelude::*;
/// # use bevy_app::{App, Update};
/// # use bevy_state::app::StatesPlugin;
/// # #[derive(Resource, Default)]
/// # struct Counter(u8);
/// # let mut app = App::new();
/// # app
/// # .init_resource::<Counter>()
/// # .add_plugins(StatesPlugin);
/// #[derive(States, Clone, Copy, Default, Eq, PartialEq, Hash, Debug)]
/// enum GameState {
/// #[default]
/// Playing,
/// Paused,
/// }
///
/// app.add_systems(Update,
/// // `state_exists` will only return true if the
/// // given state exists
/// my_system.run_if(state_exists::<GameState>),
/// );
///
/// fn my_system(mut counter: ResMut<Counter>) {
/// counter.0 += 1;
/// }
///
/// // `GameState` does not yet exist so `my_system` won't run
/// app.update();
/// assert_eq!(app.world().resource::<Counter>().0, 0);
///
/// app.init_state::<GameState>();
///
/// // `GameState` now exists so `my_system` will run
/// app.update();
/// assert_eq!(app.world().resource::<Counter>().0, 1);
/// ```
pub fn state_exists<S: States>(current_state: Option<Res<State<S>>>) -> bool {
current_state.is_some()
}
/// Generates a [`SystemCondition`](bevy_ecs::prelude::SystemCondition)-satisfying closure that returns `true`
/// if the state machine is currently in `state`.
///
/// Will return `false` if the state does not exist or if not in `state`.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # use bevy_state::prelude::*;
/// # use bevy_app::{App, Update};
/// # use bevy_state::app::StatesPlugin;
/// # #[derive(Resource, Default)]
/// # struct Counter(u8);
/// # let mut app = App::new();
/// # app
/// # .init_resource::<Counter>()
/// # .add_plugins(StatesPlugin);
/// #[derive(States, Clone, Copy, Default, Eq, PartialEq, Hash, Debug)]
/// enum GameState {
/// #[default]
/// Playing,
/// Paused,
/// }
///
/// app
/// .init_state::<GameState>()
/// .add_systems(Update, (
/// // `in_state` will only return true if the
/// // given state equals the given value
/// play_system.run_if(in_state(GameState::Playing)),
/// pause_system.run_if(in_state(GameState::Paused)),
/// ));
///
/// fn play_system(mut counter: ResMut<Counter>) {
/// counter.0 += 1;
/// }
///
/// fn pause_system(mut counter: ResMut<Counter>) {
/// counter.0 -= 1;
/// }
///
/// // We default to `GameState::Playing` so `play_system` runs
/// app.update();
/// assert_eq!(app.world().resource::<Counter>().0, 1);
///
/// app.insert_state(GameState::Paused);
///
/// // Now that we are in `GameState::Pause`, `pause_system` will run
/// app.update();
/// assert_eq!(app.world().resource::<Counter>().0, 0);
/// ```
pub fn in_state<S: States>(state: S) -> impl FnMut(Option<Res<State<S>>>) -> bool + Clone {
move |current_state: Option<Res<State<S>>>| match current_state {
Some(current_state) => *current_state == state,
None => false,
}
}
/// A [`SystemCondition`](bevy_ecs::prelude::SystemCondition)-satisfying system that returns `true`
/// if the state machine changed state.
///
/// To do things on transitions to/from specific states, use their respective OnEnter/OnExit
/// schedules. Use this run condition if you want to detect any change, regardless of the value.
///
/// Returns false if the state does not exist or the state has not changed.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # use bevy_state::prelude::*;
/// # use bevy_state::app::StatesPlugin;
/// # use bevy_app::{App, Update};
/// # #[derive(Resource, Default)]
/// # struct Counter(u8);
/// # let mut app = App::new();
/// # app
/// # .init_resource::<Counter>()
/// # .add_plugins(StatesPlugin);
/// #[derive(States, Clone, Copy, Default, Eq, PartialEq, Hash, Debug)]
/// enum GameState {
/// #[default]
/// Playing,
/// Paused,
/// }
///
/// app
/// .init_state::<GameState>()
/// .add_systems(Update,
/// // `state_changed` will only return true if the
/// // given states value has just been updated or
/// // the state has just been added
/// my_system.run_if(state_changed::<GameState>),
/// );
///
/// fn my_system(mut counter: ResMut<Counter>) {
/// counter.0 += 1;
/// }
///
/// // `GameState` has just been added so `my_system` will run
/// app.update();
/// assert_eq!(app.world().resource::<Counter>().0, 1);
///
/// // `GameState` has not been updated so `my_system` will not run
/// app.update();
/// assert_eq!(app.world().resource::<Counter>().0, 1);
///
/// app.insert_state(GameState::Paused);
///
/// // Now that `GameState` has been updated `my_system` will run
/// app.update();
/// assert_eq!(app.world().resource::<Counter>().0, 2);
/// ```
pub fn state_changed<S: States>(current_state: Option<Res<State<S>>>) -> bool {
let Some(current_state) = current_state else {
return false;
};
current_state.is_changed()
}
#[cfg(test)]
mod tests {
use bevy_ecs::schedule::{IntoScheduleConfigs, Schedule, SystemCondition};
use crate::prelude::*;
use bevy_state_macros::States;
#[derive(States, PartialEq, Eq, Debug, Default, Hash, Clone)]
enum TestState {
#[default]
A,
B,
}
fn test_system() {}
// Ensure distributive_run_if compiles with the common conditions.
#[test]
fn distributive_run_if_compiles() {
Schedule::default().add_systems(
(test_system, test_system)
.distributive_run_if(state_exists::<TestState>)
.distributive_run_if(in_state(TestState::A).or(in_state(TestState::B)))
.distributive_run_if(state_changed::<TestState>),
);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_state/src/state/computed_states.rs | crates/bevy_state/src/state/computed_states.rs | use core::{fmt::Debug, hash::Hash};
use bevy_ecs::schedule::Schedule;
use super::{state_set::StateSet, states::States};
/// A state whose value is automatically computed based on the values of other [`States`].
///
/// A **computed state** is a state that is deterministically derived from a set of `SourceStates`.
/// The [`StateSet`] is passed into the `compute` method whenever one of them changes, and the
/// result becomes the state's value.
///
/// ```
/// # use bevy_state::prelude::*;
/// # use bevy_ecs::prelude::*;
/// #
/// /// Computed States require some state to derive from
/// #[derive(States, Clone, PartialEq, Eq, Hash, Debug, Default)]
/// enum AppState {
/// #[default]
/// Menu,
/// InGame { paused: bool }
/// }
///
/// #[derive(Clone, PartialEq, Eq, Hash, Debug)]
/// struct InGame;
///
/// impl ComputedStates for InGame {
/// /// We set the source state to be the state, or a tuple of states,
/// /// we want to depend on. You can also wrap each state in an Option,
/// /// if you want the computed state to execute even if the state doesn't
/// /// currently exist in the world.
/// type SourceStates = AppState;
///
/// /// We then define the compute function, which takes in
/// /// your SourceStates
/// fn compute(sources: AppState) -> Option<Self> {
/// match sources {
/// /// When we are in game, we want to return the InGame state
/// AppState::InGame { .. } => Some(InGame),
/// /// Otherwise, we don't want the `State<InGame>` resource to exist,
/// /// so we return None.
/// _ => None
/// }
/// }
/// }
/// ```
///
/// you can then add it to an App, and from there you use the state as normal
///
/// ```
/// # use bevy_state::prelude::*;
/// # use bevy_ecs::prelude::*;
/// #
/// # struct App;
/// # impl App {
/// # fn new() -> Self { App }
/// # fn init_state<S>(&mut self) -> &mut Self {self}
/// # fn add_computed_state<S>(&mut self) -> &mut Self {self}
/// # }
/// # struct AppState;
/// # struct InGame;
/// #
/// App::new()
/// .init_state::<AppState>()
/// .add_computed_state::<InGame>();
/// ```
pub trait ComputedStates: 'static + Send + Sync + Clone + PartialEq + Eq + Hash + Debug {
/// The set of states from which the [`Self`] is derived.
///
/// This can either be a single type that implements [`States`], an Option of a type
/// that implements [`States`], or a tuple
/// containing multiple types that implement [`States`] or Optional versions of them.
///
/// For example, `(MapState, EnemyState)` is valid, as is `(MapState, Option<EnemyState>)`
type SourceStates: StateSet;
/// Whether state transition schedules should be run when the state changes to the same value. Default is `true`.
const ALLOW_SAME_STATE_TRANSITIONS: bool = true;
/// Computes the next value of [`State<Self>`](crate::state::State).
/// This function gets called whenever one of the [`SourceStates`](Self::SourceStates) changes.
///
/// If the result is [`None`], the [`State<Self>`](crate::state::State) resource will be removed from the world.
fn compute(sources: Self::SourceStates) -> Option<Self>;
/// This function sets up systems that compute the state whenever one of the [`SourceStates`](Self::SourceStates)
/// change. It is called by `App::add_computed_state`, but can be called manually if `App` is not
/// used.
fn register_computed_state_systems(schedule: &mut Schedule) {
Self::SourceStates::register_computed_state_systems_in_schedule::<Self>(schedule);
}
}
impl<S: ComputedStates> States for S {
const DEPENDENCY_DEPTH: usize = S::SourceStates::SET_DEPENDENCY_DEPTH + 1;
}
#[cfg(test)]
mod tests {
use crate::{
app::{AppExtStates, StatesPlugin},
prelude::DespawnOnEnter,
state::{ComputedStates, StateTransition},
};
use bevy_app::App;
use bevy_ecs::component::Component;
use bevy_state_macros::States;
#[derive(Component)]
struct TestComponent;
#[derive(States, Default, PartialEq, Eq, Hash, Debug, Clone)]
struct TestState;
#[derive(PartialEq, Eq, Hash, Debug, Clone)]
struct TestComputedState;
impl ComputedStates for TestComputedState {
type SourceStates = TestState;
fn compute(_: Self::SourceStates) -> Option<Self> {
Some(TestComputedState)
}
}
#[test]
fn computed_states_are_state_scoped_by_default() {
let mut app = App::new();
app.add_plugins(StatesPlugin);
app.insert_state(TestState);
app.add_computed_state::<TestComputedState>();
let world = app.world_mut();
world.spawn((DespawnOnEnter(TestComputedState), TestComponent));
assert!(world.query::<&TestComponent>().single(world).is_ok());
world.run_schedule(StateTransition);
assert_eq!(world.query::<&TestComponent>().iter(world).len(), 0);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_state/src/state/sub_states.rs | crates/bevy_state/src/state/sub_states.rs | use bevy_ecs::schedule::Schedule;
use super::{freely_mutable_state::FreelyMutableState, state_set::StateSet, states::States};
pub use bevy_state_macros::SubStates;
/// A sub-state is a state that exists only when the source state meet certain conditions,
/// but unlike [`ComputedStates`](crate::state::ComputedStates) - while they exist they can be manually modified.
///
/// The default approach to creating [`SubStates`] is using the derive macro, and defining a single source state
/// and value to determine its existence.
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # use bevy_state::prelude::*;
///
/// #[derive(States, Clone, PartialEq, Eq, Hash, Debug, Default)]
/// enum AppState {
/// #[default]
/// Menu,
/// InGame
/// }
///
///
/// #[derive(SubStates, Clone, PartialEq, Eq, Hash, Debug, Default)]
/// #[source(AppState = AppState::InGame)]
/// enum GamePhase {
/// #[default]
/// Setup,
/// Battle,
/// Conclusion
/// }
/// ```
///
/// you can then add it to an App, and from there you use the state as normal:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # use bevy_state::prelude::*;
///
/// # struct App;
/// # impl App {
/// # fn new() -> Self { App }
/// # fn init_state<S>(&mut self) -> &mut Self {self}
/// # fn add_sub_state<S>(&mut self) -> &mut Self {self}
/// # }
/// # struct AppState;
/// # struct GamePhase;
///
/// App::new()
/// .init_state::<AppState>()
/// .add_sub_state::<GamePhase>();
/// ```
///
/// In more complex situations, the recommendation is to use an intermediary computed state, like so:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # use bevy_state::prelude::*;
///
/// /// Computed States require some state to derive from
/// #[derive(States, Clone, PartialEq, Eq, Hash, Debug, Default)]
/// enum AppState {
/// #[default]
/// Menu,
/// InGame { paused: bool }
/// }
///
/// #[derive(Clone, PartialEq, Eq, Hash, Debug)]
/// struct InGame;
///
/// impl ComputedStates for InGame {
/// /// We set the source state to be the state, or set of states,
/// /// we want to depend on. Any of the states can be wrapped in an Option.
/// type SourceStates = Option<AppState>;
///
/// /// We then define the compute function, which takes in the AppState
/// fn compute(sources: Option<AppState>) -> Option<Self> {
/// match sources {
/// /// When we are in game, we want to return the InGame state
/// Some(AppState::InGame { .. }) => Some(InGame),
/// /// Otherwise, we don't want the `State<InGame>` resource to exist,
/// /// so we return None.
/// _ => None
/// }
/// }
/// }
///
/// #[derive(SubStates, Clone, PartialEq, Eq, Hash, Debug, Default)]
/// #[source(InGame = InGame)]
/// enum GamePhase {
/// #[default]
/// Setup,
/// Battle,
/// Conclusion
/// }
/// ```
///
/// However, you can also manually implement them. If you do so, you'll also need to manually implement the `States` & `FreelyMutableState` traits.
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # use bevy_state::prelude::*;
/// # use bevy_state::state::{FreelyMutableState, NextState};
///
/// /// Computed States require some state to derive from
/// #[derive(States, Clone, PartialEq, Eq, Hash, Debug, Default)]
/// enum AppState {
/// #[default]
/// Menu,
/// InGame { paused: bool }
/// }
///
/// #[derive(Clone, PartialEq, Eq, Hash, Debug)]
/// enum GamePhase {
/// Setup,
/// Battle,
/// Conclusion
/// }
///
/// impl SubStates for GamePhase {
/// /// We set the source state to be the state, or set of states,
/// /// we want to depend on. Any of the states can be wrapped in an Option.
/// type SourceStates = Option<AppState>;
///
/// /// We then define the compute function, which takes in the [`Self::SourceStates`]
/// fn should_exist(sources: Option<AppState>) -> Option<Self> {
/// match sources {
/// /// When we are in game, we want a GamePhase state to exist.
/// /// We can set the initial value here or overwrite it through [`NextState`].
/// Some(AppState::InGame { .. }) => Some(Self::Setup),
/// /// If we don't want the `State<GamePhase>` resource to exist we return [`None`].
/// _ => None
/// }
/// }
/// }
///
/// impl States for GamePhase {
/// const DEPENDENCY_DEPTH : usize = <GamePhase as SubStates>::SourceStates::SET_DEPENDENCY_DEPTH + 1;
/// }
///
/// impl FreelyMutableState for GamePhase {}
/// ```
#[diagnostic::on_unimplemented(
message = "`{Self}` can not be used as a sub-state",
label = "invalid sub-state",
note = "consider annotating `{Self}` with `#[derive(SubStates)]`"
)]
pub trait SubStates: States + FreelyMutableState {
/// The set of states from which the [`Self`] is derived.
///
/// This can either be a single type that implements [`States`], or a tuple
/// containing multiple types that implement [`States`], or any combination of
/// types implementing [`States`] and Options of types implementing [`States`].
type SourceStates: StateSet;
/// This function gets called whenever one of the [`SourceStates`](Self::SourceStates) changes.
/// The result is used to determine the existence of [`State<Self>`](crate::state::State).
///
/// If the result is [`None`], the [`State<Self>`](crate::state::State) resource will be removed from the world,
/// otherwise if the [`State<Self>`](crate::state::State) resource doesn't exist
/// it will be created from the returned [`Some`] as the initial state.
///
/// Value within [`Some`] is ignored if the state already exists in the world
/// and only symbolizes that the state should still exist.
///
/// Initial value can also be overwritten by [`NextState`](crate::state::NextState).
fn should_exist(sources: Self::SourceStates) -> Option<Self>;
/// This function sets up systems that compute the state whenever one of the [`SourceStates`](Self::SourceStates)
/// change. It is called by `App::add_computed_state`, but can be called manually if `App` is not
/// used.
fn register_sub_state_systems(schedule: &mut Schedule) {
Self::SourceStates::register_sub_state_systems_in_schedule::<Self>(schedule);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_state/src/state/state_set.rs | crates/bevy_state/src/state/state_set.rs | use bevy_ecs::{
message::{MessageReader, MessageWriter},
schedule::{IntoScheduleConfigs, Schedule},
system::{Commands, IntoSystem, Res, ResMut},
};
use variadics_please::all_tuples;
use self::sealed::StateSetSealed;
use super::{
computed_states::ComputedStates, internal_apply_state_transition, last_transition, run_enter,
run_exit, run_transition, sub_states::SubStates, take_next_state, ApplyStateTransition,
EnterSchedules, ExitSchedules, NextState, PreviousState, State, StateTransitionEvent,
StateTransitionSystems, States, TransitionSchedules,
};
mod sealed {
/// Sealed trait used to prevent external implementations of [`StateSet`](super::StateSet).
pub trait StateSetSealed {}
}
/// A [`States`] type or tuple of types which implement [`States`].
///
/// This trait is used to allow implementors of [`States`], as well
/// as tuples containing exclusively implementors of [`States`], to
/// be used as [`ComputedStates::SourceStates`].
///
/// It is sealed, and auto implemented for all [`States`] types and
/// tuples containing them.
pub trait StateSet: StateSetSealed {
/// The total [`DEPENDENCY_DEPTH`](`States::DEPENDENCY_DEPTH`) of all
/// the states that are part of this [`StateSet`], added together.
///
/// Used to de-duplicate computed state executions and prevent cyclic
/// computed states.
const SET_DEPENDENCY_DEPTH: usize;
/// Sets up the systems needed to compute `T` whenever any `State` in this
/// `StateSet` is changed.
fn register_computed_state_systems_in_schedule<T: ComputedStates<SourceStates = Self>>(
schedule: &mut Schedule,
);
/// Sets up the systems needed to compute whether `T` exists whenever any `State` in this
/// `StateSet` is changed.
fn register_sub_state_systems_in_schedule<T: SubStates<SourceStates = Self>>(
schedule: &mut Schedule,
);
}
/// The `InnerStateSet` trait is used to isolate [`ComputedStates`] & [`SubStates`] from
/// needing to wrap all state dependencies in an [`Option<S>`].
///
/// Some [`ComputedStates`]'s might need to exist in different states based on the existence
/// of other states. So we needed the ability to use[`Option<S>`] when appropriate.
///
/// The isolation works because it is implemented for both S & [`Option<S>`], and has the `RawState` associated type
/// that allows it to know what the resource in the world should be. We can then essentially "unwrap" it in our
/// `StateSet` implementation - and the behavior of that unwrapping will depend on the arguments expected by the
/// [`ComputedStates`] & [`SubStates]`.
trait InnerStateSet: Sized {
type RawState: States;
const DEPENDENCY_DEPTH: usize;
fn convert_to_usable_state(wrapped: Option<&State<Self::RawState>>) -> Option<Self>;
}
impl<S: States> InnerStateSet for S {
type RawState = Self;
const DEPENDENCY_DEPTH: usize = S::DEPENDENCY_DEPTH;
fn convert_to_usable_state(wrapped: Option<&State<Self::RawState>>) -> Option<Self> {
wrapped.map(|v| v.0.clone())
}
}
impl<S: States> InnerStateSet for Option<S> {
type RawState = S;
const DEPENDENCY_DEPTH: usize = S::DEPENDENCY_DEPTH;
fn convert_to_usable_state(wrapped: Option<&State<Self::RawState>>) -> Option<Self> {
Some(wrapped.map(|v| v.0.clone()))
}
}
impl<S: InnerStateSet> StateSetSealed for S {}
impl<S: InnerStateSet> StateSet for S {
const SET_DEPENDENCY_DEPTH: usize = S::DEPENDENCY_DEPTH;
fn register_computed_state_systems_in_schedule<T: ComputedStates<SourceStates = Self>>(
schedule: &mut Schedule,
) {
let apply_state_transition =
|mut parent_changed: MessageReader<StateTransitionEvent<S::RawState>>,
event: MessageWriter<StateTransitionEvent<T>>,
commands: Commands,
current_state: Option<ResMut<State<T>>>,
previous_state: Option<ResMut<PreviousState<T>>>,
state_set: Option<Res<State<S::RawState>>>| {
if parent_changed.is_empty() {
return;
}
parent_changed.clear();
let new_state =
if let Some(state_set) = S::convert_to_usable_state(state_set.as_deref()) {
T::compute(state_set)
} else {
None
};
internal_apply_state_transition(
event,
commands,
current_state,
previous_state,
new_state,
T::ALLOW_SAME_STATE_TRANSITIONS,
);
};
schedule.configure_sets((
ApplyStateTransition::<T>::default()
.in_set(StateTransitionSystems::DependentTransitions)
.after(ApplyStateTransition::<S::RawState>::default()),
ExitSchedules::<T>::default()
.in_set(StateTransitionSystems::ExitSchedules)
.before(ExitSchedules::<S::RawState>::default()),
TransitionSchedules::<T>::default().in_set(StateTransitionSystems::TransitionSchedules),
EnterSchedules::<T>::default()
.in_set(StateTransitionSystems::EnterSchedules)
.after(EnterSchedules::<S::RawState>::default()),
));
schedule
.add_systems(apply_state_transition.in_set(ApplyStateTransition::<T>::default()))
.add_systems(
last_transition::<T>
.pipe(run_exit::<T>)
.in_set(ExitSchedules::<T>::default()),
)
.add_systems(
last_transition::<T>
.pipe(run_transition::<T>)
.in_set(TransitionSchedules::<T>::default()),
)
.add_systems(
last_transition::<T>
.pipe(run_enter::<T>)
.in_set(EnterSchedules::<T>::default()),
);
}
fn register_sub_state_systems_in_schedule<T: SubStates<SourceStates = Self>>(
schedule: &mut Schedule,
) {
// | parent changed | next state | already exists | should exist | what happens |
// | -------------- | ---------- | -------------- | ------------ | -------------------------------- |
// | false | false | false | - | - |
// | false | false | true | - | - |
// | false | true | false | false | - |
// | true | false | false | false | - |
// | true | true | false | false | - |
// | true | false | true | false | Some(current) -> None |
// | true | true | true | false | Some(current) -> None |
// | true | false | false | true | None -> Some(default) |
// | true | true | false | true | None -> Some(next) |
// | true | true | true | true | Some(current) -> Some(next) |
// | false | true | true | true | Some(current) -> Some(next) |
// | true | false | true | true | Some(current) -> Some(current) |
let apply_state_transition =
|mut parent_changed: MessageReader<StateTransitionEvent<S::RawState>>,
event: MessageWriter<StateTransitionEvent<T>>,
commands: Commands,
current_state_res: Option<ResMut<State<T>>>,
previous_state: Option<ResMut<PreviousState<T>>>,
next_state_res: Option<ResMut<NextState<T>>>,
state_set: Option<Res<State<S::RawState>>>| {
let parent_changed = parent_changed.read().last().is_some();
let next_state = take_next_state(next_state_res);
if !parent_changed && next_state.is_none() {
return;
}
let current_state = current_state_res.as_ref().map(|s| s.get()).cloned();
let initial_state = if parent_changed {
if let Some(state_set) = S::convert_to_usable_state(state_set.as_deref()) {
T::should_exist(state_set)
} else {
None
}
} else {
current_state.clone()
};
let same_state_enforced = next_state
.as_ref()
.map(|(_, same_state_enforced)| same_state_enforced)
.cloned()
.unwrap_or_default();
let new_state = initial_state.map(|x| {
next_state
.map(|(next, _)| next)
.or(current_state)
.unwrap_or(x)
});
internal_apply_state_transition(
event,
commands,
current_state_res,
previous_state,
new_state,
same_state_enforced,
);
};
schedule.configure_sets((
ApplyStateTransition::<T>::default()
.in_set(StateTransitionSystems::DependentTransitions)
.after(ApplyStateTransition::<S::RawState>::default()),
ExitSchedules::<T>::default()
.in_set(StateTransitionSystems::ExitSchedules)
.before(ExitSchedules::<S::RawState>::default()),
TransitionSchedules::<T>::default().in_set(StateTransitionSystems::TransitionSchedules),
EnterSchedules::<T>::default()
.in_set(StateTransitionSystems::EnterSchedules)
.after(EnterSchedules::<S::RawState>::default()),
));
schedule
.add_systems(apply_state_transition.in_set(ApplyStateTransition::<T>::default()))
.add_systems(
last_transition::<T>
.pipe(run_exit::<T>)
.in_set(ExitSchedules::<T>::default()),
)
.add_systems(
last_transition::<T>
.pipe(run_transition::<T>)
.in_set(TransitionSchedules::<T>::default()),
)
.add_systems(
last_transition::<T>
.pipe(run_enter::<T>)
.in_set(EnterSchedules::<T>::default()),
);
}
}
macro_rules! impl_state_set_sealed_tuples {
($(#[$meta:meta])* $(($param: ident, $val: ident, $evt: ident)), *) => {
$(#[$meta])*
impl<$($param: InnerStateSet),*> StateSetSealed for ($($param,)*) {}
$(#[$meta])*
impl<$($param: InnerStateSet),*> StateSet for ($($param,)*) {
const SET_DEPENDENCY_DEPTH : usize = $($param::DEPENDENCY_DEPTH +)* 0;
fn register_computed_state_systems_in_schedule<T: ComputedStates<SourceStates = Self>>(
schedule: &mut Schedule,
) {
let apply_state_transition =
|($(mut $evt),*,): ($(MessageReader<StateTransitionEvent<$param::RawState>>),*,),
message: MessageWriter<StateTransitionEvent<T>>,
commands: Commands,
current_state: Option<ResMut<State<T>>>,
previous_state: Option<ResMut<PreviousState<T>>>,
($($val),*,): ($(Option<Res<State<$param::RawState>>>),*,)| {
if ($($evt.is_empty())&&*) {
return;
}
$($evt.clear();)*
let new_state = if let ($(Some($val)),*,) = ($($param::convert_to_usable_state($val.as_deref())),*,) {
T::compute(($($val),*, ))
} else {
None
};
internal_apply_state_transition(message, commands, current_state, previous_state, new_state, false);
};
schedule.configure_sets((
ApplyStateTransition::<T>::default()
.in_set(StateTransitionSystems::DependentTransitions)
$(.after(ApplyStateTransition::<$param::RawState>::default()))*,
ExitSchedules::<T>::default()
.in_set(StateTransitionSystems::ExitSchedules)
$(.before(ExitSchedules::<$param::RawState>::default()))*,
TransitionSchedules::<T>::default()
.in_set(StateTransitionSystems::TransitionSchedules),
EnterSchedules::<T>::default()
.in_set(StateTransitionSystems::EnterSchedules)
$(.after(EnterSchedules::<$param::RawState>::default()))*,
));
schedule
.add_systems(apply_state_transition.in_set(ApplyStateTransition::<T>::default()))
.add_systems(last_transition::<T>.pipe(run_exit::<T>).in_set(ExitSchedules::<T>::default()))
.add_systems(last_transition::<T>.pipe(run_transition::<T>).in_set(TransitionSchedules::<T>::default()))
.add_systems(last_transition::<T>.pipe(run_enter::<T>).in_set(EnterSchedules::<T>::default()));
}
fn register_sub_state_systems_in_schedule<T: SubStates<SourceStates = Self>>(
schedule: &mut Schedule,
) {
let apply_state_transition =
|($(mut $evt),*,): ($(MessageReader<StateTransitionEvent<$param::RawState>>),*,),
message: MessageWriter<StateTransitionEvent<T>>,
commands: Commands,
current_state_res: Option<ResMut<State<T>>>,
previous_state: Option<ResMut<PreviousState<T>>>,
next_state_res: Option<ResMut<NextState<T>>>,
($($val),*,): ($(Option<Res<State<$param::RawState>>>),*,)| {
let parent_changed = ($($evt.read().last().is_some())||*);
let next_state = take_next_state(next_state_res);
if !parent_changed && next_state.is_none() {
return;
}
let current_state = current_state_res.as_ref().map(|s| s.get()).cloned();
let initial_state = if parent_changed {
if let ($(Some($val)),*,) = ($($param::convert_to_usable_state($val.as_deref())),*,) {
T::should_exist(($($val),*, ))
} else {
None
}
} else {
current_state.clone()
};
let same_state_enforced = next_state
.as_ref()
.map(|(_, same_state_enforced)| same_state_enforced)
.cloned()
.unwrap_or_default();
let new_state = initial_state.map(|x| {
next_state
.map(|(next, _)| next)
.or(current_state)
.unwrap_or(x)
});
internal_apply_state_transition(message, commands, current_state_res, previous_state, new_state, same_state_enforced);
};
schedule.configure_sets((
ApplyStateTransition::<T>::default()
.in_set(StateTransitionSystems::DependentTransitions)
$(.after(ApplyStateTransition::<$param::RawState>::default()))*,
ExitSchedules::<T>::default()
.in_set(StateTransitionSystems::ExitSchedules)
$(.before(ExitSchedules::<$param::RawState>::default()))*,
TransitionSchedules::<T>::default()
.in_set(StateTransitionSystems::TransitionSchedules),
EnterSchedules::<T>::default()
.in_set(StateTransitionSystems::EnterSchedules)
$(.after(EnterSchedules::<$param::RawState>::default()))*,
));
schedule
.add_systems(apply_state_transition.in_set(ApplyStateTransition::<T>::default()))
.add_systems(last_transition::<T>.pipe(run_exit::<T>).in_set(ExitSchedules::<T>::default()))
.add_systems(last_transition::<T>.pipe(run_transition::<T>).in_set(TransitionSchedules::<T>::default()))
.add_systems(last_transition::<T>.pipe(run_enter::<T>).in_set(EnterSchedules::<T>::default()));
}
}
};
}
all_tuples!(
#[doc(fake_variadic)]
impl_state_set_sealed_tuples,
1,
15,
S,
s,
ereader
);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_state/src/state/transitions.rs | crates/bevy_state/src/state/transitions.rs | use core::{marker::PhantomData, mem};
use bevy_ecs::{
message::{Message, MessageReader, MessageWriter},
schedule::{IntoScheduleConfigs, Schedule, ScheduleLabel, Schedules, SystemSet},
system::{Commands, In, ResMut},
world::World,
};
use super::{
resources::{PreviousState, State},
states::States,
};
/// The label of a [`Schedule`] that **only** runs whenever [`State<S>`] enters the provided state.
///
/// This schedule ignores identity transitions.
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct OnEnter<S: States>(pub S);
/// The label of a [`Schedule`] that **only** runs whenever [`State<S>`] exits the provided state.
///
/// This schedule ignores identity transitions.
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct OnExit<S: States>(pub S);
/// The label of a [`Schedule`] that **only** runs whenever [`State<S>`]
/// exits AND enters the provided `exited` and `entered` states.
///
/// Systems added to this schedule are always ran *after* [`OnExit`], and *before* [`OnEnter`].
///
/// This schedule will run on identity transitions.
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct OnTransition<S: States> {
/// The state being exited.
pub exited: S,
/// The state being entered.
pub entered: S,
}
/// Runs [state transitions](States).
///
/// By default, it will be triggered once before [`PreStartup`] and then each frame after [`PreUpdate`], but
/// you can manually trigger it at arbitrary times by creating an exclusive
/// system to run the schedule.
///
/// ```rust
/// use bevy_state::prelude::*;
/// use bevy_ecs::prelude::*;
///
/// fn run_state_transitions(world: &mut World) {
/// let _ = world.try_run_schedule(StateTransition);
/// }
/// ```
///
/// This schedule is split up into four phases, as described in [`StateTransitionSystems`].
///
/// [`PreStartup`]: https://docs.rs/bevy/latest/bevy/prelude/struct.PreStartup.html
/// [`PreUpdate`]: https://docs.rs/bevy/latest/bevy/prelude/struct.PreUpdate.html
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct StateTransition;
/// A [`Message`] sent when any state transition of `S` happens.
/// This includes identity transitions, where `exited` and `entered` have the same value.
///
/// If you know exactly what state you want to respond to ahead of time, consider [`OnEnter`], [`OnTransition`], or [`OnExit`]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Message)]
pub struct StateTransitionEvent<S: States> {
/// The state being exited.
pub exited: Option<S>,
/// The state being entered.
pub entered: Option<S>,
/// Allow running state transition events when `exited` and `entered` are the same
pub allow_same_state_transitions: bool,
}
/// Applies state transitions and runs transitions schedules in order.
///
/// These system sets are run sequentially, in the order of the enum variants.
#[derive(SystemSet, Clone, Debug, PartialEq, Eq, Hash)]
pub enum StateTransitionSystems {
/// States apply their transitions from [`NextState`](super::NextState)
/// and compute functions based on their parent states.
DependentTransitions,
/// Exit schedules are executed in leaf to root order
ExitSchedules,
/// Transition schedules are executed in arbitrary order.
TransitionSchedules,
/// Enter schedules are executed in root to leaf order.
EnterSchedules,
}
#[derive(SystemSet, Clone, Debug, PartialEq, Eq, Hash)]
/// System set that runs exit schedule(s) for state `S`.
pub struct ExitSchedules<S: States>(PhantomData<S>);
impl<S: States> Default for ExitSchedules<S> {
fn default() -> Self {
Self(Default::default())
}
}
#[derive(SystemSet, Clone, Debug, PartialEq, Eq, Hash)]
/// System set that runs transition schedule(s) for state `S`.
pub struct TransitionSchedules<S: States>(PhantomData<S>);
impl<S: States> Default for TransitionSchedules<S> {
fn default() -> Self {
Self(Default::default())
}
}
#[derive(SystemSet, Clone, Debug, PartialEq, Eq, Hash)]
/// System set that runs enter schedule(s) for state `S`.
pub struct EnterSchedules<S: States>(PhantomData<S>);
impl<S: States> Default for EnterSchedules<S> {
fn default() -> Self {
Self(Default::default())
}
}
/// System set that applies transitions for state `S`.
#[derive(SystemSet, Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct ApplyStateTransition<S: States>(PhantomData<S>);
impl<S: States> Default for ApplyStateTransition<S> {
fn default() -> Self {
Self(Default::default())
}
}
/// This function actually applies a state change, and registers the required
/// schedules for downstream computed states and transition schedules.
///
/// The `new_state` is an option to allow for removal - `None` will trigger the
/// removal of the `State<S>` resource from the [`World`].
pub(crate) fn internal_apply_state_transition<S: States>(
mut event: MessageWriter<StateTransitionEvent<S>>,
mut commands: Commands,
current_state: Option<ResMut<State<S>>>,
mut previous_state: Option<ResMut<PreviousState<S>>>,
new_state: Option<S>,
allow_same_state_transitions: bool,
) {
match new_state {
Some(entered) => {
match current_state {
// If the [`State<S>`] resource exists, and the state is not the one we are
// entering - we need to set the new value, compute dependent states, send transition events
// and register transition schedules.
Some(mut state_resource) => {
let exited = match *state_resource == entered {
true => entered.clone(),
false => mem::replace(&mut state_resource.0, entered.clone()),
};
// Transition events are sent even for same state transitions
// Although enter and exit schedules are not run by default.
event.write(StateTransitionEvent {
exited: Some(exited.clone()),
entered: Some(entered.clone()),
allow_same_state_transitions,
});
if let Some(ref mut previous_state) = previous_state {
previous_state.0 = exited;
} else {
commands.insert_resource(PreviousState(exited));
}
}
None => {
// If the [`State<S>`] resource does not exist, we create it, compute dependent states, send a transition event and register the `OnEnter` schedule.
commands.insert_resource(State(entered.clone()));
event.write(StateTransitionEvent {
exited: None,
entered: Some(entered.clone()),
allow_same_state_transitions,
});
// When [`State<S>`] is initialized, there can be stale data in
// [`PreviousState<S>`] from a prior transition to `None`, so we remove it.
if previous_state.is_some() {
commands.remove_resource::<PreviousState<S>>();
}
}
};
}
None => {
// We first remove the [`State<S>`] resource, and if one existed we compute dependent states, send a transition event and run the `OnExit` schedule.
if let Some(resource) = current_state {
let exited = resource.get().clone();
commands.remove_resource::<State<S>>();
event.write(StateTransitionEvent {
exited: Some(exited.clone()),
entered: None,
allow_same_state_transitions,
});
if let Some(ref mut previous_state) = previous_state {
previous_state.0 = exited;
} else {
commands.insert_resource(PreviousState(exited));
}
}
}
}
}
/// Sets up the schedules and systems for handling state transitions
/// within a [`World`].
///
/// Runs automatically when using `App` to insert states, but needs to
/// be added manually in other situations.
pub fn setup_state_transitions_in_world(world: &mut World) {
let mut schedules = world.get_resource_or_init::<Schedules>();
if schedules.contains(StateTransition) {
return;
}
let mut schedule = Schedule::new(StateTransition);
schedule.configure_sets(
(
StateTransitionSystems::DependentTransitions,
StateTransitionSystems::ExitSchedules,
StateTransitionSystems::TransitionSchedules,
StateTransitionSystems::EnterSchedules,
)
.chain(),
);
schedules.insert(schedule);
}
/// Returns the latest state transition event of type `S`, if any are available.
pub fn last_transition<S: States>(
mut reader: MessageReader<StateTransitionEvent<S>>,
) -> Option<StateTransitionEvent<S>> {
reader.read().last().cloned()
}
pub(crate) fn run_enter<S: States>(
transition: In<Option<StateTransitionEvent<S>>>,
world: &mut World,
) {
let Some(transition) = transition.0 else {
return;
};
if transition.entered == transition.exited && !transition.allow_same_state_transitions {
return;
}
let Some(entered) = transition.entered else {
return;
};
let _ = world.try_run_schedule(OnEnter(entered));
}
pub(crate) fn run_exit<S: States>(
transition: In<Option<StateTransitionEvent<S>>>,
world: &mut World,
) {
let Some(transition) = transition.0 else {
return;
};
if transition.entered == transition.exited && !transition.allow_same_state_transitions {
return;
}
let Some(exited) = transition.exited else {
return;
};
let _ = world.try_run_schedule(OnExit(exited));
}
pub(crate) fn run_transition<S: States>(
transition: In<Option<StateTransitionEvent<S>>>,
world: &mut World,
) {
let Some(transition) = transition.0 else {
return;
};
let Some(exited) = transition.exited else {
return;
};
let Some(entered) = transition.entered else {
return;
};
let _ = world.try_run_schedule(OnTransition { exited, entered });
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.