diff --git a/Cargo.toml b/Cargo.toml index 1c95c166e0681..7a400b1cc214c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -45,6 +45,10 @@ ptr_as_ptr = "warn" ptr_cast_constness = "warn" ref_as_ptr = "warn" +std_instead_of_core = "warn" +std_instead_of_alloc = "warn" +alloc_instead_of_core = "warn" + [workspace.lints.rust] missing_docs = "warn" unexpected_cfgs = { level = "warn", check-cfg = ['cfg(docsrs_dep)'] } @@ -52,8 +56,42 @@ unsafe_code = "deny" unsafe_op_in_unsafe_fn = "warn" unused_qualifications = "warn" -[lints] -workspace = true +# Unfortunately, cargo does not currently support overriding workspace lints +# inside a particular crate. See https://github.com/rust-lang/cargo/issues/13157 +# +# We require an override for cases like `std_instead_of_core`, which are intended +# for the library contributors and not for how users should consume Bevy. +# To ensure examples aren't subject to these lints, below is a duplication of the +# workspace lints, with the "overrides" applied. +# +# [lints] +# workspace = true + +[lints.clippy] +doc_markdown = "warn" +manual_let_else = "warn" +match_same_arms = "warn" +redundant_closure_for_method_calls = "warn" +redundant_else = "warn" +semicolon_if_nothing_returned = "warn" +type_complexity = "allow" +undocumented_unsafe_blocks = "warn" +unwrap_or_default = "warn" + +ptr_as_ptr = "warn" +ptr_cast_constness = "warn" +ref_as_ptr = "warn" + +std_instead_of_core = "allow" +std_instead_of_alloc = "allow" +alloc_instead_of_core = "allow" + +[lints.rust] +missing_docs = "warn" +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(docsrs_dep)'] } +unsafe_code = "deny" +unsafe_op_in_unsafe_fn = "warn" +unused_qualifications = "warn" [features] default = [ diff --git a/benches/benches/bevy_ecs/change_detection.rs b/benches/benches/bevy_ecs/change_detection.rs index ae602738fe368..6c4428efed8bb 100644 --- a/benches/benches/bevy_ecs/change_detection.rs +++ b/benches/benches/bevy_ecs/change_detection.rs @@ -86,7 +86,7 @@ fn generic_bench( fn all_added_detection_generic(group: &mut BenchGroup, entity_count: u32) { group.bench_function( - format!("{}_entities_{}", entity_count, std::any::type_name::()), + format!("{}_entities_{}", entity_count, core::any::type_name::()), |bencher| { bencher.iter_batched_ref( || { @@ -110,8 +110,8 @@ fn all_added_detection_generic(group: &mut BenchGroup, e fn all_added_detection(criterion: &mut Criterion) { let mut group = criterion.benchmark_group("all_added_detection"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + 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, @@ -129,7 +129,7 @@ fn all_changed_detection_generic( entity_count: u32, ) { group.bench_function( - format!("{}_entities_{}", entity_count, std::any::type_name::()), + format!("{}_entities_{}", entity_count, core::any::type_name::()), |bencher| { bencher.iter_batched_ref( || { @@ -158,8 +158,8 @@ fn all_changed_detection_generic( fn all_changed_detection(criterion: &mut Criterion) { let mut group = criterion.benchmark_group("all_changed_detection"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + 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, @@ -179,7 +179,7 @@ fn few_changed_detection_generic( 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, std::any::type_name::()), + format!("{}_entities_{}", entity_count, core::any::type_name::()), |bencher| { bencher.iter_batched_ref( || { @@ -208,8 +208,8 @@ fn few_changed_detection_generic( fn few_changed_detection(criterion: &mut Criterion) { let mut group = criterion.benchmark_group("few_changed_detection"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + 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, @@ -227,7 +227,7 @@ fn none_changed_detection_generic( entity_count: u32, ) { group.bench_function( - format!("{}_entities_{}", entity_count, std::any::type_name::()), + format!("{}_entities_{}", entity_count, core::any::type_name::()), |bencher| { bencher.iter_batched_ref( || { @@ -252,8 +252,8 @@ fn none_changed_detection_generic( fn none_changed_detection(criterion: &mut Criterion) { let mut group = criterion.benchmark_group("none_changed_detection"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + 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, @@ -308,7 +308,7 @@ fn multiple_archetype_none_changed_detection_generic() + core::any::type_name::() ), |bencher| { bencher.iter_batched_ref( @@ -356,8 +356,8 @@ fn multiple_archetype_none_changed_detection_generic( diff --git a/benches/benches/bevy_ecs/components/mod.rs b/benches/benches/bevy_ecs/components/mod.rs index 6da93681005a0..592f40fba7d07 100644 --- a/benches/benches/bevy_ecs/components/mod.rs +++ b/benches/benches/bevy_ecs/components/mod.rs @@ -23,8 +23,8 @@ criterion_group!( fn add_remove(c: &mut Criterion) { let mut group = c.benchmark_group("add_remove"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + 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()); @@ -38,8 +38,8 @@ fn add_remove(c: &mut Criterion) { fn add_remove_big(c: &mut Criterion) { let mut group = c.benchmark_group("add_remove_big"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + 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()); @@ -53,8 +53,8 @@ fn add_remove_big(c: &mut Criterion) { fn add_remove_very_big(c: &mut Criterion) { let mut group = c.benchmark_group("add_remove_very_big"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + 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()); @@ -64,8 +64,8 @@ fn add_remove_very_big(c: &mut Criterion) { fn insert_simple(c: &mut Criterion) { let mut group = c.benchmark_group("insert_simple"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + 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()); diff --git a/benches/benches/bevy_ecs/events/iter.rs b/benches/benches/bevy_ecs/events/iter.rs index 50fb65554e837..dc20bc3395a52 100644 --- a/benches/benches/bevy_ecs/events/iter.rs +++ b/benches/benches/bevy_ecs/events/iter.rs @@ -19,7 +19,7 @@ impl Benchmark { pub fn run(&mut self) { let mut reader = self.0.get_cursor(); for evt in reader.read(&self.0) { - std::hint::black_box(evt); + core::hint::black_box(evt); } } } diff --git a/benches/benches/bevy_ecs/events/mod.rs b/benches/benches/bevy_ecs/events/mod.rs index f7130594c6ed2..5d20ef25cd018 100644 --- a/benches/benches/bevy_ecs/events/mod.rs +++ b/benches/benches/bevy_ecs/events/mod.rs @@ -7,8 +7,8 @@ criterion_group!(event_benches, send, iter); fn send(c: &mut Criterion) { let mut group = c.benchmark_group("events_send"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + group.warm_up_time(core::time::Duration::from_millis(500)); + group.measurement_time(core::time::Duration::from_secs(4)); for count in [100, 1000, 10000, 50000] { group.bench_function(format!("size_4_events_{}", count), |b| { let mut bench = send::Benchmark::<4>::new(count); @@ -32,8 +32,8 @@ fn send(c: &mut Criterion) { fn iter(c: &mut Criterion) { let mut group = c.benchmark_group("events_iter"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + group.warm_up_time(core::time::Duration::from_millis(500)); + group.measurement_time(core::time::Duration::from_secs(4)); for count in [100, 1000, 10000, 50000] { group.bench_function(format!("size_4_events_{}", count), |b| { let mut bench = iter::Benchmark::<4>::new(count); diff --git a/benches/benches/bevy_ecs/events/send.rs b/benches/benches/bevy_ecs/events/send.rs index 2c81583d74ca1..fa996b50aa5d0 100644 --- a/benches/benches/bevy_ecs/events/send.rs +++ b/benches/benches/bevy_ecs/events/send.rs @@ -32,7 +32,7 @@ impl Benchmark { pub fn run(&mut self) { for _ in 0..self.count { self.events - .send(std::hint::black_box(BenchEvent([0u8; SIZE]))); + .send(core::hint::black_box(BenchEvent([0u8; SIZE]))); } self.events.update(); } diff --git a/benches/benches/bevy_ecs/fragmentation/mod.rs b/benches/benches/bevy_ecs/fragmentation/mod.rs index c5b364622139c..ae44aae4a48c5 100644 --- a/benches/benches/bevy_ecs/fragmentation/mod.rs +++ b/benches/benches/bevy_ecs/fragmentation/mod.rs @@ -2,7 +2,7 @@ use bevy_ecs::prelude::*; use bevy_ecs::system::SystemState; use criterion::*; use glam::*; -use std::hint::black_box; +use core::hint::black_box; criterion_group!(fragmentation_benches, iter_frag_empty); @@ -17,8 +17,8 @@ fn flip_coin() -> bool { } fn iter_frag_empty(c: &mut Criterion) { let mut group = c.benchmark_group("iter_fragmented(4096)_empty"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + 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(); diff --git a/benches/benches/bevy_ecs/iteration/heavy_compute.rs b/benches/benches/bevy_ecs/iteration/heavy_compute.rs index 9a53092903f48..3a3e350637236 100644 --- a/benches/benches/bevy_ecs/iteration/heavy_compute.rs +++ b/benches/benches/bevy_ecs/iteration/heavy_compute.rs @@ -17,8 +17,8 @@ pub fn heavy_compute(c: &mut Criterion) { struct Transform(Mat4); let mut group = c.benchmark_group("heavy_compute"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + 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); diff --git a/benches/benches/bevy_ecs/iteration/iter_simple.rs b/benches/benches/bevy_ecs/iteration/iter_simple.rs index 79af49b44dc6d..1fc86f5087679 100644 --- a/benches/benches/bevy_ecs/iteration/iter_simple.rs +++ b/benches/benches/bevy_ecs/iteration/iter_simple.rs @@ -20,7 +20,7 @@ impl<'w> Benchmark<'w> { let mut world = World::new(); world.spawn_batch( - std::iter::repeat(( + core::iter::repeat(( Transform(Mat4::from_scale(Vec3::ONE)), Position(Vec3::X), Rotation(Vec3::X), diff --git a/benches/benches/bevy_ecs/iteration/iter_simple_foreach.rs b/benches/benches/bevy_ecs/iteration/iter_simple_foreach.rs index a7975f9b6ee05..f0a41d18be53b 100644 --- a/benches/benches/bevy_ecs/iteration/iter_simple_foreach.rs +++ b/benches/benches/bevy_ecs/iteration/iter_simple_foreach.rs @@ -20,7 +20,7 @@ impl<'w> Benchmark<'w> { let mut world = World::new(); world.spawn_batch( - std::iter::repeat(( + core::iter::repeat(( Transform(Mat4::from_scale(Vec3::ONE)), Position(Vec3::X), Rotation(Vec3::X), diff --git a/benches/benches/bevy_ecs/iteration/iter_simple_foreach_sparse_set.rs b/benches/benches/bevy_ecs/iteration/iter_simple_foreach_sparse_set.rs index 3864a519b0171..0075c2706ba20 100644 --- a/benches/benches/bevy_ecs/iteration/iter_simple_foreach_sparse_set.rs +++ b/benches/benches/bevy_ecs/iteration/iter_simple_foreach_sparse_set.rs @@ -22,7 +22,7 @@ impl<'w> Benchmark<'w> { let mut world = World::new(); world.spawn_batch( - std::iter::repeat(( + core::iter::repeat(( Transform(Mat4::from_scale(Vec3::ONE)), Position(Vec3::X), Rotation(Vec3::X), diff --git a/benches/benches/bevy_ecs/iteration/iter_simple_foreach_wide.rs b/benches/benches/bevy_ecs/iteration/iter_simple_foreach_wide.rs index 284706417268e..7dbd11d1e0499 100644 --- a/benches/benches/bevy_ecs/iteration/iter_simple_foreach_wide.rs +++ b/benches/benches/bevy_ecs/iteration/iter_simple_foreach_wide.rs @@ -34,7 +34,7 @@ impl<'w> Benchmark<'w> { let mut world = World::new(); world.spawn_batch( - std::iter::repeat(( + core::iter::repeat(( Transform(Mat4::from_scale(Vec3::ONE)), Rotation(Vec3::X), Position::<0>(Vec3::X), diff --git a/benches/benches/bevy_ecs/iteration/iter_simple_foreach_wide_sparse_set.rs b/benches/benches/bevy_ecs/iteration/iter_simple_foreach_wide_sparse_set.rs index c25edcd9b8608..f520ffde42662 100644 --- a/benches/benches/bevy_ecs/iteration/iter_simple_foreach_wide_sparse_set.rs +++ b/benches/benches/bevy_ecs/iteration/iter_simple_foreach_wide_sparse_set.rs @@ -36,7 +36,7 @@ impl<'w> Benchmark<'w> { let mut world = World::new(); world.spawn_batch( - std::iter::repeat(( + core::iter::repeat(( Transform(Mat4::from_scale(Vec3::ONE)), Rotation(Vec3::X), Position::<0>(Vec3::X), diff --git a/benches/benches/bevy_ecs/iteration/iter_simple_sparse_set.rs b/benches/benches/bevy_ecs/iteration/iter_simple_sparse_set.rs index d4394b5adee60..e4ba3759412c7 100644 --- a/benches/benches/bevy_ecs/iteration/iter_simple_sparse_set.rs +++ b/benches/benches/bevy_ecs/iteration/iter_simple_sparse_set.rs @@ -22,7 +22,7 @@ impl<'w> Benchmark<'w> { let mut world = World::new(); world.spawn_batch( - std::iter::repeat(( + core::iter::repeat(( Transform(Mat4::from_scale(Vec3::ONE)), Position(Vec3::X), Rotation(Vec3::X), diff --git a/benches/benches/bevy_ecs/iteration/iter_simple_system.rs b/benches/benches/bevy_ecs/iteration/iter_simple_system.rs index e583ffc558fd7..18918ee234f9f 100644 --- a/benches/benches/bevy_ecs/iteration/iter_simple_system.rs +++ b/benches/benches/bevy_ecs/iteration/iter_simple_system.rs @@ -20,7 +20,7 @@ impl Benchmark { let mut world = World::new(); world.spawn_batch( - std::iter::repeat(( + core::iter::repeat(( Transform(Mat4::from_scale(Vec3::ONE)), Position(Vec3::X), Rotation(Vec3::X), diff --git a/benches/benches/bevy_ecs/iteration/iter_simple_wide.rs b/benches/benches/bevy_ecs/iteration/iter_simple_wide.rs index 193ca0c7fb760..7d013b3bf6003 100644 --- a/benches/benches/bevy_ecs/iteration/iter_simple_wide.rs +++ b/benches/benches/bevy_ecs/iteration/iter_simple_wide.rs @@ -34,7 +34,7 @@ impl<'w> Benchmark<'w> { let mut world = World::new(); world.spawn_batch( - std::iter::repeat(( + core::iter::repeat(( Transform(Mat4::from_scale(Vec3::ONE)), Rotation(Vec3::X), Position::<0>(Vec3::X), diff --git a/benches/benches/bevy_ecs/iteration/iter_simple_wide_sparse_set.rs b/benches/benches/bevy_ecs/iteration/iter_simple_wide_sparse_set.rs index a4cea147ac91a..28a6dbd85dc28 100644 --- a/benches/benches/bevy_ecs/iteration/iter_simple_wide_sparse_set.rs +++ b/benches/benches/bevy_ecs/iteration/iter_simple_wide_sparse_set.rs @@ -36,7 +36,7 @@ impl<'w> Benchmark<'w> { let mut world = World::new(); world.spawn_batch( - std::iter::repeat(( + core::iter::repeat(( Transform(Mat4::from_scale(Vec3::ONE)), Rotation(Vec3::X), Position::<0>(Vec3::X), diff --git a/benches/benches/bevy_ecs/iteration/mod.rs b/benches/benches/bevy_ecs/iteration/mod.rs index a5dcca441c2fe..62d8b166040dc 100644 --- a/benches/benches/bevy_ecs/iteration/mod.rs +++ b/benches/benches/bevy_ecs/iteration/mod.rs @@ -35,8 +35,8 @@ criterion_group!( fn iter_simple(c: &mut Criterion) { let mut group = c.benchmark_group("iter_simple"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + 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()); @@ -82,8 +82,8 @@ fn iter_simple(c: &mut Criterion) { fn iter_frag(c: &mut Criterion) { let mut group = c.benchmark_group("iter_fragmented"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + 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()); @@ -105,8 +105,8 @@ fn iter_frag(c: &mut Criterion) { fn iter_frag_sparse(c: &mut Criterion) { let mut group = c.benchmark_group("iter_fragmented_sparse"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + 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()); @@ -128,8 +128,8 @@ fn iter_frag_sparse(c: &mut Criterion) { fn par_iter_simple(c: &mut Criterion) { let mut group = c.benchmark_group("par_iter_simple"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + 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_{}_fragment", f), |b| { let mut bench = par_iter_simple::Benchmark::new(f); diff --git a/benches/benches/bevy_ecs/iteration/par_iter_simple.rs b/benches/benches/bevy_ecs/iteration/par_iter_simple.rs index 76489e33a84a3..dfd3f9dfdab0d 100644 --- a/benches/benches/bevy_ecs/iteration/par_iter_simple.rs +++ b/benches/benches/bevy_ecs/iteration/par_iter_simple.rs @@ -31,7 +31,7 @@ impl<'w> Benchmark<'w> { let mut world = World::new(); let iter = world.spawn_batch( - std::iter::repeat(( + core::iter::repeat(( Transform(Mat4::from_scale(Vec3::ONE)), Position(Vec3::X), Rotation(Vec3::X), diff --git a/benches/benches/bevy_ecs/observers/propagation.rs b/benches/benches/bevy_ecs/observers/propagation.rs index 4b42234f96520..b702662e7dd8c 100644 --- a/benches/benches/bevy_ecs/observers/propagation.rs +++ b/benches/benches/bevy_ecs/observers/propagation.rs @@ -22,8 +22,8 @@ fn deterministic_rand() -> ChaCha8Rng { pub fn event_propagation(criterion: &mut Criterion) { let mut group = criterion.benchmark_group("event_propagation"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + 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(); diff --git a/benches/benches/bevy_ecs/observers/simple.rs b/benches/benches/bevy_ecs/observers/simple.rs index 77457d6af2e4e..4d4d5bc2aa852 100644 --- a/benches/benches/bevy_ecs/observers/simple.rs +++ b/benches/benches/bevy_ecs/observers/simple.rs @@ -12,8 +12,8 @@ struct EventBase; pub fn observe_simple(criterion: &mut Criterion) { let mut group = criterion.benchmark_group("observe"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + group.warm_up_time(core::time::Duration::from_millis(500)); + group.measurement_time(core::time::Duration::from_secs(4)); group.bench_function("trigger_simple", |bencher| { let mut world = World::new(); diff --git a/benches/benches/bevy_ecs/scheduling/run_condition.rs b/benches/benches/bevy_ecs/scheduling/run_condition.rs index 7f0100633d8f5..1a033f36ef8b8 100644 --- a/benches/benches/bevy_ecs/scheduling/run_condition.rs +++ b/benches/benches/bevy_ecs/scheduling/run_condition.rs @@ -14,8 +14,8 @@ fn no() -> bool { 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(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(3)); + 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..21 { let mut schedule = Schedule::default(); @@ -37,8 +37,8 @@ pub fn run_condition_yes(criterion: &mut Criterion) { 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(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(3)); + 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..21 { let mut schedule = Schedule::default(); @@ -64,8 +64,8 @@ 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(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(3)); + 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: Query<&TestBool>) -> bool { query.single().0 @@ -93,8 +93,8 @@ pub fn run_condition_yes_with_resource(criterion: &mut Criterion) { let mut world = World::new(); world.insert_resource(TestBool(true)); let mut group = criterion.benchmark_group("run_condition/yes_using_resource"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(3)); + 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) -> bool { res.0 diff --git a/benches/benches/bevy_ecs/scheduling/running_systems.rs b/benches/benches/bevy_ecs/scheduling/running_systems.rs index 6d5d0ed3df566..d2ea51307f87f 100644 --- a/benches/benches/bevy_ecs/scheduling/running_systems.rs +++ b/benches/benches/bevy_ecs/scheduling/running_systems.rs @@ -17,8 +17,8 @@ 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(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(3)); + 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..5 { let mut schedule = Schedule::default(); @@ -50,23 +50,23 @@ pub fn empty_systems(criterion: &mut Criterion) { 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)| { - std::mem::swap(&mut a.0, &mut b.0); + 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)| { - std::mem::swap(&mut c.0, &mut d.0); + 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)| { - std::mem::swap(&mut c.0, &mut e.0); + 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(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(3)); + group.warm_up_time(core::time::Duration::from_millis(500)); + group.measurement_time(core::time::Duration::from_secs(3)); for entity_bunches in 1..6 { 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)))); @@ -99,26 +99,26 @@ pub fn busy_systems(criterion: &mut Criterion) { 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)| { - std::mem::swap(&mut c_0.0, &mut c_1.0); + 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)| { - std::mem::swap(&mut c_0.0, &mut c_1.0); + core::mem::swap(&mut c_0.0, &mut c_1.0); }); q_1.iter_mut().for_each(|(mut c_0, mut c_1)| { - std::mem::swap(&mut c_0.0, &mut c_1.0); + 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)| { - std::mem::swap(&mut c_0.0, &mut c_1.0); + 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(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(3)); + group.warm_up_time(core::time::Duration::from_millis(500)); + group.measurement_time(core::time::Duration::from_secs(3)); for entity_bunches in 1..6 { 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)))); diff --git a/benches/benches/bevy_ecs/scheduling/schedule.rs b/benches/benches/bevy_ecs/scheduling/schedule.rs index 0930d8e122b0f..4571899a9b7b5 100644 --- a/benches/benches/bevy_ecs/scheduling/schedule.rs +++ b/benches/benches/bevy_ecs/scheduling/schedule.rs @@ -16,25 +16,25 @@ pub fn schedule(c: &mut Criterion) { fn ab(mut query: Query<(&mut A, &mut B)>) { query.iter_mut().for_each(|(mut a, mut b)| { - std::mem::swap(&mut a.0, &mut b.0); + 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)| { - std::mem::swap(&mut c.0, &mut d.0); + 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)| { - std::mem::swap(&mut c.0, &mut e.0); + core::mem::swap(&mut c.0, &mut e.0); }); } let mut group = c.benchmark_group("schedule"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + 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(); @@ -68,8 +68,8 @@ pub fn build_schedule(criterion: &mut Criterion) { struct DummySet; let mut group = criterion.benchmark_group("build_schedule"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(15)); + 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 diff --git a/benches/benches/bevy_ecs/world/commands.rs b/benches/benches/bevy_ecs/world/commands.rs index e27ccbe17285c..5f2f8a01f5213 100644 --- a/benches/benches/bevy_ecs/world/commands.rs +++ b/benches/benches/bevy_ecs/world/commands.rs @@ -15,8 +15,8 @@ struct C; pub fn empty_commands(criterion: &mut Criterion) { let mut group = criterion.benchmark_group("empty_commands"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + 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(); @@ -32,8 +32,8 @@ pub fn empty_commands(criterion: &mut Criterion) { pub fn spawn_commands(criterion: &mut Criterion) { let mut group = criterion.benchmark_group("spawn_commands"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + group.warm_up_time(core::time::Duration::from_millis(500)); + group.measurement_time(core::time::Duration::from_secs(4)); for entity_count in (1..5).map(|i| i * 2 * 1000) { group.bench_function(format!("{}_entities", entity_count), |bencher| { @@ -69,8 +69,8 @@ struct Vec3([f32; 3]); pub fn insert_commands(criterion: &mut Criterion) { let mut group = criterion.benchmark_group("insert_commands"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + 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| { @@ -132,8 +132,8 @@ impl Command for FakeCommandB { pub fn fake_commands(criterion: &mut Criterion) { let mut group = criterion.benchmark_group("fake_commands"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + group.warm_up_time(core::time::Duration::from_millis(500)); + group.measurement_time(core::time::Duration::from_secs(4)); for command_count in (1..5).map(|i| i * 2 * 1000) { group.bench_function(format!("{}_commands", command_count), |bencher| { @@ -177,8 +177,8 @@ impl Default for LargeStruct { pub fn sized_commands_impl(criterion: &mut Criterion) { let mut group = criterion.benchmark_group(format!("sized_commands_{}_bytes", size_of::())); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + group.warm_up_time(core::time::Duration::from_millis(500)); + group.measurement_time(core::time::Duration::from_secs(4)); for command_count in (1..5).map(|i| i * 2 * 1000) { group.bench_function(format!("{}_commands", command_count), |bencher| { @@ -212,8 +212,8 @@ pub fn large_sized_commands(criterion: &mut Criterion) { pub fn get_or_spawn(criterion: &mut Criterion) { let mut group = criterion.benchmark_group("get_or_spawn"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + group.warm_up_time(core::time::Duration::from_millis(500)); + group.measurement_time(core::time::Duration::from_secs(4)); group.bench_function("individual", |bencher| { let mut world = World::default(); diff --git a/benches/benches/bevy_ecs/world/entity_hash.rs b/benches/benches/bevy_ecs/world/entity_hash.rs index c337e9d86a401..3bd148d90da63 100644 --- a/benches/benches/bevy_ecs/world/entity_hash.rs +++ b/benches/benches/bevy_ecs/world/entity_hash.rs @@ -33,7 +33,7 @@ pub fn entity_set_build_and_lookup(c: &mut Criterion) { // 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(std::iter::repeat_with(|| make_entity(&mut rng, size)).take(size)); + 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| { diff --git a/benches/benches/bevy_ecs/world/spawn.rs b/benches/benches/bevy_ecs/world/spawn.rs index 0404209eaace2..0777a20cb9827 100644 --- a/benches/benches/bevy_ecs/world/spawn.rs +++ b/benches/benches/bevy_ecs/world/spawn.rs @@ -9,8 +9,8 @@ struct B(Vec4); pub fn world_spawn(criterion: &mut Criterion) { let mut group = criterion.benchmark_group("spawn_world"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + group.warm_up_time(core::time::Duration::from_millis(500)); + group.measurement_time(core::time::Duration::from_secs(4)); for entity_count in (0..5).map(|i| 10_u32.pow(i)) { group.bench_function(format!("{}_entities", entity_count), |bencher| { diff --git a/benches/benches/bevy_ecs/world/world_get.rs b/benches/benches/bevy_ecs/world/world_get.rs index 4812d44f6bca6..4c235cd1b46e3 100644 --- a/benches/benches/bevy_ecs/world/world_get.rs +++ b/benches/benches/bevy_ecs/world/world_get.rs @@ -22,7 +22,7 @@ struct WideTable(f32); #[component(storage = "SparseSet")] struct WideSparse(f32); -const RANGE: std::ops::Range = 5..6; +const RANGE: core::ops::Range = 5..6; fn deterministic_rand() -> ChaCha8Rng { ChaCha8Rng::seed_from_u64(42) @@ -42,8 +42,8 @@ fn setup_wide(entity_count: u32) -> World { pub fn world_entity(criterion: &mut Criterion) { let mut group = criterion.benchmark_group("world_entity"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + 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!("{}_entities", entity_count), |bencher| { @@ -63,8 +63,8 @@ pub fn world_entity(criterion: &mut Criterion) { pub fn world_get(criterion: &mut Criterion) { let mut group = criterion.benchmark_group("world_get"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + 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!("{}_entities_table", entity_count), |bencher| { @@ -94,8 +94,8 @@ pub fn world_get(criterion: &mut Criterion) { pub fn world_query_get(criterion: &mut Criterion) { let mut group = criterion.benchmark_group("world_query_get"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + 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!("{}_entities_table", entity_count), |bencher| { @@ -180,8 +180,8 @@ pub fn world_query_get(criterion: &mut Criterion) { pub fn world_query_iter(criterion: &mut Criterion) { let mut group = criterion.benchmark_group("world_query_iter"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + 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!("{}_entities_table", entity_count), |bencher| { @@ -219,8 +219,8 @@ pub fn world_query_iter(criterion: &mut Criterion) { pub fn world_query_for_each(criterion: &mut Criterion) { let mut group = criterion.benchmark_group("world_query_for_each"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + 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!("{}_entities_table", entity_count), |bencher| { @@ -258,8 +258,8 @@ pub fn world_query_for_each(criterion: &mut Criterion) { pub fn query_get(criterion: &mut Criterion) { let mut group = criterion.benchmark_group("query_get"); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(4)); + 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!("{}_entities_table", entity_count), |bencher| { @@ -307,8 +307,8 @@ pub fn query_get(criterion: &mut Criterion) { pub fn query_get_many(criterion: &mut Criterion) { let mut group = criterion.benchmark_group(&format!("query_get_many_{N}")); - group.warm_up_time(std::time::Duration::from_millis(500)); - group.measurement_time(std::time::Duration::from_secs(2 * N as u64)); + 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!("{}_calls_table", entity_count), |bencher| { diff --git a/benches/benches/bevy_reflect/list.rs b/benches/benches/bevy_reflect/list.rs index 0c366e0540557..e5fffaa3cddf0 100644 --- a/benches/benches/bevy_reflect/list.rs +++ b/benches/benches/bevy_reflect/list.rs @@ -1,4 +1,4 @@ -use std::{iter, time::Duration}; +use core::{iter, time::Duration}; use bevy_reflect::{DynamicList, List}; use criterion::{ diff --git a/benches/benches/bevy_reflect/map.rs b/benches/benches/bevy_reflect/map.rs index b27a096d3d072..ae3894881358e 100644 --- a/benches/benches/bevy_reflect/map.rs +++ b/benches/benches/bevy_reflect/map.rs @@ -1,4 +1,4 @@ -use std::{fmt::Write, iter, time::Duration}; +use core::{fmt::Write, iter, time::Duration}; use bevy_reflect::{DynamicMap, Map}; use bevy_utils::HashMap; diff --git a/benches/benches/bevy_reflect/path.rs b/benches/benches/bevy_reflect/path.rs index bc9af799d44cc..f18885132ac3f 100644 --- a/benches/benches/bevy_reflect/path.rs +++ b/benches/benches/bevy_reflect/path.rs @@ -1,4 +1,4 @@ -use std::{fmt::Write, str, time::Duration}; +use core::{fmt::Write, str, time::Duration}; use bevy_reflect::ParsedPath; use criterion::{ diff --git a/benches/benches/bevy_reflect/struct.rs b/benches/benches/bevy_reflect/struct.rs index 9c6163d24d3a3..0a38088666f84 100644 --- a/benches/benches/bevy_reflect/struct.rs +++ b/benches/benches/bevy_reflect/struct.rs @@ -1,4 +1,4 @@ -use std::time::Duration; +use core::time::Duration; use bevy_reflect::{DynamicStruct, GetField, PartialReflect, Reflect, Struct}; use criterion::{ diff --git a/benches/benches/bevy_tasks/iter.rs b/benches/benches/bevy_tasks/iter.rs index ee1babf4e2f46..3d4410926cf11 100644 --- a/benches/benches/bevy_tasks/iter.rs +++ b/benches/benches/bevy_tasks/iter.rs @@ -1,22 +1,22 @@ use bevy_tasks::{ParallelIterator, TaskPoolBuilder}; use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion}; -struct ParChunks<'a, T>(std::slice::Chunks<'a, T>); -impl<'a, T> ParallelIterator> for ParChunks<'a, T> +struct ParChunks<'a, T>(core::slice::Chunks<'a, T>); +impl<'a, T> ParallelIterator> for ParChunks<'a, T> where T: 'a + Send + Sync, { - fn next_batch(&mut self) -> Option> { + fn next_batch(&mut self) -> Option> { self.0.next().map(|s| s.iter()) } } -struct ParChunksMut<'a, T>(std::slice::ChunksMut<'a, T>); -impl<'a, T> ParallelIterator> for ParChunksMut<'a, T> +struct ParChunksMut<'a, T>(core::slice::ChunksMut<'a, T>); +impl<'a, T> ParallelIterator> for ParChunksMut<'a, T> where T: 'a + Send + Sync, { - fn next_batch(&mut self) -> Option> { + fn next_batch(&mut self) -> Option> { self.0.next().map(|s| s.iter_mut()) } } diff --git a/crates/bevy_a11y/src/lib.rs b/crates/bevy_a11y/src/lib.rs index 66b5d333bedde..f73a529f33e0b 100644 --- a/crates/bevy_a11y/src/lib.rs +++ b/crates/bevy_a11y/src/lib.rs @@ -7,10 +7,10 @@ //! Accessibility for Bevy -use std::sync::{ - atomic::{AtomicBool, Ordering}, - Arc, -}; +extern crate alloc; + +use alloc::sync::Arc; +use core::sync::atomic::{AtomicBool, Ordering}; pub use accesskit; use accesskit::NodeBuilder; @@ -21,8 +21,7 @@ use bevy_ecs::{ schedule::SystemSet, system::Resource, }; -use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; +use bevy_reflect::{std_traits::ReflectDefault, Reflect}; /// Wrapper struct for [`accesskit::ActionRequest`]. Required to allow it to be used as an `Event`. #[derive(Event, Deref, DerefMut)] diff --git a/crates/bevy_animation/src/graph.rs b/crates/bevy_animation/src/graph.rs index 6f04ca794f958..1ce683409a3f9 100644 --- a/crates/bevy_animation/src/graph.rs +++ b/crates/bevy_animation/src/graph.rs @@ -1,7 +1,7 @@ //! The animation graph, which allows animations to be blended together. +use core::ops::{Index, IndexMut}; use std::io::{self, Write}; -use std::ops::{Index, IndexMut}; use bevy_asset::{io::Reader, Asset, AssetId, AssetLoader, AssetPath, Handle, LoadContext}; use bevy_reflect::{Reflect, ReflectSerialize}; diff --git a/crates/bevy_animation/src/keyframes.rs b/crates/bevy_animation/src/keyframes.rs index f2694930c0be7..f754df977399a 100644 --- a/crates/bevy_animation/src/keyframes.rs +++ b/crates/bevy_animation/src/keyframes.rs @@ -1,7 +1,9 @@ //! Keyframes of animation clips. -use std::any::TypeId; -use std::fmt::{self, Debug, Formatter}; +use core::{ + any::TypeId, + fmt::{self, Debug, Formatter}, +}; use bevy_asset::Handle; use bevy_derive::{Deref, DerefMut}; diff --git a/crates/bevy_animation/src/lib.rs b/crates/bevy_animation/src/lib.rs index 837accc6fa02c..2b22f099c7acd 100755 --- a/crates/bevy_animation/src/lib.rs +++ b/crates/bevy_animation/src/lib.rs @@ -7,18 +7,21 @@ //! Animation for the game engine Bevy +extern crate alloc; + pub mod animatable; pub mod graph; pub mod keyframes; pub mod transition; mod util; -use std::any::{Any, TypeId}; -use std::cell::RefCell; -use std::collections::BTreeMap; -use std::fmt::Debug; -use std::hash::{Hash, Hasher}; -use std::iter; +use alloc::collections::BTreeMap; +use core::{ + any::{Any, TypeId}, + cell::RefCell, + hash::{Hash, Hasher}, + iter, +}; use bevy_app::{App, Plugin, PostUpdate}; use bevy_asset::{Asset, AssetApp, Assets, Handle}; diff --git a/crates/bevy_app/src/app.rs b/crates/bevy_app/src/app.rs index b0d223662bba7..0c5950bbb1fdf 100644 --- a/crates/bevy_app/src/app.rs +++ b/crates/bevy_app/src/app.rs @@ -13,14 +13,11 @@ use bevy_ecs::{ #[cfg(feature = "trace")] use bevy_utils::tracing::info_span; use bevy_utils::{tracing::debug, HashMap}; +use core::{fmt::Debug, num::NonZero, panic::AssertUnwindSafe}; use std::{ - fmt::Debug, + panic::{catch_unwind, resume_unwind}, process::{ExitCode, Termination}, }; -use std::{ - num::NonZero, - panic::{catch_unwind, resume_unwind, AssertUnwindSafe}, -}; use thiserror::Error; bevy_ecs::define_label!( @@ -79,7 +76,7 @@ pub struct App { } impl Debug for App { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "App {{ sub_apps: ")?; f.debug_map() .entries(self.sub_apps.sub_apps.iter()) @@ -167,8 +164,8 @@ impl App { panic!("App::run() was called while a plugin was building."); } - let runner = std::mem::replace(&mut self.runner, Box::new(run_once)); - let app = std::mem::replace(self, App::empty()); + let runner = core::mem::replace(&mut self.runner, Box::new(run_once)); + let app = core::mem::replace(self, App::empty()); (runner)(app) } @@ -212,7 +209,7 @@ impl App { let mut overall_plugins_state = match self.main_mut().plugins_state { PluginsState::Adding => { let mut state = PluginsState::Ready; - let plugins = std::mem::take(&mut self.main_mut().plugin_registry); + let plugins = core::mem::take(&mut self.main_mut().plugin_registry); for plugin in &plugins { // plugins installed to main need to see all sub-apps if !plugin.ready(self) { @@ -238,7 +235,7 @@ impl App { /// plugins are ready, but can be useful for situations where you want to use [`App::update`]. pub fn finish(&mut self) { // plugins installed to main should see all sub-apps - let plugins = std::mem::take(&mut self.main_mut().plugin_registry); + let plugins = core::mem::take(&mut self.main_mut().plugin_registry); for plugin in &plugins { plugin.finish(self); } @@ -252,7 +249,7 @@ impl App { /// [`App::finish`], but can be useful for situations where you want to use [`App::update`]. pub fn cleanup(&mut self) { // plugins installed to main should see all sub-apps - let plugins = std::mem::take(&mut self.main_mut().plugin_registry); + let plugins = core::mem::take(&mut self.main_mut().plugin_registry); for plugin in &plugins { plugin.cleanup(self); } @@ -746,7 +743,7 @@ impl App { #[cfg(feature = "reflect_functions")] pub fn register_function_with_name( &mut self, - name: impl Into>, + name: impl Into>, function: F, ) -> &mut Self where @@ -1118,7 +1115,8 @@ impl Termination for AppExit { #[cfg(test)] mod tests { - use std::{iter, marker::PhantomData, sync::Mutex}; + use core::{iter, marker::PhantomData}; + use std::sync::Mutex; use bevy_ecs::{ change_detection::{DetectChanges, ResMut}, diff --git a/crates/bevy_app/src/lib.rs b/crates/bevy_app/src/lib.rs index 8ea7c0e767566..830772803bec0 100644 --- a/crates/bevy_app/src/lib.rs +++ b/crates/bevy_app/src/lib.rs @@ -7,6 +7,8 @@ //! This crate is about everything concerning the highest-level, application layer of a Bevy app. +extern crate alloc; + mod app; mod main_schedule; mod panic_handler; diff --git a/crates/bevy_app/src/panic_handler.rs b/crates/bevy_app/src/panic_handler.rs index 94bb1c206cb76..56d66da7281b2 100644 --- a/crates/bevy_app/src/panic_handler.rs +++ b/crates/bevy_app/src/panic_handler.rs @@ -6,8 +6,7 @@ //! For more fine-tuned control over panic behavior, disable the [`PanicHandlerPlugin`] or //! `DefaultPlugins` during app initialization. -use crate::App; -use crate::Plugin; +use crate::{App, Plugin}; /// Adds sensible panic handlers to Apps. This plugin is part of the `DefaultPlugins`. Adding /// this plugin will setup a panic hook appropriate to your target platform: diff --git a/crates/bevy_app/src/plugin.rs b/crates/bevy_app/src/plugin.rs index 23b5be13e13d2..0659c6a311884 100644 --- a/crates/bevy_app/src/plugin.rs +++ b/crates/bevy_app/src/plugin.rs @@ -1,7 +1,7 @@ use downcast_rs::{impl_downcast, Downcast}; use crate::App; -use std::any::Any; +use core::any::Any; /// A collection of Bevy app logic and configuration. /// @@ -82,7 +82,7 @@ pub trait Plugin: Downcast + Any + Send + Sync { /// Configures a name for the [`Plugin`] which is primarily used for checking plugin /// uniqueness and debugging. fn name(&self) -> &str { - std::any::type_name::() + core::any::type_name::() } /// If the plugin can be meaningfully instantiated several times in an [`App`], diff --git a/crates/bevy_app/src/plugin_group.rs b/crates/bevy_app/src/plugin_group.rs index 28c90ff5ef1ca..ab9fd7c607e2c 100644 --- a/crates/bevy_app/src/plugin_group.rs +++ b/crates/bevy_app/src/plugin_group.rs @@ -1,6 +1,9 @@ use crate::{App, AppError, Plugin}; -use bevy_utils::{tracing::debug, tracing::warn, TypeIdMap}; -use std::any::TypeId; +use bevy_utils::{ + tracing::{debug, warn}, + TypeIdMap, +}; +use core::any::TypeId; /// A macro for generating a well-documented [`PluginGroup`] from a list of [`Plugin`] paths. /// @@ -160,7 +163,7 @@ pub trait PluginGroup: Sized { fn build(self) -> PluginGroupBuilder; /// Configures a name for the [`PluginGroup`] which is primarily used for debugging. fn name() -> String { - std::any::type_name::().to_string() + core::any::type_name::().to_string() } /// Sets the value of the given [`Plugin`], if it exists fn set(self, plugin: T) -> PluginGroupBuilder { @@ -215,7 +218,7 @@ impl PluginGroupBuilder { Some(i) => i, None => panic!( "Plugin does not exist in group: {}.", - std::any::type_name::() + core::any::type_name::() ), } } @@ -269,7 +272,7 @@ impl PluginGroupBuilder { let entry = self.plugins.get_mut(&TypeId::of::()).unwrap_or_else(|| { panic!( "{} does not exist in this PluginGroup", - std::any::type_name::(), + core::any::type_name::(), ) }); entry.plugin = Box::new(plugin); @@ -433,9 +436,9 @@ mod tests { assert_eq!( group.order, vec![ - std::any::TypeId::of::(), - std::any::TypeId::of::(), - std::any::TypeId::of::(), + core::any::TypeId::of::(), + core::any::TypeId::of::(), + core::any::TypeId::of::(), ] ); } @@ -450,9 +453,9 @@ mod tests { assert_eq!( group.order, vec![ - std::any::TypeId::of::(), - std::any::TypeId::of::(), - std::any::TypeId::of::(), + core::any::TypeId::of::(), + core::any::TypeId::of::(), + core::any::TypeId::of::(), ] ); } @@ -467,9 +470,9 @@ mod tests { assert_eq!( group.order, vec![ - std::any::TypeId::of::(), - std::any::TypeId::of::(), - std::any::TypeId::of::(), + core::any::TypeId::of::(), + core::any::TypeId::of::(), + core::any::TypeId::of::(), ] ); } @@ -485,9 +488,9 @@ mod tests { assert_eq!( group.order, vec![ - std::any::TypeId::of::(), - std::any::TypeId::of::(), - std::any::TypeId::of::(), + core::any::TypeId::of::(), + core::any::TypeId::of::(), + core::any::TypeId::of::(), ] ); } @@ -503,9 +506,9 @@ mod tests { assert_eq!( group.order, vec![ - std::any::TypeId::of::(), - std::any::TypeId::of::(), - std::any::TypeId::of::(), + core::any::TypeId::of::(), + core::any::TypeId::of::(), + core::any::TypeId::of::(), ] ); } @@ -521,9 +524,9 @@ mod tests { assert_eq!( group.order, vec![ - std::any::TypeId::of::(), - std::any::TypeId::of::(), - std::any::TypeId::of::(), + core::any::TypeId::of::(), + core::any::TypeId::of::(), + core::any::TypeId::of::(), ] ); } @@ -541,9 +544,9 @@ mod tests { assert_eq!( group_b.order, vec![ - std::any::TypeId::of::(), - std::any::TypeId::of::(), - std::any::TypeId::of::(), + core::any::TypeId::of::(), + core::any::TypeId::of::(), + core::any::TypeId::of::(), ] ); } @@ -565,9 +568,9 @@ mod tests { assert_eq!( group.order, vec![ - std::any::TypeId::of::(), - std::any::TypeId::of::(), - std::any::TypeId::of::(), + core::any::TypeId::of::(), + core::any::TypeId::of::(), + core::any::TypeId::of::(), ] ); } diff --git a/crates/bevy_app/src/schedule_runner.rs b/crates/bevy_app/src/schedule_runner.rs index 1d697ca00eb37..01c43fde6f2ae 100644 --- a/crates/bevy_app/src/schedule_runner.rs +++ b/crates/bevy_app/src/schedule_runner.rs @@ -6,9 +6,11 @@ use crate::{ use bevy_utils::{Duration, Instant}; #[cfg(target_arch = "wasm32")] -use std::{cell::RefCell, rc::Rc}; -#[cfg(target_arch = "wasm32")] -use wasm_bindgen::{prelude::*, JsCast}; +use { + alloc::rc::Rc, + core::cell::RefCell, + wasm_bindgen::{prelude::*, JsCast}, +}; /// Determines the method used to run an [`App`]'s [`Schedule`](bevy_ecs::schedule::Schedule). /// diff --git a/crates/bevy_app/src/sub_app.rs b/crates/bevy_app/src/sub_app.rs index e0d6f86f80650..901ce891a4a62 100644 --- a/crates/bevy_app/src/sub_app.rs +++ b/crates/bevy_app/src/sub_app.rs @@ -9,7 +9,7 @@ use bevy_ecs::{ #[cfg(feature = "trace")] use bevy_utils::tracing::info_span; use bevy_utils::{HashMap, HashSet}; -use std::fmt::Debug; +use core::fmt::Debug; type ExtractFn = Box; @@ -75,7 +75,7 @@ pub struct SubApp { } impl Debug for SubApp { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "SubApp") } } @@ -109,9 +109,9 @@ impl SubApp { F: FnOnce(&mut App), { let mut app = App::empty(); - std::mem::swap(self, &mut app.sub_apps.main); + core::mem::swap(self, &mut app.sub_apps.main); f(&mut app); - std::mem::swap(self, &mut app.sub_apps.main); + core::mem::swap(self, &mut app.sub_apps.main); } /// Returns a reference to the [`World`]. @@ -327,7 +327,7 @@ impl SubApp { where T: Plugin, { - self.plugin_names.contains(std::any::type_name::()) + self.plugin_names.contains(core::any::type_name::()) } /// See [`App::get_added_plugins`]. @@ -352,7 +352,7 @@ impl SubApp { match self.plugins_state { PluginsState::Adding => { let mut state = PluginsState::Ready; - let plugins = std::mem::take(&mut self.plugin_registry); + let plugins = core::mem::take(&mut self.plugin_registry); self.run_as_app(|app| { for plugin in &plugins { if !plugin.ready(app) { @@ -370,7 +370,7 @@ impl SubApp { /// Runs [`Plugin::finish`] for each plugin. pub fn finish(&mut self) { - let plugins = std::mem::take(&mut self.plugin_registry); + let plugins = core::mem::take(&mut self.plugin_registry); self.run_as_app(|app| { for plugin in &plugins { plugin.finish(app); @@ -382,7 +382,7 @@ impl SubApp { /// Runs [`Plugin::cleanup`] for each plugin. pub fn cleanup(&mut self) { - let plugins = std::mem::take(&mut self.plugin_registry); + let plugins = core::mem::take(&mut self.plugin_registry); self.run_as_app(|app| { for plugin in &plugins { plugin.cleanup(app); @@ -428,7 +428,7 @@ impl SubApp { #[cfg(feature = "reflect_functions")] pub fn register_function_with_name( &mut self, - name: impl Into>, + name: impl Into>, function: F, ) -> &mut Self where @@ -472,12 +472,12 @@ impl SubApps { /// Returns an iterator over the sub-apps (starting with the main one). pub fn iter(&self) -> impl Iterator + '_ { - std::iter::once(&self.main).chain(self.sub_apps.values()) + core::iter::once(&self.main).chain(self.sub_apps.values()) } /// Returns a mutable iterator over the sub-apps (starting with the main one). pub fn iter_mut(&mut self) -> impl Iterator + '_ { - std::iter::once(&mut self.main).chain(self.sub_apps.values_mut()) + core::iter::once(&mut self.main).chain(self.sub_apps.values_mut()) } /// Extract data from the main world into the [`SubApp`] with the given label and perform an update if it exists. diff --git a/crates/bevy_app/src/terminal_ctrl_c_handler.rs b/crates/bevy_app/src/terminal_ctrl_c_handler.rs index 8bd90ffaa62b3..b42fb47f6f676 100644 --- a/crates/bevy_app/src/terminal_ctrl_c_handler.rs +++ b/crates/bevy_app/src/terminal_ctrl_c_handler.rs @@ -1,4 +1,4 @@ -use std::sync::atomic::{AtomicBool, Ordering}; +use core::sync::atomic::{AtomicBool, Ordering}; use bevy_ecs::event::EventWriter; diff --git a/crates/bevy_asset/src/assets.rs b/crates/bevy_asset/src/assets.rs index 5a0dfcf824905..3c33aa43faf91 100644 --- a/crates/bevy_asset/src/assets.rs +++ b/crates/bevy_asset/src/assets.rs @@ -1,19 +1,17 @@ -use crate::{self as bevy_asset}; -use crate::{Asset, AssetEvent, AssetHandleProvider, AssetId, AssetServer, Handle, UntypedHandle}; +use crate::{ + self as bevy_asset, Asset, AssetEvent, AssetHandleProvider, AssetId, AssetServer, Handle, + UntypedHandle, +}; +use alloc::sync::Arc; use bevy_ecs::{ prelude::EventWriter, system::{Res, ResMut, Resource}, }; use bevy_reflect::{Reflect, TypePath}; use bevy_utils::HashMap; +use core::{any::TypeId, iter::Enumerate, marker::PhantomData, sync::atomic::AtomicU32}; use crossbeam_channel::{Receiver, Sender}; use serde::{Deserialize, Serialize}; -use std::{ - any::TypeId, - iter::Enumerate, - marker::PhantomData, - sync::{atomic::AtomicU32, Arc}, -}; use thiserror::Error; use uuid::Uuid; @@ -81,7 +79,7 @@ impl AssetIndexAllocator { AssetIndex { index: self .next_index - .fetch_add(1, std::sync::atomic::Ordering::Relaxed), + .fetch_add(1, core::sync::atomic::Ordering::Relaxed), generation: 0, } } @@ -236,7 +234,7 @@ impl DenseAssetStorage { let new_len = self .allocator .next_index - .load(std::sync::atomic::Ordering::Relaxed); + .load(core::sync::atomic::Ordering::Relaxed); self.storage.resize_with(new_len as usize, || Entry::Some { value: None, generation: 0, @@ -577,7 +575,7 @@ impl Assets { /// A mutable iterator over [`Assets`]. pub struct AssetsMutIterator<'a, A: Asset> { queued_events: &'a mut Vec>, - dense_storage: Enumerate>>, + dense_storage: Enumerate>>, hash_map: bevy_utils::hashbrown::hash_map::IterMut<'a, Uuid, A>, } diff --git a/crates/bevy_asset/src/event.rs b/crates/bevy_asset/src/event.rs index f049751bb79c3..406d2398ea287 100644 --- a/crates/bevy_asset/src/event.rs +++ b/crates/bevy_asset/src/event.rs @@ -1,6 +1,6 @@ use crate::{Asset, AssetId, AssetLoadError, AssetPath, UntypedAssetId}; use bevy_ecs::event::Event; -use std::fmt::Debug; +use core::fmt::Debug; /// An event emitted when a specific [`Asset`] fails to load. /// @@ -92,7 +92,7 @@ impl Clone for AssetEvent { impl Copy for AssetEvent {} impl Debug for AssetEvent { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { Self::Added { id } => f.debug_struct("Added").field("id", id).finish(), Self::Modified { id } => f.debug_struct("Modified").field("id", id).finish(), diff --git a/crates/bevy_asset/src/handle.rs b/crates/bevy_asset/src/handle.rs index 6371b7e01ba0f..08e10e8e620bf 100644 --- a/crates/bevy_asset/src/handle.rs +++ b/crates/bevy_asset/src/handle.rs @@ -2,15 +2,15 @@ use crate::{ meta::MetaTransform, Asset, AssetId, AssetIndexAllocator, AssetPath, InternalAssetId, UntypedAssetId, }; +use alloc::sync::Arc; use bevy_ecs::prelude::*; use bevy_reflect::{std_traits::ReflectDefault, Reflect, TypePath}; -use crossbeam_channel::{Receiver, Sender}; -use disqualified::ShortName; -use std::{ +use core::{ any::TypeId, hash::{Hash, Hasher}, - sync::Arc, }; +use crossbeam_channel::{Receiver, Sender}; +use disqualified::ShortName; use thiserror::Error; use uuid::Uuid; @@ -103,8 +103,8 @@ impl Drop for StrongHandle { } } -impl std::fmt::Debug for StrongHandle { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for StrongHandle { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("StrongHandle") .field("id", &self.id) .field("asset_server_managed", &self.asset_server_managed) @@ -204,8 +204,8 @@ impl Default for Handle { } } -impl std::fmt::Debug for Handle { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for Handle { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { let name = ShortName::of::(); match self { Handle::Strong(handle) => { @@ -229,13 +229,13 @@ impl Hash for Handle { } impl PartialOrd for Handle { - fn partial_cmp(&self, other: &Self) -> Option { + fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Ord for Handle { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { + fn cmp(&self, other: &Self) -> core::cmp::Ordering { self.id().cmp(&other.id()) } } @@ -357,7 +357,7 @@ impl UntypedHandle { let Ok(handle) = self.try_typed() else { panic!( "The target Handle<{}>'s TypeId does not match the TypeId of this UntypedHandle", - std::any::type_name::() + core::any::type_name::() ) }; @@ -397,8 +397,8 @@ impl Hash for UntypedHandle { } } -impl std::fmt::Debug for UntypedHandle { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for UntypedHandle { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { UntypedHandle::Strong(handle) => { write!( @@ -420,7 +420,7 @@ impl std::fmt::Debug for UntypedHandle { } impl PartialOrd for UntypedHandle { - fn partial_cmp(&self, other: &Self) -> Option { + fn partial_cmp(&self, other: &Self) -> Option { if self.type_id() == other.type_id() { self.id().partial_cmp(&other.id()) } else { @@ -454,7 +454,7 @@ impl PartialEq> for UntypedHandle { impl PartialOrd for Handle { #[inline] - fn partial_cmp(&self, other: &UntypedHandle) -> Option { + fn partial_cmp(&self, other: &UntypedHandle) -> Option { if TypeId::of::() != other.type_id() { None } else { @@ -465,7 +465,7 @@ impl PartialOrd for Handle { impl PartialOrd> for UntypedHandle { #[inline] - fn partial_cmp(&self, other: &Handle) -> Option { + fn partial_cmp(&self, other: &Handle) -> Option { Some(other.partial_cmp(self)?.reverse()) } } diff --git a/crates/bevy_asset/src/id.rs b/crates/bevy_asset/src/id.rs index c4b48a06d6cee..710d526373769 100644 --- a/crates/bevy_asset/src/id.rs +++ b/crates/bevy_asset/src/id.rs @@ -3,7 +3,7 @@ use bevy_reflect::Reflect; use serde::{Deserialize, Serialize}; use uuid::Uuid; -use std::{ +use core::{ any::TypeId, fmt::{Debug, Display}, hash::Hash, @@ -86,19 +86,19 @@ impl Clone for AssetId { impl Copy for AssetId {} impl Display for AssetId { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { Debug::fmt(self, f) } } impl Debug for AssetId { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { AssetId::Index { index, .. } => { write!( f, "AssetId<{}>{{ index: {}, generation: {}}}", - std::any::type_name::(), + core::any::type_name::(), index.index, index.generation ) @@ -107,7 +107,7 @@ impl Debug for AssetId { write!( f, "AssetId<{}>{{uuid: {}}}", - std::any::type_name::(), + core::any::type_name::(), uuid ) } @@ -117,7 +117,7 @@ impl Debug for AssetId { impl Hash for AssetId { #[inline] - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { self.internal().hash(state); TypeId::of::().hash(state); } @@ -133,13 +133,13 @@ impl PartialEq for AssetId { impl Eq for AssetId {} impl PartialOrd for AssetId { - fn partial_cmp(&self, other: &Self) -> Option { + fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Ord for AssetId { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { + fn cmp(&self, other: &Self) -> core::cmp::Ordering { self.internal().cmp(&other.internal()) } } @@ -206,7 +206,7 @@ impl UntypedAssetId { self.type_id(), TypeId::of::(), "The target AssetId<{}>'s TypeId does not match the TypeId of this UntypedAssetId", - std::any::type_name::() + core::any::type_name::() ); self.typed_unchecked() } @@ -221,7 +221,7 @@ impl UntypedAssetId { let Ok(id) = self.try_typed() else { panic!( "The target AssetId<{}>'s TypeId does not match the TypeId of this UntypedAssetId", - std::any::type_name::() + core::any::type_name::() ) }; @@ -254,7 +254,7 @@ impl UntypedAssetId { } impl Display for UntypedAssetId { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { let mut writer = f.debug_struct("UntypedAssetId"); match self { UntypedAssetId::Index { index, type_id } => { @@ -282,14 +282,14 @@ impl Eq for UntypedAssetId {} impl Hash for UntypedAssetId { #[inline] - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { self.internal().hash(state); self.type_id().hash(state); } } impl Ord for UntypedAssetId { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { + fn cmp(&self, other: &Self) -> core::cmp::Ordering { self.type_id() .cmp(&other.type_id()) .then_with(|| self.internal().cmp(&other.internal())) @@ -297,7 +297,7 @@ impl Ord for UntypedAssetId { } impl PartialOrd for UntypedAssetId { - fn partial_cmp(&self, other: &Self) -> Option { + fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } @@ -366,7 +366,7 @@ impl PartialEq> for UntypedAssetId { impl PartialOrd for AssetId { #[inline] - fn partial_cmp(&self, other: &UntypedAssetId) -> Option { + fn partial_cmp(&self, other: &UntypedAssetId) -> Option { if TypeId::of::() != other.type_id() { None } else { @@ -377,7 +377,7 @@ impl PartialOrd for AssetId { impl PartialOrd> for UntypedAssetId { #[inline] - fn partial_cmp(&self, other: &AssetId) -> Option { + fn partial_cmp(&self, other: &AssetId) -> Option { Some(other.partial_cmp(self)?.reverse()) } } @@ -435,7 +435,7 @@ mod tests { /// Simple utility to directly hash a value using a fixed hasher fn hash(data: &T) -> u64 { - use std::hash::Hasher; + use core::hash::Hasher; let mut hasher = bevy_utils::AHasher::default(); data.hash(&mut hasher); diff --git a/crates/bevy_asset/src/io/android.rs b/crates/bevy_asset/src/io/android.rs index 1890a943c82b1..08c964eb88fef 100644 --- a/crates/bevy_asset/src/io/android.rs +++ b/crates/bevy_asset/src/io/android.rs @@ -2,7 +2,8 @@ use crate::io::{ get_meta_path, AssetReader, AssetReaderError, EmptyPathStream, PathStream, Reader, VecReader, }; use bevy_utils::tracing::error; -use std::{ffi::CString, path::Path}; +use core::ffi::CString; +use std::path::Path; /// [`AssetReader`] implementation for Android devices, built on top of Android's [`AssetManager`]. /// @@ -52,10 +53,7 @@ impl AssetReader for AndroidAssetReader { Ok(stream) } - async fn is_directory<'a>( - &'a self, - _path: &'a Path, - ) -> std::result::Result { + async fn is_directory<'a>(&'a self, _path: &'a Path) -> Result { error!("Reading directories is not supported with the AndroidAssetReader"); Ok(false) } diff --git a/crates/bevy_asset/src/io/embedded/embedded_watcher.rs b/crates/bevy_asset/src/io/embedded/embedded_watcher.rs index 485593599c489..dd863d7cf9285 100644 --- a/crates/bevy_asset/src/io/embedded/embedded_watcher.rs +++ b/crates/bevy_asset/src/io/embedded/embedded_watcher.rs @@ -3,15 +3,14 @@ use crate::io::{ memory::Dir, AssetSourceEvent, AssetWatcher, }; -use bevy_utils::tracing::warn; -use bevy_utils::{Duration, HashMap}; +use alloc::sync::Arc; +use bevy_utils::{tracing::warn, Duration, HashMap}; use notify_debouncer_full::{notify::RecommendedWatcher, Debouncer, FileIdMap}; use parking_lot::RwLock; use std::{ fs::File, io::{BufReader, Read}, path::{Path, PathBuf}, - sync::Arc, }; /// A watcher for assets stored in the `embedded` asset source. Embedded assets are assets whose diff --git a/crates/bevy_asset/src/io/embedded/mod.rs b/crates/bevy_asset/src/io/embedded/mod.rs index b521d3737be5c..af8176d5a0d79 100644 --- a/crates/bevy_asset/src/io/embedded/mod.rs +++ b/crates/bevy_asset/src/io/embedded/mod.rs @@ -22,7 +22,7 @@ pub const EMBEDDED: &str = "embedded"; pub struct EmbeddedAssetRegistry { dir: Dir, #[cfg(feature = "embedded_watcher")] - root_paths: std::sync::Arc, PathBuf>>>, + root_paths: alloc::sync::Arc, PathBuf>>>, } impl EmbeddedAssetRegistry { @@ -107,7 +107,7 @@ impl EmbeddedAssetRegistry { dir.clone(), root_paths.clone(), sender, - std::time::Duration::from_millis(300), + core::time::Duration::from_millis(300), ))) }) .with_processed_watcher(move |sender| { @@ -115,7 +115,7 @@ impl EmbeddedAssetRegistry { processed_dir.clone(), processed_root_paths.clone(), sender, - std::time::Duration::from_millis(300), + core::time::Duration::from_millis(300), ))) }); } diff --git a/crates/bevy_asset/src/io/file/file_watcher.rs b/crates/bevy_asset/src/io/file/file_watcher.rs index 12793b738b93c..1da55fae97607 100644 --- a/crates/bevy_asset/src/io/file/file_watcher.rs +++ b/crates/bevy_asset/src/io/file/file_watcher.rs @@ -1,7 +1,8 @@ -use crate::io::{AssetSourceEvent, AssetWatcher}; -use crate::path::normalize_path; -use bevy_utils::tracing::error; -use bevy_utils::Duration; +use crate::{ + io::{AssetSourceEvent, AssetWatcher}, + path::normalize_path, +}; +use bevy_utils::{tracing::error, Duration}; use crossbeam_channel::Sender; use notify_debouncer_full::{ new_debouncer, diff --git a/crates/bevy_asset/src/io/file/mod.rs b/crates/bevy_asset/src/io/file/mod.rs index 92f99af42e185..387924001f5fd 100644 --- a/crates/bevy_asset/src/io/file/mod.rs +++ b/crates/bevy_asset/src/io/file/mod.rs @@ -73,7 +73,7 @@ impl FileAssetWriter { /// watching for changes. /// /// See `get_base_path` below. - pub fn new + std::fmt::Debug>(path: P, create_root: bool) -> Self { + pub fn new + core::fmt::Debug>(path: P, create_root: bool) -> Self { let root_path = get_base_path().join(path.as_ref()); if create_root { if let Err(e) = std::fs::create_dir_all(&root_path) { diff --git a/crates/bevy_asset/src/io/file/sync_file_asset.rs b/crates/bevy_asset/src/io/file/sync_file_asset.rs index 2ac547e9b7136..188257ddc1006 100644 --- a/crates/bevy_asset/src/io/file/sync_file_asset.rs +++ b/crates/bevy_asset/src/io/file/sync_file_asset.rs @@ -6,12 +6,11 @@ use crate::io::{ Reader, Writer, }; +use core::{pin::Pin, task::Poll}; use std::{ fs::{read_dir, File}, io::{Read, Seek, Write}, path::{Path, PathBuf}, - pin::Pin, - task::Poll, }; use super::{FileAssetReader, FileAssetWriter}; @@ -21,7 +20,7 @@ struct FileReader(File); impl AsyncRead for FileReader { fn poll_read( self: Pin<&mut Self>, - _cx: &mut std::task::Context<'_>, + _cx: &mut core::task::Context<'_>, buf: &mut [u8], ) -> Poll> { let this = self.get_mut(); @@ -33,7 +32,7 @@ impl AsyncRead for FileReader { impl AsyncSeek for FileReader { fn poll_seek( self: Pin<&mut Self>, - _cx: &mut std::task::Context<'_>, + _cx: &mut core::task::Context<'_>, pos: std::io::SeekFrom, ) -> Poll> { let this = self.get_mut(); @@ -57,7 +56,7 @@ struct FileWriter(File); impl AsyncWrite for FileWriter { fn poll_write( self: Pin<&mut Self>, - _cx: &mut std::task::Context<'_>, + _cx: &mut core::task::Context<'_>, buf: &[u8], ) -> Poll> { let this = self.get_mut(); @@ -67,7 +66,7 @@ impl AsyncWrite for FileWriter { fn poll_flush( self: Pin<&mut Self>, - _cx: &mut std::task::Context<'_>, + _cx: &mut core::task::Context<'_>, ) -> Poll> { let this = self.get_mut(); let flushed = this.0.flush(); @@ -76,7 +75,7 @@ impl AsyncWrite for FileWriter { fn poll_close( self: Pin<&mut Self>, - _cx: &mut std::task::Context<'_>, + _cx: &mut core::task::Context<'_>, ) -> Poll> { Poll::Ready(Ok(())) } @@ -89,7 +88,7 @@ impl Stream for DirReader { fn poll_next( self: Pin<&mut Self>, - _cx: &mut std::task::Context<'_>, + _cx: &mut core::task::Context<'_>, ) -> Poll> { let this = self.get_mut(); Poll::Ready(this.0.pop()) diff --git a/crates/bevy_asset/src/io/gated.rs b/crates/bevy_asset/src/io/gated.rs index 1f6e783ce8fbd..cb205f12a81bd 100644 --- a/crates/bevy_asset/src/io/gated.rs +++ b/crates/bevy_asset/src/io/gated.rs @@ -1,8 +1,9 @@ use crate::io::{AssetReader, AssetReaderError, PathStream, Reader}; +use alloc::sync::Arc; use bevy_utils::HashMap; use crossbeam_channel::{Receiver, Sender}; use parking_lot::RwLock; -use std::{path::Path, sync::Arc}; +use std::path::Path; /// A "gated" reader that will prevent asset reads from returning until /// a given path has been "opened" using [`GateOpener`]. diff --git a/crates/bevy_asset/src/io/memory.rs b/crates/bevy_asset/src/io/memory.rs index a3707e9b139c4..4164d9bbe906b 100644 --- a/crates/bevy_asset/src/io/memory.rs +++ b/crates/bevy_asset/src/io/memory.rs @@ -1,14 +1,13 @@ use crate::io::{AssetReader, AssetReaderError, PathStream, Reader}; +use alloc::sync::Arc; use bevy_utils::HashMap; +use core::{pin::Pin, task::Poll}; use futures_io::{AsyncRead, AsyncSeek}; use futures_lite::{ready, Stream}; use parking_lot::RwLock; -use std::io::SeekFrom; use std::{ + io::SeekFrom, path::{Path, PathBuf}, - pin::Pin, - sync::Arc, - task::Poll, }; #[derive(Default, Debug)] @@ -153,7 +152,7 @@ impl Stream for DirStream { fn poll_next( self: Pin<&mut Self>, - _cx: &mut std::task::Context<'_>, + _cx: &mut core::task::Context<'_>, ) -> Poll> { let this = self.get_mut(); let dir = this.dir.0.read(); @@ -234,7 +233,7 @@ struct DataReader { impl AsyncRead for DataReader { fn poll_read( mut self: Pin<&mut Self>, - cx: &mut std::task::Context<'_>, + cx: &mut core::task::Context<'_>, buf: &mut [u8], ) -> Poll> { if self.bytes_read >= self.data.value().len() { @@ -251,7 +250,7 @@ impl AsyncRead for DataReader { impl AsyncSeek for DataReader { fn poll_seek( mut self: Pin<&mut Self>, - _cx: &mut std::task::Context<'_>, + _cx: &mut core::task::Context<'_>, pos: SeekFrom, ) -> Poll> { let result = match pos { diff --git a/crates/bevy_asset/src/io/mod.rs b/crates/bevy_asset/src/io/mod.rs index 4a8815c4012c2..aafa4f1f04990 100644 --- a/crates/bevy_asset/src/io/mod.rs +++ b/crates/bevy_asset/src/io/mod.rs @@ -21,15 +21,18 @@ mod source; pub use futures_lite::AsyncWriteExt; pub use source::*; +use alloc::sync::Arc; use bevy_utils::{BoxedFuture, ConditionalSendFuture}; +use core::{ + mem::size_of, + pin::Pin, + task::{Context, Poll}, +}; use futures_io::{AsyncRead, AsyncSeek, AsyncWrite}; use futures_lite::{ready, Stream}; use std::{ io::SeekFrom, path::{Path, PathBuf}, - pin::Pin, - sync::Arc, - task::{Context, Poll}, }; use thiserror::Error; @@ -713,7 +716,7 @@ impl Stream for EmptyPathStream { fn poll_next( self: Pin<&mut Self>, - _cx: &mut std::task::Context<'_>, + _cx: &mut core::task::Context<'_>, ) -> Poll> { Poll::Ready(None) } diff --git a/crates/bevy_asset/src/io/processor_gated.rs b/crates/bevy_asset/src/io/processor_gated.rs index a77c7877970a8..963af9fd51556 100644 --- a/crates/bevy_asset/src/io/processor_gated.rs +++ b/crates/bevy_asset/src/io/processor_gated.rs @@ -3,12 +3,12 @@ use crate::{ processor::{AssetProcessorData, ProcessStatus}, AssetPath, }; +use alloc::sync::Arc; use async_lock::RwLockReadGuardArc; use bevy_utils::tracing::trace; +use core::{pin::Pin, task::Poll}; use futures_io::{AsyncRead, AsyncSeek}; -use std::io::SeekFrom; -use std::task::Poll; -use std::{path::Path, pin::Pin, sync::Arc}; +use std::{io::SeekFrom, path::Path}; use super::ErasedAssetReader; @@ -135,7 +135,7 @@ impl<'a> TransactionLockedReader<'a> { impl AsyncRead for TransactionLockedReader<'_> { fn poll_read( mut self: Pin<&mut Self>, - cx: &mut std::task::Context<'_>, + cx: &mut core::task::Context<'_>, buf: &mut [u8], ) -> Poll> { Pin::new(&mut self.reader).poll_read(cx, buf) @@ -145,7 +145,7 @@ impl AsyncRead for TransactionLockedReader<'_> { impl AsyncSeek for TransactionLockedReader<'_> { fn poll_seek( mut self: Pin<&mut Self>, - cx: &mut std::task::Context<'_>, + cx: &mut core::task::Context<'_>, pos: SeekFrom, ) -> Poll> { Pin::new(&mut self.reader).poll_seek(cx, pos) diff --git a/crates/bevy_asset/src/io/source.rs b/crates/bevy_asset/src/io/source.rs index 0a53caa23c288..4af5b377d28c8 100644 --- a/crates/bevy_asset/src/io/source.rs +++ b/crates/bevy_asset/src/io/source.rs @@ -2,11 +2,14 @@ use crate::{ io::{processor_gated::ProcessorGatedReader, AssetSourceEvent, AssetWatcher}, processor::AssetProcessorData, }; +use alloc::sync::Arc; use atomicow::CowArc; use bevy_ecs::system::Resource; -use bevy_utils::tracing::{error, warn}; -use bevy_utils::{Duration, HashMap}; -use std::{fmt::Display, hash::Hash, sync::Arc}; +use bevy_utils::{ + tracing::{error, warn}, + Duration, HashMap, +}; +use core::{fmt::Display, hash::Hash}; use thiserror::Error; use super::{ErasedAssetReader, ErasedAssetWriter}; @@ -25,7 +28,7 @@ pub enum AssetSourceId<'a> { } impl<'a> Display for AssetSourceId<'a> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self.as_str() { None => write!(f, "AssetSourceId::Default"), Some(v) => write!(f, "AssetSourceId::Name({v})"), @@ -112,7 +115,7 @@ impl From for AssetSourceId<'static> { } impl<'a> Hash for AssetSourceId<'a> { - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { self.as_str().hash(state); } } diff --git a/crates/bevy_asset/src/io/wasm.rs b/crates/bevy_asset/src/io/wasm.rs index 6378556fe0e1c..65eb852c257a2 100644 --- a/crates/bevy_asset/src/io/wasm.rs +++ b/crates/bevy_asset/src/io/wasm.rs @@ -106,10 +106,7 @@ impl AssetReader for HttpWasmAssetReader { Ok(stream) } - async fn is_directory<'a>( - &'a self, - _path: &'a Path, - ) -> std::result::Result { + async fn is_directory<'a>(&'a self, _path: &'a Path) -> Result { error!("Reading directories is not supported with the HttpWasmAssetReader"); Ok(false) } diff --git a/crates/bevy_asset/src/lib.rs b/crates/bevy_asset/src/lib.rs index 6220af7c019c2..df5879609d676 100644 --- a/crates/bevy_asset/src/lib.rs +++ b/crates/bevy_asset/src/lib.rs @@ -147,6 +147,8 @@ html_favicon_url = "https://bevyengine.org/assets/icon.png" )] +extern crate alloc; + pub mod io; pub mod meta; pub mod processor; @@ -199,6 +201,7 @@ use crate::{ io::{embedded::EmbeddedAssetRegistry, AssetSourceBuilder, AssetSourceBuilders, AssetSourceId}, processor::{AssetProcessor, Process}, }; +use alloc::sync::Arc; use bevy_app::{App, Last, Plugin, PreUpdate}; use bevy_ecs::{ reflect::AppTypeRegistry, @@ -207,7 +210,7 @@ use bevy_ecs::{ }; use bevy_reflect::{FromReflect, GetTypeRegistration, Reflect, TypePath}; use bevy_utils::{tracing::error, HashSet}; -use std::{any::TypeId, sync::Arc}; +use core::any::TypeId; #[cfg(all(feature = "file_watcher", not(feature = "multi_threaded")))] compile_error!( @@ -615,18 +618,19 @@ mod tests { AssetPlugin, AssetServer, Assets, DependencyLoadState, LoadState, RecursiveDependencyLoadState, }; + use alloc::sync::Arc; use bevy_app::{App, Update}; use bevy_core::TaskPoolPlugin; - use bevy_ecs::prelude::*; use bevy_ecs::{ event::EventCursor, + prelude::*, schedule::{LogLevel, ScheduleBuildSettings}, }; use bevy_log::LogPlugin; use bevy_reflect::TypePath; use bevy_utils::{Duration, HashMap}; use serde::{Deserialize, Serialize}; - use std::{path::Path, sync::Arc}; + use std::path::Path; use thiserror::Error; #[derive(Asset, TypePath, Debug, Default)] @@ -1487,7 +1491,7 @@ mod tests { ); // remove event is emitted app.update(); - let events = std::mem::take(&mut app.world_mut().resource_mut::().0); + let events = core::mem::take(&mut app.world_mut().resource_mut::().0); let expected_events = vec![ AssetEvent::Added { id }, AssetEvent::Unused { id }, @@ -1508,14 +1512,14 @@ mod tests { // TODO: ideally it doesn't take two updates for the added event to emit app.update(); - let events = std::mem::take(&mut app.world_mut().resource_mut::().0); + let events = core::mem::take(&mut app.world_mut().resource_mut::().0); let expected_events = vec![AssetEvent::Added { id: a_handle.id() }]; assert_eq!(events, expected_events); gate_opener.open(dep_path); loop { app.update(); - let events = std::mem::take(&mut app.world_mut().resource_mut::().0); + let events = core::mem::take(&mut app.world_mut().resource_mut::().0); if events.is_empty() { continue; } @@ -1529,7 +1533,7 @@ mod tests { break; } app.update(); - let events = std::mem::take(&mut app.world_mut().resource_mut::().0); + let events = core::mem::take(&mut app.world_mut().resource_mut::().0); let expected_events = vec![AssetEvent::Added { id: dep_handle.id(), }]; diff --git a/crates/bevy_asset/src/loader.rs b/crates/bevy_asset/src/loader.rs index 401c7db6097bb..1bcb5a304b2ca 100644 --- a/crates/bevy_asset/src/loader.rs +++ b/crates/bevy_asset/src/loader.rs @@ -9,13 +9,11 @@ use crate::{ use atomicow::CowArc; use bevy_ecs::world::World; use bevy_utils::{BoxedFuture, ConditionalSendFuture, HashMap, HashSet}; +use core::any::{Any, TypeId}; use downcast_rs::{impl_downcast, Downcast}; use ron::error::SpannedError; use serde::{Deserialize, Serialize}; -use std::{ - any::{Any, TypeId}, - path::{Path, PathBuf}, -}; +use std::path::{Path, PathBuf}; use thiserror::Error; /// Loads an [`Asset`] from a given byte [`Reader`]. This can accept [`AssetLoader::Settings`], which configure how the [`Asset`] @@ -30,7 +28,7 @@ pub trait AssetLoader: Send + Sync + 'static { /// The settings type used by this [`AssetLoader`]. type Settings: Settings + Default + Serialize + for<'a> Deserialize<'a>; /// The type of [error](`std::error::Error`) which could be encountered by this loader. - type Error: Into>; + type Error: Into>; /// Asynchronously loads [`AssetLoader::Asset`] (and any other labeled assets) from the bytes provided by [`Reader`]. fn load<'a>( &'a self, @@ -56,7 +54,7 @@ pub trait ErasedAssetLoader: Send + Sync + 'static { load_context: LoadContext<'a>, ) -> BoxedFuture< 'a, - Result>, + Result>, >; /// Returns a list of extensions supported by this asset loader, without the preceding dot. @@ -87,7 +85,7 @@ where mut load_context: LoadContext<'a>, ) -> BoxedFuture< 'a, - Result>, + Result>, > { Box::pin(async move { let settings = meta @@ -119,7 +117,7 @@ where } fn type_name(&self) -> &'static str { - std::any::type_name::() + core::any::type_name::() } fn type_id(&self) -> TypeId { @@ -127,7 +125,7 @@ where } fn asset_type_name(&self) -> &'static str { - std::any::type_name::() + core::any::type_name::() } fn asset_type_id(&self) -> TypeId { @@ -288,7 +286,7 @@ impl AssetContainer for A { } fn asset_type_name(&self) -> &'static str { - std::any::type_name::() + core::any::type_name::() } } diff --git a/crates/bevy_asset/src/loader_builders.rs b/crates/bevy_asset/src/loader_builders.rs index 27609a411e4cb..23cf722803546 100644 --- a/crates/bevy_asset/src/loader_builders.rs +++ b/crates/bevy_asset/src/loader_builders.rs @@ -7,8 +7,8 @@ use crate::{ Asset, AssetLoadError, AssetPath, ErasedAssetLoader, ErasedLoadedAsset, Handle, LoadContext, LoadDirectError, LoadedAsset, LoadedUntypedAsset, }; -use std::any::TypeId; -use std::sync::Arc; +use alloc::sync::Arc; +use core::any::TypeId; // Utility type for handling the sources of reader references enum ReaderRef<'a> { diff --git a/crates/bevy_asset/src/meta.rs b/crates/bevy_asset/src/meta.rs index b0a7a9cab0e65..53c1db824d578 100644 --- a/crates/bevy_asset/src/meta.rs +++ b/crates/bevy_asset/src/meta.rs @@ -1,5 +1,7 @@ -use crate::{self as bevy_asset, DeserializeMetaError, VisitAssetDependencies}; -use crate::{loader::AssetLoader, processor::Process, Asset, AssetPath}; +use crate::{ + self as bevy_asset, loader::AssetLoader, processor::Process, Asset, AssetPath, + DeserializeMetaError, VisitAssetDependencies, +}; use bevy_utils::tracing::error; use downcast_rs::{impl_downcast, Downcast}; use ron::ser::PrettyConfig; @@ -218,7 +220,7 @@ pub(crate) fn meta_transform_settings( } else { error!( "Configured settings type {} does not match AssetLoader settings type", - std::any::type_name::(), + core::any::type_name::(), ); } } diff --git a/crates/bevy_asset/src/path.rs b/crates/bevy_asset/src/path.rs index d52bdc02dd6e0..3bbb643650b6f 100644 --- a/crates/bevy_asset/src/path.rs +++ b/crates/bevy_asset/src/path.rs @@ -1,13 +1,13 @@ use crate::io::AssetSourceId; use atomicow::CowArc; use bevy_reflect::{Reflect, ReflectDeserialize, ReflectSerialize}; -use serde::{de::Visitor, Deserialize, Serialize}; -use std::{ +use core::{ fmt::{Debug, Display}, hash::Hash, ops::Deref, - path::{Path, PathBuf}, }; +use serde::{de::Visitor, Deserialize, Serialize}; +use std::path::{Path, PathBuf}; use thiserror::Error; /// Represents a path to an asset in a "virtual filesystem". @@ -57,13 +57,13 @@ pub struct AssetPath<'a> { } impl<'a> Debug for AssetPath<'a> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { Display::fmt(self, f) } } impl<'a> Display for AssetPath<'a> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { if let AssetSourceId::Name(name) = self.source() { write!(f, "{name}://")?; } @@ -588,7 +588,7 @@ struct AssetPathVisitor; impl<'de> Visitor<'de> for AssetPathVisitor { type Value = AssetPath<'static>; - fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result { formatter.write_str("string AssetPath") } diff --git a/crates/bevy_asset/src/processor/log.rs b/crates/bevy_asset/src/processor/log.rs index 64207295e751b..dd23ca4cb91c8 100644 --- a/crates/bevy_asset/src/processor/log.rs +++ b/crates/bevy_asset/src/processor/log.rs @@ -1,7 +1,6 @@ use crate::AssetPath; use async_fs::File; -use bevy_utils::tracing::error; -use bevy_utils::HashSet; +use bevy_utils::{tracing::error, HashSet}; use futures_lite::{AsyncReadExt, AsyncWriteExt}; use std::path::PathBuf; use thiserror::Error; diff --git a/crates/bevy_asset/src/processor/mod.rs b/crates/bevy_asset/src/processor/mod.rs index 7188f9dab4960..f9fd23f0b71b7 100644 --- a/crates/bevy_asset/src/processor/mod.rs +++ b/crates/bevy_asset/src/processor/mod.rs @@ -56,23 +56,22 @@ use crate::{ AssetLoadError, AssetMetaCheck, AssetPath, AssetServer, AssetServerMode, DeserializeMetaError, MissingAssetLoaderForExtensionError, }; +use alloc::{collections::VecDeque, sync::Arc}; use bevy_ecs::prelude::*; use bevy_tasks::IoTaskPool; -use bevy_utils::tracing::{debug, error, trace, warn}; +use bevy_utils::{ + tracing::{debug, error, trace, warn}, + HashMap, HashSet, +}; #[cfg(feature = "trace")] use bevy_utils::{ tracing::{info_span, instrument::Instrument}, ConditionalSendFuture, }; -use bevy_utils::{HashMap, HashSet}; use futures_io::ErrorKind; use futures_lite::{AsyncReadExt, AsyncWriteExt, StreamExt}; use parking_lot::RwLock; -use std::{ - collections::VecDeque, - path::{Path, PathBuf}, - sync::Arc, -}; +use std::path::{Path, PathBuf}; use thiserror::Error; /// A "background" asset processor that reads asset values from a source [`AssetSource`] (which corresponds to an [`AssetReader`](crate::io::AssetReader) / [`AssetWriter`](crate::io::AssetWriter) pair), @@ -505,7 +504,7 @@ impl AssetProcessor { async fn try_reprocessing_queued(&self) { loop { let mut check_reprocess_queue = - std::mem::take(&mut self.data.asset_infos.write().await.check_reprocess_queue); + core::mem::take(&mut self.data.asset_infos.write().await.check_reprocess_queue); IoTaskPool::get().scope(|scope| { for path in check_reprocess_queue.drain(..) { let processor = self.clone(); @@ -527,13 +526,13 @@ impl AssetProcessor { let mut process_plans = self.data.processors.write(); #[cfg(feature = "trace")] let processor = InstrumentedAssetProcessor(processor); - process_plans.insert(std::any::type_name::

(), Arc::new(processor)); + process_plans.insert(core::any::type_name::

(), Arc::new(processor)); } /// Set the default processor for the given `extension`. Make sure `P` is registered with [`AssetProcessor::register_processor`]. pub fn set_default_processor(&self, extension: &str) { let mut default_processors = self.data.default_processors.write(); - default_processors.insert(extension.into(), std::any::type_name::

()); + default_processors.insert(extension.into(), core::any::type_name::

()); } /// Returns the default processor for the given `extension`, if it exists. @@ -944,7 +943,7 @@ impl AssetProcessor { } LogEntryError::UnfinishedTransaction(path) => { debug!("Asset {path:?} did not finish processing. Clearing state for that asset"); - let mut unrecoverable_err = |message: &dyn std::fmt::Display| { + let mut unrecoverable_err = |message: &dyn core::fmt::Display| { error!("Failed to remove asset {path:?}: {message}"); state_is_valid = false; }; @@ -1110,7 +1109,7 @@ impl Process for InstrumentedAssetProcessor { }; let span = info_span!( "asset processing", - processor = std::any::type_name::(), + processor = core::any::type_name::(), asset = context.path().to_string(), ); self.0.process(context, meta, writer).instrument(span) @@ -1348,7 +1347,7 @@ impl ProcessorAssetInfos { info.dependants ); self.non_existent_dependants - .insert(old.clone(), std::mem::take(&mut info.dependants)); + .insert(old.clone(), core::mem::take(&mut info.dependants)); } if let Some(processed_info) = &info.processed_info { // Update "dependant" lists for this asset's "process dependencies" to use new path. diff --git a/crates/bevy_asset/src/processor/process.rs b/crates/bevy_asset/src/processor/process.rs index 92a13f21ff44e..108b7ffc8d2e6 100644 --- a/crates/bevy_asset/src/processor/process.rs +++ b/crates/bevy_asset/src/processor/process.rs @@ -1,20 +1,18 @@ -use crate::io::SliceReader; -use crate::transformer::IdentityAssetTransformer; use crate::{ io::{ AssetReaderError, AssetWriterError, MissingAssetWriterError, - MissingProcessedAssetReaderError, MissingProcessedAssetWriterError, Writer, + MissingProcessedAssetReaderError, MissingProcessedAssetWriterError, SliceReader, Writer, }, meta::{AssetAction, AssetMeta, AssetMetaDyn, ProcessDependencyInfo, ProcessedInfo, Settings}, processor::AssetProcessor, saver::{AssetSaver, SavedAsset}, - transformer::{AssetTransformer, TransformedAsset}, + transformer::{AssetTransformer, IdentityAssetTransformer, TransformedAsset}, AssetLoadError, AssetLoader, AssetPath, DeserializeMetaError, ErasedLoadedAsset, MissingAssetLoaderForExtensionError, MissingAssetLoaderForTypeNameError, }; use bevy_utils::{BoxedFuture, ConditionalSendFuture}; +use core::marker::PhantomData; use serde::{Deserialize, Serialize}; -use std::marker::PhantomData; use thiserror::Error; /// Asset "processor" logic that reads input asset bytes (stored on [`ProcessContext`]), processes the value in some way, @@ -164,9 +162,9 @@ pub enum ProcessError { #[error("The wrong meta type was passed into a processor. This is probably an internal implementation error.")] WrongMetaType, #[error("Encountered an error while saving the asset: {0}")] - AssetSaveError(#[from] Box), + AssetSaveError(#[from] Box), #[error("Encountered an error while transforming the asset: {0}")] - AssetTransformError(Box), + AssetTransformError(Box), #[error("Assets without extensions are not supported.")] ExtensionRequired, } @@ -191,7 +189,7 @@ where return Err(ProcessError::WrongMetaType); }; let loader_meta = AssetMeta::::new(AssetAction::Load { - loader: std::any::type_name::().to_string(), + loader: core::any::type_name::().to_string(), settings: settings.loader_settings, }); let pre_transformed_asset = TransformedAsset::::from_loaded( @@ -248,7 +246,7 @@ impl ErasedProcessor for P { let loader_settings =

::process(self, context, *meta, writer).await?; let output_meta: Box = Box::new(AssetMeta::::new(AssetAction::Load { - loader: std::any::type_name::().to_string(), + loader: core::any::type_name::().to_string(), settings: loader_settings, })); Ok(output_meta) @@ -262,7 +260,7 @@ impl ErasedProcessor for P { fn default_meta(&self) -> Box { Box::new(AssetMeta::<(), P>::new(AssetAction::Process { - processor: std::any::type_name::

().to_string(), + processor: core::any::type_name::

().to_string(), settings: P::Settings::default(), })) } @@ -318,7 +316,7 @@ impl<'a> ProcessContext<'a> { meta: AssetMeta, ) -> Result { let server = &self.processor.server; - let loader_name = std::any::type_name::(); + let loader_name = core::any::type_name::(); let loader = server.get_asset_loader_with_type_name(loader_name).await?; let mut reader = SliceReader::new(self.asset_bytes); let loaded_asset = server diff --git a/crates/bevy_asset/src/reflect.rs b/crates/bevy_asset/src/reflect.rs index 468300887bfbe..3aaa1580bb110 100644 --- a/crates/bevy_asset/src/reflect.rs +++ b/crates/bevy_asset/src/reflect.rs @@ -1,4 +1,4 @@ -use std::any::{Any, TypeId}; +use core::any::{Any, TypeId}; use bevy_ecs::world::{unsafe_world_cell::UnsafeWorldCell, World}; use bevy_reflect::{FromReflect, FromType, PartialReflect, Reflect}; @@ -243,7 +243,7 @@ impl FromType> for ReflectHandle { #[cfg(test)] mod tests { - use std::any::TypeId; + use core::any::TypeId; use crate as bevy_asset; use crate::{Asset, AssetApp, AssetPlugin, ReflectAsset, UntypedHandle}; diff --git a/crates/bevy_asset/src/saver.rs b/crates/bevy_asset/src/saver.rs index 115a88037764b..19955cd62f397 100644 --- a/crates/bevy_asset/src/saver.rs +++ b/crates/bevy_asset/src/saver.rs @@ -1,10 +1,11 @@ -use crate::transformer::TransformedAsset; -use crate::{io::Writer, meta::Settings, Asset, ErasedLoadedAsset}; -use crate::{AssetLoader, Handle, LabeledAsset, UntypedHandle}; +use crate::{ + io::Writer, meta::Settings, transformer::TransformedAsset, Asset, AssetLoader, + ErasedLoadedAsset, Handle, LabeledAsset, UntypedHandle, +}; use atomicow::CowArc; use bevy_utils::{BoxedFuture, ConditionalSendFuture, HashMap}; +use core::{borrow::Borrow, hash::Hash, ops::Deref}; use serde::{Deserialize, Serialize}; -use std::{borrow::Borrow, hash::Hash, ops::Deref}; /// Saves an [`Asset`] of a given [`AssetSaver::Asset`] type. [`AssetSaver::OutputLoader`] will then be used to load the saved asset /// in the final deployed application. The saver should produce asset bytes in a format that [`AssetSaver::OutputLoader`] can read. @@ -20,7 +21,7 @@ pub trait AssetSaver: Send + Sync + 'static { /// The type of [`AssetLoader`] used to load this [`Asset`] type OutputLoader: AssetLoader; /// The type of [error](`std::error::Error`) which could be encountered by this saver. - type Error: Into>; + type Error: Into>; /// Saves the given runtime [`Asset`] by writing it to a byte format using `writer`. The passed in `settings` can influence how the /// `asset` is saved. @@ -43,7 +44,7 @@ pub trait ErasedAssetSaver: Send + Sync + 'static { writer: &'a mut Writer, asset: &'a ErasedLoadedAsset, settings: &'a dyn Settings, - ) -> BoxedFuture<'a, Result<(), Box>>; + ) -> BoxedFuture<'a, Result<(), Box>>; /// The type name of the [`AssetSaver`]. fn type_name(&self) -> &'static str; @@ -55,7 +56,7 @@ impl ErasedAssetSaver for S { writer: &'a mut Writer, asset: &'a ErasedLoadedAsset, settings: &'a dyn Settings, - ) -> BoxedFuture<'a, Result<(), Box>> { + ) -> BoxedFuture<'a, Result<(), Box>> { Box::pin(async move { let settings = settings .downcast_ref::() @@ -68,7 +69,7 @@ impl ErasedAssetSaver for S { }) } fn type_name(&self) -> &'static str { - std::any::type_name::() + core::any::type_name::() } } diff --git a/crates/bevy_asset/src/server/info.rs b/crates/bevy_asset/src/server/info.rs index b8e6840c1f0cf..1371d0fe02837 100644 --- a/crates/bevy_asset/src/server/info.rs +++ b/crates/bevy_asset/src/server/info.rs @@ -4,15 +4,12 @@ use crate::{ Handle, InternalAssetEvent, LoadState, RecursiveDependencyLoadState, StrongHandle, UntypedAssetId, UntypedHandle, }; +use alloc::sync::{Arc, Weak}; use bevy_ecs::world::World; use bevy_tasks::Task; -use bevy_utils::tracing::warn; -use bevy_utils::{Entry, HashMap, HashSet, TypeIdMap}; +use bevy_utils::{tracing::warn, Entry, HashMap, HashSet, TypeIdMap}; +use core::any::TypeId; use crossbeam_channel::Sender; -use std::{ - any::TypeId, - sync::{Arc, Weak}, -}; use thiserror::Error; #[derive(Debug)] @@ -80,8 +77,8 @@ pub(crate) struct AssetInfos { pub(crate) pending_tasks: HashMap>, } -impl std::fmt::Debug for AssetInfos { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for AssetInfos { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("AssetInfos") .field("path_to_id", &self.path_to_id) .field("infos", &self.infos) @@ -165,7 +162,7 @@ impl AssetInfos { ); // it is ok to unwrap because TypeId was specified above let (handle, should_load) = - unwrap_with_context(result, std::any::type_name::()).unwrap(); + unwrap_with_context(result, core::any::type_name::()).unwrap(); (handle.typed_unchecked(), should_load) } @@ -500,7 +497,7 @@ impl AssetInfos { rec_dep_load_state, RecursiveDependencyLoadState::Loaded | RecursiveDependencyLoadState::Failed(_) ) { - Some(std::mem::take( + Some(core::mem::take( &mut info.dependants_waiting_on_recursive_dep_load, )) } else { @@ -508,7 +505,7 @@ impl AssetInfos { }; ( - std::mem::take(&mut info.dependants_waiting_on_load), + core::mem::take(&mut info.dependants_waiting_on_load), dependants_waiting_on_rec_load, ) }; @@ -561,7 +558,7 @@ impl AssetInfos { .send(InternalAssetEvent::LoadedWithDependencies { id: waiting_id }) .unwrap(); } - Some(std::mem::take( + Some(core::mem::take( &mut info.dependants_waiting_on_recursive_dep_load, )) } else { @@ -589,7 +586,7 @@ impl AssetInfos { info.loading_rec_dependencies.remove(&failed_id); info.failed_rec_dependencies.insert(failed_id); info.rec_dep_load_state = RecursiveDependencyLoadState::Failed(error.clone()); - Some(std::mem::take( + Some(core::mem::take( &mut info.dependants_waiting_on_recursive_dep_load, )) } else { @@ -619,8 +616,8 @@ impl AssetInfos { info.dep_load_state = DependencyLoadState::Failed(error.clone()); info.rec_dep_load_state = RecursiveDependencyLoadState::Failed(error.clone()); ( - std::mem::take(&mut info.dependants_waiting_on_load), - std::mem::take(&mut info.dependants_waiting_on_recursive_dep_load), + core::mem::take(&mut info.dependants_waiting_on_load), + core::mem::take(&mut info.dependants_waiting_on_recursive_dep_load), ) }; diff --git a/crates/bevy_asset/src/server/loaders.rs b/crates/bevy_asset/src/server/loaders.rs index b0ecba7ae3f1d..64d26d43951bb 100644 --- a/crates/bevy_asset/src/server/loaders.rs +++ b/crates/bevy_asset/src/server/loaders.rs @@ -2,16 +2,19 @@ use crate::{ loader::{AssetLoader, ErasedAssetLoader}, path::AssetPath, }; +use alloc::sync::Arc; use async_broadcast::RecvError; use bevy_tasks::IoTaskPool; -use bevy_utils::tracing::{error, warn}; +use bevy_utils::{ + tracing::{error, warn}, + HashMap, TypeIdMap, +}; #[cfg(feature = "trace")] use bevy_utils::{ tracing::{info_span, instrument::Instrument}, ConditionalSendFuture, }; -use bevy_utils::{HashMap, TypeIdMap}; -use std::{any::TypeId, sync::Arc}; +use core::any::TypeId; use thiserror::Error; #[derive(Default)] @@ -31,9 +34,9 @@ impl AssetLoaders { /// Registers a new [`AssetLoader`]. [`AssetLoader`]s must be registered before they can be used. pub(crate) fn push(&mut self, loader: L) { - let type_name = std::any::type_name::(); + let type_name = core::any::type_name::(); let loader_asset_type = TypeId::of::(); - let loader_asset_type_name = std::any::type_name::(); + let loader_asset_type_name = core::any::type_name::(); #[cfg(feature = "trace")] let loader = InstrumentedAssetLoader(loader); @@ -78,7 +81,7 @@ impl AssetLoaders { self.loaders.push(MaybeAssetLoader::Ready(loader)); } else { - let maybe_loader = std::mem::replace( + let maybe_loader = core::mem::replace( self.loaders.get_mut(loader_index).unwrap(), MaybeAssetLoader::Ready(loader.clone()), ); @@ -101,8 +104,8 @@ impl AssetLoaders { /// real loader is added. pub(crate) fn reserve(&mut self, extensions: &[&str]) { let loader_asset_type = TypeId::of::(); - let loader_asset_type_name = std::any::type_name::(); - let type_name = std::any::type_name::(); + let loader_asset_type_name = core::any::type_name::(); + let type_name = core::any::type_name::(); let loader_index = self.loaders.len(); @@ -266,7 +269,7 @@ impl AssetLoaders { pub(crate) fn get_by_path(&self, path: &AssetPath<'_>) -> Option { let extension = path.get_full_extension()?; - let result = std::iter::once(extension.as_str()) + let result = core::iter::once(extension.as_str()) .chain(AssetPath::iter_secondary_extensions(&extension)) .filter_map(|extension| self.extension_to_loaders.get(extension)?.last().copied()) .find_map(|index| self.get_by_index(index))?; @@ -316,7 +319,7 @@ impl AssetLoader for InstrumentedAssetLoader { ) -> impl ConditionalSendFuture> { let span = info_span!( "asset loading", - loader = std::any::type_name::(), + loader = core::any::type_name::(), asset = load_context.asset_path().to_string(), ); self.0.load(reader, settings, load_context).instrument(span) @@ -329,8 +332,8 @@ impl AssetLoader for InstrumentedAssetLoader { #[cfg(test)] mod tests { + use core::marker::PhantomData; use std::{ - marker::PhantomData, path::Path, sync::mpsc::{channel, Receiver, Sender}, }; @@ -390,7 +393,7 @@ mod tests { Err(format!( "Loaded {}:{}", - std::any::type_name::(), + core::any::type_name::(), N )) } @@ -424,7 +427,7 @@ mod tests { let loader = block_on( loaders - .get_by_name(std::any::type_name::>()) + .get_by_name(core::any::type_name::>()) .unwrap() .get(), ) diff --git a/crates/bevy_asset/src/server/mod.rs b/crates/bevy_asset/src/server/mod.rs index b1b9f7e49c698..7d6f1d1bf50e2 100644 --- a/crates/bevy_asset/src/server/mod.rs +++ b/crates/bevy_asset/src/server/mod.rs @@ -17,19 +17,25 @@ use crate::{ DeserializeMetaError, ErasedLoadedAsset, Handle, LoadedUntypedAsset, UntypedAssetId, UntypedAssetLoadFailedEvent, UntypedHandle, }; +use alloc::sync::Arc; use atomicow::CowArc; use bevy_ecs::prelude::*; use bevy_tasks::IoTaskPool; -use bevy_utils::tracing::{error, info}; -use bevy_utils::HashSet; +use bevy_utils::{ + tracing::{error, info}, + HashSet, +}; +use core::{ + any::{Any, TypeId}, + future::Future, + panic::AssertUnwindSafe, +}; use crossbeam_channel::{Receiver, Sender}; use futures_lite::{FutureExt, StreamExt}; use info::*; use loaders::*; use parking_lot::RwLock; -use std::{any::Any, path::PathBuf}; -use std::{any::TypeId, path::Path, sync::Arc}; -use std::{future::Future, panic::AssertUnwindSafe}; +use std::path::{Path, PathBuf}; use thiserror::Error; /// Loads and tracks the state of [`Asset`] values from a configured [`AssetReader`](crate::io::AssetReader). This can be used to kick off new asset loads and @@ -728,13 +734,13 @@ impl AssetServer { /// /// After the asset has been fully loaded, it will show up in the relevant [`Assets`] storage. #[must_use = "not using the returned strong handle may result in the unexpected release of the asset"] - pub fn add_async( + pub fn add_async( &self, future: impl Future> + Send + 'static, ) -> Handle { let mut infos = self.data.infos.write(); let handle = - infos.create_loading_handle_untyped(TypeId::of::(), std::any::type_name::()); + infos.create_loading_handle_untyped(TypeId::of::(), core::any::type_name::()); let id = handle.id(); let event_sender = self.data.asset_event_sender.clone(); @@ -1518,7 +1524,7 @@ pub enum AssetLoadError { pub struct AssetLoaderError { path: AssetPath<'static>, loader_name: &'static str, - error: Arc, + error: Arc, } impl PartialEq for AssetLoaderError { @@ -1542,7 +1548,7 @@ impl AssetLoaderError { #[derive(Error, Debug, Clone)] #[error("An error occurred while resolving an asset added by `add_async`: {error}")] pub struct AddAsyncError { - error: Arc, + error: Arc, } impl PartialEq for AddAsyncError { @@ -1588,8 +1594,8 @@ fn format_missing_asset_ext(exts: &[String]) -> String { } } -impl std::fmt::Debug for AssetServer { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for AssetServer { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("AssetServer") .field("info", &self.data.infos.read()) .finish() diff --git a/crates/bevy_asset/src/transformer.rs b/crates/bevy_asset/src/transformer.rs index f13d81ca67346..484e02003f644 100644 --- a/crates/bevy_asset/src/transformer.rs +++ b/crates/bevy_asset/src/transformer.rs @@ -1,14 +1,14 @@ use crate::{meta::Settings, Asset, ErasedLoadedAsset, Handle, LabeledAsset, UntypedHandle}; use atomicow::CowArc; use bevy_utils::{ConditionalSendFuture, HashMap}; -use serde::{Deserialize, Serialize}; -use std::{ +use core::{ borrow::Borrow, convert::Infallible, hash::Hash, marker::PhantomData, ops::{Deref, DerefMut}, }; +use serde::{Deserialize, Serialize}; /// Transforms an [`Asset`] of a given [`AssetTransformer::AssetInput`] type to an [`Asset`] of [`AssetTransformer::AssetOutput`] type. /// @@ -21,7 +21,7 @@ pub trait AssetTransformer: Send + Sync + 'static { /// The settings type used by this [`AssetTransformer`]. type Settings: Settings + Default + Serialize + for<'a> Deserialize<'a>; /// The type of [error](`std::error::Error`) which could be encountered by this transformer. - type Error: Into>; + type Error: Into>; /// Transforms the given [`TransformedAsset`] to [`AssetTransformer::AssetOutput`]. /// The [`TransformedAsset`]'s `labeled_assets` can be altered to add new Labeled Sub-Assets diff --git a/crates/bevy_audio/src/audio_output.rs b/crates/bevy_audio/src/audio_output.rs index cfe344c1cebe0..69a31acff1878 100644 --- a/crates/bevy_audio/src/audio_output.rs +++ b/crates/bevy_audio/src/audio_output.rs @@ -33,7 +33,7 @@ impl Default for AudioOutput { fn default() -> Self { if let Ok((stream, stream_handle)) = OutputStream::try_default() { // We leak `OutputStream` to prevent the audio from stopping. - std::mem::forget(stream); + core::mem::forget(stream); Self { stream_handle: Some(stream_handle), } diff --git a/crates/bevy_audio/src/audio_source.rs b/crates/bevy_audio/src/audio_source.rs index 64a481b32852b..1c9a4e1e3ca2b 100644 --- a/crates/bevy_audio/src/audio_source.rs +++ b/crates/bevy_audio/src/audio_source.rs @@ -1,6 +1,7 @@ +use alloc::sync::Arc; use bevy_asset::{io::Reader, Asset, AssetLoader, LoadContext}; use bevy_reflect::TypePath; -use std::{io::Cursor, sync::Arc}; +use std::io::Cursor; /// A source of audio data #[derive(Asset, Debug, Clone, TypePath)] diff --git a/crates/bevy_audio/src/lib.rs b/crates/bevy_audio/src/lib.rs index 65d7b4e6bce5b..6fae1e835d972 100644 --- a/crates/bevy_audio/src/lib.rs +++ b/crates/bevy_audio/src/lib.rs @@ -27,6 +27,8 @@ //! } //! ``` +extern crate alloc; + mod audio; mod audio_output; mod audio_source; @@ -48,9 +50,7 @@ pub use audio::*; pub use audio_source::*; pub use pitch::*; -pub use rodio::cpal::Sample as CpalSample; -pub use rodio::source::Source; -pub use rodio::Sample; +pub use rodio::{cpal::Sample as CpalSample, source::Source, Sample}; pub use sinks::*; use bevy_app::prelude::*; diff --git a/crates/bevy_audio/src/pitch.rs b/crates/bevy_audio/src/pitch.rs index 3cc913b66fbcd..1f4c406a5d967 100644 --- a/crates/bevy_audio/src/pitch.rs +++ b/crates/bevy_audio/src/pitch.rs @@ -1,7 +1,10 @@ use crate::{AudioSourceBundle, Decodable}; use bevy_asset::Asset; use bevy_reflect::TypePath; -use rodio::{source::SineWave, source::TakeDuration, Source}; +use rodio::{ + source::{SineWave, TakeDuration}, + Source, +}; /// A source of sine wave sound #[derive(Asset, Debug, Clone, TypePath)] @@ -9,12 +12,12 @@ pub struct Pitch { /// Frequency at which sound will be played pub frequency: f32, /// Duration for which sound will be played - pub duration: std::time::Duration, + pub duration: core::time::Duration, } impl Pitch { /// Creates a new note - pub fn new(frequency: f32, duration: std::time::Duration) -> Self { + pub fn new(frequency: f32, duration: core::time::Duration) -> Self { Pitch { frequency, duration, diff --git a/crates/bevy_color/crates/gen_tests/src/main.rs b/crates/bevy_color/crates/gen_tests/src/main.rs index 80aa88b288683..7cd614f966fea 100644 --- a/crates/bevy_color/crates/gen_tests/src/main.rs +++ b/crates/bevy_color/crates/gen_tests/src/main.rs @@ -110,8 +110,8 @@ pub struct TestColor {{ struct VariablePrecision(f32); -impl std::fmt::Display for VariablePrecision { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Display for VariablePrecision { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { if self.0.fract() == 0.0 { return write!(f, "{}.0", self.0); } diff --git a/crates/bevy_color/src/color_gradient.rs b/crates/bevy_color/src/color_gradient.rs index 60920d6ca3576..bb6457e6fdc68 100644 --- a/crates/bevy_color/src/color_gradient.rs +++ b/crates/bevy_color/src/color_gradient.rs @@ -66,8 +66,7 @@ where #[cfg(test)] mod tests { use super::*; - use crate::palettes::basic; - use crate::Srgba; + use crate::{palettes::basic, Srgba}; #[test] fn test_color_curve() { diff --git a/crates/bevy_color/src/color_ops.rs b/crates/bevy_color/src/color_ops.rs index ffba9467f6170..4fda6eb4e43b2 100644 --- a/crates/bevy_color/src/color_ops.rs +++ b/crates/bevy_color/src/color_ops.rs @@ -137,7 +137,7 @@ pub(crate) fn lerp_hue(a: f32, b: f32, t: f32) -> f32 { #[cfg(test)] mod tests { - use std::fmt::Debug; + use core::fmt::Debug; use super::*; use crate::{testing::assert_approx_eq, Hsla}; diff --git a/crates/bevy_color/src/color_range.rs b/crates/bevy_color/src/color_range.rs index 72260b27f4a7e..48afa5418225d 100644 --- a/crates/bevy_color/src/color_range.rs +++ b/crates/bevy_color/src/color_range.rs @@ -1,4 +1,4 @@ -use std::ops::Range; +use core::ops::Range; use crate::Mix; @@ -22,8 +22,7 @@ impl ColorRange for Range { #[cfg(test)] mod tests { use super::*; - use crate::palettes::basic; - use crate::{LinearRgba, Srgba}; + use crate::{palettes::basic, LinearRgba, Srgba}; #[test] fn test_color_range() { diff --git a/crates/bevy_color/src/lib.rs b/crates/bevy_color/src/lib.rs index 344a159695935..9f940743da551 100644 --- a/crates/bevy_color/src/lib.rs +++ b/crates/bevy_color/src/lib.rs @@ -115,18 +115,10 @@ mod xyza; /// /// This includes the most common types in this crate, re-exported for your convenience. pub mod prelude { - pub use crate::color::*; - pub use crate::color_ops::*; - pub use crate::hsla::*; - pub use crate::hsva::*; - pub use crate::hwba::*; - pub use crate::laba::*; - pub use crate::lcha::*; - pub use crate::linear_rgba::*; - pub use crate::oklaba::*; - pub use crate::oklcha::*; - pub use crate::srgba::*; - pub use crate::xyza::*; + pub use crate::{ + color::*, color_ops::*, hsla::*, hsva::*, hwba::*, laba::*, lcha::*, linear_rgba::*, + oklaba::*, oklcha::*, srgba::*, xyza::*, + }; } pub use color::*; @@ -169,7 +161,7 @@ where macro_rules! impl_componentwise_vector_space { ($ty: ident, [$($element: ident),+]) => { - impl std::ops::Add for $ty { + impl core::ops::Add for $ty { type Output = Self; fn add(self, rhs: Self) -> Self::Output { @@ -179,13 +171,13 @@ macro_rules! impl_componentwise_vector_space { } } - impl std::ops::AddAssign for $ty { + impl core::ops::AddAssign for $ty { fn add_assign(&mut self, rhs: Self) { *self = *self + rhs; } } - impl std::ops::Neg for $ty { + impl core::ops::Neg for $ty { type Output = Self; fn neg(self) -> Self::Output { @@ -195,7 +187,7 @@ macro_rules! impl_componentwise_vector_space { } } - impl std::ops::Sub for $ty { + impl core::ops::Sub for $ty { type Output = Self; fn sub(self, rhs: Self) -> Self::Output { @@ -205,13 +197,13 @@ macro_rules! impl_componentwise_vector_space { } } - impl std::ops::SubAssign for $ty { + impl core::ops::SubAssign for $ty { fn sub_assign(&mut self, rhs: Self) { *self = *self - rhs; } } - impl std::ops::Mul for $ty { + impl core::ops::Mul for $ty { type Output = Self; fn mul(self, rhs: f32) -> Self::Output { @@ -221,7 +213,7 @@ macro_rules! impl_componentwise_vector_space { } } - impl std::ops::Mul<$ty> for f32 { + impl core::ops::Mul<$ty> for f32 { type Output = $ty; fn mul(self, rhs: $ty) -> Self::Output { @@ -231,13 +223,13 @@ macro_rules! impl_componentwise_vector_space { } } - impl std::ops::MulAssign for $ty { + impl core::ops::MulAssign for $ty { fn mul_assign(&mut self, rhs: f32) { *self = *self * rhs; } } - impl std::ops::Div for $ty { + impl core::ops::Div for $ty { type Output = Self; fn div(self, rhs: f32) -> Self::Output { @@ -247,7 +239,7 @@ macro_rules! impl_componentwise_vector_space { } } - impl std::ops::DivAssign for $ty { + impl core::ops::DivAssign for $ty { fn div_assign(&mut self, rhs: f32) { *self = *self / rhs; } diff --git a/crates/bevy_color/src/srgba.rs b/crates/bevy_color/src/srgba.rs index b235749a64a59..cd863c21b6749 100644 --- a/crates/bevy_color/src/srgba.rs +++ b/crates/bevy_color/src/srgba.rs @@ -1,7 +1,6 @@ -use crate::color_difference::EuclideanDistance; use crate::{ - impl_componentwise_vector_space, Alpha, ColorToComponents, ColorToPacked, Gray, LinearRgba, - Luminance, Mix, StandardColor, Xyza, + color_difference::EuclideanDistance, impl_componentwise_vector_space, Alpha, ColorToComponents, + ColorToPacked, Gray, LinearRgba, Luminance, Mix, StandardColor, Xyza, }; use bevy_math::{ops, Vec3, Vec4}; #[cfg(feature = "bevy_reflect")] @@ -428,7 +427,7 @@ impl From for Xyza { pub enum HexColorError { /// Parsing error. #[error("Invalid hex string")] - Parse(#[from] std::num::ParseIntError), + Parse(#[from] core::num::ParseIntError), /// Invalid length. #[error("Unexpected length of hex string")] Length, diff --git a/crates/bevy_core/src/lib.rs b/crates/bevy_core/src/lib.rs index 94a8b3a541f88..748e26109984e 100644 --- a/crates/bevy_core/src/lib.rs +++ b/crates/bevy_core/src/lib.rs @@ -7,6 +7,8 @@ //! This crate provides core functionality for Bevy Engine. +extern crate alloc; + mod name; #[cfg(feature = "serialize")] mod serde; @@ -29,7 +31,7 @@ pub mod prelude { use bevy_app::prelude::*; use bevy_ecs::prelude::*; -use std::marker::PhantomData; +use core::marker::PhantomData; #[cfg(not(target_arch = "wasm32"))] use bevy_tasks::tick_global_task_pools_on_main_thread; diff --git a/crates/bevy_core/src/name.rs b/crates/bevy_core/src/name.rs index 9f858cf96e09c..db71bb4f8637e 100644 --- a/crates/bevy_core/src/name.rs +++ b/crates/bevy_core/src/name.rs @@ -1,15 +1,14 @@ -use bevy_ecs::query::QueryData; #[cfg(feature = "bevy_reflect")] use bevy_ecs::reflect::ReflectComponent; -use bevy_ecs::{component::Component, entity::Entity}; +use bevy_ecs::{component::Component, entity::Entity, query::QueryData}; +use alloc::borrow::Cow; #[cfg(feature = "bevy_reflect")] use bevy_reflect::std_traits::ReflectDefault; #[cfg(feature = "bevy_reflect")] use bevy_reflect::Reflect; use bevy_utils::AHasher; -use std::{ - borrow::Cow, +use core::{ hash::{Hash, Hasher}, ops::Deref, }; @@ -87,17 +86,17 @@ impl Name { } } -impl std::fmt::Display for Name { +impl core::fmt::Display for Name { #[inline(always)] - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - std::fmt::Display::fmt(&self.name, f) + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + core::fmt::Display::fmt(&self.name, f) } } -impl std::fmt::Debug for Name { +impl core::fmt::Debug for Name { #[inline(always)] - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - std::fmt::Debug::fmt(&self.name, f) + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + core::fmt::Debug::fmt(&self.name, f) } } @@ -131,12 +130,12 @@ pub struct NameOrEntity { pub entity: Entity, } -impl<'a> std::fmt::Display for NameOrEntityItem<'a> { +impl<'a> core::fmt::Display for NameOrEntityItem<'a> { #[inline(always)] - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { match self.name { - Some(name) => std::fmt::Display::fmt(name, f), - None => std::fmt::Display::fmt(&self.entity, f), + Some(name) => core::fmt::Display::fmt(name, f), + None => core::fmt::Display::fmt(&self.entity, f), } } } @@ -197,13 +196,13 @@ impl PartialEq for Name { impl Eq for Name {} impl PartialOrd for Name { - fn partial_cmp(&self, other: &Self) -> Option { + fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Ord for Name { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { + fn cmp(&self, other: &Self) -> core::cmp::Ordering { self.name.cmp(&other.name) } } diff --git a/crates/bevy_core/src/serde.rs b/crates/bevy_core/src/serde.rs index fc4d81b4bd055..d618ba179492a 100644 --- a/crates/bevy_core/src/serde.rs +++ b/crates/bevy_core/src/serde.rs @@ -1,4 +1,4 @@ -use std::{ +use core::{ any, fmt::{self, Formatter}, }; @@ -8,8 +8,7 @@ use serde::{ Deserialize, Deserializer, Serialize, Serializer, }; -use super::name::Name; -use super::FrameCount; +use super::{name::Name, FrameCount}; impl Serialize for Name { fn serialize(&self, serializer: S) -> Result { diff --git a/crates/bevy_core_pipeline/src/auto_exposure/buffers.rs b/crates/bevy_core_pipeline/src/auto_exposure/buffers.rs index 76698d14c4443..836c18b3a75aa 100644 --- a/crates/bevy_core_pipeline/src/auto_exposure/buffers.rs +++ b/crates/bevy_core_pipeline/src/auto_exposure/buffers.rs @@ -6,8 +6,7 @@ use bevy_render::{ }; use bevy_utils::{Entry, HashMap}; -use super::pipeline::AutoExposureUniform; -use super::AutoExposure; +use super::{pipeline::AutoExposureUniform, AutoExposure}; #[derive(Resource, Default)] pub(super) struct AutoExposureBuffers { diff --git a/crates/bevy_core_pipeline/src/auto_exposure/mod.rs b/crates/bevy_core_pipeline/src/auto_exposure/mod.rs index dccd63bff0194..59f314d12e1ab 100644 --- a/crates/bevy_core_pipeline/src/auto_exposure/mod.rs +++ b/crates/bevy_core_pipeline/src/auto_exposure/mod.rs @@ -1,17 +1,15 @@ use bevy_app::prelude::*; use bevy_asset::{load_internal_asset, AssetApp, Assets, Handle}; use bevy_ecs::prelude::*; -use bevy_render::extract_component::ExtractComponentPlugin; -use bevy_render::render_asset::RenderAssetPlugin; -use bevy_render::render_resource::Shader; -use bevy_render::ExtractSchedule; use bevy_render::{ + extract_component::ExtractComponentPlugin, + render_asset::RenderAssetPlugin, render_graph::RenderGraphApp, render_resource::{ - Buffer, BufferDescriptor, BufferUsages, PipelineCache, SpecializedComputePipelines, + Buffer, BufferDescriptor, BufferUsages, PipelineCache, Shader, SpecializedComputePipelines, }, renderer::RenderDevice, - Render, RenderApp, RenderSet, + ExtractSchedule, Render, RenderApp, RenderSet, }; mod buffers; @@ -29,8 +27,10 @@ use pipeline::{ #[allow(deprecated)] pub use settings::{AutoExposure, AutoExposureSettings}; -use crate::auto_exposure::compensation_curve::GpuAutoExposureCompensationCurve; -use crate::core_3d::graph::{Core3d, Node3d}; +use crate::{ + auto_exposure::compensation_curve::GpuAutoExposureCompensationCurve, + core_3d::graph::{Core3d, Node3d}, +}; /// Plugin for the auto exposure feature. /// diff --git a/crates/bevy_core_pipeline/src/auto_exposure/pipeline.rs b/crates/bevy_core_pipeline/src/auto_exposure/pipeline.rs index 684c8dd9e200a..410b7deb6d47e 100644 --- a/crates/bevy_core_pipeline/src/auto_exposure/pipeline.rs +++ b/crates/bevy_core_pipeline/src/auto_exposure/pipeline.rs @@ -10,7 +10,7 @@ use bevy_render::{ texture::Image, view::ViewUniform, }; -use std::num::NonZero; +use core::num::NonZero; #[derive(Resource)] pub struct AutoExposurePipeline { diff --git a/crates/bevy_core_pipeline/src/auto_exposure/settings.rs b/crates/bevy_core_pipeline/src/auto_exposure/settings.rs index 388a67fb79933..b8f7949521f30 100644 --- a/crates/bevy_core_pipeline/src/auto_exposure/settings.rs +++ b/crates/bevy_core_pipeline/src/auto_exposure/settings.rs @@ -1,10 +1,9 @@ -use std::ops::RangeInclusive; +use core::ops::RangeInclusive; use super::compensation_curve::AutoExposureCompensationCurve; use bevy_asset::Handle; use bevy_ecs::{prelude::Component, reflect::ReflectComponent}; -use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; +use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_render::{extract_component::ExtractComponent, texture::Image}; use bevy_utils::default; diff --git a/crates/bevy_core_pipeline/src/contrast_adaptive_sharpening/mod.rs b/crates/bevy_core_pipeline/src/contrast_adaptive_sharpening/mod.rs index 5afde16797728..71c9cc2bb2a61 100644 --- a/crates/bevy_core_pipeline/src/contrast_adaptive_sharpening/mod.rs +++ b/crates/bevy_core_pipeline/src/contrast_adaptive_sharpening/mod.rs @@ -6,8 +6,7 @@ use crate::{ use bevy_app::prelude::*; use bevy_asset::{load_internal_asset, Handle}; use bevy_ecs::{prelude::*, query::QueryItem}; -use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; +use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_render::{ extract_component::{ExtractComponent, ExtractComponentPlugin, UniformComponentPlugin}, prelude::Camera, diff --git a/crates/bevy_core_pipeline/src/core_2d/camera_2d.rs b/crates/bevy_core_pipeline/src/core_2d/camera_2d.rs index b2181bdddcaac..682c15cd035ee 100644 --- a/crates/bevy_core_pipeline/src/core_2d/camera_2d.rs +++ b/crates/bevy_core_pipeline/src/core_2d/camera_2d.rs @@ -1,15 +1,16 @@ -use crate::core_2d::graph::Core2d; -use crate::tonemapping::{DebandDither, Tonemapping}; +use crate::{ + core_2d::graph::Core2d, + tonemapping::{DebandDither, Tonemapping}, +}; use bevy_ecs::prelude::*; -use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; -use bevy_render::prelude::Msaa; +use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_render::{ camera::{ Camera, CameraMainTextureUsages, CameraProjection, CameraRenderGraph, OrthographicProjection, }, extract_component::ExtractComponent, + prelude::Msaa, primitives::Frustum, view::VisibleEntities, }; diff --git a/crates/bevy_core_pipeline/src/core_2d/mod.rs b/crates/bevy_core_pipeline/src/core_2d/mod.rs index 7bd6bea38cb58..6bd3b3e324bcd 100644 --- a/crates/bevy_core_pipeline/src/core_2d/mod.rs +++ b/crates/bevy_core_pipeline/src/core_2d/mod.rs @@ -30,7 +30,7 @@ pub mod graph { } } -use std::ops::Range; +use core::ops::Range; use bevy_asset::UntypedAssetId; use bevy_utils::HashMap; diff --git a/crates/bevy_core_pipeline/src/core_3d/camera_3d.rs b/crates/bevy_core_pipeline/src/core_3d/camera_3d.rs index c2f703a784f7f..ed748c52bc328 100644 --- a/crates/bevy_core_pipeline/src/core_3d/camera_3d.rs +++ b/crates/bevy_core_pipeline/src/core_3d/camera_3d.rs @@ -3,15 +3,13 @@ use crate::{ tonemapping::{DebandDither, Tonemapping}, }; use bevy_ecs::prelude::*; -use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::{Reflect, ReflectDeserialize, ReflectSerialize}; -use bevy_render::view::Msaa; +use bevy_reflect::{std_traits::ReflectDefault, Reflect, ReflectDeserialize, ReflectSerialize}; use bevy_render::{ camera::{Camera, CameraMainTextureUsages, CameraRenderGraph, Exposure, Projection}, extract_component::ExtractComponent, primitives::Frustum, render_resource::{LoadOp, TextureUsages}, - view::{ColorGrading, VisibleEntities}, + view::{ColorGrading, Msaa, VisibleEntities}, }; use bevy_transform::prelude::{GlobalTransform, Transform}; use serde::{Deserialize, Serialize}; diff --git a/crates/bevy_core_pipeline/src/core_3d/main_transmissive_pass_3d_node.rs b/crates/bevy_core_pipeline/src/core_3d/main_transmissive_pass_3d_node.rs index f78083afb3816..225ce81da6c3a 100644 --- a/crates/bevy_core_pipeline/src/core_3d/main_transmissive_pass_3d_node.rs +++ b/crates/bevy_core_pipeline/src/core_3d/main_transmissive_pass_3d_node.rs @@ -12,7 +12,7 @@ use bevy_render::{ use bevy_utils::tracing::error; #[cfg(feature = "trace")] use bevy_utils::tracing::info_span; -use std::ops::Range; +use core::ops::Range; /// A [`bevy_render::render_graph::Node`] that runs the [`Transmissive3d`] /// [`ViewSortedRenderPhases`]. diff --git a/crates/bevy_core_pipeline/src/core_3d/mod.rs b/crates/bevy_core_pipeline/src/core_3d/mod.rs index c539c10fa71ce..fc066e2d9ea7f 100644 --- a/crates/bevy_core_pipeline/src/core_3d/mod.rs +++ b/crates/bevy_core_pipeline/src/core_3d/mod.rs @@ -63,7 +63,7 @@ pub const DEPTH_TEXTURE_SAMPLING_SUPPORTED: bool = false; #[cfg(any(feature = "webgpu", not(target_arch = "wasm32")))] pub const DEPTH_TEXTURE_SAMPLING_SUPPORTED: bool = true; -use std::ops::Range; +use core::ops::Range; use bevy_asset::{AssetId, UntypedAssetId}; use bevy_color::LinearRgba; diff --git a/crates/bevy_core_pipeline/src/deferred/mod.rs b/crates/bevy_core_pipeline/src/deferred/mod.rs index 1372731820224..ef20bf7ee59d6 100644 --- a/crates/bevy_core_pipeline/src/deferred/mod.rs +++ b/crates/bevy_core_pipeline/src/deferred/mod.rs @@ -1,7 +1,7 @@ pub mod copy_lighting_id; pub mod node; -use std::ops::Range; +use core::ops::Range; use bevy_ecs::prelude::*; use bevy_render::{ diff --git a/crates/bevy_core_pipeline/src/deferred/node.rs b/crates/bevy_core_pipeline/src/deferred/node.rs index 44895aaeb8cd2..5aa89a8e94a0d 100644 --- a/crates/bevy_core_pipeline/src/deferred/node.rs +++ b/crates/bevy_core_pipeline/src/deferred/node.rs @@ -1,13 +1,11 @@ -use bevy_ecs::prelude::*; -use bevy_ecs::query::QueryItem; +use bevy_ecs::{prelude::*, query::QueryItem}; use bevy_render::render_graph::ViewNode; -use bevy_render::render_phase::{TrackedRenderPass, ViewBinnedRenderPhases}; -use bevy_render::render_resource::{CommandEncoderDescriptor, StoreOp}; use bevy_render::{ camera::ExtractedCamera, render_graph::{NodeRunError, RenderGraphContext}, - render_resource::RenderPassDescriptor, + render_phase::{TrackedRenderPass, ViewBinnedRenderPhases}, + render_resource::{CommandEncoderDescriptor, RenderPassDescriptor, StoreOp}, renderer::RenderContext, view::ViewDepthTexture, }; diff --git a/crates/bevy_core_pipeline/src/fxaa/mod.rs b/crates/bevy_core_pipeline/src/fxaa/mod.rs index 85fe16bd48021..a448444bafc4b 100644 --- a/crates/bevy_core_pipeline/src/fxaa/mod.rs +++ b/crates/bevy_core_pipeline/src/fxaa/mod.rs @@ -10,8 +10,7 @@ use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_render::{ extract_component::{ExtractComponent, ExtractComponentPlugin}, prelude::Camera, - render_graph::RenderGraphApp, - render_graph::ViewNodeRunner, + render_graph::{RenderGraphApp, ViewNodeRunner}, render_resource::{ binding_types::{sampler, texture_2d}, *, diff --git a/crates/bevy_core_pipeline/src/fxaa/node.rs b/crates/bevy_core_pipeline/src/fxaa/node.rs index 857a3015c181b..a58f21d9a7746 100644 --- a/crates/bevy_core_pipeline/src/fxaa/node.rs +++ b/crates/bevy_core_pipeline/src/fxaa/node.rs @@ -1,8 +1,7 @@ use std::sync::Mutex; use crate::fxaa::{CameraFxaaPipeline, Fxaa, FxaaPipeline}; -use bevy_ecs::prelude::*; -use bevy_ecs::query::QueryItem; +use bevy_ecs::{prelude::*, query::QueryItem}; use bevy_render::{ render_graph::{NodeRunError, RenderGraphContext, ViewNode}, render_resource::{ diff --git a/crates/bevy_core_pipeline/src/msaa_writeback.rs b/crates/bevy_core_pipeline/src/msaa_writeback.rs index 01f579a0e1404..f9c543aeff03c 100644 --- a/crates/bevy_core_pipeline/src/msaa_writeback.rs +++ b/crates/bevy_core_pipeline/src/msaa_writeback.rs @@ -5,17 +5,15 @@ use crate::{ }; use bevy_app::{App, Plugin}; use bevy_color::LinearRgba; -use bevy_ecs::prelude::*; -use bevy_ecs::query::QueryItem; -use bevy_render::render_graph::{ViewNode, ViewNodeRunner}; +use bevy_ecs::{prelude::*, query::QueryItem}; use bevy_render::{ camera::ExtractedCamera, - render_graph::{NodeRunError, RenderGraphApp, RenderGraphContext}, + render_graph::{NodeRunError, RenderGraphApp, RenderGraphContext, ViewNode, ViewNodeRunner}, + render_resource::*, renderer::RenderContext, view::{Msaa, ViewTarget}, - Render, RenderSet, + Render, RenderApp, RenderSet, }; -use bevy_render::{render_resource::*, RenderApp}; /// This enables "msaa writeback" support for the `core_2d` and `core_3d` pipelines, which can be enabled on cameras /// using [`bevy_render::camera::Camera::msaa_writeback`]. See the docs on that field for more information. diff --git a/crates/bevy_core_pipeline/src/prepass/mod.rs b/crates/bevy_core_pipeline/src/prepass/mod.rs index bebb2a180f88c..4829c76ee7653 100644 --- a/crates/bevy_core_pipeline/src/prepass/mod.rs +++ b/crates/bevy_core_pipeline/src/prepass/mod.rs @@ -27,13 +27,12 @@ pub mod node; -use std::ops::Range; +use core::ops::Range; use bevy_asset::UntypedAssetId; use bevy_ecs::prelude::*; use bevy_math::Mat4; -use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; +use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_render::{ render_phase::{ BinnedPhaseItem, CachedRenderPipelinePhaseItem, DrawFunctionId, PhaseItem, diff --git a/crates/bevy_core_pipeline/src/prepass/node.rs b/crates/bevy_core_pipeline/src/prepass/node.rs index d362c36f6c21f..17f5dfb2cfe84 100644 --- a/crates/bevy_core_pipeline/src/prepass/node.rs +++ b/crates/bevy_core_pipeline/src/prepass/node.rs @@ -1,5 +1,4 @@ -use bevy_ecs::prelude::*; -use bevy_ecs::query::QueryItem; +use bevy_ecs::{prelude::*, query::QueryItem}; use bevy_render::{ camera::ExtractedCamera, diagnostic::RecordDiagnostics, diff --git a/crates/bevy_core_pipeline/src/taa/mod.rs b/crates/bevy_core_pipeline/src/taa/mod.rs index 635b0a7dbe14b..56dcd6a69bb4d 100644 --- a/crates/bevy_core_pipeline/src/taa/mod.rs +++ b/crates/bevy_core_pipeline/src/taa/mod.rs @@ -15,8 +15,7 @@ use bevy_ecs::{ world::{FromWorld, World}, }; use bevy_math::vec2; -use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; +use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_render::{ camera::{ExtractedCamera, MipBias, TemporalJitter}, prelude::{Camera, Projection}, diff --git a/crates/bevy_core_pipeline/src/tonemapping/mod.rs b/crates/bevy_core_pipeline/src/tonemapping/mod.rs index 353690d165099..7614b50153a40 100644 --- a/crates/bevy_core_pipeline/src/tonemapping/mod.rs +++ b/crates/bevy_core_pipeline/src/tonemapping/mod.rs @@ -2,19 +2,21 @@ use crate::fullscreen_vertex_shader::fullscreen_shader_vertex_state; use bevy_app::prelude::*; use bevy_asset::{load_internal_asset, Assets, Handle}; use bevy_ecs::prelude::*; -use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; -use bevy_render::extract_component::{ExtractComponent, ExtractComponentPlugin}; -use bevy_render::extract_resource::{ExtractResource, ExtractResourcePlugin}; -use bevy_render::render_asset::{RenderAssetUsages, RenderAssets}; -use bevy_render::render_resource::binding_types::{ - sampler, texture_2d, texture_3d, uniform_buffer, +use bevy_reflect::{std_traits::ReflectDefault, Reflect}; +use bevy_render::{ + camera::Camera, + extract_component::{ExtractComponent, ExtractComponentPlugin}, + extract_resource::{ExtractResource, ExtractResourcePlugin}, + render_asset::{RenderAssetUsages, RenderAssets}, + render_resource::{ + binding_types::{sampler, texture_2d, texture_3d, uniform_buffer}, + *, + }, + renderer::RenderDevice, + texture::{CompressedImageFormats, FallbackImage, GpuImage, Image, ImageSampler, ImageType}, + view::{ExtractedView, ViewTarget, ViewUniform}, + Render, RenderApp, RenderSet, }; -use bevy_render::renderer::RenderDevice; -use bevy_render::texture::{CompressedImageFormats, GpuImage, Image, ImageSampler, ImageType}; -use bevy_render::view::{ExtractedView, ViewTarget, ViewUniform}; -use bevy_render::{camera::Camera, texture::FallbackImage}; -use bevy_render::{render_resource::*, Render, RenderApp, RenderSet}; #[cfg(not(feature = "tonemapping_luts"))] use bevy_utils::tracing::error; use bitflags::bitflags; diff --git a/crates/bevy_core_pipeline/src/upscaling/mod.rs b/crates/bevy_core_pipeline/src/upscaling/mod.rs index 1f99580dbe1b3..42f6744bfb32c 100644 --- a/crates/bevy_core_pipeline/src/upscaling/mod.rs +++ b/crates/bevy_core_pipeline/src/upscaling/mod.rs @@ -1,9 +1,12 @@ use crate::blit::{BlitPipeline, BlitPipelineKey}; use bevy_app::prelude::*; use bevy_ecs::prelude::*; -use bevy_render::camera::{CameraOutputMode, ExtractedCamera}; -use bevy_render::view::ViewTarget; -use bevy_render::{render_resource::*, Render, RenderApp, RenderSet}; +use bevy_render::{ + camera::{CameraOutputMode, ExtractedCamera}, + render_resource::*, + view::ViewTarget, + Render, RenderApp, RenderSet, +}; use bevy_utils::HashSet; mod node; diff --git a/crates/bevy_core_pipeline/src/upscaling/node.rs b/crates/bevy_core_pipeline/src/upscaling/node.rs index e3b1aa3109dab..ece71c194710c 100644 --- a/crates/bevy_core_pipeline/src/upscaling/node.rs +++ b/crates/bevy_core_pipeline/src/upscaling/node.rs @@ -1,8 +1,7 @@ use crate::{blit::BlitPipeline, upscaling::ViewUpscalingPipeline}; use bevy_ecs::{prelude::*, query::QueryItem}; -use bevy_render::camera::{ClearColor, ClearColorConfig}; use bevy_render::{ - camera::{CameraOutputMode, ExtractedCamera}, + camera::{CameraOutputMode, ClearColor, ClearColorConfig, ExtractedCamera}, render_graph::{NodeRunError, RenderGraphContext, ViewNode}, render_resource::{ BindGroup, BindGroupEntries, PipelineCache, RenderPassDescriptor, TextureViewId, diff --git a/crates/bevy_derive/compile_fail/tests/deref_mut_derive/invalid_attribute_fail.rs b/crates/bevy_derive/compile_fail/tests/deref_mut_derive/invalid_attribute_fail.rs index aa39ac923e6fe..d3efd7c902ac9 100644 --- a/crates/bevy_derive/compile_fail/tests/deref_mut_derive/invalid_attribute_fail.rs +++ b/crates/bevy_derive/compile_fail/tests/deref_mut_derive/invalid_attribute_fail.rs @@ -1,5 +1,5 @@ use bevy_derive::DerefMut; -use std::ops::Deref; +use core::ops::Deref; // Reason: `#[deref]` doesn't take any arguments diff --git a/crates/bevy_derive/compile_fail/tests/deref_mut_derive/mismatched_target_type_fail.rs b/crates/bevy_derive/compile_fail/tests/deref_mut_derive/mismatched_target_type_fail.rs index 253c59e734aa9..224a53e709e73 100644 --- a/crates/bevy_derive/compile_fail/tests/deref_mut_derive/mismatched_target_type_fail.rs +++ b/crates/bevy_derive/compile_fail/tests/deref_mut_derive/mismatched_target_type_fail.rs @@ -1,5 +1,5 @@ use bevy_derive::DerefMut; -use std::ops::Deref; +use core::ops::Deref; #[derive(DerefMut)] //~^ E0308 diff --git a/crates/bevy_derive/compile_fail/tests/deref_mut_derive/missing_attribute_fail.rs b/crates/bevy_derive/compile_fail/tests/deref_mut_derive/missing_attribute_fail.rs index f2568bb698fc2..0415516d135d6 100644 --- a/crates/bevy_derive/compile_fail/tests/deref_mut_derive/missing_attribute_fail.rs +++ b/crates/bevy_derive/compile_fail/tests/deref_mut_derive/missing_attribute_fail.rs @@ -1,5 +1,5 @@ use bevy_derive::DerefMut; -use std::ops::Deref; +use core::ops::Deref; #[derive(DerefMut)] //~^ ERROR: requires one field to have diff --git a/crates/bevy_derive/compile_fail/tests/deref_mut_derive/multiple_attributes_fail.rs b/crates/bevy_derive/compile_fail/tests/deref_mut_derive/multiple_attributes_fail.rs index 449720934e084..b855f9f4f4bb3 100644 --- a/crates/bevy_derive/compile_fail/tests/deref_mut_derive/multiple_attributes_fail.rs +++ b/crates/bevy_derive/compile_fail/tests/deref_mut_derive/multiple_attributes_fail.rs @@ -1,5 +1,5 @@ use bevy_derive::DerefMut; -use std::ops::Deref; +use core::ops::Deref; #[derive(DerefMut)] struct TupleStruct( diff --git a/crates/bevy_derive/compile_fail/tests/deref_mut_derive/multiple_fields_pass.rs b/crates/bevy_derive/compile_fail/tests/deref_mut_derive/multiple_fields_pass.rs index bc65df7baf796..86d0bceb1e1ed 100644 --- a/crates/bevy_derive/compile_fail/tests/deref_mut_derive/multiple_fields_pass.rs +++ b/crates/bevy_derive/compile_fail/tests/deref_mut_derive/multiple_fields_pass.rs @@ -1,7 +1,7 @@ //@check-pass use bevy_derive::DerefMut; -use std::ops::Deref; +use core::ops::Deref; #[derive(DerefMut)] // The first field is never read, but we want it there to check that the derive skips it. diff --git a/crates/bevy_derive/compile_fail/tests/deref_mut_derive/single_field_pass.rs b/crates/bevy_derive/compile_fail/tests/deref_mut_derive/single_field_pass.rs index 803ed3ba5cc21..e63200ccc7971 100644 --- a/crates/bevy_derive/compile_fail/tests/deref_mut_derive/single_field_pass.rs +++ b/crates/bevy_derive/compile_fail/tests/deref_mut_derive/single_field_pass.rs @@ -1,6 +1,6 @@ //@check-pass use bevy_derive::DerefMut; -use std::ops::Deref; +use core::ops::Deref; #[derive(DerefMut)] struct TupleStruct(#[deref] String); diff --git a/crates/bevy_derive/src/derefs.rs b/crates/bevy_derive/src/derefs.rs index 90b00f7b71c33..0dd3b152bfda5 100644 --- a/crates/bevy_derive/src/derefs.rs +++ b/crates/bevy_derive/src/derefs.rs @@ -19,7 +19,7 @@ pub fn derive_deref(input: TokenStream) -> TokenStream { let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); TokenStream::from(quote! { - impl #impl_generics ::std::ops::Deref for #ident #ty_generics #where_clause { + impl #impl_generics ::core::ops::Deref for #ident #ty_generics #where_clause { type Target = #field_type; fn deref(&self) -> &Self::Target { @@ -42,7 +42,7 @@ pub fn derive_deref_mut(input: TokenStream) -> TokenStream { let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); TokenStream::from(quote! { - impl #impl_generics ::std::ops::DerefMut for #ident #ty_generics #where_clause { + impl #impl_generics ::core::ops::DerefMut for #ident #ty_generics #where_clause { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.#field_member } diff --git a/crates/bevy_dev_tools/src/ci_testing/mod.rs b/crates/bevy_dev_tools/src/ci_testing/mod.rs index 39b9bee6da7e6..5c85aeff48340 100644 --- a/crates/bevy_dev_tools/src/ci_testing/mod.rs +++ b/crates/bevy_dev_tools/src/ci_testing/mod.rs @@ -9,7 +9,7 @@ use bevy_app::prelude::*; use bevy_ecs::prelude::*; use bevy_render::view::screenshot::trigger_screenshots; use bevy_time::TimeUpdateStrategy; -use std::time::Duration; +use core::time::Duration; /// A plugin that instruments continuous integration testing by automatically executing user-defined actions. /// diff --git a/crates/bevy_dev_tools/src/ci_testing/systems.rs b/crates/bevy_dev_tools/src/ci_testing/systems.rs index 2b652abf96db6..20c758a91cdfc 100644 --- a/crates/bevy_dev_tools/src/ci_testing/systems.rs +++ b/crates/bevy_dev_tools/src/ci_testing/systems.rs @@ -8,7 +8,7 @@ pub(crate) fn send_events(world: &mut World, mut current_frame: Local) { let mut config = world.resource_mut::(); // Take all events for the current frame, leaving all the remaining alone. - let events = std::mem::take(&mut config.events); + let events = core::mem::take(&mut config.events); let (to_run, remaining): (Vec<_>, _) = events .into_iter() .partition(|event| event.0 == *current_frame); diff --git a/crates/bevy_dev_tools/src/states.rs b/crates/bevy_dev_tools/src/states.rs index 7e3aa237c60cf..21d5aedc03232 100644 --- a/crates/bevy_dev_tools/src/states.rs +++ b/crates/bevy_dev_tools/src/states.rs @@ -12,7 +12,7 @@ pub fn log_transitions(mut transitions: EventReader(); + let name = core::any::type_name::(); let StateTransitionEvent { exited, entered } = transition; info!("{} transition: {:?} => {:?}", name, exited, entered); } diff --git a/crates/bevy_dev_tools/src/ui_debug_overlay/mod.rs b/crates/bevy_dev_tools/src/ui_debug_overlay/mod.rs index 88af56210a9e3..d84143943c973 100644 --- a/crates/bevy_dev_tools/src/ui_debug_overlay/mod.rs +++ b/crates/bevy_dev_tools/src/ui_debug_overlay/mod.rs @@ -1,5 +1,5 @@ //! A visual representation of UI node sizes. -use std::any::{Any, TypeId}; +use core::any::{Any, TypeId}; use bevy_app::{App, Plugin, PostUpdate}; use bevy_color::Hsla; diff --git a/crates/bevy_diagnostic/src/diagnostic.rs b/crates/bevy_diagnostic/src/diagnostic.rs index b45ee593cfab3..ccd6e17df175d 100644 --- a/crates/bevy_diagnostic/src/diagnostic.rs +++ b/crates/bevy_diagnostic/src/diagnostic.rs @@ -1,5 +1,5 @@ -use std::hash::{Hash, Hasher}; -use std::{borrow::Cow, collections::VecDeque}; +use alloc::{borrow::Cow, collections::VecDeque}; +use core::hash::{Hash, Hasher}; use bevy_app::{App, SubApp}; use bevy_ecs::system::{Deferred, Res, Resource, SystemBuffer, SystemParam}; @@ -100,8 +100,8 @@ impl Hash for DiagnosticPath { } } -impl std::fmt::Display for DiagnosticPath { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Display for DiagnosticPath { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.path.fmt(f) } } diff --git a/crates/bevy_diagnostic/src/lib.rs b/crates/bevy_diagnostic/src/lib.rs index 88fdac61035e0..5db2c188b8666 100644 --- a/crates/bevy_diagnostic/src/lib.rs +++ b/crates/bevy_diagnostic/src/lib.rs @@ -11,6 +11,8 @@ //! It allows users to easily add diagnostic functionality to their Bevy applications, enhancing //! their ability to monitor and optimize their game's. +extern crate alloc; + mod diagnostic; mod entity_count_diagnostics_plugin; mod frame_time_diagnostics_plugin; diff --git a/crates/bevy_diagnostic/src/log_diagnostics_plugin.rs b/crates/bevy_diagnostic/src/log_diagnostics_plugin.rs index 2f007edcaaf50..d6e7a2e0b6a75 100644 --- a/crates/bevy_diagnostic/src/log_diagnostics_plugin.rs +++ b/crates/bevy_diagnostic/src/log_diagnostics_plugin.rs @@ -2,8 +2,10 @@ use super::{Diagnostic, DiagnosticPath, DiagnosticsStore}; use bevy_app::prelude::*; use bevy_ecs::prelude::*; use bevy_time::{Real, Time, Timer, TimerMode}; -use bevy_utils::tracing::{debug, info}; -use bevy_utils::Duration; +use bevy_utils::{ + tracing::{debug, info}, + Duration, +}; /// An App Plugin that logs diagnostics to the console. /// diff --git a/crates/bevy_ecs/examples/change_detection.rs b/crates/bevy_ecs/examples/change_detection.rs index 0f49c5e709f7d..41300653ba6fb 100644 --- a/crates/bevy_ecs/examples/change_detection.rs +++ b/crates/bevy_ecs/examples/change_detection.rs @@ -6,6 +6,8 @@ //! To demonstrate change detection, there are some console outputs based on changes in //! the `EntityCounter` resource and updated Age components +#![expect(clippy::std_instead_of_core)] + use bevy_ecs::prelude::*; use rand::Rng; use std::ops::Deref; diff --git a/crates/bevy_ecs/examples/resources.rs b/crates/bevy_ecs/examples/resources.rs index ff266fdd45234..f5de6f7b3d30e 100644 --- a/crates/bevy_ecs/examples/resources.rs +++ b/crates/bevy_ecs/examples/resources.rs @@ -1,6 +1,8 @@ //! In this example we add a counter resource and increase its value in one system, //! while a different system prints the current count to the console. +#![expect(clippy::std_instead_of_core)] + use bevy_ecs::prelude::*; use rand::Rng; use std::ops::Deref; diff --git a/crates/bevy_ecs/macros/src/lib.rs b/crates/bevy_ecs/macros/src/lib.rs index 291e9d116d93d..fc15c5c6c7979 100644 --- a/crates/bevy_ecs/macros/src/lib.rs +++ b/crates/bevy_ecs/macros/src/lib.rs @@ -118,7 +118,7 @@ pub fn derive_bundle(input: TokenStream) -> TokenStream { BundleFieldKind::Ignore => { field_from_components.push(quote! { - #field: ::std::default::Default::default(), + #field: ::core::default::Default::default(), }); } } diff --git a/crates/bevy_ecs/src/archetype.rs b/crates/bevy_ecs/src/archetype.rs index 7df84b87c4a79..3f5456370258c 100644 --- a/crates/bevy_ecs/src/archetype.rs +++ b/crates/bevy_ecs/src/archetype.rs @@ -27,7 +27,7 @@ use crate::{ storage::{ImmutableSparseSet, SparseArray, SparseSet, SparseSetIndex, TableId, TableRow}, }; use bevy_utils::HashMap; -use std::{ +use core::{ hash::Hash, ops::{Index, IndexMut, RangeFrom}, }; diff --git a/crates/bevy_ecs/src/batching.rs b/crates/bevy_ecs/src/batching.rs index 5143dfb73e426..902c56eebc584 100644 --- a/crates/bevy_ecs/src/batching.rs +++ b/crates/bevy_ecs/src/batching.rs @@ -1,6 +1,6 @@ //! Types for controlling batching behavior during parallel processing. -use std::ops::Range; +use core::ops::Range; /// Dictates how a parallel operation chunks up large quantities /// during iteration. diff --git a/crates/bevy_ecs/src/bundle.rs b/crates/bevy_ecs/src/bundle.rs index 607e14145aa57..fe1675705a6e2 100644 --- a/crates/bevy_ecs/src/bundle.rs +++ b/crates/bevy_ecs/src/bundle.rs @@ -23,8 +23,8 @@ use crate::{ use bevy_ptr::{ConstNonNull, OwningPtr}; use bevy_utils::{all_tuples, HashMap, HashSet, TypeIdMap}; #[cfg(feature = "track_change_detection")] -use std::panic::Location; -use std::{any::TypeId, ptr::NonNull}; +use core::panic::Location; +use core::{any::TypeId, ptr::NonNull}; /// The `Bundle` trait enables insertion and removal of [`Component`]s from an entity. /// @@ -1336,7 +1336,7 @@ impl Bundles { // - its info was created // - appropriate storage for it has been initialized. // - it was created in the same order as the components in T - unsafe { BundleInfo::new(std::any::type_name::(), components, component_ids, id) }; + unsafe { BundleInfo::new(core::any::type_name::(), components, component_ids, id) }; bundle_infos.push(bundle_info); id }); @@ -1446,9 +1446,7 @@ fn initialize_dynamic_bundle( #[cfg(test)] mod tests { use crate as bevy_ecs; - use crate::component::ComponentId; - use crate::prelude::*; - use crate::world::DeferredWorld; + use crate::{component::ComponentId, prelude::*, world::DeferredWorld}; #[derive(Component)] struct A; diff --git a/crates/bevy_ecs/src/change_detection.rs b/crates/bevy_ecs/src/change_detection.rs index 247825c285704..c35d09facf411 100644 --- a/crates/bevy_ecs/src/change_detection.rs +++ b/crates/bevy_ecs/src/change_detection.rs @@ -5,13 +5,16 @@ use crate::{ ptr::PtrMut, system::Resource, }; -#[cfg(feature = "track_change_detection")] -use bevy_ptr::ThinSlicePtr; use bevy_ptr::{Ptr, UnsafeCellDeref}; -use std::mem; -use std::ops::{Deref, DerefMut}; +use core::{ + mem, + ops::{Deref, DerefMut}, +}; #[cfg(feature = "track_change_detection")] -use std::{cell::UnsafeCell, panic::Location}; +use { + bevy_ptr::ThinSlicePtr, + core::{cell::UnsafeCell, panic::Location}, +}; /// The (arbitrarily chosen) minimum number of world tick increments between `check_tick` scans. /// @@ -456,10 +459,10 @@ macro_rules! impl_methods { macro_rules! impl_debug { ($name:ident < $( $generics:tt ),+ >, $($traits:ident)?) => { - impl<$($generics),* : ?Sized $(+ $traits)?> std::fmt::Debug for $name<$($generics),*> - where T: std::fmt::Debug + impl<$($generics),* : ?Sized $(+ $traits)?> core::fmt::Debug for $name<$($generics),*> + where T: core::fmt::Debug { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_tuple(stringify!($name)) .field(&self.value) .finish() @@ -1122,8 +1125,8 @@ impl<'w> DetectChangesMut for MutUntyped<'w> { } } -impl std::fmt::Debug for MutUntyped<'_> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for MutUntyped<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_tuple("MutUntyped") .field(&self.value.as_ptr()) .finish() @@ -1197,9 +1200,9 @@ mod tests { use bevy_ecs_macros::Resource; use bevy_ptr::PtrMut; use bevy_reflect::{FromType, ReflectFromPtr}; - use std::ops::{Deref, DerefMut}; + use core::ops::{Deref, DerefMut}; #[cfg(feature = "track_change_detection")] - use std::panic::Location; + use core::panic::Location; use crate::{ self as bevy_ecs, diff --git a/crates/bevy_ecs/src/component.rs b/crates/bevy_ecs/src/component.rs index 910bd9fc102bc..a4af8e02632b5 100644 --- a/crates/bevy_ecs/src/component.rs +++ b/crates/bevy_ecs/src/component.rs @@ -10,22 +10,22 @@ use crate::{ system::{Local, Resource, SystemParam}, world::{DeferredWorld, FromWorld, World}, }; +use alloc::{borrow::Cow, sync::Arc}; pub use bevy_ecs_macros::Component; use bevy_ptr::{OwningPtr, UnsafeCellDeref}; #[cfg(feature = "bevy_reflect")] use bevy_reflect::Reflect; use bevy_utils::{HashMap, TypeIdMap}; #[cfg(feature = "track_change_detection")] -use std::panic::Location; -use std::{ +use core::panic::Location; +use core::{ alloc::Layout, any::{Any, TypeId}, - borrow::Cow, + cell::UnsafeCell, + fmt::Debug, marker::PhantomData, mem::needs_drop, - sync::Arc, }; -use std::{cell::UnsafeCell, fmt::Debug}; /// A data type that can be used to store data for an [entity]. /// @@ -726,7 +726,7 @@ pub struct ComponentDescriptor { // We need to ignore the `drop` field in our `Debug` impl impl Debug for ComponentDescriptor { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("ComponentDescriptor") .field("name", &self.name) .field("storage_type", &self.storage_type) @@ -751,7 +751,7 @@ impl ComponentDescriptor { /// Create a new `ComponentDescriptor` for the type `T`. pub fn new() -> Self { Self { - name: Cow::Borrowed(std::any::type_name::()), + name: Cow::Borrowed(core::any::type_name::()), storage_type: T::STORAGE_TYPE, is_send_and_sync: true, type_id: Some(TypeId::of::()), @@ -786,7 +786,7 @@ impl ComponentDescriptor { /// The [`StorageType`] for resources is always [`StorageType::Table`]. pub fn new_resource() -> Self { Self { - name: Cow::Borrowed(std::any::type_name::()), + name: Cow::Borrowed(core::any::type_name::()), // PERF: `SparseStorage` may actually be a more // reasonable choice as `storage_type` for resources. storage_type: StorageType::Table, @@ -799,7 +799,7 @@ impl ComponentDescriptor { fn new_non_send(storage_type: StorageType) -> Self { Self { - name: Cow::Borrowed(std::any::type_name::()), + name: Cow::Borrowed(core::any::type_name::()), storage_type, is_send_and_sync: false, type_id: Some(TypeId::of::()), @@ -1270,7 +1270,7 @@ impl ComponentIdFor<'_, T> { } } -impl std::ops::Deref for ComponentIdFor<'_, T> { +impl core::ops::Deref for ComponentIdFor<'_, T> { type Target = ComponentId; fn deref(&self) -> &Self::Target { &self.0.component_id @@ -1351,7 +1351,7 @@ impl RequiredComponentConstructor { pub struct RequiredComponents(pub(crate) HashMap); impl Debug for RequiredComponents { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_tuple("RequiredComponents") .field(&self.0.keys()) .finish() diff --git a/crates/bevy_ecs/src/entity/hash.rs b/crates/bevy_ecs/src/entity/hash.rs index fac4ad12d8055..1b1ff531ffeb4 100644 --- a/crates/bevy_ecs/src/entity/hash.rs +++ b/crates/bevy_ecs/src/entity/hash.rs @@ -1,4 +1,4 @@ -use std::hash::{BuildHasher, Hasher}; +use core::hash::{BuildHasher, Hasher}; #[cfg(feature = "bevy_reflect")] use bevy_reflect::Reflect; diff --git a/crates/bevy_ecs/src/entity/map_entities.rs b/crates/bevy_ecs/src/entity/map_entities.rs index 8283e55e95204..96045d3597cf4 100644 --- a/crates/bevy_ecs/src/entity/map_entities.rs +++ b/crates/bevy_ecs/src/entity/map_entities.rs @@ -221,9 +221,8 @@ impl<'m> SceneEntityMapper<'m> { #[cfg(test)] mod tests { - use crate::entity::DynEntityMapper; use crate::{ - entity::{Entity, EntityHashMap, EntityMapper, SceneEntityMapper}, + entity::{DynEntityMapper, Entity, EntityHashMap, EntityMapper, SceneEntityMapper}, world::World, }; use bevy_utils::assert_object_safe; diff --git a/crates/bevy_ecs/src/entity/mod.rs b/crates/bevy_ecs/src/entity/mod.rs index 3ad78f73a21af..6df7f3603a1eb 100644 --- a/crates/bevy_ecs/src/entity/mod.rs +++ b/crates/bevy_ecs/src/entity/mod.rs @@ -57,12 +57,12 @@ use crate::{ }, storage::{SparseSetIndex, TableId, TableRow}, }; +use core::{fmt, hash::Hash, mem, num::NonZero, sync::atomic::Ordering}; #[cfg(feature = "serialize")] use serde::{Deserialize, Serialize}; -use std::{fmt, hash::Hash, mem, num::NonZero, sync::atomic::Ordering}; #[cfg(target_has_atomic = "64")] -use std::sync::atomic::AtomicI64 as AtomicIdCursor; +use core::sync::atomic::AtomicI64 as AtomicIdCursor; #[cfg(target_has_atomic = "64")] type IdCursor = i64; @@ -70,7 +70,7 @@ type IdCursor = i64; /// do not. This fallback allows compilation using a 32-bit cursor instead, with /// the caveat that some conversions may fail (and panic) at runtime. #[cfg(not(target_has_atomic = "64"))] -use std::sync::atomic::AtomicIsize as AtomicIdCursor; +use core::sync::atomic::AtomicIsize as AtomicIdCursor; #[cfg(not(target_has_atomic = "64"))] type IdCursor = isize; @@ -185,7 +185,7 @@ impl Eq for Entity {} // See impl PartialOrd for Entity { #[inline] - fn partial_cmp(&self, other: &Self) -> Option { + fn partial_cmp(&self, other: &Self) -> Option { // Make use of our `Ord` impl to ensure optimal codegen output Some(self.cmp(other)) } @@ -199,7 +199,7 @@ impl PartialOrd for Entity { // See impl Ord for Entity { #[inline] - fn cmp(&self, other: &Self) -> std::cmp::Ordering { + fn cmp(&self, other: &Self) -> core::cmp::Ordering { // This will result in better codegen for ordering comparisons, plus // avoids pitfalls with regards to macro codegen relying on property // position when we want to compare against the bit representation. @@ -209,7 +209,7 @@ impl Ord for Entity { impl Hash for Entity { #[inline] - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { self.to_bits().hash(state); } } @@ -451,10 +451,10 @@ pub struct ReserveEntitiesIterator<'a> { meta: &'a [EntityMeta], // Reserved indices formerly in the freelist to hand out. - freelist_indices: std::slice::Iter<'a, u32>, + freelist_indices: core::slice::Iter<'a, u32>, // New Entity indices to hand out, outside the range of meta.len(). - new_indices: std::ops::Range, + new_indices: core::ops::Range, } impl<'a> Iterator for ReserveEntitiesIterator<'a> { @@ -1160,7 +1160,7 @@ mod tests { // part of the best-case performance changes in PR#9903. #[test] fn entity_hash_keeps_similar_ids_together() { - use std::hash::BuildHasher; + use core::hash::BuildHasher; let hash = EntityHash; let first_id = 0xC0FFEE << 8; @@ -1175,7 +1175,7 @@ mod tests { #[test] fn entity_hash_id_bitflip_affects_high_7_bits() { - use std::hash::BuildHasher; + use core::hash::BuildHasher; let hash = EntityHash; diff --git a/crates/bevy_ecs/src/event/base.rs b/crates/bevy_ecs/src/event/base.rs index ab56ac58ae5b4..ca26a0abee2e6 100644 --- a/crates/bevy_ecs/src/event/base.rs +++ b/crates/bevy_ecs/src/event/base.rs @@ -1,7 +1,7 @@ use crate::{component::Component, traversal::Traversal}; #[cfg(feature = "bevy_reflect")] use bevy_reflect::Reflect; -use std::{ +use core::{ cmp::Ordering, fmt, hash::{Hash, Hasher}, @@ -82,7 +82,7 @@ impl fmt::Debug for EventId { write!( f, "event<{}>#{}", - std::any::type_name::().split("::").last().unwrap(), + core::any::type_name::().split("::").last().unwrap(), self.id, ) } diff --git a/crates/bevy_ecs/src/event/collections.rs b/crates/bevy_ecs/src/event/collections.rs index ea203bdc4648b..4c9bc1996f8da 100644 --- a/crates/bevy_ecs/src/event/collections.rs +++ b/crates/bevy_ecs/src/event/collections.rs @@ -1,15 +1,18 @@ use crate as bevy_ecs; -#[cfg(feature = "bevy_reflect")] -use bevy_ecs::reflect::ReflectResource; use bevy_ecs::{ event::{Event, EventCursor, EventId, EventInstance}, system::Resource, }; -#[cfg(feature = "bevy_reflect")] -use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_utils::detailed_trace; -use std::marker::PhantomData; -use std::ops::{Deref, DerefMut}; +use core::{ + marker::PhantomData, + ops::{Deref, DerefMut}, +}; +#[cfg(feature = "bevy_reflect")] +use { + bevy_ecs::reflect::ReflectResource, + bevy_reflect::{std_traits::ReflectDefault, Reflect}, +}; /// An event collection that represents the events that occurred within the last two /// [`Events::update`] calls. @@ -199,7 +202,7 @@ impl Events { /// /// If you need access to the events that were removed, consider using [`Events::update_drain`]. pub fn update(&mut self) { - std::mem::swap(&mut self.events_a, &mut self.events_b); + core::mem::swap(&mut self.events_a, &mut self.events_b); self.events_b.clear(); self.events_b.start_event_count = self.event_count; debug_assert_eq!( @@ -214,7 +217,7 @@ impl Events { /// If you do not need to take ownership of the removed events, use [`Events::update`] instead. #[must_use = "If you do not need the returned events, call .update() instead."] pub fn update_drain(&mut self) -> impl Iterator + '_ { - std::mem::swap(&mut self.events_a, &mut self.events_b); + core::mem::swap(&mut self.events_a, &mut self.events_b); let iter = self.events_b.events.drain(..); self.events_b.start_event_count = self.event_count; debug_assert_eq!( diff --git a/crates/bevy_ecs/src/event/event_cursor.rs b/crates/bevy_ecs/src/event/event_cursor.rs index 4868197712a6e..8fdcea8d244c5 100644 --- a/crates/bevy_ecs/src/event/event_cursor.rs +++ b/crates/bevy_ecs/src/event/event_cursor.rs @@ -4,7 +4,7 @@ use bevy_ecs::event::{ }; #[cfg(feature = "multi_threaded")] use bevy_ecs::event::{EventMutParIter, EventParIter}; -use std::marker::PhantomData; +use core::marker::PhantomData; // Deprecated in favor of `EventCursor`, there is no nice way to deprecate this // because generic constraints are not allowed in type aliases, so this will always diff --git a/crates/bevy_ecs/src/event/iterators.rs b/crates/bevy_ecs/src/event/iterators.rs index df1f9aae621d9..28c671fe947db 100644 --- a/crates/bevy_ecs/src/event/iterators.rs +++ b/crates/bevy_ecs/src/event/iterators.rs @@ -3,7 +3,7 @@ use crate as bevy_ecs; use bevy_ecs::batching::BatchingStrategy; use bevy_ecs::event::{Event, EventCursor, EventId, EventInstance, Events}; use bevy_utils::detailed_trace; -use std::{iter::Chain, slice::Iter}; +use core::{iter::Chain, slice::Iter}; /// An iterator that yields any unread events from an [`EventReader`](super::EventReader) or [`EventCursor`]. #[derive(Debug)] @@ -224,7 +224,7 @@ impl<'a, E: Event> EventParIter<'a, E> { .batching_strategy .calc_batch_size(|| self.len(), thread_count); let chunks = self.slices.map(|s| s.chunks_exact(batch_size)); - let remainders = chunks.each_ref().map(std::slice::ChunksExact::remainder); + let remainders = chunks.each_ref().map(core::slice::ChunksExact::remainder); pool.scope(|scope| { for batch in chunks.into_iter().flatten().chain(remainders) { diff --git a/crates/bevy_ecs/src/event/mod.rs b/crates/bevy_ecs/src/event/mod.rs index a570be5cab16e..f7f46af258a3c 100644 --- a/crates/bevy_ecs/src/event/mod.rs +++ b/crates/bevy_ecs/src/event/mod.rs @@ -423,7 +423,7 @@ mod tests { #[test] fn test_event_cursor_par_read() { use crate::prelude::*; - use std::sync::atomic::{AtomicUsize, Ordering}; + use core::sync::atomic::{AtomicUsize, Ordering}; #[derive(Resource)] struct Counter(AtomicUsize); @@ -465,7 +465,7 @@ mod tests { #[test] fn test_event_cursor_par_read_mut() { use crate::prelude::*; - use std::sync::atomic::{AtomicUsize, Ordering}; + use core::sync::atomic::{AtomicUsize, Ordering}; #[derive(Resource)] struct Counter(AtomicUsize); diff --git a/crates/bevy_ecs/src/event/mut_iterators.rs b/crates/bevy_ecs/src/event/mut_iterators.rs index 490503af7eb53..5f70875a31702 100644 --- a/crates/bevy_ecs/src/event/mut_iterators.rs +++ b/crates/bevy_ecs/src/event/mut_iterators.rs @@ -3,7 +3,7 @@ use crate as bevy_ecs; use bevy_ecs::batching::BatchingStrategy; use bevy_ecs::event::{Event, EventCursor, EventId, EventInstance, Events}; use bevy_utils::detailed_trace; -use std::{iter::Chain, slice::IterMut}; +use core::{iter::Chain, slice::IterMut}; /// An iterator that yields any unread events from an [`EventMutator`] or [`EventCursor`]. /// diff --git a/crates/bevy_ecs/src/event/update.rs b/crates/bevy_ecs/src/event/update.rs index 09bdc49ae1237..bf3c07de4d3c8 100644 --- a/crates/bevy_ecs/src/event/update.rs +++ b/crates/bevy_ecs/src/event/update.rs @@ -8,7 +8,7 @@ use bevy_ecs::{ }; use bevy_ecs_macros::SystemSet; #[cfg(feature = "bevy_reflect")] -use std::hash::Hash; +use core::hash::Hash; use super::registry::ShouldUpdateEvents; diff --git a/crates/bevy_ecs/src/identifier/error.rs b/crates/bevy_ecs/src/identifier/error.rs index 6f0ee8a972706..8d278528ab99c 100644 --- a/crates/bevy_ecs/src/identifier/error.rs +++ b/crates/bevy_ecs/src/identifier/error.rs @@ -1,7 +1,7 @@ //! Error types for [`super::Identifier`] conversions. An ID can be converted //! to various kinds, but these can fail if they are not valid forms of those //! kinds. The error type in this module encapsulates the various failure modes. -use std::fmt; +use core::fmt; /// An Error type for [`super::Identifier`], mostly for providing error /// handling for conversions of an ID to a type abstracting over the ID bits. @@ -26,4 +26,4 @@ impl fmt::Display for IdentifierError { } } -impl std::error::Error for IdentifierError {} +impl core::error::Error for IdentifierError {} diff --git a/crates/bevy_ecs/src/identifier/masks.rs b/crates/bevy_ecs/src/identifier/masks.rs index 85fb393cb6f13..30ece9d8e3eec 100644 --- a/crates/bevy_ecs/src/identifier/masks.rs +++ b/crates/bevy_ecs/src/identifier/masks.rs @@ -1,4 +1,4 @@ -use std::num::NonZero; +use core::num::NonZero; use super::kinds::IdKind; diff --git a/crates/bevy_ecs/src/identifier/mod.rs b/crates/bevy_ecs/src/identifier/mod.rs index 54bb29218b37a..0fb3ffdbeb766 100644 --- a/crates/bevy_ecs/src/identifier/mod.rs +++ b/crates/bevy_ecs/src/identifier/mod.rs @@ -7,7 +7,7 @@ use bevy_reflect::Reflect; use self::{error::IdentifierError, kinds::IdKind, masks::IdentifierMask}; -use std::{hash::Hash, num::NonZero}; +use core::{hash::Hash, num::NonZero}; pub mod error; pub(crate) mod kinds; @@ -149,7 +149,7 @@ impl Eq for Identifier {} // See impl PartialOrd for Identifier { #[inline] - fn partial_cmp(&self, other: &Self) -> Option { + fn partial_cmp(&self, other: &Self) -> Option { // Make use of our `Ord` impl to ensure optimal codegen output Some(self.cmp(other)) } @@ -163,7 +163,7 @@ impl PartialOrd for Identifier { // See impl Ord for Identifier { #[inline] - fn cmp(&self, other: &Self) -> std::cmp::Ordering { + fn cmp(&self, other: &Self) -> core::cmp::Ordering { // This will result in better codegen for ordering comparisons, plus // avoids pitfalls with regards to macro codegen relying on property // position when we want to compare against the bit representation. @@ -173,7 +173,7 @@ impl Ord for Identifier { impl Hash for Identifier { #[inline] - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { self.to_bits().hash(state); } } diff --git a/crates/bevy_ecs/src/intern.rs b/crates/bevy_ecs/src/intern.rs index 54ea4e32071bc..243ac55c9aab3 100644 --- a/crates/bevy_ecs/src/intern.rs +++ b/crates/bevy_ecs/src/intern.rs @@ -4,12 +4,8 @@ //! speed up code by shrinking the stack size of large types, //! and make comparisons for any type as fast as integers. -use std::{ - fmt::Debug, - hash::Hash, - ops::Deref, - sync::{OnceLock, PoisonError, RwLock}, -}; +use core::{fmt::Debug, hash::Hash, ops::Deref}; +use std::sync::{OnceLock, PoisonError, RwLock}; use bevy_utils::HashSet; @@ -71,13 +67,13 @@ impl Eq for Interned {} // Important: This must be kept in sync with the PartialEq/Eq implementation impl Hash for Interned { - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { self.0.ref_hash(state); } } impl Debug for Interned { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.0.fmt(f) } } @@ -99,7 +95,7 @@ pub trait Internable: Hash + Eq { fn ref_eq(&self, other: &Self) -> bool; /// Feeds the reference to the hasher. - fn ref_hash(&self, state: &mut H); + fn ref_hash(&self, state: &mut H); } impl Internable for str { @@ -112,7 +108,7 @@ impl Internable for str { self.as_ptr() == other.as_ptr() && self.len() == other.len() } - fn ref_hash(&self, state: &mut H) { + fn ref_hash(&self, state: &mut H) { self.len().hash(state); self.as_ptr().hash(state); } @@ -169,10 +165,8 @@ impl Default for Interner { #[cfg(test)] mod tests { - use std::{ - collections::hash_map::DefaultHasher, - hash::{Hash, Hasher}, - }; + use core::hash::{Hash, Hasher}; + use std::collections::hash_map::DefaultHasher; use crate::intern::{Internable, Interned, Interner}; @@ -187,11 +181,11 @@ mod tests { } fn ref_eq(&self, other: &Self) -> bool { - std::ptr::eq(self, other) + core::ptr::eq(self, other) } fn ref_hash(&self, state: &mut H) { - std::ptr::hash(self, state); + core::ptr::hash(self, state); } } @@ -218,11 +212,11 @@ mod tests { } fn ref_eq(&self, other: &Self) -> bool { - std::ptr::eq(self, other) + core::ptr::eq(self, other) } fn ref_hash(&self, state: &mut H) { - std::ptr::hash(self, state); + core::ptr::hash(self, state); } } diff --git a/crates/bevy_ecs/src/label.rs b/crates/bevy_ecs/src/label.rs index 519171eded9ef..e3f5078b22f71 100644 --- a/crates/bevy_ecs/src/label.rs +++ b/crates/bevy_ecs/src/label.rs @@ -1,10 +1,14 @@ //! Traits used by label implementations -use std::{ +use core::{ any::Any, hash::{Hash, Hasher}, }; +// Re-exported for use within `define_label!` +#[doc(hidden)] +pub use alloc::boxed::Box; + /// An object safe version of [`Eq`]. This trait is automatically implemented /// for any `'static` type that implements `Eq`. pub trait DynEq: Any { @@ -110,20 +114,20 @@ macro_rules! define_label { ) => { $(#[$label_attr])* - pub trait $label_trait_name: 'static + Send + Sync + ::std::fmt::Debug { + pub trait $label_trait_name: 'static + Send + Sync + ::core::fmt::Debug { $($trait_extra_methods)* /// Clones this ` #[doc = stringify!($label_trait_name)] ///`. - fn dyn_clone(&self) -> ::std::boxed::Box; + fn dyn_clone(&self) -> $crate::label::Box; /// Casts this value to a form where it can be compared with other type-erased values. fn as_dyn_eq(&self) -> &dyn $crate::label::DynEq; /// Feeds this value into the given [`Hasher`]. - fn dyn_hash(&self, state: &mut dyn ::std::hash::Hasher); + fn dyn_hash(&self, state: &mut dyn ::core::hash::Hasher); /// Returns an [`Interned`] value corresponding to `self`. fn intern(&self) -> $crate::intern::Interned @@ -136,7 +140,7 @@ macro_rules! define_label { $($interned_extra_methods_impl)* - fn dyn_clone(&self) -> ::std::boxed::Box { + fn dyn_clone(&self) -> $crate::label::Box { (**self).dyn_clone() } @@ -145,7 +149,7 @@ macro_rules! define_label { (**self).as_dyn_eq() } - fn dyn_hash(&self, state: &mut dyn ::std::hash::Hasher) { + fn dyn_hash(&self, state: &mut dyn ::core::hash::Hasher) { (**self).dyn_hash(state); } @@ -162,8 +166,8 @@ macro_rules! define_label { impl Eq for dyn $label_trait_name {} - impl ::std::hash::Hash for dyn $label_trait_name { - fn hash(&self, state: &mut H) { + impl ::core::hash::Hash for dyn $label_trait_name { + fn hash(&self, state: &mut H) { self.dyn_hash(state); } } @@ -174,15 +178,15 @@ macro_rules! define_label { } fn ref_eq(&self, other: &Self) -> bool { - use ::std::ptr; + use ::core::ptr; // Test that both the type id and pointer address are equivalent. self.as_dyn_eq().type_id() == other.as_dyn_eq().type_id() && ptr::addr_eq(ptr::from_ref::(self), ptr::from_ref::(other)) } - fn ref_hash(&self, state: &mut H) { - use ::std::{hash::Hash, ptr}; + fn ref_hash(&self, state: &mut H) { + use ::core::{hash::Hash, ptr}; // Hash the type id... self.as_dyn_eq().type_id().hash(state); diff --git a/crates/bevy_ecs/src/lib.rs b/crates/bevy_ecs/src/lib.rs index aa24c15a3c7d2..bffe35c6695ff 100644 --- a/crates/bevy_ecs/src/lib.rs +++ b/crates/bevy_ecs/src/lib.rs @@ -13,6 +13,8 @@ #[cfg(target_pointer_width = "16")] compile_error!("bevy_ecs cannot safely compile for a 16-bit platform."); +extern crate alloc; + pub mod archetype; pub mod batching; pub mod bundle; @@ -40,14 +42,6 @@ pub use bevy_ptr as ptr; /// /// This includes the most common types in this crate, re-exported for your convenience. pub mod prelude { - #[doc(hidden)] - #[cfg(feature = "reflect_functions")] - pub use crate::reflect::AppFunctionRegistry; - #[doc(hidden)] - #[cfg(feature = "bevy_reflect")] - pub use crate::reflect::{ - AppTypeRegistry, ReflectComponent, ReflectFromWorld, ReflectResource, - }; #[doc(hidden)] pub use crate::{ bundle::Bundle, @@ -72,33 +66,41 @@ pub mod prelude { OnReplace, World, }, }; + + #[doc(hidden)] + #[cfg(feature = "bevy_reflect")] + pub use crate::reflect::{ + AppTypeRegistry, ReflectComponent, ReflectFromWorld, ReflectResource, + }; + + #[doc(hidden)] + #[cfg(feature = "reflect_functions")] + pub use crate::reflect::AppFunctionRegistry; } #[cfg(test)] mod tests { use crate as bevy_ecs; - use crate::prelude::Or; - use crate::world::EntityMut; use crate::{ bundle::Bundle, change_detection::Ref, component::{Component, ComponentId}, entity::Entity, + prelude::Or, query::{Added, Changed, FilteredAccess, QueryFilter, With, Without}, system::Resource, - world::{EntityRef, Mut, World}, + world::{EntityMut, EntityRef, Mut, World}, }; + use alloc::sync::Arc; use bevy_tasks::{ComputeTaskPool, TaskPool}; use bevy_utils::HashSet; - use std::num::NonZero; - use std::{ + use core::{ any::TypeId, marker::PhantomData, - sync::{ - atomic::{AtomicUsize, Ordering}, - Arc, Mutex, - }, + num::NonZero, + sync::atomic::{AtomicUsize, Ordering}, }; + use std::sync::Mutex; #[derive(Component, Resource, Debug, PartialEq, Eq, Hash, Clone, Copy)] struct A(usize); diff --git a/crates/bevy_ecs/src/observer/entity_observer.rs b/crates/bevy_ecs/src/observer/entity_observer.rs index ce30201785758..0f9baba760a85 100644 --- a/crates/bevy_ecs/src/observer/entity_observer.rs +++ b/crates/bevy_ecs/src/observer/entity_observer.rs @@ -15,7 +15,7 @@ impl Component for ObservedBy { hooks.on_remove(|mut world, entity, _| { let observed_by = { let mut component = world.get_mut::(entity).unwrap(); - std::mem::take(&mut component.0) + core::mem::take(&mut component.0) }; for e in observed_by { let (total_entities, despawned_watched_entities) = { diff --git a/crates/bevy_ecs/src/observer/mod.rs b/crates/bevy_ecs/src/observer/mod.rs index a339bf6b1f479..be97293a8af38 100644 --- a/crates/bevy_ecs/src/observer/mod.rs +++ b/crates/bevy_ecs/src/observer/mod.rs @@ -7,14 +7,22 @@ mod trigger_event; pub use runner::*; pub use trigger_event::*; -use crate::entity::EntityHashMap; -use crate::observer::entity_observer::ObservedBy; -use crate::{archetype::ArchetypeFlags, system::IntoObserverSystem, world::*}; -use crate::{component::ComponentId, prelude::*, world::DeferredWorld}; +use crate::{ + archetype::ArchetypeFlags, + component::ComponentId, + entity::EntityHashMap, + observer::entity_observer::ObservedBy, + prelude::*, + system::IntoObserverSystem, + world::{DeferredWorld, *}, +}; use bevy_ptr::Ptr; use bevy_utils::HashMap; -use std::ops::{Deref, DerefMut}; -use std::{fmt::Debug, marker::PhantomData}; +use core::{ + fmt::Debug, + marker::PhantomData, + ops::{Deref, DerefMut}, +}; /// Type containing triggered [`Event`] information for a given run of an [`Observer`]. This contains the /// [`Event`] data itself. If it was triggered for a specific [`Entity`], it includes that as well. It also @@ -113,7 +121,7 @@ impl<'w, E, B: Bundle> Trigger<'w, E, B> { } impl<'w, E: Debug, B: Bundle> Debug for Trigger<'w, E, B> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("Trigger") .field("event", &self.event) .field("propagate", &self.propagate) @@ -520,16 +528,16 @@ impl World { #[cfg(test)] mod tests { - use std::vec; + use alloc::vec; use bevy_ptr::OwningPtr; use crate as bevy_ecs; - use crate::observer::{ - EmitDynamicTrigger, Observer, ObserverDescriptor, ObserverState, OnReplace, + use crate::{ + observer::{EmitDynamicTrigger, Observer, ObserverDescriptor, ObserverState, OnReplace}, + prelude::*, + traversal::Traversal, }; - use crate::prelude::*; - use crate::traversal::Traversal; #[derive(Component)] struct A; diff --git a/crates/bevy_ecs/src/observer/runner.rs b/crates/bevy_ecs/src/observer/runner.rs index a23172fa862c9..f7d298cb5c2e8 100644 --- a/crates/bevy_ecs/src/observer/runner.rs +++ b/crates/bevy_ecs/src/observer/runner.rs @@ -1,4 +1,4 @@ -use std::any::Any; +use core::any::Any; use crate::{ component::{ComponentHook, ComponentHooks, ComponentId, StorageType}, @@ -70,7 +70,7 @@ impl Component for ObserverState { }); }); hooks.on_remove(|mut world, entity, _| { - let descriptor = std::mem::take( + let descriptor = core::mem::take( &mut world .entity_mut(entity) .get_mut::() diff --git a/crates/bevy_ecs/src/observer/trigger_event.rs b/crates/bevy_ecs/src/observer/trigger_event.rs index ce368d9398f92..be649d93e206d 100644 --- a/crates/bevy_ecs/src/observer/trigger_event.rs +++ b/crates/bevy_ecs/src/observer/trigger_event.rs @@ -129,7 +129,7 @@ impl TriggerTargets for Entity { } fn entities(&self) -> &[Entity] { - std::slice::from_ref(self) + core::slice::from_ref(self) } } @@ -155,7 +155,7 @@ impl TriggerTargets for [Entity; N] { impl TriggerTargets for ComponentId { fn components(&self) -> &[ComponentId] { - std::slice::from_ref(self) + core::slice::from_ref(self) } fn entities(&self) -> &[Entity] { diff --git a/crates/bevy_ecs/src/query/access.rs b/crates/bevy_ecs/src/query/access.rs index 0f5fb318af7a8..cf504c2606635 100644 --- a/crates/bevy_ecs/src/query/access.rs +++ b/crates/bevy_ecs/src/query/access.rs @@ -1,8 +1,6 @@ use crate::storage::SparseSetIndex; -use core::fmt; +use core::{fmt, fmt::Debug, marker::PhantomData}; use fixedbitset::FixedBitSet; -use std::fmt::Debug; -use std::marker::PhantomData; /// A wrapper struct to make Debug representations of [`FixedBitSet`] easier /// to read, when used to store [`SparseSetIndex`]. @@ -1277,10 +1275,11 @@ impl Default for FilteredAccessSet { #[cfg(test)] mod tests { - use crate::query::access::AccessFilters; - use crate::query::{Access, AccessConflicts, FilteredAccess, FilteredAccessSet}; + use crate::query::{ + access::AccessFilters, Access, AccessConflicts, FilteredAccess, FilteredAccessSet, + }; + use core::marker::PhantomData; use fixedbitset::FixedBitSet; - use std::marker::PhantomData; fn create_sample_access() -> Access { let mut access = Access::::default(); diff --git a/crates/bevy_ecs/src/query/builder.rs b/crates/bevy_ecs/src/query/builder.rs index 2f4217e711aae..30d6d5feaaa8f 100644 --- a/crates/bevy_ecs/src/query/builder.rs +++ b/crates/bevy_ecs/src/query/builder.rs @@ -1,7 +1,9 @@ -use std::marker::PhantomData; +use core::marker::PhantomData; -use crate::component::StorageType; -use crate::{component::ComponentId, prelude::*}; +use crate::{ + component::{ComponentId, StorageType}, + prelude::*, +}; use super::{FilteredAccess, QueryData, QueryFilter}; @@ -260,7 +262,7 @@ impl<'w, D: QueryData, F: QueryFilter> QueryBuilder<'w, D, F> { // SAFETY: // - We have included all required accesses for NewQ and NewF // - The layout of all QueryBuilder instances is the same - unsafe { std::mem::transmute(self) } + unsafe { core::mem::transmute(self) } } /// Create a [`QueryState`] with the accesses of the builder. @@ -275,8 +277,7 @@ impl<'w, D: QueryData, F: QueryFilter> QueryBuilder<'w, D, F> { #[cfg(test)] mod tests { use crate as bevy_ecs; - use crate::prelude::*; - use crate::world::FilteredEntityRef; + use crate::{prelude::*, world::FilteredEntityRef}; #[derive(Component, PartialEq, Debug)] struct A(usize); diff --git a/crates/bevy_ecs/src/query/fetch.rs b/crates/bevy_ecs/src/query/fetch.rs index 311ddcc9aaaaa..a69242980223f 100644 --- a/crates/bevy_ecs/src/query/fetch.rs +++ b/crates/bevy_ecs/src/query/fetch.rs @@ -13,8 +13,8 @@ use crate::{ }; use bevy_ptr::{ThinSlicePtr, UnsafeCellDeref}; use bevy_utils::all_tuples; +use core::{cell::UnsafeCell, marker::PhantomData}; use smallvec::SmallVec; -use std::{cell::UnsafeCell, marker::PhantomData}; /// Types that can be fetched from a [`World`] using a [`Query`]. /// @@ -846,7 +846,7 @@ where assert!( access.is_compatible(&my_access), "`EntityRefExcept<{}>` conflicts with a previous access in this query.", - std::any::type_name::(), + core::any::type_name::(), ); access.extend(&my_access); } @@ -945,7 +945,7 @@ where assert!( access.is_compatible(&my_access), "`EntityMutExcept<{}>` conflicts with a previous access in this query.", - std::any::type_name::() + core::any::type_name::() ); access.extend(&my_access); } @@ -1182,7 +1182,7 @@ unsafe impl WorldQuery for &T { assert!( !access.access().has_component_write(component_id), "&{} conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.", - std::any::type_name::(), + core::any::type_name::(), ); access.add_component_read(component_id); } @@ -1381,7 +1381,7 @@ unsafe impl<'__w, T: Component> WorldQuery for Ref<'__w, T> { assert!( !access.access().has_component_write(component_id), "&{} conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.", - std::any::type_name::(), + core::any::type_name::(), ); access.add_component_read(component_id); } @@ -1580,7 +1580,7 @@ unsafe impl<'__w, T: Component> WorldQuery for &'__w mut T { assert!( !access.access().has_component_read(component_id), "&mut {} conflicts with a previous access in this query. Mutable component access must be unique.", - std::any::type_name::(), + core::any::type_name::(), ); access.add_component_write(component_id); } @@ -1682,7 +1682,7 @@ unsafe impl<'__w, T: Component> WorldQuery for Mut<'__w, T> { assert!( !access.access().has_component_read(component_id), "Mut<{}> conflicts with a previous access in this query. Mutable component access mut be unique.", - std::any::type_name::(), + core::any::type_name::(), ); access.add_component_write(component_id); } @@ -1905,9 +1905,9 @@ unsafe impl ReadOnlyQueryData for Option {} /// ``` pub struct Has(PhantomData); -impl std::fmt::Debug for Has { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { - write!(f, "Has<{}>", std::any::type_name::()) +impl core::fmt::Debug for Has { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> { + write!(f, "Has<{}>", core::any::type_name::()) } } diff --git a/crates/bevy_ecs/src/query/filter.rs b/crates/bevy_ecs/src/query/filter.rs index ee447ec99bc42..860314b231a87 100644 --- a/crates/bevy_ecs/src/query/filter.rs +++ b/crates/bevy_ecs/src/query/filter.rs @@ -8,7 +8,7 @@ use crate::{ }; use bevy_ptr::{ThinSlicePtr, UnsafeCellDeref}; use bevy_utils::all_tuples; -use std::{cell::UnsafeCell, marker::PhantomData}; +use core::{cell::UnsafeCell, marker::PhantomData}; /// Types that filter the results of a [`Query`]. /// @@ -478,7 +478,7 @@ macro_rules! impl_or_query_filter { )* // The required components remain the same as the original `access`. - _new_access.required = std::mem::take(&mut access.required); + _new_access.required = core::mem::take(&mut access.required); *access = _new_access; } @@ -724,7 +724,7 @@ unsafe impl WorldQuery for Added { #[inline] fn update_component_access(&id: &ComponentId, access: &mut FilteredAccess) { if access.access().has_component_write(id) { - panic!("$state_name<{}> conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.",std::any::type_name::()); + panic!("$state_name<{}> conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.",core::any::type_name::()); } access.add_component_read(id); } @@ -942,7 +942,7 @@ unsafe impl WorldQuery for Changed { #[inline] fn update_component_access(&id: &ComponentId, access: &mut FilteredAccess) { if access.access().has_component_write(id) { - panic!("$state_name<{}> conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.",std::any::type_name::()); + panic!("$state_name<{}> conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.",core::any::type_name::()); } access.add_component_read(id); } diff --git a/crates/bevy_ecs/src/query/iter.rs b/crates/bevy_ecs/src/query/iter.rs index 6522a1b2372ba..290ad3346b999 100644 --- a/crates/bevy_ecs/src/query/iter.rs +++ b/crates/bevy_ecs/src/query/iter.rs @@ -6,7 +6,7 @@ use crate::{ storage::{Table, TableRow, Tables}, world::unsafe_world_cell::UnsafeWorldCell, }; -use std::{ +use core::{ borrow::Borrow, cmp::Ordering, fmt::{self, Debug, Formatter}, @@ -1706,7 +1706,7 @@ impl<'w, 's, D: QueryData, F: QueryFilter, const K: usize> Debug struct QueryIterationCursor<'w, 's, D: QueryData, F: QueryFilter> { // whether the query iteration is dense or not. Mirrors QueryState's `is_dense` field. is_dense: bool, - storage_id_iter: std::slice::Iter<'s, StorageId>, + storage_id_iter: core::slice::Iter<'s, StorageId>, table_entities: &'w [Entity], archetype_entities: &'w [ArchetypeEntity], fetch: D::Fetch<'w>, @@ -1983,7 +1983,13 @@ impl Ord for NeutralOrd { #[cfg(test)] mod tests { #[allow(unused_imports)] - use crate::{self as bevy_ecs, component::Component, entity::Entity, prelude::World}; + use crate::component::Component; + #[allow(unused_imports)] + use crate::entity::Entity; + #[allow(unused_imports)] + use crate::prelude::World; + #[allow(unused_imports)] + use crate::{self as bevy_ecs}; #[derive(Component, Debug, PartialEq, PartialOrd, Clone, Copy)] struct A(f32); diff --git a/crates/bevy_ecs/src/query/mod.rs b/crates/bevy_ecs/src/query/mod.rs index 3102a37d14108..0a9f664fb50ba 100644 --- a/crates/bevy_ecs/src/query/mod.rs +++ b/crates/bevy_ecs/src/query/mod.rs @@ -82,7 +82,7 @@ impl DebugCheckedUnwrap for Result { if let Ok(inner) = self { inner } else { - std::hint::unreachable_unchecked() + core::hint::unreachable_unchecked() } } } @@ -96,23 +96,25 @@ impl DebugCheckedUnwrap for Option { if let Some(inner) = self { inner } else { - std::hint::unreachable_unchecked() + core::hint::unreachable_unchecked() } } } #[cfg(test)] mod tests { - use crate::prelude::{AnyOf, Changed, Entity, Or, QueryState, With, Without}; - use crate::query::{ArchetypeFilter, Has, QueryCombinationIter, ReadOnlyQueryData}; - use crate::schedule::{IntoSystemConfigs, Schedule}; - use crate::system::{IntoSystem, Query, System, SystemState}; - use crate::{self as bevy_ecs, component::Component, world::World}; + use crate::{ + self as bevy_ecs, + component::Component, + prelude::{AnyOf, Changed, Entity, Or, QueryState, With, Without}, + query::{ArchetypeFilter, Has, QueryCombinationIter, ReadOnlyQueryData}, + schedule::{IntoSystemConfigs, Schedule}, + system::{IntoSystem, Query, System, SystemState}, + world::World, + }; use bevy_ecs_macros::{QueryData, QueryFilter}; - use std::any::type_name; + use core::{any::type_name, fmt::Debug, hash::Hash}; use std::collections::HashSet; - use std::fmt::Debug; - use std::hash::Hash; #[derive(Component, Debug, Hash, Eq, PartialEq, Clone, Copy, PartialOrd, Ord)] struct A(usize); diff --git a/crates/bevy_ecs/src/query/state.rs b/crates/bevy_ecs/src/query/state.rs index 6ac740255c055..a63312b01a4bf 100644 --- a/crates/bevy_ecs/src/query/state.rs +++ b/crates/bevy_ecs/src/query/state.rs @@ -13,8 +13,8 @@ use crate::{ use bevy_utils::tracing::warn; #[cfg(feature = "trace")] use bevy_utils::tracing::Span; +use core::{borrow::Borrow, fmt, mem::MaybeUninit, ptr}; use fixedbitset::FixedBitSet; -use std::{borrow::Borrow, fmt, mem::MaybeUninit, ptr}; use super::{ NopWorldQuery, QueryBuilder, QueryData, QueryEntityError, QueryFilter, QueryManyIter, @@ -217,8 +217,8 @@ impl QueryState { #[cfg(feature = "trace")] par_iter_span: bevy_utils::tracing::info_span!( "par_for_each", - query = std::any::type_name::(), - filter = std::any::type_name::(), + query = core::any::type_name::(), + filter = core::any::type_name::(), ), } } @@ -243,8 +243,8 @@ impl QueryState { #[cfg(feature = "trace")] par_iter_span: bevy_utils::tracing::info_span!( "par_for_each", - data = std::any::type_name::(), - filter = std::any::type_name::(), + data = core::any::type_name::(), + filter = core::any::type_name::(), ), }; state.update_archetypes(builder.world()); @@ -357,7 +357,7 @@ impl QueryState { if self.component_access.required.is_empty() { let archetypes = world.archetypes(); let old_generation = - std::mem::replace(&mut self.archetype_generation, archetypes.generation()); + core::mem::replace(&mut self.archetype_generation, archetypes.generation()); for archetype in &archetypes[old_generation..] { // SAFETY: The validate_world call ensures that the world is the same the QueryState @@ -590,7 +590,7 @@ impl QueryState { assert!( component_access.is_subset(&self.component_access), "Transmuted state for {} attempts to access terms that are not allowed by original state {}.", - std::any::type_name::<(NewD, NewF)>(), std::any::type_name::<(D, F)>() + core::any::type_name::<(NewD, NewF)>(), core::any::type_name::<(D, F)>() ); QueryState { @@ -606,8 +606,8 @@ impl QueryState { #[cfg(feature = "trace")] par_iter_span: bevy_utils::tracing::info_span!( "par_for_each", - query = std::any::type_name::(), - filter = std::any::type_name::(), + query = core::any::type_name::(), + filter = core::any::type_name::(), ), } } @@ -684,7 +684,7 @@ impl QueryState { assert!( component_access.is_subset(&joined_component_access), "Joined state for {} attempts to access terms that are not allowed by state {} joined with {}.", - std::any::type_name::<(NewD, NewF)>(), std::any::type_name::<(D, F)>(), std::any::type_name::<(OtherD, OtherF)>() + core::any::type_name::<(NewD, NewF)>(), core::any::type_name::<(D, F)>(), core::any::type_name::<(OtherD, OtherF)>() ); if self.archetype_generation != other.archetype_generation { @@ -728,8 +728,8 @@ impl QueryState { #[cfg(feature = "trace")] par_iter_span: bevy_utils::tracing::info_span!( "par_for_each", - query = std::any::type_name::(), - filter = std::any::type_name::(), + query = core::any::type_name::(), + filter = core::any::type_name::(), ), } } @@ -1011,7 +1011,7 @@ impl QueryState { ) -> Result<[ROQueryItem<'w, D>; N], QueryEntityError> { let mut values = [(); N].map(|_| MaybeUninit::uninit()); - for (value, entity) in std::iter::zip(&mut values, entities) { + for (value, entity) in core::iter::zip(&mut values, entities) { // SAFETY: fetch is read-only and world must be validated let item = unsafe { self.as_readonly() @@ -1054,7 +1054,7 @@ impl QueryState { let mut values = [(); N].map(|_| MaybeUninit::uninit()); - for (value, entity) in std::iter::zip(&mut values, entities) { + for (value, entity) in core::iter::zip(&mut values, entities) { let item = self.get_unchecked_manual(world, entity, last_run, this_run)?; *value = MaybeUninit::new(item); } @@ -1511,7 +1511,7 @@ impl QueryState { if queue.is_empty() { return; } - let queue = std::mem::take(queue); + let queue = core::mem::take(queue); let mut func = func.clone(); let init_accum = init_accum.clone(); scope.spawn(async move { @@ -1702,8 +1702,8 @@ impl QueryState { match (first, extra) { (Some(r), false) => Ok(r), - (None, _) => Err(QuerySingleError::NoEntities(std::any::type_name::())), - (Some(_), _) => Err(QuerySingleError::MultipleEntities(std::any::type_name::< + (None, _) => Err(QuerySingleError::NoEntities(core::any::type_name::())), + (Some(_), _) => Err(QuerySingleError::MultipleEntities(core::any::type_name::< Self, >())), } @@ -1719,8 +1719,9 @@ impl From> for QueryState FromType for ReflectBundle { _ => panic!( "expected bundle `{}` to be named struct or tuple", // FIXME: once we have unique reflect, use `TypePath`. - std::any::type_name::(), + core::any::type_name::(), ), } } @@ -170,7 +170,7 @@ impl FromType for ReflectBundle { _ => panic!( "expected bundle `{}` to be named struct or tuple", // FIXME: once we have unique reflect, use `TypePath`. - std::any::type_name::(), + core::any::type_name::(), ), } } diff --git a/crates/bevy_ecs/src/reflect/entity_commands.rs b/crates/bevy_ecs/src/reflect/entity_commands.rs index 52e6800a495ed..de3a185a97536 100644 --- a/crates/bevy_ecs/src/reflect/entity_commands.rs +++ b/crates/bevy_ecs/src/reflect/entity_commands.rs @@ -1,15 +1,13 @@ -use crate::prelude::Mut; -use crate::reflect::AppTypeRegistry; -use crate::system::{EntityCommands, Resource}; -use crate::world::Command; use crate::{ entity::Entity, - reflect::{ReflectBundle, ReflectComponent}, - world::World, + prelude::Mut, + reflect::{AppTypeRegistry, ReflectBundle, ReflectComponent}, + system::{EntityCommands, Resource}, + world::{Command, World}, }; +use alloc::borrow::Cow; use bevy_reflect::{PartialReflect, TypeRegistry}; -use std::borrow::Cow; -use std::marker::PhantomData; +use core::marker::PhantomData; /// An extension trait for [`EntityCommands`] for reflection related functions pub trait ReflectCommandExt { @@ -351,10 +349,15 @@ impl> Command for RemoveReflectWithRegistry #[cfg(test)] mod tests { - use crate::prelude::{AppTypeRegistry, ReflectComponent}; - use crate::reflect::{ReflectBundle, ReflectCommandExt}; - use crate::system::{Commands, SystemState}; - use crate::{self as bevy_ecs, bundle::Bundle, component::Component, world::World}; + use crate::{ + self as bevy_ecs, + bundle::Bundle, + component::Component, + prelude::{AppTypeRegistry, ReflectComponent}, + reflect::{ReflectBundle, ReflectCommandExt}, + system::{Commands, SystemState}, + world::World, + }; use bevy_ecs_macros::Resource; use bevy_reflect::{PartialReflect, Reflect, TypeRegistry}; diff --git a/crates/bevy_ecs/src/reflect/mod.rs b/crates/bevy_ecs/src/reflect/mod.rs index ae02af891314f..5508f87af4871 100644 --- a/crates/bevy_ecs/src/reflect/mod.rs +++ b/crates/bevy_ecs/src/reflect/mod.rs @@ -1,13 +1,15 @@ //! Types that enable reflection support. -use std::any::TypeId; -use std::ops::{Deref, DerefMut}; +use core::{ + any::TypeId, + ops::{Deref, DerefMut}, +}; use crate as bevy_ecs; use crate::{system::Resource, world::World}; -use bevy_reflect::std_traits::ReflectDefault; use bevy_reflect::{ - PartialReflect, Reflect, ReflectFromReflect, TypePath, TypeRegistry, TypeRegistryArc, + std_traits::ReflectDefault, PartialReflect, Reflect, ReflectFromReflect, TypePath, + TypeRegistry, TypeRegistryArc, }; mod bundle; @@ -135,7 +137,7 @@ pub fn from_reflect_with_fallback( `Default` or `FromWorld` traits. Are you perhaps missing a `#[reflect(Default)]` \ or `#[reflect(FromWorld)]`?", // FIXME: once we have unique reflect, use `TypePath`. - std::any::type_name::(), + core::any::type_name::(), ); }; diff --git a/crates/bevy_ecs/src/removal_detection.rs b/crates/bevy_ecs/src/removal_detection.rs index f55af1f5c6c5e..e4ecaad7431a8 100644 --- a/crates/bevy_ecs/src/removal_detection.rs +++ b/crates/bevy_ecs/src/removal_detection.rs @@ -11,7 +11,7 @@ use crate::{ world::{unsafe_world_cell::UnsafeWorldCell, World}, }; -use std::{ +use core::{ fmt::Debug, iter, marker::PhantomData, diff --git a/crates/bevy_ecs/src/schedule/condition.rs b/crates/bevy_ecs/src/schedule/condition.rs index 924f8cd0b873a..007b6d4767e6b 100644 --- a/crates/bevy_ecs/src/schedule/condition.rs +++ b/crates/bevy_ecs/src/schedule/condition.rs @@ -1,5 +1,5 @@ -use std::borrow::Cow; -use std::ops::Not; +use alloc::borrow::Cow; +use core::ops::Not; use crate::system::{ Adapt, AdapterSystem, CombinatorSystem, Combine, IntoSystem, ReadOnlySystem, System, SystemIn, @@ -1065,7 +1065,7 @@ pub mod common_conditions { /// ``` pub fn not(condition: T) -> NotSystem where - TOut: std::ops::Not, + TOut: core::ops::Not, T: IntoSystem<(), TOut, Marker>, { let condition = IntoSystem::into_system(condition); @@ -1351,12 +1351,14 @@ where mod tests { use super::{common_conditions::*, Condition}; use crate as bevy_ecs; - use crate::component::Component; - use crate::schedule::IntoSystemConfigs; - use crate::system::Local; - use crate::{change_detection::ResMut, schedule::Schedule, world::World}; - use bevy_ecs_macros::Event; - use bevy_ecs_macros::Resource; + use crate::{ + change_detection::ResMut, + component::Component, + schedule::{IntoSystemConfigs, Schedule}, + system::Local, + world::World, + }; + use bevy_ecs_macros::{Event, Resource}; #[derive(Resource, Default)] struct Counter(usize); diff --git a/crates/bevy_ecs/src/schedule/executor/mod.rs b/crates/bevy_ecs/src/schedule/executor/mod.rs index 952bf5b39dab3..3d96d3cb747ba 100644 --- a/crates/bevy_ecs/src/schedule/executor/mod.rs +++ b/crates/bevy_ecs/src/schedule/executor/mod.rs @@ -2,9 +2,11 @@ mod multi_threaded; mod simple; mod single_threaded; -pub use self::multi_threaded::{MainThreadExecutor, MultiThreadedExecutor}; -pub use self::simple::SimpleExecutor; -pub use self::single_threaded::SingleThreadedExecutor; +pub use self::{ + multi_threaded::{MainThreadExecutor, MultiThreadedExecutor}, + simple::SimpleExecutor, + single_threaded::SingleThreadedExecutor, +}; use fixedbitset::FixedBitSet; @@ -134,7 +136,7 @@ pub(super) fn is_apply_deferred(system: &BoxedSystem) -> bool { /// This is reliant on undocumented behavior in Rust's default panic handler, which checks the call stack for symbols /// containing the string `__rust_begin_short_backtrace` in their mangled name. mod __rust_begin_short_backtrace { - use std::hint::black_box; + use core::hint::black_box; use crate::{ system::{ReadOnlySystem, System}, diff --git a/crates/bevy_ecs/src/schedule/executor/multi_threaded.rs b/crates/bevy_ecs/src/schedule/executor/multi_threaded.rs index 92f71362ea884..8782793e32f71 100644 --- a/crates/bevy_ecs/src/schedule/executor/multi_threaded.rs +++ b/crates/bevy_ecs/src/schedule/executor/multi_threaded.rs @@ -1,14 +1,14 @@ -use std::{ - any::Any, - sync::{Arc, Mutex, MutexGuard}, -}; +use alloc::sync::Arc; +use core::any::Any; +use std::sync::{Mutex, MutexGuard}; use bevy_tasks::{ComputeTaskPool, Scope, TaskPool, ThreadExecutor}; -use bevy_utils::default; -use bevy_utils::syncunsafecell::SyncUnsafeCell; #[cfg(feature = "trace")] -use bevy_utils::tracing::{info_span, Span}; -use std::panic::AssertUnwindSafe; +use bevy_utils::tracing::info_span; +#[cfg(feature = "trace")] +use bevy_utils::tracing::Span; +use bevy_utils::{default, syncunsafecell::SyncUnsafeCell}; +use core::panic::AssertUnwindSafe; use concurrent_queue::ConcurrentQueue; use fixedbitset::FixedBitSet; @@ -382,7 +382,7 @@ impl ExecutorState { } // can't borrow since loop mutably borrows `self` - let mut ready_systems = std::mem::take(&mut self.ready_systems_copy); + let mut ready_systems = core::mem::take(&mut self.ready_systems_copy); // Skipping systems may cause their dependents to become ready immediately. // If that happens, we need to run again immediately or we may fail to spawn those dependents. diff --git a/crates/bevy_ecs/src/schedule/executor/simple.rs b/crates/bevy_ecs/src/schedule/executor/simple.rs index 3a7dd05397342..171125342cd78 100644 --- a/crates/bevy_ecs/src/schedule/executor/simple.rs +++ b/crates/bevy_ecs/src/schedule/executor/simple.rs @@ -1,7 +1,7 @@ #[cfg(feature = "trace")] use bevy_utils::tracing::info_span; +use core::panic::AssertUnwindSafe; use fixedbitset::FixedBitSet; -use std::panic::AssertUnwindSafe; use crate::{ schedule::{ diff --git a/crates/bevy_ecs/src/schedule/executor/single_threaded.rs b/crates/bevy_ecs/src/schedule/executor/single_threaded.rs index 3ae907c4f5f26..93d814d3b2f83 100644 --- a/crates/bevy_ecs/src/schedule/executor/single_threaded.rs +++ b/crates/bevy_ecs/src/schedule/executor/single_threaded.rs @@ -1,7 +1,7 @@ #[cfg(feature = "trace")] use bevy_utils::tracing::info_span; +use core::panic::AssertUnwindSafe; use fixedbitset::FixedBitSet; -use std::panic::AssertUnwindSafe; use crate::{ schedule::{is_apply_deferred, BoxedCondition, ExecutorKind, SystemExecutor, SystemSchedule}, diff --git a/crates/bevy_ecs/src/schedule/graph_utils.rs b/crates/bevy_ecs/src/schedule/graph_utils.rs index 2fcbb6df90f2b..a92579ca58293 100644 --- a/crates/bevy_ecs/src/schedule/graph_utils.rs +++ b/crates/bevy_ecs/src/schedule/graph_utils.rs @@ -1,4 +1,4 @@ -use std::fmt::Debug; +use core::fmt::Debug; use bevy_utils::{HashMap, HashSet}; use fixedbitset::FixedBitSet; diff --git a/crates/bevy_ecs/src/schedule/mod.rs b/crates/bevy_ecs/src/schedule/mod.rs index 28aa65c59d2b9..68dc5fd78a0a8 100644 --- a/crates/bevy_ecs/src/schedule/mod.rs +++ b/crates/bevy_ecs/src/schedule/mod.rs @@ -9,24 +9,22 @@ mod schedule; mod set; mod stepping; -pub use self::condition::*; -pub use self::config::*; -pub use self::executor::*; use self::graph_utils::*; -pub use self::schedule::*; -pub use self::set::*; +pub use self::{condition::*, config::*, executor::*, schedule::*, set::*}; pub use self::graph_utils::NodeId; #[cfg(test)] mod tests { use super::*; - use std::sync::atomic::{AtomicU32, Ordering}; + use core::sync::atomic::{AtomicU32, Ordering}; pub use crate as bevy_ecs; - pub use crate::schedule::{Schedule, SystemSet}; - pub use crate::system::{Res, ResMut}; - pub use crate::{prelude::World, system::Resource}; + pub use crate::{ + prelude::World, + schedule::{Schedule, SystemSet}, + system::{Res, ResMut, Resource}, + }; #[derive(SystemSet, Clone, Debug, PartialEq, Eq, Hash)] enum TestSet { @@ -98,8 +96,9 @@ mod tests { #[test] #[cfg(not(miri))] fn parallel_execution() { + use alloc::sync::Arc; use bevy_tasks::{ComputeTaskPool, TaskPool}; - use std::sync::{Arc, Barrier}; + use std::sync::Barrier; let mut world = World::default(); let mut schedule = Schedule::default(); @@ -717,7 +716,7 @@ mod tests { } mod system_ambiguity { - use std::collections::BTreeSet; + use alloc::collections::BTreeSet; use super::*; // Required to make the derive macro behave diff --git a/crates/bevy_ecs/src/schedule/schedule.rs b/crates/bevy_ecs/src/schedule/schedule.rs index 83d0fbc64470a..fbc5198e421dc 100644 --- a/crates/bevy_ecs/src/schedule/schedule.rs +++ b/crates/bevy_ecs/src/schedule/schedule.rs @@ -1,13 +1,11 @@ -use std::{ - collections::BTreeSet, - fmt::{Debug, Write}, -}; +use alloc::collections::BTreeSet; +use core::fmt::{Debug, Write}; #[cfg(feature = "trace")] use bevy_utils::tracing::info_span; -use bevy_utils::{default, tracing::info}; use bevy_utils::{ - tracing::{error, warn}, + default, + tracing::{error, info, warn}, HashMap, HashSet, }; use disqualified::ShortName; @@ -24,8 +22,7 @@ use crate::{ world::World, }; -use crate::query::AccessConflicts; -use crate::storage::SparseSetIndex; +use crate::{query::AccessConflicts, storage::SparseSetIndex}; pub use stepping::Stepping; /// Resource that stores [`Schedule`]s mapped to [`ScheduleLabel`]s excluding the current running [`Schedule`]. @@ -1526,13 +1523,13 @@ impl ScheduleGraph { // move systems into new schedule for &id in &schedule.system_ids { let system = self.systems[id.index()].inner.take().unwrap(); - let conditions = std::mem::take(&mut self.system_conditions[id.index()]); + let conditions = core::mem::take(&mut self.system_conditions[id.index()]); schedule.systems.push(system); schedule.system_conditions.push(conditions); } for &id in &schedule.set_ids { - let conditions = std::mem::take(&mut self.system_set_conditions[id.index()]); + let conditions = core::mem::take(&mut self.system_set_conditions[id.index()]); schedule.set_conditions.push(conditions); } @@ -1744,7 +1741,7 @@ impl ScheduleGraph { ) .unwrap(); writeln!(message, "set `{first_name}`").unwrap(); - for name in names.chain(std::iter::once(first_name)) { + for name in names.chain(core::iter::once(first_name)) { writeln!(message, " ... which contains set `{name}`").unwrap(); } writeln!(message).unwrap(); @@ -1768,7 +1765,7 @@ impl ScheduleGraph { ) .unwrap(); writeln!(message, "{first_kind} `{first_name}`").unwrap(); - for (kind, name) in names.chain(std::iter::once((first_kind, first_name))) { + for (kind, name) in names.chain(core::iter::once((first_kind, first_name))) { writeln!(message, " ... which must run before {kind} `{name}`").unwrap(); } writeln!(message).unwrap(); @@ -1882,7 +1879,7 @@ impl ScheduleGraph { writeln!(message, " conflict on: {conflicts:?}").unwrap(); } else { // one or both systems must be exclusive - let world = std::any::type_name::(); + let world = core::any::type_name::(); writeln!(message, " conflict on: {world}").unwrap(); } } diff --git a/crates/bevy_ecs/src/schedule/set.rs b/crates/bevy_ecs/src/schedule/set.rs index a39efdb41b584..244dd436351ec 100644 --- a/crates/bevy_ecs/src/schedule/set.rs +++ b/crates/bevy_ecs/src/schedule/set.rs @@ -1,7 +1,9 @@ -use std::any::TypeId; -use std::fmt::Debug; -use std::hash::{Hash, Hasher}; -use std::marker::PhantomData; +use core::{ + any::TypeId, + fmt::Debug, + hash::{Hash, Hasher}, + marker::PhantomData, +}; pub use crate::label::DynEq; pub use bevy_ecs_macros::{ScheduleLabel, SystemSet}; @@ -67,9 +69,9 @@ impl SystemTypeSet { } impl Debug for SystemTypeSet { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_tuple("SystemTypeSet") - .field(&format_args!("fn {}()", &std::any::type_name::())) + .field(&format_args!("fn {}()", &core::any::type_name::())) .finish() } } diff --git a/crates/bevy_ecs/src/schedule/stepping.rs b/crates/bevy_ecs/src/schedule/stepping.rs index 822e69f16d882..622ec6ea03e45 100644 --- a/crates/bevy_ecs/src/schedule/stepping.rs +++ b/crates/bevy_ecs/src/schedule/stepping.rs @@ -1,5 +1,5 @@ +use core::any::TypeId; use fixedbitset::FixedBitSet; -use std::any::TypeId; use std::collections::HashMap; use crate::{ @@ -113,8 +113,8 @@ pub struct Stepping { updates: Vec, } -impl std::fmt::Debug for Stepping { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for Stepping { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!( f, "Stepping {{ action: {:?}, schedules: {:?}, order: {:?}", @@ -691,7 +691,7 @@ impl ScheduleState { start: usize, mut action: Action, ) -> (FixedBitSet, Option) { - use std::cmp::Ordering; + use core::cmp::Ordering; // if our NodeId list hasn't been populated, copy it over from the // schedule @@ -827,8 +827,7 @@ impl ScheduleState { #[cfg(all(test, feature = "bevy_debug_stepping"))] mod tests { use super::*; - use crate::prelude::*; - use crate::schedule::ScheduleLabel; + use crate::{prelude::*, schedule::ScheduleLabel}; pub use crate as bevy_ecs; @@ -868,7 +867,7 @@ mod tests { let systems: &Vec<&str> = $system_names; if (actual != expected) { - use std::fmt::Write as _; + use core::fmt::Write as _; // mismatch, let's construct a human-readable message of what // was returned @@ -900,7 +899,7 @@ mod tests { ($schedule:expr, $skipped_systems:expr, $($system:expr),*) => { // pull an ordered list of systems in the schedule, and save the // system TypeId, and name. - let systems: Vec<(TypeId, std::borrow::Cow<'static, str>)> = $schedule.systems().unwrap() + let systems: Vec<(TypeId, alloc::borrow::Cow<'static, str>)> = $schedule.systems().unwrap() .map(|(_, system)| { (system.type_id(), system.name()) }) diff --git a/crates/bevy_ecs/src/storage/blob_array.rs b/crates/bevy_ecs/src/storage/blob_array.rs index 9970d82e75ea5..e6aefdb4b7dd4 100644 --- a/crates/bevy_ecs/src/storage/blob_array.rs +++ b/crates/bevy_ecs/src/storage/blob_array.rs @@ -1,13 +1,9 @@ use super::blob_vec::array_layout; use crate::storage::blob_vec::array_layout_unchecked; +use alloc::alloc::handle_alloc_error; use bevy_ptr::{OwningPtr, Ptr, PtrMut}; use bevy_utils::OnDrop; -use std::{ - alloc::{handle_alloc_error, Layout}, - cell::UnsafeCell, - num::NonZeroUsize, - ptr::NonNull, -}; +use core::{alloc::Layout, cell::UnsafeCell, num::NonZeroUsize, ptr::NonNull}; /// A flat, type-erased data storage type similar to a [`BlobVec`](super::blob_vec::BlobVec), but with the length and capacity cut out /// for performance reasons. This type is reliant on its owning type to store the capacity and length information. @@ -38,7 +34,7 @@ impl BlobArray { /// `drop` should be safe to call with an [`OwningPtr`] pointing to any item that's been placed into this [`BlobArray`]. /// If `drop` is `None`, the items will be leaked. This should generally be set as None based on [`needs_drop`]. /// - /// [`needs_drop`]: core::mem::needs_drop + /// [`needs_drop`]: std::mem::needs_drop pub unsafe fn with_capacity( item_layout: Layout, drop_fn: Option)>, @@ -142,7 +138,9 @@ impl BlobArray { #[cfg(debug_assertions)] debug_assert!(slice_len <= self.capacity); // SAFETY: the inner data will remain valid for as long as 'self. - unsafe { std::slice::from_raw_parts(self.data.as_ptr() as *const UnsafeCell, slice_len) } + unsafe { + core::slice::from_raw_parts(self.data.as_ptr() as *const UnsafeCell, slice_len) + } } /// Clears the array, i.e. removing (and dropping) all of the elements. @@ -189,7 +187,7 @@ impl BlobArray { if !self.is_zst() { let layout = array_layout(&self.item_layout, cap).expect("array layout should be valid"); - std::alloc::dealloc(self.data.as_ptr().cast(), layout); + alloc::alloc::dealloc(self.data.as_ptr().cast(), layout); } #[cfg(debug_assertions)] { @@ -228,7 +226,7 @@ impl BlobArray { let new_layout = array_layout(&self.item_layout, capacity.get()) .expect("array layout should be valid"); // SAFETY: layout has non-zero size because capacity > 0, and the blob isn't ZST (`self.is_zst` == false) - let new_data = unsafe { std::alloc::alloc(new_layout) }; + let new_data = unsafe { alloc::alloc::alloc(new_layout) }; self.data = NonNull::new(new_data).unwrap_or_else(|| handle_alloc_error(new_layout)); } #[cfg(debug_assertions)] @@ -263,7 +261,7 @@ impl BlobArray { // since the item size is always a multiple of its align, the rounding cannot happen // here and the overflow is handled in `array_layout` let new_data = unsafe { - std::alloc::realloc( + alloc::alloc::realloc( self.get_ptr_mut().as_ptr(), // SAFETY: This is the Layout of the current array, it must be valid, if it hadn't have been, there would have been a panic on a previous allocation array_layout_unchecked(&self.item_layout, current_capacity.get()), @@ -291,7 +289,7 @@ impl BlobArray { debug_assert!(self.capacity > index); let size = self.item_layout.size(); let dst = self.get_unchecked_mut(index); - std::ptr::copy::(value.as_ptr(), dst.as_ptr(), size); + core::ptr::copy::(value.as_ptr(), dst.as_ptr(), size); } /// Replaces the value at `index` with `value`. This function does not do any bounds checking. @@ -345,7 +343,7 @@ impl BlobArray { // - `source` and `destination` were obtained from different memory locations, // both of which we have exclusive access to, so they are guaranteed not to overlap. unsafe { - std::ptr::copy_nonoverlapping::( + core::ptr::copy_nonoverlapping::( source, destination.as_ptr(), self.item_layout.size(), @@ -405,7 +403,7 @@ impl BlobArray { debug_assert_ne!(index_to_keep, index_to_remove); } debug_assert_ne!(index_to_keep, index_to_remove); - std::ptr::swap_nonoverlapping::( + core::ptr::swap_nonoverlapping::( self.get_unchecked_mut(index_to_keep).as_ptr(), self.get_unchecked_mut(index_to_remove).as_ptr(), self.item_layout.size(), diff --git a/crates/bevy_ecs/src/storage/blob_vec.rs b/crates/bevy_ecs/src/storage/blob_vec.rs index 9d268944e956b..d42c63a6f1605 100644 --- a/crates/bevy_ecs/src/storage/blob_vec.rs +++ b/crates/bevy_ecs/src/storage/blob_vec.rs @@ -1,11 +1,7 @@ +use alloc::alloc::handle_alloc_error; use bevy_ptr::{OwningPtr, Ptr, PtrMut}; use bevy_utils::OnDrop; -use std::{ - alloc::{handle_alloc_error, Layout}, - cell::UnsafeCell, - num::NonZero, - ptr::NonNull, -}; +use core::{alloc::Layout, cell::UnsafeCell, num::NonZero, ptr::NonNull}; /// A flat, type-erased data storage type /// @@ -24,8 +20,8 @@ pub(super) struct BlobVec { } // We want to ignore the `drop` field in our `Debug` impl -impl std::fmt::Debug for BlobVec { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for BlobVec { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("BlobVec") .field("item_layout", &self.item_layout) .field("capacity", &self.capacity) @@ -49,7 +45,7 @@ impl BlobVec { /// /// If `drop` is `None`, the items will be leaked. This should generally be set as None based on [`needs_drop`]. /// - /// [`needs_drop`]: core::mem::needs_drop + /// [`needs_drop`]: std::mem::needs_drop pub unsafe fn new( item_layout: Layout, drop: Option)>, @@ -152,7 +148,7 @@ impl BlobVec { let new_data = if self.capacity == 0 { // SAFETY: // - layout has non-zero size as per safety requirement - unsafe { std::alloc::alloc(new_layout) } + unsafe { alloc::alloc::alloc(new_layout) } } else { // SAFETY: // - ptr was be allocated via this allocator @@ -162,7 +158,7 @@ impl BlobVec { // since the item size is always a multiple of its alignment, the rounding cannot happen // here and the overflow is handled in `array_layout` unsafe { - std::alloc::realloc( + alloc::alloc::realloc( self.get_ptr_mut().as_ptr(), array_layout(&self.item_layout, self.capacity) .expect("array layout should be valid"), @@ -185,7 +181,7 @@ impl BlobVec { pub unsafe fn initialize_unchecked(&mut self, index: usize, value: OwningPtr<'_>) { debug_assert!(index < self.len()); let ptr = self.get_unchecked_mut(index); - std::ptr::copy_nonoverlapping::(value.as_ptr(), ptr.as_ptr(), self.item_layout.size()); + core::ptr::copy_nonoverlapping::(value.as_ptr(), ptr.as_ptr(), self.item_layout.size()); } /// Replaces the value at `index` with `value`. This function does not do any bounds checking. @@ -244,7 +240,7 @@ impl BlobVec { // - `source` and `destination` were obtained from different memory locations, // both of which we have exclusive access to, so they are guaranteed not to overlap. unsafe { - std::ptr::copy_nonoverlapping::( + core::ptr::copy_nonoverlapping::( source, destination.as_ptr(), self.item_layout.size(), @@ -278,7 +274,7 @@ impl BlobVec { let new_len = self.len - 1; let size = self.item_layout.size(); if index != new_len { - std::ptr::swap_nonoverlapping::( + core::ptr::swap_nonoverlapping::( self.get_unchecked_mut(index).as_ptr(), self.get_unchecked_mut(new_len).as_ptr(), size, @@ -367,7 +363,7 @@ impl BlobVec { /// The type `T` must be the type of the items in this [`BlobVec`]. pub unsafe fn get_slice(&self) -> &[UnsafeCell] { // SAFETY: the inner data will remain valid for as long as 'self. - unsafe { std::slice::from_raw_parts(self.data.as_ptr() as *const UnsafeCell, self.len) } + unsafe { core::slice::from_raw_parts(self.data.as_ptr() as *const UnsafeCell, self.len) } } /// Clears the vector, removing (and dropping) all values. @@ -405,7 +401,7 @@ impl Drop for BlobVec { if array_layout.size() > 0 { // SAFETY: data ptr layout is correct, swap_scratch ptr layout is correct unsafe { - std::alloc::dealloc(self.get_ptr_mut().as_ptr(), array_layout); + alloc::alloc::dealloc(self.get_ptr_mut().as_ptr(), array_layout); } } } @@ -505,7 +501,8 @@ mod tests { use crate::{component::Component, ptr::OwningPtr, world::World}; use super::BlobVec; - use std::{alloc::Layout, cell::RefCell, rc::Rc}; + use alloc::rc::Rc; + use core::{alloc::Layout, cell::RefCell}; /// # Safety /// @@ -708,7 +705,7 @@ mod tests { for zst in q.iter(&world) { // Ensure that the references returned are properly aligned. assert_eq!( - std::ptr::from_ref::(zst) as usize % align_of::(), + core::ptr::from_ref::(zst) as usize % align_of::(), 0 ); count += 1; diff --git a/crates/bevy_ecs/src/storage/resource.rs b/crates/bevy_ecs/src/storage/resource.rs index fec0ca86d64d6..ed8700e1c74e2 100644 --- a/crates/bevy_ecs/src/storage/resource.rs +++ b/crates/bevy_ecs/src/storage/resource.rs @@ -1,11 +1,14 @@ -use crate::archetype::ArchetypeComponentId; -use crate::change_detection::{MaybeLocation, MaybeUnsafeCellLocation, MutUntyped, TicksMut}; -use crate::component::{ComponentId, ComponentTicks, Components, Tick, TickCells}; -use crate::storage::{blob_vec::BlobVec, SparseSet}; +use crate::{ + archetype::ArchetypeComponentId, + change_detection::{MaybeLocation, MaybeUnsafeCellLocation, MutUntyped, TicksMut}, + component::{ComponentId, ComponentTicks, Components, Tick, TickCells}, + storage::{blob_vec::BlobVec, SparseSet}, +}; use bevy_ptr::{OwningPtr, Ptr, UnsafeCellDeref}; #[cfg(feature = "track_change_detection")] -use std::panic::Location; -use std::{cell::UnsafeCell, mem::ManuallyDrop, thread::ThreadId}; +use core::panic::Location; +use core::{cell::UnsafeCell, mem::ManuallyDrop}; +use std::thread::ThreadId; /// The type-erased backing storage and metadata for a single resource within a [`World`]. /// diff --git a/crates/bevy_ecs/src/storage/sparse_set.rs b/crates/bevy_ecs/src/storage/sparse_set.rs index 6a7b2460a2b4d..ff740d755b20f 100644 --- a/crates/bevy_ecs/src/storage/sparse_set.rs +++ b/crates/bevy_ecs/src/storage/sparse_set.rs @@ -5,10 +5,10 @@ use crate::{ storage::{Column, TableRow}, }; use bevy_ptr::{OwningPtr, Ptr}; -use nonmax::NonMaxUsize; #[cfg(feature = "track_change_detection")] -use std::panic::Location; -use std::{cell::UnsafeCell, hash::Hash, marker::PhantomData}; +use core::panic::Location; +use core::{cell::UnsafeCell, hash::Hash, marker::PhantomData}; +use nonmax::NonMaxUsize; type EntityIndex = u32; diff --git a/crates/bevy_ecs/src/storage/table/column.rs b/crates/bevy_ecs/src/storage/table/column.rs index ccc930d552df5..041ddab7521dc 100644 --- a/crates/bevy_ecs/src/storage/table/column.rs +++ b/crates/bevy_ecs/src/storage/table/column.rs @@ -281,10 +281,10 @@ impl ThinColumn { /// - `last_element_index` is indeed the index of the last element /// - the data stored in `last_element_index` will never be used unless properly initialized again. pub(crate) unsafe fn drop_last_component(&mut self, last_element_index: usize) { - std::ptr::drop_in_place(self.added_ticks.get_unchecked_raw(last_element_index)); - std::ptr::drop_in_place(self.changed_ticks.get_unchecked_raw(last_element_index)); + core::ptr::drop_in_place(self.added_ticks.get_unchecked_raw(last_element_index)); + core::ptr::drop_in_place(self.changed_ticks.get_unchecked_raw(last_element_index)); #[cfg(feature = "track_change_detection")] - std::ptr::drop_in_place(self.changed_by.get_unchecked_raw(last_element_index)); + core::ptr::drop_in_place(self.changed_by.get_unchecked_raw(last_element_index)); self.data.drop_last_element(last_element_index); } diff --git a/crates/bevy_ecs/src/storage/table/mod.rs b/crates/bevy_ecs/src/storage/table/mod.rs index c08b49c3363f5..8af24d2c3f92d 100644 --- a/crates/bevy_ecs/src/storage/table/mod.rs +++ b/crates/bevy_ecs/src/storage/table/mod.rs @@ -9,10 +9,11 @@ use bevy_ptr::{OwningPtr, Ptr, UnsafeCellDeref}; use bevy_utils::HashMap; pub use column::*; #[cfg(feature = "track_change_detection")] -use std::panic::Location; -use std::{alloc::Layout, num::NonZeroUsize}; -use std::{ +use core::panic::Location; +use core::{ + alloc::Layout, cell::UnsafeCell, + num::NonZeroUsize, ops::{Index, IndexMut}, }; mod column; @@ -763,7 +764,7 @@ impl Tables { } /// Iterates through all of the tables stored within in [`TableId`] order. - pub fn iter(&self) -> std::slice::Iter<'_, Table> { + pub fn iter(&self) -> core::slice::Iter<'_, Table> { self.tables.iter() } @@ -814,16 +815,14 @@ impl Drop for Table { #[cfg(test)] mod tests { use crate as bevy_ecs; - use crate::component::Component; - use crate::ptr::OwningPtr; - use crate::storage::Storages; use crate::{ - component::{Components, Tick}, + component::{Component, Components, Tick}, entity::Entity, - storage::{TableBuilder, TableRow}, + ptr::OwningPtr, + storage::{Storages, TableBuilder, TableRow}, }; #[cfg(feature = "track_change_detection")] - use std::panic::Location; + use core::panic::Location; #[derive(Component)] struct W(T); diff --git a/crates/bevy_ecs/src/storage/thin_array_ptr.rs b/crates/bevy_ecs/src/storage/thin_array_ptr.rs index d5c36e1f04ce8..a4d25265e0066 100644 --- a/crates/bevy_ecs/src/storage/thin_array_ptr.rs +++ b/crates/bevy_ecs/src/storage/thin_array_ptr.rs @@ -1,8 +1,11 @@ use crate::query::DebugCheckedUnwrap; -use std::alloc::{alloc, handle_alloc_error, realloc, Layout}; -use std::mem::{needs_drop, size_of}; -use std::num::NonZeroUsize; -use std::ptr::{self, NonNull}; +use alloc::alloc::{alloc, handle_alloc_error, realloc}; +use core::{ + alloc::Layout, + mem::{needs_drop, size_of}, + num::NonZeroUsize, + ptr::{self, NonNull}, +}; /// Similar to [`Vec`], but with the capacity and length cut out for performance reasons. /// @@ -279,7 +282,7 @@ impl ThinArrayPtr { if current_capacity != 0 { self.clear_elements(current_len); let layout = Layout::array::(current_capacity).expect("layout should be valid"); - std::alloc::dealloc(self.data.as_ptr().cast(), layout); + alloc::alloc::dealloc(self.data.as_ptr().cast(), layout); } self.set_capacity(0); } @@ -294,7 +297,7 @@ impl ThinArrayPtr { // - the data is valid - allocated with the same allocater // - non-null and well-aligned // - we have a shared reference to self - the data will not be mutated during 'a - unsafe { std::slice::from_raw_parts(self.data.as_ptr(), slice_len) } + unsafe { core::slice::from_raw_parts(self.data.as_ptr(), slice_len) } } } diff --git a/crates/bevy_ecs/src/system/adapter_system.rs b/crates/bevy_ecs/src/system/adapter_system.rs index 2c7aea84bf8eb..04f077eed65a0 100644 --- a/crates/bevy_ecs/src/system/adapter_system.rs +++ b/crates/bevy_ecs/src/system/adapter_system.rs @@ -1,4 +1,4 @@ -use std::borrow::Cow; +use alloc::borrow::Cow; use super::{ReadOnlySystem, System}; use crate::{ diff --git a/crates/bevy_ecs/src/system/builder.rs b/crates/bevy_ecs/src/system/builder.rs index b9734e41774e8..9e359d4a0fbf8 100644 --- a/crates/bevy_ecs/src/system/builder.rs +++ b/crates/bevy_ecs/src/system/builder.rs @@ -9,7 +9,7 @@ use crate::{ }, world::{FromWorld, World}, }; -use std::fmt::Debug; +use core::fmt::Debug; use super::{init_query_param, Res, ResMut, Resource, SystemState}; @@ -348,9 +348,11 @@ unsafe impl<'s, T: FromWorld + Send + 'static> SystemParamBuilder> #[cfg(test)] mod tests { use crate as bevy_ecs; - use crate::entity::Entities; - use crate::prelude::{Component, Query}; - use crate::system::{Local, RunSystemOnce}; + use crate::{ + entity::Entities, + prelude::{Component, Query}, + system::{Local, RunSystemOnce}, + }; use super::*; diff --git a/crates/bevy_ecs/src/system/combinator.rs b/crates/bevy_ecs/src/system/combinator.rs index 5434a0bb2d6c2..87976a4d9c280 100644 --- a/crates/bevy_ecs/src/system/combinator.rs +++ b/crates/bevy_ecs/src/system/combinator.rs @@ -1,4 +1,5 @@ -use std::{borrow::Cow, marker::PhantomData}; +use alloc::borrow::Cow; +use core::marker::PhantomData; use crate::{ archetype::ArchetypeComponentId, diff --git a/crates/bevy_ecs/src/system/commands/mod.rs b/crates/bevy_ecs/src/system/commands/mod.rs index 8220d38021c20..daeae8eb85465 100644 --- a/crates/bevy_ecs/src/system/commands/mod.rs +++ b/crates/bevy_ecs/src/system/commands/mod.rs @@ -1,7 +1,6 @@ mod parallel_scope; -use core::panic::Location; -use std::marker::PhantomData; +use core::{marker::PhantomData, panic::Location}; use super::{ Deferred, IntoObserverSystem, IntoSystem, RegisterSystem, Resource, RunSystemCachedWith, @@ -1149,7 +1148,7 @@ impl EntityCommands<'_> { let caller = Location::caller(); // SAFETY: same invariants as parent call self.queue(unsafe {insert_by_id(component_id, value, move |entity| { - panic!("error[B0003]: {caller}: Could not insert a component {component_id:?} (with type {}) for entity {entity:?} because it doesn't exist in this World. See: https://bevyengine.org/learn/errors/b0003", std::any::type_name::()); + panic!("error[B0003]: {caller}: Could not insert a component {component_id:?} (with type {}) for entity {entity:?} because it doesn't exist in this World. See: https://bevyengine.org/learn/errors/b0003", core::any::type_name::()); })}) } @@ -1674,7 +1673,7 @@ where ) { error!( "Failed to 'insert or spawn' bundle of type {} into the following invalid entities: {:?}", - std::any::type_name::(), + core::any::type_name::(), invalid_entities ); } @@ -1709,7 +1708,7 @@ fn insert(bundle: T, mode: InsertMode) -> impl EntityCommand { caller, ); } else { - panic!("error[B0003]: {caller}: Could not insert a bundle (of type `{}`) for entity {:?} because it doesn't exist in this World. See: https://bevyengine.org/learn/errors/b0003", std::any::type_name::(), entity); + panic!("error[B0003]: {caller}: Could not insert a bundle (of type `{}`) for entity {:?} because it doesn't exist in this World. See: https://bevyengine.org/learn/errors/b0003", core::any::type_name::(), entity); } } } @@ -1728,7 +1727,7 @@ fn insert_from_world(mode: InsertMode) -> impl EntityC caller, ); } else { - panic!("error[B0003]: {caller}: Could not insert a bundle (of type `{}`) for entity {:?} because it doesn't exist in this World. See: https://bevyengine.org/learn/errors/b0003", std::any::type_name::(), entity); + panic!("error[B0003]: {caller}: Could not insert a bundle (of type `{}`) for entity {:?} because it doesn't exist in this World. See: https://bevyengine.org/learn/errors/b0003", core::any::type_name::(), entity); } } } @@ -1870,12 +1869,10 @@ mod tests { system::{Commands, Resource}, world::{CommandQueue, FromWorld, World}, }; - use std::{ + use alloc::sync::Arc; + use core::{ any::TypeId, - sync::{ - atomic::{AtomicUsize, Ordering}, - Arc, - }, + sync::atomic::{AtomicUsize, Ordering}, }; #[allow(dead_code)] diff --git a/crates/bevy_ecs/src/system/exclusive_function_system.rs b/crates/bevy_ecs/src/system/exclusive_function_system.rs index 9019a920a2e67..3075f3c55772e 100644 --- a/crates/bevy_ecs/src/system/exclusive_function_system.rs +++ b/crates/bevy_ecs/src/system/exclusive_function_system.rs @@ -10,8 +10,9 @@ use crate::{ world::{unsafe_world_cell::UnsafeWorldCell, World}, }; +use alloc::borrow::Cow; use bevy_utils::all_tuples; -use std::{borrow::Cow, marker::PhantomData}; +use core::marker::PhantomData; /// A function system that runs with exclusive [`World`] access. /// @@ -298,7 +299,7 @@ mod tests { { fn reference_system(_world: &mut World) {} - use std::any::TypeId; + use core::any::TypeId; let system = IntoSystem::into_system(function); diff --git a/crates/bevy_ecs/src/system/exclusive_system_param.rs b/crates/bevy_ecs/src/system/exclusive_system_param.rs index 255da95fec682..9d3279e3e053a 100644 --- a/crates/bevy_ecs/src/system/exclusive_system_param.rs +++ b/crates/bevy_ecs/src/system/exclusive_system_param.rs @@ -4,9 +4,8 @@ use crate::{ system::{Local, SystemMeta, SystemParam, SystemState}, world::World, }; -use bevy_utils::all_tuples; -use bevy_utils::synccell::SyncCell; -use std::marker::PhantomData; +use bevy_utils::{all_tuples, synccell::SyncCell}; +use core::marker::PhantomData; /// A parameter that can be used in an exclusive system (a system with an `&mut World` parameter). /// Any parameters implementing this trait must come after the `&mut World` parameter. @@ -125,11 +124,9 @@ all_tuples!( #[cfg(test)] mod tests { use crate as bevy_ecs; - use crate::schedule::Schedule; - use crate::system::Local; - use crate::world::World; + use crate::{schedule::Schedule, system::Local, world::World}; use bevy_ecs_macros::Resource; - use std::marker::PhantomData; + use core::marker::PhantomData; #[test] fn test_exclusive_system_params() { diff --git a/crates/bevy_ecs/src/system/function_system.rs b/crates/bevy_ecs/src/system/function_system.rs index 54b54bfd56217..0614d7339ca4b 100644 --- a/crates/bevy_ecs/src/system/function_system.rs +++ b/crates/bevy_ecs/src/system/function_system.rs @@ -11,8 +11,9 @@ use crate::{ world::{unsafe_world_cell::UnsafeWorldCell, DeferredWorld, World, WorldId}, }; +use alloc::borrow::Cow; use bevy_utils::all_tuples; -use std::{borrow::Cow, marker::PhantomData}; +use core::marker::PhantomData; #[cfg(feature = "trace")] use bevy_utils::tracing::{info_span, Span}; @@ -50,7 +51,7 @@ pub struct SystemMeta { impl SystemMeta { pub(crate) fn new() -> Self { - let name = std::any::type_name::(); + let name = core::any::type_name::(); Self { name: name.into(), archetype_component_access: Access::default(), @@ -405,7 +406,7 @@ impl SystemState { let archetypes = world.archetypes(); let old_generation = - std::mem::replace(&mut self.archetype_generation, archetypes.generation()); + core::mem::replace(&mut self.archetype_generation, archetypes.generation()); for archetype in &archetypes[old_generation..] { // SAFETY: The assertion above ensures that the param_state was initialized from `world`. @@ -680,7 +681,7 @@ where assert_eq!(self.world_id, Some(world.id()), "Encountered a mismatched World. A System cannot be used with Worlds other than the one it was initialized with."); let archetypes = world.archetypes(); let old_generation = - std::mem::replace(&mut self.archetype_generation, archetypes.generation()); + core::mem::replace(&mut self.archetype_generation, archetypes.generation()); for archetype in &archetypes[old_generation..] { let param_state = self.param_state.as_mut().unwrap(); @@ -884,7 +885,7 @@ mod tests { { fn reference_system() {} - use std::any::TypeId; + use core::any::TypeId; let system = IntoSystem::into_system(function); diff --git a/crates/bevy_ecs/src/system/input.rs b/crates/bevy_ecs/src/system/input.rs index 26bf5af368ffd..57032f71928ef 100644 --- a/crates/bevy_ecs/src/system/input.rs +++ b/crates/bevy_ecs/src/system/input.rs @@ -1,4 +1,4 @@ -use std::ops::{Deref, DerefMut}; +use core::ops::{Deref, DerefMut}; use crate::{bundle::Bundle, prelude::Trigger, system::System}; diff --git a/crates/bevy_ecs/src/system/mod.rs b/crates/bevy_ecs/src/system/mod.rs index c3781d96fbf7d..4f97b64d3aa82 100644 --- a/crates/bevy_ecs/src/system/mod.rs +++ b/crates/bevy_ecs/src/system/mod.rs @@ -117,7 +117,8 @@ mod system_name; mod system_param; mod system_registry; -use std::{any::TypeId, borrow::Cow}; +use alloc::borrow::Cow; +use core::any::TypeId; pub use adapter_system::*; pub use builder::*; @@ -305,10 +306,8 @@ pub fn assert_system_does_not_conflict); + struct NotSend1(alloc::rc::Rc); #[allow(dead_code)] - struct NotSend2(std::rc::Rc); - world.insert_non_send_resource(NotSend1(std::rc::Rc::new(0))); + struct NotSend2(alloc::rc::Rc); + world.insert_non_send_resource(NotSend1(alloc::rc::Rc::new(0))); fn sys( op: Option>, @@ -912,12 +911,12 @@ mod tests { world.insert_resource(SystemRan::No); #[allow(dead_code)] - struct NotSend1(std::rc::Rc); + struct NotSend1(alloc::rc::Rc); #[allow(dead_code)] - struct NotSend2(std::rc::Rc); + struct NotSend2(alloc::rc::Rc); - world.insert_non_send_resource(NotSend1(std::rc::Rc::new(1))); - world.insert_non_send_resource(NotSend2(std::rc::Rc::new(2))); + world.insert_non_send_resource(NotSend1(alloc::rc::Rc::new(1))); + world.insert_non_send_resource(NotSend2(alloc::rc::Rc::new(2))); fn sys( _op: NonSend, @@ -1600,7 +1599,7 @@ mod tests { #[test] fn assert_systems() { - use std::str::FromStr; + use core::str::FromStr; use crate::{prelude::*, system::assert_is_system}; diff --git a/crates/bevy_ecs/src/system/query.rs b/crates/bevy_ecs/src/system/query.rs index ddff01e19fa11..83681ae5b686f 100644 --- a/crates/bevy_ecs/src/system/query.rs +++ b/crates/bevy_ecs/src/system/query.rs @@ -8,7 +8,7 @@ use crate::{ }, world::unsafe_world_cell::UnsafeWorldCell, }; -use std::borrow::Borrow; +use core::borrow::Borrow; /// [System parameter] that provides selective access to the [`Component`] data stored in a [`World`]. /// @@ -354,8 +354,8 @@ pub struct Query<'world, 'state, D: QueryData, F: QueryFilter = ()> { this_run: Tick, } -impl std::fmt::Debug for Query<'_, '_, D, F> { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { +impl core::fmt::Debug for Query<'_, '_, D, F> { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { f.debug_struct("Query") .field("matched_entities", &self.iter().count()) .field("state", &self.state) diff --git a/crates/bevy_ecs/src/system/system.rs b/crates/bevy_ecs/src/system/system.rs index 296bf8ea2dd47..63ef1a16c3d17 100644 --- a/crates/bevy_ecs/src/system/system.rs +++ b/crates/bevy_ecs/src/system/system.rs @@ -1,16 +1,17 @@ use bevy_utils::tracing::warn; use core::fmt::Debug; -use crate::component::Tick; -use crate::schedule::InternedSystemSet; -use crate::system::input::SystemInput; -use crate::system::SystemIn; -use crate::world::unsafe_world_cell::UnsafeWorldCell; -use crate::world::DeferredWorld; -use crate::{archetype::ArchetypeComponentId, component::ComponentId, query::Access, world::World}; - -use std::any::TypeId; -use std::borrow::Cow; +use crate::{ + archetype::ArchetypeComponentId, + component::{ComponentId, Tick}, + query::Access, + schedule::InternedSystemSet, + system::{input::SystemInput, SystemIn}, + world::{unsafe_world_cell::UnsafeWorldCell, DeferredWorld, World}, +}; + +use alloc::borrow::Cow; +use core::any::TypeId; use super::IntoSystem; @@ -206,7 +207,7 @@ where In: SystemInput + 'static, Out: 'static, { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("System") .field("name", &self.name()) .field("is_exclusive", &self.is_exclusive()) diff --git a/crates/bevy_ecs/src/system/system_name.rs b/crates/bevy_ecs/src/system/system_name.rs index a158a8327cc14..4759f8cb5ca65 100644 --- a/crates/bevy_ecs/src/system/system_name.rs +++ b/crates/bevy_ecs/src/system/system_name.rs @@ -1,9 +1,11 @@ -use crate::component::Tick; -use crate::prelude::World; -use crate::system::{ExclusiveSystemParam, ReadOnlySystemParam, SystemMeta, SystemParam}; -use crate::world::unsafe_world_cell::UnsafeWorldCell; -use std::borrow::Cow; -use std::ops::Deref; +use crate::{ + component::Tick, + prelude::World, + system::{ExclusiveSystemParam, ReadOnlySystemParam, SystemMeta, SystemParam}, + world::unsafe_world_cell::UnsafeWorldCell, +}; +use alloc::borrow::Cow; +use core::ops::Deref; /// [`SystemParam`] that returns the name of the system which it is used in. /// @@ -60,10 +62,10 @@ impl<'s> From> for &'s str { } } -impl<'s> std::fmt::Display for SystemName<'s> { +impl<'s> core::fmt::Display for SystemName<'s> { #[inline(always)] - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - std::fmt::Display::fmt(&self.name(), f) + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + core::fmt::Display::fmt(&self.name(), f) } } @@ -105,8 +107,10 @@ impl ExclusiveSystemParam for SystemName<'_> { #[cfg(test)] mod tests { - use crate::system::{IntoSystem, RunSystemOnce, SystemName}; - use crate::world::World; + use crate::{ + system::{IntoSystem, RunSystemOnce, SystemName}, + world::World, + }; #[test] fn test_system_name_regular_param() { diff --git a/crates/bevy_ecs/src/system/system_param.rs b/crates/bevy_ecs/src/system/system_param.rs index 4b7d69eff9e20..7a985c011e15a 100644 --- a/crates/bevy_ecs/src/system/system_param.rs +++ b/crates/bevy_ecs/src/system/system_param.rs @@ -1,5 +1,4 @@ pub use crate::change_detection::{NonSendMut, Res, ResMut}; -use crate::storage::SparseSetIndex; use crate::{ archetype::{Archetype, Archetypes}, bundle::Bundles, @@ -7,21 +6,20 @@ use crate::{ component::{ComponentId, ComponentTicks, Components, Tick}, entity::Entities, query::{ - Access, FilteredAccess, FilteredAccessSet, QueryData, QueryFilter, QueryState, - ReadOnlyQueryData, + Access, AccessConflicts, FilteredAccess, FilteredAccessSet, QueryData, QueryFilter, + QueryState, ReadOnlyQueryData, }, + storage::{ResourceData, SparseSetIndex}, system::{Query, SystemMeta}, world::{unsafe_world_cell::UnsafeWorldCell, DeferredWorld, FromWorld, World}, }; -use crate::{query::AccessConflicts, storage::ResourceData}; use bevy_ecs_macros::impl_param_set; -pub use bevy_ecs_macros::Resource; -pub use bevy_ecs_macros::SystemParam; +pub use bevy_ecs_macros::{Resource, SystemParam}; use bevy_ptr::UnsafeCellDeref; use bevy_utils::{all_tuples, synccell::SyncCell}; #[cfg(feature = "track_change_detection")] -use std::panic::Location; -use std::{ +use core::panic::Location; +use core::{ any::Any, fmt::Debug, marker::PhantomData, @@ -317,8 +315,8 @@ pub(crate) fn init_query_param ) { assert_component_access_compatibility( &system_meta.name, - std::any::type_name::(), - std::any::type_name::(), + core::any::type_name::(), + core::any::type_name::(), &system_meta.component_access_set, &state.component_access, world, @@ -600,7 +598,7 @@ unsafe impl<'a, T: Resource> SystemParam for Res<'a, T> { assert!( !combined_access.has_resource_write(component_id), "error[B0002]: Res<{}> in system {} conflicts with a previous ResMut<{0}> access. Consider removing the duplicate access. See: https://bevyengine.org/learn/errors/b0002", - std::any::type_name::(), + core::any::type_name::(), system_meta.name, ); system_meta @@ -641,7 +639,7 @@ unsafe impl<'a, T: Resource> SystemParam for Res<'a, T> { panic!( "Resource requested by {} does not exist: {}", system_meta.name, - std::any::type_name::() + core::any::type_name::() ) }); Res { @@ -707,11 +705,11 @@ unsafe impl<'a, T: Resource> SystemParam for ResMut<'a, T> { if combined_access.has_resource_write(component_id) { panic!( "error[B0002]: ResMut<{}> in system {} conflicts with a previous ResMut<{0}> access. Consider removing the duplicate access. See: https://bevyengine.org/learn/errors/b0002", - std::any::type_name::(), system_meta.name); + core::any::type_name::(), system_meta.name); } else if combined_access.has_resource_read(component_id) { panic!( "error[B0002]: ResMut<{}> in system {} conflicts with a previous Res<{0}> access. Consider removing the duplicate access. See: https://bevyengine.org/learn/errors/b0002", - std::any::type_name::(), system_meta.name); + core::any::type_name::(), system_meta.name); } system_meta .component_access_set @@ -750,7 +748,7 @@ unsafe impl<'a, T: Resource> SystemParam for ResMut<'a, T> { panic!( "Resource requested by {} does not exist: {}", system_meta.name, - std::any::type_name::() + core::any::type_name::() ) }); ResMut { @@ -1195,7 +1193,7 @@ impl<'w, T> Debug for NonSend<'w, T> where T: Debug, { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_tuple("NonSend").field(&self.value).finish() } } @@ -1257,7 +1255,7 @@ unsafe impl<'a, T: 'static> SystemParam for NonSend<'a, T> { assert!( !combined_access.has_resource_write(component_id), "error[B0002]: NonSend<{}> in system {} conflicts with a previous mutable resource access ({0}). Consider removing the duplicate access. See: https://bevyengine.org/learn/errors/b0002", - std::any::type_name::(), + core::any::type_name::(), system_meta.name, ); system_meta @@ -1298,7 +1296,7 @@ unsafe impl<'a, T: 'static> SystemParam for NonSend<'a, T> { panic!( "Non-send resource requested by {} does not exist: {}", system_meta.name, - std::any::type_name::() + core::any::type_name::() ) }); @@ -1361,11 +1359,11 @@ unsafe impl<'a, T: 'static> SystemParam for NonSendMut<'a, T> { if combined_access.has_component_write(component_id) { panic!( "error[B0002]: NonSendMut<{}> in system {} conflicts with a previous mutable resource access ({0}). Consider removing the duplicate access. See: https://bevyengine.org/learn/errors/b0002", - std::any::type_name::(), system_meta.name); + core::any::type_name::(), system_meta.name); } else if combined_access.has_component_read(component_id) { panic!( "error[B0002]: NonSendMut<{}> in system {} conflicts with a previous immutable resource access ({0}). Consider removing the duplicate access. See: https://bevyengine.org/learn/errors/b0002", - std::any::type_name::(), system_meta.name); + core::any::type_name::(), system_meta.name); } system_meta .component_access_set @@ -1405,7 +1403,7 @@ unsafe impl<'a, T: 'static> SystemParam for NonSendMut<'a, T> { panic!( "Non-send resource requested by {} does not exist: {}", system_meta.name, - std::any::type_name::() + core::any::type_name::() ) }); NonSendMut { @@ -1868,7 +1866,7 @@ pub mod lifetimeless { /// struct GenericParam<'w, 's, T: SystemParam> { /// field: T, /// // Use the lifetimes in this type, or they will be unbound. -/// phantom: core::marker::PhantomData<&'w &'s ()> +/// phantom: std::marker::PhantomData<&'w &'s ()> /// } /// # fn check_always_is_system(){ /// # bevy_ecs::system::assert_is_system(do_thing_generically::); @@ -2275,7 +2273,7 @@ mod tests { self as bevy_ecs, // Necessary for the `SystemParam` Derive when used inside `bevy_ecs`. system::assert_is_system, }; - use std::cell::RefCell; + use core::cell::RefCell; // Compile test for https://github.com/bevyengine/bevy/pull/2838. #[test] @@ -2467,7 +2465,7 @@ mod tests { } let mut world = World::new(); - world.insert_non_send_resource(std::ptr::null_mut::()); + world.insert_non_send_resource(core::ptr::null_mut::()); let mut schedule = crate::schedule::Schedule::default(); schedule.add_systems((non_send_param_set, non_send_param_set, non_send_param_set)); schedule.run(&mut world); @@ -2482,7 +2480,7 @@ mod tests { } let mut world = World::new(); - world.insert_non_send_resource(std::ptr::null_mut::()); + world.insert_non_send_resource(core::ptr::null_mut::()); let mut schedule = crate::schedule::Schedule::default(); schedule.add_systems((non_send_param_set, non_send_param_set, non_send_param_set)); schedule.run(&mut world); diff --git a/crates/bevy_ecs/src/system/system_registry.rs b/crates/bevy_ecs/src/system/system_registry.rs index 3374f1b15a3d7..294cdd2669388 100644 --- a/crates/bevy_ecs/src/system/system_registry.rs +++ b/crates/bevy_ecs/src/system/system_registry.rs @@ -1,10 +1,12 @@ -use crate::bundle::Bundle; -use crate::change_detection::Mut; -use crate::entity::Entity; -use crate::system::input::SystemInput; -use crate::system::{BoxedSystem, IntoSystem, System, SystemIn}; -use crate::world::{Command, World}; -use crate::{self as bevy_ecs}; +use crate::{ + self as bevy_ecs, + bundle::Bundle, + change_detection::Mut, + entity::Entity, + system::input::SystemInput, + system::{BoxedSystem, IntoSystem, System, SystemIn}, + world::{Command, World}, +}; use bevy_ecs_macros::{Component, Resource}; use thiserror::Error; @@ -47,7 +49,7 @@ impl RemovedSystem { /// and are created via [`World::register_system`]. pub struct SystemId { pub(crate) entity: Entity, - pub(crate) marker: std::marker::PhantomData O>, + pub(crate) marker: core::marker::PhantomData O>, } impl SystemId { @@ -68,7 +70,7 @@ impl SystemId { pub fn from_entity(entity: Entity) -> Self { Self { entity, - marker: std::marker::PhantomData, + marker: core::marker::PhantomData, } } } @@ -93,14 +95,14 @@ impl PartialEq for SystemId { } // A manual impl is used because the trait bounds should ignore the `I` and `O` phantom parameters. -impl std::hash::Hash for SystemId { - fn hash(&self, state: &mut H) { +impl core::hash::Hash for SystemId { + fn hash(&self, state: &mut H) { self.entity.hash(state); } } -impl std::fmt::Debug for SystemId { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for SystemId { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_tuple("SystemId").field(&self.entity).finish() } } @@ -584,8 +586,8 @@ pub enum RegisteredSystemError { SelfRemove(SystemId), } -impl std::fmt::Debug for RegisteredSystemError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for RegisteredSystemError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { Self::SystemIdNotRegistered(arg0) => { f.debug_tuple("SystemIdNotRegistered").field(arg0).finish() diff --git a/crates/bevy_ecs/src/world/command_queue.rs b/crates/bevy_ecs/src/world/command_queue.rs index e78ce8b03ea1f..10b901e4aafee 100644 --- a/crates/bevy_ecs/src/world/command_queue.rs +++ b/crates/bevy_ecs/src/world/command_queue.rs @@ -1,9 +1,9 @@ use crate::system::{SystemBuffer, SystemMeta}; -use std::{ +use core::{ fmt::Debug, mem::{size_of, MaybeUninit}, - panic::{self, AssertUnwindSafe}, + panic::AssertUnwindSafe, ptr::{addr_of_mut, NonNull}, }; @@ -59,7 +59,7 @@ pub(crate) struct RawCommandQueue { // It is not possible to soundly print the values of the contained bytes, as some of them may be padding or uninitialized (#4863) // So instead, the manual impl just prints the length of vec. impl Debug for CommandQueue { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("CommandQueue") .field("len_bytes", &self.bytes.len()) .finish_non_exhaustive() @@ -262,7 +262,7 @@ impl RawCommandQueue { self.bytes.as_mut().as_mut_ptr().add(local_cursor).cast(), )) }; - let result = panic::catch_unwind(AssertUnwindSafe(|| { + let result = std::panic::catch_unwind(AssertUnwindSafe(|| { // SAFETY: The data underneath the cursor must correspond to the type erased in metadata, // since they were stored next to each other by `.push()`. // For ZSTs, the type doesn't matter as long as the pointer is non-null. @@ -295,7 +295,7 @@ impl RawCommandQueue { if start == 0 { bytes.append(panic_recovery); } - panic::resume_unwind(payload); + std::panic::resume_unwind(payload); } } @@ -338,12 +338,10 @@ mod test { use super::*; use crate as bevy_ecs; use crate::system::Resource; - use std::{ + use alloc::sync::Arc; + use core::{ panic::AssertUnwindSafe, - sync::{ - atomic::{AtomicU32, Ordering}, - Arc, - }, + sync::atomic::{AtomicU32, Ordering}, }; struct DropCheck(Arc); @@ -445,7 +443,7 @@ mod test { #[test] fn test_command_queue_inner_panic_safe() { - panic::set_hook(Box::new(|_| {})); + std::panic::set_hook(Box::new(|_| {})); let mut queue = CommandQueue::default(); @@ -454,7 +452,7 @@ mod test { let mut world = World::new(); - let _ = panic::catch_unwind(AssertUnwindSafe(|| { + let _ = std::panic::catch_unwind(AssertUnwindSafe(|| { queue.apply(&mut world); })); @@ -468,7 +466,7 @@ mod test { #[test] fn test_command_queue_inner_nested_panic_safe() { - panic::set_hook(Box::new(|_| {})); + std::panic::set_hook(Box::new(|_| {})); #[derive(Resource, Default)] struct Order(Vec); @@ -488,7 +486,7 @@ mod test { }); world.commands().queue(add_index(4)); - let _ = panic::catch_unwind(AssertUnwindSafe(|| { + let _ = std::panic::catch_unwind(AssertUnwindSafe(|| { world.flush_commands(); })); diff --git a/crates/bevy_ecs/src/world/deferred_world.rs b/crates/bevy_ecs/src/world/deferred_world.rs index 9f80ca8d860ac..8b3b046859137 100644 --- a/crates/bevy_ecs/src/world/deferred_world.rs +++ b/crates/bevy_ecs/src/world/deferred_world.rs @@ -1,4 +1,4 @@ -use std::ops::Deref; +use core::ops::Deref; use crate::{ archetype::Archetype, @@ -152,7 +152,7 @@ impl<'w> DeferredWorld<'w> { Did you forget to add it using `app.insert_resource` / `app.init_resource`? Resources are also implicitly added via `app.add_event`, and can be added by plugins.", - std::any::type_name::() + core::any::type_name::() ), } } @@ -181,7 +181,7 @@ impl<'w> DeferredWorld<'w> { "Requested non-send resource {} does not exist in the `World`. Did you forget to add it using `app.insert_non_send_resource` / `app.init_non_send_resource`? Non-send resources can also be added by plugins.", - std::any::type_name::() + core::any::type_name::() ), } } @@ -202,7 +202,7 @@ impl<'w> DeferredWorld<'w> { /// or [`None`] if the `event` could not be sent. #[inline] pub fn send_event(&mut self, event: E) -> Option> { - self.send_event_batch(std::iter::once(event))?.next() + self.send_event_batch(core::iter::once(event))?.next() } /// Sends the default value of the [`Event`] of type `E`. @@ -224,7 +224,7 @@ impl<'w> DeferredWorld<'w> { let Some(mut events_resource) = self.get_resource_mut::>() else { bevy_utils::tracing::error!( "Unable to send event `{}`\n\tEvent must be added to the app with `add_event()`\n\thttps://docs.rs/bevy/*/bevy/app/struct.App.html#method.add_event ", - std::any::type_name::() + core::any::type_name::() ); return None; }; diff --git a/crates/bevy_ecs/src/world/entity_ref.rs b/crates/bevy_ecs/src/world/entity_ref.rs index c91885469c766..adf867d142a6b 100644 --- a/crates/bevy_ecs/src/world/entity_ref.rs +++ b/crates/bevy_ecs/src/world/entity_ref.rs @@ -13,7 +13,7 @@ use crate::{ world::{DeferredWorld, Mut, World}, }; use bevy_ptr::{OwningPtr, Ptr}; -use std::{any::TypeId, marker::PhantomData}; +use core::{any::TypeId, marker::PhantomData}; use thiserror::Error; use super::{unsafe_world_cell::UnsafeEntityCell, Ref, ON_REMOVE, ON_REPLACE}; @@ -925,7 +925,7 @@ impl<'w> EntityWorldMut<'w> { .bundles .init_dynamic_info(&self.world.components, component_ids); let mut storage_types = - std::mem::take(self.world.bundles.get_storages_unchecked(bundle_id)); + core::mem::take(self.world.bundles.get_storages_unchecked(bundle_id)); let bundle_inserter = BundleInserter::new_with_id( self.world, self.location.archetype_id, @@ -940,7 +940,7 @@ impl<'w> EntityWorldMut<'w> { iter_components, (*storage_types).iter().cloned(), ); - *self.world.bundles.get_storages_unchecked(bundle_id) = std::mem::take(&mut storage_types); + *self.world.bundles.get_storages_unchecked(bundle_id) = core::mem::take(&mut storage_types); self } @@ -2782,11 +2782,15 @@ pub(crate) unsafe fn take_component<'a>( #[cfg(test)] mod tests { use bevy_ptr::OwningPtr; - use std::panic::AssertUnwindSafe; - - use crate::system::RunSystemOnce as _; - use crate::world::{FilteredEntityMut, FilteredEntityRef}; - use crate::{self as bevy_ecs, component::ComponentId, prelude::*, system::assert_is_system}; + use core::panic::AssertUnwindSafe; + + use crate::{ + self as bevy_ecs, + component::ComponentId, + prelude::*, + system::{assert_is_system, RunSystemOnce as _}, + world::{FilteredEntityMut, FilteredEntityRef}, + }; use super::{EntityMutExcept, EntityRefExcept}; @@ -2824,7 +2828,7 @@ mod tests { let entity = world.spawn(TestComponent(42)).id(); let component_id = world .components() - .get_id(std::any::TypeId::of::()) + .get_id(core::any::TypeId::of::()) .unwrap(); let entity = world.entity(entity); @@ -2841,7 +2845,7 @@ mod tests { let entity = world.spawn(TestComponent(42)).id(); let component_id = world .components() - .get_id(std::any::TypeId::of::()) + .get_id(core::any::TypeId::of::()) .unwrap(); let mut entity_mut = world.entity_mut(entity); diff --git a/crates/bevy_ecs/src/world/identifier.rs b/crates/bevy_ecs/src/world/identifier.rs index 1c1fd93c3bd3c..9187b818504b5 100644 --- a/crates/bevy_ecs/src/world/identifier.rs +++ b/crates/bevy_ecs/src/world/identifier.rs @@ -1,11 +1,10 @@ -use crate::system::{ExclusiveSystemParam, SystemMeta}; use crate::{ component::Tick, storage::SparseSetIndex, - system::{ReadOnlySystemParam, SystemParam}, + system::{ExclusiveSystemParam, ReadOnlySystemParam, SystemMeta, SystemParam}, world::{FromWorld, World}, }; -use std::sync::atomic::{AtomicUsize, Ordering}; +use core::sync::atomic::{AtomicUsize, Ordering}; use super::unsafe_world_cell::UnsafeWorldCell; @@ -98,7 +97,7 @@ mod tests { #[test] fn world_ids_unique() { - let ids = std::iter::repeat_with(WorldId::new) + let ids = core::iter::repeat_with(WorldId::new) .take(50) .map(Option::unwrap) .collect::>(); @@ -139,7 +138,7 @@ mod tests { // #[should_panic] // fn panic_on_overflow() { // MAX_WORLD_ID.store(usize::MAX - 50, Ordering::Relaxed); - // std::iter::repeat_with(WorldId::new) + // core::iter::repeat_with(WorldId::new) // .take(500) // .for_each(|_| ()); // } diff --git a/crates/bevy_ecs/src/world/mod.rs b/crates/bevy_ecs/src/world/mod.rs index 00be7aee4d68f..528cbaa2ae424 100644 --- a/crates/bevy_ecs/src/world/mod.rs +++ b/crates/bevy_ecs/src/world/mod.rs @@ -45,7 +45,7 @@ use crate::{ }; use bevy_ptr::{OwningPtr, Ptr}; use bevy_utils::tracing::warn; -use std::{ +use core::{ any::TypeId, fmt, mem::MaybeUninit, @@ -271,7 +271,7 @@ impl World { /// Will panic if `T` exists in any archetypes. pub fn register_component_hooks(&mut self) -> &mut ComponentHooks { let index = self.init_component::(); - assert!(!self.archetypes.archetypes.iter().any(|a| a.contains(index)), "Components hooks cannot be modified if the component already exists in an archetype, use init_component if {} may already be in use", std::any::type_name::()); + assert!(!self.archetypes.archetypes.iter().any(|a| a.contains(index)), "Components hooks cannot be modified if the component already exists in an archetype, use init_component if {} may already be in use", core::any::type_name::()); // SAFETY: We just created this component unsafe { self.components.get_hooks_mut(index).debug_checked_unwrap() } } @@ -590,7 +590,7 @@ impl World { entities: [Entity; N], ) -> Result<[EntityRef<'_>; N], Entity> { let mut refs = [MaybeUninit::uninit(); N]; - for (r, id) in std::iter::zip(&mut refs, entities) { + for (r, id) in core::iter::zip(&mut refs, entities) { *r = MaybeUninit::new(self.get_entity(id).ok_or(id)?); } @@ -773,7 +773,7 @@ impl World { let world_cell = self.as_unsafe_world_cell(); let mut cells = [MaybeUninit::uninit(); N]; - for (cell, id) in std::iter::zip(&mut cells, entities) { + for (cell, id) in core::iter::zip(&mut cells, entities) { *cell = MaybeUninit::new( world_cell .get_entity(id) @@ -1611,7 +1611,7 @@ impl World { Did you forget to add it using `app.insert_resource` / `app.init_resource`? Resources are also implicitly added via `app.add_event`, and can be added by plugins.", - std::any::type_name::() + core::any::type_name::() ), } } @@ -1635,7 +1635,7 @@ impl World { Did you forget to add it using `app.insert_resource` / `app.init_resource`? Resources are also implicitly added via `app.add_event`, and can be added by plugins.", - std::any::type_name::() + core::any::type_name::() ), } } @@ -1659,7 +1659,7 @@ impl World { Did you forget to add it using `app.insert_resource` / `app.init_resource`? Resources are also implicitly added via `app.add_event`, and can be added by plugins.", - std::any::type_name::() + core::any::type_name::() ), } } @@ -1746,7 +1746,7 @@ impl World { "Requested non-send resource {} does not exist in the `World`. Did you forget to add it using `app.insert_non_send_resource` / `app.init_non_send_resource`? Non-send resources can also be added by plugins.", - std::any::type_name::() + core::any::type_name::() ), } } @@ -1768,7 +1768,7 @@ impl World { "Requested non-send resource {} does not exist in the `World`. Did you forget to add it using `app.insert_non_send_resource` / `app.init_non_send_resource`? Non-send resources can also be added by plugins.", - std::any::type_name::() + core::any::type_name::() ), } } @@ -2000,13 +2000,13 @@ impl World { let component_id = self .components .get_resource_id(TypeId::of::()) - .unwrap_or_else(|| panic!("resource does not exist: {}", std::any::type_name::())); + .unwrap_or_else(|| panic!("resource does not exist: {}", core::any::type_name::())); let (ptr, mut ticks, mut _caller) = self .storages .resources .get_mut(component_id) .and_then(ResourceData::remove) - .unwrap_or_else(|| panic!("resource does not exist: {}", std::any::type_name::())); + .unwrap_or_else(|| panic!("resource does not exist: {}", core::any::type_name::())); // Read the value onto the stack to avoid potential mut aliasing. // SAFETY: `ptr` was obtained from the TypeId of `R`. let mut value = unsafe { ptr.read::() }; @@ -2025,7 +2025,7 @@ impl World { assert!(!self.contains_resource::(), "Resource `{}` was inserted during a call to World::resource_scope.\n\ This is not allowed as the original resource is reinserted to the world after the closure is invoked.", - std::any::type_name::()); + core::any::type_name::()); OwningPtr::make(value, |ptr| { // SAFETY: pointer is of type R @@ -2044,7 +2044,7 @@ impl World { .unwrap_or_else(|| { panic!( "No resource of type {} exists in the World.", - std::any::type_name::() + core::any::type_name::() ) }); } @@ -2058,7 +2058,7 @@ impl World { /// or [`None`] if the `event` could not be sent. #[inline] pub fn send_event(&mut self, event: E) -> Option> { - self.send_event_batch(std::iter::once(event))?.next() + self.send_event_batch(core::iter::once(event))?.next() } /// Sends the default value of the [`Event`] of type `E`. @@ -2080,7 +2080,7 @@ impl World { let Some(mut events_resource) = self.get_resource_mut::>() else { bevy_utils::tracing::error!( "Unable to send event `{}`\n\tEvent must be added to the app with `add_event()`\n\thttps://docs.rs/bevy/*/bevy/app/struct.App.html#method.add_event ", - std::any::type_name::() + core::any::type_name::() ); return None; }; @@ -2989,16 +2989,15 @@ mod tests { ptr::OwningPtr, system::Resource, }; + use alloc::sync::Arc; use bevy_ecs_macros::Component; use bevy_utils::{HashMap, HashSet}; - use std::{ + use core::{ any::TypeId, panic, - sync::{ - atomic::{AtomicBool, AtomicU32, Ordering}, - Arc, Mutex, - }, + sync::atomic::{AtomicBool, AtomicU32, Ordering}, }; + use std::sync::Mutex; // For bevy_ecs_macros use crate as bevy_ecs; @@ -3082,7 +3081,7 @@ mod tests { if !expected_panic_flag { match panic_res { Ok(()) => panic!("Expected a panic but it didn't happen"), - Err(e) => panic::resume_unwind(e), + Err(e) => std::panic::resume_unwind(e), } } @@ -3094,7 +3093,7 @@ mod tests { fn panic_while_overwriting_component() { let helper = DropTestHelper::new(); - let res = panic::catch_unwind(|| { + let res = std::panic::catch_unwind(|| { let mut world = World::new(); world .spawn_empty() @@ -3177,12 +3176,12 @@ mod tests { let mut iter = world.iter_resources(); let (info, ptr) = iter.next().unwrap(); - assert_eq!(info.name(), std::any::type_name::()); + assert_eq!(info.name(), core::any::type_name::()); // SAFETY: We know that the resource is of type `TestResource` assert_eq!(unsafe { ptr.deref::().0 }, 42); let (info, ptr) = iter.next().unwrap(); - assert_eq!(info.name(), std::any::type_name::()); + assert_eq!(info.name(), core::any::type_name::()); assert_eq!( // SAFETY: We know that the resource is of type `TestResource2` unsafe { &ptr.deref::().0 }, @@ -3203,14 +3202,14 @@ mod tests { let mut iter = world.iter_resources_mut(); let (info, mut mut_untyped) = iter.next().unwrap(); - assert_eq!(info.name(), std::any::type_name::()); + assert_eq!(info.name(), core::any::type_name::()); // SAFETY: We know that the resource is of type `TestResource` unsafe { mut_untyped.as_mut().deref_mut::().0 = 43; }; let (info, mut mut_untyped) = iter.next().unwrap(); - assert_eq!(info.name(), std::any::type_name::()); + assert_eq!(info.name(), core::any::type_name::()); // SAFETY: We know that the resource is of type `TestResource2` unsafe { mut_untyped.as_mut().deref_mut::().0 = "Hello, world?".to_string(); @@ -3237,7 +3236,7 @@ mod tests { ComponentDescriptor::new_with_layout( "Custom Test Component".to_string(), StorageType::Table, - std::alloc::Layout::new::<[u8; 8]>(), + core::alloc::Layout::new::<[u8; 8]>(), Some(|ptr| { let data = ptr.read::<[u8; 8]>(); assert_eq!(data, [0, 1, 2, 3, 4, 5, 6, 7]); @@ -3256,7 +3255,7 @@ mod tests { component_id, ptr, #[cfg(feature = "track_change_detection")] - core::panic::Location::caller(), + panic::Location::caller(), ); } }); @@ -3477,7 +3476,7 @@ mod tests { let mut entities = world.iter_entities_mut().collect::>(); entities.sort_by_key(|e| e.get::().map(|a| a.0).or(e.get::().map(|b| b.0))); let (a, b) = entities.split_at_mut(2); - std::mem::swap( + core::mem::swap( &mut a[1].get_mut::().unwrap().0, &mut b[0].get_mut::().unwrap().0, ); diff --git a/crates/bevy_ecs/src/world/reflect.rs b/crates/bevy_ecs/src/world/reflect.rs index 2609d4e416722..f0f982926549b 100644 --- a/crates/bevy_ecs/src/world/reflect.rs +++ b/crates/bevy_ecs/src/world/reflect.rs @@ -6,8 +6,7 @@ use thiserror::Error; use bevy_reflect::{Reflect, ReflectFromPtr}; -use crate::prelude::*; -use crate::world::ComponentId; +use crate::{prelude::*, world::ComponentId}; impl World { /// Retrieves a reference to the given `entity`'s [`Component`] of the given `type_id` using @@ -247,7 +246,7 @@ pub enum GetComponentReflectError { #[cfg(test)] mod tests { - use std::any::TypeId; + use core::any::TypeId; use bevy_reflect::Reflect; diff --git a/crates/bevy_ecs/src/world/spawn_batch.rs b/crates/bevy_ecs/src/world/spawn_batch.rs index ea6955a96d9ef..dbdbc1cfac31b 100644 --- a/crates/bevy_ecs/src/world/spawn_batch.rs +++ b/crates/bevy_ecs/src/world/spawn_batch.rs @@ -3,9 +3,9 @@ use crate::{ entity::Entity, world::World, }; -use std::iter::FusedIterator; +use core::iter::FusedIterator; #[cfg(feature = "track_change_detection")] -use std::panic::Location; +use core::panic::Location; /// An iterator that spawns a series of entities and returns the [ID](Entity) of /// each spawned entity. diff --git a/crates/bevy_ecs/src/world/unsafe_world_cell.rs b/crates/bevy_ecs/src/world/unsafe_world_cell.rs index 7aac53742d458..45223b836d71b 100644 --- a/crates/bevy_ecs/src/world/unsafe_world_cell.rs +++ b/crates/bevy_ecs/src/world/unsafe_world_cell.rs @@ -20,7 +20,7 @@ use crate::{ use bevy_ptr::Ptr; #[cfg(feature = "track_change_detection")] use bevy_ptr::UnsafeCellDeref; -use std::{any::TypeId, cell::UnsafeCell, fmt::Debug, marker::PhantomData, ptr}; +use core::{any::TypeId, cell::UnsafeCell, fmt::Debug, marker::PhantomData, ptr}; /// Variant of the [`World`] where resource and component accesses take `&self`, and the responsibility to avoid /// aliasing violations are given to the caller instead of being checked at compile-time by rust's unique XOR shared rule. @@ -303,7 +303,7 @@ impl<'w> UnsafeWorldCell<'w> { let change_tick = unsafe { &self.world_metadata().change_tick }; // NOTE: We can used a relaxed memory ordering here, since nothing // other than the atomic value itself is relying on atomic synchronization - Tick::new(change_tick.fetch_add(1, std::sync::atomic::Ordering::Relaxed)) + Tick::new(change_tick.fetch_add(1, core::sync::atomic::Ordering::Relaxed)) } /// Provides unchecked access to the internal data stores of the [`World`]. @@ -634,7 +634,7 @@ impl<'w> UnsafeWorldCell<'w> { } impl Debug for UnsafeWorldCell<'_> { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { // SAFETY: World's Debug implementation only accesses metadata. Debug::fmt(unsafe { self.world_metadata() }, f) } diff --git a/crates/bevy_gilrs/src/gilrs_system.rs b/crates/bevy_gilrs/src/gilrs_system.rs index 331bccb0cad91..6a54249be7508 100644 --- a/crates/bevy_gilrs/src/gilrs_system.rs +++ b/crates/bevy_gilrs/src/gilrs_system.rs @@ -2,17 +2,20 @@ use crate::{ converter::{convert_axis, convert_button, convert_gamepad_id}, Gilrs, }; -use bevy_ecs::event::EventWriter; #[cfg(target_arch = "wasm32")] use bevy_ecs::system::NonSendMut; -use bevy_ecs::system::{Res, ResMut}; -use bevy_input::gamepad::{ - GamepadAxisChangedEvent, GamepadButtonChangedEvent, GamepadConnection, GamepadConnectionEvent, - GamepadSettings, +use bevy_ecs::{ + event::EventWriter, + system::{Res, ResMut}, +}; +use bevy_input::{ + gamepad::{ + GamepadAxisChangedEvent, GamepadButtonChangedEvent, GamepadConnection, + GamepadConnectionEvent, GamepadEvent, GamepadInfo, GamepadSettings, + }, + prelude::{GamepadAxis, GamepadButton}, + Axis, }; -use bevy_input::gamepad::{GamepadEvent, GamepadInfo}; -use bevy_input::prelude::{GamepadAxis, GamepadButton}; -use bevy_input::Axis; use gilrs::{ev::filter::axis_dpad_to_button, EventType, Filter}; pub fn gilrs_event_startup_system( diff --git a/crates/bevy_gilrs/src/rumble.rs b/crates/bevy_gilrs/src/rumble.rs index b59abef9a066f..4d96ca4e307a9 100644 --- a/crates/bevy_gilrs/src/rumble.rs +++ b/crates/bevy_gilrs/src/rumble.rs @@ -5,8 +5,11 @@ use bevy_ecs::prelude::{EventReader, Res, ResMut, Resource}; use bevy_ecs::system::NonSendMut; use bevy_input::gamepad::{GamepadRumbleIntensity, GamepadRumbleRequest}; use bevy_time::{Real, Time}; -use bevy_utils::tracing::{debug, warn}; -use bevy_utils::{synccell::SyncCell, Duration, HashMap}; +use bevy_utils::{ + synccell::SyncCell, + tracing::{debug, warn}, + Duration, HashMap, +}; use gilrs::{ ff::{self, BaseEffect, BaseEffectType, Repeat, Replay}, GamepadId, diff --git a/crates/bevy_gizmos/src/arcs.rs b/crates/bevy_gizmos/src/arcs.rs index c3b96f75dc2c8..cc4934398db06 100644 --- a/crates/bevy_gizmos/src/arcs.rs +++ b/crates/bevy_gizmos/src/arcs.rs @@ -3,11 +3,13 @@ //! Includes the implementation of [`Gizmos::arc_2d`], //! and assorted support items. -use crate::circles::DEFAULT_CIRCLE_RESOLUTION; -use crate::prelude::{GizmoConfigGroup, Gizmos}; +use crate::{ + circles::DEFAULT_CIRCLE_RESOLUTION, + prelude::{GizmoConfigGroup, Gizmos}, +}; use bevy_color::Color; use bevy_math::{Isometry2d, Isometry3d, Quat, Rot2, Vec2, Vec3}; -use std::f32::consts::{FRAC_PI_2, TAU}; +use core::f32::consts::{FRAC_PI_2, TAU}; // === 2D === @@ -365,7 +367,7 @@ where to: Vec2, color: impl Into, ) -> Arc2dBuilder<'_, 'w, 's, Config, Clear> { - self.arc_2d_from_to(center, from, to, color, std::convert::identity) + self.arc_2d_from_to(center, from, to, color, core::convert::identity) } /// Draws the longest arc between two points (`from` and `to`) relative to a specified `center` point. diff --git a/crates/bevy_gizmos/src/circles.rs b/crates/bevy_gizmos/src/circles.rs index 1f63aed486c23..7b0a5e82890a8 100644 --- a/crates/bevy_gizmos/src/circles.rs +++ b/crates/bevy_gizmos/src/circles.rs @@ -5,9 +5,8 @@ use crate::prelude::{GizmoConfigGroup, Gizmos}; use bevy_color::Color; -use bevy_math::{ops, Isometry2d, Isometry3d}; -use bevy_math::{Quat, Vec2, Vec3}; -use std::f32::consts::TAU; +use bevy_math::{ops, Isometry2d, Isometry3d, Quat, Vec2, Vec3}; +use core::f32::consts::TAU; pub(crate) const DEFAULT_CIRCLE_RESOLUTION: u32 = 32; diff --git a/crates/bevy_gizmos/src/config.rs b/crates/bevy_gizmos/src/config.rs index 0705029ddf19c..2f164d9f0b956 100644 --- a/crates/bevy_gizmos/src/config.rs +++ b/crates/bevy_gizmos/src/config.rs @@ -12,10 +12,10 @@ use bevy_ecs::component::Component; use bevy_ecs::{reflect::ReflectResource, system::Resource}; use bevy_reflect::{std_traits::ReflectDefault, Reflect, TypePath}; use bevy_utils::TypeIdMap; -use core::panic; -use std::{ +use core::{ any::TypeId, ops::{Deref, DerefMut}, + panic, }; /// An enum configuring how line joints will be drawn. diff --git a/crates/bevy_gizmos/src/gizmos.rs b/crates/bevy_gizmos/src/gizmos.rs index da66a8981dcf9..86df15333949f 100644 --- a/crates/bevy_gizmos/src/gizmos.rs +++ b/crates/bevy_gizmos/src/gizmos.rs @@ -1,6 +1,6 @@ //! A module for the [`Gizmos`] [`SystemParam`]. -use std::{iter, marker::PhantomData, mem}; +use core::{iter, marker::PhantomData, mem}; use bevy_color::{Color, LinearRgba}; use bevy_ecs::{ @@ -13,8 +13,7 @@ use bevy_transform::TransformPoint; use bevy_utils::default; use crate::{ - config::GizmoConfigGroup, - config::{DefaultGizmoConfigGroup, GizmoConfigStore}, + config::{DefaultGizmoConfigGroup, GizmoConfigGroup, GizmoConfigStore}, prelude::GizmoConfig, }; diff --git a/crates/bevy_gizmos/src/grid.rs b/crates/bevy_gizmos/src/grid.rs index 7e637c54e183c..55e611d767874 100644 --- a/crates/bevy_gizmos/src/grid.rs +++ b/crates/bevy_gizmos/src/grid.rs @@ -5,8 +5,7 @@ use crate::prelude::{GizmoConfigGroup, Gizmos}; use bevy_color::Color; -use bevy_math::Vec3Swizzles; -use bevy_math::{ops, Isometry2d, Isometry3d, Quat, UVec2, UVec3, Vec2, Vec3}; +use bevy_math::{ops, Isometry2d, Isometry3d, Quat, UVec2, UVec3, Vec2, Vec3, Vec3Swizzles}; /// A builder returned by [`Gizmos::grid_3d`] pub struct GridBuilder3d<'a, 'w, 's, Config, Clear> diff --git a/crates/bevy_gizmos/src/lib.rs b/crates/bevy_gizmos/src/lib.rs index bbef44df46677..0c3bd81d67a10 100644 --- a/crates/bevy_gizmos/src/lib.rs +++ b/crates/bevy_gizmos/src/lib.rs @@ -57,6 +57,7 @@ mod pipeline_3d; pub mod prelude { #[cfg(feature = "bevy_render")] pub use crate::aabb::{AabbGizmoConfigGroup, ShowAabbGizmo}; + #[doc(hidden)] pub use crate::{ config::{ @@ -72,56 +73,56 @@ pub mod prelude { pub use crate::light::{LightGizmoColor, LightGizmoConfigGroup, ShowLightGizmo}; } -#[cfg(feature = "bevy_render")] -use bevy_ecs::{ - query::ROQueryItem, - system::{ - lifetimeless::{Read, SRes}, - Commands, SystemParamItem, - }, -}; - use bevy_app::{App, FixedFirst, FixedLast, Last, Plugin, RunFixedMainLoop}; use bevy_asset::{Asset, AssetApp, Assets, Handle}; use bevy_color::LinearRgba; -#[cfg(feature = "bevy_render")] -use bevy_ecs::component::Component; use bevy_ecs::{ schedule::{IntoSystemConfigs, SystemSet}, system::{Res, ResMut, Resource}, }; use bevy_math::Vec3; use bevy_reflect::TypePath; + +#[cfg(feature = "bevy_render")] +use { + bevy_ecs::{ + component::Component, + query::ROQueryItem, + system::{ + lifetimeless::{Read, SRes}, + Commands, SystemParamItem, + }, + }, + bevy_render::{ + extract_component::{ComponentUniforms, DynamicUniformIndex, UniformComponentPlugin}, + render_asset::{PrepareAssetError, RenderAsset, RenderAssetPlugin, RenderAssets}, + render_phase::{PhaseItem, RenderCommand, RenderCommandResult, TrackedRenderPass}, + render_resource::{ + binding_types::uniform_buffer, BindGroup, BindGroupEntries, BindGroupLayout, + BindGroupLayoutEntries, Buffer, BufferInitDescriptor, BufferUsages, Shader, + ShaderStages, ShaderType, VertexFormat, + }, + renderer::RenderDevice, + Extract, ExtractSchedule, Render, RenderApp, RenderSet, + }, + bytemuck::cast_slice, +}; + #[cfg(all( feature = "bevy_render", any(feature = "bevy_pbr", feature = "bevy_sprite"), ))] use bevy_render::render_resource::{VertexAttribute, VertexBufferLayout, VertexStepMode}; -#[cfg(feature = "bevy_render")] -use bevy_render::{ - extract_component::{ComponentUniforms, DynamicUniformIndex, UniformComponentPlugin}, - render_asset::{PrepareAssetError, RenderAsset, RenderAssetPlugin, RenderAssets}, - render_phase::{PhaseItem, RenderCommand, RenderCommandResult, TrackedRenderPass}, - render_resource::{ - binding_types::uniform_buffer, BindGroup, BindGroupEntries, BindGroupLayout, - BindGroupLayoutEntries, Buffer, BufferInitDescriptor, BufferUsages, Shader, ShaderStages, - ShaderType, VertexFormat, - }, - renderer::RenderDevice, - Extract, ExtractSchedule, Render, RenderApp, RenderSet, -}; use bevy_time::Fixed; use bevy_utils::TypeIdMap; -#[cfg(feature = "bevy_render")] -use bytemuck::cast_slice; use config::{ DefaultGizmoConfigGroup, GizmoConfig, GizmoConfigGroup, GizmoConfigStore, GizmoLineJoint, }; +use core::{any::TypeId, mem}; use gizmos::{GizmoStorage, Swap}; #[cfg(all(feature = "bevy_pbr", feature = "bevy_render"))] use light::LightGizmoPlugin; -use std::{any::TypeId, mem}; #[cfg(feature = "bevy_render")] const LINE_SHADER_HANDLE: Handle = Handle::weak_from_u128(7414812689238026784); diff --git a/crates/bevy_gizmos/src/light.rs b/crates/bevy_gizmos/src/light.rs index 0debc8238c247..615f1e8753cbf 100644 --- a/crates/bevy_gizmos/src/light.rs +++ b/crates/bevy_gizmos/src/light.rs @@ -1,6 +1,6 @@ //! A module adding debug visualization of [`PointLight`]s, [`SpotLight`]s and [`DirectionalLight`]s. -use std::f32::consts::PI; +use core::f32::consts::PI; use crate::{self as bevy_gizmos, primitives::dim3::GizmoPrimitive3d}; diff --git a/crates/bevy_gizmos/src/primitives/dim2.rs b/crates/bevy_gizmos/src/primitives/dim2.rs index 7d0d3850a11c6..1c696dfc8d2b3 100644 --- a/crates/bevy_gizmos/src/primitives/dim2.rs +++ b/crates/bevy_gizmos/src/primitives/dim2.rs @@ -1,16 +1,18 @@ //! A module for rendering each of the 2D [`bevy_math::primitives`] with [`Gizmos`]. -use std::f32::consts::{FRAC_PI_2, PI}; +use core::f32::consts::{FRAC_PI_2, PI}; use super::helpers::*; use bevy_color::Color; -use bevy_math::primitives::{ - Annulus, Arc2d, BoxedPolygon, BoxedPolyline2d, Capsule2d, Circle, CircularSector, - CircularSegment, Ellipse, Line2d, Plane2d, Polygon, Polyline2d, Primitive2d, Rectangle, - RegularPolygon, Rhombus, Segment2d, Triangle2d, +use bevy_math::{ + primitives::{ + Annulus, Arc2d, BoxedPolygon, BoxedPolyline2d, Capsule2d, Circle, CircularSector, + CircularSegment, Ellipse, Line2d, Plane2d, Polygon, Polyline2d, Primitive2d, Rectangle, + RegularPolygon, Rhombus, Segment2d, Triangle2d, + }, + Dir2, Isometry2d, Rot2, Vec2, }; -use bevy_math::{Dir2, Isometry2d, Rot2, Vec2}; use crate::prelude::{GizmoConfigGroup, Gizmos}; diff --git a/crates/bevy_gizmos/src/primitives/dim3.rs b/crates/bevy_gizmos/src/primitives/dim3.rs index f2ee075c16c75..cde97c0836cbc 100644 --- a/crates/bevy_gizmos/src/primitives/dim3.rs +++ b/crates/bevy_gizmos/src/primitives/dim3.rs @@ -3,14 +3,18 @@ use super::helpers::*; use bevy_color::Color; -use bevy_math::primitives::{ - BoxedPolyline3d, Capsule3d, Cone, ConicalFrustum, Cuboid, Cylinder, Line3d, Plane3d, - Polyline3d, Primitive3d, Segment3d, Sphere, Tetrahedron, Torus, Triangle3d, +use bevy_math::{ + primitives::{ + BoxedPolyline3d, Capsule3d, Cone, ConicalFrustum, Cuboid, Cylinder, Line3d, Plane3d, + Polyline3d, Primitive3d, Segment3d, Sphere, Tetrahedron, Torus, Triangle3d, + }, + Dir3, Isometry3d, Quat, UVec2, Vec2, Vec3, }; -use bevy_math::{Dir3, Isometry3d, Quat, UVec2, Vec2, Vec3}; -use crate::circles::SphereBuilder; -use crate::prelude::{GizmoConfigGroup, Gizmos}; +use crate::{ + circles::SphereBuilder, + prelude::{GizmoConfigGroup, Gizmos}, +}; const DEFAULT_RESOLUTION: u32 = 5; // length used to simulate infinite lines diff --git a/crates/bevy_gizmos/src/primitives/helpers.rs b/crates/bevy_gizmos/src/primitives/helpers.rs index fa86a6ebe0413..66e171c6c9f59 100644 --- a/crates/bevy_gizmos/src/primitives/helpers.rs +++ b/crates/bevy_gizmos/src/primitives/helpers.rs @@ -1,4 +1,4 @@ -use std::f32::consts::TAU; +use core::f32::consts::TAU; use bevy_math::{ops, Vec2}; @@ -37,7 +37,7 @@ pub(crate) fn circle_coordinates_closed( radius: f32, resolution: u32, ) -> impl Iterator { - circle_coordinates(radius, resolution).chain(std::iter::once(single_circle_coordinate( + circle_coordinates(radius, resolution).chain(core::iter::once(single_circle_coordinate( radius, resolution, resolution, ))) } diff --git a/crates/bevy_gizmos/src/rounded_box.rs b/crates/bevy_gizmos/src/rounded_box.rs index ac459c917866f..70ee09b64d01d 100644 --- a/crates/bevy_gizmos/src/rounded_box.rs +++ b/crates/bevy_gizmos/src/rounded_box.rs @@ -3,7 +3,7 @@ //! Includes the implementation of [`Gizmos::rounded_rect`], [`Gizmos::rounded_rect_2d`] and [`Gizmos::rounded_cuboid`]. //! and assorted support items. -use std::f32::consts::FRAC_PI_2; +use core::f32::consts::FRAC_PI_2; use crate::prelude::{GizmoConfigGroup, Gizmos}; use bevy_color::Color; @@ -75,7 +75,7 @@ impl Drop for RoundedRectBuilder<'_, '_, '_, T> { let mut inner_half_size = outer_half_size - Vec2::splat(corner_radius); if config.corner_radius < 0. { - std::mem::swap(&mut outer_half_size, &mut inner_half_size); + core::mem::swap(&mut outer_half_size, &mut inner_half_size); } // Handle cases where the rectangle collapses into simpler shapes diff --git a/crates/bevy_gltf/src/lib.rs b/crates/bevy_gltf/src/lib.rs index d27a899b761e1..fdd3a6e783557 100644 --- a/crates/bevy_gltf/src/lib.rs +++ b/crates/bevy_gltf/src/lib.rs @@ -95,6 +95,8 @@ //! //! You can use [`GltfAssetLabel`] to ensure you are using the correct label. +extern crate alloc; + #[cfg(feature = "bevy_animation")] use bevy_animation::AnimationClip; use bevy_utils::HashMap; @@ -107,8 +109,7 @@ use bevy_app::prelude::*; use bevy_asset::{Asset, AssetApp, AssetPath, Handle}; use bevy_ecs::{prelude::Component, reflect::ReflectComponent}; use bevy_pbr::StandardMaterial; -use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::{Reflect, TypePath}; +use bevy_reflect::{std_traits::ReflectDefault, Reflect, TypePath}; use bevy_render::{ mesh::{skinning::SkinnedMeshInverseBindposes, Mesh, MeshVertexAttribute}, renderer::RenderDevice, @@ -527,8 +528,8 @@ pub enum GltfAssetLabel { InverseBindMatrices(usize), } -impl std::fmt::Display for GltfAssetLabel { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Display for GltfAssetLabel { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { GltfAssetLabel::Scene(index) => f.write_str(&format!("Scene{index}")), GltfAssetLabel::Node(index) => f.write_str(&format!("Node{index}")), diff --git a/crates/bevy_gltf/src/loader.rs b/crates/bevy_gltf/src/loader.rs index d36fc4a39a97c..421d87349fdad 100644 --- a/crates/bevy_gltf/src/loader.rs +++ b/crates/bevy_gltf/src/loader.rs @@ -3,6 +3,7 @@ use crate::{ GltfMeshExtras, GltfNode, GltfSceneExtras, GltfSkin, }; +use alloc::collections::VecDeque; use bevy_animation::prelude::{ Keyframes, MorphWeightsKeyframes, RotationKeyframes, ScaleKeyframes, TranslationKeyframes, }; @@ -14,8 +15,10 @@ use bevy_asset::{ use bevy_color::{Color, LinearRgba}; use bevy_core::Name; use bevy_core_pipeline::prelude::Camera3dBundle; -use bevy_ecs::entity::EntityHashMap; -use bevy_ecs::{entity::Entity, world::World}; +use bevy_ecs::{ + entity::{Entity, EntityHashMap}, + world::World, +}; use bevy_hierarchy::{BuildChildren, ChildBuild, WorldChildBuilder}; use bevy_math::{Affine2, Mat4, Vec3}; use bevy_pbr::{ @@ -43,23 +46,24 @@ use bevy_scene::Scene; #[cfg(not(target_arch = "wasm32"))] use bevy_tasks::IoTaskPool; use bevy_transform::components::Transform; -use bevy_utils::tracing::{error, info_span, warn}; -use bevy_utils::{HashMap, HashSet}; -use gltf::image::Source; +use bevy_utils::{ + tracing::{error, info_span, warn}, + HashMap, HashSet, +}; use gltf::{ accessor::Iter, + image::Source, + json, mesh::{util::ReadIndices, Mode}, texture::{Info, MagFilter, MinFilter, TextureTransform, WrappingMode}, - Material, Node, Primitive, Semantic, + Document, Material, Node, Primitive, Semantic, }; -use gltf::{json, Document}; use serde::{Deserialize, Serialize}; use serde_json::{value, Value}; #[cfg(feature = "bevy_animation")] use smallvec::SmallVec; -use std::io::Error; use std::{ - collections::VecDeque, + io::Error, path::{Path, PathBuf}, }; use thiserror::Error; @@ -1417,7 +1421,7 @@ fn load_node( // NOTE: KHR_punctual_lights defines the intensity units for point lights in // candela (lm/sr) which is luminous intensity and we need luminous power. // For a point light, luminous power = 4 * pi * luminous intensity - intensity: light.intensity() * std::f32::consts::PI * 4.0, + intensity: light.intensity() * core::f32::consts::PI * 4.0, range: light.range().unwrap_or(20.0), radius: 0.0, ..Default::default() @@ -1443,7 +1447,7 @@ fn load_node( // NOTE: KHR_punctual_lights defines the intensity units for spot lights in // candela (lm/sr) which is luminous intensity and we need luminous power. // For a spot light, we map luminous power = 4 * pi * luminous intensity - intensity: light.intensity() * std::f32::consts::PI * 4.0, + intensity: light.intensity() * core::f32::consts::PI * 4.0, range: light.range().unwrap_or(20.0), radius: light.range().unwrap_or(0.0), inner_angle: inner_cone_angle, diff --git a/crates/bevy_hierarchy/src/child_builder.rs b/crates/bevy_hierarchy/src/child_builder.rs index 0c9d03ce77991..c1e51d6f36846 100644 --- a/crates/bevy_hierarchy/src/child_builder.rs +++ b/crates/bevy_hierarchy/src/child_builder.rs @@ -750,7 +750,7 @@ mod tests { let world = &mut World::new(); world.insert_resource(Events::::default()); - let [a, b, c, d] = std::array::from_fn(|_| world.spawn_empty().id()); + let [a, b, c, d] = core::array::from_fn(|_| world.spawn_empty().id()); world.entity_mut(a).add_child(b); @@ -785,7 +785,7 @@ mod tests { let world = &mut World::new(); world.insert_resource(Events::::default()); - let [a, b, c] = std::array::from_fn(|_| world.spawn_empty().id()); + let [a, b, c] = core::array::from_fn(|_| world.spawn_empty().id()); world.entity_mut(a).set_parent(b); @@ -819,7 +819,7 @@ mod tests { fn set_parent_of_orphan() { let world = &mut World::new(); - let [a, b, c] = std::array::from_fn(|_| world.spawn_empty().id()); + let [a, b, c] = core::array::from_fn(|_| world.spawn_empty().id()); world.entity_mut(a).set_parent(b); assert_parent(world, a, Some(b)); assert_children(world, b, Some(&[a])); @@ -836,7 +836,7 @@ mod tests { let world = &mut World::new(); world.insert_resource(Events::::default()); - let [a, b, c] = std::array::from_fn(|_| world.spawn_empty().id()); + let [a, b, c] = core::array::from_fn(|_| world.spawn_empty().id()); world.entity_mut(a).add_children(&[b, c]); world.entity_mut(b).remove_parent(); diff --git a/crates/bevy_hierarchy/src/components/children.rs b/crates/bevy_hierarchy/src/components/children.rs index ee2fb5578a8cf..df4127b2a40e8 100644 --- a/crates/bevy_hierarchy/src/components/children.rs +++ b/crates/bevy_hierarchy/src/components/children.rs @@ -6,9 +6,8 @@ use bevy_ecs::{ prelude::FromWorld, world::World, }; -use core::slice; +use core::{ops::Deref, slice}; use smallvec::SmallVec; -use std::ops::Deref; /// Contains references to the child entities of this entity. /// @@ -71,7 +70,7 @@ impl Children { #[inline] pub fn sort_by(&mut self, compare: F) where - F: FnMut(&Entity, &Entity) -> std::cmp::Ordering, + F: FnMut(&Entity, &Entity) -> core::cmp::Ordering, { self.0.sort_by(compare); } @@ -120,7 +119,7 @@ impl Children { #[inline] pub fn sort_unstable_by(&mut self, compare: F) where - F: FnMut(&Entity, &Entity) -> std::cmp::Ordering, + F: FnMut(&Entity, &Entity) -> core::cmp::Ordering, { self.0.sort_unstable_by(compare); } diff --git a/crates/bevy_hierarchy/src/components/parent.rs b/crates/bevy_hierarchy/src/components/parent.rs index 4bd1ea40859c9..4a00e87309d08 100644 --- a/crates/bevy_hierarchy/src/components/parent.rs +++ b/crates/bevy_hierarchy/src/components/parent.rs @@ -6,7 +6,7 @@ use bevy_ecs::{ traversal::Traversal, world::{FromWorld, World}, }; -use std::ops::Deref; +use core::ops::Deref; /// Holds a reference to the parent entity of this entity. /// This component should only be present on entities that actually have a parent entity. @@ -44,7 +44,7 @@ impl Parent { /// [`Children`]: super::children::Children #[inline(always)] pub fn as_slice(&self) -> &[Entity] { - std::slice::from_ref(&self.0) + core::slice::from_ref(&self.0) } } diff --git a/crates/bevy_hierarchy/src/hierarchy.rs b/crates/bevy_hierarchy/src/hierarchy.rs index 446f3884eff24..9f090d8ce4b91 100644 --- a/crates/bevy_hierarchy/src/hierarchy.rs +++ b/crates/bevy_hierarchy/src/hierarchy.rs @@ -36,7 +36,7 @@ pub fn despawn_with_children_recursive(world: &mut World, entity: Entity) { // Should only be called by `despawn_with_children_recursive`! fn despawn_with_children_recursive_inner(world: &mut World, entity: Entity) { if let Some(mut children) = world.get_mut::(entity) { - for e in std::mem::take(&mut children.0) { + for e in core::mem::take(&mut children.0) { despawn_with_children_recursive_inner(world, e); } } diff --git a/crates/bevy_hierarchy/src/lib.rs b/crates/bevy_hierarchy/src/lib.rs index 98011ced58591..ced37bd154f64 100755 --- a/crates/bevy_hierarchy/src/lib.rs +++ b/crates/bevy_hierarchy/src/lib.rs @@ -51,6 +51,8 @@ //! [plugin]: HierarchyPlugin //! [query extension methods]: HierarchyQueryExt +extern crate alloc; + mod components; pub use components::*; diff --git a/crates/bevy_hierarchy/src/query_extension.rs b/crates/bevy_hierarchy/src/query_extension.rs index de342846a7a82..36bf790cec1bd 100644 --- a/crates/bevy_hierarchy/src/query_extension.rs +++ b/crates/bevy_hierarchy/src/query_extension.rs @@ -1,4 +1,4 @@ -use std::collections::VecDeque; +use alloc::collections::VecDeque; use bevy_ecs::{ entity::Entity, @@ -170,7 +170,7 @@ mod tests { fn descendant_iter() { let world = &mut World::new(); - let [a, b, c, d] = std::array::from_fn(|i| world.spawn(A(i)).id()); + let [a, b, c, d] = core::array::from_fn(|i| world.spawn(A(i)).id()); world.entity_mut(a).add_children(&[b, c]); world.entity_mut(c).add_children(&[d]); @@ -189,7 +189,7 @@ mod tests { fn ancestor_iter() { let world = &mut World::new(); - let [a, b, c] = std::array::from_fn(|i| world.spawn(A(i)).id()); + let [a, b, c] = core::array::from_fn(|i| world.spawn(A(i)).id()); world.entity_mut(a).add_children(&[b]); world.entity_mut(b).add_children(&[c]); diff --git a/crates/bevy_hierarchy/src/valid_parent_check_plugin.rs b/crates/bevy_hierarchy/src/valid_parent_check_plugin.rs index d03460375eeda..c24266205c5e7 100644 --- a/crates/bevy_hierarchy/src/valid_parent_check_plugin.rs +++ b/crates/bevy_hierarchy/src/valid_parent_check_plugin.rs @@ -1,12 +1,9 @@ -use std::marker::PhantomData; +use core::marker::PhantomData; -#[cfg(feature = "bevy_app")] -use crate::Parent; use bevy_ecs::prelude::*; + #[cfg(feature = "bevy_app")] -use bevy_utils::HashSet; -#[cfg(feature = "bevy_app")] -use disqualified::ShortName; +use {crate::Parent, bevy_utils::HashSet, disqualified::ShortName}; /// When enabled, runs [`check_hierarchy_component_has_valid_parent`]. /// diff --git a/crates/bevy_input/src/axis.rs b/crates/bevy_input/src/axis.rs index 21e4b7165b444..5e84b4bb4a965 100644 --- a/crates/bevy_input/src/axis.rs +++ b/crates/bevy_input/src/axis.rs @@ -2,7 +2,7 @@ use bevy_ecs::system::Resource; use bevy_utils::HashMap; -use std::hash::Hash; +use core::hash::Hash; /// Stores the position data of the input devices of type `T`. /// diff --git a/crates/bevy_input/src/button_input.rs b/crates/bevy_input/src/button_input.rs index 3a5d7fd6aee5c..b4f5921e7e7b7 100644 --- a/crates/bevy_input/src/button_input.rs +++ b/crates/bevy_input/src/button_input.rs @@ -1,12 +1,13 @@ //! The generic input type. -#[cfg(feature = "bevy_reflect")] -use bevy_ecs::reflect::ReflectResource; use bevy_ecs::system::Resource; -#[cfg(feature = "bevy_reflect")] -use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_utils::HashSet; -use std::hash::Hash; +use core::hash::Hash; +#[cfg(feature = "bevy_reflect")] +use { + bevy_ecs::reflect::ReflectResource, + bevy_reflect::{std_traits::ReflectDefault, Reflect}, +}; /// A "press-able" input of type `T`. /// diff --git a/crates/bevy_input/src/common_conditions.rs b/crates/bevy_input/src/common_conditions.rs index 4a7e4dd7bed9f..d146a16420988 100644 --- a/crates/bevy_input/src/common_conditions.rs +++ b/crates/bevy_input/src/common_conditions.rs @@ -1,6 +1,6 @@ use crate::ButtonInput; use bevy_ecs::system::Res; -use std::hash::Hash; +use core::hash::Hash; /// Stateful run condition that can be toggled via a input press using [`ButtonInput::just_pressed`]. /// diff --git a/crates/bevy_input/src/gamepad.rs b/crates/bevy_input/src/gamepad.rs index 734492df38e74..63007631cdf13 100644 --- a/crates/bevy_input/src/gamepad.rs +++ b/crates/bevy_input/src/gamepad.rs @@ -1,18 +1,18 @@ //! The gamepad input functionality. use crate::{Axis, ButtonInput, ButtonState}; -use bevy_ecs::event::{Event, EventReader, EventWriter}; -#[cfg(feature = "bevy_reflect")] -use bevy_ecs::reflect::ReflectResource; use bevy_ecs::{ change_detection::DetectChangesMut, + event::{Event, EventReader, EventWriter}, system::{Res, ResMut, Resource}, }; -#[cfg(feature = "bevy_reflect")] -use bevy_reflect::{std_traits::ReflectDefault, Reflect}; -use bevy_utils::Duration; -use bevy_utils::{tracing::info, HashMap}; +use bevy_utils::{tracing::info, Duration, HashMap}; use thiserror::Error; +#[cfg(feature = "bevy_reflect")] +use { + bevy_ecs::reflect::ReflectResource, + bevy_reflect::{std_traits::ReflectDefault, Reflect}, +}; /// Errors that occur when setting axis settings for gamepad input. #[derive(Error, Debug, PartialEq)] diff --git a/crates/bevy_input/src/keyboard.rs b/crates/bevy_input/src/keyboard.rs index 0a9109e46bdb6..223003c85c0a0 100644 --- a/crates/bevy_input/src/keyboard.rs +++ b/crates/bevy_input/src/keyboard.rs @@ -66,9 +66,9 @@ // --------- END OF W3C SHORT NOTICE --------------------------------------------------------------- use crate::{ButtonInput, ButtonState}; -use bevy_ecs::entity::Entity; use bevy_ecs::{ change_detection::DetectChangesMut, + entity::Entity, event::{Event, EventReader}, system::ResMut, }; diff --git a/crates/bevy_input/src/mouse.rs b/crates/bevy_input/src/mouse.rs index e890efccee8c6..a6fd70f013712 100644 --- a/crates/bevy_input/src/mouse.rs +++ b/crates/bevy_input/src/mouse.rs @@ -1,18 +1,18 @@ //! The mouse input functionality. use crate::{ButtonInput, ButtonState}; -use bevy_ecs::entity::Entity; -#[cfg(feature = "bevy_reflect")] -use bevy_ecs::reflect::ReflectResource; -use bevy_ecs::system::Resource; use bevy_ecs::{ change_detection::DetectChangesMut, + entity::Entity, event::{Event, EventReader}, - system::ResMut, + system::{ResMut, Resource}, }; use bevy_math::Vec2; #[cfg(feature = "bevy_reflect")] -use bevy_reflect::{std_traits::ReflectDefault, Reflect}; +use { + bevy_ecs::reflect::ReflectResource, + bevy_reflect::{std_traits::ReflectDefault, Reflect}, +}; #[cfg(all(feature = "serialize", feature = "bevy_reflect"))] use bevy_reflect::{ReflectDeserialize, ReflectSerialize}; diff --git a/crates/bevy_input/src/touch.rs b/crates/bevy_input/src/touch.rs index 89c749b7e3fce..a67d1bc2b2f68 100644 --- a/crates/bevy_input/src/touch.rs +++ b/crates/bevy_input/src/touch.rs @@ -1,8 +1,10 @@ //! The touch input functionality. -use bevy_ecs::entity::Entity; -use bevy_ecs::event::{Event, EventReader}; -use bevy_ecs::system::{ResMut, Resource}; +use bevy_ecs::{ + entity::Entity, + event::{Event, EventReader}, + system::{ResMut, Resource}, +}; use bevy_math::Vec2; #[cfg(feature = "bevy_reflect")] use bevy_reflect::Reflect; diff --git a/crates/bevy_log/src/android_tracing.rs b/crates/bevy_log/src/android_tracing.rs index fe55d6d46d845..2d7400e2e446d 100644 --- a/crates/bevy_log/src/android_tracing.rs +++ b/crates/bevy_log/src/android_tracing.rs @@ -3,7 +3,7 @@ use bevy_utils::tracing::{ span::{Attributes, Record}, Event, Id, Level, Subscriber, }; -use std::{ +use core::{ ffi::CString, fmt::{Debug, Write}, }; diff --git a/crates/bevy_log/src/lib.rs b/crates/bevy_log/src/lib.rs index 00e82e64f6667..327c9bb8f4edc 100644 --- a/crates/bevy_log/src/lib.rs +++ b/crates/bevy_log/src/lib.rs @@ -16,9 +16,7 @@ //! For more fine-tuned control over logging behavior, set up the [`LogPlugin`] or //! `DefaultPlugins` during app initialization. -use std::error::Error; -#[cfg(feature = "trace")] -use std::panic; +use core::error::Error; #[cfg(target_os = "android")] mod android_tracing; @@ -53,8 +51,6 @@ pub use tracing_subscriber; use bevy_app::{App, Plugin}; use tracing_log::LogTracer; -#[cfg(feature = "tracing-chrome")] -use tracing_subscriber::fmt::{format::DefaultFields, FormattedFields}; use tracing_subscriber::{ filter::{FromEnvError, ParseError}, prelude::*, @@ -62,7 +58,11 @@ use tracing_subscriber::{ EnvFilter, Layer, }; #[cfg(feature = "tracing-chrome")] -use {bevy_ecs::system::Resource, bevy_utils::synccell::SyncCell}; +use { + bevy_ecs::system::Resource, + bevy_utils::synccell::SyncCell, + tracing_subscriber::fmt::{format::DefaultFields, FormattedFields}, +}; /// Wrapper resource for `tracing-chrome`'s flush guard. /// When the guard is dropped the chrome log is written to file. @@ -193,8 +193,8 @@ impl Plugin for LogPlugin { fn build(&self, app: &mut App) { #[cfg(feature = "trace")] { - let old_handler = panic::take_hook(); - panic::set_hook(Box::new(move |infos| { + let old_handler = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |infos| { eprintln!("{}", tracing_error::SpanTrace::capture()); old_handler(infos); })); diff --git a/crates/bevy_macro_utils/src/fq_std.rs b/crates/bevy_macro_utils/src/fq_std.rs index 46bfdd43dab59..c350d101ad71a 100644 --- a/crates/bevy_macro_utils/src/fq_std.rs +++ b/crates/bevy_macro_utils/src/fq_std.rs @@ -39,7 +39,7 @@ use proc_macro2::TokenStream; use quote::{quote, ToTokens}; -/// Fully Qualified (FQ) short name for [`core::any::Any`] +/// Fully Qualified (FQ) short name for [`std::any::Any`] pub struct FQAny; /// Fully Qualified (FQ) short name for [`Box`] pub struct FQBox; diff --git a/crates/bevy_macro_utils/src/label.rs b/crates/bevy_macro_utils/src/label.rs index 43f393739b869..a952b4a5702bd 100644 --- a/crates/bevy_macro_utils/src/label.rs +++ b/crates/bevy_macro_utils/src/label.rs @@ -75,24 +75,24 @@ pub fn derive_label( }); where_clause.predicates.push( syn::parse2(quote! { - Self: 'static + Send + Sync + Clone + Eq + ::std::fmt::Debug + ::std::hash::Hash + Self: 'static + Send + Sync + Clone + Eq + ::core::fmt::Debug + ::core::hash::Hash }) .unwrap(), ); quote! { impl #impl_generics #trait_path for #ident #ty_generics #where_clause { fn dyn_clone(&self) -> ::std::boxed::Box { - ::std::boxed::Box::new(::std::clone::Clone::clone(self)) + ::std::boxed::Box::new(::core::clone::Clone::clone(self)) } fn as_dyn_eq(&self) -> &dyn #dyn_eq_path { self } - fn dyn_hash(&self, mut state: &mut dyn ::std::hash::Hasher) { - let ty_id = ::std::any::TypeId::of::(); - ::std::hash::Hash::hash(&ty_id, &mut state); - ::std::hash::Hash::hash(self, &mut state); + fn dyn_hash(&self, mut state: &mut dyn ::core::hash::Hasher) { + let ty_id = ::core::any::TypeId::of::(); + ::core::hash::Hash::hash(&ty_id, &mut state); + ::core::hash::Hash::hash(self, &mut state); } } } diff --git a/crates/bevy_macro_utils/src/symbol.rs b/crates/bevy_macro_utils/src/symbol.rs index f99b8dfc5cbac..4bac22a0a16b2 100644 --- a/crates/bevy_macro_utils/src/symbol.rs +++ b/crates/bevy_macro_utils/src/symbol.rs @@ -1,4 +1,4 @@ -use std::fmt::{self, Display}; +use core::fmt::{self, Display}; use syn::{Ident, Path}; /// A single named value, representable as a [string](str). diff --git a/crates/bevy_math/src/bounding/bounded2d/mod.rs b/crates/bevy_math/src/bounding/bounded2d/mod.rs index 8db21c94ca8a9..8f6812bc27247 100644 --- a/crates/bevy_math/src/bounding/bounded2d/mod.rs +++ b/crates/bevy_math/src/bounding/bounded2d/mod.rs @@ -384,7 +384,7 @@ mod aabb2d_tests { min: Vec2::new(-2.0, -2.0), max: Vec2::new(2.0, 2.0), }; - let transformed = a.transformed_by(Vec2::new(2.0, -2.0), std::f32::consts::FRAC_PI_4); + let transformed = a.transformed_by(Vec2::new(2.0, -2.0), core::f32::consts::FRAC_PI_4); let half_length = ops::hypot(2.0, 2.0); assert_eq!( transformed.min, @@ -529,7 +529,7 @@ impl BoundingVolume for BoundingCircle { #[inline(always)] fn visible_area(&self) -> f32 { - std::f32::consts::PI * self.radius() * self.radius() + core::f32::consts::PI * self.radius() * self.radius() } #[inline(always)] @@ -701,10 +701,10 @@ mod bounding_circle_tests { #[test] fn transform() { let a = BoundingCircle::new(Vec2::ONE, 5.0); - let transformed = a.transformed_by(Vec2::new(2.0, -2.0), std::f32::consts::FRAC_PI_4); + let transformed = a.transformed_by(Vec2::new(2.0, -2.0), core::f32::consts::FRAC_PI_4); assert_eq!( transformed.center, - Vec2::new(2.0, std::f32::consts::SQRT_2 - 2.0) + Vec2::new(2.0, core::f32::consts::SQRT_2 - 2.0) ); assert_eq!(transformed.radius(), 5.0); } diff --git a/crates/bevy_math/src/bounding/bounded2d/primitive_impls.rs b/crates/bevy_math/src/bounding/bounded2d/primitive_impls.rs index f3cccbfb0fd1a..1d6b67b0d6aa7 100644 --- a/crates/bevy_math/src/bounding/bounded2d/primitive_impls.rs +++ b/crates/bevy_math/src/bounding/bounded2d/primitive_impls.rs @@ -9,7 +9,7 @@ use crate::{ }, Dir2, Isometry2d, Mat2, Rot2, Vec2, }; -use std::f32::consts::{FRAC_PI_2, PI, TAU}; +use core::f32::consts::{FRAC_PI_2, PI, TAU}; use smallvec::SmallVec; @@ -397,7 +397,7 @@ impl Bounded2d for Capsule2d { #[cfg(test)] mod tests { - use std::f32::consts::{FRAC_PI_2, FRAC_PI_3, FRAC_PI_4, FRAC_PI_6, TAU}; + use core::f32::consts::{FRAC_PI_2, FRAC_PI_3, FRAC_PI_4, FRAC_PI_6, TAU}; use approx::assert_abs_diff_eq; use glam::Vec2; @@ -866,7 +866,7 @@ mod tests { let bounding_circle = polyline.bounding_circle(isometry); assert_eq!(bounding_circle.center, translation); - assert_eq!(bounding_circle.radius(), std::f32::consts::SQRT_2); + assert_eq!(bounding_circle.radius(), core::f32::consts::SQRT_2); } #[test] @@ -939,7 +939,7 @@ mod tests { let bounding_circle = polygon.bounding_circle(isometry); assert_eq!(bounding_circle.center, translation); - assert_eq!(bounding_circle.radius(), std::f32::consts::SQRT_2); + assert_eq!(bounding_circle.radius(), core::f32::consts::SQRT_2); } #[test] diff --git a/crates/bevy_math/src/bounding/bounded3d/extrusion.rs b/crates/bevy_math/src/bounding/bounded3d/extrusion.rs index 631d33790cca8..8784a3286ecfd 100644 --- a/crates/bevy_math/src/bounding/bounded3d/extrusion.rs +++ b/crates/bevy_math/src/bounding/bounded3d/extrusion.rs @@ -1,13 +1,16 @@ -use std::f32::consts::FRAC_PI_2; +use core::f32::consts::FRAC_PI_2; use glam::{Vec2, Vec3A, Vec3Swizzles}; -use crate::bounding::{BoundingCircle, BoundingVolume}; -use crate::primitives::{ - BoxedPolygon, BoxedPolyline2d, Capsule2d, Cuboid, Cylinder, Ellipse, Extrusion, Line2d, - Polygon, Polyline2d, Primitive2d, Rectangle, RegularPolygon, Segment2d, Triangle2d, +use crate::{ + bounding::{BoundingCircle, BoundingVolume}, + ops, + primitives::{ + BoxedPolygon, BoxedPolyline2d, Capsule2d, Cuboid, Cylinder, Ellipse, Extrusion, Line2d, + Polygon, Polyline2d, Primitive2d, Rectangle, RegularPolygon, Segment2d, Triangle2d, + }, + Isometry2d, Isometry3d, Quat, Rot2, }; -use crate::{ops, Isometry2d, Isometry3d, Quat, Rot2}; use crate::{bounding::Bounded2d, primitives::Circle}; @@ -240,7 +243,7 @@ pub trait BoundedExtrusion: Primitive2d + Bounded2d { #[cfg(test)] mod tests { - use std::f32::consts::FRAC_PI_4; + use core::f32::consts::FRAC_PI_4; use glam::{EulerRot, Quat, Vec2, Vec3, Vec3A}; diff --git a/crates/bevy_math/src/bounding/bounded3d/mod.rs b/crates/bevy_math/src/bounding/bounded3d/mod.rs index 60822fa3fe4cd..81edbe8a57d4f 100644 --- a/crates/bevy_math/src/bounding/bounded3d/mod.rs +++ b/crates/bevy_math/src/bounding/bounded3d/mod.rs @@ -387,7 +387,7 @@ mod aabb3d_tests { }; let transformed = a.transformed_by( Vec3A::new(2.0, -2.0, 4.0), - Quat::from_rotation_z(std::f32::consts::FRAC_PI_4), + Quat::from_rotation_z(core::f32::consts::FRAC_PI_4), ); let half_length = ops::hypot(2.0, 2.0); assert_eq!( @@ -547,7 +547,7 @@ impl BoundingVolume for BoundingSphere { #[inline(always)] fn visible_area(&self) -> f32 { - 2. * std::f32::consts::PI * self.radius() * self.radius() + 2. * core::f32::consts::PI * self.radius() * self.radius() } #[inline(always)] @@ -733,11 +733,11 @@ mod bounding_sphere_tests { let a = BoundingSphere::new(Vec3::ONE, 5.0); let transformed = a.transformed_by( Vec3::new(2.0, -2.0, 4.0), - Quat::from_rotation_z(std::f32::consts::FRAC_PI_4), + Quat::from_rotation_z(core::f32::consts::FRAC_PI_4), ); assert_relative_eq!( transformed.center, - Vec3A::new(2.0, std::f32::consts::SQRT_2 - 2.0, 5.0) + Vec3A::new(2.0, core::f32::consts::SQRT_2 - 2.0, 5.0) ); assert_eq!(transformed.radius(), 5.0); } diff --git a/crates/bevy_math/src/bounding/bounded3d/primitive_impls.rs b/crates/bevy_math/src/bounding/bounded3d/primitive_impls.rs index 8827b0f253b61..bb6a6a5a12c37 100644 --- a/crates/bevy_math/src/bounding/bounded3d/primitive_impls.rs +++ b/crates/bevy_math/src/bounding/bounded3d/primitive_impls.rs @@ -475,7 +475,7 @@ mod tests { let aabb = cuboid.aabb_3d(Isometry3d::new( translation, - Quat::from_rotation_z(std::f32::consts::FRAC_PI_4), + Quat::from_rotation_z(core::f32::consts::FRAC_PI_4), )); let expected_half_size = Vec3A::new(1.0606601, 1.0606601, 0.5); assert_eq!(aabb.min, Vec3A::from(translation) - expected_half_size); diff --git a/crates/bevy_math/src/common_traits.rs b/crates/bevy_math/src/common_traits.rs index 525d8e403524e..12bea91461e57 100644 --- a/crates/bevy_math/src/common_traits.rs +++ b/crates/bevy_math/src/common_traits.rs @@ -1,8 +1,10 @@ //! This module contains abstract mathematical traits shared by types used in `bevy_math`. use crate::{ops, Dir2, Dir3, Dir3A, Quat, Rot2, Vec2, Vec3, Vec3A, Vec4}; -use std::fmt::Debug; -use std::ops::{Add, Div, Mul, Neg, Sub}; +use core::{ + fmt::Debug, + ops::{Add, Div, Mul, Neg, Sub}, +}; /// A type that supports the mathematical operations of a real vector space, irrespective of dimension. /// In particular, this means that the implementing type supports: diff --git a/crates/bevy_math/src/cubic_splines.rs b/crates/bevy_math/src/cubic_splines.rs index b99c035c8e71f..63d5c03cdfe4c 100644 --- a/crates/bevy_math/src/cubic_splines.rs +++ b/crates/bevy_math/src/cubic_splines.rs @@ -1,6 +1,6 @@ //! Provides types for building cubic splines for rendering curves and use with animation easing. -use std::{fmt::Debug, iter::once}; +use core::{fmt::Debug, iter::once}; use crate::{ops::FloatPow, Vec2, VectorSpace}; @@ -701,10 +701,10 @@ impl CubicNurbs

{ } let last_knots_value = control_points - 3; Some( - std::iter::repeat(0.0) + core::iter::repeat(0.0) .take(4) .chain((1..last_knots_value).map(|v| v as f32)) - .chain(std::iter::repeat(last_knots_value as f32).take(4)) + .chain(core::iter::repeat(last_knots_value as f32).take(4)) .collect(), ) } @@ -1667,7 +1667,7 @@ mod tests { /// Test that a nurbs curve can approximate a portion of a circle. #[test] fn nurbs_circular_arc() { - use std::f32::consts::FRAC_PI_2; + use core::f32::consts::FRAC_PI_2; const EPSILON: f32 = 0.0000001; // The following NURBS parameters were determined by constraining the first two diff --git a/crates/bevy_math/src/curve/interval.rs b/crates/bevy_math/src/curve/interval.rs index e3852ad06ef60..ae651b52cfb77 100644 --- a/crates/bevy_math/src/curve/interval.rs +++ b/crates/bevy_math/src/curve/interval.rs @@ -1,10 +1,10 @@ //! The [`Interval`] type for nonempty intervals used by the [`Curve`](super::Curve) trait. -use itertools::Either; -use std::{ +use core::{ cmp::{max_by, min_by}, ops::RangeInclusive, }; +use itertools::Either; use thiserror::Error; #[cfg(feature = "bevy_reflect")] diff --git a/crates/bevy_math/src/curve/mod.rs b/crates/bevy_math/src/curve/mod.rs index dfadf3db4b620..4d94e59c37ef9 100644 --- a/crates/bevy_math/src/curve/mod.rs +++ b/crates/bevy_math/src/curve/mod.rs @@ -9,9 +9,9 @@ pub use interval::{interval, Interval}; use itertools::Itertools; use crate::StableInterpolate; +use core::{marker::PhantomData, ops::Deref}; use cores::{EvenCore, EvenCoreError, UnevenCore, UnevenCoreError}; use interval::InvalidIntervalError; -use std::{marker::PhantomData, ops::Deref}; use thiserror::Error; #[cfg(feature = "bevy_reflect")] @@ -1020,7 +1020,7 @@ mod tests { use super::*; use crate::{ops, Quat}; use approx::{assert_abs_diff_eq, AbsDiffEq}; - use std::f32::consts::TAU; + use core::f32::consts::TAU; #[test] fn curve_can_be_made_into_an_object() { diff --git a/crates/bevy_math/src/direction.rs b/crates/bevy_math/src/direction.rs index 8f4cf7d9eabab..fe796c64602b4 100644 --- a/crates/bevy_math/src/direction.rs +++ b/crates/bevy_math/src/direction.rs @@ -36,8 +36,8 @@ impl InvalidDirectionError { } } -impl std::fmt::Display for InvalidDirectionError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Display for InvalidDirectionError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!( f, "Direction can not be zero (or very close to zero), or non-finite." @@ -278,35 +278,35 @@ impl From for Vec2 { } } -impl std::ops::Deref for Dir2 { +impl core::ops::Deref for Dir2 { type Target = Vec2; fn deref(&self) -> &Self::Target { &self.0 } } -impl std::ops::Neg for Dir2 { +impl core::ops::Neg for Dir2 { type Output = Self; fn neg(self) -> Self::Output { Self(-self.0) } } -impl std::ops::Mul for Dir2 { +impl core::ops::Mul for Dir2 { type Output = Vec2; fn mul(self, rhs: f32) -> Self::Output { self.0 * rhs } } -impl std::ops::Mul for f32 { +impl core::ops::Mul for f32 { type Output = Vec2; fn mul(self, rhs: Dir2) -> Self::Output { self * rhs.0 } } -impl std::ops::Mul for Rot2 { +impl core::ops::Mul for Rot2 { type Output = Dir2; /// Rotates the [`Dir2`] using a [`Rot2`]. @@ -540,35 +540,35 @@ impl From for Vec3 { } } -impl std::ops::Deref for Dir3 { +impl core::ops::Deref for Dir3 { type Target = Vec3; fn deref(&self) -> &Self::Target { &self.0 } } -impl std::ops::Neg for Dir3 { +impl core::ops::Neg for Dir3 { type Output = Self; fn neg(self) -> Self::Output { Self(-self.0) } } -impl std::ops::Mul for Dir3 { +impl core::ops::Mul for Dir3 { type Output = Vec3; fn mul(self, rhs: f32) -> Self::Output { self.0 * rhs } } -impl std::ops::Mul for f32 { +impl core::ops::Mul for f32 { type Output = Vec3; fn mul(self, rhs: Dir3) -> Self::Output { self * rhs.0 } } -impl std::ops::Mul for Quat { +impl core::ops::Mul for Quat { type Output = Dir3; /// Rotates the [`Dir3`] using a [`Quat`]. @@ -781,35 +781,35 @@ impl From for Vec3A { } } -impl std::ops::Deref for Dir3A { +impl core::ops::Deref for Dir3A { type Target = Vec3A; fn deref(&self) -> &Self::Target { &self.0 } } -impl std::ops::Neg for Dir3A { +impl core::ops::Neg for Dir3A { type Output = Self; fn neg(self) -> Self::Output { Self(-self.0) } } -impl std::ops::Mul for Dir3A { +impl core::ops::Mul for Dir3A { type Output = Vec3A; fn mul(self, rhs: f32) -> Self::Output { self.0 * rhs } } -impl std::ops::Mul for f32 { +impl core::ops::Mul for f32 { type Output = Vec3A; fn mul(self, rhs: Dir3A) -> Self::Output { self * rhs.0 } } -impl std::ops::Mul for Quat { +impl core::ops::Mul for Quat { type Output = Dir3A; /// Rotates the [`Dir3A`] using a [`Quat`]. @@ -963,7 +963,7 @@ mod tests { // Test rotation assert!( - (Quat::from_rotation_z(std::f32::consts::FRAC_PI_2) * Dir3::X) + (Quat::from_rotation_z(core::f32::consts::FRAC_PI_2) * Dir3::X) .abs_diff_eq(Vec3::Y, 10e-6) ); } @@ -1034,7 +1034,7 @@ mod tests { // Test rotation assert!( - (Quat::from_rotation_z(std::f32::consts::FRAC_PI_2) * Dir3A::X) + (Quat::from_rotation_z(core::f32::consts::FRAC_PI_2) * Dir3A::X) .abs_diff_eq(Vec3A::Y, 10e-6) ); } diff --git a/crates/bevy_math/src/float_ord.rs b/crates/bevy_math/src/float_ord.rs index 63360449258d3..e53a083f773e6 100644 --- a/crates/bevy_math/src/float_ord.rs +++ b/crates/bevy_math/src/float_ord.rs @@ -1,4 +1,4 @@ -use std::{ +use core::{ cmp::Ordering, hash::{Hash, Hasher}, ops::Neg, diff --git a/crates/bevy_math/src/isometry.rs b/crates/bevy_math/src/isometry.rs index a6505eb846c5d..356b78738db05 100644 --- a/crates/bevy_math/src/isometry.rs +++ b/crates/bevy_math/src/isometry.rs @@ -1,7 +1,7 @@ //! Isometry types for expressing rigid motions in two and three dimensions. use crate::{Affine2, Affine3, Affine3A, Dir2, Dir3, Mat3, Mat3A, Quat, Rot2, Vec2, Vec3, Vec3A}; -use std::ops::Mul; +use core::ops::Mul; #[cfg(feature = "approx")] use approx::{AbsDiffEq, RelativeEq, UlpsEq}; @@ -286,7 +286,7 @@ impl UlpsEq for Isometry2d { /// /// ``` /// # use bevy_math::{Isometry3d, Quat, Vec3}; -/// # use core::f32::consts::FRAC_PI_2; +/// # use std::f32::consts::FRAC_PI_2; /// # /// let iso = Isometry3d::new(Vec3::new(2.0, 1.0, 3.0), Quat::from_rotation_z(FRAC_PI_2)); /// ``` @@ -295,7 +295,7 @@ impl UlpsEq for Isometry2d { /// /// ``` /// # use bevy_math::{Isometry3d, Quat, Vec3}; -/// # use core::f32::consts::FRAC_PI_2; +/// # use std::f32::consts::FRAC_PI_2; /// # /// let iso1 = Isometry3d::from_translation(Vec3::new(2.0, 1.0, 3.0)); /// let iso2 = Isometry3d::from_rotation(Quat::from_rotation_z(FRAC_PI_2)); @@ -306,7 +306,7 @@ impl UlpsEq for Isometry2d { /// ``` /// # use approx::assert_relative_eq; /// # use bevy_math::{Isometry3d, Quat, Vec3}; -/// # use core::f32::consts::FRAC_PI_2; +/// # use std::f32::consts::FRAC_PI_2; /// # /// let iso = Isometry3d::new(Vec3::new(2.0, 1.0, 3.0), Quat::from_rotation_z(FRAC_PI_2)); /// let point = Vec3::new(4.0, 4.0, 4.0); @@ -322,7 +322,7 @@ impl UlpsEq for Isometry2d { /// /// ``` /// # use bevy_math::{Isometry3d, Quat, Vec3}; -/// # use core::f32::consts::FRAC_PI_2; +/// # use std::f32::consts::FRAC_PI_2; /// # /// # let iso = Isometry3d::new(Vec3::new(2.0, 1.0, 3.0), Quat::from_rotation_z(FRAC_PI_2)); /// # let iso1 = Isometry3d::from_translation(Vec3::new(2.0, 1.0, 3.0)); @@ -336,7 +336,7 @@ impl UlpsEq for Isometry2d { /// /// ``` /// # use bevy_math::{Isometry3d, Quat, Vec3}; -/// # use core::f32::consts::FRAC_PI_2; +/// # use std::f32::consts::FRAC_PI_2; /// # /// let sphere_iso = Isometry3d::from_translation(Vec3::new(2.0, 1.0, 3.0)); /// let cuboid_iso = Isometry3d::from_rotation(Quat::from_rotation_z(FRAC_PI_2)); @@ -558,7 +558,7 @@ mod tests { use super::*; use crate::{vec2, vec3, vec3a}; use approx::assert_abs_diff_eq; - use std::f32::consts::{FRAC_PI_2, FRAC_PI_3}; + use core::f32::consts::{FRAC_PI_2, FRAC_PI_3}; #[test] fn mul_2d() { diff --git a/crates/bevy_math/src/lib.rs b/crates/bevy_math/src/lib.rs index 1020cb114cc07..984a068ff82a4 100644 --- a/crates/bevy_math/src/lib.rs +++ b/crates/bevy_math/src/lib.rs @@ -41,15 +41,14 @@ pub use ray::{Ray2d, Ray3d}; pub use rects::*; pub use rotation2d::Rot2; #[cfg(feature = "rand")] -pub use sampling::{FromRng, ShapeSample}; +pub use sampling::FromRng; +#[cfg(feature = "rand")] +pub use sampling::ShapeSample; /// The math prelude. /// /// This includes the most common types in this crate, re-exported for your convenience. pub mod prelude { - #[doc(hidden)] - #[cfg(feature = "rand")] - pub use crate::sampling::{FromRng, ShapeSample}; #[doc(hidden)] pub use crate::{ cubic_splines::{ @@ -65,6 +64,10 @@ pub mod prelude { Isometry3d, Mat2, Mat3, Mat4, Quat, Ray2d, Ray3d, Rect, Rot2, StableInterpolate, URect, UVec2, UVec3, UVec4, Vec2, Vec2Swizzles, Vec3, Vec3Swizzles, Vec4, Vec4Swizzles, }; + + #[doc(hidden)] + #[cfg(feature = "rand")] + pub use crate::sampling::{FromRng, ShapeSample}; } pub use glam::*; diff --git a/crates/bevy_math/src/primitives/dim2.rs b/crates/bevy_math/src/primitives/dim2.rs index f43541809b970..6e44d8bc045ec 100644 --- a/crates/bevy_math/src/primitives/dim2.rs +++ b/crates/bevy_math/src/primitives/dim2.rs @@ -1,4 +1,4 @@ -use std::f32::consts::{FRAC_1_SQRT_2, FRAC_PI_2, FRAC_PI_3, PI}; +use core::f32::consts::{FRAC_1_SQRT_2, FRAC_PI_2, FRAC_PI_3, PI}; use super::{Measured2d, Primitive2d, WindingOrder}; use crate::{ @@ -536,7 +536,7 @@ impl CircularSegment { #[cfg(test)] mod arc_tests { - use std::f32::consts::FRAC_PI_4; + use core::f32::consts::FRAC_PI_4; use approx::assert_abs_diff_eq; @@ -1041,7 +1041,7 @@ impl Rhombus { /// Create a new `Rhombus` from a given inradius with all inner angles equal. #[inline(always)] pub fn from_inradius(inradius: f32) -> Self { - let half_diagonal = inradius * 2.0 / std::f32::consts::SQRT_2; + let half_diagonal = inradius * 2.0 / core::f32::consts::SQRT_2; Self { half_diagonals: Vec2::new(half_diagonal, half_diagonal), } @@ -1749,7 +1749,7 @@ impl RegularPolygon { pub fn vertices(self, rotation: f32) -> impl IntoIterator { // Add pi/2 so that the polygon has a vertex at the top (sin is 1.0 and cos is 0.0) let start_angle = rotation + FRAC_PI_2; - let step = std::f32::consts::TAU / self.sides as f32; + let step = core::f32::consts::TAU / self.sides as f32; (0..self.sides).map(move |i| { let theta = start_angle + i as f32 * step; @@ -1915,7 +1915,7 @@ mod tests { assert_eq!(rhombus.side(), 0.0, "incorrect side"); assert_eq!(rhombus.inradius(), 0.0, "incorrect inradius"); assert_eq!(rhombus.circumradius(), 0.0, "incorrect circumradius"); - let rhombus = Rhombus::from_side(std::f32::consts::SQRT_2); + let rhombus = Rhombus::from_side(core::f32::consts::SQRT_2); assert_abs_diff_eq!(rhombus.half_diagonals, Vec2::new(1.0, 1.0)); assert_abs_diff_eq!( rhombus.half_diagonals, @@ -2069,7 +2069,7 @@ mod tests { assert!((vertices.next().unwrap() - Vec2::Y).length() < 1e-7); // Rotate by 45 degrees, forming an axis-aligned square - let mut rotated_vertices = polygon.vertices(std::f32::consts::FRAC_PI_4).into_iter(); + let mut rotated_vertices = polygon.vertices(core::f32::consts::FRAC_PI_4).into_iter(); // Distance from the origin to the middle of a side, derived using Pythagorean theorem let side_sistance = FRAC_1_SQRT_2; diff --git a/crates/bevy_math/src/primitives/dim3.rs b/crates/bevy_math/src/primitives/dim3.rs index 7ee6a82d6f241..d3761455d8cf2 100644 --- a/crates/bevy_math/src/primitives/dim3.rs +++ b/crates/bevy_math/src/primitives/dim3.rs @@ -1,4 +1,4 @@ -use std::f32::consts::{FRAC_PI_3, PI}; +use core::f32::consts::{FRAC_PI_3, PI}; use super::{Circle, Measured2d, Measured3d, Primitive2d, Primitive3d}; use crate::{ops, ops::FloatPow, Dir3, InvalidDirectionError, Isometry3d, Mat3, Vec2, Vec3}; @@ -187,7 +187,7 @@ impl InfinitePlane3d { #[inline(always)] pub fn new>(normal: T) -> Self where - >::Error: std::fmt::Debug, + >::Error: core::fmt::Debug, { Self { normal: normal @@ -926,9 +926,9 @@ impl Torus { } match self.major_radius.partial_cmp(&self.minor_radius).unwrap() { - std::cmp::Ordering::Greater => TorusKind::Ring, - std::cmp::Ordering::Equal => TorusKind::Horn, - std::cmp::Ordering::Less => TorusKind::Spindle, + core::cmp::Ordering::Greater => TorusKind::Ring, + core::cmp::Ordering::Equal => TorusKind::Horn, + core::cmp::Ordering::Less => TorusKind::Spindle, } } } @@ -1320,7 +1320,7 @@ mod tests { // Test rotation assert!( - (Quat::from_rotation_z(std::f32::consts::FRAC_PI_2) * Dir3::X) + (Quat::from_rotation_z(core::f32::consts::FRAC_PI_2) * Dir3::X) .abs_diff_eq(Vec3::Y, 10e-6) ); } diff --git a/crates/bevy_math/src/primitives/serde.rs b/crates/bevy_math/src/primitives/serde.rs index 79abb778cd39d..bdbf72f69e737 100644 --- a/crates/bevy_math/src/primitives/serde.rs +++ b/crates/bevy_math/src/primitives/serde.rs @@ -4,12 +4,12 @@ //! pub(crate) mod array { + use core::marker::PhantomData; use serde::{ de::{SeqAccess, Visitor}, ser::SerializeTuple, Deserialize, Deserializer, Serialize, Serializer, }; - use std::marker::PhantomData; pub fn serialize( data: &[T; N], @@ -30,7 +30,7 @@ pub(crate) mod array { { type Value = [T; N]; - fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result { formatter.write_str(&format!("an array of length {}", N)) } diff --git a/crates/bevy_math/src/rotation2d.rs b/crates/bevy_math/src/rotation2d.rs index 02f6d3411794e..5f4d7565c93c0 100644 --- a/crates/bevy_math/src/rotation2d.rs +++ b/crates/bevy_math/src/rotation2d.rs @@ -1,4 +1,4 @@ -use std::f32::consts::TAU; +use core::f32::consts::TAU; use glam::FloatExt; @@ -445,7 +445,7 @@ impl From for Mat2 { } } -impl std::ops::Mul for Rot2 { +impl core::ops::Mul for Rot2 { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { @@ -456,13 +456,13 @@ impl std::ops::Mul for Rot2 { } } -impl std::ops::MulAssign for Rot2 { +impl core::ops::MulAssign for Rot2 { fn mul_assign(&mut self, rhs: Self) { *self = *self * rhs; } } -impl std::ops::Mul for Rot2 { +impl core::ops::Mul for Rot2 { type Output = Vec2; /// Rotates a [`Vec2`] by a [`Rot2`]. @@ -509,7 +509,7 @@ impl approx::UlpsEq for Rot2 { #[cfg(test)] mod tests { - use std::f32::consts::FRAC_PI_2; + use core::f32::consts::FRAC_PI_2; use approx::assert_relative_eq; @@ -572,7 +572,7 @@ mod tests { // This should be equivalent to the above assert_relative_eq!( rotation2.angle_between(rotation1), - std::f32::consts::FRAC_PI_4 + core::f32::consts::FRAC_PI_4 ); } diff --git a/crates/bevy_math/src/sampling/shape_sampling.rs b/crates/bevy_math/src/sampling/shape_sampling.rs index 10d99f8a8b16d..7e8c672a6bf7c 100644 --- a/crates/bevy_math/src/sampling/shape_sampling.rs +++ b/crates/bevy_math/src/sampling/shape_sampling.rs @@ -38,7 +38,7 @@ //! //! In any case, the [`Rng`] used as the source of randomness must be provided explicitly. -use std::f32::consts::{PI, TAU}; +use core::f32::consts::{PI, TAU}; use crate::{ops, primitives::*, NormedVectorSpace, Vec2, Vec3}; use rand::{ diff --git a/crates/bevy_math/src/sampling/standard.rs b/crates/bevy_math/src/sampling/standard.rs index 9c5ff1fa3dea4..6750d5c6d5fac 100644 --- a/crates/bevy_math/src/sampling/standard.rs +++ b/crates/bevy_math/src/sampling/standard.rs @@ -21,7 +21,7 @@ //! let many_random_directions: Vec = rng.sample_iter(Standard).take(5).collect(); //! ``` -use std::f32::consts::TAU; +use core::f32::consts::TAU; use crate::{ primitives::{Circle, Sphere}, diff --git a/crates/bevy_mikktspace/src/generated.rs b/crates/bevy_mikktspace/src/generated.rs index 2589e3930b1a4..b4bf42275a66c 100644 --- a/crates/bevy_mikktspace/src/generated.rs +++ b/crates/bevy_mikktspace/src/generated.rs @@ -45,7 +45,7 @@ unsafe_code )] -use std::ptr::{self, null_mut}; +use core::ptr::{self, null_mut}; use glam::Vec3; diff --git a/crates/bevy_pbr/src/bundle.rs b/crates/bevy_pbr/src/bundle.rs index 52c7c64384068..9561b00bab85e 100644 --- a/crates/bevy_pbr/src/bundle.rs +++ b/crates/bevy_pbr/src/bundle.rs @@ -4,10 +4,13 @@ use crate::{ }; use bevy_asset::Handle; use bevy_derive::{Deref, DerefMut}; -use bevy_ecs::entity::{Entity, EntityHashMap}; -use bevy_ecs::{bundle::Bundle, component::Component, reflect::ReflectComponent}; -use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; +use bevy_ecs::{ + bundle::Bundle, + component::Component, + entity::{Entity, EntityHashMap}, + reflect::ReflectComponent, +}; +use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_render::{ mesh::Mesh, primitives::{CascadesFrusta, CubemapFrusta, Frustum}, diff --git a/crates/bevy_pbr/src/cluster/assign.rs b/crates/bevy_pbr/src/cluster/assign.rs index 8e358a29b97f2..a45ff03c5e534 100644 --- a/crates/bevy_pbr/src/cluster/assign.rs +++ b/crates/bevy_pbr/src/cluster/assign.rs @@ -360,7 +360,7 @@ pub(crate) fn assign_objects_to_clusters( // initialize empty cluster bounding spheres cluster_aabb_spheres.clear(); - cluster_aabb_spheres.extend(std::iter::repeat(None).take(cluster_count)); + cluster_aabb_spheres.extend(core::iter::repeat(None).take(cluster_count)); // Calculate the x/y/z cluster frustum planes in view space let mut x_planes = Vec::with_capacity(clusters.dimensions.x as usize + 1); diff --git a/crates/bevy_pbr/src/cluster/mod.rs b/crates/bevy_pbr/src/cluster/mod.rs index add1b38850b54..f21781e147232 100644 --- a/crates/bevy_pbr/src/cluster/mod.rs +++ b/crates/bevy_pbr/src/cluster/mod.rs @@ -1,6 +1,6 @@ //! Spatial clustering of objects, currently just point and spot lights. -use std::num::NonZero; +use core::num::NonZero; use bevy_core_pipeline::core_3d::Camera3d; use bevy_ecs::{ @@ -507,7 +507,7 @@ impl Default for GpuClusterableObjectsUniform { pub(crate) fn clusterable_object_order( (entity_1, shadows_enabled_1, is_spot_light_1): (&Entity, &bool, &bool), (entity_2, shadows_enabled_2, is_spot_light_2): (&Entity, &bool, &bool), -) -> std::cmp::Ordering { +) -> core::cmp::Ordering { is_spot_light_1 .cmp(is_spot_light_2) // pointlights before spot lights .then_with(|| shadows_enabled_2.cmp(shadows_enabled_1)) // shadow casters before non-casters diff --git a/crates/bevy_pbr/src/deferred/mod.rs b/crates/bevy_pbr/src/deferred/mod.rs index 10d8a57962f2b..c70308eb761ae 100644 --- a/crates/bevy_pbr/src/deferred/mod.rs +++ b/crates/bevy_pbr/src/deferred/mod.rs @@ -20,8 +20,7 @@ use bevy_render::{ ComponentUniforms, ExtractComponent, ExtractComponentPlugin, UniformComponentPlugin, }, render_graph::{NodeRunError, RenderGraphApp, RenderGraphContext, ViewNode, ViewNodeRunner}, - render_resource::binding_types::uniform_buffer, - render_resource::*, + render_resource::{binding_types::uniform_buffer, *}, renderer::{RenderContext, RenderDevice}, texture::BevyDefault, view::{ExtractedView, ViewTarget, ViewUniformOffset}, diff --git a/crates/bevy_pbr/src/fog.rs b/crates/bevy_pbr/src/fog.rs index 5f4738d619bea..c2ff30bb56411 100644 --- a/crates/bevy_pbr/src/fog.rs +++ b/crates/bevy_pbr/src/fog.rs @@ -409,7 +409,7 @@ impl FogFalloff { extinction_color: Color, inscattering_color: Color, ) -> FogFalloff { - use std::f32::consts::E; + use core::f32::consts::E; let [r_e, g_e, b_e, a_e] = LinearRgba::from(extinction_color).to_f32_array(); let [r_i, g_i, b_i, a_i] = LinearRgba::from(inscattering_color).to_f32_array(); diff --git a/crates/bevy_pbr/src/lib.rs b/crates/bevy_pbr/src/lib.rs index 59cdf3e33bb88..feb6b3d4fccf0 100644 --- a/crates/bevy_pbr/src/lib.rs +++ b/crates/bevy_pbr/src/lib.rs @@ -7,6 +7,8 @@ html_favicon_url = "https://bevyengine.org/assets/icon.png" )] +extern crate alloc; + #[cfg(feature = "meshlet")] mod meshlet; pub mod wireframe; @@ -41,7 +43,7 @@ mod ssr; mod volumetric_fog; use bevy_color::{Color, LinearRgba}; -use std::marker::PhantomData; +use core::marker::PhantomData; pub use bundle::*; pub use cluster::*; diff --git a/crates/bevy_pbr/src/light/mod.rs b/crates/bevy_pbr/src/light/mod.rs index 28b463041192e..991ca40ba1f1d 100644 --- a/crates/bevy_pbr/src/light/mod.rs +++ b/crates/bevy_pbr/src/light/mod.rs @@ -1,7 +1,6 @@ -use std::ops::DerefMut; +use core::ops::DerefMut; -use bevy_ecs::entity::EntityHashMap; -use bevy_ecs::prelude::*; +use bevy_ecs::{entity::EntityHashMap, prelude::*}; use bevy_math::{ops, Mat4, Vec3A, Vec4}; use bevy_reflect::prelude::*; use bevy_render::{ @@ -527,7 +526,7 @@ pub enum SimulationLightSystems { pub(crate) fn directional_light_order( (entity_1, volumetric_1, shadows_enabled_1): (&Entity, &bool, &bool), (entity_2, volumetric_2, shadows_enabled_2): (&Entity, &bool, &bool), -) -> std::cmp::Ordering { +) -> core::cmp::Ordering { volumetric_2 .cmp(volumetric_1) // volumetric before shadows .then_with(|| shadows_enabled_2.cmp(shadows_enabled_1)) // shadow casters before non-casters @@ -596,7 +595,7 @@ pub fn update_point_light_frusta( } let clip_from_view = Mat4::perspective_infinite_reverse_rh( - std::f32::consts::FRAC_PI_2, + core::f32::consts::FRAC_PI_2, 1.0, point_light.shadow_map_near_z, ); @@ -824,7 +823,7 @@ pub fn check_dir_light_mesh_visibility( // Defer marking view visibility so this system can run in parallel with check_point_light_mesh_visibility // TODO: use resource to avoid unnecessary memory alloc - let mut defer_queue = std::mem::take(defer_visible_entities_queue.deref_mut()); + let mut defer_queue = core::mem::take(defer_visible_entities_queue.deref_mut()); commands.queue(move |world: &mut World| { let mut query = world.query::<&mut ViewVisibility>(); for entities in defer_queue.iter_mut() { diff --git a/crates/bevy_pbr/src/light/spot_light.rs b/crates/bevy_pbr/src/light/spot_light.rs index f2e595fbf8c49..70ec1d607e2a5 100644 --- a/crates/bevy_pbr/src/light/spot_light.rs +++ b/crates/bevy_pbr/src/light/spot_light.rs @@ -116,7 +116,7 @@ impl Default for SpotLight { shadow_normal_bias: Self::DEFAULT_SHADOW_NORMAL_BIAS, shadow_map_near_z: Self::DEFAULT_SHADOW_MAP_NEAR_Z, inner_angle: 0.0, - outer_angle: std::f32::consts::FRAC_PI_4, + outer_angle: core::f32::consts::FRAC_PI_4, } } } diff --git a/crates/bevy_pbr/src/light_probe/environment_map.rs b/crates/bevy_pbr/src/light_probe/environment_map.rs index a9be284fba0c0..c366d02b59bb6 100644 --- a/crates/bevy_pbr/src/light_probe/environment_map.rs +++ b/crates/bevy_pbr/src/light_probe/environment_map.rs @@ -52,8 +52,7 @@ use bevy_ecs::{ system::lifetimeless::Read, }; use bevy_math::Quat; -use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; +use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_render::{ extract_instances::ExtractInstance, prelude::SpatialBundle, @@ -67,8 +66,7 @@ use bevy_render::{ texture::{FallbackImage, GpuImage, Image}, }; -use std::num::NonZero; -use std::ops::Deref; +use core::{num::NonZero, ops::Deref}; use crate::{ add_cubemap_texture_view, binding_arrays_are_usable, EnvironmentMapUniform, LightProbe, diff --git a/crates/bevy_pbr/src/light_probe/irradiance_volume.rs b/crates/bevy_pbr/src/light_probe/irradiance_volume.rs index 34f9f902a6ef1..f43d84d4e7c39 100644 --- a/crates/bevy_pbr/src/light_probe/irradiance_volume.rs +++ b/crates/bevy_pbr/src/light_probe/irradiance_volume.rs @@ -142,11 +142,10 @@ use bevy_render::{ renderer::RenderDevice, texture::{FallbackImage, GpuImage, Image}, }; -use std::{num::NonZero, ops::Deref}; +use core::{num::NonZero, ops::Deref}; use bevy_asset::{AssetId, Handle}; -use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; +use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use crate::{ add_cubemap_texture_view, binding_arrays_are_usable, RenderViewLightProbes, diff --git a/crates/bevy_pbr/src/light_probe/mod.rs b/crates/bevy_pbr/src/light_probe/mod.rs index 7d84a28b19893..69e29dfb34ec0 100644 --- a/crates/bevy_pbr/src/light_probe/mod.rs +++ b/crates/bevy_pbr/src/light_probe/mod.rs @@ -28,8 +28,7 @@ use bevy_render::{ use bevy_transform::{components::Transform, prelude::GlobalTransform}; use bevy_utils::{tracing::error, HashMap}; -use std::hash::Hash; -use std::ops::Deref; +use core::{hash::Hash, ops::Deref}; use crate::{ irradiance_volume::IRRADIANCE_VOLUME_SHADER_HANDLE, diff --git a/crates/bevy_pbr/src/lightmap/mod.rs b/crates/bevy_pbr/src/lightmap/mod.rs index 913f86a812768..d1fd1cc143b8c 100644 --- a/crates/bevy_pbr/src/lightmap/mod.rs +++ b/crates/bevy_pbr/src/lightmap/mod.rs @@ -30,21 +30,22 @@ use bevy_app::{App, Plugin}; use bevy_asset::{load_internal_asset, AssetId, Handle}; -use bevy_ecs::entity::EntityHashMap; use bevy_ecs::{ component::Component, - entity::Entity, + entity::{Entity, EntityHashMap}, reflect::ReflectComponent, schedule::IntoSystemConfigs, system::{Query, Res, ResMut, Resource}, }; use bevy_math::{uvec2, vec4, Rect, UVec2}; use bevy_reflect::{std_traits::ReflectDefault, Reflect}; -use bevy_render::mesh::RenderMesh; -use bevy_render::texture::GpuImage; use bevy_render::{ - mesh::Mesh, render_asset::RenderAssets, render_resource::Shader, texture::Image, - view::ViewVisibility, Extract, ExtractSchedule, RenderApp, + mesh::{Mesh, RenderMesh}, + render_asset::RenderAssets, + render_resource::Shader, + texture::{GpuImage, Image}, + view::ViewVisibility, + Extract, ExtractSchedule, RenderApp, }; use bevy_utils::HashSet; diff --git a/crates/bevy_pbr/src/material.rs b/crates/bevy_pbr/src/material.rs index 8bf6ae254d9f3..eb2fecba93549 100644 --- a/crates/bevy_pbr/src/material.rs +++ b/crates/bevy_pbr/src/material.rs @@ -20,8 +20,7 @@ use bevy_ecs::{ prelude::*, system::{lifetimeless::SRes, SystemParamItem}, }; -use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; +use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_render::{ camera::TemporalJitter, extract_instances::{ExtractInstancesPlugin, ExtractedInstances}, @@ -34,9 +33,12 @@ use bevy_render::{ view::{ExtractedView, Msaa, RenderVisibilityRanges, VisibleEntities, WithMesh}, }; use bevy_utils::tracing::error; -use std::marker::PhantomData; -use std::sync::atomic::{AtomicU32, Ordering}; -use std::{hash::Hash, num::NonZero}; +use core::{ + hash::Hash, + marker::PhantomData, + num::NonZero, + sync::atomic::{AtomicU32, Ordering}, +}; use self::{irradiance_volume::IrradianceVolume, prelude::EnvironmentMapLight}; @@ -348,7 +350,7 @@ impl Hash for MaterialPipelineKey where M::Data: Hash, { - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { self.mesh_key.hash(state); self.bind_group_data.hash(state); } diff --git a/crates/bevy_pbr/src/meshlet/asset.rs b/crates/bevy_pbr/src/meshlet/asset.rs index 108cf981515c7..6daf1ba4d5f30 100644 --- a/crates/bevy_pbr/src/meshlet/asset.rs +++ b/crates/bevy_pbr/src/meshlet/asset.rs @@ -1,3 +1,4 @@ +use alloc::sync::Arc; use bevy_asset::{ io::{Reader, Writer}, saver::{AssetSaver, SavedAsset}, @@ -8,10 +9,7 @@ use bevy_reflect::TypePath; use bevy_tasks::block_on; use bytemuck::{Pod, Zeroable}; use lz4_flex::frame::{FrameDecoder, FrameEncoder}; -use std::{ - io::{Read, Write}, - sync::Arc, -}; +use std::io::{Read, Write}; /// Unique identifier for the [`MeshletMesh`] asset format. const MESHLET_MESH_ASSET_MAGIC: u64 = 1717551717668; @@ -200,7 +198,7 @@ fn write_slice( fn read_slice(reader: &mut dyn Read) -> Result, std::io::Error> { let len = read_u64(reader)? as usize; - let mut data: Arc<[T]> = std::iter::repeat_with(T::zeroed).take(len).collect(); + let mut data: Arc<[T]> = core::iter::repeat_with(T::zeroed).take(len).collect(); let slice = Arc::get_mut(&mut data).unwrap(); reader.read_exact(bytemuck::cast_slice_mut(slice))?; diff --git a/crates/bevy_pbr/src/meshlet/from_mesh.rs b/crates/bevy_pbr/src/meshlet/from_mesh.rs index 660a5bdeea18b..e4436383344c3 100644 --- a/crates/bevy_pbr/src/meshlet/from_mesh.rs +++ b/crates/bevy_pbr/src/meshlet/from_mesh.rs @@ -1,9 +1,11 @@ use super::asset::{Meshlet, MeshletBoundingSphere, MeshletBoundingSpheres, MeshletMesh}; +use alloc::borrow::Cow; use bevy_render::{ mesh::{Indices, Mesh}, render_resource::PrimitiveTopology, }; use bevy_utils::HashMap; +use core::ops::Range; use itertools::Itertools; use meshopt::{ build_meshlets, compute_cluster_bounds, compute_meshlet_bounds, ffi::meshopt_Bounds, simplify, @@ -11,7 +13,6 @@ use meshopt::{ }; use metis::Graph; use smallvec::SmallVec; -use std::{borrow::Cow, ops::Range}; impl MeshletMesh { /// Process a [`Mesh`] to generate a [`MeshletMesh`]. diff --git a/crates/bevy_pbr/src/meshlet/instance_manager.rs b/crates/bevy_pbr/src/meshlet/instance_manager.rs index 0f370f2200459..161cbf7f8b963 100644 --- a/crates/bevy_pbr/src/meshlet/instance_manager.rs +++ b/crates/bevy_pbr/src/meshlet/instance_manager.rs @@ -13,7 +13,7 @@ use bevy_ecs::{ use bevy_render::{render_resource::StorageBuffer, view::RenderLayers, MainWorld}; use bevy_transform::components::GlobalTransform; use bevy_utils::{HashMap, HashSet}; -use std::ops::{DerefMut, Range}; +use core::ops::{DerefMut, Range}; /// Manages data for each entity with a [`MeshletMesh`]. #[derive(Resource)] diff --git a/crates/bevy_pbr/src/meshlet/material_pipeline_prepare.rs b/crates/bevy_pbr/src/meshlet/material_pipeline_prepare.rs index 6a0f093d815c3..b1b91e8cc5c6a 100644 --- a/crates/bevy_pbr/src/meshlet/material_pipeline_prepare.rs +++ b/crates/bevy_pbr/src/meshlet/material_pipeline_prepare.rs @@ -18,7 +18,7 @@ use bevy_render::{ view::ExtractedView, }; use bevy_utils::{HashMap, HashSet}; -use std::hash::Hash; +use core::hash::Hash; /// A list of `(Material ID, Pipeline, BindGroup)` for a view for use in [`super::MeshletMainOpaquePass3dNode`]. #[derive(Component, Deref, DerefMut, Default)] diff --git a/crates/bevy_pbr/src/meshlet/meshlet_mesh_manager.rs b/crates/bevy_pbr/src/meshlet/meshlet_mesh_manager.rs index 7c25be7529759..09e065b019f45 100644 --- a/crates/bevy_pbr/src/meshlet/meshlet_mesh_manager.rs +++ b/crates/bevy_pbr/src/meshlet/meshlet_mesh_manager.rs @@ -3,6 +3,7 @@ use super::{ persistent_buffer::PersistentGpuBuffer, MeshletMesh, }; +use alloc::sync::Arc; use bevy_asset::{AssetId, Assets}; use bevy_ecs::{ system::{Res, ResMut, Resource}, @@ -13,7 +14,7 @@ use bevy_render::{ renderer::{RenderDevice, RenderQueue}, }; use bevy_utils::HashMap; -use std::{ops::Range, sync::Arc}; +use core::ops::Range; /// Manages uploading [`MeshletMesh`] asset data to the GPU. #[derive(Resource)] diff --git a/crates/bevy_pbr/src/meshlet/persistent_buffer.rs b/crates/bevy_pbr/src/meshlet/persistent_buffer.rs index e10dad6ef0aed..85dec457f9808 100644 --- a/crates/bevy_pbr/src/meshlet/persistent_buffer.rs +++ b/crates/bevy_pbr/src/meshlet/persistent_buffer.rs @@ -5,8 +5,8 @@ use bevy_render::{ }, renderer::{RenderDevice, RenderQueue}, }; +use core::{num::NonZero, ops::Range}; use range_alloc::RangeAllocator; -use std::{num::NonZero, ops::Range}; /// Wrapper for a GPU buffer holding a large amount of data that persists across frames. pub struct PersistentGpuBuffer { diff --git a/crates/bevy_pbr/src/meshlet/persistent_buffer_impls.rs b/crates/bevy_pbr/src/meshlet/persistent_buffer_impls.rs index 175fbe75143f5..bd15e4c42c477 100644 --- a/crates/bevy_pbr/src/meshlet/persistent_buffer_impls.rs +++ b/crates/bevy_pbr/src/meshlet/persistent_buffer_impls.rs @@ -2,7 +2,7 @@ use super::{ asset::{Meshlet, MeshletBoundingSpheres}, persistent_buffer::PersistentGpuBufferable, }; -use std::sync::Arc; +use alloc::sync::Arc; const MESHLET_VERTEX_SIZE_IN_BYTES: u32 = 48; diff --git a/crates/bevy_pbr/src/meshlet/resource_manager.rs b/crates/bevy_pbr/src/meshlet/resource_manager.rs index 4df1fb8fd3e05..aca52d133364b 100644 --- a/crates/bevy_pbr/src/meshlet/resource_manager.rs +++ b/crates/bevy_pbr/src/meshlet/resource_manager.rs @@ -1,5 +1,6 @@ use super::{instance_manager::InstanceManager, meshlet_mesh_manager::MeshletMeshManager}; use crate::ShadowView; +use alloc::sync::Arc; use bevy_core_pipeline::{ core_3d::Camera3d, prepass::{PreviousViewData, PreviousViewUniforms}, @@ -18,11 +19,8 @@ use bevy_render::{ view::{ExtractedView, RenderLayers, ViewUniform, ViewUniforms}, }; use binding_types::*; +use core::{array, iter, sync::atomic::AtomicBool}; use encase::internal::WriteInto; -use std::{ - array, iter, - sync::{atomic::AtomicBool, Arc}, -}; /// Manages per-view and per-cluster GPU resources for [`super::MeshletPlugin`]. #[derive(Resource)] diff --git a/crates/bevy_pbr/src/meshlet/visibility_buffer_raster_node.rs b/crates/bevy_pbr/src/meshlet/visibility_buffer_raster_node.rs index e05956fc80789..3dceb239ccda3 100644 --- a/crates/bevy_pbr/src/meshlet/visibility_buffer_raster_node.rs +++ b/crates/bevy_pbr/src/meshlet/visibility_buffer_raster_node.rs @@ -17,7 +17,7 @@ use bevy_render::{ renderer::RenderContext, view::{ViewDepthTexture, ViewUniformOffset}, }; -use std::sync::atomic::Ordering; +use core::sync::atomic::Ordering; /// Rasterize meshlets into a depth buffer, and optional visibility buffer + material depth buffer for shading passes. pub struct MeshletVisibilityBufferRasterPassNode { diff --git a/crates/bevy_pbr/src/pbr_material.rs b/crates/bevy_pbr/src/pbr_material.rs index 9e4a1c920b918..87aff3d4e4a8a 100644 --- a/crates/bevy_pbr/src/pbr_material.rs +++ b/crates/bevy_pbr/src/pbr_material.rs @@ -7,8 +7,7 @@ use bevy_render::{ }; use bitflags::bitflags; -use crate::deferred::DEFAULT_PBR_DEFERRED_LIGHTING_PASS_ID; -use crate::*; +use crate::{deferred::DEFAULT_PBR_DEFERRED_LIGHTING_PASS_ID, *}; /// An enum to define which UV attribute to use for a texture. /// It is used for every texture in the [`StandardMaterial`]. diff --git a/crates/bevy_pbr/src/prepass/mod.rs b/crates/bevy_pbr/src/prepass/mod.rs index 859a8624065c4..6cf3d8f6419f1 100644 --- a/crates/bevy_pbr/src/prepass/mod.rs +++ b/crates/bevy_pbr/src/prepass/mod.rs @@ -1,13 +1,16 @@ mod prepass_bindings; -use bevy_render::mesh::{MeshVertexBufferLayoutRef, RenderMesh}; -use bevy_render::render_resource::binding_types::uniform_buffer; -use bevy_render::view::WithMesh; +use bevy_render::{ + mesh::{MeshVertexBufferLayoutRef, RenderMesh}, + render_resource::binding_types::uniform_buffer, + view::WithMesh, +}; pub use prepass_bindings::*; use bevy_asset::{load_internal_asset, AssetServer}; -use bevy_core_pipeline::{core_3d::CORE_3D_DEPTH_FORMAT, prelude::Camera3d}; -use bevy_core_pipeline::{deferred::*, prepass::*}; +use bevy_core_pipeline::{ + core_3d::CORE_3D_DEPTH_FORMAT, deferred::*, prelude::Camera3d, prepass::*, +}; use bevy_ecs::{ prelude::*, system::{ @@ -36,7 +39,7 @@ use crate::meshlet::{ }; use crate::*; -use std::{hash::Hash, marker::PhantomData}; +use core::{hash::Hash, marker::PhantomData}; pub const PREPASS_SHADER_HANDLE: Handle = Handle::weak_from_u128(921124473254008983); diff --git a/crates/bevy_pbr/src/render/gpu_preprocess.rs b/crates/bevy_pbr/src/render/gpu_preprocess.rs index 38650d280891b..ef4877c1c612b 100644 --- a/crates/bevy_pbr/src/render/gpu_preprocess.rs +++ b/crates/bevy_pbr/src/render/gpu_preprocess.rs @@ -6,7 +6,7 @@ //! [`MeshInputUniform`]s instead and use the GPU to calculate the remaining //! derived fields in [`MeshUniform`]. -use std::num::NonZero; +use core::num::NonZero; use bevy_app::{App, Plugin}; use bevy_asset::{load_internal_asset, Handle}; diff --git a/crates/bevy_pbr/src/render/light.rs b/crates/bevy_pbr/src/render/light.rs index 86fd2151ce00c..04eeb04cf8f71 100644 --- a/crates/bevy_pbr/src/render/light.rs +++ b/crates/bevy_pbr/src/render/light.rs @@ -1,9 +1,11 @@ use bevy_asset::UntypedAssetId; use bevy_color::ColorToComponents; use bevy_core_pipeline::core_3d::{Camera3d, CORE_3D_DEPTH_FORMAT}; -use bevy_ecs::entity::EntityHashSet; -use bevy_ecs::prelude::*; -use bevy_ecs::{entity::EntityHashMap, system::lifetimeless::Read}; +use bevy_ecs::{ + entity::{EntityHashMap, EntityHashSet}, + prelude::*, + system::lifetimeless::Read, +}; use bevy_math::{ops, Mat4, UVec4, Vec2, Vec3, Vec3Swizzles, Vec4, Vec4Swizzles}; use bevy_render::{ diagnostic::RecordDiagnostics, @@ -23,7 +25,7 @@ use bevy_utils::prelude::default; #[cfg(feature = "trace")] use bevy_utils::tracing::info_span; use bevy_utils::tracing::{error, warn}; -use std::{hash::Hash, ops::Range}; +use core::{hash::Hash, ops::Range}; use crate::*; @@ -257,7 +259,7 @@ pub fn extract_lights( // NOTE: Map from luminous power in lumens to luminous intensity in lumens per steradian // for a point light. See https://google.github.io/filament/Filament.html#mjx-eqn-pointLightLuminousPower // for details. - intensity: point_light.intensity / (4.0 * std::f32::consts::PI), + intensity: point_light.intensity / (4.0 * core::f32::consts::PI), range: point_light.range, radius: point_light.radius, transform: *transform, @@ -267,7 +269,7 @@ pub fn extract_lights( // The factor of SQRT_2 is for the worst-case diagonal offset shadow_normal_bias: point_light.shadow_normal_bias * point_light_texel_size - * std::f32::consts::SQRT_2, + * core::f32::consts::SQRT_2, shadow_map_near_z: point_light.shadow_map_near_z, spot_light_angles: None, }; @@ -308,7 +310,7 @@ pub fn extract_lights( // Note: Filament uses a divisor of PI for spot lights. We choose to use the same 4*PI divisor // in both cases so that toggling between point light and spot light keeps lit areas lit equally, // which seems least surprising for users - intensity: spot_light.intensity / (4.0 * std::f32::consts::PI), + intensity: spot_light.intensity / (4.0 * core::f32::consts::PI), range: spot_light.range, radius: spot_light.radius, transform: *transform, @@ -318,7 +320,7 @@ pub fn extract_lights( // The factor of SQRT_2 is for the worst-case diagonal offset shadow_normal_bias: spot_light.shadow_normal_bias * texel_size - * std::f32::consts::SQRT_2, + * core::f32::consts::SQRT_2, shadow_map_near_z: spot_light.shadow_map_near_z, spot_light_angles: Some((spot_light.inner_angle, spot_light.outer_angle)), }, @@ -360,7 +362,8 @@ pub fn extract_lights( shadows_enabled: directional_light.shadows_enabled, shadow_depth_bias: directional_light.shadow_depth_bias, // The factor of SQRT_2 is for the worst-case diagonal offset - shadow_normal_bias: directional_light.shadow_normal_bias * std::f32::consts::SQRT_2, + shadow_normal_bias: directional_light.shadow_normal_bias + * core::f32::consts::SQRT_2, cascade_shadow_config: cascade_config.clone(), cascades: cascades.cascades.clone(), frusta: frusta.frusta.clone(), @@ -697,7 +700,7 @@ pub fn prepare_lights( } let cube_face_projection = Mat4::perspective_infinite_reverse_rh( - std::f32::consts::FRAC_PI_2, + core::f32::consts::FRAC_PI_2, 1.0, light.shadow_map_near_z, ); @@ -905,7 +908,7 @@ pub fn prepare_lights( let view_translation = GlobalTransform::from_translation(light.transform.translation()); let cube_face_projection = Mat4::perspective_infinite_reverse_rh( - std::f32::consts::FRAC_PI_2, + core::f32::consts::FRAC_PI_2, 1.0, light.shadow_map_near_z, ); diff --git a/crates/bevy_pbr/src/render/mesh.rs b/crates/bevy_pbr/src/render/mesh.rs index 007ed983e5fad..c1c9a29129563 100644 --- a/crates/bevy_pbr/src/render/mesh.rs +++ b/crates/bevy_pbr/src/render/mesh.rs @@ -1,4 +1,4 @@ -use std::mem::{self, size_of}; +use core::mem::{self, size_of}; use allocator::MeshAllocator; use bevy_asset::{load_internal_asset, AssetId}; @@ -8,8 +8,8 @@ use bevy_core_pipeline::{ prepass::MotionVectorPrepass, }; use bevy_derive::{Deref, DerefMut}; -use bevy_ecs::entity::EntityHashMap; use bevy_ecs::{ + entity::EntityHashMap, prelude::*, query::ROQueryItem, system::{lifetimeless::*, SystemParamItem, SystemState}, @@ -40,19 +40,25 @@ use bevy_render::{ Extract, }; use bevy_transform::components::GlobalTransform; -use bevy_utils::{tracing::error, tracing::warn, Entry, HashMap, Parallel}; +use bevy_utils::{ + tracing::{error, warn}, + Entry, HashMap, Parallel, +}; use bytemuck::{Pod, Zeroable}; use nonmax::{NonMaxU16, NonMaxU32}; use static_assertions::const_assert_eq; -use crate::render::{ - morph::{ - extract_morphs, no_automatic_morph_batching, prepare_morphs, MorphIndices, MorphUniforms, +use crate::{ + render::{ + morph::{ + extract_morphs, no_automatic_morph_batching, prepare_morphs, MorphIndices, + MorphUniforms, + }, + skin::no_automatic_skin_batching, }, - skin::no_automatic_skin_batching, + *, }; -use crate::*; use self::irradiance_volume::IRRADIANCE_VOLUMES_ARE_USABLE; diff --git a/crates/bevy_pbr/src/render/mesh_view_bindings.rs b/crates/bevy_pbr/src/render/mesh_view_bindings.rs index 9446b3c9a9180..f44999b8b6499 100644 --- a/crates/bevy_pbr/src/render/mesh_view_bindings.rs +++ b/crates/bevy_pbr/src/render/mesh_view_bindings.rs @@ -1,4 +1,5 @@ -use std::{array, num::NonZero, sync::Arc}; +use alloc::sync::Arc; +use core::{array, num::NonZero}; use bevy_core_pipeline::{ core_3d::ViewTransmissionTexture, diff --git a/crates/bevy_pbr/src/render/morph.rs b/crates/bevy_pbr/src/render/morph.rs index 2f28fbf588d73..c2696652a7a2f 100644 --- a/crates/bevy_pbr/src/render/morph.rs +++ b/crates/bevy_pbr/src/render/morph.rs @@ -1,7 +1,6 @@ -use std::{iter, mem}; +use core::{iter, mem}; -use bevy_ecs::entity::EntityHashMap; -use bevy_ecs::prelude::*; +use bevy_ecs::{entity::EntityHashMap, prelude::*}; use bevy_render::{ batching::NoAutomaticBatching, mesh::morph::{MeshMorphWeights, MAX_MORPH_WEIGHTS}, @@ -89,7 +88,7 @@ fn add_to_alignment(buffer: &mut RawBufferVec) { panic!( "RawBufferVec should contain only types with a size multiple or divisible by {n}, \ {} has a size of {t_size}, which is neither multiple or divisible by {n}", - std::any::type_name::() + core::any::type_name::() ); } diff --git a/crates/bevy_pbr/src/render/skin.rs b/crates/bevy_pbr/src/render/skin.rs index 6d6f974b761cc..1719789d55420 100644 --- a/crates/bevy_pbr/src/render/skin.rs +++ b/crates/bevy_pbr/src/render/skin.rs @@ -1,8 +1,7 @@ -use std::mem::{self, size_of}; +use core::mem::{self, size_of}; use bevy_asset::Assets; -use bevy_ecs::entity::EntityHashMap; -use bevy_ecs::prelude::*; +use bevy_ecs::{entity::EntityHashMap, prelude::*}; use bevy_math::Mat4; use bevy_render::{ batching::NoAutomaticBatching, diff --git a/crates/bevy_pbr/src/ssao/mod.rs b/crates/bevy_pbr/src/ssao/mod.rs index 249a2267b77fb..ffbd7584583af 100644 --- a/crates/bevy_pbr/src/ssao/mod.rs +++ b/crates/bevy_pbr/src/ssao/mod.rs @@ -14,8 +14,7 @@ use bevy_ecs::{ system::{Commands, Query, Res, ResMut, Resource}, world::{FromWorld, World}, }; -use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; +use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_render::{ camera::{ExtractedCamera, TemporalJitter}, extract_component::ExtractComponent, @@ -37,7 +36,7 @@ use bevy_utils::{ prelude::default, tracing::{error, warn}, }; -use std::mem; +use core::mem; const PREPROCESS_DEPTH_SHADER_HANDLE: Handle = Handle::weak_from_u128(102258915420479); const GTAO_SHADER_HANDLE: Handle = Handle::weak_from_u128(253938746510568); diff --git a/crates/bevy_pbr/src/volumetric_fog/mod.rs b/crates/bevy_pbr/src/volumetric_fog/mod.rs index cbf735b592684..8a45fdc4b0107 100644 --- a/crates/bevy_pbr/src/volumetric_fog/mod.rs +++ b/crates/bevy_pbr/src/volumetric_fog/mod.rs @@ -44,8 +44,7 @@ use bevy_math::{ primitives::{Cuboid, Plane3d}, Vec2, Vec3, }; -use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; +use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_render::{ mesh::{Mesh, Meshable}, render_graph::{RenderGraphApp, ViewNodeRunner}, diff --git a/crates/bevy_pbr/src/volumetric_fog/render.rs b/crates/bevy_pbr/src/volumetric_fog/render.rs index 9a35a92eae31c..126d2fddf7dd3 100644 --- a/crates/bevy_pbr/src/volumetric_fog/render.rs +++ b/crates/bevy_pbr/src/volumetric_fog/render.rs @@ -1,6 +1,6 @@ //! Rendering of fog volumes. -use std::array; +use core::array; use bevy_asset::{AssetId, Handle}; use bevy_color::ColorToComponents as _; diff --git a/crates/bevy_picking/src/events.rs b/crates/bevy_picking/src/events.rs index 56f10c24cb881..c61ca42aea4c9 100644 --- a/crates/bevy_picking/src/events.rs +++ b/crates/bevy_picking/src/events.rs @@ -37,7 +37,7 @@ //! When received by an observer, these events will always be wrapped by the [`Pointer`] type, which contains //! general metadata about the pointer and it's location. -use std::fmt::Debug; +use core::fmt::Debug; use bevy_ecs::prelude::*; use bevy_hierarchy::Parent; @@ -78,8 +78,8 @@ where const AUTO_PROPAGATE: bool = true; } -impl std::fmt::Display for Pointer { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Display for Pointer { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.write_fmt(format_args!( "{:?}, {:.1?}, {:.1?}", self.pointer_id, self.pointer_location.position, self.event @@ -87,7 +87,7 @@ impl std::fmt::Display for Pointer { } } -impl std::ops::Deref for Pointer { +impl core::ops::Deref for Pointer { type Target = E; fn deref(&self) -> &Self::Target { diff --git a/crates/bevy_picking/src/focus.rs b/crates/bevy_picking/src/focus.rs index 3d10019401736..6d9a5d1c95799 100644 --- a/crates/bevy_picking/src/focus.rs +++ b/crates/bevy_picking/src/focus.rs @@ -3,10 +3,9 @@ //! The most important type in this module is the [`HoverMap`], which maps pointers to the entities //! they are hovering over. -use std::{ - collections::{BTreeMap, HashSet}, - fmt::Debug, -}; +use alloc::collections::BTreeMap; +use core::fmt::Debug; +use std::collections::HashSet; use crate::{ backend::{self, HitData}, diff --git a/crates/bevy_picking/src/input.rs b/crates/bevy_picking/src/input.rs index bef8b57c47aad..0238f9d76be24 100644 --- a/crates/bevy_picking/src/input.rs +++ b/crates/bevy_picking/src/input.rs @@ -14,8 +14,11 @@ use bevy_app::prelude::*; use bevy_ecs::prelude::*; use bevy_hierarchy::DespawnRecursiveExt; -use bevy_input::touch::{TouchInput, TouchPhase}; -use bevy_input::{prelude::*, ButtonState}; +use bevy_input::{ + prelude::*, + touch::{TouchInput, TouchPhase}, + ButtonState, +}; use bevy_math::Vec2; use bevy_reflect::prelude::*; use bevy_render::camera::RenderTarget; diff --git a/crates/bevy_picking/src/lib.rs b/crates/bevy_picking/src/lib.rs index 4f38d3454d04a..68441496707aa 100644 --- a/crates/bevy_picking/src/lib.rs +++ b/crates/bevy_picking/src/lib.rs @@ -150,6 +150,8 @@ #![deny(missing_docs)] +extern crate alloc; + pub mod backend; pub mod events; pub mod focus; diff --git a/crates/bevy_picking/src/pointer.rs b/crates/bevy_picking/src/pointer.rs index 4dbeb46146b7d..ee04fc732c880 100644 --- a/crates/bevy_picking/src/pointer.rs +++ b/crates/bevy_picking/src/pointer.rs @@ -17,7 +17,7 @@ use bevy_window::PrimaryWindow; use uuid::Uuid; -use std::fmt::Debug; +use core::fmt::Debug; use crate::backend::HitData; diff --git a/crates/bevy_ptr/src/lib.rs b/crates/bevy_ptr/src/lib.rs index f083c6a3b8fb9..f9bd5c1389b82 100644 --- a/crates/bevy_ptr/src/lib.rs +++ b/crates/bevy_ptr/src/lib.rs @@ -53,7 +53,7 @@ impl ConstNonNull { /// let x = 0u32; /// let ptr = ConstNonNull::::new(&x as *const _).expect("ptr is null!"); /// - /// if let Some(ptr) = ConstNonNull::::new(std::ptr::null()) { + /// if let Some(ptr) = ConstNonNull::::new(core::ptr::null()) { /// unreachable!(); /// } /// ``` @@ -82,7 +82,7 @@ impl ConstNonNull { /// use bevy_ptr::ConstNonNull; /// /// // NEVER DO THAT!!! This is undefined behavior. ⚠️ - /// let ptr = unsafe { ConstNonNull::::new_unchecked(std::ptr::null()) }; + /// let ptr = unsafe { ConstNonNull::::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` diff --git a/crates/bevy_reflect/compile_fail/tests/reflect_derive/custom_where_fail.rs b/crates/bevy_reflect/compile_fail/tests/reflect_derive/custom_where_fail.rs index 3cd2d1f60fd43..28370ca7555de 100644 --- a/crates/bevy_reflect/compile_fail/tests/reflect_derive/custom_where_fail.rs +++ b/crates/bevy_reflect/compile_fail/tests/reflect_derive/custom_where_fail.rs @@ -1,5 +1,5 @@ use bevy_reflect::{FromType, Reflect}; -use std::marker::PhantomData; +use core::marker::PhantomData; #[derive(Clone)] struct ReflectMyTrait; @@ -12,7 +12,7 @@ impl FromType for ReflectMyTrait { // Reason: populated `where` clause must be last with #[reflect(MyTrait)] #[derive(Reflect)] -#[reflect(where T: std::fmt::Debug, MyTrait)] +#[reflect(where T: core::fmt::Debug, MyTrait)] //~^ ERROR: /expected.+:/ // TODO: Investigate a way to improve the error message. pub struct Foo { diff --git a/crates/bevy_reflect/compile_fail/tests/reflect_derive/custom_where_pass.rs b/crates/bevy_reflect/compile_fail/tests/reflect_derive/custom_where_pass.rs index 2b317c2e6185e..456afd35f5240 100644 --- a/crates/bevy_reflect/compile_fail/tests/reflect_derive/custom_where_pass.rs +++ b/crates/bevy_reflect/compile_fail/tests/reflect_derive/custom_where_pass.rs @@ -1,6 +1,6 @@ //@check-pass use bevy_reflect::{FromType, Reflect}; -use std::marker::PhantomData; +use core::marker::PhantomData; #[derive(Clone)] struct ReflectMyTrait; @@ -12,7 +12,7 @@ impl FromType for ReflectMyTrait { } #[derive(Reflect)] -#[reflect(MyTrait, where T: std::fmt::Debug)] +#[reflect(MyTrait, where T: core::fmt::Debug)] pub struct Foo { value: String, #[reflect(ignore)] @@ -29,7 +29,7 @@ pub struct Bar { #[derive(Reflect)] #[reflect(MyTrait)] -#[reflect(where T: std::fmt::Debug)] +#[reflect(where T: core::fmt::Debug)] pub struct Baz { value: String, #[reflect(ignore)] diff --git a/crates/bevy_reflect/derive/src/container_attributes.rs b/crates/bevy_reflect/derive/src/container_attributes.rs index 7aa027cb1f51f..fce88c10062b3 100644 --- a/crates/bevy_reflect/derive/src/container_attributes.rs +++ b/crates/bevy_reflect/derive/src/container_attributes.rs @@ -5,16 +5,17 @@ //! the derive helper attribute for `Reflect`, which looks like: //! `#[reflect(PartialEq, Default, ...)]`. -use crate::attribute_parser::terminated_parser; -use crate::custom_attributes::CustomAttributes; -use crate::derive_data::ReflectTraitToImpl; +use crate::{ + attribute_parser::terminated_parser, custom_attributes::CustomAttributes, + derive_data::ReflectTraitToImpl, +}; use bevy_macro_utils::fq_std::{FQAny, FQOption}; use proc_macro2::{Ident, Span}; use quote::quote_spanned; -use syn::ext::IdentExt; -use syn::parse::ParseStream; -use syn::spanned::Spanned; -use syn::{parenthesized, token, Expr, LitBool, MetaList, MetaNameValue, Path, Token, WhereClause}; +use syn::{ + ext::IdentExt, parenthesized, parse::ParseStream, spanned::Spanned, token, Expr, LitBool, + MetaList, MetaNameValue, Path, Token, WhereClause, +}; mod kw { syn::custom_keyword!(from_reflect); diff --git a/crates/bevy_reflect/derive/src/custom_attributes.rs b/crates/bevy_reflect/derive/src/custom_attributes.rs index 68bb7d1843a7c..f12b6d7c12480 100644 --- a/crates/bevy_reflect/derive/src/custom_attributes.rs +++ b/crates/bevy_reflect/derive/src/custom_attributes.rs @@ -1,7 +1,6 @@ use proc_macro2::TokenStream; use quote::quote; -use syn::parse::ParseStream; -use syn::{Expr, Path, Token}; +use syn::{parse::ParseStream, Expr, Path, Token}; #[derive(Default, Clone)] pub(crate) struct CustomAttributes { diff --git a/crates/bevy_reflect/derive/src/derive_data.rs b/crates/bevy_reflect/derive/src/derive_data.rs index 5c2e99db5b9d9..ccfa621dc2a5c 100644 --- a/crates/bevy_reflect/derive/src/derive_data.rs +++ b/crates/bevy_reflect/derive/src/derive_data.rs @@ -1,23 +1,23 @@ use core::fmt; use proc_macro2::Span; -use crate::container_attributes::{ContainerAttributes, FromReflectAttrs, TypePathAttrs}; -use crate::field_attributes::FieldAttributes; -use crate::result_sifter::ResultSifter; -use crate::string_expr::StringExpr; -use crate::type_path::parse_path_no_leading_colon; -use crate::where_clause_options::WhereClauseOptions; +use crate::{ + container_attributes::{ContainerAttributes, FromReflectAttrs, TypePathAttrs}, + field_attributes::FieldAttributes, + remote::RemoteType, + result_sifter::ResultSifter, + serialization::SerializationDataDef, + string_expr::StringExpr, + type_path::parse_path_no_leading_colon, + where_clause_options::WhereClauseOptions, + REFLECT_ATTRIBUTE_NAME, TYPE_NAME_ATTRIBUTE_NAME, TYPE_PATH_ATTRIBUTE_NAME, +}; use quote::{quote, ToTokens}; use syn::token::Comma; -use crate::remote::RemoteType; -use crate::serialization::SerializationDataDef; -use crate::{REFLECT_ATTRIBUTE_NAME, TYPE_NAME_ATTRIBUTE_NAME, TYPE_PATH_ATTRIBUTE_NAME}; -use syn::punctuated::Punctuated; -use syn::spanned::Spanned; use syn::{ - parse_str, Data, DeriveInput, Field, Fields, GenericParam, Generics, Ident, LitStr, Meta, Path, - PathSegment, Type, TypeParam, Variant, + parse_str, punctuated::Punctuated, spanned::Spanned, Data, DeriveInput, Field, Fields, + GenericParam, Generics, Ident, LitStr, Meta, Path, PathSegment, Type, TypeParam, Variant, }; pub(crate) enum ReflectDerive<'a> { @@ -477,7 +477,7 @@ impl<'a> ReflectMeta<'a> { self, where_clause_options, None, - Option::>::None, + Option::>::None, ) } @@ -855,14 +855,14 @@ impl<'a> EnumVariant<'a> { /// ```ignore (bevy_reflect is not accessible from this crate) /// # use syn::parse_quote; /// # use bevy_reflect_derive::ReflectTypePath; -/// let path: syn::Path = parse_quote!(::core::marker::PhantomData)?; +/// let path: syn::Path = parse_quote!(::std::marker::PhantomData)?; /// /// let type_path = ReflectTypePath::External { /// path, /// custom_path: None, /// }; /// -/// // Equivalent to "core::marker". +/// // Equivalent to "std::marker". /// let module_path = type_path.module_path(); /// # Ok::<(), syn::Error>(()) /// ``` @@ -1059,7 +1059,7 @@ impl<'a> ReflectTypePath<'a> { /// Returns a [`StringExpr`] representing the "type path" of the type. /// - /// For `Option`, this is `"core::option::Option"`. + /// For `Option`, this is `"std::option::Option"`. pub fn long_type_path(&self, bevy_reflect_path: &Path) -> StringExpr { match self { Self::Primitive(ident) => StringExpr::from(ident), @@ -1135,7 +1135,7 @@ impl<'a> ReflectTypePath<'a> { /// /// For non-customised [internal] paths this is created from [`module_path`]. /// - /// For `Option`, this is `"core::option"`. + /// For `Option`, this is `"std::option"`. /// /// [primitive]: ReflectTypePath::Primitive /// [anonymous]: ReflectTypePath::Anonymous diff --git a/crates/bevy_reflect/derive/src/enum_utility.rs b/crates/bevy_reflect/derive/src/enum_utility.rs index 766e94b859adf..f4b1e5ede8b77 100644 --- a/crates/bevy_reflect/derive/src/enum_utility.rs +++ b/crates/bevy_reflect/derive/src/enum_utility.rs @@ -1,6 +1,7 @@ -use crate::derive_data::StructField; -use crate::field_attributes::DefaultBehavior; -use crate::{derive_data::ReflectEnum, ident::ident_or_index}; +use crate::{ + derive_data::ReflectEnum, derive_data::StructField, field_attributes::DefaultBehavior, + ident::ident_or_index, +}; use bevy_macro_utils::fq_std::{FQDefault, FQOption}; use proc_macro2::{Ident, TokenStream}; use quote::{format_ident, quote}; diff --git a/crates/bevy_reflect/derive/src/field_attributes.rs b/crates/bevy_reflect/derive/src/field_attributes.rs index a0ef12ef8f110..6cddb50e61bda 100644 --- a/crates/bevy_reflect/derive/src/field_attributes.rs +++ b/crates/bevy_reflect/derive/src/field_attributes.rs @@ -4,12 +4,12 @@ //! as opposed to an entire struct or enum. An example of such an attribute is //! the derive helper attribute for `Reflect`, which looks like: `#[reflect(ignore)]`. -use crate::attribute_parser::terminated_parser; -use crate::custom_attributes::CustomAttributes; -use crate::REFLECT_ATTRIBUTE_NAME; +use crate::{ + attribute_parser::terminated_parser, custom_attributes::CustomAttributes, + REFLECT_ATTRIBUTE_NAME, +}; use quote::ToTokens; -use syn::parse::ParseStream; -use syn::{Attribute, LitStr, Meta, Token, Type}; +use syn::{parse::ParseStream, Attribute, LitStr, Meta, Token, Type}; mod kw { syn::custom_keyword!(ignore); diff --git a/crates/bevy_reflect/derive/src/from_reflect.rs b/crates/bevy_reflect/derive/src/from_reflect.rs index 026fb33dba8c6..d994cbd2f79a2 100644 --- a/crates/bevy_reflect/derive/src/from_reflect.rs +++ b/crates/bevy_reflect/derive/src/from_reflect.rs @@ -1,10 +1,12 @@ -use crate::container_attributes::REFLECT_DEFAULT; -use crate::derive_data::ReflectEnum; -use crate::enum_utility::{EnumVariantOutputData, FromReflectVariantBuilder, VariantBuilder}; -use crate::field_attributes::DefaultBehavior; -use crate::ident::ident_or_index; -use crate::where_clause_options::WhereClauseOptions; -use crate::{ReflectMeta, ReflectStruct}; +use crate::{ + container_attributes::REFLECT_DEFAULT, + derive_data::ReflectEnum, + enum_utility::{EnumVariantOutputData, FromReflectVariantBuilder, VariantBuilder}, + field_attributes::DefaultBehavior, + ident::ident_or_index, + where_clause_options::WhereClauseOptions, + ReflectMeta, ReflectStruct, +}; use bevy_macro_utils::fq_std::{FQClone, FQDefault, FQOption}; use proc_macro2::Span; use quote::{quote, ToTokens}; diff --git a/crates/bevy_reflect/derive/src/impls/assertions.rs b/crates/bevy_reflect/derive/src/impls/assertions.rs index 06d835e6cf9d4..22a2c4f5a3e6f 100644 --- a/crates/bevy_reflect/derive/src/impls/assertions.rs +++ b/crates/bevy_reflect/derive/src/impls/assertions.rs @@ -1,5 +1,4 @@ -use crate::derive_data::ReflectDerive; -use crate::remote::generate_remote_assertions; +use crate::{derive_data::ReflectDerive, remote::generate_remote_assertions}; use quote::quote; /// Generates an anonymous block containing compile-time assertions. diff --git a/crates/bevy_reflect/derive/src/impls/enums.rs b/crates/bevy_reflect/derive/src/impls/enums.rs index 15d5c01ffa796..c4791ca32bb07 100644 --- a/crates/bevy_reflect/derive/src/impls/enums.rs +++ b/crates/bevy_reflect/derive/src/impls/enums.rs @@ -1,6 +1,8 @@ -use crate::derive_data::{EnumVariantFields, ReflectEnum, StructField}; -use crate::enum_utility::{EnumVariantOutputData, TryApplyVariantBuilder, VariantBuilder}; -use crate::impls::{common_partial_reflect_methods, impl_full_reflect, impl_type_path, impl_typed}; +use crate::{ + derive_data::{EnumVariantFields, ReflectEnum, StructField}, + enum_utility::{EnumVariantOutputData, TryApplyVariantBuilder, VariantBuilder}, + impls::{common_partial_reflect_methods, impl_full_reflect, impl_type_path, impl_typed}, +}; use bevy_macro_utils::fq_std::{FQBox, FQOption, FQResult}; use proc_macro2::{Ident, Span}; use quote::quote; diff --git a/crates/bevy_reflect/derive/src/impls/func/from_arg.rs b/crates/bevy_reflect/derive/src/impls/func/from_arg.rs index ec663a103e8d9..77b984e04a14d 100644 --- a/crates/bevy_reflect/derive/src/impls/func/from_arg.rs +++ b/crates/bevy_reflect/derive/src/impls/func/from_arg.rs @@ -1,5 +1,4 @@ -use crate::derive_data::ReflectMeta; -use crate::where_clause_options::WhereClauseOptions; +use crate::{derive_data::ReflectMeta, where_clause_options::WhereClauseOptions}; use bevy_macro_utils::fq_std::FQResult; use quote::quote; diff --git a/crates/bevy_reflect/derive/src/impls/func/function_impls.rs b/crates/bevy_reflect/derive/src/impls/func/function_impls.rs index 1696f906f6ad0..64ca7ca7b7365 100644 --- a/crates/bevy_reflect/derive/src/impls/func/function_impls.rs +++ b/crates/bevy_reflect/derive/src/impls/func/function_impls.rs @@ -1,8 +1,10 @@ -use crate::derive_data::ReflectMeta; -use crate::impls::func::from_arg::impl_from_arg; -use crate::impls::func::get_ownership::impl_get_ownership; -use crate::impls::func::into_return::impl_into_return; -use crate::where_clause_options::WhereClauseOptions; +use crate::{ + derive_data::ReflectMeta, + impls::func::{ + from_arg::impl_from_arg, get_ownership::impl_get_ownership, into_return::impl_into_return, + }, + where_clause_options::WhereClauseOptions, +}; use quote::quote; pub(crate) fn impl_function_traits( diff --git a/crates/bevy_reflect/derive/src/impls/func/get_ownership.rs b/crates/bevy_reflect/derive/src/impls/func/get_ownership.rs index f04a9cad39b5b..01d33eb7bb164 100644 --- a/crates/bevy_reflect/derive/src/impls/func/get_ownership.rs +++ b/crates/bevy_reflect/derive/src/impls/func/get_ownership.rs @@ -1,5 +1,4 @@ -use crate::derive_data::ReflectMeta; -use crate::where_clause_options::WhereClauseOptions; +use crate::{derive_data::ReflectMeta, where_clause_options::WhereClauseOptions}; use quote::quote; pub(crate) fn impl_get_ownership( diff --git a/crates/bevy_reflect/derive/src/impls/func/into_return.rs b/crates/bevy_reflect/derive/src/impls/func/into_return.rs index 7359184e62556..c47c328f9ae13 100644 --- a/crates/bevy_reflect/derive/src/impls/func/into_return.rs +++ b/crates/bevy_reflect/derive/src/impls/func/into_return.rs @@ -1,5 +1,4 @@ -use crate::derive_data::ReflectMeta; -use crate::where_clause_options::WhereClauseOptions; +use crate::{derive_data::ReflectMeta, where_clause_options::WhereClauseOptions}; use quote::quote; pub(crate) fn impl_into_return( diff --git a/crates/bevy_reflect/derive/src/impls/opaque.rs b/crates/bevy_reflect/derive/src/impls/opaque.rs index 5391dae6d64c1..eb8fb9f4e01fa 100644 --- a/crates/bevy_reflect/derive/src/impls/opaque.rs +++ b/crates/bevy_reflect/derive/src/impls/opaque.rs @@ -1,6 +1,8 @@ -use crate::impls::{common_partial_reflect_methods, impl_full_reflect, impl_type_path, impl_typed}; -use crate::where_clause_options::WhereClauseOptions; -use crate::ReflectMeta; +use crate::{ + impls::{common_partial_reflect_methods, impl_full_reflect, impl_type_path, impl_typed}, + where_clause_options::WhereClauseOptions, + ReflectMeta, +}; use bevy_macro_utils::fq_std::{FQBox, FQClone, FQOption, FQResult}; use quote::quote; diff --git a/crates/bevy_reflect/derive/src/impls/structs.rs b/crates/bevy_reflect/derive/src/impls/structs.rs index 15b11d4dd97a1..fa1b454cfc373 100644 --- a/crates/bevy_reflect/derive/src/impls/structs.rs +++ b/crates/bevy_reflect/derive/src/impls/structs.rs @@ -1,6 +1,8 @@ -use crate::impls::{common_partial_reflect_methods, impl_full_reflect, impl_type_path, impl_typed}; -use crate::struct_utility::FieldAccessors; -use crate::ReflectStruct; +use crate::{ + impls::{common_partial_reflect_methods, impl_full_reflect, impl_type_path, impl_typed}, + struct_utility::FieldAccessors, + ReflectStruct, +}; use bevy_macro_utils::fq_std::{FQBox, FQDefault, FQOption, FQResult}; use quote::{quote, ToTokens}; diff --git a/crates/bevy_reflect/derive/src/impls/tuple_structs.rs b/crates/bevy_reflect/derive/src/impls/tuple_structs.rs index fc2228e70e4c8..f0f3cc8f2bdf0 100644 --- a/crates/bevy_reflect/derive/src/impls/tuple_structs.rs +++ b/crates/bevy_reflect/derive/src/impls/tuple_structs.rs @@ -1,6 +1,8 @@ -use crate::impls::{common_partial_reflect_methods, impl_full_reflect, impl_type_path, impl_typed}; -use crate::struct_utility::FieldAccessors; -use crate::ReflectStruct; +use crate::{ + impls::{common_partial_reflect_methods, impl_full_reflect, impl_type_path, impl_typed}, + struct_utility::FieldAccessors, + ReflectStruct, +}; use bevy_macro_utils::fq_std::{FQBox, FQDefault, FQOption, FQResult}; use quote::{quote, ToTokens}; diff --git a/crates/bevy_reflect/derive/src/lib.rs b/crates/bevy_reflect/derive/src/lib.rs index e7fc27bcfe1a3..a54442028df37 100644 --- a/crates/bevy_reflect/derive/src/lib.rs +++ b/crates/bevy_reflect/derive/src/lib.rs @@ -159,7 +159,7 @@ fn match_reflect_impls(ast: DeriveInput, source: ReflectImplSource) -> TokenStre /// the type's [`Debug`] implementation. /// A custom implementation may be provided using `#[reflect(Debug(my_debug_func))]` where /// `my_debug_func` is the path to a function matching the signature: -/// `(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result`. +/// `(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result`. /// * `#[reflect(PartialEq)]` will force the implementation of `Reflect::reflect_partial_eq` to rely on /// the type's [`PartialEq`] implementation. /// A custom implementation may be provided using `#[reflect(PartialEq(my_partial_eq_func))]` where diff --git a/crates/bevy_reflect/derive/src/reflect_opaque.rs b/crates/bevy_reflect/derive/src/reflect_opaque.rs index 24b92dbeae259..7cebcd7aff16c 100644 --- a/crates/bevy_reflect/derive/src/reflect_opaque.rs +++ b/crates/bevy_reflect/derive/src/reflect_opaque.rs @@ -1,9 +1,8 @@ -use crate::container_attributes::ContainerAttributes; -use crate::derive_data::ReflectTraitToImpl; -use crate::type_path::CustomPathDef; -use syn::parse::ParseStream; -use syn::token::Paren; -use syn::{parenthesized, Attribute, Generics, Path}; +use crate::{ + container_attributes::ContainerAttributes, derive_data::ReflectTraitToImpl, + type_path::CustomPathDef, +}; +use syn::{parenthesized, parse::ParseStream, token::Paren, Attribute, Generics, Path}; /// A struct used to define a simple reflection-opaque types (including primitives). /// diff --git a/crates/bevy_reflect/derive/src/registration.rs b/crates/bevy_reflect/derive/src/registration.rs index 6210b4358b1d8..f60791215cef8 100644 --- a/crates/bevy_reflect/derive/src/registration.rs +++ b/crates/bevy_reflect/derive/src/registration.rs @@ -1,8 +1,9 @@ //! Contains code related specifically to Bevy's type registration. -use crate::derive_data::ReflectMeta; -use crate::serialization::SerializationDataDef; -use crate::where_clause_options::WhereClauseOptions; +use crate::{ + derive_data::ReflectMeta, serialization::SerializationDataDef, + where_clause_options::WhereClauseOptions, +}; use quote::quote; use syn::Type; diff --git a/crates/bevy_reflect/derive/src/remote.rs b/crates/bevy_reflect/derive/src/remote.rs index dab2d0562bba5..13cbe681ed4c7 100644 --- a/crates/bevy_reflect/derive/src/remote.rs +++ b/crates/bevy_reflect/derive/src/remote.rs @@ -1,16 +1,21 @@ -use crate::derive_data::{ReflectImplSource, ReflectProvenance, ReflectTraitToImpl}; -use crate::ident::ident_or_index; -use crate::impls::impl_assertions; -use crate::{from_reflect, impls, ReflectDerive, REFLECT_ATTRIBUTE_NAME}; +use crate::{ + derive_data::{ReflectImplSource, ReflectProvenance, ReflectTraitToImpl}, + from_reflect, + ident::ident_or_index, + impls, + impls::impl_assertions, + ReflectDerive, REFLECT_ATTRIBUTE_NAME, +}; use bevy_macro_utils::fq_std::FQOption; use proc_macro::TokenStream; use proc_macro2::{Ident, Span}; use quote::{format_ident, quote, quote_spanned}; -use syn::parse::{Parse, ParseStream}; -use syn::spanned::Spanned; -use syn::token::PathSep; use syn::{ - parse_macro_input, DeriveInput, ExprPath, Generics, Member, PathArguments, Type, TypePath, + parse::{Parse, ParseStream}, + parse_macro_input, + spanned::Spanned, + token::PathSep, + DeriveInput, ExprPath, Generics, Member, PathArguments, Type, TypePath, }; /// Generates the remote wrapper type and implements all the necessary traits. @@ -162,7 +167,7 @@ fn impl_reflect_remote(input: &ReflectDerive, remote_ty: &TypePath) -> proc_macr // ``` // error[E0512]: cannot transmute between types of different sizes, or dependently-sized types // | - // | std::mem::transmute::(a) + // | core::mem::transmute::(a) // | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ // | // = note: source type: `A` (this type does not have a fixed size) @@ -191,7 +196,7 @@ fn impl_reflect_remote(input: &ReflectDerive, remote_ty: &TypePath) -> proc_macr // ``` // error[E0512]: cannot transmute between types of different sizes, or dependently-sized types // | - // | std::mem::transmute::(a) + // | core::mem::transmute::(a) // | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ // | // = note: source type: `A` (this type does not have a fixed size) diff --git a/crates/bevy_reflect/derive/src/serialization.rs b/crates/bevy_reflect/derive/src/serialization.rs index 0242947b5c91f..a1ea937894d79 100644 --- a/crates/bevy_reflect/derive/src/serialization.rs +++ b/crates/bevy_reflect/derive/src/serialization.rs @@ -1,10 +1,11 @@ -use crate::derive_data::StructField; -use crate::field_attributes::{DefaultBehavior, ReflectIgnoreBehavior}; +use crate::{ + derive_data::StructField, + field_attributes::{DefaultBehavior, ReflectIgnoreBehavior}, +}; use bevy_macro_utils::fq_std::{FQBox, FQDefault}; use quote::quote; use std::collections::HashMap; -use syn::spanned::Spanned; -use syn::Path; +use syn::{spanned::Spanned, Path}; type ReflectionIndex = usize; diff --git a/crates/bevy_reflect/derive/src/struct_utility.rs b/crates/bevy_reflect/derive/src/struct_utility.rs index df9279c87430d..09604419b6043 100644 --- a/crates/bevy_reflect/derive/src/struct_utility.rs +++ b/crates/bevy_reflect/derive/src/struct_utility.rs @@ -1,5 +1,4 @@ -use crate::derive_data::StructField; -use crate::ReflectStruct; +use crate::{derive_data::StructField, ReflectStruct}; use quote::quote; /// A helper struct for creating remote-aware field accessors. @@ -7,7 +6,7 @@ use quote::quote; /// These are "remote-aware" because when a field is a remote field, it uses a [`transmute`] internally /// to access the field. /// -/// [`transmute`]: core::mem::transmute +/// [`transmute`]: std::mem::transmute pub(crate) struct FieldAccessors { /// The referenced field accessors, such as `&self.foo`. pub fields_ref: Vec, diff --git a/crates/bevy_reflect/src/array.rs b/crates/bevy_reflect/src/array.rs index 0932a512c583d..55c62604b7860 100644 --- a/crates/bevy_reflect/src/array.rs +++ b/crates/bevy_reflect/src/array.rs @@ -1,10 +1,10 @@ -use crate::type_info::impl_type_methods; use crate::{ - self as bevy_reflect, utility::reflect_hasher, ApplyError, MaybeTyped, PartialReflect, Reflect, - ReflectKind, ReflectMut, ReflectOwned, ReflectRef, Type, TypeInfo, TypePath, + self as bevy_reflect, type_info::impl_type_methods, utility::reflect_hasher, ApplyError, + MaybeTyped, PartialReflect, Reflect, ReflectKind, ReflectMut, ReflectOwned, ReflectRef, Type, + TypeInfo, TypePath, }; use bevy_reflect_derive::impl_type_path; -use std::{ +use core::{ any::Any, fmt::{Debug, Formatter}, hash::{Hash, Hasher}, @@ -265,7 +265,7 @@ impl PartialReflect for DynamicArray { array_partial_eq(self, value) } - fn debug(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "DynamicArray(")?; array_debug(self, f)?; write!(f, ")") @@ -336,7 +336,7 @@ impl FromIterator for DynamicArray { impl IntoIterator for DynamicArray { type Item = Box; - type IntoIter = std::vec::IntoIter; + type IntoIter = alloc::vec::IntoIter; fn into_iter(self) -> Self::IntoIter { self.values.into_vec().into_iter() @@ -495,7 +495,7 @@ pub fn array_partial_eq( /// // ] /// ``` #[inline] -pub fn array_debug(dyn_array: &dyn Array, f: &mut Formatter<'_>) -> std::fmt::Result { +pub fn array_debug(dyn_array: &dyn Array, f: &mut Formatter<'_>) -> core::fmt::Result { let mut debug = f.debug_list(); for item in dyn_array.iter() { debug.entry(&item as &dyn Debug); diff --git a/crates/bevy_reflect/src/attributes.rs b/crates/bevy_reflect/src/attributes.rs index a567b71716487..b167f4a4c08b7 100644 --- a/crates/bevy_reflect/src/attributes.rs +++ b/crates/bevy_reflect/src/attributes.rs @@ -1,7 +1,9 @@ use crate::Reflect; use bevy_utils::TypeIdMap; -use core::fmt::{Debug, Formatter}; -use std::any::TypeId; +use core::{ + any::TypeId, + fmt::{Debug, Formatter}, +}; /// A collection of custom attributes for a type, field, or variant. /// @@ -14,7 +16,7 @@ use std::any::TypeId; /// /// ``` /// # use bevy_reflect::{Reflect, Typed, TypeInfo}; -/// use core::ops::RangeInclusive; +/// use std::ops::RangeInclusive; /// #[derive(Reflect)] /// struct Slider { /// #[reflect(@RangeInclusive::::new(0.0, 1.0))] @@ -154,7 +156,7 @@ macro_rules! impl_custom_attribute_methods { /// Gets a custom attribute by its [`TypeId`](std::any::TypeId). /// /// This is the dynamic equivalent of [`get_attribute`](Self::get_attribute). - pub fn get_attribute_by_id(&$self, id: ::std::any::TypeId) -> Option<&dyn $crate::Reflect> { + pub fn get_attribute_by_id(&$self, id: ::core::any::TypeId) -> Option<&dyn $crate::Reflect> { $self.custom_attributes().get_by_id(id) } @@ -164,9 +166,9 @@ macro_rules! impl_custom_attribute_methods { $self.custom_attributes().contains::() } - #[doc = concat!("Returns `true` if this ", $term, " has a custom attribute with the specified [`TypeId`](::std::any::TypeId).")] + #[doc = concat!("Returns `true` if this ", $term, " has a custom attribute with the specified [`TypeId`](::core::any::TypeId).")] #[doc = "\n\nThis is the dynamic equivalent of [`has_attribute`](Self::has_attribute)"] - pub fn has_attribute_by_id(&$self, id: ::std::any::TypeId) -> bool { + pub fn has_attribute_by_id(&$self, id: ::core::any::TypeId) -> bool { $self.custom_attributes().contains_by_id(id) } }; @@ -178,9 +180,8 @@ pub(crate) use impl_custom_attribute_methods; mod tests { use super::*; use crate as bevy_reflect; - use crate::type_info::Typed; - use crate::{TypeInfo, VariantInfo}; - use std::ops::RangeInclusive; + use crate::{type_info::Typed, TypeInfo, VariantInfo}; + use core::ops::RangeInclusive; #[derive(Reflect, PartialEq, Debug)] struct Tooltip(String); diff --git a/crates/bevy_reflect/src/enums/dynamic_enum.rs b/crates/bevy_reflect/src/enums/dynamic_enum.rs index ff8165158ae4b..b608adf713b94 100644 --- a/crates/bevy_reflect/src/enums/dynamic_enum.rs +++ b/crates/bevy_reflect/src/enums/dynamic_enum.rs @@ -6,7 +6,7 @@ use crate::{ Struct, Tuple, TypeInfo, VariantFieldIter, VariantType, }; -use std::fmt::Formatter; +use core::fmt::Formatter; /// A dynamic representation of an enum variant. #[derive(Debug, Default)] @@ -405,7 +405,7 @@ impl PartialReflect for DynamicEnum { } #[inline] - fn debug(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "DynamicEnum(")?; enum_debug(self, f)?; write!(f, ")") diff --git a/crates/bevy_reflect/src/enums/enum_trait.rs b/crates/bevy_reflect/src/enums/enum_trait.rs index f3fe336fccb55..e6f78521250f7 100644 --- a/crates/bevy_reflect/src/enums/enum_trait.rs +++ b/crates/bevy_reflect/src/enums/enum_trait.rs @@ -1,9 +1,11 @@ -use crate::attributes::{impl_custom_attribute_methods, CustomAttributes}; -use crate::type_info::impl_type_methods; -use crate::{DynamicEnum, PartialReflect, Type, TypePath, VariantInfo, VariantType}; +use crate::{ + attributes::{impl_custom_attribute_methods, CustomAttributes}, + type_info::impl_type_methods, + DynamicEnum, PartialReflect, Type, TypePath, VariantInfo, VariantType, +}; +use alloc::sync::Arc; use bevy_utils::HashMap; -use std::slice::Iter; -use std::sync::Arc; +use core::slice::Iter; /// A trait used to power [enum-like] operations via [reflection]. /// diff --git a/crates/bevy_reflect/src/enums/helpers.rs b/crates/bevy_reflect/src/enums/helpers.rs index 6771b1b1655ab..659d0bd7bc823 100644 --- a/crates/bevy_reflect/src/enums/helpers.rs +++ b/crates/bevy_reflect/src/enums/helpers.rs @@ -1,13 +1,14 @@ -use crate::PartialReflect; -use crate::{utility::reflect_hasher, Enum, ReflectRef, VariantType}; -use std::fmt::Debug; -use std::hash::{Hash, Hasher}; +use crate::{utility::reflect_hasher, Enum, PartialReflect, ReflectRef, VariantType}; +use core::{ + fmt::Debug, + hash::{Hash, Hasher}, +}; /// Returns the `u64` hash of the given [enum](Enum). #[inline] pub fn enum_hash(value: &TEnum) -> Option { let mut hasher = reflect_hasher(); - std::any::Any::type_id(value).hash(&mut hasher); + core::any::Any::type_id(value).hash(&mut hasher); value.variant_name().hash(&mut hasher); value.variant_type().hash(&mut hasher); for field in value.iter_fields() { @@ -99,7 +100,7 @@ pub fn enum_partial_eq(a: &TEnum, b: &dyn PartialReflect) /// // ) /// ``` #[inline] -pub fn enum_debug(dyn_enum: &dyn Enum, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +pub fn enum_debug(dyn_enum: &dyn Enum, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match dyn_enum.variant_type() { VariantType::Unit => f.write_str(dyn_enum.variant_name()), VariantType::Tuple => { diff --git a/crates/bevy_reflect/src/enums/variants.rs b/crates/bevy_reflect/src/enums/variants.rs index fb6baf652e743..6323e2a3c92d0 100644 --- a/crates/bevy_reflect/src/enums/variants.rs +++ b/crates/bevy_reflect/src/enums/variants.rs @@ -1,9 +1,11 @@ -use crate::attributes::{impl_custom_attribute_methods, CustomAttributes}; -use crate::{NamedField, UnnamedField}; +use crate::{ + attributes::{impl_custom_attribute_methods, CustomAttributes}, + NamedField, UnnamedField, +}; use bevy_utils::HashMap; -use std::slice::Iter; +use core::slice::Iter; -use std::sync::Arc; +use alloc::sync::Arc; use thiserror::Error; /// Describes the form of an enum variant. diff --git a/crates/bevy_reflect/src/fields.rs b/crates/bevy_reflect/src/fields.rs index 56f6a25879098..ab7c3cd34db84 100644 --- a/crates/bevy_reflect/src/fields.rs +++ b/crates/bevy_reflect/src/fields.rs @@ -1,7 +1,9 @@ -use crate::attributes::{impl_custom_attribute_methods, CustomAttributes}; -use crate::type_info::impl_type_methods; -use crate::{MaybeTyped, PartialReflect, Type, TypeInfo, TypePath}; -use std::sync::Arc; +use crate::{ + attributes::{impl_custom_attribute_methods, CustomAttributes}, + type_info::impl_type_methods, + MaybeTyped, PartialReflect, Type, TypeInfo, TypePath, +}; +use alloc::sync::Arc; /// The named field of a reflected struct. #[derive(Clone, Debug)] diff --git a/crates/bevy_reflect/src/func/args/arg.rs b/crates/bevy_reflect/src/func/args/arg.rs index 14c02eecf1175..a61ff7c184fe2 100644 --- a/crates/bevy_reflect/src/func/args/arg.rs +++ b/crates/bevy_reflect/src/func/args/arg.rs @@ -1,6 +1,8 @@ -use crate::func::args::{ArgError, FromArg, Ownership}; -use crate::{PartialReflect, Reflect, TypePath}; -use std::ops::Deref; +use crate::{ + func::args::{ArgError, FromArg, Ownership}, + PartialReflect, Reflect, TypePath, +}; +use core::ops::Deref; /// Represents an argument that can be passed to a [`DynamicFunction`] or [`DynamicFunctionMut`]. /// @@ -83,8 +85,8 @@ impl<'a> Arg<'a> { match self.value { ArgValue::Owned(arg) => arg.try_take().map_err(|arg| ArgError::UnexpectedType { index: self.index, - expected: std::borrow::Cow::Borrowed(T::type_path()), - received: std::borrow::Cow::Owned(arg.reflect_type_path().to_string()), + expected: alloc::borrow::Cow::Borrowed(T::type_path()), + received: alloc::borrow::Cow::Owned(arg.reflect_type_path().to_string()), }), ArgValue::Ref(_) => Err(ArgError::InvalidOwnership { index: self.index, @@ -126,8 +128,8 @@ impl<'a> Arg<'a> { .try_downcast_ref() .ok_or_else(|| ArgError::UnexpectedType { index: self.index, - expected: std::borrow::Cow::Borrowed(T::type_path()), - received: std::borrow::Cow::Owned(arg.reflect_type_path().to_string()), + expected: alloc::borrow::Cow::Borrowed(T::type_path()), + received: alloc::borrow::Cow::Owned(arg.reflect_type_path().to_string()), })?) } ArgValue::Mut(_) => Err(ArgError::InvalidOwnership { @@ -166,12 +168,12 @@ impl<'a> Arg<'a> { received: Ownership::Ref, }), ArgValue::Mut(arg) => { - let received = std::borrow::Cow::Owned(arg.reflect_type_path().to_string()); + let received = alloc::borrow::Cow::Owned(arg.reflect_type_path().to_string()); Ok(arg .try_downcast_mut() .ok_or_else(|| ArgError::UnexpectedType { index: self.index, - expected: std::borrow::Cow::Borrowed(T::type_path()), + expected: alloc::borrow::Cow::Borrowed(T::type_path()), received, })?) } diff --git a/crates/bevy_reflect/src/func/args/info.rs b/crates/bevy_reflect/src/func/args/info.rs index 3c1098637c17e..b1a81f3059a2e 100644 --- a/crates/bevy_reflect/src/func/args/info.rs +++ b/crates/bevy_reflect/src/func/args/info.rs @@ -1,8 +1,10 @@ use alloc::borrow::Cow; -use crate::func::args::{GetOwnership, Ownership}; -use crate::type_info::impl_type_methods; -use crate::{Type, TypePath}; +use crate::{ + func::args::{GetOwnership, Ownership}, + type_info::impl_type_methods, + Type, TypePath, +}; /// Type information for an [`Arg`] used in a [`DynamicFunction`] or [`DynamicFunctionMut`]. /// diff --git a/crates/bevy_reflect/src/func/args/list.rs b/crates/bevy_reflect/src/func/args/list.rs index 15458250f4d8e..ea35cdb2adbdc 100644 --- a/crates/bevy_reflect/src/func/args/list.rs +++ b/crates/bevy_reflect/src/func/args/list.rs @@ -1,7 +1,11 @@ -use crate::func::args::{Arg, ArgValue, FromArg}; -use crate::func::ArgError; -use crate::{PartialReflect, Reflect, TypePath}; -use std::collections::VecDeque; +use crate::{ + func::{ + args::{Arg, ArgValue, FromArg}, + ArgError, + }, + PartialReflect, Reflect, TypePath, +}; +use alloc::collections::VecDeque; /// A list of arguments that can be passed to a [`DynamicFunction`] or [`DynamicFunctionMut`]. /// diff --git a/crates/bevy_reflect/src/func/dynamic_function.rs b/crates/bevy_reflect/src/func/dynamic_function.rs index dcaa051c008b6..e6cfd9bea7022 100644 --- a/crates/bevy_reflect/src/func/dynamic_function.rs +++ b/crates/bevy_reflect/src/func/dynamic_function.rs @@ -1,19 +1,17 @@ -use crate as bevy_reflect; -use crate::__macro_exports::RegisterForReflection; -use crate::func::args::ArgList; -use crate::func::info::FunctionInfo; -use crate::func::{ - DynamicFunctionMut, Function, FunctionError, FunctionResult, IntoFunction, IntoFunctionMut, -}; -use crate::serde::Serializable; use crate::{ + self as bevy_reflect, + __macro_exports::RegisterForReflection, + func::{ + args::ArgList, info::FunctionInfo, DynamicFunctionMut, Function, FunctionError, + FunctionResult, IntoFunction, IntoFunctionMut, + }, + serde::Serializable, ApplyError, MaybeTyped, PartialReflect, Reflect, ReflectKind, ReflectMut, ReflectOwned, ReflectRef, TypeInfo, TypePath, }; -use alloc::borrow::Cow; +use alloc::{borrow::Cow, sync::Arc}; use bevy_reflect_derive::impl_type_path; use core::fmt::{Debug, Formatter}; -use std::sync::Arc; /// A dynamic representation of a function. /// diff --git a/crates/bevy_reflect/src/func/dynamic_function_mut.rs b/crates/bevy_reflect/src/func/dynamic_function_mut.rs index d39202a1f6cb5..e17f6bc67fff3 100644 --- a/crates/bevy_reflect/src/func/dynamic_function_mut.rs +++ b/crates/bevy_reflect/src/func/dynamic_function_mut.rs @@ -1,9 +1,10 @@ use alloc::borrow::Cow; use core::fmt::{Debug, Formatter}; -use crate::func::args::ArgList; -use crate::func::info::FunctionInfo; -use crate::func::{DynamicFunction, FunctionError, FunctionResult, IntoFunctionMut}; +use crate::func::{ + args::ArgList, info::FunctionInfo, DynamicFunction, FunctionError, FunctionResult, + IntoFunctionMut, +}; /// A dynamic representation of a function. /// diff --git a/crates/bevy_reflect/src/func/error.rs b/crates/bevy_reflect/src/func/error.rs index a37123f1b6cba..3d4f3d0a8b371 100644 --- a/crates/bevy_reflect/src/func/error.rs +++ b/crates/bevy_reflect/src/func/error.rs @@ -1,5 +1,4 @@ -use crate::func::args::ArgError; -use crate::func::Return; +use crate::func::{args::ArgError, Return}; use alloc::borrow::Cow; use thiserror::Error; diff --git a/crates/bevy_reflect/src/func/info.rs b/crates/bevy_reflect/src/func/info.rs index 8627424dd0188..39accdf52dceb 100644 --- a/crates/bevy_reflect/src/func/info.rs +++ b/crates/bevy_reflect/src/func/info.rs @@ -2,9 +2,11 @@ use alloc::borrow::Cow; use bevy_utils::all_tuples; -use crate::func::args::{ArgInfo, GetOwnership, Ownership}; -use crate::type_info::impl_type_methods; -use crate::{Type, TypePath}; +use crate::{ + func::args::{ArgInfo, GetOwnership, Ownership}, + type_info::impl_type_methods, + Type, TypePath, +}; /// Type information for a [`DynamicFunction`] or [`DynamicFunctionMut`]. /// @@ -351,7 +353,7 @@ all_tuples!(impl_typed_function, 0, 15, Arg, arg); /// /// [`type_name`]: std::any::type_name fn create_info() -> FunctionInfo { - let name = std::any::type_name::(); + let name = core::any::type_name::(); if name.ends_with("{{closure}}") || name.starts_with("fn(") { FunctionInfo::anonymous() @@ -372,7 +374,7 @@ mod tests { // Sanity check: assert_eq!( - std::any::type_name_of_val(&add), + core::any::type_name_of_val(&add), "bevy_reflect::func::info::tests::should_create_function_info::add" ); @@ -396,7 +398,7 @@ mod tests { let add = add as fn(i32, i32) -> i32; // Sanity check: - assert_eq!(std::any::type_name_of_val(&add), "fn(i32, i32) -> i32"); + assert_eq!(core::any::type_name_of_val(&add), "fn(i32, i32) -> i32"); let info = add.get_function_info(); assert!(info.name().is_none()); @@ -412,7 +414,7 @@ mod tests { // Sanity check: assert_eq!( - std::any::type_name_of_val(&add), + core::any::type_name_of_val(&add), "bevy_reflect::func::info::tests::should_create_anonymous_function_info::{{closure}}" ); @@ -431,7 +433,7 @@ mod tests { // Sanity check: assert_eq!( - std::any::type_name_of_val(&add), + core::any::type_name_of_val(&add), "bevy_reflect::func::info::tests::should_create_closure_info::{{closure}}" ); diff --git a/crates/bevy_reflect/src/func/mod.rs b/crates/bevy_reflect/src/func/mod.rs index 0a5b1d789598a..2811f5c22663a 100644 --- a/crates/bevy_reflect/src/func/mod.rs +++ b/crates/bevy_reflect/src/func/mod.rs @@ -107,14 +107,14 @@ //! //! let mut registry = FunctionRegistry::default(); //! -//! // You can register functions and methods by their `std::any::type_name`: +//! // You can register functions and methods by their `core::any::type_name`: //! registry.register(add).unwrap(); //! //! // Or you can register them by a custom name: //! registry.register_with_name("mul", |a: i32, b: i32| a * b).unwrap(); //! //! // You can then retrieve and call these functions by name: -//! let reflect_add = registry.get(std::any::type_name_of_val(&add)).unwrap(); +//! let reflect_add = registry.get(core::any::type_name_of_val(&add)).unwrap(); //! let value = reflect_add.call(ArgList::default().push_owned(10_i32).push_owned(5_i32)).unwrap(); //! assert_eq!(value.unwrap_owned().try_downcast_ref::(), Some(&15)); //! @@ -159,8 +159,10 @@ mod return_type; mod tests { use alloc::borrow::Cow; - use crate::func::args::{ArgError, ArgList, Ownership}; - use crate::TypePath; + use crate::{ + func::args::{ArgError, ArgList, Ownership}, + TypePath, + }; use super::*; diff --git a/crates/bevy_reflect/src/func/reflect_fn.rs b/crates/bevy_reflect/src/func/reflect_fn.rs index 1dc1d31302309..6e29fd4e075eb 100644 --- a/crates/bevy_reflect/src/func/reflect_fn.rs +++ b/crates/bevy_reflect/src/func/reflect_fn.rs @@ -1,9 +1,12 @@ use bevy_utils::all_tuples; -use crate::func::args::FromArg; -use crate::func::macros::count_tokens; -use crate::func::{ArgList, FunctionError, FunctionResult, IntoReturn, ReflectFnMut}; -use crate::{Reflect, TypePath}; +use crate::{ + func::{ + args::FromArg, macros::count_tokens, ArgList, FunctionError, FunctionResult, IntoReturn, + ReflectFnMut, + }, + Reflect, TypePath, +}; /// A reflection-based version of the [`Fn`] trait. /// diff --git a/crates/bevy_reflect/src/func/reflect_fn_mut.rs b/crates/bevy_reflect/src/func/reflect_fn_mut.rs index a6a6bd6e9fa58..be73aca79b6bb 100644 --- a/crates/bevy_reflect/src/func/reflect_fn_mut.rs +++ b/crates/bevy_reflect/src/func/reflect_fn_mut.rs @@ -1,9 +1,11 @@ use bevy_utils::all_tuples; -use crate::func::args::FromArg; -use crate::func::macros::count_tokens; -use crate::func::{ArgList, FunctionError, FunctionResult, IntoReturn}; -use crate::{Reflect, TypePath}; +use crate::{ + func::{ + args::FromArg, macros::count_tokens, ArgList, FunctionError, FunctionResult, IntoReturn, + }, + Reflect, TypePath, +}; /// A reflection-based version of the [`FnMut`] trait. /// diff --git a/crates/bevy_reflect/src/func/registry.rs b/crates/bevy_reflect/src/func/registry.rs index 2c88ef509a09b..9ad51557da6fe 100644 --- a/crates/bevy_reflect/src/func/registry.rs +++ b/crates/bevy_reflect/src/func/registry.rs @@ -1,6 +1,6 @@ -use alloc::borrow::Cow; +use alloc::{borrow::Cow, sync::Arc}; use core::fmt::Debug; -use std::sync::{Arc, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard}; +use std::sync::{PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard}; use bevy_utils::HashMap; @@ -366,7 +366,7 @@ mod tests { let mut registry = FunctionRegistry::default(); registry.register(foo).unwrap(); - let function = registry.get(std::any::type_name_of_val(&foo)).unwrap(); + let function = registry.get(core::any::type_name_of_val(&foo)).unwrap(); let value = function.call(ArgList::new()).unwrap().unwrap_owned(); assert_eq!(value.try_downcast_ref::(), Some(&123)); } @@ -435,7 +435,7 @@ mod tests { 321 } - let name = std::any::type_name_of_val(&foo); + let name = core::any::type_name_of_val(&foo); let mut registry = FunctionRegistry::default(); registry.register(foo).unwrap(); @@ -462,7 +462,7 @@ mod tests { 321 } - let name = std::any::type_name_of_val(&foo); + let name = core::any::type_name_of_val(&foo); let mut registry = FunctionRegistry::default(); registry.register(foo).unwrap(); @@ -488,7 +488,7 @@ mod tests { let args = ArgList::new().push_owned(25_i32).push_owned(75_i32); let result = registry - .call(std::any::type_name_of_val(&add), args) + .call(core::any::type_name_of_val(&add), args) .unwrap(); let value = result.unwrap().unwrap_owned(); assert_eq!(value.try_downcast_ref::(), Some(&100)); diff --git a/crates/bevy_reflect/src/impls/petgraph.rs b/crates/bevy_reflect/src/impls/petgraph.rs index c4bdaa83e1a72..f9ab09e1b9f26 100644 --- a/crates/bevy_reflect/src/impls/petgraph.rs +++ b/crates/bevy_reflect/src/impls/petgraph.rs @@ -9,7 +9,7 @@ impl_reflect_opaque!(::petgraph::graph::NodeIndex( Deserialize )); impl_reflect_opaque!(::petgraph::graph::DiGraph< - N: ::std::clone::Clone, - E: ::std::clone::Clone, + N: ::core::clone::Clone, + E: ::core::clone::Clone, Ix: ::petgraph::graph::IndexType >()); diff --git a/crates/bevy_reflect/src/impls/smallvec.rs b/crates/bevy_reflect/src/impls/smallvec.rs index fa3d66b6bc75c..7fa43e3308dc0 100644 --- a/crates/bevy_reflect/src/impls/smallvec.rs +++ b/crates/bevy_reflect/src/impls/smallvec.rs @@ -1,13 +1,13 @@ use bevy_reflect_derive::impl_type_path; use smallvec::{Array as SmallArray, SmallVec}; -use std::any::Any; +use core::any::Any; -use crate::utility::GenericTypeInfoCell; use crate::{ - self as bevy_reflect, ApplyError, FromReflect, FromType, GetTypeRegistration, List, ListInfo, - ListIter, MaybeTyped, PartialReflect, Reflect, ReflectFromPtr, ReflectKind, ReflectMut, - ReflectOwned, ReflectRef, TypeInfo, TypePath, TypeRegistration, Typed, + self as bevy_reflect, utility::GenericTypeInfoCell, ApplyError, FromReflect, FromType, + GetTypeRegistration, List, ListInfo, ListIter, MaybeTyped, PartialReflect, Reflect, + ReflectFromPtr, ReflectKind, ReflectMut, ReflectOwned, ReflectRef, TypeInfo, TypePath, + TypeRegistration, Typed, }; impl List for SmallVec diff --git a/crates/bevy_reflect/src/impls/smol_str.rs b/crates/bevy_reflect/src/impls/smol_str.rs index 11e5f9da3747a..7a0f99e2ed7fe 100644 --- a/crates/bevy_reflect/src/impls/smol_str.rs +++ b/crates/bevy_reflect/src/impls/smol_str.rs @@ -1,5 +1,6 @@ -use crate::{self as bevy_reflect}; -use crate::{std_traits::ReflectDefault, ReflectDeserialize, ReflectSerialize}; +use crate::{ + self as bevy_reflect, std_traits::ReflectDefault, ReflectDeserialize, ReflectSerialize, +}; use bevy_reflect_derive::impl_reflect_opaque; impl_reflect_opaque!(::smol_str::SmolStr( diff --git a/crates/bevy_reflect/src/impls/std.rs b/crates/bevy_reflect/src/impls/std.rs index e62b3b4e14c7c..dba41e003f695 100644 --- a/crates/bevy_reflect/src/impls/std.rs +++ b/crates/bevy_reflect/src/impls/std.rs @@ -1,28 +1,26 @@ // Temporary workaround for impl_reflect!(Option/Result false-positive #![allow(unused_qualifications)] -use crate::std_traits::ReflectDefault; -use crate::utility::{ - reflect_hasher, GenericTypeInfoCell, GenericTypePathCell, NonGenericTypeInfoCell, -}; use crate::{ self as bevy_reflect, impl_type_path, map_apply, map_partial_eq, map_try_apply, - reflect::impl_full_reflect, set_apply, set_partial_eq, set_try_apply, ApplyError, Array, - ArrayInfo, ArrayIter, DynamicMap, DynamicSet, DynamicTypePath, FromReflect, FromType, - GetTypeRegistration, List, ListInfo, ListIter, Map, MapInfo, MapIter, MaybeTyped, OpaqueInfo, - PartialReflect, Reflect, ReflectDeserialize, ReflectFromPtr, ReflectFromReflect, ReflectKind, - ReflectMut, ReflectOwned, ReflectRef, ReflectSerialize, Set, SetInfo, TypeInfo, TypePath, - TypeRegistration, TypeRegistry, Typed, + prelude::ReflectDefault, + reflect::impl_full_reflect, + set_apply, set_partial_eq, set_try_apply, + utility::{reflect_hasher, GenericTypeInfoCell, GenericTypePathCell, NonGenericTypeInfoCell}, + ApplyError, Array, ArrayInfo, ArrayIter, DynamicMap, DynamicSet, DynamicTypePath, FromReflect, + FromType, GetTypeRegistration, List, ListInfo, ListIter, Map, MapInfo, MapIter, MaybeTyped, + OpaqueInfo, PartialReflect, Reflect, ReflectDeserialize, ReflectFromPtr, ReflectFromReflect, + ReflectKind, ReflectMut, ReflectOwned, ReflectRef, ReflectSerialize, Set, SetInfo, TypeInfo, + TypePath, TypeRegistration, TypeRegistry, Typed, }; +use alloc::{borrow::Cow, collections::VecDeque}; use bevy_reflect_derive::{impl_reflect, impl_reflect_opaque}; -use std::fmt; -use std::{ +use core::{ any::Any, - borrow::Cow, - collections::VecDeque, + fmt, hash::{BuildHasher, Hash, Hasher}, - path::Path, }; +use std::path::Path; impl_reflect_opaque!(bool( Debug, @@ -99,15 +97,15 @@ impl_reflect_opaque!(::std::path::PathBuf( Deserialize, Default )); -impl_reflect_opaque!(::std::any::TypeId(Debug, Hash, PartialEq,)); -impl_reflect_opaque!(::std::collections::BTreeSet()); +impl_reflect_opaque!(::core::any::TypeId(Debug, Hash, PartialEq,)); +impl_reflect_opaque!(::alloc::collections::BTreeSet()); impl_reflect_opaque!(::core::ops::Range()); impl_reflect_opaque!(::core::ops::RangeInclusive()); impl_reflect_opaque!(::core::ops::RangeFrom()); impl_reflect_opaque!(::core::ops::RangeTo()); impl_reflect_opaque!(::core::ops::RangeToInclusive()); impl_reflect_opaque!(::core::ops::RangeFull()); -impl_reflect_opaque!(::std::ops::Bound()); +impl_reflect_opaque!(::core::ops::Bound()); impl_reflect_opaque!(::bevy_utils::Duration( Debug, Hash, @@ -203,7 +201,7 @@ impl_reflect_opaque!(::core::num::NonZeroI8( )); impl_reflect_opaque!(::core::num::Wrapping()); impl_reflect_opaque!(::core::num::Saturating()); -impl_reflect_opaque!(::std::sync::Arc); +impl_reflect_opaque!(::alloc::sync::Arc); // `Serialize` and `Deserialize` only for platforms supported by serde: // https://github.com/serde-rs/serde/blob/3ffb86fc70efd3d329519e2dddfa306cc04f167c/serde/src/de/impls.rs#L1732 @@ -346,48 +344,48 @@ macro_rules! impl_reflect_for_atomic { } impl_reflect_for_atomic!( - ::std::sync::atomic::AtomicIsize, - ::std::sync::atomic::Ordering::SeqCst + ::core::sync::atomic::AtomicIsize, + ::core::sync::atomic::Ordering::SeqCst ); impl_reflect_for_atomic!( - ::std::sync::atomic::AtomicUsize, - ::std::sync::atomic::Ordering::SeqCst + ::core::sync::atomic::AtomicUsize, + ::core::sync::atomic::Ordering::SeqCst ); impl_reflect_for_atomic!( - ::std::sync::atomic::AtomicI64, - ::std::sync::atomic::Ordering::SeqCst + ::core::sync::atomic::AtomicI64, + ::core::sync::atomic::Ordering::SeqCst ); impl_reflect_for_atomic!( - ::std::sync::atomic::AtomicU64, - ::std::sync::atomic::Ordering::SeqCst + ::core::sync::atomic::AtomicU64, + ::core::sync::atomic::Ordering::SeqCst ); impl_reflect_for_atomic!( - ::std::sync::atomic::AtomicI32, - ::std::sync::atomic::Ordering::SeqCst + ::core::sync::atomic::AtomicI32, + ::core::sync::atomic::Ordering::SeqCst ); impl_reflect_for_atomic!( - ::std::sync::atomic::AtomicU32, - ::std::sync::atomic::Ordering::SeqCst + ::core::sync::atomic::AtomicU32, + ::core::sync::atomic::Ordering::SeqCst ); impl_reflect_for_atomic!( - ::std::sync::atomic::AtomicI16, - ::std::sync::atomic::Ordering::SeqCst + ::core::sync::atomic::AtomicI16, + ::core::sync::atomic::Ordering::SeqCst ); impl_reflect_for_atomic!( - ::std::sync::atomic::AtomicU16, - ::std::sync::atomic::Ordering::SeqCst + ::core::sync::atomic::AtomicU16, + ::core::sync::atomic::Ordering::SeqCst ); impl_reflect_for_atomic!( - ::std::sync::atomic::AtomicI8, - ::std::sync::atomic::Ordering::SeqCst + ::core::sync::atomic::AtomicI8, + ::core::sync::atomic::Ordering::SeqCst ); impl_reflect_for_atomic!( - ::std::sync::atomic::AtomicU8, - ::std::sync::atomic::Ordering::SeqCst + ::core::sync::atomic::AtomicU8, + ::core::sync::atomic::Ordering::SeqCst ); impl_reflect_for_atomic!( - ::std::sync::atomic::AtomicBool, - ::std::sync::atomic::Ordering::SeqCst + ::core::sync::atomic::AtomicBool, + ::core::sync::atomic::Ordering::SeqCst ); macro_rules! impl_reflect_for_veclike { @@ -1054,7 +1052,7 @@ crate::func::macros::impl_function_traits!(::bevy_utils::hashbrown::HashSet ); -impl Map for ::std::collections::BTreeMap +impl Map for ::alloc::collections::BTreeMap where K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Ord, V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration, @@ -1153,7 +1151,7 @@ where } } -impl PartialReflect for ::std::collections::BTreeMap +impl PartialReflect for ::alloc::collections::BTreeMap where K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Ord, V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration, @@ -1219,13 +1217,13 @@ where } impl_full_reflect!( - for ::std::collections::BTreeMap + for ::alloc::collections::BTreeMap where K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Ord, V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration, ); -impl Typed for ::std::collections::BTreeMap +impl Typed for ::alloc::collections::BTreeMap where K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Ord, V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration, @@ -1236,7 +1234,7 @@ where } } -impl GetTypeRegistration for ::std::collections::BTreeMap +impl GetTypeRegistration for ::alloc::collections::BTreeMap where K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Ord, V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration, @@ -1248,7 +1246,7 @@ where } } -impl FromReflect for ::std::collections::BTreeMap +impl FromReflect for ::alloc::collections::BTreeMap where K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Ord, V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration, @@ -1268,9 +1266,9 @@ where } } -impl_type_path!(::std::collections::BTreeMap); +impl_type_path!(::alloc::collections::BTreeMap); #[cfg(feature = "functions")] -crate::func::macros::impl_function_traits!(::std::collections::BTreeMap; +crate::func::macros::impl_function_traits!(::alloc::collections::BTreeMap; < K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Ord, V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration @@ -2225,16 +2223,14 @@ crate::func::macros::impl_function_traits!(Cow<'static, Path>); #[cfg(test)] mod tests { - use crate::{self as bevy_reflect, PartialReflect}; use crate::{ - Enum, FromReflect, Reflect, ReflectSerialize, TypeInfo, TypeRegistry, Typed, VariantInfo, - VariantType, + self as bevy_reflect, Enum, FromReflect, PartialReflect, Reflect, ReflectSerialize, + TypeInfo, TypeRegistry, Typed, VariantInfo, VariantType, }; - use bevy_utils::HashMap; - use bevy_utils::{Duration, Instant}; + use alloc::collections::BTreeMap; + use bevy_utils::{Duration, HashMap, Instant}; + use core::f32::consts::{PI, TAU}; use static_assertions::assert_impl_all; - use std::collections::BTreeMap; - use std::f32::consts::{PI, TAU}; use std::path::Path; #[test] @@ -2243,7 +2239,7 @@ mod tests { type_registry.register::(); let reflect_serialize = type_registry - .get_type_data::(std::any::TypeId::of::()) + .get_type_data::(core::any::TypeId::of::()) .unwrap(); let _serializable = reflect_serialize.get_serializable(&Duration::ZERO); } @@ -2446,11 +2442,11 @@ mod tests { #[test] fn nonzero_usize_impl_reflect_from_reflect() { - let a: &dyn PartialReflect = &std::num::NonZero::::new(42).unwrap(); - let b: &dyn PartialReflect = &std::num::NonZero::::new(42).unwrap(); + let a: &dyn PartialReflect = &core::num::NonZero::::new(42).unwrap(); + let b: &dyn PartialReflect = &core::num::NonZero::::new(42).unwrap(); assert!(a.reflect_partial_eq(b).unwrap_or_default()); - let forty_two: std::num::NonZero = FromReflect::from_reflect(a).unwrap(); - assert_eq!(forty_two, std::num::NonZero::::new(42).unwrap()); + let forty_two: core::num::NonZero = FromReflect::from_reflect(a).unwrap(); + assert_eq!(forty_two, core::num::NonZero::::new(42).unwrap()); } #[test] @@ -2469,8 +2465,8 @@ mod tests { #[test] fn type_id_should_from_reflect() { - let type_id = std::any::TypeId::of::(); - let output = ::from_reflect(&type_id).unwrap(); + let type_id = core::any::TypeId::of::(); + let output = ::from_reflect(&type_id).unwrap(); assert_eq!(type_id, output); } diff --git a/crates/bevy_reflect/src/kind.rs b/crates/bevy_reflect/src/kind.rs index 079f3150783ae..114be8ed3830c 100644 --- a/crates/bevy_reflect/src/kind.rs +++ b/crates/bevy_reflect/src/kind.rs @@ -67,8 +67,8 @@ pub enum ReflectKind { Opaque, } -impl std::fmt::Display for ReflectKind { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Display for ReflectKind { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { ReflectKind::Struct => f.pad("struct"), ReflectKind::TupleStruct => f.pad("tuple struct"), diff --git a/crates/bevy_reflect/src/lib.rs b/crates/bevy_reflect/src/lib.rs index 4bdc65b318acf..21f96f079c0f5 100644 --- a/crates/bevy_reflect/src/lib.rs +++ b/crates/bevy_reflect/src/lib.rs @@ -333,7 +333,7 @@ //! registry.register::(); //! registry.register_type_data::(); //! -//! let registration = registry.get(std::any::TypeId::of::()).unwrap(); +//! let registration = registry.get(core::any::TypeId::of::()).unwrap(); //! let reflect_default = registration.data::().unwrap(); //! //! let new_value: Box = reflect_default.default(); @@ -542,6 +542,8 @@ //! [`bevy_reflect_derive/documentation`]: bevy_reflect_derive //! [derive `Reflect`]: derive@crate::Reflect +extern crate alloc; + mod array; mod fields; mod from_reflect; @@ -592,6 +594,7 @@ pub mod utility; /// This includes the most common types in this crate, re-exported for your convenience. pub mod prelude { pub use crate::std_traits::*; + #[doc(hidden)] pub use crate::{ reflect_trait, FromReflect, GetField, GetPath, GetTupleStructField, PartialReflect, @@ -625,8 +628,6 @@ pub use type_registry::*; pub use bevy_reflect_derive::*; pub use erased_serde; -extern crate alloc; - /// Exports used by the reflection macros. /// /// These are not meant to be used directly and are subject to breaking changes. @@ -679,26 +680,27 @@ pub mod __macro_exports { #[allow(clippy::disallowed_types, clippy::approx_constant)] mod tests { use ::serde::{de::DeserializeSeed, Deserialize, Serialize}; + use alloc::borrow::Cow; use bevy_utils::HashMap; + use core::{ + any::TypeId, + fmt::{Debug, Formatter}, + hash::Hash, + marker::PhantomData, + }; use disqualified::ShortName; use ron::{ ser::{to_string_pretty, PrettyConfig}, Deserializer, }; use static_assertions::{assert_impl_all, assert_not_impl_all}; - use std::{ - any::TypeId, - borrow::Cow, - fmt::{Debug, Formatter}, - hash::Hash, - marker::PhantomData, - }; - use super::prelude::*; - use super::*; + use super::{prelude::*, *}; use crate as bevy_reflect; - use crate::serde::{ReflectDeserializer, ReflectSerializer}; - use crate::utility::GenericTypePathCell; + use crate::{ + serde::{ReflectDeserializer, ReflectSerializer}, + utility::GenericTypePathCell, + }; #[test] fn try_apply_should_detect_kinds() { @@ -1797,7 +1799,7 @@ mod tests { let info = MyCowStr::type_info().as_opaque().unwrap(); assert!(info.is::()); - assert_eq!(std::any::type_name::(), info.type_path()); + assert_eq!(core::any::type_name::(), info.type_path()); let value: &dyn Reflect = &Cow::<'static, str>::Owned("Hello!".to_string()); let info = value.reflect_type_info(); @@ -1811,8 +1813,8 @@ mod tests { assert!(info.is::()); assert!(info.item_ty().is::()); assert!(info.item_info().unwrap().is::()); - assert_eq!(std::any::type_name::(), info.type_path()); - assert_eq!(std::any::type_name::(), info.item_ty().path()); + assert_eq!(core::any::type_name::(), info.type_path()); + assert_eq!(core::any::type_name::(), info.item_ty().path()); let value: &dyn Reflect = &Cow::<'static, [u8]>::Owned(vec![0, 1, 2, 3]); let info = value.reflect_type_info(); @@ -2093,7 +2095,7 @@ mod tests { #[reflect(Debug)] struct CustomDebug; impl Debug for CustomDebug { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { f.write_str("Cool debug!") } } @@ -2161,7 +2163,7 @@ bevy_reflect::tests::Test { struct Foo(i32); impl Debug for Foo { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "Foo") } } @@ -2182,7 +2184,7 @@ bevy_reflect::tests::Test { a: u32, } - fn custom_debug(_x: &Foo, f: &mut Formatter<'_>) -> std::fmt::Result { + fn custom_debug(_x: &Foo, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "123") } @@ -2224,7 +2226,7 @@ bevy_reflect::tests::Test { fn should_allow_multiple_custom_where() { #[derive(Reflect)] #[reflect(where T: Default)] - #[reflect(where U: std::ops::Add)] + #[reflect(where U: core::ops::Add)] struct Foo(T, U); #[derive(Reflect)] @@ -2347,7 +2349,7 @@ bevy_reflect::tests::Test { impl TypePath for Foo { fn type_path() -> &'static str { - std::any::type_name::() + core::any::type_name::() } fn short_type_path() -> &'static str { @@ -2773,7 +2775,7 @@ bevy_reflect::tests::Test { #[test] fn should_reflect_nested_remote_enum() { mod external_crate { - use std::fmt::Debug; + use core::fmt::Debug; #[derive(Debug)] pub enum TheirOuter { diff --git a/crates/bevy_reflect/src/list.rs b/crates/bevy_reflect/src/list.rs index 784d00231f4a1..3844605b0b9ae 100644 --- a/crates/bevy_reflect/src/list.rs +++ b/crates/bevy_reflect/src/list.rs @@ -1,14 +1,15 @@ -use std::any::Any; -use std::fmt::{Debug, Formatter}; -use std::hash::{Hash, Hasher}; +use core::{ + any::Any, + fmt::{Debug, Formatter}, + hash::{Hash, Hasher}, +}; use bevy_reflect_derive::impl_type_path; -use crate::type_info::impl_type_methods; -use crate::utility::reflect_hasher; use crate::{ - self as bevy_reflect, ApplyError, FromReflect, MaybeTyped, PartialReflect, Reflect, - ReflectKind, ReflectMut, ReflectOwned, ReflectRef, Type, TypeInfo, TypePath, + self as bevy_reflect, type_info::impl_type_methods, utility::reflect_hasher, ApplyError, + FromReflect, MaybeTyped, PartialReflect, Reflect, ReflectKind, ReflectMut, ReflectOwned, + ReflectRef, Type, TypeInfo, TypePath, }; /// A trait used to power [list-like] operations via [reflection]. @@ -319,7 +320,7 @@ impl PartialReflect for DynamicList { list_partial_eq(self, value) } - fn debug(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "DynamicList(")?; list_debug(self, f)?; write!(f, ")") @@ -334,7 +335,7 @@ impl PartialReflect for DynamicList { impl_type_path!((in bevy_reflect) DynamicList); impl Debug for DynamicList { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { self.debug(f) } } @@ -359,7 +360,7 @@ impl FromIterator for DynamicList { impl IntoIterator for DynamicList { type Item = Box; - type IntoIter = std::vec::IntoIter; + type IntoIter = alloc::vec::IntoIter; fn into_iter(self) -> Self::IntoIter { self.values.into_iter() @@ -508,7 +509,7 @@ pub fn list_partial_eq(a: &L, b: &dyn PartialReflect) -> Optio /// // ] /// ``` #[inline] -pub fn list_debug(dyn_list: &dyn List, f: &mut Formatter<'_>) -> std::fmt::Result { +pub fn list_debug(dyn_list: &dyn List, f: &mut Formatter<'_>) -> core::fmt::Result { let mut debug = f.debug_list(); for item in dyn_list.iter() { debug.entry(&item as &dyn Debug); @@ -520,7 +521,7 @@ pub fn list_debug(dyn_list: &dyn List, f: &mut Formatter<'_>) -> std::fmt::Resul mod tests { use super::DynamicList; use crate::Reflect; - use std::assert_eq; + use core::assert_eq; #[test] fn test_into_iter() { diff --git a/crates/bevy_reflect/src/map.rs b/crates/bevy_reflect/src/map.rs index c21762f7cbd1d..ad1fcdd73e78c 100644 --- a/crates/bevy_reflect/src/map.rs +++ b/crates/bevy_reflect/src/map.rs @@ -1,12 +1,11 @@ -use std::fmt::{Debug, Formatter}; +use core::fmt::{Debug, Formatter}; use bevy_reflect_derive::impl_type_path; use bevy_utils::{Entry, HashMap}; -use crate::type_info::impl_type_methods; use crate::{ - self as bevy_reflect, ApplyError, MaybeTyped, PartialReflect, Reflect, ReflectKind, ReflectMut, - ReflectOwned, ReflectRef, Type, TypeInfo, TypePath, + self as bevy_reflect, type_info::impl_type_methods, ApplyError, MaybeTyped, PartialReflect, + Reflect, ReflectKind, ReflectMut, ReflectOwned, ReflectRef, Type, TypeInfo, TypePath, }; /// A trait used to power [map-like] operations via [reflection]. @@ -292,7 +291,7 @@ impl Map for DynamicMap { { Entry::Occupied(entry) => { let (_old_key, old_value) = self.values.get_mut(*entry.get()).unwrap(); - std::mem::swap(old_value, &mut value); + core::mem::swap(old_value, &mut value); Some(value) } Entry::Vacant(entry) => { @@ -377,7 +376,7 @@ impl PartialReflect for DynamicMap { map_partial_eq(self, value) } - fn debug(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "DynamicMap(")?; map_debug(self, f)?; write!(f, ")") @@ -392,7 +391,7 @@ impl PartialReflect for DynamicMap { impl_type_path!((in bevy_reflect) DynamicMap); impl Debug for DynamicMap { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { self.debug(f) } } @@ -450,7 +449,7 @@ impl FromIterator<(K, V)> for DynamicMap { impl IntoIterator for DynamicMap { type Item = (Box, Box); - type IntoIter = std::vec::IntoIter; + type IntoIter = alloc::vec::IntoIter; fn into_iter(self) -> Self::IntoIter { self.values.into_iter() @@ -519,7 +518,7 @@ pub fn map_partial_eq(a: &M, b: &dyn PartialReflect) -> Option< /// // } /// ``` #[inline] -pub fn map_debug(dyn_map: &dyn Map, f: &mut Formatter<'_>) -> std::fmt::Result { +pub fn map_debug(dyn_map: &dyn Map, f: &mut Formatter<'_>) -> core::fmt::Result { let mut debug = f.debug_map(); for (key, value) in dyn_map.iter() { debug.entry(&key as &dyn Debug, &value as &dyn Debug); @@ -567,8 +566,7 @@ pub fn map_try_apply(a: &mut M, b: &dyn PartialReflect) -> Result<(), Ap #[cfg(test)] mod tests { - use super::DynamicMap; - use super::Map; + use super::{DynamicMap, Map}; #[test] fn test_into_iter() { diff --git a/crates/bevy_reflect/src/path/access.rs b/crates/bevy_reflect/src/path/access.rs index 4648b9dfa6349..c0a141fcbaee1 100644 --- a/crates/bevy_reflect/src/path/access.rs +++ b/crates/bevy_reflect/src/path/access.rs @@ -1,6 +1,7 @@ //! Representation for individual element accesses within a path. -use std::{borrow::Cow, fmt}; +use alloc::borrow::Cow; +use core::fmt; use super::error::AccessErrorKind; use crate::{AccessError, PartialReflect, ReflectKind, ReflectMut, ReflectRef, VariantType}; diff --git a/crates/bevy_reflect/src/path/error.rs b/crates/bevy_reflect/src/path/error.rs index d25d1670492f6..0e900c8315ecb 100644 --- a/crates/bevy_reflect/src/path/error.rs +++ b/crates/bevy_reflect/src/path/error.rs @@ -1,4 +1,4 @@ -use std::fmt; +use core::fmt; use super::Access; use crate::{ReflectKind, VariantType}; @@ -126,4 +126,4 @@ impl fmt::Display for AccessError<'_> { } } } -impl std::error::Error for AccessError<'_> {} +impl core::error::Error for AccessError<'_> {} diff --git a/crates/bevy_reflect/src/path/mod.rs b/crates/bevy_reflect/src/path/mod.rs index ced501c15424d..f4b6504c53ccb 100644 --- a/crates/bevy_reflect/src/path/mod.rs +++ b/crates/bevy_reflect/src/path/mod.rs @@ -9,7 +9,7 @@ pub use parse::ParseError; use parse::PathParser; use crate::{PartialReflect, Reflect}; -use std::fmt; +use core::fmt; use thiserror::Error; type PathResult<'a, T> = Result>; @@ -493,13 +493,13 @@ impl fmt::Display for ParsedPath { Ok(()) } } -impl std::ops::Index for ParsedPath { +impl core::ops::Index for ParsedPath { type Output = OffsetAccess; fn index(&self, index: usize) -> &Self::Output { &self.0[index] } } -impl std::ops::IndexMut for ParsedPath { +impl core::ops::IndexMut for ParsedPath { fn index_mut(&mut self, index: usize) -> &mut Self::Output { &mut self.0[index] } diff --git a/crates/bevy_reflect/src/path/parse.rs b/crates/bevy_reflect/src/path/parse.rs index 8195a23a31cb4..0c85c4b93331a 100644 --- a/crates/bevy_reflect/src/path/parse.rs +++ b/crates/bevy_reflect/src/path/parse.rs @@ -1,4 +1,4 @@ -use std::{ +use core::{ fmt::{self, Write}, num::ParseIntError, str::from_utf8_unchecked, diff --git a/crates/bevy_reflect/src/reflect.rs b/crates/bevy_reflect/src/reflect.rs index 0c8550107c96b..b572780896375 100644 --- a/crates/bevy_reflect/src/reflect.rs +++ b/crates/bevy_reflect/src/reflect.rs @@ -3,7 +3,7 @@ use crate::{ tuple_debug, tuple_struct_debug, DynamicTypePath, DynamicTyped, OpaqueInfo, ReflectKind, ReflectKindMismatchError, ReflectMut, ReflectOwned, ReflectRef, TypeInfo, TypePath, Typed, }; -use std::{ +use core::{ any::{Any, TypeId}, fmt::Debug, }; @@ -253,7 +253,7 @@ where /// [`List`]: crate::List /// [`Map`]: crate::Map /// [type path]: TypePath::type_path - fn debug(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn debug(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self.reflect_ref() { ReflectRef::Struct(dyn_struct) => struct_debug(dyn_struct, f), ReflectRef::TupleStruct(dyn_tuple_struct) => tuple_struct_debug(dyn_tuple_struct, f), @@ -408,7 +408,7 @@ impl dyn PartialReflect { } impl Debug for dyn PartialReflect { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.debug(f) } } @@ -488,7 +488,7 @@ impl dyn Reflect { } impl Debug for dyn Reflect { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.debug(f) } } @@ -515,15 +515,15 @@ impl TypePath for dyn Reflect { macro_rules! impl_full_reflect { ($(<$($id:ident),* $(,)?>)? for $ty:ty $(where $($tt:tt)*)?) => { impl $(<$($id),*>)? $crate::Reflect for $ty $(where $($tt)*)? { - fn into_any(self: Box) -> Box { + fn into_any(self: Box) -> Box { self } - fn as_any(&self) -> &dyn ::std::any::Any { + fn as_any(&self) -> &dyn ::core::any::Any { self } - fn as_any_mut(&mut self) -> &mut dyn ::std::any::Any { + fn as_any_mut(&mut self) -> &mut dyn ::core::any::Any { self } diff --git a/crates/bevy_reflect/src/remote.rs b/crates/bevy_reflect/src/remote.rs index a19d3bdb148d6..22e663b20d7fa 100644 --- a/crates/bevy_reflect/src/remote.rs +++ b/crates/bevy_reflect/src/remote.rs @@ -41,7 +41,7 @@ use crate::Reflect; /// ``` /// /// [reflectable]: Reflect -/// [`transmute`]: core::mem::transmute +/// [`transmute`]: std::mem::transmute /// [very unsafe]: https://doc.rust-lang.org/1.71.0/nomicon/transmutes.html /// [`FromReflect`]: crate::FromReflect pub trait ReflectRemote: Reflect { diff --git a/crates/bevy_reflect/src/serde/de/arrays.rs b/crates/bevy_reflect/src/serde/de/arrays.rs index 2ffd2419a9217..24d009716a36c 100644 --- a/crates/bevy_reflect/src/serde/de/arrays.rs +++ b/crates/bevy_reflect/src/serde/de/arrays.rs @@ -1,9 +1,9 @@ -use crate::serde::de::registration_utils::try_get_registration; -use crate::serde::TypedReflectDeserializer; -use crate::{ArrayInfo, DynamicArray, TypeRegistry}; -use core::fmt::Formatter; +use crate::{ + serde::{de::registration_utils::try_get_registration, TypedReflectDeserializer}, + ArrayInfo, DynamicArray, TypeRegistry, +}; +use core::{fmt, fmt::Formatter}; use serde::de::{Error, SeqAccess, Visitor}; -use std::fmt; /// A [`Visitor`] for deserializing [`Array`] values. /// diff --git a/crates/bevy_reflect/src/serde/de/deserializer.rs b/crates/bevy_reflect/src/serde/de/deserializer.rs index 46530c2fe0309..6eddc2deed076 100644 --- a/crates/bevy_reflect/src/serde/de/deserializer.rs +++ b/crates/bevy_reflect/src/serde/de/deserializer.rs @@ -1,20 +1,18 @@ -use crate::serde::de::arrays::ArrayVisitor; -use crate::serde::de::enums::EnumVisitor; -use crate::serde::de::error_utils::make_custom_error; #[cfg(feature = "debug_stack")] use crate::serde::de::error_utils::TYPE_INFO_STACK; -use crate::serde::de::lists::ListVisitor; -use crate::serde::de::maps::MapVisitor; -use crate::serde::de::options::OptionVisitor; -use crate::serde::de::sets::SetVisitor; -use crate::serde::de::structs::StructVisitor; -use crate::serde::de::tuple_structs::TupleStructVisitor; -use crate::serde::de::tuples::TupleVisitor; -use crate::serde::TypeRegistrationDeserializer; -use crate::{PartialReflect, ReflectDeserialize, TypeInfo, TypeRegistration, TypeRegistry}; -use core::fmt::Formatter; +use crate::{ + serde::{ + de::{ + arrays::ArrayVisitor, enums::EnumVisitor, error_utils::make_custom_error, + lists::ListVisitor, maps::MapVisitor, options::OptionVisitor, sets::SetVisitor, + structs::StructVisitor, tuple_structs::TupleStructVisitor, tuples::TupleVisitor, + }, + TypeRegistrationDeserializer, + }, + PartialReflect, ReflectDeserialize, TypeInfo, TypeRegistration, TypeRegistry, +}; +use core::{fmt, fmt::Formatter}; use serde::de::{DeserializeSeed, Error, IgnoredAny, MapAccess, Visitor}; -use std::fmt; /// A general purpose deserializer for reflected types. /// diff --git a/crates/bevy_reflect/src/serde/de/enums.rs b/crates/bevy_reflect/src/serde/de/enums.rs index 8f4a094e831e0..ecdcc1435c6b3 100644 --- a/crates/bevy_reflect/src/serde/de/enums.rs +++ b/crates/bevy_reflect/src/serde/de/enums.rs @@ -1,16 +1,19 @@ -use crate::serde::de::error_utils::make_custom_error; -use crate::serde::de::helpers::ExpectedValues; -use crate::serde::de::registration_utils::try_get_registration; -use crate::serde::de::struct_utils::{visit_struct, visit_struct_seq}; -use crate::serde::de::tuple_utils::{visit_tuple, TupleLikeInfo}; -use crate::serde::TypedReflectDeserializer; use crate::{ + serde::{ + de::{ + error_utils::make_custom_error, + helpers::ExpectedValues, + registration_utils::try_get_registration, + struct_utils::{visit_struct, visit_struct_seq}, + tuple_utils::{visit_tuple, TupleLikeInfo}, + }, + TypedReflectDeserializer, + }, DynamicEnum, DynamicStruct, DynamicTuple, DynamicVariant, EnumInfo, StructVariantInfo, TupleVariantInfo, TypeRegistration, TypeRegistry, VariantInfo, }; -use core::fmt::Formatter; +use core::{fmt, fmt::Formatter}; use serde::de::{DeserializeSeed, EnumAccess, Error, MapAccess, SeqAccess, VariantAccess, Visitor}; -use std::fmt; /// A [`Visitor`] for deserializing [`Enum`] values. /// diff --git a/crates/bevy_reflect/src/serde/de/error_utils.rs b/crates/bevy_reflect/src/serde/de/error_utils.rs index 6a97c2518cbf7..f028976805791 100644 --- a/crates/bevy_reflect/src/serde/de/error_utils.rs +++ b/crates/bevy_reflect/src/serde/de/error_utils.rs @@ -6,7 +6,7 @@ thread_local! { /// The thread-local [`TypeInfoStack`] used for debugging. /// /// [`TypeInfoStack`]: crate::type_info_stack::TypeInfoStack - pub(super) static TYPE_INFO_STACK: std::cell::RefCell = const { std::cell::RefCell::new( + pub(super) static TYPE_INFO_STACK: core::cell::RefCell = const { core::cell::RefCell::new( crate::type_info_stack::TypeInfoStack::new() ) }; } diff --git a/crates/bevy_reflect/src/serde/de/helpers.rs b/crates/bevy_reflect/src/serde/de/helpers.rs index 3243a6c011c3e..bdb567a22eeb1 100644 --- a/crates/bevy_reflect/src/serde/de/helpers.rs +++ b/crates/bevy_reflect/src/serde/de/helpers.rs @@ -1,7 +1,11 @@ -use core::fmt::{Debug, Display, Formatter}; -use serde::de::{Error, Visitor}; -use serde::Deserialize; -use std::fmt; +use core::{ + fmt, + fmt::{Debug, Display, Formatter}, +}; +use serde::{ + de::{Error, Visitor}, + Deserialize, +}; /// A debug struct used for error messages that displays a list of expected values. /// diff --git a/crates/bevy_reflect/src/serde/de/lists.rs b/crates/bevy_reflect/src/serde/de/lists.rs index d0387f8a0a854..7d4ab44f8aea9 100644 --- a/crates/bevy_reflect/src/serde/de/lists.rs +++ b/crates/bevy_reflect/src/serde/de/lists.rs @@ -1,9 +1,9 @@ -use crate::serde::de::registration_utils::try_get_registration; -use crate::serde::TypedReflectDeserializer; -use crate::{DynamicList, ListInfo, TypeRegistry}; -use core::fmt::Formatter; +use crate::{ + serde::{de::registration_utils::try_get_registration, TypedReflectDeserializer}, + DynamicList, ListInfo, TypeRegistry, +}; +use core::{fmt, fmt::Formatter}; use serde::de::{SeqAccess, Visitor}; -use std::fmt; /// A [`Visitor`] for deserializing [`List`] values. /// diff --git a/crates/bevy_reflect/src/serde/de/maps.rs b/crates/bevy_reflect/src/serde/de/maps.rs index 1bda2e6837224..fbb5f9d449208 100644 --- a/crates/bevy_reflect/src/serde/de/maps.rs +++ b/crates/bevy_reflect/src/serde/de/maps.rs @@ -1,9 +1,9 @@ -use crate::serde::de::registration_utils::try_get_registration; -use crate::serde::TypedReflectDeserializer; -use crate::{DynamicMap, Map, MapInfo, TypeRegistry}; -use core::fmt::Formatter; +use crate::{ + serde::{de::registration_utils::try_get_registration, TypedReflectDeserializer}, + DynamicMap, Map, MapInfo, TypeRegistry, +}; +use core::{fmt, fmt::Formatter}; use serde::de::{MapAccess, Visitor}; -use std::fmt; /// A [`Visitor`] for deserializing [`Map`] values. /// diff --git a/crates/bevy_reflect/src/serde/de/mod.rs b/crates/bevy_reflect/src/serde/de/mod.rs index 4b89803e1d557..482ce9fb6378c 100644 --- a/crates/bevy_reflect/src/serde/de/mod.rs +++ b/crates/bevy_reflect/src/serde/de/mod.rs @@ -21,18 +21,15 @@ mod tuples; #[cfg(test)] mod tests { use bincode::Options; - use std::any::TypeId; - use std::f32::consts::PI; - use std::ops::RangeInclusive; + use core::{any::TypeId, f32::consts::PI, ops::RangeInclusive}; - use serde::de::DeserializeSeed; - use serde::Deserialize; + use serde::{de::DeserializeSeed, Deserialize}; use bevy_utils::{HashMap, HashSet}; use crate as bevy_reflect; - use crate::serde::{ReflectDeserializer, ReflectSerializer, TypedReflectDeserializer}; use crate::{ + serde::{ReflectDeserializer, ReflectSerializer, TypedReflectDeserializer}, DynamicEnum, FromReflect, PartialReflect, Reflect, ReflectDeserialize, TypeRegistry, }; diff --git a/crates/bevy_reflect/src/serde/de/options.rs b/crates/bevy_reflect/src/serde/de/options.rs index f4a5467c63d0c..de9ded50750cb 100644 --- a/crates/bevy_reflect/src/serde/de/options.rs +++ b/crates/bevy_reflect/src/serde/de/options.rs @@ -1,10 +1,12 @@ -use crate::serde::de::error_utils::make_custom_error; -use crate::serde::de::registration_utils::try_get_registration; -use crate::serde::TypedReflectDeserializer; -use crate::{DynamicEnum, DynamicTuple, EnumInfo, TypeRegistry, VariantInfo}; -use core::fmt::Formatter; +use crate::{ + serde::{ + de::{error_utils::make_custom_error, registration_utils::try_get_registration}, + TypedReflectDeserializer, + }, + DynamicEnum, DynamicTuple, EnumInfo, TypeRegistry, VariantInfo, +}; +use core::{fmt, fmt::Formatter}; use serde::de::{DeserializeSeed, Error, Visitor}; -use std::fmt; /// A [`Visitor`] for deserializing [`Option`] values. pub(super) struct OptionVisitor<'a> { diff --git a/crates/bevy_reflect/src/serde/de/registration_utils.rs b/crates/bevy_reflect/src/serde/de/registration_utils.rs index 2c88a73939d15..0559af70afe55 100644 --- a/crates/bevy_reflect/src/serde/de/registration_utils.rs +++ b/crates/bevy_reflect/src/serde/de/registration_utils.rs @@ -1,5 +1,4 @@ -use crate::serde::de::error_utils::make_custom_error; -use crate::{Type, TypeRegistration, TypeRegistry}; +use crate::{serde::de::error_utils::make_custom_error, Type, TypeRegistration, TypeRegistry}; use serde::de::Error; /// Attempts to find the [`TypeRegistration`] for a given [type]. diff --git a/crates/bevy_reflect/src/serde/de/registrations.rs b/crates/bevy_reflect/src/serde/de/registrations.rs index 8b34c348c0fad..adc0025c5489a 100644 --- a/crates/bevy_reflect/src/serde/de/registrations.rs +++ b/crates/bevy_reflect/src/serde/de/registrations.rs @@ -1,8 +1,6 @@ -use crate::serde::de::error_utils::make_custom_error; -use crate::{TypeRegistration, TypeRegistry}; -use core::fmt::Formatter; +use crate::{serde::de::error_utils::make_custom_error, TypeRegistration, TypeRegistry}; +use core::{fmt, fmt::Formatter}; use serde::de::{DeserializeSeed, Error, Visitor}; -use std::fmt; /// A deserializer for type registrations. /// diff --git a/crates/bevy_reflect/src/serde/de/sets.rs b/crates/bevy_reflect/src/serde/de/sets.rs index 2127f84b48310..faecf5bc396e8 100644 --- a/crates/bevy_reflect/src/serde/de/sets.rs +++ b/crates/bevy_reflect/src/serde/de/sets.rs @@ -1,9 +1,9 @@ -use crate::serde::de::registration_utils::try_get_registration; -use crate::serde::TypedReflectDeserializer; -use crate::{DynamicSet, Set, SetInfo, TypeRegistry}; -use core::fmt::Formatter; +use crate::{ + serde::{de::registration_utils::try_get_registration, TypedReflectDeserializer}, + DynamicSet, Set, SetInfo, TypeRegistry, +}; +use core::{fmt, fmt::Formatter}; use serde::de::{SeqAccess, Visitor}; -use std::fmt; /// A [`Visitor`] for deserializing [`Set`] values. /// diff --git a/crates/bevy_reflect/src/serde/de/struct_utils.rs b/crates/bevy_reflect/src/serde/de/struct_utils.rs index 836d36c0bdba5..0833678753d11 100644 --- a/crates/bevy_reflect/src/serde/de/struct_utils.rs +++ b/crates/bevy_reflect/src/serde/de/struct_utils.rs @@ -1,8 +1,12 @@ -use crate::serde::de::error_utils::make_custom_error; -use crate::serde::de::helpers::{ExpectedValues, Ident}; -use crate::serde::de::registration_utils::try_get_registration; -use crate::serde::{SerializationData, TypedReflectDeserializer}; use crate::{ + serde::{ + de::{ + error_utils::make_custom_error, + helpers::{ExpectedValues, Ident}, + registration_utils::try_get_registration, + }, + SerializationData, TypedReflectDeserializer, + }, DynamicStruct, NamedField, StructInfo, StructVariantInfo, TypeRegistration, TypeRegistry, }; use core::slice::Iter; diff --git a/crates/bevy_reflect/src/serde/de/structs.rs b/crates/bevy_reflect/src/serde/de/structs.rs index 85aa6f15b3309..750c739e8ef5a 100644 --- a/crates/bevy_reflect/src/serde/de/structs.rs +++ b/crates/bevy_reflect/src/serde/de/structs.rs @@ -1,8 +1,9 @@ -use crate::serde::de::struct_utils::{visit_struct, visit_struct_seq}; -use crate::{DynamicStruct, StructInfo, TypeRegistration, TypeRegistry}; -use core::fmt::Formatter; +use crate::{ + serde::de::struct_utils::{visit_struct, visit_struct_seq}, + DynamicStruct, StructInfo, TypeRegistration, TypeRegistry, +}; +use core::{fmt, fmt::Formatter}; use serde::de::{MapAccess, SeqAccess, Visitor}; -use std::fmt; /// A [`Visitor`] for deserializing [`Struct`] values. /// diff --git a/crates/bevy_reflect/src/serde/de/tuple_structs.rs b/crates/bevy_reflect/src/serde/de/tuple_structs.rs index 8bbe44a32442b..e070142ab71c8 100644 --- a/crates/bevy_reflect/src/serde/de/tuple_structs.rs +++ b/crates/bevy_reflect/src/serde/de/tuple_structs.rs @@ -1,8 +1,9 @@ -use crate::serde::de::tuple_utils::visit_tuple; -use crate::{DynamicTupleStruct, TupleStructInfo, TypeRegistration, TypeRegistry}; -use core::fmt::Formatter; +use crate::{ + serde::de::tuple_utils::visit_tuple, DynamicTupleStruct, TupleStructInfo, TypeRegistration, + TypeRegistry, +}; +use core::{fmt, fmt::Formatter}; use serde::de::{SeqAccess, Visitor}; -use std::fmt; /// A [`Visitor`] for deserializing [`TupleStruct`] values. /// diff --git a/crates/bevy_reflect/src/serde/de/tuple_utils.rs b/crates/bevy_reflect/src/serde/de/tuple_utils.rs index 7dd8ad448185d..ae49fe4084480 100644 --- a/crates/bevy_reflect/src/serde/de/tuple_utils.rs +++ b/crates/bevy_reflect/src/serde/de/tuple_utils.rs @@ -1,7 +1,8 @@ -use crate::serde::de::error_utils::make_custom_error; -use crate::serde::de::registration_utils::try_get_registration; -use crate::serde::{SerializationData, TypedReflectDeserializer}; use crate::{ + serde::{ + de::{error_utils::make_custom_error, registration_utils::try_get_registration}, + SerializationData, TypedReflectDeserializer, + }, DynamicTuple, TupleInfo, TupleStructInfo, TupleVariantInfo, TypeRegistration, TypeRegistry, UnnamedField, }; diff --git a/crates/bevy_reflect/src/serde/de/tuples.rs b/crates/bevy_reflect/src/serde/de/tuples.rs index de18cbda61bdb..ea06ad3154db8 100644 --- a/crates/bevy_reflect/src/serde/de/tuples.rs +++ b/crates/bevy_reflect/src/serde/de/tuples.rs @@ -1,8 +1,8 @@ -use crate::serde::de::tuple_utils::visit_tuple; -use crate::{DynamicTuple, TupleInfo, TypeRegistration, TypeRegistry}; -use core::fmt::Formatter; +use crate::{ + serde::de::tuple_utils::visit_tuple, DynamicTuple, TupleInfo, TypeRegistration, TypeRegistry, +}; +use core::{fmt, fmt::Formatter}; use serde::de::{SeqAccess, Visitor}; -use std::fmt; /// A [`Visitor`] for deserializing [`Tuple`] values. /// diff --git a/crates/bevy_reflect/src/serde/mod.rs b/crates/bevy_reflect/src/serde/mod.rs index bc3137d0b2b55..5a307c7d18443 100644 --- a/crates/bevy_reflect/src/serde/mod.rs +++ b/crates/bevy_reflect/src/serde/mod.rs @@ -8,11 +8,11 @@ pub use type_data::*; #[cfg(test)] mod tests { - use crate::{self as bevy_reflect, DynamicTupleStruct, PartialReflect, Struct}; use crate::{ + self as bevy_reflect, serde::{ReflectDeserializer, ReflectSerializer}, type_registry::TypeRegistry, - DynamicStruct, FromReflect, Reflect, + DynamicStruct, DynamicTupleStruct, FromReflect, PartialReflect, Reflect, Struct, }; use serde::de::DeserializeSeed; diff --git a/crates/bevy_reflect/src/serde/ser/arrays.rs b/crates/bevy_reflect/src/serde/ser/arrays.rs index b318047ee2887..16c741a68059a 100644 --- a/crates/bevy_reflect/src/serde/ser/arrays.rs +++ b/crates/bevy_reflect/src/serde/ser/arrays.rs @@ -1,7 +1,5 @@ -use crate::serde::TypedReflectSerializer; -use crate::{Array, TypeRegistry}; -use serde::ser::SerializeTuple; -use serde::Serialize; +use crate::{serde::TypedReflectSerializer, Array, TypeRegistry}; +use serde::{ser::SerializeTuple, Serialize}; /// A serializer for [`Array`] values. pub(super) struct ArraySerializer<'a> { diff --git a/crates/bevy_reflect/src/serde/ser/enums.rs b/crates/bevy_reflect/src/serde/ser/enums.rs index 6951617cb6243..4b71207a9700d 100644 --- a/crates/bevy_reflect/src/serde/ser/enums.rs +++ b/crates/bevy_reflect/src/serde/ser/enums.rs @@ -1,8 +1,11 @@ -use crate::serde::ser::error_utils::make_custom_error; -use crate::serde::TypedReflectSerializer; -use crate::{Enum, TypeInfo, TypeRegistry, VariantInfo, VariantType}; -use serde::ser::{SerializeStructVariant, SerializeTupleVariant}; -use serde::Serialize; +use crate::{ + serde::{ser::error_utils::make_custom_error, TypedReflectSerializer}, + Enum, TypeInfo, TypeRegistry, VariantInfo, VariantType, +}; +use serde::{ + ser::{SerializeStructVariant, SerializeTupleVariant}, + Serialize, +}; /// A serializer for [`Enum`] values. pub(super) struct EnumSerializer<'a> { diff --git a/crates/bevy_reflect/src/serde/ser/error_utils.rs b/crates/bevy_reflect/src/serde/ser/error_utils.rs index 58a029f986588..8e6570c6691a2 100644 --- a/crates/bevy_reflect/src/serde/ser/error_utils.rs +++ b/crates/bevy_reflect/src/serde/ser/error_utils.rs @@ -6,7 +6,7 @@ thread_local! { /// The thread-local [`TypeInfoStack`] used for debugging. /// /// [`TypeInfoStack`]: crate::type_info_stack::TypeInfoStack - pub(super) static TYPE_INFO_STACK: std::cell::RefCell = const { std::cell::RefCell::new( + pub(super) static TYPE_INFO_STACK: core::cell::RefCell = const { core::cell::RefCell::new( crate::type_info_stack::TypeInfoStack::new() ) }; } diff --git a/crates/bevy_reflect/src/serde/ser/lists.rs b/crates/bevy_reflect/src/serde/ser/lists.rs index ad3bb1a040a47..b52d52202f37d 100644 --- a/crates/bevy_reflect/src/serde/ser/lists.rs +++ b/crates/bevy_reflect/src/serde/ser/lists.rs @@ -1,7 +1,5 @@ -use crate::serde::TypedReflectSerializer; -use crate::{List, TypeRegistry}; -use serde::ser::SerializeSeq; -use serde::Serialize; +use crate::{serde::TypedReflectSerializer, List, TypeRegistry}; +use serde::{ser::SerializeSeq, Serialize}; /// A serializer for [`List`] values. pub(super) struct ListSerializer<'a> { diff --git a/crates/bevy_reflect/src/serde/ser/maps.rs b/crates/bevy_reflect/src/serde/ser/maps.rs index d5493cd35e523..354169193b59d 100644 --- a/crates/bevy_reflect/src/serde/ser/maps.rs +++ b/crates/bevy_reflect/src/serde/ser/maps.rs @@ -1,7 +1,5 @@ -use crate::serde::TypedReflectSerializer; -use crate::{Map, TypeRegistry}; -use serde::ser::SerializeMap; -use serde::Serialize; +use crate::{serde::TypedReflectSerializer, Map, TypeRegistry}; +use serde::{ser::SerializeMap, Serialize}; /// A serializer for [`Map`] values. pub(super) struct MapSerializer<'a> { diff --git a/crates/bevy_reflect/src/serde/ser/mod.rs b/crates/bevy_reflect/src/serde/ser/mod.rs index 30d684d4aac92..9ce71a839be35 100644 --- a/crates/bevy_reflect/src/serde/ser/mod.rs +++ b/crates/bevy_reflect/src/serde/ser/mod.rs @@ -15,15 +15,14 @@ mod tuples; #[cfg(test)] mod tests { - use crate::serde::ReflectSerializer; - use crate::{self as bevy_reflect, PartialReflect, Struct}; - use crate::{Reflect, ReflectSerialize, TypeRegistry}; + use crate::{ + self as bevy_reflect, serde::ReflectSerializer, PartialReflect, Reflect, ReflectSerialize, + Struct, TypeRegistry, + }; use bevy_utils::{HashMap, HashSet}; - use ron::extensions::Extensions; - use ron::ser::PrettyConfig; + use core::{f32::consts::PI, ops::RangeInclusive}; + use ron::{extensions::Extensions, ser::PrettyConfig}; use serde::Serialize; - use std::f32::consts::PI; - use std::ops::RangeInclusive; #[derive(Reflect, Debug, PartialEq)] struct MyStruct { @@ -410,7 +409,7 @@ mod tests { serializer.serialize(&mut ser).unwrap(); - let output = std::str::from_utf8(&buf).unwrap(); + let output = core::str::from_utf8(&buf).unwrap(); let expected = r#"{ "bevy_reflect::serde::ser::tests::OtherStruct": { "some": { diff --git a/crates/bevy_reflect/src/serde/ser/serializable.rs b/crates/bevy_reflect/src/serde/ser/serializable.rs index 9cf96ee77a26e..3ca19a3912568 100644 --- a/crates/bevy_reflect/src/serde/ser/serializable.rs +++ b/crates/bevy_reflect/src/serde/ser/serializable.rs @@ -1,7 +1,8 @@ -use crate::serde::ser::error_utils::make_custom_error; -use crate::{PartialReflect, ReflectSerialize, TypeRegistry}; +use crate::{ + serde::ser::error_utils::make_custom_error, PartialReflect, ReflectSerialize, TypeRegistry, +}; +use core::ops::Deref; use serde::ser::Error; -use std::ops::Deref; /// A type-erased serializable value. pub enum Serializable<'a> { diff --git a/crates/bevy_reflect/src/serde/ser/serializer.rs b/crates/bevy_reflect/src/serde/ser/serializer.rs index f6fd518e73a11..55fad6d8e6281 100644 --- a/crates/bevy_reflect/src/serde/ser/serializer.rs +++ b/crates/bevy_reflect/src/serde/ser/serializer.rs @@ -1,18 +1,18 @@ -use crate::serde::ser::arrays::ArraySerializer; -use crate::serde::ser::enums::EnumSerializer; -use crate::serde::ser::error_utils::make_custom_error; #[cfg(feature = "debug_stack")] use crate::serde::ser::error_utils::TYPE_INFO_STACK; -use crate::serde::ser::lists::ListSerializer; -use crate::serde::ser::maps::MapSerializer; -use crate::serde::ser::sets::SetSerializer; -use crate::serde::ser::structs::StructSerializer; -use crate::serde::ser::tuple_structs::TupleStructSerializer; -use crate::serde::ser::tuples::TupleSerializer; -use crate::serde::Serializable; -use crate::{PartialReflect, ReflectRef, TypeRegistry}; -use serde::ser::SerializeMap; -use serde::Serialize; +use crate::{ + serde::{ + ser::{ + arrays::ArraySerializer, enums::EnumSerializer, error_utils::make_custom_error, + lists::ListSerializer, maps::MapSerializer, sets::SetSerializer, + structs::StructSerializer, tuple_structs::TupleStructSerializer, + tuples::TupleSerializer, + }, + Serializable, + }, + PartialReflect, ReflectRef, TypeRegistry, +}; +use serde::{ser::SerializeMap, Serialize}; /// A general purpose serializer for reflected types. /// diff --git a/crates/bevy_reflect/src/serde/ser/sets.rs b/crates/bevy_reflect/src/serde/ser/sets.rs index 846f9e4f84fd3..343c253eb213e 100644 --- a/crates/bevy_reflect/src/serde/ser/sets.rs +++ b/crates/bevy_reflect/src/serde/ser/sets.rs @@ -1,7 +1,5 @@ -use crate::serde::TypedReflectSerializer; -use crate::{Set, TypeRegistry}; -use serde::ser::SerializeSeq; -use serde::Serialize; +use crate::{serde::TypedReflectSerializer, Set, TypeRegistry}; +use serde::{ser::SerializeSeq, Serialize}; /// A serializer for [`Set`] values. pub(super) struct SetSerializer<'a> { diff --git a/crates/bevy_reflect/src/serde/ser/structs.rs b/crates/bevy_reflect/src/serde/ser/structs.rs index 7763e297feaa8..c8c2b87b44360 100644 --- a/crates/bevy_reflect/src/serde/ser/structs.rs +++ b/crates/bevy_reflect/src/serde/ser/structs.rs @@ -1,8 +1,8 @@ -use crate::serde::ser::error_utils::make_custom_error; -use crate::serde::{SerializationData, TypedReflectSerializer}; -use crate::{Struct, TypeInfo, TypeRegistry}; -use serde::ser::SerializeStruct; -use serde::Serialize; +use crate::{ + serde::{ser::error_utils::make_custom_error, SerializationData, TypedReflectSerializer}, + Struct, TypeInfo, TypeRegistry, +}; +use serde::{ser::SerializeStruct, Serialize}; /// A serializer for [`Struct`] values. pub(super) struct StructSerializer<'a> { diff --git a/crates/bevy_reflect/src/serde/ser/tuple_structs.rs b/crates/bevy_reflect/src/serde/ser/tuple_structs.rs index 625e41e116a1c..388cdebe5718f 100644 --- a/crates/bevy_reflect/src/serde/ser/tuple_structs.rs +++ b/crates/bevy_reflect/src/serde/ser/tuple_structs.rs @@ -1,8 +1,8 @@ -use crate::serde::ser::error_utils::make_custom_error; -use crate::serde::{SerializationData, TypedReflectSerializer}; -use crate::{TupleStruct, TypeInfo, TypeRegistry}; -use serde::ser::SerializeTupleStruct; -use serde::Serialize; +use crate::{ + serde::{ser::error_utils::make_custom_error, SerializationData, TypedReflectSerializer}, + TupleStruct, TypeInfo, TypeRegistry, +}; +use serde::{ser::SerializeTupleStruct, Serialize}; /// A serializer for [`TupleStruct`] values. pub(super) struct TupleStructSerializer<'a> { diff --git a/crates/bevy_reflect/src/serde/ser/tuples.rs b/crates/bevy_reflect/src/serde/ser/tuples.rs index e106149613092..133818dfa905d 100644 --- a/crates/bevy_reflect/src/serde/ser/tuples.rs +++ b/crates/bevy_reflect/src/serde/ser/tuples.rs @@ -1,7 +1,5 @@ -use crate::serde::TypedReflectSerializer; -use crate::{Tuple, TypeRegistry}; -use serde::ser::SerializeTuple; -use serde::Serialize; +use crate::{serde::TypedReflectSerializer, Tuple, TypeRegistry}; +use serde::{ser::SerializeTuple, Serialize}; /// A serializer for [`Tuple`] values. pub(super) struct TupleSerializer<'a> { diff --git a/crates/bevy_reflect/src/serde/type_data.rs b/crates/bevy_reflect/src/serde/type_data.rs index 66dc9c8237b2e..35366b3909d94 100644 --- a/crates/bevy_reflect/src/serde/type_data.rs +++ b/crates/bevy_reflect/src/serde/type_data.rs @@ -1,6 +1,5 @@ use crate::Reflect; -use bevy_utils::hashbrown::hash_map::Iter; -use bevy_utils::HashMap; +use bevy_utils::{hashbrown::hash_map::Iter, HashMap}; /// Contains data relevant to the automatic reflect powered (de)serialization of a type. #[derive(Debug, Clone)] diff --git a/crates/bevy_reflect/src/set.rs b/crates/bevy_reflect/src/set.rs index 101ed23bb2a40..85bc57ca8431a 100644 --- a/crates/bevy_reflect/src/set.rs +++ b/crates/bevy_reflect/src/set.rs @@ -1,13 +1,11 @@ -use std::fmt::{Debug, Formatter}; +use core::fmt::{Debug, Formatter}; use bevy_reflect_derive::impl_type_path; -use bevy_utils::hashbrown::hash_table::OccupiedEntry as HashTableOccupiedEntry; -use bevy_utils::hashbrown::HashTable; +use bevy_utils::hashbrown::{hash_table::OccupiedEntry as HashTableOccupiedEntry, HashTable}; -use crate::type_info::impl_type_methods; use crate::{ - self as bevy_reflect, hash_error, ApplyError, PartialReflect, Reflect, ReflectKind, ReflectMut, - ReflectOwned, ReflectRef, Type, TypeInfo, TypePath, + self as bevy_reflect, hash_error, type_info::impl_type_methods, ApplyError, PartialReflect, + Reflect, ReflectKind, ReflectMut, ReflectOwned, ReflectRef, Type, TypeInfo, TypePath, }; /// A trait used to power [set-like] operations via [reflection]. @@ -312,7 +310,7 @@ impl PartialReflect for DynamicSet { set_partial_eq(self, value) } - fn debug(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "DynamicSet(")?; set_debug(self, f)?; write!(f, ")") @@ -327,7 +325,7 @@ impl PartialReflect for DynamicSet { impl_type_path!((in bevy_reflect) DynamicSet); impl Debug for DynamicSet { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { self.debug(f) } } @@ -373,7 +371,7 @@ impl IntoIterator for DynamicSet { impl<'a> IntoIterator for &'a DynamicSet { type Item = &'a dyn PartialReflect; - type IntoIter = std::iter::Map< + type IntoIter = core::iter::Map< bevy_utils::hashbrown::hash_table::Iter<'a, Box>, fn(&'a Box) -> Self::Item, >; @@ -434,7 +432,7 @@ pub fn set_partial_eq(a: &M, b: &dyn PartialReflect) -> Option { /// // } /// ``` #[inline] -pub fn set_debug(dyn_set: &dyn Set, f: &mut Formatter<'_>) -> std::fmt::Result { +pub fn set_debug(dyn_set: &dyn Set, f: &mut Formatter<'_>) -> core::fmt::Result { let mut debug = f.debug_set(); for value in dyn_set.iter() { debug.entry(&value as &dyn Debug); diff --git a/crates/bevy_reflect/src/struct_trait.rs b/crates/bevy_reflect/src/struct_trait.rs index 9b399fcf82458..965080dc6f58a 100644 --- a/crates/bevy_reflect/src/struct_trait.rs +++ b/crates/bevy_reflect/src/struct_trait.rs @@ -1,14 +1,17 @@ -use crate::attributes::{impl_custom_attribute_methods, CustomAttributes}; -use crate::type_info::impl_type_methods; use crate::{ - self as bevy_reflect, ApplyError, NamedField, PartialReflect, Reflect, ReflectKind, ReflectMut, - ReflectOwned, ReflectRef, Type, TypeInfo, TypePath, + self as bevy_reflect, + attributes::{impl_custom_attribute_methods, CustomAttributes}, + type_info::impl_type_methods, + ApplyError, NamedField, PartialReflect, Reflect, ReflectKind, ReflectMut, ReflectOwned, + ReflectRef, Type, TypeInfo, TypePath, }; +use alloc::{borrow::Cow, sync::Arc}; use bevy_reflect_derive::impl_type_path; use bevy_utils::HashMap; -use std::fmt::{Debug, Formatter}; -use std::sync::Arc; -use std::{borrow::Cow, slice::Iter}; +use core::{ + fmt::{Debug, Formatter}, + slice::Iter, +}; /// A trait used to power [struct-like] operations via [reflection]. /// @@ -447,7 +450,7 @@ impl PartialReflect for DynamicStruct { struct_partial_eq(self, value) } - fn debug(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "DynamicStruct(")?; struct_debug(self, f)?; write!(f, ")") @@ -462,7 +465,7 @@ impl PartialReflect for DynamicStruct { impl_type_path!((in bevy_reflect) DynamicStruct); impl Debug for DynamicStruct { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { self.debug(f) } } @@ -484,7 +487,7 @@ where impl IntoIterator for DynamicStruct { type Item = Box; - type IntoIter = std::vec::IntoIter; + type IntoIter = alloc::vec::IntoIter; fn into_iter(self) -> Self::IntoIter { self.fields.into_iter() @@ -554,7 +557,7 @@ pub fn struct_partial_eq(a: &S, b: &dyn PartialReflect) -> O /// // } /// ``` #[inline] -pub fn struct_debug(dyn_struct: &dyn Struct, f: &mut Formatter<'_>) -> std::fmt::Result { +pub fn struct_debug(dyn_struct: &dyn Struct, f: &mut Formatter<'_>) -> core::fmt::Result { let mut debug = f.debug_struct( dyn_struct .get_represented_type_info() diff --git a/crates/bevy_reflect/src/tuple.rs b/crates/bevy_reflect/src/tuple.rs index 8ed85c67de2da..25be1ad561d92 100644 --- a/crates/bevy_reflect/src/tuple.rs +++ b/crates/bevy_reflect/src/tuple.rs @@ -1,16 +1,17 @@ use bevy_reflect_derive::impl_type_path; use bevy_utils::all_tuples; -use crate::type_info::impl_type_methods; use crate::{ - self as bevy_reflect, utility::GenericTypePathCell, ApplyError, FromReflect, - GetTypeRegistration, MaybeTyped, Reflect, ReflectMut, ReflectOwned, ReflectRef, Type, TypeInfo, - TypePath, TypeRegistration, TypeRegistry, Typed, UnnamedField, + self as bevy_reflect, type_info::impl_type_methods, utility::GenericTypePathCell, ApplyError, + FromReflect, GetTypeRegistration, MaybeTyped, PartialReflect, Reflect, ReflectKind, ReflectMut, + ReflectOwned, ReflectRef, Type, TypeInfo, TypePath, TypeRegistration, TypeRegistry, Typed, + UnnamedField, +}; +use core::{ + any::Any, + fmt::{Debug, Formatter}, + slice::Iter, }; -use crate::{PartialReflect, ReflectKind}; -use std::any::Any; -use std::fmt::{Debug, Formatter}; -use std::slice::Iter; /// A trait used to power [tuple-like] operations via [reflection]. /// @@ -341,7 +342,7 @@ impl PartialReflect for DynamicTuple { tuple_partial_eq(self, value) } - fn debug(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "DynamicTuple(")?; tuple_debug(self, f)?; write!(f, ")") @@ -366,7 +367,7 @@ impl FromIterator> for DynamicTuple { impl IntoIterator for DynamicTuple { type Item = Box; - type IntoIter = std::vec::IntoIter; + type IntoIter = alloc::vec::IntoIter; fn into_iter(self) -> Self::IntoIter { self.fields.into_iter() @@ -460,7 +461,7 @@ pub fn tuple_partial_eq(a: &T, b: &dyn PartialReflect) -> Opt /// // ) /// ``` #[inline] -pub fn tuple_debug(dyn_tuple: &dyn Tuple, f: &mut Formatter<'_>) -> std::fmt::Result { +pub fn tuple_debug(dyn_tuple: &dyn Tuple, f: &mut Formatter<'_>) -> core::fmt::Result { let mut debug = f.debug_tuple(""); for field in dyn_tuple.iter_fields() { debug.field(&field as &dyn Debug); diff --git a/crates/bevy_reflect/src/tuple_struct.rs b/crates/bevy_reflect/src/tuple_struct.rs index 2acc1602b2e6a..f908356c8fe06 100644 --- a/crates/bevy_reflect/src/tuple_struct.rs +++ b/crates/bevy_reflect/src/tuple_struct.rs @@ -1,14 +1,17 @@ use bevy_reflect_derive::impl_type_path; -use crate::attributes::{impl_custom_attribute_methods, CustomAttributes}; -use crate::type_info::impl_type_methods; use crate::{ - self as bevy_reflect, ApplyError, DynamicTuple, PartialReflect, Reflect, ReflectKind, - ReflectMut, ReflectOwned, ReflectRef, Tuple, Type, TypeInfo, TypePath, UnnamedField, + self as bevy_reflect, + attributes::{impl_custom_attribute_methods, CustomAttributes}, + type_info::impl_type_methods, + ApplyError, DynamicTuple, PartialReflect, Reflect, ReflectKind, ReflectMut, ReflectOwned, + ReflectRef, Tuple, Type, TypeInfo, TypePath, UnnamedField, +}; +use alloc::sync::Arc; +use core::{ + fmt::{Debug, Formatter}, + slice::Iter, }; -use std::fmt::{Debug, Formatter}; -use std::slice::Iter; -use std::sync::Arc; /// A trait used to power [tuple struct-like] operations via [reflection]. /// @@ -355,7 +358,7 @@ impl PartialReflect for DynamicTupleStruct { tuple_struct_partial_eq(self, value) } - fn debug(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "DynamicTupleStruct(")?; tuple_struct_debug(self, f)?; write!(f, ")") @@ -370,7 +373,7 @@ impl PartialReflect for DynamicTupleStruct { impl_type_path!((in bevy_reflect) DynamicTupleStruct); impl Debug for DynamicTupleStruct { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { self.debug(f) } } @@ -395,7 +398,7 @@ impl FromIterator> for DynamicTupleStruct { impl IntoIterator for DynamicTupleStruct { type Item = Box; - type IntoIter = std::vec::IntoIter; + type IntoIter = alloc::vec::IntoIter; fn into_iter(self) -> Self::IntoIter { self.fields.into_iter() @@ -467,7 +470,7 @@ pub fn tuple_struct_partial_eq( pub fn tuple_struct_debug( dyn_tuple_struct: &dyn TupleStruct, f: &mut Formatter<'_>, -) -> std::fmt::Result { +) -> core::fmt::Result { let mut debug = f.debug_tuple( dyn_tuple_struct .get_represented_type_info() diff --git a/crates/bevy_reflect/src/type_info.rs b/crates/bevy_reflect/src/type_info.rs index d667dda3bbdcb..aaa4b8861cf64 100644 --- a/crates/bevy_reflect/src/type_info.rs +++ b/crates/bevy_reflect/src/type_info.rs @@ -3,10 +3,11 @@ use crate::{ DynamicTupleStruct, EnumInfo, ListInfo, MapInfo, PartialReflect, Reflect, ReflectKind, SetInfo, StructInfo, TupleInfo, TupleStructInfo, TypePath, TypePathTable, }; -use core::fmt::Formatter; -use std::any::{Any, TypeId}; -use std::fmt::Debug; -use std::hash::Hash; +use core::{ + any::{Any, TypeId}, + fmt::{Debug, Formatter}, + hash::Hash, +}; use thiserror::Error; /// A static accessor to compile-time type information. @@ -460,7 +461,7 @@ impl PartialEq for Type { /// [type path]: TypePath impl Hash for Type { #[inline] - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { self.type_id.hash(state); } } @@ -477,7 +478,7 @@ macro_rules! impl_type_methods { /// The [`TypeId`] of this type. /// /// [`TypeId`]: std::any::TypeId - pub fn type_id(&self) -> ::std::any::TypeId { + pub fn type_id(&self) -> ::core::any::TypeId { self.$field.id() } @@ -508,7 +509,7 @@ macro_rules! impl_type_methods { /// /// [`TypeId`]: std::any::TypeId /// [`TypePath`]: crate::type_path::TypePath - pub fn is(&self) -> bool { + pub fn is(&self) -> bool { self.$field.is::() } }; diff --git a/crates/bevy_reflect/src/type_info_stack.rs b/crates/bevy_reflect/src/type_info_stack.rs index f7f22a54ac44d..c2806553dd49a 100644 --- a/crates/bevy_reflect/src/type_info_stack.rs +++ b/crates/bevy_reflect/src/type_info_stack.rs @@ -1,6 +1,8 @@ use crate::TypeInfo; -use core::fmt::{Debug, Formatter}; -use core::slice::Iter; +use core::{ + fmt::{Debug, Formatter}, + slice::Iter, +}; /// Helper struct for managing a stack of [`TypeInfo`] instances. /// diff --git a/crates/bevy_reflect/src/type_path.rs b/crates/bevy_reflect/src/type_path.rs index bc685eb9f95cf..1287eeb8822cd 100644 --- a/crates/bevy_reflect/src/type_path.rs +++ b/crates/bevy_reflect/src/type_path.rs @@ -1,4 +1,4 @@ -use std::fmt; +use core::fmt; /// A static accessor to type paths and names. /// @@ -88,7 +88,7 @@ pub trait TypePath: 'static { /// /// Generic parameter types are also fully expanded. /// - /// For `Option>`, this is `"core::option::Option>"`. + /// For `Option>`, this is `"std::option::Option>"`. fn type_path() -> &'static str; /// Returns a short, pretty-print enabled path to the type. @@ -120,7 +120,7 @@ pub trait TypePath: 'static { /// Returns the path to the module the type is in, or [`None`] if it is [anonymous]. /// - /// For `Option>`, this is `"core::option"`. + /// For `Option>`, this is `"std::option"`. /// /// [anonymous]: TypePath#anonymity fn module_path() -> Option<&'static str> { diff --git a/crates/bevy_reflect/src/type_registry.rs b/crates/bevy_reflect/src/type_registry.rs index 849d8279b9b70..e70a8bd698ff5 100644 --- a/crates/bevy_reflect/src/type_registry.rs +++ b/crates/bevy_reflect/src/type_registry.rs @@ -1,14 +1,15 @@ use crate::{serde::Serializable, FromReflect, Reflect, TypeInfo, TypePath, Typed}; +use alloc::sync::Arc; use bevy_ptr::{Ptr, PtrMut}; use bevy_utils::{HashMap, HashSet, TypeIdMap}; -use downcast_rs::{impl_downcast, Downcast}; -use serde::Deserialize; -use std::ops::{Deref, DerefMut}; -use std::{ +use core::{ any::TypeId, fmt::Debug, - sync::{Arc, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard}, + ops::{Deref, DerefMut}, }; +use downcast_rs::{impl_downcast, Downcast}; +use serde::Deserialize; +use std::sync::{PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard}; /// A registry of [reflected] types. /// @@ -38,7 +39,7 @@ pub struct TypeRegistryArc { } impl Debug for TypeRegistryArc { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.internal .read() .unwrap_or_else(PoisonError::into_inner) @@ -265,7 +266,7 @@ impl TypeRegistry { panic!( "attempted to call `TypeRegistry::register_type_data` for type `{T}` with data `{D}` without registering `{T}` first", T = T::type_path(), - D = std::any::type_name::(), + D = core::any::type_name::(), ) }); data.insert(D::from_type()); @@ -471,7 +472,7 @@ pub struct TypeRegistration { } impl Debug for TypeRegistration { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("TypeRegistration") .field("type_info", &self.type_info) .finish() diff --git a/crates/bevy_reflect/src/utility.rs b/crates/bevy_reflect/src/utility.rs index 6eafc3e7c4287..2457db8faa8d3 100644 --- a/crates/bevy_reflect/src/utility.rs +++ b/crates/bevy_reflect/src/utility.rs @@ -2,11 +2,11 @@ use crate::TypeInfo; use bevy_utils::{FixedState, NoOpHash, TypeIdMap}; -use std::{ +use core::{ any::{Any, TypeId}, hash::BuildHasher, - sync::{OnceLock, PoisonError, RwLock}, }; +use std::sync::{OnceLock, PoisonError, RwLock}; /// A type that can be stored in a ([`Non`])[`GenericTypeCell`]. /// diff --git a/crates/bevy_remote/src/builtin_methods.rs b/crates/bevy_remote/src/builtin_methods.rs index d6ca798dad3d0..3fd467b4a8b0b 100644 --- a/crates/bevy_remote/src/builtin_methods.rs +++ b/crates/bevy_remote/src/builtin_methods.rs @@ -1,6 +1,6 @@ //! Built-in verbs for the Bevy Remote Protocol. -use std::any::TypeId; +use core::any::TypeId; use anyhow::{anyhow, Result as AnyhowResult}; use bevy_ecs::{ diff --git a/crates/bevy_remote/src/lib.rs b/crates/bevy_remote/src/lib.rs index 1f9b8d069515c..5f7d10b6006d8 100644 --- a/crates/bevy_remote/src/lib.rs +++ b/crates/bevy_remote/src/lib.rs @@ -247,10 +247,8 @@ #![cfg(not(target_family = "wasm"))] -use std::{ - net::{IpAddr, Ipv4Addr}, - sync::RwLock, -}; +use core::net::{IpAddr, Ipv4Addr}; +use std::sync::RwLock; use anyhow::Result as AnyhowResult; use bevy_app::prelude::*; diff --git a/crates/bevy_render/macros/src/as_bind_group.rs b/crates/bevy_render/macros/src/as_bind_group.rs index 6de62672a63ab..d0edd18dd633c 100644 --- a/crates/bevy_render/macros/src/as_bind_group.rs +++ b/crates/bevy_render/macros/src/as_bind_group.rs @@ -1109,7 +1109,7 @@ fn get_storage_binding_attr(metas: Vec) -> Result { let mut buffer = false; for meta in metas { - use syn::{Meta::List, Meta::Path}; + use syn::Meta::{List, Path}; match meta { // Parse #[storage(0, visibility(...))]. List(m) if m.path == VISIBILITY => { diff --git a/crates/bevy_render/src/alpha.rs b/crates/bevy_render/src/alpha.rs index 13a4943c10a2f..12e1377eabaab 100644 --- a/crates/bevy_render/src/alpha.rs +++ b/crates/bevy_render/src/alpha.rs @@ -1,5 +1,4 @@ -use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; +use bevy_reflect::{std_traits::ReflectDefault, Reflect}; // TODO: add discussion about performance. /// Sets how a material's base color alpha channel is used for transparency. diff --git a/crates/bevy_render/src/camera/camera.rs b/crates/bevy_render/src/camera/camera.rs index f58f75aaf84ac..3fd905bdcf104 100644 --- a/crates/bevy_render/src/camera/camera.rs +++ b/crates/bevy_render/src/camera/camera.rs @@ -28,13 +28,12 @@ use bevy_math::{ops, vec2, Dir3, Mat4, Ray3d, Rect, URect, UVec2, UVec4, Vec2, V use bevy_reflect::prelude::*; use bevy_render_macros::ExtractComponent; use bevy_transform::components::GlobalTransform; -use bevy_utils::{tracing::warn, warn_once}; -use bevy_utils::{HashMap, HashSet}; +use bevy_utils::{tracing::warn, warn_once, HashMap, HashSet}; use bevy_window::{ NormalizedWindowRef, PrimaryWindow, Window, WindowCreated, WindowRef, WindowResized, WindowScaleFactorChanged, }; -use std::ops::Range; +use core::ops::Range; use wgpu::{BlendState, TextureFormat, TextureUsages}; use super::{ClearColorConfig, Projection}; @@ -1079,7 +1078,7 @@ pub fn sort_cameras( sorted_cameras .0 .sort_by(|c1, c2| match c1.order.cmp(&c2.order) { - std::cmp::Ordering::Equal => c1.target.cmp(&c2.target), + core::cmp::Ordering::Equal => c1.target.cmp(&c2.target), ord => ord, }); let mut previous_order_target = None; diff --git a/crates/bevy_render/src/camera/manual_texture_view.rs b/crates/bevy_render/src/camera/manual_texture_view.rs index 1672bcf399c31..a1353b9d0f9c9 100644 --- a/crates/bevy_render/src/camera/manual_texture_view.rs +++ b/crates/bevy_render/src/camera/manual_texture_view.rs @@ -1,8 +1,7 @@ -use crate::extract_resource::ExtractResource; -use crate::render_resource::TextureView; -use crate::texture::BevyDefault; -use bevy_ecs::system::Resource; -use bevy_ecs::{prelude::Component, reflect::ReflectComponent}; +use crate::{ + extract_resource::ExtractResource, render_resource::TextureView, texture::BevyDefault, +}; +use bevy_ecs::{prelude::Component, reflect::ReflectComponent, system::Resource}; use bevy_math::UVec2; use bevy_reflect::prelude::*; use bevy_utils::HashMap; @@ -35,7 +34,7 @@ impl ManualTextureView { #[derive(Default, Clone, Resource, ExtractResource)] pub struct ManualTextureViews(HashMap); -impl std::ops::Deref for ManualTextureViews { +impl core::ops::Deref for ManualTextureViews { type Target = HashMap; fn deref(&self) -> &Self::Target { @@ -43,7 +42,7 @@ impl std::ops::Deref for ManualTextureViews { } } -impl std::ops::DerefMut for ManualTextureViews { +impl core::ops::DerefMut for ManualTextureViews { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } diff --git a/crates/bevy_render/src/camera/projection.rs b/crates/bevy_render/src/camera/projection.rs index 3a08506f37adb..91c9b9cc8d8ec 100644 --- a/crates/bevy_render/src/camera/projection.rs +++ b/crates/bevy_render/src/camera/projection.rs @@ -1,16 +1,16 @@ -use std::marker::PhantomData; -use std::ops::{Div, DivAssign, Mul, MulAssign}; +use core::{ + marker::PhantomData, + ops::{Div, DivAssign, Mul, MulAssign}, +}; -use crate::primitives::Frustum; -use crate::view::VisibilitySystems; +use crate::{primitives::Frustum, view::VisibilitySystems}; use bevy_app::{App, Plugin, PostStartup, PostUpdate}; use bevy_ecs::prelude::*; use bevy_math::{ops, AspectRatio, Mat4, Rect, Vec2, Vec3A}; use bevy_reflect::{ std_traits::ReflectDefault, GetTypeRegistration, Reflect, ReflectDeserialize, ReflectSerialize, }; -use bevy_transform::components::GlobalTransform; -use bevy_transform::TransformSystem; +use bevy_transform::{components::GlobalTransform, TransformSystem}; use serde::{Deserialize, Serialize}; /// Adds [`Camera`](crate::camera::Camera) driver systems for a given projection type. @@ -221,7 +221,7 @@ impl CameraProjection for PerspectiveProjection { impl Default for PerspectiveProjection { fn default() -> Self { PerspectiveProjection { - fov: std::f32::consts::PI / 4.0, + fov: core::f32::consts::PI / 4.0, near: 0.1, far: 1000.0, aspect_ratio: 1.0, diff --git a/crates/bevy_render/src/diagnostic/internal.rs b/crates/bevy_render/src/diagnostic/internal.rs index 297e09863101b..e023fe9bd2323 100644 --- a/crates/bevy_render/src/diagnostic/internal.rs +++ b/crates/bevy_render/src/diagnostic/internal.rs @@ -1,12 +1,9 @@ -use std::{ - borrow::Cow, +use alloc::{borrow::Cow, sync::Arc}; +use core::{ ops::{DerefMut, Range}, - sync::{ - atomic::{AtomicBool, Ordering}, - Arc, - }, - thread::{self, ThreadId}, + sync::atomic::{AtomicBool, Ordering}, }; +use std::thread::{self, ThreadId}; use bevy_diagnostic::{Diagnostic, DiagnosticMeasurement, DiagnosticPath, DiagnosticsStore}; use bevy_ecs::system::{Res, ResMut, Resource}; @@ -117,7 +114,7 @@ impl DiagnosticsRecorder { None => FrameData::new(device, internal.features), }; - let old_frame = std::mem::replace( + let old_frame = core::mem::replace( internal.current_frame.get_mut().expect("lock poisoned"), new_frame, ); @@ -421,9 +418,9 @@ impl FrameData { fn diagnostic_path(&self, range: &Range, field: &str) -> DiagnosticPath { DiagnosticPath::from_components( - std::iter::once("render") + core::iter::once("render") .chain(self.path_components[range.clone()].iter().map(|v| &**v)) - .chain(std::iter::once(field)), + .chain(core::iter::once(field)), ) } diff --git a/crates/bevy_render/src/diagnostic/mod.rs b/crates/bevy_render/src/diagnostic/mod.rs index f64d17a1884c4..6e91e2a736e79 100644 --- a/crates/bevy_render/src/diagnostic/mod.rs +++ b/crates/bevy_render/src/diagnostic/mod.rs @@ -4,7 +4,8 @@ pub(crate) mod internal; -use std::{borrow::Cow, marker::PhantomData, sync::Arc}; +use alloc::{borrow::Cow, sync::Arc}; +use core::marker::PhantomData; use bevy_app::{App, Plugin, PreUpdate}; @@ -126,7 +127,7 @@ impl TimeSpanGuard<'_, R, E> { /// End the span. You have to provide the same encoder which was used to begin the span. pub fn end(self, encoder: &mut E) { self.recorder.end_time_span(encoder); - std::mem::forget(self); + core::mem::forget(self); } } @@ -148,7 +149,7 @@ impl PassSpanGuard<'_, R, P> { /// End the span. You have to provide the same encoder which was used to begin the span. pub fn end(self, pass: &mut P) { self.recorder.end_pass_span(pass); - std::mem::forget(self); + core::mem::forget(self); } } diff --git a/crates/bevy_render/src/extract_component.rs b/crates/bevy_render/src/extract_component.rs index 4b327cf6af3e8..01b6b06ceacaa 100644 --- a/crates/bevy_render/src/extract_component.rs +++ b/crates/bevy_render/src/extract_component.rs @@ -12,7 +12,7 @@ use bevy_ecs::{ query::{QueryFilter, QueryItem, ReadOnlyQueryData}, system::lifetimeless::Read, }; -use std::{marker::PhantomData, ops::Deref}; +use core::{marker::PhantomData, ops::Deref}; pub use bevy_render_macros::ExtractComponent; diff --git a/crates/bevy_render/src/extract_instances.rs b/crates/bevy_render/src/extract_instances.rs index 537ca5f11e439..37edd85076b03 100644 --- a/crates/bevy_render/src/extract_instances.rs +++ b/crates/bevy_render/src/extract_instances.rs @@ -4,7 +4,7 @@ //! This is essentially the same as the `extract_component` module, but //! higher-performance because it avoids the ECS overhead. -use std::marker::PhantomData; +use core::marker::PhantomData; use bevy_app::{App, Plugin}; use bevy_asset::{Asset, AssetId, Handle}; diff --git a/crates/bevy_render/src/extract_param.rs b/crates/bevy_render/src/extract_param.rs index 6635dd270ce3e..914fe32dfb6e4 100644 --- a/crates/bevy_render/src/extract_param.rs +++ b/crates/bevy_render/src/extract_param.rs @@ -5,7 +5,7 @@ use bevy_ecs::{ system::{ReadOnlySystemParam, SystemMeta, SystemParam, SystemParamItem, SystemState}, world::unsafe_world_cell::UnsafeWorldCell, }; -use std::ops::{Deref, DerefMut}; +use core::ops::{Deref, DerefMut}; /// A helper for accessing [`MainWorld`] content using a system parameter. /// diff --git a/crates/bevy_render/src/extract_resource.rs b/crates/bevy_render/src/extract_resource.rs index 63a6c42dc4a20..2d36e694be7e5 100644 --- a/crates/bevy_render/src/extract_resource.rs +++ b/crates/bevy_render/src/extract_resource.rs @@ -1,4 +1,4 @@ -use std::marker::PhantomData; +use core::marker::PhantomData; use bevy_app::{App, Plugin}; use bevy_ecs::prelude::*; @@ -36,7 +36,7 @@ impl Plugin for ExtractResourcePlugin { } else { bevy_utils::error_once!( "Render app did not exist when trying to add `extract_resource` for <{}>.", - std::any::type_name::() + core::any::type_name::() ); } } @@ -59,7 +59,7 @@ pub fn extract_resource( bevy_utils::warn_once!( "Removing resource {} from render world not expected, adding using `Commands`. This may decrease performance", - std::any::type_name::() + core::any::type_name::() ); } commands.insert_resource(R::extract_resource(main_resource)); diff --git a/crates/bevy_render/src/gpu_component_array_buffer.rs b/crates/bevy_render/src/gpu_component_array_buffer.rs index 44e7d8c14cd7c..ac0f471a4a235 100644 --- a/crates/bevy_render/src/gpu_component_array_buffer.rs +++ b/crates/bevy_render/src/gpu_component_array_buffer.rs @@ -9,7 +9,7 @@ use bevy_ecs::{ schedule::IntoSystemConfigs, system::{Commands, Query, Res, ResMut}, }; -use std::marker::PhantomData; +use core::marker::PhantomData; /// This plugin prepares the components of the corresponding type for the GPU /// by storing them in a [`GpuArrayBuffer`]. diff --git a/crates/bevy_render/src/lib.rs b/crates/bevy_render/src/lib.rs index e6c35f0783568..450852fa2fb03 100644 --- a/crates/bevy_render/src/lib.rs +++ b/crates/bevy_render/src/lib.rs @@ -12,6 +12,7 @@ #[cfg(target_pointer_width = "16")] compile_error!("bevy_render cannot compile for a 16-bit platform."); +extern crate alloc; extern crate core; pub mod alpha; @@ -71,26 +72,23 @@ use globals::GlobalsPlugin; use render_asset::RenderAssetBytesPerFrame; use renderer::{RenderAdapter, RenderAdapterInfo, RenderDevice, RenderQueue}; -use crate::mesh::RenderMesh; -use crate::renderer::WgpuWrapper; use crate::{ camera::CameraPlugin, - mesh::{morph::MorphPlugin, MeshPlugin}, + mesh::{morph::MorphPlugin, MeshPlugin, RenderMesh}, render_asset::prepare_assets, render_resource::{PipelineCache, Shader, ShaderLoader}, - renderer::{render_system, RenderInstance}, + renderer::{render_system, RenderInstance, WgpuWrapper}, settings::RenderCreation, storage::StoragePlugin, view::{ViewPlugin, WindowRenderPlugin}, }; +use alloc::sync::Arc; use bevy_app::{App, AppLabel, Plugin, SubApp}; use bevy_asset::{load_internal_asset, AssetApp, AssetServer, Handle}; use bevy_ecs::{prelude::*, schedule::ScheduleLabel, system::SystemState}; use bevy_utils::tracing::debug; -use std::{ - ops::{Deref, DerefMut}, - sync::{Arc, Mutex}, -}; +use core::ops::{Deref, DerefMut}; +use std::sync::Mutex; /// Contains the default Bevy rendering backend based on wgpu. /// @@ -437,13 +435,13 @@ struct ScratchMainWorld(World); fn extract(main_world: &mut World, render_world: &mut World) { // temporarily add the app world to the render world as a resource let scratch_world = main_world.remove_resource::().unwrap(); - let inserted_world = std::mem::replace(main_world, scratch_world.0); + let inserted_world = core::mem::replace(main_world, scratch_world.0); render_world.insert_resource(MainWorld(inserted_world)); render_world.run_schedule(ExtractSchedule); // move the app world back, as if nothing happened. let inserted_world = render_world.remove_resource::().unwrap(); - let scratch_world = std::mem::replace(main_world, inserted_world.0); + let scratch_world = core::mem::replace(main_world, inserted_world.0); main_world.insert_resource(ScratchMainWorld(scratch_world)); } diff --git a/crates/bevy_render/src/mesh/allocator.rs b/crates/bevy_render/src/mesh/allocator.rs index 94186517a4d9f..e20cb1774453e 100644 --- a/crates/bevy_render/src/mesh/allocator.rs +++ b/crates/bevy_render/src/mesh/allocator.rs @@ -1,11 +1,10 @@ //! Manages mesh vertex and index buffers. -use std::{ - borrow::Cow, +use alloc::{borrow::Cow, vec::Vec}; +use core::{ fmt::{self, Display, Formatter}, iter, ops::Range, - vec::Vec, }; use bevy_app::{App, Plugin}; diff --git a/crates/bevy_render/src/mesh/mesh/conversions.rs b/crates/bevy_render/src/mesh/mesh/conversions.rs index f067839b325a2..3f3c8c2ae3243 100644 --- a/crates/bevy_render/src/mesh/mesh/conversions.rs +++ b/crates/bevy_render/src/mesh/mesh/conversions.rs @@ -40,7 +40,7 @@ impl FromVertexAttributeError { fn new(from: VertexAttributeValues) -> Self { Self { variant: from.enum_variant_name(), - into: std::any::type_name::(), + into: core::any::type_name::(), from, } } diff --git a/crates/bevy_render/src/mesh/mesh/mod.rs b/crates/bevy_render/src/mesh/mesh/mod.rs index 954a585b57c99..46faf1908eff5 100644 --- a/crates/bevy_render/src/mesh/mesh/mod.rs +++ b/crates/bevy_render/src/mesh/mesh/mod.rs @@ -11,6 +11,7 @@ use crate::{ render_resource::{TextureView, VertexBufferLayout}, texture::GpuImage, }; +use alloc::collections::BTreeMap; use bevy_asset::{Asset, Handle}; use bevy_derive::EnumVariantMeta; use bevy_ecs::system::{ @@ -21,7 +22,7 @@ use bevy_math::{primitives::Triangle3d, *}; use bevy_reflect::Reflect; use bevy_utils::tracing::{error, warn}; use bytemuck::cast_slice; -use std::{collections::BTreeMap, hash::Hash, iter::FusedIterator}; +use core::{hash::Hash, iter::FusedIterator}; use thiserror::Error; use wgpu::{IndexFormat, VertexAttribute, VertexFormat, VertexStepMode}; @@ -364,7 +365,7 @@ impl Mesh { /// Removes the vertex `indices` from the mesh and returns them. #[inline] pub fn remove_indices(&mut self) -> Option { - std::mem::take(&mut self.indices) + core::mem::take(&mut self.indices) } /// Consumes the mesh and returns a mesh without the vertex `indices` of the mesh. @@ -441,7 +442,7 @@ impl Mesh { warn!("{name} has a different vertex count ({attribute_len}) than other attributes ({previous_vertex_count}) in this mesh, \ all attributes will be truncated to match the smallest."); - vertex_count = Some(std::cmp::min(previous_vertex_count, attribute_len)); + vertex_count = Some(core::cmp::min(previous_vertex_count, attribute_len)); } } else { vertex_count = Some(attribute_len); @@ -570,7 +571,7 @@ impl Mesh { let [_, b, c] = chunk else { return Err(MeshWindingInvertError::AbruptIndicesEnd); }; - std::mem::swap(b, c); + core::mem::swap(b, c); } Ok(()) } @@ -1657,8 +1658,8 @@ impl Indices { /// An Iterator for the [`Indices`]. enum IndicesIter<'a> { - U16(std::slice::Iter<'a, u16>), - U32(std::slice::Iter<'a, u32>), + U16(core::slice::Iter<'a, u16>), + U32(core::slice::Iter<'a, u32>), } impl Iterator for IndicesIter<'_> { diff --git a/crates/bevy_render/src/mesh/mesh/skinning.rs b/crates/bevy_render/src/mesh/mesh/skinning.rs index e7a91252e7f65..016f0b9567264 100644 --- a/crates/bevy_render/src/mesh/mesh/skinning.rs +++ b/crates/bevy_render/src/mesh/mesh/skinning.rs @@ -7,7 +7,7 @@ use bevy_ecs::{ }; use bevy_math::Mat4; use bevy_reflect::prelude::*; -use std::ops::Deref; +use core::ops::Deref; #[derive(Component, Debug, Default, Clone, Reflect)] #[reflect(Component, MapEntities, Default, Debug)] diff --git a/crates/bevy_render/src/mesh/mod.rs b/crates/bevy_render/src/mesh/mod.rs index 84accac658236..6897e1d176f74 100644 --- a/crates/bevy_render/src/mesh/mod.rs +++ b/crates/bevy_render/src/mesh/mod.rs @@ -5,14 +5,12 @@ pub mod allocator; pub mod morph; pub mod primitives; +use alloc::sync::Arc; use allocator::MeshAllocatorPlugin; use bevy_utils::HashSet; +use core::hash::{Hash, Hasher}; pub use mesh::*; pub use primitives::*; -use std::{ - hash::{Hash, Hasher}, - sync::Arc, -}; use crate::{render_asset::RenderAssetPlugin, texture::GpuImage, RenderApp}; use bevy_app::{App, Plugin}; diff --git a/crates/bevy_render/src/mesh/morph.rs b/crates/bevy_render/src/mesh/morph.rs index e44dd65b44e66..db28ed5afea0e 100644 --- a/crates/bevy_render/src/mesh/morph.rs +++ b/crates/bevy_render/src/mesh/morph.rs @@ -11,7 +11,7 @@ use bevy_hierarchy::Children; use bevy_math::Vec3; use bevy_reflect::prelude::*; use bytemuck::{Pod, Zeroable}; -use std::iter; +use core::iter; use thiserror::Error; const MAX_TEXTURE_WIDTH: u32 = 2048; diff --git a/crates/bevy_render/src/mesh/primitives/dim2.rs b/crates/bevy_render/src/mesh/primitives/dim2.rs index a7183f99f2fc5..fc117a6f5dae5 100644 --- a/crates/bevy_render/src/mesh/primitives/dim2.rs +++ b/crates/bevy_render/src/mesh/primitives/dim2.rs @@ -1,4 +1,4 @@ -use std::f32::consts::FRAC_PI_2; +use core::f32::consts::FRAC_PI_2; use crate::{ mesh::{primitives::dim3::triangle3d, Indices, Mesh, PerimeterSegment}, @@ -489,7 +489,7 @@ impl MeshBuilder for EllipseMeshBuilder { // Add pi/2 so that there is a vertex at the top (sin is 1.0 and cos is 0.0) let start_angle = FRAC_PI_2; - let step = std::f32::consts::TAU / self.resolution as f32; + let step = core::f32::consts::TAU / self.resolution as f32; for i in 0..self.resolution { // Compute vertex position at angle theta @@ -597,7 +597,7 @@ impl MeshBuilder for AnnulusMeshBuilder { // mapping. Here, each iteration places a pair of vertices at a fixed // angle from the center of the annulus. let start_angle = FRAC_PI_2; - let step = std::f32::consts::TAU / self.resolution as f32; + let step = core::f32::consts::TAU / self.resolution as f32; for i in 0..=self.resolution { let theta = start_angle + (i % self.resolution) as f32 * step; let (sin, cos) = ops::sin_cos(theta); @@ -898,7 +898,7 @@ impl MeshBuilder for Capsule2dMeshBuilder { let mut uvs = Vec::with_capacity(vertex_count as usize); let radius = self.capsule.radius; - let step = std::f32::consts::TAU / vertex_count as f32; + let step = core::f32::consts::TAU / vertex_count as f32; // If the vertex count is even, offset starting angle of top semicircle by half a step // to position the vertices evenly. diff --git a/crates/bevy_render/src/mesh/primitives/dim3/capsule.rs b/crates/bevy_render/src/mesh/primitives/dim3/capsule.rs index eeea5e906f1eb..33fe54d3d82b3 100644 --- a/crates/bevy_render/src/mesh/primitives/dim3/capsule.rs +++ b/crates/bevy_render/src/mesh/primitives/dim3/capsule.rs @@ -136,8 +136,8 @@ impl MeshBuilder for Capsule3dMeshBuilder { let mut vts: Vec = vec![Vec2::ZERO; vert_len]; let mut vns: Vec = vec![Vec3::ZERO; vert_len]; - let to_theta = 2.0 * std::f32::consts::PI / longitudes as f32; - let to_phi = std::f32::consts::PI / latitudes as f32; + let to_theta = 2.0 * core::f32::consts::PI / longitudes as f32; + let to_phi = core::f32::consts::PI / latitudes as f32; let to_tex_horizontal = 1.0 / longitudes as f32; let to_tex_vertical = 1.0 / half_lats as f32; diff --git a/crates/bevy_render/src/mesh/primitives/dim3/cone.rs b/crates/bevy_render/src/mesh/primitives/dim3/cone.rs index 7ad5394a3c055..51e18e20c40d4 100644 --- a/crates/bevy_render/src/mesh/primitives/dim3/cone.rs +++ b/crates/bevy_render/src/mesh/primitives/dim3/cone.rs @@ -111,7 +111,7 @@ impl MeshBuilder for ConeMeshBuilder { let normalization_factor = (1.0 + normal_slope * normal_slope).sqrt().recip(); // How much the angle changes at each step - let step_theta = std::f32::consts::TAU / self.resolution as f32; + let step_theta = core::f32::consts::TAU / self.resolution as f32; // Add vertices for the bottom of the lateral surface. for segment in 0..self.resolution { diff --git a/crates/bevy_render/src/mesh/primitives/dim3/conical_frustum.rs b/crates/bevy_render/src/mesh/primitives/dim3/conical_frustum.rs index 3b7da0bea5b57..cf3d160ffb4b1 100644 --- a/crates/bevy_render/src/mesh/primitives/dim3/conical_frustum.rs +++ b/crates/bevy_render/src/mesh/primitives/dim3/conical_frustum.rs @@ -83,7 +83,7 @@ impl MeshBuilder for ConicalFrustumMeshBuilder { let mut uvs = Vec::with_capacity(num_vertices); let mut indices = Vec::with_capacity(num_indices); - let step_theta = std::f32::consts::TAU / self.resolution as f32; + let step_theta = core::f32::consts::TAU / self.resolution as f32; let step_y = height / self.segments as f32; let step_radius = (radius_top - radius_bottom) / self.segments as f32; diff --git a/crates/bevy_render/src/mesh/primitives/dim3/cylinder.rs b/crates/bevy_render/src/mesh/primitives/dim3/cylinder.rs index c6522d98c7808..67a81afc964d3 100644 --- a/crates/bevy_render/src/mesh/primitives/dim3/cylinder.rs +++ b/crates/bevy_render/src/mesh/primitives/dim3/cylinder.rs @@ -112,7 +112,7 @@ impl MeshBuilder for CylinderMeshBuilder { let mut uvs = Vec::with_capacity(num_vertices as usize); let mut indices = Vec::with_capacity(num_indices as usize); - let step_theta = std::f32::consts::TAU / resolution as f32; + let step_theta = core::f32::consts::TAU / resolution as f32; let step_y = 2.0 * self.cylinder.half_height / segments as f32; // rings diff --git a/crates/bevy_render/src/mesh/primitives/dim3/sphere.rs b/crates/bevy_render/src/mesh/primitives/dim3/sphere.rs index 0d2e4e84d8c5a..5ab6257029534 100644 --- a/crates/bevy_render/src/mesh/primitives/dim3/sphere.rs +++ b/crates/bevy_render/src/mesh/primitives/dim3/sphere.rs @@ -1,4 +1,4 @@ -use std::f32::consts::PI; +use core::f32::consts::PI; use crate::{ mesh::{Indices, Mesh, MeshBuilder, Meshable}, @@ -124,7 +124,7 @@ impl SphereMeshBuilder { let azimuth = ops::atan2(point.z, point.x); let norm_inclination = inclination / PI; - let norm_azimuth = 0.5 - (azimuth / std::f32::consts::TAU); + let norm_azimuth = 0.5 - (azimuth / core::f32::consts::TAU); [norm_azimuth, norm_inclination] }); diff --git a/crates/bevy_render/src/mesh/primitives/dim3/torus.rs b/crates/bevy_render/src/mesh/primitives/dim3/torus.rs index 0dcbd68353da9..e0d56a67613a5 100644 --- a/crates/bevy_render/src/mesh/primitives/dim3/torus.rs +++ b/crates/bevy_render/src/mesh/primitives/dim3/torus.rs @@ -1,5 +1,5 @@ use bevy_math::{ops, primitives::Torus, Vec3}; -use std::ops::RangeInclusive; +use core::ops::RangeInclusive; use wgpu::PrimitiveTopology; use crate::{ @@ -34,7 +34,7 @@ impl Default for TorusMeshBuilder { torus: Torus::default(), minor_resolution: 24, major_resolution: 32, - angle_range: (0.0..=2.0 * std::f32::consts::PI), + angle_range: (0.0..=2.0 * core::f32::consts::PI), } } } @@ -91,7 +91,7 @@ impl MeshBuilder for TorusMeshBuilder { let end_angle = self.angle_range.end(); let segment_stride = (end_angle - start_angle) / self.major_resolution as f32; - let side_stride = 2.0 * std::f32::consts::PI / self.minor_resolution as f32; + let side_stride = 2.0 * core::f32::consts::PI / self.minor_resolution as f32; for segment in 0..=self.major_resolution { let theta = start_angle + segment_stride * segment as f32; diff --git a/crates/bevy_render/src/primitives/mod.rs b/crates/bevy_render/src/primitives/mod.rs index 476e4740ecd8d..e3a76a7c3e53e 100644 --- a/crates/bevy_render/src/primitives/mod.rs +++ b/crates/bevy_render/src/primitives/mod.rs @@ -1,4 +1,4 @@ -use std::borrow::Borrow; +use core::borrow::Borrow; use bevy_ecs::{component::Component, entity::EntityHashMap, reflect::ReflectComponent}; use bevy_math::{Affine3A, Mat3A, Mat4, Vec3, Vec3A, Vec4, Vec4Swizzles}; diff --git a/crates/bevy_render/src/render_asset.rs b/crates/bevy_render/src/render_asset.rs index 5705e0ba71154..46ee40fd20ef8 100644 --- a/crates/bevy_render/src/render_asset.rs +++ b/crates/bevy_render/src/render_asset.rs @@ -15,8 +15,8 @@ use bevy_utils::{ tracing::{debug, error}, HashMap, HashSet, }; +use core::marker::PhantomData; use serde::{Deserialize, Serialize}; -use std::marker::PhantomData; use thiserror::Error; #[derive(Debug, Error)] @@ -337,7 +337,7 @@ pub fn prepare_assets( let mut wrote_asset_count = 0; let mut param = param.into_inner(); - let queued_assets = std::mem::take(&mut prepare_next_frame.assets); + let queued_assets = core::mem::take(&mut prepare_next_frame.assets); for (id, extracted_asset) in queued_assets { if extracted_assets.removed.contains(&id) || extracted_assets.added.contains(&id) { // skip previous frame's assets that have been removed or updated @@ -370,7 +370,7 @@ pub fn prepare_assets( Err(PrepareAssetError::AsBindGroupError(e)) => { error!( "{} Bind group construction failed: {e}", - std::any::type_name::() + core::any::type_name::() ); } } @@ -408,7 +408,7 @@ pub fn prepare_assets( Err(PrepareAssetError::AsBindGroupError(e)) => { error!( "{} Bind group construction failed: {e}", - std::any::type_name::() + core::any::type_name::() ); } } @@ -417,7 +417,7 @@ pub fn prepare_assets( if bpf.exhausted() && !prepare_next_frame.assets.is_empty() { debug!( "{} write budget exhausted with {} assets remaining (wrote {})", - std::any::type_name::(), + core::any::type_name::(), prepare_next_frame.assets.len(), wrote_asset_count ); diff --git a/crates/bevy_render/src/render_graph/context.rs b/crates/bevy_render/src/render_graph/context.rs index 1cf2dc89570fa..c27f269d0ba45 100644 --- a/crates/bevy_render/src/render_graph/context.rs +++ b/crates/bevy_render/src/render_graph/context.rs @@ -2,8 +2,8 @@ use crate::{ render_graph::{NodeState, RenderGraph, SlotInfos, SlotLabel, SlotType, SlotValue}, render_resource::{Buffer, Sampler, TextureView}, }; +use alloc::borrow::Cow; use bevy_ecs::entity::Entity; -use std::borrow::Cow; use thiserror::Error; use super::{InternedRenderSubGraph, RenderSubGraph}; diff --git a/crates/bevy_render/src/render_graph/graph.rs b/crates/bevy_render/src/render_graph/graph.rs index 9779e4a75ccee..4eee0e4294238 100644 --- a/crates/bevy_render/src/render_graph/graph.rs +++ b/crates/bevy_render/src/render_graph/graph.rs @@ -7,7 +7,7 @@ use crate::{ }; use bevy_ecs::{define_label, intern::Interned, prelude::World, system::Resource}; use bevy_utils::HashMap; -use std::fmt::Debug; +use core::fmt::Debug; use super::{EdgeExistence, InternedRenderLabel, IntoRenderNodeArray}; @@ -626,7 +626,7 @@ impl RenderGraph { } impl Debug for RenderGraph { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { for node in self.iter_nodes() { writeln!(f, "{:?}", node.label)?; writeln!(f, " in: {:?}", node.input_slots)?; diff --git a/crates/bevy_render/src/render_graph/node.rs b/crates/bevy_render/src/render_graph/node.rs index 8528457d420a1..9406baf580d02 100644 --- a/crates/bevy_render/src/render_graph/node.rs +++ b/crates/bevy_render/src/render_graph/node.rs @@ -14,8 +14,8 @@ use bevy_ecs::{ world::{FromWorld, World}, }; use bevy_utils::all_tuples_with_size; +use core::fmt::Debug; use downcast_rs::{impl_downcast, Downcast}; -use std::fmt::Debug; use thiserror::Error; pub use bevy_render_macros::RenderLabel; @@ -229,7 +229,7 @@ pub struct NodeState { } impl Debug for NodeState { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { writeln!(f, "{:?} ({:?})", self.label, self.type_name) } } @@ -246,7 +246,7 @@ impl NodeState { input_slots: node.input().into(), output_slots: node.output().into(), node: Box::new(node), - type_name: std::any::type_name::(), + type_name: core::any::type_name::(), edges: Edges { label, input_edges: Vec::new(), diff --git a/crates/bevy_render/src/render_graph/node_slot.rs b/crates/bevy_render/src/render_graph/node_slot.rs index fd5dc388d3812..81a736754017e 100644 --- a/crates/bevy_render/src/render_graph/node_slot.rs +++ b/crates/bevy_render/src/render_graph/node_slot.rs @@ -1,5 +1,6 @@ +use alloc::borrow::Cow; use bevy_ecs::entity::Entity; -use std::{borrow::Cow, fmt}; +use core::fmt; use crate::render_resource::{Buffer, Sampler, TextureView}; diff --git a/crates/bevy_render/src/render_phase/draw.rs b/crates/bevy_render/src/render_phase/draw.rs index 0880ae797efd3..25f77ebe151c1 100644 --- a/crates/bevy_render/src/render_phase/draw.rs +++ b/crates/bevy_render/src/render_phase/draw.rs @@ -7,12 +7,8 @@ use bevy_ecs::{ world::World, }; use bevy_utils::{all_tuples, TypeIdMap}; -use std::{ - any::TypeId, - fmt::Debug, - hash::Hash, - sync::{PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard}, -}; +use core::{any::TypeId, fmt::Debug, hash::Hash}; +use std::sync::{PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard}; use thiserror::Error; /// A draw function used to draw [`PhaseItem`]s. @@ -102,8 +98,8 @@ impl DrawFunctionsInternal

{ self.get_id::().unwrap_or_else(|| { panic!( "Draw function {} not found for {}", - std::any::type_name::(), - std::any::type_name::

() + core::any::type_name::(), + core::any::type_name::

() ) }) } @@ -168,7 +164,7 @@ impl DrawFunctions

{ /// # use bevy_render::render_phase::SetItemPipeline; /// # struct SetMeshViewBindGroup; /// # struct SetMeshBindGroup; -/// # struct SetMaterialBindGroup(core::marker::PhantomData); +/// # struct SetMaterialBindGroup(std::marker::PhantomData); /// # struct DrawMesh; /// pub type DrawMaterial = ( /// SetItemPipeline, @@ -365,7 +361,7 @@ impl AddRenderCommand for SubApp { panic!( "DrawFunctions<{}> must be added to the world as a resource \ before adding render commands to it", - std::any::type_name::

(), + core::any::type_name::

(), ); }); draw_functions.write().add_with::(draw_function); diff --git a/crates/bevy_render/src/render_phase/draw_state.rs b/crates/bevy_render/src/render_phase/draw_state.rs index f19dff1971b3c..4ba3e410870a5 100644 --- a/crates/bevy_render/src/render_phase/draw_state.rs +++ b/crates/bevy_render/src/render_phase/draw_state.rs @@ -9,7 +9,7 @@ use crate::{ }; use bevy_color::LinearRgba; use bevy_utils::{default, detailed_trace}; -use std::ops::Range; +use core::ops::Range; use wgpu::{IndexFormat, QuerySet, RenderPass}; /// Tracks the state of a [`TrackedRenderPass`]. diff --git a/crates/bevy_render/src/render_phase/mod.rs b/crates/bevy_render/src/render_phase/mod.rs index 1bc1ee52ca687..2fa3e673640e4 100644 --- a/crates/bevy_render/src/render_phase/mod.rs +++ b/crates/bevy_render/src/render_phase/mod.rs @@ -52,8 +52,7 @@ use bevy_ecs::{ prelude::*, system::{lifetimeless::SRes, SystemParamItem}, }; -use smallvec::SmallVec; -use std::{ +use core::{ fmt::{self, Debug, Formatter}, hash::Hash, iter, @@ -61,6 +60,7 @@ use std::{ ops::Range, slice::SliceIndex, }; +use smallvec::SmallVec; /// Stores the rendering instructions for a single phase that uses bins in all /// views. diff --git a/crates/bevy_render/src/render_resource/batched_uniform_buffer.rs b/crates/bevy_render/src/render_resource/batched_uniform_buffer.rs index 75a747cf46fe3..f2d8d430c58fe 100644 --- a/crates/bevy_render/src/render_resource/batched_uniform_buffer.rs +++ b/crates/bevy_render/src/render_resource/batched_uniform_buffer.rs @@ -3,12 +3,12 @@ use crate::{ render_resource::DynamicUniformBuffer, renderer::{RenderDevice, RenderQueue}, }; +use core::{marker::PhantomData, num::NonZero}; use encase::{ private::{ArrayMetadata, BufferMut, Metadata, RuntimeSizedArray, WriteInto, Writer}, ShaderType, }; use nonmax::NonMaxU32; -use std::{marker::PhantomData, num::NonZero}; use wgpu::{BindingResource, Limits}; // 1MB else we will make really large arrays on macOS which reports very large diff --git a/crates/bevy_render/src/render_resource/bind_group.rs b/crates/bevy_render/src/render_resource/bind_group.rs index cb3a6fb347631..24a4c13b56293 100644 --- a/crates/bevy_render/src/render_resource/bind_group.rs +++ b/crates/bevy_render/src/render_resource/bind_group.rs @@ -7,8 +7,8 @@ use crate::{ }; use bevy_ecs::system::{SystemParam, SystemParamItem}; pub use bevy_render_macros::AsBindGroup; +use core::ops::Deref; use encase::ShaderType; -use std::ops::Deref; use thiserror::Error; use wgpu::{BindGroupEntry, BindGroupLayoutEntry, BindingResource}; diff --git a/crates/bevy_render/src/render_resource/bind_group_entries.rs b/crates/bevy_render/src/render_resource/bind_group_entries.rs index 33260f985067d..316bfa118546a 100644 --- a/crates/bevy_render/src/render_resource/bind_group_entries.rs +++ b/crates/bevy_render/src/render_resource/bind_group_entries.rs @@ -129,7 +129,7 @@ impl<'b> BindGroupEntries<'b, 1> { } } -impl<'b, const N: usize> std::ops::Deref for BindGroupEntries<'b, N> { +impl<'b, const N: usize> core::ops::Deref for BindGroupEntries<'b, N> { type Target = [BindGroupEntry<'b>]; fn deref(&self) -> &[BindGroupEntry<'b>] { @@ -273,7 +273,7 @@ impl<'b> DynamicBindGroupEntries<'b> { } } -impl<'b> std::ops::Deref for DynamicBindGroupEntries<'b> { +impl<'b> core::ops::Deref for DynamicBindGroupEntries<'b> { type Target = [BindGroupEntry<'b>]; fn deref(&self) -> &[BindGroupEntry<'b>] { diff --git a/crates/bevy_render/src/render_resource/bind_group_layout.rs b/crates/bevy_render/src/render_resource/bind_group_layout.rs index 9793f1391d188..201237a64d537 100644 --- a/crates/bevy_render/src/render_resource/bind_group_layout.rs +++ b/crates/bevy_render/src/render_resource/bind_group_layout.rs @@ -1,5 +1,5 @@ use crate::{define_atomic_id, render_resource::resource_macros::*}; -use std::ops::Deref; +use core::ops::Deref; define_atomic_id!(BindGroupLayoutId); render_resource_wrapper!(ErasedBindGroupLayout, wgpu::BindGroupLayout); diff --git a/crates/bevy_render/src/render_resource/bind_group_layout_entries.rs b/crates/bevy_render/src/render_resource/bind_group_layout_entries.rs index 58d1d62a19889..346019a2fb272 100644 --- a/crates/bevy_render/src/render_resource/bind_group_layout_entries.rs +++ b/crates/bevy_render/src/render_resource/bind_group_layout_entries.rs @@ -1,5 +1,5 @@ use bevy_utils::all_tuples_with_size; -use std::num::NonZero; +use core::num::NonZero; use wgpu::{BindGroupLayoutEntry, BindingType, ShaderStages}; /// Helper for constructing bind group layouts. @@ -198,7 +198,7 @@ impl BindGroupLayoutEntries<1> { } } -impl std::ops::Deref for BindGroupLayoutEntries { +impl core::ops::Deref for BindGroupLayoutEntries { type Target = [BindGroupLayoutEntry]; fn deref(&self) -> &[BindGroupLayoutEntry] { &self.entries @@ -340,7 +340,7 @@ impl DynamicBindGroupLayoutEntries { } } -impl std::ops::Deref for DynamicBindGroupLayoutEntries { +impl core::ops::Deref for DynamicBindGroupLayoutEntries { type Target = [BindGroupLayoutEntry]; fn deref(&self) -> &[BindGroupLayoutEntry] { @@ -352,8 +352,8 @@ pub mod binding_types { use crate::render_resource::{ BufferBindingType, SamplerBindingType, TextureSampleType, TextureViewDimension, }; + use core::num::NonZero; use encase::ShaderType; - use std::num::NonZero; use wgpu::{StorageTextureAccess, TextureFormat}; use super::*; diff --git a/crates/bevy_render/src/render_resource/buffer.rs b/crates/bevy_render/src/render_resource/buffer.rs index cf98fdafb8692..81a8dbc9b7687 100644 --- a/crates/bevy_render/src/render_resource/buffer.rs +++ b/crates/bevy_render/src/render_resource/buffer.rs @@ -1,5 +1,5 @@ use crate::{define_atomic_id, render_resource::resource_macros::render_resource_wrapper}; -use std::ops::{Bound, Deref, RangeBounds}; +use core::ops::{Bound, Deref, RangeBounds}; define_atomic_id!(BufferId); render_resource_wrapper!(ErasedBuffer, wgpu::Buffer); diff --git a/crates/bevy_render/src/render_resource/buffer_vec.rs b/crates/bevy_render/src/render_resource/buffer_vec.rs index c720605d9274f..ab384fadcf100 100644 --- a/crates/bevy_render/src/render_resource/buffer_vec.rs +++ b/crates/bevy_render/src/render_resource/buffer_vec.rs @@ -1,4 +1,4 @@ -use std::{iter, marker::PhantomData}; +use core::{iter, marker::PhantomData}; use crate::{ render_resource::Buffer, diff --git a/crates/bevy_render/src/render_resource/gpu_array_buffer.rs b/crates/bevy_render/src/render_resource/gpu_array_buffer.rs index f1980062bd2b5..c4c5906373029 100644 --- a/crates/bevy_render/src/render_resource/gpu_array_buffer.rs +++ b/crates/bevy_render/src/render_resource/gpu_array_buffer.rs @@ -7,9 +7,9 @@ use crate::{ renderer::{RenderDevice, RenderQueue}, }; use bevy_ecs::{prelude::Component, system::Resource}; +use core::marker::PhantomData; use encase::{private::WriteInto, ShaderSize, ShaderType}; use nonmax::NonMaxU32; -use std::marker::PhantomData; use wgpu::{BindingResource, BufferUsages}; /// Trait for types able to go in a [`GpuArrayBuffer`]. diff --git a/crates/bevy_render/src/render_resource/pipeline.rs b/crates/bevy_render/src/render_resource/pipeline.rs index 93f76d3f56e8a..f81fb57b173e6 100644 --- a/crates/bevy_render/src/render_resource/pipeline.rs +++ b/crates/bevy_render/src/render_resource/pipeline.rs @@ -3,8 +3,9 @@ use crate::{ define_atomic_id, render_resource::{resource_macros::render_resource_wrapper, BindGroupLayout, Shader}, }; +use alloc::borrow::Cow; use bevy_asset::Handle; -use std::{borrow::Cow, ops::Deref}; +use core::ops::Deref; use wgpu::{ BufferAddress, ColorTargetState, DepthStencilState, MultisampleState, PrimitiveState, PushConstantRange, VertexAttribute, VertexFormat, VertexStepMode, diff --git a/crates/bevy_render/src/render_resource/pipeline_cache.rs b/crates/bevy_render/src/render_resource/pipeline_cache.rs index 0c25d358d535f..2222df6098b95 100644 --- a/crates/bevy_render/src/render_resource/pipeline_cache.rs +++ b/crates/bevy_render/src/render_resource/pipeline_cache.rs @@ -3,25 +3,22 @@ use crate::{ renderer::{RenderAdapter, RenderDevice}, Extract, }; +use alloc::{borrow::Cow, sync::Arc}; use bevy_asset::{AssetEvent, AssetId, Assets}; -use bevy_ecs::system::{Res, ResMut}; -use bevy_ecs::{event::EventReader, system::Resource}; +use bevy_ecs::{ + event::EventReader, + system::{Res, ResMut, Resource}, +}; use bevy_tasks::Task; -use bevy_utils::hashbrown::hash_map::EntryRef; use bevy_utils::{ default, + hashbrown::hash_map::EntryRef, tracing::{debug, error}, HashMap, HashSet, }; +use core::{future::Future, hash::Hash, mem, ops::Deref}; use naga::valid::Capabilities; -use std::{ - borrow::Cow, - future::Future, - hash::Hash, - mem, - ops::Deref, - sync::{Arc, Mutex, PoisonError}, -}; +use std::sync::{Mutex, PoisonError}; use thiserror::Error; #[cfg(feature = "shader_format_spirv")] use wgpu::util::make_spirv; diff --git a/crates/bevy_render/src/render_resource/pipeline_specializer.rs b/crates/bevy_render/src/render_resource/pipeline_specializer.rs index 93c4b236c6aeb..0ff2f50cd15ff 100644 --- a/crates/bevy_render/src/render_resource/pipeline_specializer.rs +++ b/crates/bevy_render/src/render_resource/pipeline_specializer.rs @@ -1,16 +1,18 @@ -use crate::mesh::MeshVertexBufferLayoutRef; -use crate::render_resource::CachedComputePipelineId; use crate::{ - mesh::MissingVertexAttributeError, + mesh::{MeshVertexBufferLayoutRef, MissingVertexAttributeError}, render_resource::{ - CachedRenderPipelineId, ComputePipelineDescriptor, PipelineCache, RenderPipelineDescriptor, - VertexBufferLayout, + CachedComputePipelineId, CachedRenderPipelineId, ComputePipelineDescriptor, PipelineCache, + RenderPipelineDescriptor, VertexBufferLayout, }, }; use bevy_ecs::system::Resource; -use bevy_utils::hashbrown::hash_map::VacantEntry; -use bevy_utils::{default, hashbrown::hash_map::RawEntryMut, tracing::error, Entry, HashMap}; -use std::{fmt::Debug, hash::Hash}; +use bevy_utils::{ + default, + hashbrown::hash_map::{RawEntryMut, VacantEntry}, + tracing::error, + Entry, HashMap, +}; +use core::{fmt::Debug, hash::Hash}; use thiserror::Error; pub trait SpecializedRenderPipeline { @@ -140,7 +142,7 @@ impl SpecializedMeshPipelines { .map_err(|mut err| { { let SpecializedMeshPipelineError::MissingVertexAttribute(err) = &mut err; - err.pipeline_type = Some(std::any::type_name::()); + err.pipeline_type = Some(core::any::type_name::()); } err })?; @@ -169,7 +171,7 @@ impl SpecializedMeshPipelines { unused' MeshVertexBufferLayout information to specialize \ the pipeline. This is not allowed because it would invalidate \ the pipeline cache.", - std::any::type_name::() + core::any::type_name::() ); } } diff --git a/crates/bevy_render/src/render_resource/resource_macros.rs b/crates/bevy_render/src/render_resource/resource_macros.rs index e22c59b1c031f..75580f32a0ee7 100644 --- a/crates/bevy_render/src/render_resource/resource_macros.rs +++ b/crates/bevy_render/src/render_resource/resource_macros.rs @@ -20,8 +20,8 @@ macro_rules! render_resource_wrapper { impl $wrapper_type { pub fn new(value: $wgpu_type) -> Self { - let arc = std::sync::Arc::new(value); - let value_ptr = std::sync::Arc::into_raw(arc); + let arc = alloc::sync::Arc::new(value); + let value_ptr = alloc::sync::Arc::into_raw(arc); let unit_ptr = value_ptr.cast::<()>(); #[cfg(not(all(target_arch = "wasm32", target_feature = "atomics")))] @@ -33,16 +33,16 @@ macro_rules! render_resource_wrapper { pub fn try_unwrap(self) -> Option<$wgpu_type> { let value_ptr = self.0.cast::<$wgpu_type>(); // SAFETY: pointer refers to a valid Arc, and was created from Arc::into_raw. - let arc = unsafe { std::sync::Arc::from_raw(value_ptr) }; + let arc = unsafe { alloc::sync::Arc::from_raw(value_ptr) }; // we forget ourselves here since the reconstructed arc will be dropped/decremented within this scope - std::mem::forget(self); + core::mem::forget(self); - std::sync::Arc::try_unwrap(arc).ok() + alloc::sync::Arc::try_unwrap(arc).ok() } } - impl std::ops::Deref for $wrapper_type { + impl core::ops::Deref for $wrapper_type { type Target = $wgpu_type; fn deref(&self) -> &Self::Target { @@ -58,7 +58,7 @@ macro_rules! render_resource_wrapper { let value_ptr = self.0.cast::<$wgpu_type>(); // SAFETY: pointer refers to a valid Arc, and was created from Arc::into_raw. // this reconstructed arc is dropped/decremented within this scope. - unsafe { std::sync::Arc::from_raw(value_ptr) }; + unsafe { alloc::sync::Arc::from_raw(value_ptr) }; } } @@ -81,11 +81,11 @@ macro_rules! render_resource_wrapper { fn clone(&self) -> Self { let value_ptr = self.0.cast::<$wgpu_type>(); // SAFETY: pointer refers to a valid Arc, and was created from Arc::into_raw. - let arc = unsafe { std::sync::Arc::from_raw(value_ptr.cast::<$wgpu_type>()) }; - let cloned = std::sync::Arc::clone(&arc); + let arc = unsafe { alloc::sync::Arc::from_raw(value_ptr.cast::<$wgpu_type>()) }; + let cloned = alloc::sync::Arc::clone(&arc); // we forget the reconstructed Arc to avoid decrementing the ref counter, as self is still live. - std::mem::forget(arc); - let cloned_value_ptr = std::sync::Arc::into_raw(cloned); + core::mem::forget(arc); + let cloned_value_ptr = alloc::sync::Arc::into_raw(cloned); let cloned_unit_ptr = cloned_value_ptr.cast::<()>(); #[cfg(not(all(target_arch = "wasm32", target_feature = "atomics")))] @@ -129,7 +129,7 @@ macro_rules! render_resource_wrapper { } } - impl std::ops::Deref for $wrapper_type { + impl core::ops::Deref for $wrapper_type { type Target = $wgpu_type; fn deref(&self) -> &Self::Target { @@ -155,7 +155,7 @@ macro_rules! define_atomic_id { #[allow(clippy::new_without_default)] impl $atomic_id_type { pub fn new() -> Self { - use std::sync::atomic::{AtomicU32, Ordering}; + use core::sync::atomic::{AtomicU32, Ordering}; static COUNTER: AtomicU32 = AtomicU32::new(1); diff --git a/crates/bevy_render/src/render_resource/shader.rs b/crates/bevy_render/src/render_resource/shader.rs index 33055de58ccb9..7cb8b8f9ee4c1 100644 --- a/crates/bevy_render/src/render_resource/shader.rs +++ b/crates/bevy_render/src/render_resource/shader.rs @@ -1,9 +1,10 @@ use super::ShaderDefVal; use crate::define_atomic_id; +use alloc::borrow::Cow; use bevy_asset::{io::Reader, Asset, AssetLoader, AssetPath, Handle, LoadContext}; use bevy_reflect::TypePath; use bevy_utils::tracing::error; -use std::{borrow::Cow, marker::Copy}; +use core::marker::Copy; use thiserror::Error; define_atomic_id!(ShaderId); @@ -251,7 +252,7 @@ pub enum ShaderLoaderError { #[error("Could not load shader: {0}")] Io(#[from] std::io::Error), #[error("Could not parse shader: {0}")] - Parse(#[from] std::string::FromUtf8Error), + Parse(#[from] alloc::string::FromUtf8Error), } impl AssetLoader for ShaderLoader { diff --git a/crates/bevy_render/src/render_resource/storage_buffer.rs b/crates/bevy_render/src/render_resource/storage_buffer.rs index 1b244f90327ac..3f65d534ebd7f 100644 --- a/crates/bevy_render/src/render_resource/storage_buffer.rs +++ b/crates/bevy_render/src/render_resource/storage_buffer.rs @@ -1,4 +1,4 @@ -use std::marker::PhantomData; +use core::marker::PhantomData; use super::Buffer; use crate::renderer::{RenderDevice, RenderQueue}; diff --git a/crates/bevy_render/src/render_resource/texture.rs b/crates/bevy_render/src/render_resource/texture.rs index df0df616a6f6c..624935b5a6f62 100644 --- a/crates/bevy_render/src/render_resource/texture.rs +++ b/crates/bevy_render/src/render_resource/texture.rs @@ -1,5 +1,5 @@ use crate::define_atomic_id; -use std::ops::Deref; +use core::ops::Deref; use crate::render_resource::resource_macros::*; diff --git a/crates/bevy_render/src/render_resource/uniform_buffer.rs b/crates/bevy_render/src/render_resource/uniform_buffer.rs index db51653f146ea..95e1a0a56664e 100644 --- a/crates/bevy_render/src/render_resource/uniform_buffer.rs +++ b/crates/bevy_render/src/render_resource/uniform_buffer.rs @@ -1,4 +1,4 @@ -use std::{marker::PhantomData, num::NonZero}; +use core::{marker::PhantomData, num::NonZero}; use crate::{ render_resource::Buffer, diff --git a/crates/bevy_render/src/renderer/graph_runner.rs b/crates/bevy_render/src/renderer/graph_runner.rs index 835144976e47d..15b3240638e7c 100644 --- a/crates/bevy_render/src/renderer/graph_runner.rs +++ b/crates/bevy_render/src/renderer/graph_runner.rs @@ -3,8 +3,8 @@ use bevy_ecs::{prelude::Entity, world::World}; use bevy_utils::tracing::info_span; use bevy_utils::HashMap; +use alloc::{borrow::Cow, collections::VecDeque}; use smallvec::{smallvec, SmallVec}; -use std::{borrow::Cow, collections::VecDeque}; use thiserror::Error; use crate::{ diff --git a/crates/bevy_render/src/renderer/mod.rs b/crates/bevy_render/src/renderer/mod.rs index 582ad2d18150b..5cd442da8c74f 100644 --- a/crates/bevy_render/src/renderer/mod.rs +++ b/crates/bevy_render/src/renderer/mod.rs @@ -15,10 +15,10 @@ use crate::{ settings::{WgpuSettings, WgpuSettingsPriority}, view::{ExtractedWindows, ViewTarget}, }; +use alloc::sync::Arc; use bevy_ecs::{prelude::*, system::SystemState}; use bevy_time::TimeSender; use bevy_utils::Instant; -use std::sync::Arc; use wgpu::{ Adapter, AdapterInfo, CommandBuffer, CommandEncoder, DeviceType, Instance, Queue, RequestAdapterOptions, @@ -57,7 +57,7 @@ pub fn render_system(world: &mut World, state: &mut SystemState { error!("Error running render graph:"); { - let mut src: &dyn std::error::Error = &e; + let mut src: &dyn core::error::Error = &e; loop { error!("> {}", src); match src.source() { diff --git a/crates/bevy_render/src/renderer/render_device.rs b/crates/bevy_render/src/renderer/render_device.rs index 4c2e41186f48c..64f4772ec3dc8 100644 --- a/crates/bevy_render/src/renderer/render_device.rs +++ b/crates/bevy_render/src/renderer/render_device.rs @@ -10,8 +10,7 @@ use wgpu::{ use super::RenderQueue; -use crate::render_resource::resource_macros::*; -use crate::WgpuWrapper; +use crate::{render_resource::resource_macros::*, WgpuWrapper}; render_resource_wrapper!(ErasedRenderDevice, wgpu::Device); diff --git a/crates/bevy_render/src/settings.rs b/crates/bevy_render/src/settings.rs index 7dbf016a8e4c2..bf1db17ff110c 100644 --- a/crates/bevy_render/src/settings.rs +++ b/crates/bevy_render/src/settings.rs @@ -1,7 +1,8 @@ use crate::renderer::{ RenderAdapter, RenderAdapterInfo, RenderDevice, RenderInstance, RenderQueue, }; -use std::{borrow::Cow, path::PathBuf}; +use alloc::borrow::Cow; +use std::path::PathBuf; pub use wgpu::{ Backends, Dx12Compiler, Features as WgpuFeatures, Gles3MinorVersion, InstanceFlags, diff --git a/crates/bevy_render/src/storage.rs b/crates/bevy_render/src/storage.rs index 0eb6adaea0d14..bd5c3dba9fc38 100644 --- a/crates/bevy_render/src/storage.rs +++ b/crates/bevy_render/src/storage.rs @@ -1,15 +1,14 @@ -use crate::render_asset::{PrepareAssetError, RenderAsset, RenderAssetPlugin, RenderAssetUsages}; -use crate::render_resource::{Buffer, BufferUsages}; -use crate::renderer::RenderDevice; +use crate::{ + render_asset::{PrepareAssetError, RenderAsset, RenderAssetPlugin, RenderAssetUsages}, + render_resource::{Buffer, BufferUsages}, + renderer::RenderDevice, +}; use bevy_app::{App, Plugin}; use bevy_asset::{Asset, AssetApp}; -use bevy_ecs::system::lifetimeless::SRes; -use bevy_ecs::system::SystemParamItem; -use bevy_reflect::prelude::ReflectDefault; -use bevy_reflect::Reflect; +use bevy_ecs::system::{lifetimeless::SRes, SystemParamItem}; +use bevy_reflect::{prelude::ReflectDefault, Reflect}; use bevy_utils::default; -use encase::internal::WriteInto; -use encase::ShaderType; +use encase::{internal::WriteInto, ShaderType}; use wgpu::util::BufferInitDescriptor; /// Adds [`ShaderStorageBuffer`] as an asset that is extracted and uploaded to the GPU. diff --git a/crates/bevy_render/src/texture/image.rs b/crates/bevy_render/src/texture/image.rs index bd3b8e01fd45e..c606e6be13013 100644 --- a/crates/bevy_render/src/texture/image.rs +++ b/crates/bevy_render/src/texture/image.rs @@ -16,8 +16,8 @@ use bevy_derive::{Deref, DerefMut}; use bevy_ecs::system::{lifetimeless::SRes, Resource, SystemParamItem}; use bevy_math::{AspectRatio, UVec2, Vec2}; use bevy_reflect::prelude::*; +use core::hash::Hash; use serde::{Deserialize, Serialize}; -use std::hash::Hash; use thiserror::Error; use wgpu::{Extent3d, TextureDimension, TextureFormat, TextureViewDescriptor}; diff --git a/crates/bevy_render/src/texture/image_loader.rs b/crates/bevy_render/src/texture/image_loader.rs index 85a97ad431e54..c671108e581c9 100644 --- a/crates/bevy_render/src/texture/image_loader.rs +++ b/crates/bevy_render/src/texture/image_loader.rs @@ -154,8 +154,8 @@ pub struct FileTextureError { error: TextureError, path: String, } -impl std::fmt::Display for FileTextureError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { +impl core::fmt::Display for FileTextureError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> { write!( f, "Error reading image file {}: {}, this is an error in `bevy_render`.", diff --git a/crates/bevy_render/src/texture/ktx2.rs b/crates/bevy_render/src/texture/ktx2.rs index 941cb4299aba4..8924ea72c4533 100644 --- a/crates/bevy_render/src/texture/ktx2.rs +++ b/crates/bevy_render/src/texture/ktx2.rs @@ -427,7 +427,7 @@ enum DataType { Sint, } -// This can be obtained from std::mem::transmute::(1.0f32). It is used for identifying +// This can be obtained from core::mem::transmute::(1.0f32). It is used for identifying // normalized sample types as in Unorm or Snorm. const F32_1_AS_U32: u32 = 1065353216; diff --git a/crates/bevy_render/src/texture/texture_attachment.rs b/crates/bevy_render/src/texture/texture_attachment.rs index 6681ba9916211..e0947e997207e 100644 --- a/crates/bevy_render/src/texture/texture_attachment.rs +++ b/crates/bevy_render/src/texture/texture_attachment.rs @@ -1,10 +1,8 @@ use super::CachedTexture; use crate::render_resource::{TextureFormat, TextureView}; +use alloc::sync::Arc; use bevy_color::LinearRgba; -use std::sync::{ - atomic::{AtomicBool, Ordering}, - Arc, -}; +use core::sync::atomic::{AtomicBool, Ordering}; use wgpu::{ LoadOp, Operations, RenderPassColorAttachment, RenderPassDepthStencilAttachment, StoreOp, }; diff --git a/crates/bevy_render/src/view/mod.rs b/crates/bevy_render/src/view/mod.rs index 6542677c94950..c8292d4f90ce3 100644 --- a/crates/bevy_render/src/view/mod.rs +++ b/crates/bevy_render/src/view/mod.rs @@ -5,13 +5,12 @@ use bevy_asset::{load_internal_asset, Handle}; pub use visibility::*; pub use window::*; -use crate::camera::NormalizedRenderTarget; -use crate::extract_component::ExtractComponentPlugin; use crate::{ camera::{ CameraMainTextureUsages, ClearColor, ClearColorConfig, Exposure, ExtractedCamera, - ManualTextureViews, MipBias, TemporalJitter, + ManualTextureViews, MipBias, NormalizedRenderTarget, TemporalJitter, }, + extract_component::ExtractComponentPlugin, prelude::Shader, primitives::Frustum, render_asset::RenderAssets, @@ -24,6 +23,7 @@ use crate::{ }, Render, RenderApp, RenderSet, }; +use alloc::sync::Arc; use bevy_app::{App, Plugin}; use bevy_color::LinearRgba; use bevy_derive::{Deref, DerefMut}; @@ -33,12 +33,9 @@ use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_render_macros::ExtractComponent; use bevy_transform::components::GlobalTransform; use bevy_utils::{hashbrown::hash_map::Entry, HashMap}; -use std::{ +use core::{ ops::Range, - sync::{ - atomic::{AtomicUsize, Ordering}, - Arc, - }, + sync::atomic::{AtomicUsize, Ordering}, }; use wgpu::{ BufferUsages, Extent3d, RenderPassColorAttachment, RenderPassDepthStencilAttachment, StoreOp, diff --git a/crates/bevy_render/src/view/visibility/mod.rs b/crates/bevy_render/src/view/visibility/mod.rs index b219b89f12b65..adef70251bb88 100644 --- a/crates/bevy_render/src/view/visibility/mod.rs +++ b/crates/bevy_render/src/view/visibility/mod.rs @@ -1,7 +1,7 @@ mod range; mod render_layers; -use std::any::TypeId; +use core::any::TypeId; pub use range::*; pub use render_layers::*; diff --git a/crates/bevy_render/src/view/visibility/range.rs b/crates/bevy_render/src/view/visibility/range.rs index 50c49eb657825..cbf93d2b2674a 100644 --- a/crates/bevy_render/src/view/visibility/range.rs +++ b/crates/bevy_render/src/view/visibility/range.rs @@ -1,7 +1,7 @@ //! Specific distances from the camera in which entities are visible, also known //! as *hierarchical levels of detail* or *HLOD*s. -use std::{ +use core::{ hash::{Hash, Hasher}, ops::Range, }; diff --git a/crates/bevy_render/src/view/visibility/render_layers.rs b/crates/bevy_render/src/view/visibility/render_layers.rs index 81a1df0c2f9e0..1932abdf71fba 100644 --- a/crates/bevy_render/src/view/visibility/render_layers.rs +++ b/crates/bevy_render/src/view/visibility/render_layers.rs @@ -1,6 +1,5 @@ use bevy_ecs::prelude::{Component, ReflectComponent}; -use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; +use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use smallvec::SmallVec; pub const DEFAULT_LAYERS: &RenderLayers = &RenderLayers::layer(0); @@ -33,8 +32,8 @@ impl Default for &RenderLayers { } } -impl std::fmt::Debug for RenderLayers { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for RenderLayers { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_tuple("RenderLayers") .field(&self.iter().collect::>()) .finish() @@ -153,7 +152,7 @@ impl RenderLayers { } fn extend_buffer(&mut self, other_len: usize) { - let new_size = std::cmp::max(self.0.len(), other_len); + let new_size = core::cmp::max(self.0.len(), other_len); self.0.reserve_exact(new_size - self.0.len()); self.0.resize(new_size, 0u64); } @@ -161,7 +160,7 @@ impl RenderLayers { fn iter_layers(buffer_and_offset: (u64, usize)) -> impl Iterator + 'static { let (mut buffer, mut layer) = buffer_and_offset; layer *= 64; - std::iter::from_fn(move || { + core::iter::from_fn(move || { if buffer == 0 { return None; } @@ -215,7 +214,7 @@ impl RenderLayers { fn combine_blocks(&self, other: &Self, mut f: impl FnMut(u64, u64) -> u64) -> Self { let mut a = self.0.iter(); let mut b = other.0.iter(); - let mask = std::iter::from_fn(|| { + let mask = core::iter::from_fn(|| { let a = a.next().copied(); let b = b.next().copied(); if a.is_none() && b.is_none() { @@ -227,21 +226,21 @@ impl RenderLayers { } } -impl std::ops::BitAnd for RenderLayers { +impl core::ops::BitAnd for RenderLayers { type Output = Self; fn bitand(self, rhs: Self) -> Self::Output { self.intersection(&rhs) } } -impl std::ops::BitOr for RenderLayers { +impl core::ops::BitOr for RenderLayers { type Output = Self; fn bitor(self, rhs: Self) -> Self::Output { self.union(&rhs) } } -impl std::ops::BitXor for RenderLayers { +impl core::ops::BitXor for RenderLayers { type Output = Self; fn bitxor(self, rhs: Self) -> Self::Output { self.symmetric_difference(&rhs) diff --git a/crates/bevy_render/src/view/window/mod.rs b/crates/bevy_render/src/view/window/mod.rs index 0eb9e95d8718e..1def6df2aee16 100644 --- a/crates/bevy_render/src/view/window/mod.rs +++ b/crates/bevy_render/src/view/window/mod.rs @@ -11,11 +11,11 @@ use bevy_utils::{default, tracing::debug, HashSet}; use bevy_window::{ CompositeAlphaMode, PresentMode, PrimaryWindow, RawHandleWrapper, Window, WindowClosing, }; -use cursor::CursorPlugin; -use std::{ +use core::{ num::NonZero, ops::{Deref, DerefMut}, }; +use cursor::CursorPlugin; use wgpu::{ SurfaceConfiguration, SurfaceTargetUnsafe, TextureFormat, TextureUsages, TextureViewDescriptor, }; diff --git a/crates/bevy_render/src/view/window/screenshot.rs b/crates/bevy_render/src/view/window/screenshot.rs index bc53fc9880f82..b17de0d2f2c8f 100644 --- a/crates/bevy_render/src/view/window/screenshot.rs +++ b/crates/bevy_render/src/view/window/screenshot.rs @@ -1,41 +1,43 @@ use super::ExtractedWindows; -use crate::camera::{ - ManualTextureViewHandle, ManualTextureViews, NormalizedRenderTarget, RenderTarget, -}; -use crate::render_asset::RenderAssets; -use crate::render_resource::{BindGroupEntries, BufferUsages, TextureUsages, TextureView}; -use crate::texture::{GpuImage, OutputColorAttachment}; -use crate::view::{ - prepare_view_attachments, prepare_view_targets, ViewTargetAttachments, WindowSurfaces, -}; use crate::{ + camera::{ManualTextureViewHandle, ManualTextureViews, NormalizedRenderTarget, RenderTarget}, prelude::{Image, Shader}, - render_asset::RenderAssetUsages, + render_asset::{RenderAssetUsages, RenderAssets}, render_resource::{ - binding_types::texture_2d, BindGroup, BindGroupLayout, BindGroupLayoutEntries, Buffer, - CachedRenderPipelineId, FragmentState, PipelineCache, RenderPipelineDescriptor, - SpecializedRenderPipeline, SpecializedRenderPipelines, Texture, VertexState, + binding_types::texture_2d, BindGroup, BindGroupEntries, BindGroupLayout, + BindGroupLayoutEntries, Buffer, BufferUsages, CachedRenderPipelineId, FragmentState, + PipelineCache, RenderPipelineDescriptor, SpecializedRenderPipeline, + SpecializedRenderPipelines, Texture, TextureUsages, TextureView, VertexState, }, renderer::RenderDevice, - texture::TextureFormatPixelInfo, + texture::{GpuImage, OutputColorAttachment, TextureFormatPixelInfo}, + view::{prepare_view_attachments, prepare_view_targets, ViewTargetAttachments, WindowSurfaces}, ExtractSchedule, MainWorld, Render, RenderApp, RenderSet, }; +use alloc::{borrow::Cow, sync::Arc}; use bevy_app::{First, Plugin, Update}; use bevy_asset::{load_internal_asset, Handle}; use bevy_derive::{Deref, DerefMut}; -use bevy_ecs::event::event_update_system; -use bevy_ecs::system::SystemState; -use bevy_ecs::{entity::EntityHashMap, prelude::*}; +use bevy_ecs::{ + entity::EntityHashMap, event::event_update_system, prelude::*, system::SystemState, +}; use bevy_hierarchy::DespawnRecursiveExt; use bevy_reflect::Reflect; use bevy_tasks::AsyncComputeTaskPool; -use bevy_utils::tracing::{error, info, warn}; -use bevy_utils::{default, HashSet}; +use bevy_utils::{ + default, + tracing::{error, info, warn}, + HashSet, +}; use bevy_window::{PrimaryWindow, WindowRef}; -use std::ops::Deref; -use std::sync::mpsc::{Receiver, Sender}; -use std::sync::{Arc, Mutex}; -use std::{borrow::Cow, path::Path}; +use core::ops::Deref; +use std::{ + path::Path, + sync::{ + mpsc::{Receiver, Sender}, + Mutex, + }, +}; use wgpu::{ CommandEncoder, Extent3d, ImageDataLayout, TextureFormat, COPY_BYTES_PER_ROW_ALIGNMENT, }; diff --git a/crates/bevy_scene/src/bundle.rs b/crates/bevy_scene/src/bundle.rs index a154acdccdaa5..ac656f15af93f 100644 --- a/crates/bevy_scene/src/bundle.rs +++ b/crates/bevy_scene/src/bundle.rs @@ -104,9 +104,11 @@ mod tests { use crate::{DynamicScene, DynamicSceneBundle, ScenePlugin, SceneSpawner}; use bevy_app::{App, ScheduleRunnerPlugin}; use bevy_asset::{AssetPlugin, Assets}; - use bevy_ecs::component::Component; - use bevy_ecs::entity::Entity; - use bevy_ecs::prelude::{AppTypeRegistry, ReflectComponent, World}; + use bevy_ecs::{ + component::Component, + entity::Entity, + prelude::{AppTypeRegistry, ReflectComponent, World}, + }; use bevy_hierarchy::{Children, HierarchyPlugin}; use bevy_reflect::Reflect; use bevy_utils::default; diff --git a/crates/bevy_scene/src/dynamic_scene.rs b/crates/bevy_scene/src/dynamic_scene.rs index 411d5a6099b98..7f094ce0167ed 100644 --- a/crates/bevy_scene/src/dynamic_scene.rs +++ b/crates/bevy_scene/src/dynamic_scene.rs @@ -1,7 +1,6 @@ use crate::{ron, DynamicSceneBuilder, Scene, SceneSpawnError}; -use bevy_ecs::entity::EntityHashMap; use bevy_ecs::{ - entity::Entity, + entity::{Entity, EntityHashMap}, reflect::{AppTypeRegistry, ReflectComponent, ReflectMapEntities}, world::World, }; @@ -209,10 +208,12 @@ where #[cfg(test)] mod tests { - use bevy_ecs::entity::{Entity, EntityHashMap, EntityMapper, MapEntities}; - use bevy_ecs::reflect::{ReflectMapEntitiesResource, ReflectResource}; - use bevy_ecs::system::Resource; - use bevy_ecs::{reflect::AppTypeRegistry, world::Command, world::World}; + use bevy_ecs::{ + entity::{Entity, EntityHashMap, EntityMapper, MapEntities}, + reflect::{AppTypeRegistry, ReflectMapEntitiesResource, ReflectResource}, + system::Resource, + world::{Command, World}, + }; use bevy_hierarchy::{AddChild, Parent}; use bevy_reflect::Reflect; diff --git a/crates/bevy_scene/src/dynamic_scene_builder.rs b/crates/bevy_scene/src/dynamic_scene_builder.rs index e7d451968785c..894f300a9b651 100644 --- a/crates/bevy_scene/src/dynamic_scene_builder.rs +++ b/crates/bevy_scene/src/dynamic_scene_builder.rs @@ -1,14 +1,14 @@ use crate::{DynamicEntity, DynamicScene, SceneFilter}; -use bevy_ecs::component::{Component, ComponentId}; -use bevy_ecs::system::Resource; +use alloc::collections::BTreeMap; use bevy_ecs::{ + component::{Component, ComponentId}, prelude::Entity, reflect::{AppTypeRegistry, ReflectComponent, ReflectResource}, + system::Resource, world::World, }; use bevy_reflect::{PartialReflect, ReflectFromReflect}; use bevy_utils::default; -use std::collections::BTreeMap; /// A [`DynamicScene`] builder, used to build a scene from a [`World`] by extracting some entities and resources. /// @@ -217,7 +217,7 @@ impl<'w> DynamicSceneBuilder<'w> { /// Re-extracting an entity that was already extracted will have no effect. #[must_use] pub fn extract_entity(self, entity: Entity) -> Self { - self.extract_entities(std::iter::once(entity)) + self.extract_entities(core::iter::once(entity)) } /// Despawns all entities with no components. @@ -384,8 +384,10 @@ impl<'w> DynamicSceneBuilder<'w> { #[cfg(test)] mod tests { use bevy_ecs::{ - component::Component, prelude::Entity, prelude::Resource, query::With, - reflect::AppTypeRegistry, reflect::ReflectComponent, reflect::ReflectResource, + component::Component, + prelude::{Entity, Resource}, + query::With, + reflect::{AppTypeRegistry, ReflectComponent, ReflectResource}, world::World, }; diff --git a/crates/bevy_scene/src/lib.rs b/crates/bevy_scene/src/lib.rs index 1fbf3b11b0c97..ffbc7af17e790 100644 --- a/crates/bevy_scene/src/lib.rs +++ b/crates/bevy_scene/src/lib.rs @@ -11,6 +11,8 @@ //! instantiated or removed from a world to allow composition. Scenes can be serialized/deserialized, //! for example to save part of the world state to a file. +extern crate alloc; + mod bundle; mod dynamic_scene; mod dynamic_scene_builder; diff --git a/crates/bevy_scene/src/scene.rs b/crates/bevy_scene/src/scene.rs index f852d356b390b..5d0cf57639201 100644 --- a/crates/bevy_scene/src/scene.rs +++ b/crates/bevy_scene/src/scene.rs @@ -1,7 +1,7 @@ use crate::{DynamicScene, SceneSpawnError}; use bevy_asset::Asset; -use bevy_ecs::entity::{Entity, EntityHashMap}; use bevy_ecs::{ + entity::{Entity, EntityHashMap}, reflect::{AppTypeRegistry, ReflectComponent, ReflectMapEntities, ReflectResource}, world::World, }; diff --git a/crates/bevy_scene/src/scene_filter.rs b/crates/bevy_scene/src/scene_filter.rs index 1bdfdfa871a45..eb86984903c79 100644 --- a/crates/bevy_scene/src/scene_filter.rs +++ b/crates/bevy_scene/src/scene_filter.rs @@ -1,6 +1,5 @@ -use bevy_utils::hashbrown::hash_set::IntoIter; -use bevy_utils::HashSet; -use std::any::{Any, TypeId}; +use bevy_utils::{hashbrown::hash_set::IntoIter, HashSet}; +use core::any::{Any, TypeId}; /// A filter used to control which types can be added to a [`DynamicScene`]. /// diff --git a/crates/bevy_scene/src/scene_loader.rs b/crates/bevy_scene/src/scene_loader.rs index 566a573560d0f..200fb2d7eaaa2 100644 --- a/crates/bevy_scene/src/scene_loader.rs +++ b/crates/bevy_scene/src/scene_loader.rs @@ -1,10 +1,11 @@ -use crate::ron; #[cfg(feature = "serialize")] use crate::serde::SceneDeserializer; -use crate::DynamicScene; +use crate::{ron, DynamicScene}; use bevy_asset::{io::Reader, AssetLoader, LoadContext}; -use bevy_ecs::reflect::AppTypeRegistry; -use bevy_ecs::world::{FromWorld, World}; +use bevy_ecs::{ + reflect::AppTypeRegistry, + world::{FromWorld, World}, +}; use bevy_reflect::TypeRegistryArc; #[cfg(feature = "serialize")] use serde::de::DeserializeSeed; diff --git a/crates/bevy_scene/src/scene_spawner.rs b/crates/bevy_scene/src/scene_spawner.rs index fb3fa62466194..7341d9a250d21 100644 --- a/crates/bevy_scene/src/scene_spawner.rs +++ b/crates/bevy_scene/src/scene_spawner.rs @@ -1,8 +1,7 @@ use crate::{DynamicScene, Scene}; use bevy_asset::{AssetEvent, AssetId, Assets, Handle}; -use bevy_ecs::entity::EntityHashMap; use bevy_ecs::{ - entity::Entity, + entity::{Entity, EntityHashMap}, event::{Event, EventCursor, Events}, reflect::AppTypeRegistry, system::Resource, @@ -286,7 +285,7 @@ impl SceneSpawner { /// Immediately despawns all scenes scheduled for despawn by despawning their instances. pub fn despawn_queued_scenes(&mut self, world: &mut World) -> Result<(), SceneSpawnError> { - let scenes_to_despawn = std::mem::take(&mut self.scenes_to_despawn); + let scenes_to_despawn = core::mem::take(&mut self.scenes_to_despawn); for scene_handle in scenes_to_despawn { self.despawn_sync(world, scene_handle)?; @@ -296,7 +295,7 @@ impl SceneSpawner { /// Immediately despawns all scene instances scheduled for despawn. pub fn despawn_queued_instances(&mut self, world: &mut World) { - let instances_to_despawn = std::mem::take(&mut self.instances_to_despawn); + let instances_to_despawn = core::mem::take(&mut self.instances_to_despawn); for instance_id in instances_to_despawn { self.despawn_instance_sync(world, &instance_id); @@ -305,7 +304,7 @@ impl SceneSpawner { /// Immediately spawns all scenes scheduled for spawn. pub fn spawn_queued_scenes(&mut self, world: &mut World) -> Result<(), SceneSpawnError> { - let scenes_to_spawn = std::mem::take(&mut self.dynamic_scenes_to_spawn); + let scenes_to_spawn = core::mem::take(&mut self.dynamic_scenes_to_spawn); for (handle, instance_id, parent) in scenes_to_spawn { let mut entity_map = EntityHashMap::default(); @@ -335,7 +334,7 @@ impl SceneSpawner { } } - let scenes_to_spawn = std::mem::take(&mut self.scenes_to_spawn); + let scenes_to_spawn = core::mem::take(&mut self.scenes_to_spawn); for (scene_handle, instance_id, parent) in scenes_to_spawn { let mut entity_map = EntityHashMap::default(); @@ -364,7 +363,7 @@ impl SceneSpawner { } pub(crate) fn set_scene_instance_parent_sync(&mut self, world: &mut World) { - let scenes_with_parent = std::mem::take(&mut self.scenes_with_parent); + let scenes_with_parent = core::mem::take(&mut self.scenes_with_parent); for (instance_id, parent) in scenes_with_parent { if let Some(instance) = self.spawned_instances.get(&instance_id) { @@ -473,13 +472,14 @@ pub fn scene_spawner_system(world: &mut World) { #[cfg(test)] mod tests { use bevy_app::App; - use bevy_asset::Handle; - use bevy_asset::{AssetPlugin, AssetServer}; - use bevy_ecs::observer::Trigger; - use bevy_ecs::prelude::ReflectComponent; - use bevy_ecs::query::With; - use bevy_ecs::system::{Commands, Res, ResMut, RunSystemOnce}; - use bevy_ecs::{component::Component, system::Query}; + use bevy_asset::{AssetPlugin, AssetServer, Handle}; + use bevy_ecs::{ + component::Component, + observer::Trigger, + prelude::ReflectComponent, + query::With, + system::{Commands, Query, Res, ResMut, RunSystemOnce}, + }; use bevy_reflect::Reflect; use crate::{DynamicSceneBuilder, ScenePlugin}; diff --git a/crates/bevy_scene/src/serde.rs b/crates/bevy_scene/src/serde.rs index bbf57350186a9..cdb0db9597343 100644 --- a/crates/bevy_scene/src/serde.rs +++ b/crates/bevy_scene/src/serde.rs @@ -2,20 +2,20 @@ use crate::{DynamicEntity, DynamicScene}; use bevy_ecs::entity::Entity; -use bevy_reflect::serde::{TypedReflectDeserializer, TypedReflectSerializer}; use bevy_reflect::{ - serde::{ReflectDeserializer, TypeRegistrationDeserializer}, - TypeRegistry, + serde::{ + ReflectDeserializer, TypeRegistrationDeserializer, TypedReflectDeserializer, + TypedReflectSerializer, + }, + PartialReflect, ReflectFromReflect, TypeRegistry, }; -use bevy_reflect::{PartialReflect, ReflectFromReflect}; use bevy_utils::HashSet; -use serde::ser::SerializeMap; +use core::fmt::Formatter; use serde::{ de::{DeserializeSeed, Error, MapAccess, SeqAccess, Visitor}, - ser::SerializeStruct, + ser::{SerializeMap, SerializeStruct}, Deserialize, Deserializer, Serialize, Serializer, }; -use std::fmt::Formatter; /// Name of the serialized scene struct type. pub const SCENE_STRUCT: &str = "Scene"; @@ -237,7 +237,7 @@ struct SceneVisitor<'a> { impl<'a, 'de> Visitor<'de> for SceneVisitor<'a> { type Value = DynamicScene; - fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result { + fn expecting(&self, formatter: &mut Formatter) -> core::fmt::Result { formatter.write_str("scene struct") } @@ -326,7 +326,7 @@ struct SceneEntitiesVisitor<'a> { impl<'a, 'de> Visitor<'de> for SceneEntitiesVisitor<'a> { type Value = Vec; - fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result { + fn expecting(&self, formatter: &mut Formatter) -> core::fmt::Result { formatter.write_str("map of entities") } @@ -381,7 +381,7 @@ struct SceneEntityVisitor<'a> { impl<'a, 'de> Visitor<'de> for SceneEntityVisitor<'a> { type Value = DynamicEntity; - fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result { + fn expecting(&self, formatter: &mut Formatter) -> core::fmt::Result { formatter.write_str("entities") } @@ -456,7 +456,7 @@ struct SceneMapVisitor<'a> { impl<'a, 'de> Visitor<'de> for SceneMapVisitor<'a> { type Value = Vec>; - fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result { + fn expecting(&self, formatter: &mut Formatter) -> core::fmt::Result { formatter.write_str("map of reflect types") } @@ -509,19 +509,21 @@ impl<'a, 'de> Visitor<'de> for SceneMapVisitor<'a> { #[cfg(test)] mod tests { - use crate::ron; - use crate::serde::{SceneDeserializer, SceneSerializer}; - use crate::{DynamicScene, DynamicSceneBuilder}; - use bevy_ecs::entity::EntityHashMap; - use bevy_ecs::entity::{Entity, EntityMapper, MapEntities}; - use bevy_ecs::prelude::{Component, ReflectComponent, ReflectResource, Resource, World}; - use bevy_ecs::query::{With, Without}; - use bevy_ecs::reflect::{AppTypeRegistry, ReflectMapEntities}; - use bevy_ecs::world::FromWorld; + use crate::{ + ron, + serde::{SceneDeserializer, SceneSerializer}, + DynamicScene, DynamicSceneBuilder, + }; + use bevy_ecs::{ + entity::{Entity, EntityHashMap, EntityMapper, MapEntities}, + prelude::{Component, ReflectComponent, ReflectResource, Resource, World}, + query::{With, Without}, + reflect::{AppTypeRegistry, ReflectMapEntities}, + world::FromWorld, + }; use bevy_reflect::{Reflect, ReflectDeserialize, ReflectSerialize}; use bincode::Options; - use serde::de::DeserializeSeed; - use serde::{Deserialize, Serialize}; + use serde::{de::DeserializeSeed, Deserialize, Serialize}; use std::io::BufReader; #[derive(Component, Reflect, Default)] diff --git a/crates/bevy_sprite/src/lib.rs b/crates/bevy_sprite/src/lib.rs index 163d3878bc474..a411cef4afc1f 100644 --- a/crates/bevy_sprite/src/lib.rs +++ b/crates/bevy_sprite/src/lib.rs @@ -8,6 +8,9 @@ )] //! Provides 2D sprite rendering functionality. + +extern crate alloc; + mod bundle; mod dynamic_texture_atlas_builder; mod mesh2d; diff --git a/crates/bevy_sprite/src/mesh2d/material.rs b/crates/bevy_sprite/src/mesh2d/material.rs index 6c91e27ee849f..be3010792a0f4 100644 --- a/crates/bevy_sprite/src/mesh2d/material.rs +++ b/crates/bevy_sprite/src/mesh2d/material.rs @@ -33,7 +33,7 @@ use bevy_render::{ }; use bevy_transform::components::{GlobalTransform, Transform}; use bevy_utils::tracing::error; -use std::{hash::Hash, marker::PhantomData}; +use core::{hash::Hash, marker::PhantomData}; use crate::{ DrawMesh2d, Mesh2dHandle, Mesh2dPipeline, Mesh2dPipelineKey, RenderMesh2dInstances, @@ -268,7 +268,7 @@ impl Hash for Material2dKey where M::Data: Hash, { - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { self.mesh_key.hash(state); self.bind_group_data.hash(state); } diff --git a/crates/bevy_sprite/src/mesh2d/mesh.rs b/crates/bevy_sprite/src/mesh2d/mesh.rs index 7ef45ec298ed9..0f70232afcdf8 100644 --- a/crates/bevy_sprite/src/mesh2d/mesh.rs +++ b/crates/bevy_sprite/src/mesh2d/mesh.rs @@ -16,26 +16,26 @@ use bevy_ecs::{ }; use bevy_math::{Affine3, Vec4}; use bevy_reflect::{std_traits::ReflectDefault, Reflect}; -use bevy_render::batching::gpu_preprocessing::IndirectParameters; -use bevy_render::batching::no_gpu_preprocessing::batch_and_prepare_binned_render_phase; -use bevy_render::batching::no_gpu_preprocessing::{ - self, batch_and_prepare_sorted_render_phase, write_batched_instance_buffer, - BatchedInstanceBuffer, -}; -use bevy_render::batching::GetFullBatchData; -use bevy_render::mesh::allocator::MeshAllocator; -use bevy_render::mesh::{MeshVertexBufferLayoutRef, RenderMesh}; -use bevy_render::texture::FallbackImage; use bevy_render::{ - batching::{GetBatchData, NoAutomaticBatching}, + batching::{ + gpu_preprocessing::IndirectParameters, + no_gpu_preprocessing::{ + self, batch_and_prepare_binned_render_phase, batch_and_prepare_sorted_render_phase, + write_batched_instance_buffer, BatchedInstanceBuffer, + }, + GetBatchData, GetFullBatchData, NoAutomaticBatching, + }, globals::{GlobalsBuffer, GlobalsUniform}, - mesh::{Mesh, RenderMeshBufferInfo}, + mesh::{ + allocator::MeshAllocator, Mesh, MeshVertexBufferLayoutRef, RenderMesh, RenderMeshBufferInfo, + }, render_asset::RenderAssets, render_phase::{PhaseItem, RenderCommand, RenderCommandResult, TrackedRenderPass}, render_resource::{binding_types::uniform_buffer, *}, renderer::{RenderDevice, RenderQueue}, texture::{ - BevyDefault, DefaultImageSampler, GpuImage, Image, ImageSampler, TextureFormatPixelInfo, + BevyDefault, DefaultImageSampler, FallbackImage, GpuImage, Image, ImageSampler, + TextureFormatPixelInfo, }, view::{ ExtractedView, ViewTarget, ViewUniform, ViewUniformOffset, ViewUniforms, ViewVisibility, diff --git a/crates/bevy_sprite/src/picking_backend.rs b/crates/bevy_sprite/src/picking_backend.rs index 15fd90b0842ae..baf06d1a143b4 100644 --- a/crates/bevy_sprite/src/picking_backend.rs +++ b/crates/bevy_sprite/src/picking_backend.rs @@ -2,7 +2,7 @@ //! sprites with arbitrary transforms. Picking is done based on sprite bounds, not visible pixels. //! This means a partially transparent sprite is pickable even in its transparent areas. -use std::cmp::Reverse; +use core::cmp::Reverse; use crate::{Sprite, TextureAtlas, TextureAtlasLayout}; use bevy_app::prelude::*; diff --git a/crates/bevy_sprite/src/render/mod.rs b/crates/bevy_sprite/src/render/mod.rs index 60c64131fe12b..1efa866ec7e64 100644 --- a/crates/bevy_sprite/src/render/mod.rs +++ b/crates/bevy_sprite/src/render/mod.rs @@ -1,4 +1,4 @@ -use std::ops::Range; +use core::ops::Range; use crate::{ texture_atlas::{TextureAtlas, TextureAtlasLayout}, @@ -13,9 +13,10 @@ use bevy_core_pipeline::{ TonemappingLuts, }, }; -use bevy_ecs::{entity::EntityHashMap, query::ROQueryItem}; use bevy_ecs::{ + entity::EntityHashMap, prelude::*, + query::ROQueryItem, system::{lifetimeless::*, SystemParamItem, SystemState}, }; use bevy_math::{Affine3A, FloatOrd, Quat, Rect, Vec2, Vec4}; diff --git a/crates/bevy_sprite/src/texture_atlas.rs b/crates/bevy_sprite/src/texture_atlas.rs index 70e10e591431a..a22cbe8e913e0 100644 --- a/crates/bevy_sprite/src/texture_atlas.rs +++ b/crates/bevy_sprite/src/texture_atlas.rs @@ -1,9 +1,7 @@ use bevy_asset::{Asset, AssetId, Assets, Handle}; -use bevy_ecs::component::Component; -use bevy_ecs::reflect::ReflectComponent; +use bevy_ecs::{component::Component, reflect::ReflectComponent}; use bevy_math::{URect, UVec2}; -use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; +use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_render::texture::Image; use bevy_utils::HashMap; diff --git a/crates/bevy_sprite/src/texture_atlas_builder.rs b/crates/bevy_sprite/src/texture_atlas_builder.rs index e000516a7dacc..8aad5216c02aa 100644 --- a/crates/bevy_sprite/src/texture_atlas_builder.rs +++ b/crates/bevy_sprite/src/texture_atlas_builder.rs @@ -5,8 +5,10 @@ use bevy_render::{ render_resource::{Extent3d, TextureDimension, TextureFormat}, texture::{Image, TextureFormatPixelInfo}, }; -use bevy_utils::tracing::{debug, error, warn}; -use bevy_utils::HashMap; +use bevy_utils::{ + tracing::{debug, error, warn}, + HashMap, +}; use rectangle_pack::{ contains_smallest_box, pack_rects, volume_heuristic, GroupedRectsToPlace, PackedLocation, RectToInsert, TargetBin, @@ -227,7 +229,7 @@ impl<'a> TextureAtlasBuilder<'a> { let last_attempt = current_height == max_height && current_width == max_width; - let mut target_bins = std::collections::BTreeMap::new(); + let mut target_bins = alloc::collections::BTreeMap::new(); target_bins.insert(0, TargetBin::new(current_width, current_height, 1)); rect_placements = match pack_rects( &rects_to_place, diff --git a/crates/bevy_state/src/app.rs b/crates/bevy_state/src/app.rs index 4541a1cd5d62c..666b35ce846a6 100644 --- a/crates/bevy_state/src/app.rs +++ b/crates/bevy_state/src/app.rs @@ -2,11 +2,13 @@ use bevy_app::{App, MainScheduleOrder, Plugin, PreStartup, PreUpdate, SubApp}; use bevy_ecs::{event::Events, schedule::IntoSystemConfigs, world::FromWorld}; use bevy_utils::{tracing::warn, warn_once}; -use crate::state::{ - setup_state_transitions_in_world, ComputedStates, FreelyMutableState, NextState, State, - StateTransition, StateTransitionEvent, StateTransitionSteps, States, SubStates, +use crate::{ + state::{ + setup_state_transitions_in_world, ComputedStates, FreelyMutableState, NextState, State, + StateTransition, StateTransitionEvent, StateTransitionSteps, States, SubStates, + }, + state_scoped::clear_state_scoped_entities, }; -use crate::state_scoped::clear_state_scoped_entities; #[cfg(feature = "bevy_reflect")] use bevy_reflect::{FromReflect, GetTypeRegistration, Typed}; @@ -103,7 +105,7 @@ impl AppExtStates for SubApp { entered: Some(state), }); } else { - let name = std::any::type_name::(); + let name = core::any::type_name::(); warn!("State {} is already initialized.", name); } @@ -159,7 +161,7 @@ impl AppExtStates for SubApp { entered: state, }); } else { - let name = std::any::type_name::(); + let name = core::any::type_name::(); warn!("Computed state {} is already initialized.", name); } @@ -187,7 +189,7 @@ impl AppExtStates for SubApp { entered: state, }); } else { - let name = std::any::type_name::(); + let name = core::any::type_name::(); warn!("Sub state {} is already initialized.", name); } @@ -199,7 +201,7 @@ impl AppExtStates for SubApp { .world() .contains_resource::>>() { - let name = std::any::type_name::(); + let name = core::any::type_name::(); warn!("State scoped entities are enabled for state `{}`, but the state isn't installed in the app!", name); } // We work with [`StateTransition`] in set [`StateTransitionSteps::ExitSchedules`] as opposed to [`OnExit`], diff --git a/crates/bevy_state/src/lib.rs b/crates/bevy_state/src/lib.rs index c2aba9c24d1ac..c8cc1855bcc72 100644 --- a/crates/bevy_state/src/lib.rs +++ b/crates/bevy_state/src/lib.rs @@ -59,23 +59,21 @@ pub mod reflect; pub mod prelude { #[cfg(feature = "bevy_app")] #[doc(hidden)] - pub use crate::app::AppExtStates; - #[doc(hidden)] - pub use crate::commands::CommandsStatesExt; - #[doc(hidden)] - pub use crate::condition::*; + pub use crate::{app::AppExtStates, state_scoped_events::StateScopedEventsAppExt}; + #[cfg(feature = "bevy_reflect")] #[doc(hidden)] pub use crate::reflect::{ReflectFreelyMutableState, ReflectState}; + #[doc(hidden)] - pub use crate::state::{ - last_transition, ComputedStates, EnterSchedules, ExitSchedules, NextState, OnEnter, OnExit, - OnTransition, State, StateSet, StateTransition, StateTransitionEvent, States, SubStates, - TransitionSchedules, + pub use crate::{ + commands::CommandsStatesExt, + condition::*, + state::{ + last_transition, ComputedStates, EnterSchedules, ExitSchedules, NextState, OnEnter, + OnExit, OnTransition, State, StateSet, StateTransition, StateTransitionEvent, States, + SubStates, TransitionSchedules, + }, + state_scoped::StateScoped, }; - #[doc(hidden)] - pub use crate::state_scoped::StateScoped; - #[cfg(feature = "bevy_app")] - #[doc(hidden)] - pub use crate::state_scoped_events::StateScopedEventsAppExt; } diff --git a/crates/bevy_state/src/reflect.rs b/crates/bevy_state/src/reflect.rs index 422d4aff1a341..c620cd4638466 100644 --- a/crates/bevy_state/src/reflect.rs +++ b/crates/bevy_state/src/reflect.rs @@ -1,7 +1,6 @@ use crate::state::{FreelyMutableState, NextState, State, States}; -use bevy_ecs::reflect::from_reflect_with_fallback; -use bevy_ecs::world::World; +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. @@ -100,14 +99,16 @@ impl FromType for ReflectFreelyMu #[cfg(test)] mod tests { use crate as bevy_state; - use crate::app::{AppExtStates, StatesPlugin}; - use crate::reflect::{ReflectFreelyMutableState, ReflectState}; - use crate::state::State; + 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 std::any::TypeId; + use core::any::TypeId; #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, States, Reflect)] enum StateTest { diff --git a/crates/bevy_state/src/state/computed_states.rs b/crates/bevy_state/src/state/computed_states.rs index fda0f99d8c821..60e7bd79e94f3 100644 --- a/crates/bevy_state/src/state/computed_states.rs +++ b/crates/bevy_state/src/state/computed_states.rs @@ -1,10 +1,8 @@ -use std::fmt::Debug; -use std::hash::Hash; +use core::{fmt::Debug, hash::Hash}; use bevy_ecs::schedule::Schedule; -use super::state_set::StateSet; -use super::states::States; +use super::{state_set::StateSet, states::States}; /// A state whose value is automatically computed based on the values of other [`States`]. /// diff --git a/crates/bevy_state/src/state/freely_mutable_state.rs b/crates/bevy_state/src/state/freely_mutable_state.rs index f2b6dd0c21171..2bc186ebe0fb2 100644 --- a/crates/bevy_state/src/state/freely_mutable_state.rs +++ b/crates/bevy_state/src/state/freely_mutable_state.rs @@ -1,13 +1,11 @@ -use bevy_ecs::schedule::{IntoSystemConfigs, IntoSystemSetConfigs}; -use bevy_ecs::system::IntoSystem; use bevy_ecs::{ event::EventWriter, prelude::Schedule, - system::{Commands, ResMut}, + schedule::{IntoSystemConfigs, IntoSystemSetConfigs}, + system::{Commands, IntoSystem, ResMut}, }; -use super::{states::States, NextState, State}; -use super::{take_next_state, transitions::*}; +use super::{states::States, take_next_state, transitions::*, NextState, State}; /// This trait allows a state to be mutated directly using the [`NextState`](crate::state::NextState) resource. /// diff --git a/crates/bevy_state/src/state/mod.rs b/crates/bevy_state/src/state/mod.rs index 5e5ea005df0d7..d02d3a32ed452 100644 --- a/crates/bevy_state/src/state/mod.rs +++ b/crates/bevy_state/src/state/mod.rs @@ -17,10 +17,8 @@ pub use transitions::*; #[cfg(test)] mod tests { - use bevy_ecs::event::EventRegistry; - use bevy_ecs::prelude::*; - use bevy_state_macros::States; - use bevy_state_macros::SubStates; + use bevy_ecs::{event::EventRegistry, prelude::*}; + use bevy_state_macros::{States, SubStates}; use super::*; use crate as bevy_state; diff --git a/crates/bevy_state/src/state/resources.rs b/crates/bevy_state/src/state/resources.rs index e4d5804ebf51e..71c192cb2a3e7 100644 --- a/crates/bevy_state/src/state/resources.rs +++ b/crates/bevy_state/src/state/resources.rs @@ -1,4 +1,4 @@ -use std::ops::Deref; +use core::ops::Deref; use bevy_ecs::{ change_detection::DetectChangesMut, @@ -145,7 +145,7 @@ pub(crate) fn take_next_state( ) -> Option { let mut next_state = next_state?; - match std::mem::take(next_state.bypass_change_detection()) { + match core::mem::take(next_state.bypass_change_detection()) { NextState::Pending(x) => { next_state.set_changed(); Some(x) diff --git a/crates/bevy_state/src/state/states.rs b/crates/bevy_state/src/state/states.rs index 057d6fca0e89e..3d315ab202fd8 100644 --- a/crates/bevy_state/src/state/states.rs +++ b/crates/bevy_state/src/state/states.rs @@ -1,6 +1,6 @@ -use std::fmt::Debug; +use core::fmt::Debug; -use std::hash::Hash; +use core::hash::Hash; /// Types that can define world-wide states in a finite-state machine. /// diff --git a/crates/bevy_state/src/state/transitions.rs b/crates/bevy_state/src/state/transitions.rs index 08f3d254acd28..6902a791c5d20 100644 --- a/crates/bevy_state/src/state/transitions.rs +++ b/crates/bevy_state/src/state/transitions.rs @@ -1,4 +1,4 @@ -use std::{marker::PhantomData, mem}; +use core::{marker::PhantomData, mem}; use bevy_ecs::{ event::{Event, EventReader, EventWriter}, diff --git a/crates/bevy_state/src/state_scoped_events.rs b/crates/bevy_state/src/state_scoped_events.rs index 5e2c3f68c45f3..fbeafe545310b 100644 --- a/crates/bevy_state/src/state_scoped_events.rs +++ b/crates/bevy_state/src/state_scoped_events.rs @@ -1,4 +1,4 @@ -use std::marker::PhantomData; +use core::marker::PhantomData; use bevy_app::{App, SubApp}; use bevy_ecs::{ diff --git a/crates/bevy_tasks/Cargo.toml b/crates/bevy_tasks/Cargo.toml index 0e8831e59f9c9..53fd71995220d 100644 --- a/crates/bevy_tasks/Cargo.toml +++ b/crates/bevy_tasks/Cargo.toml @@ -9,14 +9,36 @@ license = "MIT OR Apache-2.0" keywords = ["bevy"] [features] -multi_threaded = ["dep:async-channel", "dep:concurrent-queue"] +default = ["std"] +multi_threaded = ["std", "dep:async-channel"] +async-io = ["std", "dep:async-io"] +std = [ + "futures-lite/std", + "async-task/std", + "slab/std", + "fastrand/std", + "spin/std", + "concurrent-queue/std", +] [dependencies] -futures-lite = "2.0.1" -async-executor = "1.11" +futures-lite = { version = "2.0.1", default-features = false, features = [ + "race", +] } +async-task = { version = "4.4.0", default-features = false } +slab = { version = "0.4.4", default-features = false } +fastrand = { version = "2.0.0", default-features = false } +spin = { version = "0.9.8", default-features = false, features = [ + "spin_mutex", + "rwlock", + "once", +] } +concurrent-queue = { version = "2.0.0", default-features = false } + +bevy_utils = { path = "../bevy_utils", version = "0.15.0-dev", default-features = false } + async-channel = { version = "2.2.0", optional = true } async-io = { version = "2.0.0", optional = true } -concurrent-queue = { version = "2.0.0", optional = true } [target.'cfg(target_arch = "wasm32")'.dependencies] wasm-bindgen-futures = "0.4" diff --git a/crates/bevy_tasks/src/executor.rs b/crates/bevy_tasks/src/executor.rs new file mode 100644 index 0000000000000..2d6987966be12 --- /dev/null +++ b/crates/bevy_tasks/src/executor.rs @@ -0,0 +1,837 @@ +#![expect(unsafe_code, reason = "TBA")] + +use alloc::{sync::Arc, vec::Vec}; + +use core::{ + fmt, + marker::PhantomData, + panic::{RefUnwindSafe, UnwindSafe}, + sync::atomic::{AtomicBool, AtomicPtr, Ordering}, + task::{Poll, Waker}, +}; + +use async_task::{Builder, Runnable, Task}; +use concurrent_queue::ConcurrentQueue; +use futures_lite::{future, prelude::*}; +use slab::Slab; +use spin::{Mutex, RwLock}; + +use bevy_utils::OnDrop; + +/// An async executor. +/// Based on the reference executor provided by [async_executor]. +/// +/// [async_executor]: https://crates.io/crates/async-executor +pub struct Executor<'a> { + /// The executor state. + state: AtomicPtr, + + /// Makes the `'a` lifetime invariant. + _marker: PhantomData>, +} + +// SAFETY: Executor stores no thread local state that can be accessed via other thread. +unsafe impl Send for Executor<'_> {} +// SAFETY: Executor internally synchronizes all of it's operations internally. +unsafe impl Sync for Executor<'_> {} + +impl UnwindSafe for Executor<'_> {} +impl RefUnwindSafe for Executor<'_> {} + +impl fmt::Debug for Executor<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + debug_executor(self, "Executor", f) + } +} + +impl<'a> Executor<'a> { + /// Creates a new executor. + pub const fn new() -> Executor<'a> { + Executor { + state: AtomicPtr::new(core::ptr::null_mut()), + _marker: PhantomData, + } + } + + /// Returns `true` if there are no unfinished tasks. + pub fn is_empty(&self) -> bool { + self.state().active.lock().is_empty() + } + + /// Spawns a task onto the executor. + pub fn spawn(&self, future: impl Future + Send + 'a) -> Task { + let mut active = self.state().active.lock(); + + // SAFETY: `T` and the future are `Send`. + unsafe { self.spawn_inner(future, &mut active) } + } + + /// Spawn a future while holding the inner lock. + /// + /// # Safety + /// + /// If this is an `Executor`, `F` and `T` must be `Send`. + unsafe fn spawn_inner( + &self, + future: impl Future + 'a, + active: &mut Slab, + ) -> Task { + // Remove the task from the set of active tasks when the future finishes. + let entry = active.vacant_entry(); + let index = entry.key(); + let state = self.state_as_arc(); + let future = async move { + let _guard = OnDrop::new(move || drop(state.active.lock().try_remove(index))); + future.await + }; + + // Create the task and register it in the set of active tasks. + // + // SAFETY: + // + // If `future` is not `Send`, this must be a `LocalExecutor` as per this + // function's unsafe precondition. Since `LocalExecutor` is `!Sync`, + // `try_tick`, `tick` and `run` can only be called from the origin + // thread of the `LocalExecutor`. Similarly, `spawn` can only be called + // from the origin thread, ensuring that `future` and the executor share + // the same origin thread. The `Runnable` can be scheduled from other + // threads, but because of the above `Runnable` can only be called or + // dropped on the origin thread. + // + // `future` is not `'static`, but we make sure that the `Runnable` does + // not outlive `'a`. When the executor is dropped, the `active` field is + // drained and all of the `Waker`s are woken. Then, the queue inside of + // the `Executor` is drained of all of its runnables. This ensures that + // runnables are dropped and this precondition is satisfied. + // + // `self.schedule()` is `Send`, `Sync` and `'static`, as checked below. + // Therefore we do not need to worry about what is done with the + // `Waker`. + let (runnable, task) = unsafe { + let builder = Builder::new(); + + #[cfg(feature = "std")] + let builder = builder.propagate_panic(true); + + builder.spawn_unchecked(|()| future, self.schedule()) + }; + entry.insert(runnable.waker()); + + runnable.schedule(); + task + } + + /// Attempts to run a task if at least one is scheduled. + /// + /// Running a scheduled task means simply polling its future once. + pub fn try_tick(&self) -> bool { + self.state().try_tick() + } + + /// Runs a single task. + /// + /// Running a task means simply polling its future once. + /// + /// If no tasks are scheduled when this method is called, it will wait until one is scheduled. + pub async fn tick(&self) { + self.state().tick().await; + } + + /// Runs the executor until the given future completes. + pub async fn run(&self, future: impl Future) -> T { + self.state().run(future).await + } + + /// Returns a function that schedules a runnable task when it gets woken up. + fn schedule(&self) -> impl Fn(Runnable) + Send + Sync + 'static { + let state = self.state_as_arc(); + + // TODO: If possible, push into the current local queue and notify the ticker. + move |runnable| { + state.queue.push(runnable).unwrap(); + state.notify(); + } + } + + /// Returns a pointer to the inner state. + #[inline] + fn state_ptr(&self) -> *const State { + let mut ptr = self.state.load(Ordering::Acquire); + if ptr.is_null() { + ptr = State::alloc_atomic(&self.state); + } + ptr + } + + /// Returns a reference to the inner state. + #[inline] + fn state(&self) -> &State { + // SAFETY: So long as an Executor lives, it's state pointer will always be valid + // when accessed through state_ptr. + unsafe { &*self.state_ptr() } + } + + // Clones the inner state Arc + #[inline] + fn state_as_arc(&self) -> Arc { + // SAFETY: So long as an Executor lives, it's state pointer will always be a valid + // Arc when accessed through state_ptr. + let arc = unsafe { Arc::from_raw(self.state_ptr()) }; + let clone = arc.clone(); + core::mem::forget(arc); + clone + } +} + +impl Drop for Executor<'_> { + fn drop(&mut self) { + let ptr = *self.state.get_mut(); + if ptr.is_null() { + return; + } + + // SAFETY: As ptr is not null, it was allocated via Arc::new and converted + // via Arc::into_raw in state_ptr. + let state = unsafe { Arc::from_raw(ptr) }; + + let mut active = state.active.lock(); + for w in active.drain() { + w.wake(); + } + drop(active); + + while state.queue.pop().is_ok() {} + } +} + +impl<'a> Default for Executor<'a> { + fn default() -> Executor<'a> { + Executor::new() + } +} + +/// A thread-local executor. +/// +/// The executor can only be run on the thread that created it. +pub struct LocalExecutor<'a> { + /// The inner executor. + inner: Executor<'a>, + + /// Makes the type `!Send` and `!Sync`. + _marker: PhantomData>, +} + +impl UnwindSafe for LocalExecutor<'_> {} +impl RefUnwindSafe for LocalExecutor<'_> {} + +impl fmt::Debug for LocalExecutor<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + debug_executor(&self.inner, "LocalExecutor", f) + } +} + +impl<'a> LocalExecutor<'a> { + /// Creates a single-threaded executor. + pub const fn new() -> LocalExecutor<'a> { + LocalExecutor { + inner: Executor::new(), + _marker: PhantomData, + } + } + + /// Returns `true` if there are no unfinished tasks. + pub fn is_empty(&self) -> bool { + self.inner().is_empty() + } + + /// Spawns a task onto the executor. + pub fn spawn(&self, future: impl Future + 'a) -> Task { + let mut active = self.inner().state().active.lock(); + + // SAFETY: This executor is not thread safe, so the future and its result + // cannot be sent to another thread. + unsafe { self.inner().spawn_inner(future, &mut active) } + } + + /// Spawns many tasks onto the executor. + /// + /// As opposed to the [`spawn`] method, this locks the executor's inner task lock once and + /// spawns all of the tasks in one go. With large amounts of tasks this can improve + /// contention. + /// + /// It is assumed that the iterator provided does not block; blocking iterators can lock up + /// the internal mutex and therefore the entire executor. Unlike [`Executor::spawn`], the + /// mutex is not released, as there are no other threads that can poll this executor. + /// + /// [`spawn`]: LocalExecutor::spawn + /// [`Executor::spawn_many`]: Executor::spawn_many + pub fn spawn_many + 'a>( + &self, + futures: impl IntoIterator, + handles: &mut impl Extend>, + ) { + let mut active = self.inner().state().active.lock(); + + // Convert all of the futures to tasks. + let tasks = futures.into_iter().map(|future| { + // SAFETY: This executor is not thread safe, so the future and its result + // cannot be sent to another thread. + unsafe { self.inner().spawn_inner(future, &mut active) } + + // As only one thread can spawn or poll tasks at a time, there is no need + // to release lock contention here. + }); + + // Push them to the user's collection. + handles.extend(tasks); + } + + /// Attempts to run a task if at least one is scheduled. + /// + /// Running a scheduled task means simply polling its future once. + pub fn try_tick(&self) -> bool { + self.inner().try_tick() + } + + /// Runs a single task. + /// + /// Running a task means simply polling its future once. + /// + /// If no tasks are scheduled when this method is called, it will wait until one is scheduled. + pub async fn tick(&self) { + self.inner().tick().await; + } + + /// Runs the executor until the given future completes. + pub async fn run(&self, future: impl Future) -> T { + self.inner().run(future).await + } + + /// Returns a reference to the inner executor. + fn inner(&self) -> &Executor<'a> { + &self.inner + } +} + +impl<'a> Default for LocalExecutor<'a> { + fn default() -> LocalExecutor<'a> { + LocalExecutor::new() + } +} + +/// The state of a executor. +struct State { + /// The global queue. + queue: ConcurrentQueue, + + /// Local queues created by runners. + local_queues: RwLock>>>, + + /// Set to `true` when a sleeping ticker is notified or no tickers are sleeping. + notified: AtomicBool, + + /// A list of sleeping tickers. + sleepers: Mutex, + + /// Currently active tasks. + active: Mutex>, +} + +impl State { + /// Creates state for a new executor. + const fn new() -> State { + State { + queue: ConcurrentQueue::unbounded(), + local_queues: RwLock::new(Vec::new()), + notified: AtomicBool::new(true), + sleepers: Mutex::new(Sleepers { + count: 0, + wakers: Vec::new(), + free_ids: Vec::new(), + }), + active: Mutex::new(Slab::new()), + } + } + + /// Notifies a sleeping ticker. + #[inline] + fn notify(&self) { + if self + .notified + .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) + .is_ok() + { + let waker = self.sleepers.lock().notify(); + if let Some(w) = waker { + w.wake(); + } + } + } + + fn try_tick(&self) -> bool { + match self.queue.pop() { + Err(_) => false, + Ok(runnable) => { + // Notify another ticker now to pick up where this ticker left off, just in case + // running the task takes a long time. + self.notify(); + + // Run the task. + runnable.run(); + true + } + } + } + + async fn tick(&self) { + let runnable = Ticker::new(self).runnable().await; + runnable.run(); + } + + async fn run(&self, future: impl Future) -> T { + let mut runner = Runner::new(self); + let mut rng = fastrand::Rng::with_seed(0x4d595df4d0f33173); + + // A future that runs tasks forever. + let run_forever = async { + loop { + for _ in 0..200 { + let runnable = runner.runnable(&mut rng).await; + runnable.run(); + } + future::yield_now().await; + } + }; + + // Run `future` and `run_forever` concurrently until `future` completes. + future.or(run_forever).await + } + + #[cold] + fn alloc_atomic(atomic_ptr: &AtomicPtr) -> *mut Self { + let state = Arc::new(Self::new()); + let ptr = Arc::into_raw(state).cast_mut(); + if let Err(actual) = atomic_ptr.compare_exchange( + core::ptr::null_mut(), + ptr, + Ordering::AcqRel, + Ordering::Acquire, + ) { + // SAFETY: This was just created from Arc::into_raw. + drop(unsafe { Arc::from_raw(ptr) }); + actual + } else { + ptr + } + } +} + +/// A list of sleeping tickers. +struct Sleepers { + /// Number of sleeping tickers (both notified and unnotified). + count: usize, + + /// IDs and wakers of sleeping unnotified tickers. + /// + /// A sleeping ticker is notified when its waker is missing from this list. + wakers: Vec<(usize, Waker)>, + + /// Reclaimed IDs. + free_ids: Vec, +} + +impl Sleepers { + /// Inserts a new sleeping ticker. + fn insert(&mut self, waker: &Waker) -> usize { + let id = match self.free_ids.pop() { + Some(id) => id, + None => self.count + 1, + }; + self.count += 1; + self.wakers.push((id, waker.clone())); + id + } + + /// Re-inserts a sleeping ticker's waker if it was notified. + /// + /// Returns `true` if the ticker was notified. + fn update(&mut self, id: usize, waker: &Waker) -> bool { + for item in &mut self.wakers { + if item.0 == id { + item.1.clone_from(waker); + return false; + } + } + + self.wakers.push((id, waker.clone())); + true + } + + /// Removes a previously inserted sleeping ticker. + /// + /// Returns `true` if the ticker was notified. + fn remove(&mut self, id: usize) -> bool { + self.count -= 1; + self.free_ids.push(id); + + for i in (0..self.wakers.len()).rev() { + if self.wakers[i].0 == id { + self.wakers.remove(i); + return false; + } + } + true + } + + /// Returns `true` if a sleeping ticker is notified or no tickers are sleeping. + fn is_notified(&self) -> bool { + self.count == 0 || self.count > self.wakers.len() + } + + /// Returns notification waker for a sleeping ticker. + /// + /// If a ticker was notified already or there are no tickers, `None` will be returned. + fn notify(&mut self) -> Option { + if self.wakers.len() == self.count { + self.wakers.pop().map(|item| item.1) + } else { + None + } + } +} + +/// Runs task one by one. +struct Ticker<'a> { + /// The executor state. + state: &'a State, + + /// Set to a non-zero sleeper ID when in sleeping state. + /// + /// States a ticker can be in: + /// 1) Woken. + /// 2a) Sleeping and unnotified. + /// 2b) Sleeping and notified. + sleeping: usize, +} + +impl Ticker<'_> { + /// Creates a ticker. + fn new(state: &State) -> Ticker<'_> { + Ticker { state, sleeping: 0 } + } + + /// Moves the ticker into sleeping and unnotified state. + /// + /// Returns `false` if the ticker was already sleeping and unnotified. + fn sleep(&mut self, waker: &Waker) -> bool { + let mut sleepers = self.state.sleepers.lock(); + + match self.sleeping { + // Move to sleeping state. + 0 => { + self.sleeping = sleepers.insert(waker); + } + + // Already sleeping, check if notified. + id => { + if !sleepers.update(id, waker) { + return false; + } + } + } + + self.state + .notified + .store(sleepers.is_notified(), Ordering::Release); + + true + } + + /// Moves the ticker into woken state. + fn wake(&mut self) { + if self.sleeping != 0 { + let mut sleepers = self.state.sleepers.lock(); + sleepers.remove(self.sleeping); + + self.state + .notified + .store(sleepers.is_notified(), Ordering::Release); + } + self.sleeping = 0; + } + + /// Waits for the next runnable task to run. + async fn runnable(&mut self) -> Runnable { + self.runnable_with(|| self.state.queue.pop().ok()).await + } + + /// Waits for the next runnable task to run, given a function that searches for a task. + async fn runnable_with(&mut self, mut search: impl FnMut() -> Option) -> Runnable { + future::poll_fn(|cx| { + loop { + match search() { + None => { + // Move to sleeping and unnotified state. + if !self.sleep(cx.waker()) { + // If already sleeping and unnotified, return. + return Poll::Pending; + } + } + Some(r) => { + // Wake up. + self.wake(); + + // Notify another ticker now to pick up where this ticker left off, just in + // case running the task takes a long time. + self.state.notify(); + + return Poll::Ready(r); + } + } + } + }) + .await + } +} + +impl Drop for Ticker<'_> { + fn drop(&mut self) { + // If this ticker is in sleeping state, it must be removed from the sleepers list. + if self.sleeping != 0 { + let mut sleepers = self.state.sleepers.lock(); + let notified = sleepers.remove(self.sleeping); + + self.state + .notified + .store(sleepers.is_notified(), Ordering::Release); + + // If this ticker was notified, then notify another ticker. + if notified { + drop(sleepers); + self.state.notify(); + } + } + } +} + +/// A worker in a work-stealing executor. +/// +/// This is just a ticker that also has an associated local queue for improved cache locality. +struct Runner<'a> { + /// The executor state. + state: &'a State, + + /// Inner ticker. + ticker: Ticker<'a>, + + /// The local queue. + local: Arc>, + + /// Bumped every time a runnable task is found. + ticks: usize, +} + +impl Runner<'_> { + /// Creates a runner and registers it in the executor state. + fn new(state: &State) -> Runner<'_> { + let runner = Runner { + state, + ticker: Ticker::new(state), + local: Arc::new(ConcurrentQueue::bounded(512)), + ticks: 0, + }; + state.local_queues.write().push(runner.local.clone()); + runner + } + + /// Waits for the next runnable task to run. + async fn runnable(&mut self, rng: &mut fastrand::Rng) -> Runnable { + let runnable = self + .ticker + .runnable_with(|| { + // Try the local queue. + if let Ok(r) = self.local.pop() { + return Some(r); + } + + // Try stealing from the global queue. + if let Ok(r) = self.state.queue.pop() { + steal(&self.state.queue, &self.local); + return Some(r); + } + + // Try stealing from other runners. + let local_queues = self.state.local_queues.read(); + + // Pick a random starting point in the iterator list and rotate the list. + let n = local_queues.len(); + let start = rng.usize(..n); + let iter = local_queues + .iter() + .chain(local_queues.iter()) + .skip(start) + .take(n); + + // Remove this runner's local queue. + let iter = iter.filter(|local| !Arc::ptr_eq(local, &self.local)); + + // Try stealing from each local queue in the list. + for local in iter { + steal(local, &self.local); + if let Ok(r) = self.local.pop() { + return Some(r); + } + } + + None + }) + .await; + + // Bump the tick counter. + self.ticks = self.ticks.wrapping_add(1); + + if self.ticks % 64 == 0 { + // Steal tasks from the global queue to ensure fair task scheduling. + steal(&self.state.queue, &self.local); + } + + runnable + } +} + +impl Drop for Runner<'_> { + fn drop(&mut self) { + // Remove the local queue. + self.state + .local_queues + .write() + .retain(|local| !Arc::ptr_eq(local, &self.local)); + + // Re-schedule remaining tasks in the local queue. + while let Ok(r) = self.local.pop() { + r.schedule(); + } + } +} + +/// Steals some items from one queue into another. +fn steal(src: &ConcurrentQueue, dest: &ConcurrentQueue) { + // Half of `src`'s length rounded up. + let mut count = (src.len() + 1) / 2; + + if count > 0 { + // Don't steal more than fits into the queue. + if let Some(cap) = dest.capacity() { + count = count.min(cap - dest.len()); + } + + // Steal tasks. + for _ in 0..count { + if let Ok(t) = src.pop() { + assert!(dest.push(t).is_ok()); + } else { + break; + } + } + } +} + +/// Debug implementation for `Executor` and `LocalExecutor`. +fn debug_executor(executor: &Executor<'_>, name: &str, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // Get a reference to the state. + let ptr = executor.state.load(Ordering::Acquire); + if ptr.is_null() { + // The executor has not been initialized. + struct Uninitialized; + + impl fmt::Debug for Uninitialized { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("") + } + } + + return f.debug_tuple(name).field(&Uninitialized).finish(); + } + + // SAFETY: If the state pointer is not null, it must have been + // allocated properly by Arc::new and converted via Arc::into_raw + // in state_ptr. + let state = unsafe { &*ptr }; + + debug_state(state, name, f) +} + +/// Debug implementation for `Executor` and `LocalExecutor`. +fn debug_state(state: &State, name: &str, f: &mut fmt::Formatter<'_>) -> fmt::Result { + /// Debug wrapper for the number of active tasks. + struct ActiveTasks<'a>(&'a Mutex>); + + impl fmt::Debug for ActiveTasks<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.0.try_lock() { + Some(lock) => fmt::Debug::fmt(&lock.len(), f), + None => f.write_str(""), + } + } + } + + /// Debug wrapper for the local runners. + struct LocalRunners<'a>(&'a RwLock>>>); + + impl fmt::Debug for LocalRunners<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.0.try_read() { + Some(lock) => f + .debug_list() + .entries(lock.iter().map(|queue| queue.len())) + .finish(), + None => f.write_str(""), + } + } + } + + /// Debug wrapper for the sleepers. + struct SleepCount<'a>(&'a Mutex); + + impl fmt::Debug for SleepCount<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.0.try_lock() { + Some(lock) => fmt::Debug::fmt(&lock.count, f), + None => f.write_str(""), + } + } + } + + f.debug_struct(name) + .field("active", &ActiveTasks(&state.active)) + .field("global_tasks", &state.queue.len()) + .field("local_runners", &LocalRunners(&state.local_queues)) + .field("sleepers", &SleepCount(&state.sleepers)) + .finish() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ensure_send_and_sync() { + use futures_lite::future::pending; + + fn is_send(_: T) {} + fn is_sync(_: T) {} + fn is_static(_: T) {} + + is_send::>(Executor::new()); + is_sync::>(Executor::new()); + + let ex = Executor::new(); + is_send(ex.run(pending::<()>())); + is_sync(ex.run(pending::<()>())); + is_send(ex.tick()); + is_sync(ex.tick()); + is_send(ex.schedule()); + is_sync(ex.schedule()); + is_static(ex.schedule()); + } +} diff --git a/crates/bevy_tasks/src/global_task_pool.rs b/crates/bevy_tasks/src/global_task_pool.rs new file mode 100644 index 0000000000000..315fe1fe6706c --- /dev/null +++ b/crates/bevy_tasks/src/global_task_pool.rs @@ -0,0 +1,249 @@ +use alloc::{string::String, sync::Arc, vec::Vec}; +use core::{cell::RefCell, future::Future, marker::PhantomData, mem}; + +use spin::RwLock; + +use crate::{executor::Executor, Task}; + +static GLOBAL_EXECUTOR: Executor<'static> = Executor::new(); + +/// Used to create a [`TaskPool`]. +#[derive(Debug, Default, Clone)] +pub struct TaskPoolBuilder {} + +/// This is a dummy struct for wasm support to provide the same api as with the multithreaded +/// task pool. In the case of the multithreaded task pool this struct is used to spawn +/// tasks on a specific thread. But the wasm task pool just calls +/// `wasm_bindgen_futures::spawn_local` for spawning which just runs tasks on the main thread +/// and so the [`ThreadExecutor`] does nothing. +#[derive(Default)] +pub struct ThreadExecutor<'a>(PhantomData<&'a ()>); +impl<'a> ThreadExecutor<'a> { + /// Creates a new `ThreadExecutor` + pub fn new() -> Self { + Self::default() + } +} + +impl TaskPoolBuilder { + /// Creates a new `TaskPoolBuilder` instance + pub fn new() -> Self { + Self::default() + } + + /// No op on the single threaded task pool + pub fn num_threads(self, _num_threads: usize) -> Self { + self + } + + /// No op on the single threaded task pool + pub fn stack_size(self, _stack_size: usize) -> Self { + self + } + + /// No op on the single threaded task pool + pub fn thread_name(self, _thread_name: String) -> Self { + self + } + + /// Creates a new [`TaskPool`] + pub fn build(self) -> TaskPool { + TaskPool::new_internal() + } +} + +/// A thread pool for executing tasks. Tasks are futures that are being automatically driven by +/// the pool on threads owned by the pool. In this case - main thread only. +#[derive(Debug, Default, Clone)] +pub struct TaskPool {} + +impl TaskPool { + /// Just create a new `ThreadExecutor` for wasm + pub fn get_thread_executor() -> Arc> { + Arc::new(ThreadExecutor::new()) + } + + /// Create a `TaskPool` with the default configuration. + pub fn new() -> Self { + TaskPoolBuilder::new().build() + } + + fn new_internal() -> Self { + Self {} + } + + /// Return the number of threads owned by the task pool + pub fn thread_num(&self) -> usize { + 1 + } + + /// Allows spawning non-`'static` futures on the thread pool. The function takes a callback, + /// passing a scope object into it. The scope object provided to the callback can be used + /// to spawn tasks. This function will await the completion of all tasks before returning. + /// + /// This is similar to `rayon::scope` and `crossbeam::scope` + pub fn scope<'env, F, T>(&self, f: F) -> Vec + where + F: for<'scope> FnOnce(&'env mut Scope<'scope, 'env, T>), + T: Send + 'static, + { + self.scope_with_executor(false, None, f) + } + + /// Allows spawning non-`'static` futures on the thread pool. The function takes a callback, + /// passing a scope object into it. The scope object provided to the callback can be used + /// to spawn tasks. This function will await the completion of all tasks before returning. + /// + /// This is similar to `rayon::scope` and `crossbeam::scope` + #[expect(unsafe_code, reason = "Required to transmute lifetimes.")] + pub fn scope_with_executor<'env, F, T>( + &self, + _tick_task_pool_executor: bool, + _thread_executor: Option<&ThreadExecutor>, + f: F, + ) -> Vec + where + F: for<'scope> FnOnce(&'env mut Scope<'scope, 'env, T>), + T: Send + 'static, + { + // SAFETY: This safety comment applies to all references transmuted to 'env. + // Any futures spawned with these references need to return before this function completes. + // This is guaranteed because we drive all the futures spawned onto the Scope + // to completion in this function. However, rust has no way of knowing this so we + // transmute the lifetimes to 'env here to appease the compiler as it is unable to validate safety. + // Any usages of the references passed into `Scope` must be accessed through + // the transmuted reference for the rest of this function. + + let executor = &Executor::new(); + // SAFETY: As above, all futures must complete in this function so we can change the lifetime + let executor: &'env Executor<'env> = unsafe { mem::transmute(executor) }; + + let results: RefCell>>>> = RefCell::new(Vec::new()); + // SAFETY: As above, all futures must complete in this function so we can change the lifetime + let results: &'env RefCell>>>> = + unsafe { mem::transmute(&results) }; + + let mut scope = Scope { + executor, + results, + scope: PhantomData, + env: PhantomData, + }; + + // SAFETY: As above, all futures must complete in this function so we can change the lifetime + let scope_ref: &'env mut Scope<'_, 'env, T> = unsafe { mem::transmute(&mut scope) }; + + f(scope_ref); + + // Loop until all tasks are done + while executor.try_tick() {} + + let results = scope.results.borrow(); + results + .iter() + .map(|result| result.write().take().unwrap()) + .collect() + } + + /// Spawns a static future onto the thread pool. The returned Task is a future, which can be polled + /// to retrieve the output of the original future. Dropping the task will attempt to cancel it. + /// It can also be "detached", allowing it to continue running without having to be polled by the + /// end-user. + /// + /// If the provided future is non-`Send`, [`TaskPool::spawn_local`] should be used instead. + pub fn spawn(&self, future: impl Future + Send + 'static) -> Task + where + T: Send + 'static, + { + #[cfg(target_arch = "wasm32")] + return Task::wrap_future(future); + + #[cfg(not(target_arch = "wasm32"))] + { + let task = GLOBAL_EXECUTOR.spawn(future); + // Loop until all tasks are done + while GLOBAL_EXECUTOR.try_tick() {} + + Task::new(task) + } + } + + /// Spawns a static future on the JS event loop. This is exactly the same as [`TaskPool::spawn`]. + pub fn spawn_local(&self, future: impl Future + Send + 'static) -> Task + where + T: Send + 'static, + { + self.spawn(future) + } + + /// Runs a function with the local executor. Typically used to tick + /// the local executor on the main thread as it needs to share time with + /// other things. + /// + /// ``` + /// use bevy_tasks::TaskPool; + /// + /// TaskPool::new().with_local_executor(|local_executor| { + /// local_executor.try_tick(); + /// }); + /// ``` + pub fn with_local_executor(&self, f: F) -> R + where + F: FnOnce(&Executor) -> R, + { + (f)(&GLOBAL_EXECUTOR) + } +} + +/// A `TaskPool` scope for running one or more non-`'static` futures. +/// +/// For more information, see [`TaskPool::scope`]. +#[derive(Debug)] +pub struct Scope<'scope, 'env: 'scope, T> { + executor: &'scope Executor<'scope>, + // Vector to gather results of all futures spawned during scope run + results: &'env RefCell>>>>, + + // make `Scope` invariant over 'scope and 'env + scope: PhantomData<&'scope mut &'scope ()>, + env: PhantomData<&'env mut &'env ()>, +} + +impl<'scope, 'env, T: Send + Sync + 'env> Scope<'scope, 'env, T> { + /// Spawns a scoped future onto the executor. The scope *must* outlive + /// the provided future. The results of the future will be returned as a part of + /// [`TaskPool::scope`]'s return value. + /// + /// On the single threaded task pool, it just calls [`Scope::spawn_on_scope`]. + /// + /// For more information, see [`TaskPool::scope`]. + pub fn spawn + Send + 'scope>(&self, f: Fut) { + self.spawn_on_scope(f); + } + + /// Spawns a scoped future onto the executor. The scope *must* outlive + /// the provided future. The results of the future will be returned as a part of + /// [`TaskPool::scope`]'s return value. + /// + /// On the single threaded task pool, it just calls [`Scope::spawn_on_scope`]. + /// + /// For more information, see [`TaskPool::scope`]. + pub fn spawn_on_external + Send + 'scope>(&self, f: Fut) { + self.spawn_on_scope(f); + } + + /// Spawns a scoped future that runs on the thread the scope called from. The + /// scope *must* outlive the provided future. The results of the future will be + /// returned as a part of [`TaskPool::scope`]'s return value. + /// + /// For more information, see [`TaskPool::scope`]. + pub fn spawn_on_scope + Send + 'scope>(&self, f: Fut) { + let result = Arc::new(RwLock::new(None)); + self.results.borrow_mut().push(result.clone()); + let f = async move { + let temp_result = f.await; + result.write().replace(temp_result); + }; + self.executor.spawn(f).detach(); + } +} diff --git a/crates/bevy_tasks/src/iter/adapters.rs b/crates/bevy_tasks/src/iter/adapters.rs index 2f8f8b28e1241..617f5bdf868ca 100644 --- a/crates/bevy_tasks/src/iter/adapters.rs +++ b/crates/bevy_tasks/src/iter/adapters.rs @@ -30,13 +30,13 @@ pub struct Map { pub(crate) f: F, } -impl ParallelIterator> for Map +impl ParallelIterator> for Map where B: Iterator + Send, U: ParallelIterator, F: FnMut(B::Item) -> T + Send + Clone, { - fn next_batch(&mut self) -> Option> { + fn next_batch(&mut self) -> Option> { self.iter.next_batch().map(|b| b.map(self.f.clone())) } } @@ -47,13 +47,13 @@ pub struct Filter { pub(crate) predicate: F, } -impl ParallelIterator> for Filter +impl ParallelIterator> for Filter where B: Iterator + Send, P: ParallelIterator, F: FnMut(&B::Item) -> bool + Send + Clone, { - fn next_batch(&mut self) -> Option> { + fn next_batch(&mut self) -> Option> { self.iter .next_batch() .map(|b| b.filter(self.predicate.clone())) @@ -66,13 +66,13 @@ pub struct FilterMap { pub(crate) f: F, } -impl ParallelIterator> for FilterMap +impl ParallelIterator> for FilterMap where B: Iterator + Send, P: ParallelIterator, F: FnMut(B::Item) -> Option + Send + Clone, { - fn next_batch(&mut self) -> Option> { + fn next_batch(&mut self) -> Option> { self.iter.next_batch().map(|b| b.filter_map(self.f.clone())) } } @@ -83,7 +83,7 @@ pub struct FlatMap { pub(crate) f: F, } -impl ParallelIterator> for FlatMap +impl ParallelIterator> for FlatMap where B: Iterator + Send, P: ParallelIterator, @@ -93,7 +93,7 @@ where { // This extends each batch using the flat map. The other option is // to turn each IntoIter into its own batch. - fn next_batch(&mut self) -> Option> { + fn next_batch(&mut self) -> Option> { self.iter.next_batch().map(|b| b.flat_map(self.f.clone())) } } @@ -103,7 +103,7 @@ pub struct Flatten

{ pub(crate) iter: P, } -impl ParallelIterator> for Flatten

+impl ParallelIterator> for Flatten

where B: Iterator + Send, P: ParallelIterator, @@ -112,7 +112,7 @@ where { // This extends each batch using the flatten. The other option is to // turn each IntoIter into its own batch. - fn next_batch(&mut self) -> Option> { + fn next_batch(&mut self) -> Option> { self.iter.next_batch().map(Iterator::flatten) } } @@ -144,13 +144,13 @@ pub struct Inspect { pub(crate) f: F, } -impl ParallelIterator> for Inspect +impl ParallelIterator> for Inspect where B: Iterator + Send, P: ParallelIterator, F: FnMut(&B::Item) + Send + Clone, { - fn next_batch(&mut self) -> Option> { + fn next_batch(&mut self) -> Option> { self.iter.next_batch().map(|b| b.inspect(self.f.clone())) } } @@ -160,13 +160,13 @@ pub struct Copied

{ pub(crate) iter: P, } -impl<'a, B, P, T> ParallelIterator> for Copied

+impl<'a, B, P, T> ParallelIterator> for Copied

where B: Iterator + Send, P: ParallelIterator, T: 'a + Copy, { - fn next_batch(&mut self) -> Option> { + fn next_batch(&mut self) -> Option> { self.iter.next_batch().map(Iterator::copied) } } @@ -176,13 +176,13 @@ pub struct Cloned

{ pub(crate) iter: P, } -impl<'a, B, P, T> ParallelIterator> for Cloned

+impl<'a, B, P, T> ParallelIterator> for Cloned

where B: Iterator + Send, P: ParallelIterator, T: 'a + Copy, { - fn next_batch(&mut self) -> Option> { + fn next_batch(&mut self) -> Option> { self.iter.next_batch().map(Iterator::cloned) } } diff --git a/crates/bevy_tasks/src/iter/mod.rs b/crates/bevy_tasks/src/iter/mod.rs index 6887fa05440a1..39ab1b72a2677 100644 --- a/crates/bevy_tasks/src/iter/mod.rs +++ b/crates/bevy_tasks/src/iter/mod.rs @@ -1,3 +1,5 @@ +use alloc::vec::Vec; + use crate::TaskPool; mod adapters; @@ -193,7 +195,7 @@ where fn collect(mut self, pool: &TaskPool) -> C where C: FromIterator, - BatchIter::Item: Send + 'static, + BatchIter::Item: crate::TaskBounds, { pool.scope(|s| { while let Some(batch) = self.next_batch() { @@ -213,7 +215,7 @@ where where C: Default + Extend + Send, F: FnMut(&BatchIter::Item) -> bool + Send + Sync + Clone, - BatchIter::Item: Send + 'static, + BatchIter::Item: crate::TaskBounds, { let (mut a, mut b) = <(C, C)>::default(); pool.scope(|s| { @@ -267,7 +269,7 @@ where } }) .into_iter() - .all(std::convert::identity) + .all(core::convert::identity) } /// Tests if any element of the parallel iterator matches a predicate. @@ -286,7 +288,7 @@ where } }) .into_iter() - .any(std::convert::identity) + .any(core::convert::identity) } /// Searches for an element in a parallel iterator, returning its index. @@ -330,7 +332,7 @@ where /// See [`Iterator::max()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.max) fn max(mut self, pool: &TaskPool) -> Option where - BatchIter::Item: Ord + Send + 'static, + BatchIter::Item: Ord + crate::TaskBounds, { pool.scope(|s| { while let Some(batch) = self.next_batch() { @@ -347,7 +349,7 @@ where /// See [`Iterator::min()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.min) fn min(mut self, pool: &TaskPool) -> Option where - BatchIter::Item: Ord + Send + 'static, + BatchIter::Item: Ord + crate::TaskBounds, { pool.scope(|s| { while let Some(batch) = self.next_batch() { @@ -366,7 +368,7 @@ where where R: Ord, F: FnMut(&BatchIter::Item) -> R + Send + Sync + Clone, - BatchIter::Item: Send + 'static, + BatchIter::Item: crate::TaskBounds, { pool.scope(|s| { while let Some(batch) = self.next_batch() { @@ -385,8 +387,8 @@ where /// See [`Iterator::max_by()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.max_by) fn max_by(mut self, pool: &TaskPool, f: F) -> Option where - F: FnMut(&BatchIter::Item, &BatchIter::Item) -> std::cmp::Ordering + Send + Sync + Clone, - BatchIter::Item: Send + 'static, + F: FnMut(&BatchIter::Item, &BatchIter::Item) -> core::cmp::Ordering + Send + Sync + Clone, + BatchIter::Item: crate::TaskBounds, { pool.scope(|s| { while let Some(batch) = self.next_batch() { @@ -406,7 +408,7 @@ where where R: Ord, F: FnMut(&BatchIter::Item) -> R + Send + Sync + Clone, - BatchIter::Item: Send + 'static, + BatchIter::Item: crate::TaskBounds, { pool.scope(|s| { while let Some(batch) = self.next_batch() { @@ -425,8 +427,8 @@ where /// See [`Iterator::min_by()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.min_by) fn min_by(mut self, pool: &TaskPool, f: F) -> Option where - F: FnMut(&BatchIter::Item, &BatchIter::Item) -> std::cmp::Ordering + Send + Sync + Clone, - BatchIter::Item: Send + 'static, + F: FnMut(&BatchIter::Item, &BatchIter::Item) -> core::cmp::Ordering + Send + Sync + Clone, + BatchIter::Item: crate::TaskBounds, { pool.scope(|s| { while let Some(batch) = self.next_batch() { @@ -479,8 +481,8 @@ where /// See [`Iterator::sum()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.sum) fn sum(mut self, pool: &TaskPool) -> R where - S: std::iter::Sum + Send + 'static, - R: std::iter::Sum, + S: core::iter::Sum + crate::TaskBounds, + R: core::iter::Sum, { pool.scope(|s| { while let Some(batch) = self.next_batch() { @@ -496,8 +498,8 @@ where /// See [`Iterator::product()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.product) fn product(mut self, pool: &TaskPool) -> R where - S: std::iter::Product + Send + 'static, - R: std::iter::Product, + S: core::iter::Product + crate::TaskBounds, + R: core::iter::Product, { pool.scope(|s| { while let Some(batch) = self.next_batch() { diff --git a/crates/bevy_tasks/src/lib.rs b/crates/bevy_tasks/src/lib.rs index d8736d55cab07..f5817c8b77da2 100644 --- a/crates/bevy_tasks/src/lib.rs +++ b/crates/bevy_tasks/src/lib.rs @@ -4,8 +4,20 @@ html_logo_url = "https://bevyengine.org/assets/icon.png", html_favicon_url = "https://bevyengine.org/assets/icon.png" )] +#![cfg_attr(not(feature = "std"), no_std)] + +extern crate alloc; + +mod executor; + +#[cfg(not(feature = "std"))] +mod global_task_pool; + +#[cfg(not(feature = "std"))] +pub use global_task_pool::{Scope, TaskPool, TaskPoolBuilder, ThreadExecutor}; mod slice; + pub use slice::{ParallelSlice, ParallelSliceMut}; #[cfg_attr(target_arch = "wasm32", path = "wasm_task.rs")] @@ -13,33 +25,63 @@ mod task; pub use task::Task; -#[cfg(all(not(target_arch = "wasm32"), feature = "multi_threaded"))] +#[cfg(all( + feature = "std", + not(target_arch = "wasm32"), + feature = "multi_threaded" +))] mod task_pool; -#[cfg(all(not(target_arch = "wasm32"), feature = "multi_threaded"))] + +#[cfg(all( + feature = "std", + not(target_arch = "wasm32"), + feature = "multi_threaded" +))] pub use task_pool::{Scope, TaskPool, TaskPoolBuilder}; -#[cfg(any(target_arch = "wasm32", not(feature = "multi_threaded")))] +#[cfg(all( + feature = "std", + any(target_arch = "wasm32", not(feature = "multi_threaded")) +))] mod single_threaded_task_pool; -#[cfg(any(target_arch = "wasm32", not(feature = "multi_threaded")))] + +#[cfg(all( + feature = "std", + any(target_arch = "wasm32", not(feature = "multi_threaded")) +))] pub use single_threaded_task_pool::{Scope, TaskPool, TaskPoolBuilder, ThreadExecutor}; mod usages; + #[cfg(not(target_arch = "wasm32"))] pub use usages::tick_global_task_pools_on_main_thread; + pub use usages::{AsyncComputeTaskPool, ComputeTaskPool, IoTaskPool}; -#[cfg(all(not(target_arch = "wasm32"), feature = "multi_threaded"))] +#[cfg(all( + feature = "std", + not(target_arch = "wasm32"), + feature = "multi_threaded" +))] mod thread_executor; -#[cfg(all(not(target_arch = "wasm32"), feature = "multi_threaded"))] + +#[cfg(all( + feature = "std", + not(target_arch = "wasm32"), + feature = "multi_threaded" +))] pub use thread_executor::{ThreadExecutor, ThreadExecutorTicker}; #[cfg(feature = "async-io")] pub use async_io::block_on; -#[cfg(not(feature = "async-io"))] + +#[cfg(all(feature = "std", not(feature = "async-io")))] pub use futures_lite::future::block_on; + pub use futures_lite::future::poll_once; mod iter; + pub use iter::ParallelIterator; pub use futures_lite; @@ -48,25 +90,41 @@ pub use futures_lite; /// /// This includes the most common types in this crate, re-exported for your convenience. pub mod prelude { + #[cfg(feature = "std")] + #[doc(hidden)] + pub use crate::block_on; + #[doc(hidden)] pub use crate::{ - block_on, iter::ParallelIterator, slice::{ParallelSlice, ParallelSliceMut}, usages::{AsyncComputeTaskPool, ComputeTaskPool, IoTaskPool}, }; } -use std::num::NonZero; - /// Gets the logical CPU core count available to the current process. /// /// This is identical to [`std::thread::available_parallelism`], except /// it will return a default value of 1 if it internally errors out. /// /// This will always return at least 1. +#[cfg(feature = "std")] pub fn available_parallelism() -> usize { std::thread::available_parallelism() - .map(NonZero::::get) + .map(core::num::NonZero::::get) .unwrap_or(1) } + +/// Marker trait indicating [`Task`] requirements. +#[cfg(feature = "std")] +pub trait TaskBounds: Send + 'static {} + +#[cfg(feature = "std")] +impl TaskBounds for T {} + +/// Marker trait indicating [`Task`] requirements. +#[cfg(not(feature = "std"))] +pub trait TaskBounds: Send + Sync + 'static {} + +#[cfg(not(feature = "std"))] +impl TaskBounds for T {} diff --git a/crates/bevy_tasks/src/single_threaded_task_pool.rs b/crates/bevy_tasks/src/single_threaded_task_pool.rs index 7022405cc2b55..bd5346fea73ab 100644 --- a/crates/bevy_tasks/src/single_threaded_task_pool.rs +++ b/crates/bevy_tasks/src/single_threaded_task_pool.rs @@ -1,10 +1,10 @@ -use std::sync::Arc; -use std::{cell::RefCell, future::Future, marker::PhantomData, mem, rc::Rc}; +use alloc::{rc::Rc, sync::Arc}; +use core::{cell::RefCell, future::Future, marker::PhantomData, mem}; -use crate::Task; +use crate::{executor::LocalExecutor, Task}; thread_local! { - static LOCAL_EXECUTOR: async_executor::LocalExecutor<'static> = const { async_executor::LocalExecutor::new() }; + static LOCAL_EXECUTOR: LocalExecutor<'static> = const { LocalExecutor::new() }; } /// Used to create a [`TaskPool`]. @@ -114,10 +114,9 @@ impl TaskPool { // Any usages of the references passed into `Scope` must be accessed through // the transmuted reference for the rest of this function. - let executor = &async_executor::LocalExecutor::new(); + let executor = &LocalExecutor::new(); // SAFETY: As above, all futures must complete in this function so we can change the lifetime - let executor: &'env async_executor::LocalExecutor<'env> = - unsafe { mem::transmute(executor) }; + let executor: &'env LocalExecutor<'env> = unsafe { mem::transmute(executor) }; let results: RefCell>>>> = RefCell::new(Vec::new()); // SAFETY: As above, all futures must complete in this function so we can change the lifetime @@ -192,7 +191,7 @@ impl TaskPool { /// ``` pub fn with_local_executor(&self, f: F) -> R where - F: FnOnce(&async_executor::LocalExecutor) -> R, + F: FnOnce(&LocalExecutor) -> R, { LOCAL_EXECUTOR.with(f) } @@ -203,7 +202,7 @@ impl TaskPool { /// For more information, see [`TaskPool::scope`]. #[derive(Debug)] pub struct Scope<'scope, 'env: 'scope, T> { - executor: &'scope async_executor::LocalExecutor<'scope>, + executor: &'scope LocalExecutor<'scope>, // Vector to gather results of all futures spawned during scope run results: &'env RefCell>>>>, diff --git a/crates/bevy_tasks/src/slice.rs b/crates/bevy_tasks/src/slice.rs index 93568fd15dad0..712126ffe254f 100644 --- a/crates/bevy_tasks/src/slice.rs +++ b/crates/bevy_tasks/src/slice.rs @@ -1,3 +1,5 @@ +use alloc::vec::Vec; + use super::TaskPool; /// Provides functions for mapping read-only slices across a provided [`TaskPool`]. @@ -36,7 +38,7 @@ pub trait ParallelSlice: AsRef<[T]> { fn par_chunk_map(&self, task_pool: &TaskPool, chunk_size: usize, f: F) -> Vec where F: Fn(usize, &[T]) -> R + Send + Sync, - R: Send + 'static, + R: crate::TaskBounds, { let slice = self.as_ref(); let f = &f; @@ -83,12 +85,12 @@ pub trait ParallelSlice: AsRef<[T]> { fn par_splat_map(&self, task_pool: &TaskPool, max_tasks: Option, f: F) -> Vec where F: Fn(usize, &[T]) -> R + Send + Sync, - R: Send + 'static, + R: crate::TaskBounds, { let slice = self.as_ref(); - let chunk_size = std::cmp::max( + let chunk_size = core::cmp::max( 1, - std::cmp::max( + core::cmp::max( slice.len() / task_pool.thread_num(), slice.len() / max_tasks.unwrap_or(usize::MAX), ), @@ -139,7 +141,7 @@ pub trait ParallelSliceMut: AsMut<[T]> { fn par_chunk_map_mut(&mut self, task_pool: &TaskPool, chunk_size: usize, f: F) -> Vec where F: Fn(usize, &mut [T]) -> R + Send + Sync, - R: Send + 'static, + R: crate::TaskBounds, { let slice = self.as_mut(); let f = &f; @@ -194,12 +196,12 @@ pub trait ParallelSliceMut: AsMut<[T]> { ) -> Vec where F: Fn(usize, &mut [T]) -> R + Send + Sync, - R: Send + 'static, + R: crate::TaskBounds, { let mut slice = self.as_mut(); - let chunk_size = std::cmp::max( + let chunk_size = core::cmp::max( 1, - std::cmp::max( + core::cmp::max( slice.len() / task_pool.thread_num(), slice.len() / max_tasks.unwrap_or(usize::MAX), ), diff --git a/crates/bevy_tasks/src/task.rs b/crates/bevy_tasks/src/task.rs index b16b5a88d8417..e1c252bea1388 100644 --- a/crates/bevy_tasks/src/task.rs +++ b/crates/bevy_tasks/src/task.rs @@ -1,10 +1,10 @@ -use std::{ +use core::{ future::Future, pin::Pin, task::{Context, Poll}, }; -/// Wraps `async_executor::Task`, a spawned future. +/// Wraps `async_task::Task`, a spawned future. /// /// Tasks are also futures themselves and yield the output of the spawned future. /// @@ -14,16 +14,16 @@ use std::{ /// Tasks that panic get immediately canceled. Awaiting a canceled task also causes a panic. #[derive(Debug)] #[must_use = "Tasks are canceled when dropped, use `.detach()` to run them in the background."] -pub struct Task(async_executor::Task); +pub struct Task(async_task::Task); impl Task { - /// Creates a new task from a given `async_executor::Task` - pub fn new(task: async_executor::Task) -> Self { + /// Creates a new task from a given `async_task::Task` + pub fn new(task: async_task::Task) -> Self { Self(task) } /// Detaches the task to let it keep running in the background. See - /// `async_executor::Task::detach` + /// `async_task::Task::detach` pub fn detach(self) { self.0.detach(); } @@ -36,7 +36,7 @@ impl Task { /// While it's possible to simply drop the [`Task`] to cancel it, this is a cleaner way of /// canceling because it also waits for the task to stop running. /// - /// See `async_executor::Task::cancel` + /// See `async_task::Task::cancel` pub async fn cancel(self) -> Option { self.0.cancel().await } diff --git a/crates/bevy_tasks/src/task_pool.rs b/crates/bevy_tasks/src/task_pool.rs index cd395a35fd2ce..b882ecc03038f 100644 --- a/crates/bevy_tasks/src/task_pool.rs +++ b/crates/bevy_tasks/src/task_pool.rs @@ -1,31 +1,20 @@ -use std::{ - future::Future, - marker::PhantomData, - mem, - panic::AssertUnwindSafe, - sync::Arc, - thread::{self, JoinHandle}, -}; +use alloc::sync::Arc; +use core::{future::Future, marker::PhantomData, mem, panic::AssertUnwindSafe}; +use std::thread::{self, JoinHandle}; -use async_executor::FallibleTask; +use async_task::FallibleTask; use concurrent_queue::ConcurrentQueue; use futures_lite::FutureExt; +use crate::executor::{Executor, LocalExecutor}; + use crate::{ block_on, thread_executor::{ThreadExecutor, ThreadExecutorTicker}, Task, }; -struct CallOnDrop(Option>); - -impl Drop for CallOnDrop { - fn drop(&mut self) { - if let Some(call) = self.0.as_ref() { - call(); - } - } -} +use bevy_utils::OnDrop; /// Used to create a [`TaskPool`] #[derive(Default)] @@ -107,7 +96,7 @@ impl TaskPoolBuilder { #[derive(Debug)] pub struct TaskPool { /// The executor for the pool. - executor: Arc>, + executor: Arc>, // The inner state of the pool. threads: Vec>, @@ -116,7 +105,7 @@ pub struct TaskPool { impl TaskPool { thread_local! { - static LOCAL_EXECUTOR: async_executor::LocalExecutor<'static> = const { async_executor::LocalExecutor::new() }; + static LOCAL_EXECUTOR: LocalExecutor<'static> = const { LocalExecutor::new() }; static THREAD_EXECUTOR: Arc> = Arc::new(ThreadExecutor::new()); } @@ -133,7 +122,7 @@ impl TaskPool { fn new_internal(builder: TaskPoolBuilder) -> Self { let (shutdown_tx, shutdown_rx) = async_channel::unbounded::<()>(); - let executor = Arc::new(async_executor::Executor::new()); + let executor = Arc::new(Executor::new()); let num_threads = builder .num_threads @@ -165,7 +154,11 @@ impl TaskPool { on_thread_spawn(); drop(on_thread_spawn); } - let _destructor = CallOnDrop(on_thread_destroy); + let _destructor = OnDrop::new(move || { + if let Some(f) = on_thread_destroy { + (f)(); + } + }); loop { let res = std::panic::catch_unwind(|| { let tick_forever = async move { @@ -349,20 +342,20 @@ impl TaskPool { // transmute the lifetimes to 'env here to appease the compiler as it is unable to validate safety. // Any usages of the references passed into `Scope` must be accessed through // the transmuted reference for the rest of this function. - let executor: &async_executor::Executor = &self.executor; + let executor: &Executor = &self.executor; // SAFETY: As above, all futures must complete in this function so we can change the lifetime - let executor: &'env async_executor::Executor = unsafe { mem::transmute(executor) }; + let executor: &'env Executor = unsafe { mem::transmute(executor) }; // SAFETY: As above, all futures must complete in this function so we can change the lifetime let external_executor: &'env ThreadExecutor<'env> = unsafe { mem::transmute(external_executor) }; // SAFETY: As above, all futures must complete in this function so we can change the lifetime let scope_executor: &'env ThreadExecutor<'env> = unsafe { mem::transmute(scope_executor) }; - let spawned: ConcurrentQueue>>> = + let spawned: ConcurrentQueue>>> = ConcurrentQueue::unbounded(); // shadow the variable so that the owned value cannot be used for the rest of the function // SAFETY: As above, all futures must complete in this function so we can change the lifetime let spawned: &'env ConcurrentQueue< - FallibleTask>>, + FallibleTask>>, > = unsafe { mem::transmute(&spawned) }; let scope = Scope { @@ -437,7 +430,7 @@ impl TaskPool { #[inline] async fn execute_global_external_scope<'scope, 'ticker, T>( - executor: &'scope async_executor::Executor<'scope>, + executor: &'scope Executor<'scope>, external_ticker: ThreadExecutorTicker<'scope, 'ticker>, scope_ticker: ThreadExecutorTicker<'scope, 'ticker>, get_results: impl Future>, @@ -483,7 +476,7 @@ impl TaskPool { #[inline] async fn execute_global_scope<'scope, 'ticker, T>( - executor: &'scope async_executor::Executor<'scope>, + executor: &'scope Executor<'scope>, scope_ticker: ThreadExecutorTicker<'scope, 'ticker>, get_results: impl Future>, ) -> Vec { @@ -567,7 +560,7 @@ impl TaskPool { /// ``` pub fn with_local_executor(&self, f: F) -> R where - F: FnOnce(&async_executor::LocalExecutor) -> R, + F: FnOnce(&LocalExecutor) -> R, { Self::LOCAL_EXECUTOR.with(f) } @@ -598,10 +591,10 @@ impl Drop for TaskPool { /// For more information, see [`TaskPool::scope`]. #[derive(Debug)] pub struct Scope<'scope, 'env: 'scope, T> { - executor: &'scope async_executor::Executor<'scope>, + executor: &'scope Executor<'scope>, external_executor: &'scope ThreadExecutor<'scope>, scope_executor: &'scope ThreadExecutor<'scope>, - spawned: &'scope ConcurrentQueue>>>, + spawned: &'scope ConcurrentQueue>>>, // make `Scope` invariant over 'scope and 'env scope: PhantomData<&'scope mut &'scope ()>, env: PhantomData<&'env mut &'env ()>, @@ -677,10 +670,8 @@ where #[allow(clippy::disallowed_types)] mod tests { use super::*; - use std::sync::{ - atomic::{AtomicBool, AtomicI32, Ordering}, - Barrier, - }; + use core::sync::atomic::{AtomicBool, AtomicI32, Ordering}; + use std::sync::Barrier; #[test] fn test_spawn() { diff --git a/crates/bevy_tasks/src/thread_executor.rs b/crates/bevy_tasks/src/thread_executor.rs index cc6b272efb4ff..c29940cbd5fa8 100644 --- a/crates/bevy_tasks/src/thread_executor.rs +++ b/crates/bevy_tasks/src/thread_executor.rs @@ -1,11 +1,11 @@ -use std::{ - marker::PhantomData, - thread::{self, ThreadId}, -}; +use core::marker::PhantomData; +use std::thread::{self, ThreadId}; -use async_executor::{Executor, Task}; +use async_task::Task; use futures_lite::Future; +use crate::executor::Executor; + /// An executor that can only be ticked on the thread it was instantiated on. But /// can spawn `Send` tasks from other threads. /// @@ -86,7 +86,7 @@ impl<'task> ThreadExecutor<'task> { /// Returns true if `self` and `other`'s executor is same pub fn is_same(&self, other: &Self) -> bool { - std::ptr::eq(self, other) + core::ptr::eq(self, other) } } @@ -115,7 +115,7 @@ impl<'task, 'ticker> ThreadExecutorTicker<'task, 'ticker> { #[cfg(test)] mod tests { use super::*; - use std::sync::Arc; + use alloc::sync::Arc; #[test] fn test_ticker() { diff --git a/crates/bevy_tasks/src/usages.rs b/crates/bevy_tasks/src/usages.rs index fda3092b8ebc8..ccfb6b6818d84 100644 --- a/crates/bevy_tasks/src/usages.rs +++ b/crates/bevy_tasks/src/usages.rs @@ -1,9 +1,10 @@ use super::TaskPool; -use std::{ops::Deref, sync::OnceLock}; +use core::ops::Deref; +use spin::Once; macro_rules! taskpool { ($(#[$attr:meta])* ($static:ident, $type:ident)) => { - static $static: OnceLock<$type> = OnceLock::new(); + static $static: Once<$type> = Once::new(); $(#[$attr])* #[derive(Debug)] @@ -12,7 +13,7 @@ macro_rules! taskpool { impl $type { #[doc = concat!(" Gets the global [`", stringify!($type), "`] instance, or initializes it with `f`.")] pub fn get_or_init(f: impl FnOnce() -> TaskPool) -> &'static Self { - $static.get_or_init(|| Self(f())) + $static.call_once(|| Self(f())) } #[doc = concat!(" Attempts to get the global [`", stringify!($type), "`] instance, \ diff --git a/crates/bevy_tasks/src/wasm_task.rs b/crates/bevy_tasks/src/wasm_task.rs index 47c082516ad2b..572b381043b27 100644 --- a/crates/bevy_tasks/src/wasm_task.rs +++ b/crates/bevy_tasks/src/wasm_task.rs @@ -1,4 +1,4 @@ -use std::{ +use core::{ any::Any, future::{Future, IntoFuture}, panic::{AssertUnwindSafe, UnwindSafe}, @@ -44,7 +44,7 @@ impl Task { Ok(Err(panic)) => { // drop this to prevent the panic payload from resuming the panic on drop. // this also leaks the box but I'm not sure how to avoid that - std::mem::forget(panic); + core::mem::forget(panic); None } } @@ -54,8 +54,8 @@ impl Task { impl Future for Task { type Output = T; fn poll( - mut self: std::pin::Pin<&mut Self>, - cx: &mut std::task::Context<'_>, + mut self: core::pin::Pin<&mut Self>, + cx: &mut core::task::Context<'_>, ) -> std::task::Poll { match Pin::new(&mut self.0).poll(cx) { Poll::Ready(Ok(Ok(value))) => Poll::Ready(value), @@ -76,7 +76,7 @@ struct CatchUnwind(#[pin] F); impl Future for CatchUnwind { type Output = Result; - fn poll(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context) -> Poll { + fn poll(self: core::pin::Pin<&mut Self>, cx: &mut core::task::Context) -> Poll { std::panic::catch_unwind(AssertUnwindSafe(|| self.project().0.poll(cx)))?.map(Ok) } } diff --git a/crates/bevy_text/src/bounds.rs b/crates/bevy_text/src/bounds.rs index 2dc5a27a49c53..76ce50bf36889 100644 --- a/crates/bevy_text/src/bounds.rs +++ b/crates/bevy_text/src/bounds.rs @@ -1,7 +1,6 @@ use bevy_ecs::{component::Component, reflect::ReflectComponent}; use bevy_math::Vec2; -use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; +use bevy_reflect::{std_traits::ReflectDefault, Reflect}; /// The maximum width and height of text. The text will wrap according to the specified size. /// Characters out of the bounds after wrapping will be truncated. Text is aligned according to the diff --git a/crates/bevy_text/src/font.rs b/crates/bevy_text/src/font.rs index d24d89eea337d..b748f4a111fdd 100644 --- a/crates/bevy_text/src/font.rs +++ b/crates/bevy_text/src/font.rs @@ -1,4 +1,4 @@ -use std::sync::Arc; +use alloc::sync::Arc; use bevy_asset::Asset; use bevy_reflect::TypePath; diff --git a/crates/bevy_text/src/font_atlas.rs b/crates/bevy_text/src/font_atlas.rs index 31c0fec9e844b..8f32dade935f1 100644 --- a/crates/bevy_text/src/font_atlas.rs +++ b/crates/bevy_text/src/font_atlas.rs @@ -116,8 +116,8 @@ impl FontAtlas { } } -impl std::fmt::Debug for FontAtlas { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for FontAtlas { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("FontAtlas") .field("glyph_to_atlas_index", &self.glyph_to_atlas_index) .field("texture_atlas", &self.texture_atlas) diff --git a/crates/bevy_text/src/lib.rs b/crates/bevy_text/src/lib.rs index 0b638cdb1d5e8..136ee7d7e7be6 100644 --- a/crates/bevy_text/src/lib.rs +++ b/crates/bevy_text/src/lib.rs @@ -31,6 +31,8 @@ #![allow(clippy::type_complexity)] +extern crate alloc; + mod bounds; mod error; mod font; diff --git a/crates/bevy_text/src/pipeline.rs b/crates/bevy_text/src/pipeline.rs index 3a6abd6a77d6a..10efe23f748da 100644 --- a/crates/bevy_text/src/pipeline.rs +++ b/crates/bevy_text/src/pipeline.rs @@ -1,4 +1,4 @@ -use std::sync::Arc; +use alloc::sync::Arc; use bevy_asset::{AssetId, Assets}; use bevy_ecs::{ @@ -109,7 +109,7 @@ impl TextPipeline { // The section index is stored in the metadata of the spans, and could be used // to look up the section the span came from and is not used internally // in cosmic-text. - let mut spans: Vec<(&str, Attrs)> = std::mem::take(&mut self.spans_buffer) + let mut spans: Vec<(&str, Attrs)> = core::mem::take(&mut self.spans_buffer) .into_iter() .map(|_| -> (&str, Attrs) { unreachable!() }) .collect(); diff --git a/crates/bevy_time/src/lib.rs b/crates/bevy_time/src/lib.rs index 794423b196314..4637b000fd174 100644 --- a/crates/bevy_time/src/lib.rs +++ b/crates/bevy_time/src/lib.rs @@ -31,10 +31,10 @@ pub mod prelude { } use bevy_app::{prelude::*, RunFixedMainLoop}; -use bevy_ecs::event::{ - event_update_system, signal_event_update_system, EventRegistry, ShouldUpdateEvents, +use bevy_ecs::{ + event::{event_update_system, signal_event_update_system, EventRegistry, ShouldUpdateEvents}, + prelude::*, }; -use bevy_ecs::prelude::*; use bevy_utils::{tracing::warn, Duration, Instant}; pub use crossbeam_channel::TrySendError; use crossbeam_channel::{Receiver, Sender}; @@ -162,7 +162,7 @@ mod tests { system::{Local, Res, ResMut, Resource}, }; use bevy_utils::Duration; - use std::error::Error; + use core::error::Error; #[derive(Event)] struct TestEvent { diff --git a/crates/bevy_time/src/time.rs b/crates/bevy_time/src/time.rs index 36feb7fe70fbc..739f7f674245b 100644 --- a/crates/bevy_time/src/time.rs +++ b/crates/bevy_time/src/time.rs @@ -1,9 +1,10 @@ -#[cfg(feature = "bevy_reflect")] -use bevy_ecs::reflect::ReflectResource; use bevy_ecs::system::Resource; -#[cfg(feature = "bevy_reflect")] -use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_utils::Duration; +#[cfg(feature = "bevy_reflect")] +use { + bevy_ecs::reflect::ReflectResource, + bevy_reflect::{std_traits::ReflectDefault, Reflect}, +}; /// A generic clock resource that tracks how much it has advanced since its /// previous update and since its creation. diff --git a/crates/bevy_transform/src/components/global_transform.rs b/crates/bevy_transform/src/components/global_transform.rs index 0b377567966d9..b3f4988e4481b 100644 --- a/crates/bevy_transform/src/components/global_transform.rs +++ b/crates/bevy_transform/src/components/global_transform.rs @@ -1,13 +1,14 @@ -use std::ops::Mul; +use core::ops::Mul; use super::Transform; -#[cfg(feature = "bevy-support")] -use bevy_ecs::{component::Component, reflect::ReflectComponent}; use bevy_math::{Affine3A, Dir3, Isometry3d, Mat4, Quat, Vec3, Vec3A}; -#[cfg(feature = "bevy-support")] -use bevy_reflect::{std_traits::ReflectDefault, Reflect}; #[cfg(all(feature = "bevy-support", feature = "serialize"))] use bevy_reflect::{ReflectDeserialize, ReflectSerialize}; +#[cfg(feature = "bevy-support")] +use { + bevy_ecs::{component::Component, reflect::ReflectComponent}, + bevy_reflect::{std_traits::ReflectDefault, Reflect}, +}; /// [`GlobalTransform`] is an affine transformation from entity-local coordinates to worldspace coordinates. /// diff --git a/crates/bevy_transform/src/components/transform.rs b/crates/bevy_transform/src/components/transform.rs index 9202b0618c940..e43b6bf4b43e7 100644 --- a/crates/bevy_transform/src/components/transform.rs +++ b/crates/bevy_transform/src/components/transform.rs @@ -1,10 +1,11 @@ use super::GlobalTransform; -#[cfg(feature = "bevy-support")] -use bevy_ecs::{component::Component, reflect::ReflectComponent}; use bevy_math::{Affine3A, Dir3, Isometry3d, Mat3, Mat4, Quat, Vec3}; +use core::ops::Mul; #[cfg(feature = "bevy-support")] -use bevy_reflect::prelude::*; -use std::ops::Mul; +use { + bevy_ecs::{component::Component, reflect::ReflectComponent}, + bevy_reflect::prelude::*, +}; /// Describe the position of an entity. If the entity has a parent, the position is relative /// to its parent position. diff --git a/crates/bevy_transform/src/helper.rs b/crates/bevy_transform/src/helper.rs index 091e39e189bac..272dd444a1b0b 100644 --- a/crates/bevy_transform/src/helper.rs +++ b/crates/bevy_transform/src/helper.rs @@ -80,7 +80,7 @@ pub enum ComputeGlobalTransformError { #[cfg(test)] mod tests { - use std::f32::consts::TAU; + use core::f32::consts::TAU; use bevy_app::App; use bevy_ecs::system::SystemState; diff --git a/crates/bevy_transform/src/lib.rs b/crates/bevy_transform/src/lib.rs index c6f55362924bd..e3705742a004b 100644 --- a/crates/bevy_transform/src/lib.rs +++ b/crates/bevy_transform/src/lib.rs @@ -39,8 +39,11 @@ pub mod prelude { #[cfg(feature = "bevy-support")] #[doc(hidden)] pub use crate::{ - bundles::TransformBundle, commands::BuildChildrenTransformExt, helper::TransformHelper, - plugins::TransformPlugin, plugins::TransformSystem, traits::TransformPoint, + bundles::TransformBundle, + commands::BuildChildrenTransformExt, + helper::TransformHelper, + plugins::{TransformPlugin, TransformSystem}, + traits::TransformPoint, }; } diff --git a/crates/bevy_transform/src/systems.rs b/crates/bevy_transform/src/systems.rs index c1a1df063171a..a06432b0f3d30 100644 --- a/crates/bevy_transform/src/systems.rs +++ b/crates/bevy_transform/src/systems.rs @@ -186,13 +186,11 @@ unsafe fn propagate_recursive( #[cfg(test)] mod test { use bevy_app::prelude::*; - use bevy_ecs::prelude::*; - use bevy_ecs::world::CommandQueue; + use bevy_ecs::{prelude::*, world::CommandQueue}; use bevy_math::{vec3, Vec3}; use bevy_tasks::{ComputeTaskPool, TaskPool}; - use crate::bundles::TransformBundle; - use crate::systems::*; + use crate::{bundles::TransformBundle, systems::*}; use bevy_hierarchy::{BuildChildren, ChildBuild}; #[test] @@ -481,7 +479,7 @@ mod test { app.world_mut() .spawn(TransformBundle::IDENTITY) .add_children(&[child]); - std::mem::swap( + core::mem::swap( &mut *app.world_mut().get_mut::(child).unwrap(), &mut *temp.get_mut::(grandchild).unwrap(), ); diff --git a/crates/bevy_ui/src/geometry.rs b/crates/bevy_ui/src/geometry.rs index bd0164bbcc747..628e8d9853142 100644 --- a/crates/bevy_ui/src/geometry.rs +++ b/crates/bevy_ui/src/geometry.rs @@ -1,8 +1,6 @@ use bevy_math::Vec2; -use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; -use std::ops::Neg; -use std::ops::{Div, DivAssign, Mul, MulAssign}; +use bevy_reflect::{std_traits::ReflectDefault, Reflect}; +use core::ops::{Div, DivAssign, Mul, MulAssign, Neg}; use thiserror::Error; #[cfg(feature = "serialize")] diff --git a/crates/bevy_ui/src/layout/debug.rs b/crates/bevy_ui/src/layout/debug.rs index 47b02396a6816..359658f59dbe9 100644 --- a/crates/bevy_ui/src/layout/debug.rs +++ b/crates/bevy_ui/src/layout/debug.rs @@ -1,4 +1,4 @@ -use std::fmt::Write; +use core::fmt::Write; use taffy::{NodeId, TraversePartialTree}; diff --git a/crates/bevy_ui/src/layout/mod.rs b/crates/bevy_ui/src/layout/mod.rs index 43e7fa428fcf1..f3dad4e22c8d0 100644 --- a/crates/bevy_ui/src/layout/mod.rs +++ b/crates/bevy_ui/src/layout/mod.rs @@ -14,14 +14,15 @@ use bevy_ecs::{ use bevy_hierarchy::{Children, Parent}; use bevy_math::{UVec2, Vec2}; use bevy_render::camera::{Camera, NormalizedRenderTarget}; -#[cfg(feature = "bevy_text")] -use bevy_text::{CosmicBuffer, TextPipeline}; use bevy_transform::components::Transform; use bevy_utils::tracing::warn; use bevy_window::{PrimaryWindow, Window, WindowScaleFactorChanged}; use thiserror::Error; use ui_surface::UiSurface; +#[cfg(feature = "bevy_text")] +use bevy_text::{CosmicBuffer, TextPipeline}; + mod convert; pub mod debug; pub(crate) mod ui_surface; @@ -447,43 +448,43 @@ fn approx_round_layout_coords(value: Vec2) -> Vec2 { mod tests { use taffy::TraversePartialTree; - use bevy_asset::AssetEvent; - use bevy_asset::Assets; + use bevy_asset::{AssetEvent, Assets}; use bevy_core_pipeline::core_2d::Camera2dBundle; - use bevy_ecs::entity::Entity; - use bevy_ecs::event::Events; - use bevy_ecs::prelude::{Commands, Component, In, Query, With}; - use bevy_ecs::query::Without; - use bevy_ecs::schedule::apply_deferred; - use bevy_ecs::schedule::IntoSystemConfigs; - use bevy_ecs::schedule::Schedule; - use bevy_ecs::system::RunSystemOnce; - use bevy_ecs::world::World; + use bevy_ecs::{ + entity::Entity, + event::Events, + prelude::{Commands, Component, In, Query, With}, + query::Without, + schedule::{apply_deferred, IntoSystemConfigs, Schedule}, + system::RunSystemOnce, + world::World, + }; use bevy_hierarchy::{ despawn_with_children_recursive, BuildChildren, ChildBuild, Children, Parent, }; use bevy_math::{vec2, Rect, UVec2, Vec2}; - use bevy_render::camera::ManualTextureViews; - use bevy_render::camera::OrthographicProjection; - use bevy_render::prelude::Camera; - use bevy_render::texture::Image; - use bevy_transform::prelude::GlobalTransform; - use bevy_transform::systems::{propagate_transforms, sync_simple_transforms}; - use bevy_utils::prelude::default; - use bevy_utils::HashMap; - use bevy_window::PrimaryWindow; - use bevy_window::Window; - use bevy_window::WindowCreated; - use bevy_window::WindowResized; - use bevy_window::WindowResolution; - use bevy_window::WindowScaleFactorChanged; - - use crate::layout::approx_round_layout_coords; - use crate::layout::ui_surface::UiSurface; - use crate::prelude::*; - use crate::ui_layout_system; - use crate::update::update_target_camera_system; - use crate::ContentSize; + use bevy_render::{ + camera::{ManualTextureViews, OrthographicProjection}, + prelude::Camera, + texture::Image, + }; + use bevy_transform::{ + prelude::GlobalTransform, + systems::{propagate_transforms, sync_simple_transforms}, + }; + use bevy_utils::{prelude::default, HashMap}; + use bevy_window::{ + PrimaryWindow, Window, WindowCreated, WindowResized, WindowResolution, + WindowScaleFactorChanged, + }; + + use crate::{ + layout::{approx_round_layout_coords, ui_surface::UiSurface}, + prelude::*, + ui_layout_system, + update::update_target_camera_system, + ContentSize, + }; #[test] fn round_layout_coords_must_round_ties_up() { diff --git a/crates/bevy_ui/src/layout/ui_surface.rs b/crates/bevy_ui/src/layout/ui_surface.rs index 0cca1d6a0b695..ce4f47e0928c9 100644 --- a/crates/bevy_ui/src/layout/ui_surface.rs +++ b/crates/bevy_ui/src/layout/ui_surface.rs @@ -1,16 +1,18 @@ -use std::fmt; +use core::fmt; use taffy::TaffyTree; -use bevy_ecs::entity::{Entity, EntityHashMap}; -use bevy_ecs::prelude::Resource; +use bevy_ecs::{ + entity::{Entity, EntityHashMap}, + prelude::Resource, +}; use bevy_hierarchy::Children; use bevy_math::UVec2; -use bevy_utils::default; -use bevy_utils::tracing::warn; +use bevy_utils::{default, tracing::warn}; -use crate::layout::convert; -use crate::{LayoutContext, LayoutError, Measure, MeasureArgs, NodeMeasure, Style}; +use crate::{ + layout::convert, LayoutContext, LayoutError, Measure, MeasureArgs, NodeMeasure, Style, +}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct RootNodePair { @@ -246,7 +248,7 @@ without UI components as a child of an entity with UI components, results may be #[cfg(feature = "bevy_text")] buffer, #[cfg(not(feature = "bevy_text"))] - font_system: std::marker::PhantomData, + font_system: core::marker::PhantomData, }, style, ); diff --git a/crates/bevy_ui/src/lib.rs b/crates/bevy_ui/src/lib.rs index e1f46c405ba46..4e88534e9305d 100644 --- a/crates/bevy_ui/src/lib.rs +++ b/crates/bevy_ui/src/lib.rs @@ -21,8 +21,7 @@ pub mod widget; pub mod picking_backend; use bevy_derive::{Deref, DerefMut}; -use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; +use bevy_reflect::{std_traits::ReflectDefault, Reflect}; #[cfg(feature = "bevy_text")] mod accessibility; mod focus; @@ -46,13 +45,14 @@ use widget::UiImageSize; /// This includes the most common types in this crate, re-exported for your convenience. pub mod prelude { #[doc(hidden)] - pub use crate::{ - geometry::*, node_bundles::*, ui_material::*, ui_node::*, widget::Button, widget::Label, - Interaction, UiMaterialPlugin, UiScale, + pub use { + crate::{ + geometry::*, node_bundles::*, ui_material::*, ui_node::*, widget::Button, + widget::Label, Interaction, UiMaterialPlugin, UiScale, + }, + // `bevy_sprite` re-exports for texture slicing + bevy_sprite::{BorderRect, ImageScaleMode, SliceScaleMode, TextureSlicer}, }; - // `bevy_sprite` re-exports for texture slicing - #[doc(hidden)] - pub use bevy_sprite::{BorderRect, ImageScaleMode, SliceScaleMode, TextureSlicer}; } use bevy_app::prelude::*; diff --git a/crates/bevy_ui/src/measurement.rs b/crates/bevy_ui/src/measurement.rs index 647bc27a4a92a..c50d81453129d 100644 --- a/crates/bevy_ui/src/measurement.rs +++ b/crates/bevy_ui/src/measurement.rs @@ -1,8 +1,7 @@ -use bevy_ecs::prelude::Component; -use bevy_ecs::reflect::ReflectComponent; +use bevy_ecs::{prelude::Component, reflect::ReflectComponent}; use bevy_math::Vec2; use bevy_reflect::{std_traits::ReflectDefault, Reflect}; -use std::fmt::Formatter; +use core::fmt::Formatter; pub use taffy::style::AvailableSpace; use crate::widget::ImageMeasure; @@ -10,8 +9,8 @@ use crate::widget::ImageMeasure; #[cfg(feature = "bevy_text")] use crate::widget::TextMeasure; -impl std::fmt::Debug for ContentSize { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for ContentSize { + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { f.debug_struct("ContentSize").finish() } } @@ -27,7 +26,7 @@ pub struct MeasureArgs<'a> { pub buffer: Option<&'a mut bevy_text::cosmic_text::Buffer>, // When `bevy_text` is disabled, use `PhantomData` in order to keep lifetime in type signature. #[cfg(not(feature = "bevy_text"))] - pub font_system: std::marker::PhantomData<&'a mut ()>, + pub font_system: core::marker::PhantomData<&'a mut ()>, } /// A `Measure` is used to compute the size of a ui node diff --git a/crates/bevy_ui/src/node_bundles.rs b/crates/bevy_ui/src/node_bundles.rs index b99681ff39a0f..e8e2430605cad 100644 --- a/crates/bevy_ui/src/node_bundles.rs +++ b/crates/bevy_ui/src/node_bundles.rs @@ -1,22 +1,23 @@ //! This module contains basic node bundles used to build UIs -#[cfg(feature = "bevy_text")] -use crate::widget::TextFlags; use crate::{ widget::{Button, UiImageSize}, BackgroundColor, BorderColor, BorderRadius, ContentSize, FocusPolicy, Interaction, Node, ScrollPosition, Style, UiImage, UiMaterial, ZIndex, }; use bevy_asset::Handle; -#[cfg(feature = "bevy_text")] -use bevy_color::Color; use bevy_ecs::bundle::Bundle; use bevy_render::view::{InheritedVisibility, ViewVisibility, Visibility}; +use bevy_transform::prelude::{GlobalTransform, Transform}; + #[cfg(feature = "bevy_text")] -use bevy_text::{ - BreakLineOn, CosmicBuffer, JustifyText, Text, TextLayoutInfo, TextSection, TextStyle, +use { + crate::widget::TextFlags, + bevy_color::Color, + bevy_text::{ + BreakLineOn, CosmicBuffer, JustifyText, Text, TextLayoutInfo, TextSection, TextStyle, + }, }; -use bevy_transform::prelude::{GlobalTransform, Transform}; /// The basic UI node. /// diff --git a/crates/bevy_ui/src/render/mod.rs b/crates/bevy_ui/src/render/mod.rs index ead0059c2b2c3..d33d3ce6e94e9 100644 --- a/crates/bevy_ui/src/render/mod.rs +++ b/crates/bevy_ui/src/render/mod.rs @@ -4,15 +4,20 @@ mod ui_material_pipeline; pub mod ui_texture_slice_pipeline; use bevy_color::{Alpha, ColorToComponents, LinearRgba}; -use bevy_core_pipeline::core_2d::graph::{Core2d, Node2d}; -use bevy_core_pipeline::core_3d::graph::{Core3d, Node3d}; -use bevy_core_pipeline::{core_2d::Camera2d, core_3d::Camera3d}; +use bevy_core_pipeline::{ + core_2d::{ + graph::{Core2d, Node2d}, + Camera2d, + }, + core_3d::{ + graph::{Core3d, Node3d}, + Camera3d, + }, +}; use bevy_hierarchy::Parent; -use bevy_render::render_phase::ViewSortedRenderPhases; -use bevy_render::texture::TRANSPARENT_IMAGE_HANDLE; use bevy_render::{ - render_phase::{PhaseItem, PhaseItemExtraIndex}, - texture::GpuImage, + render_phase::{PhaseItem, PhaseItemExtraIndex, ViewSortedRenderPhases}, + texture::{GpuImage, TRANSPARENT_IMAGE_HANDLE}, view::ViewVisibility, ExtractSchedule, Render, }; @@ -22,16 +27,18 @@ pub use render_pass::*; pub use ui_material_pipeline::*; use ui_texture_slice_pipeline::UiTextureSlicerPlugin; -use crate::graph::{NodeUi, SubGraphUi}; use crate::{ + graph::{NodeUi, SubGraphUi}, BackgroundColor, BorderColor, CalculatedClip, DefaultUiCamera, Display, Node, Outline, Style, TargetCamera, UiAntiAlias, UiImage, UiScale, Val, }; use bevy_app::prelude::*; use bevy_asset::{load_internal_asset, AssetEvent, AssetId, Assets, Handle}; -use bevy_ecs::entity::{EntityHashMap, EntityHashSet}; -use bevy_ecs::prelude::*; +use bevy_ecs::{ + entity::{EntityHashMap, EntityHashSet}, + prelude::*, +}; use bevy_math::{FloatOrd, Mat4, Rect, URect, UVec4, Vec2, Vec3, Vec3Swizzles, Vec4, Vec4Swizzles}; use bevy_render::{ camera::Camera, @@ -46,11 +53,15 @@ use bevy_render::{ }; use bevy_sprite::TextureAtlasLayout; #[cfg(feature = "bevy_text")] -use bevy_text::{PositionedGlyph, Text, TextLayoutInfo}; +use bevy_text::PositionedGlyph; +#[cfg(feature = "bevy_text")] +use bevy_text::Text; +#[cfg(feature = "bevy_text")] +use bevy_text::TextLayoutInfo; use bevy_transform::components::GlobalTransform; use bevy_utils::HashMap; use bytemuck::{Pod, Zeroable}; -use std::ops::Range; +use core::ops::Range; pub mod graph { use bevy_render::render_graph::{RenderLabel, RenderSubGraph}; @@ -1078,14 +1089,14 @@ pub fn prepare_uinodes( .map(|scaling| image.size.as_vec2() * scaling) .unwrap_or(uinode_rect.max); if extracted_uinode.flip_x { - std::mem::swap(&mut uinode_rect.max.x, &mut uinode_rect.min.x); + core::mem::swap(&mut uinode_rect.max.x, &mut uinode_rect.min.x); positions_diff[0].x *= -1.; positions_diff[1].x *= -1.; positions_diff[2].x *= -1.; positions_diff[3].x *= -1.; } if extracted_uinode.flip_y { - std::mem::swap(&mut uinode_rect.max.y, &mut uinode_rect.min.y); + core::mem::swap(&mut uinode_rect.max.y, &mut uinode_rect.min.y); positions_diff[0].y *= -1.; positions_diff[1].y *= -1.; positions_diff[2].y *= -1.; diff --git a/crates/bevy_ui/src/render/render_pass.rs b/crates/bevy_ui/src/render/render_pass.rs index 7c9931b82f183..08ee870668fcf 100644 --- a/crates/bevy_ui/src/render/render_pass.rs +++ b/crates/bevy_ui/src/render/render_pass.rs @@ -1,4 +1,4 @@ -use std::ops::Range; +use core::ops::Range; use super::{UiBatch, UiImageBindGroups, UiMeta}; use crate::DefaultCameraView; diff --git a/crates/bevy_ui/src/render/ui_material_pipeline.rs b/crates/bevy_ui/src/render/ui_material_pipeline.rs index 1a3cf489ac9be..6feaa5d3a541b 100644 --- a/crates/bevy_ui/src/render/ui_material_pipeline.rs +++ b/crates/bevy_ui/src/render/ui_material_pipeline.rs @@ -1,12 +1,14 @@ -use std::{hash::Hash, marker::PhantomData, ops::Range}; +use core::{hash::Hash, marker::PhantomData, ops::Range}; use bevy_asset::*; use bevy_ecs::{ prelude::Component, query::ROQueryItem, storage::SparseSet, - system::lifetimeless::{Read, SRes}, - system::*, + system::{ + lifetimeless::{Read, SRes}, + *, + }, }; use bevy_hierarchy::Parent; use bevy_math::{FloatOrd, Mat4, Rect, Vec2, Vec4Swizzles}; diff --git a/crates/bevy_ui/src/render/ui_texture_slice_pipeline.rs b/crates/bevy_ui/src/render/ui_texture_slice_pipeline.rs index 5839f7034ace5..c8b9cfb9b2977 100644 --- a/crates/bevy_ui/src/render/ui_texture_slice_pipeline.rs +++ b/crates/bevy_ui/src/render/ui_texture_slice_pipeline.rs @@ -1,4 +1,4 @@ -use std::{hash::Hash, ops::Range}; +use core::{hash::Hash, ops::Range}; use bevy_asset::*; use bevy_color::{Alpha, ColorToComponents, LinearRgba}; diff --git a/crates/bevy_ui/src/ui_material.rs b/crates/bevy_ui/src/ui_material.rs index dfeb3ee4c19ce..68d727cdb88f7 100644 --- a/crates/bevy_ui/src/ui_material.rs +++ b/crates/bevy_ui/src/ui_material.rs @@ -1,4 +1,4 @@ -use std::hash::Hash; +use core::hash::Hash; use bevy_asset::Asset; use bevy_render::render_resource::{AsBindGroup, RenderPipelineDescriptor, ShaderRef}; @@ -140,7 +140,7 @@ impl Hash for UiMaterialKey where M::Data: Hash, { - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { self.hdr.hash(state); self.bind_group_data.hash(state); } diff --git a/crates/bevy_ui/src/ui_node.rs b/crates/bevy_ui/src/ui_node.rs index 9df4478eb6987..560e6cbad0898 100644 --- a/crates/bevy_ui/src/ui_node.rs +++ b/crates/bevy_ui/src/ui_node.rs @@ -11,8 +11,8 @@ use bevy_render::{ use bevy_transform::prelude::GlobalTransform; use bevy_utils::warn_once; use bevy_window::{PrimaryWindow, WindowRef}; +use core::num::NonZero; use smallvec::SmallVec; -use std::num::NonZero; use thiserror::Error; /// Base component for a UI node, which also provides the computed size of the node. diff --git a/crates/bevy_ui/src/widget/button.rs b/crates/bevy_ui/src/widget/button.rs index dbe1405e9200b..19fe728b681c3 100644 --- a/crates/bevy_ui/src/widget/button.rs +++ b/crates/bevy_ui/src/widget/button.rs @@ -1,7 +1,5 @@ -use bevy_ecs::prelude::Component; -use bevy_ecs::reflect::ReflectComponent; -use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; +use bevy_ecs::{prelude::Component, reflect::ReflectComponent}; +use bevy_reflect::{std_traits::ReflectDefault, Reflect}; /// Marker struct for buttons #[derive(Component, Debug, Default, Clone, Copy, PartialEq, Eq, Reflect)] diff --git a/crates/bevy_ui/src/widget/label.rs b/crates/bevy_ui/src/widget/label.rs index 4aa7f7e36b4fc..f464fea527fc4 100644 --- a/crates/bevy_ui/src/widget/label.rs +++ b/crates/bevy_ui/src/widget/label.rs @@ -1,7 +1,5 @@ -use bevy_ecs::prelude::Component; -use bevy_ecs::reflect::ReflectComponent; -use bevy_reflect::std_traits::ReflectDefault; -use bevy_reflect::Reflect; +use bevy_ecs::{prelude::Component, reflect::ReflectComponent}; +use bevy_reflect::{std_traits::ReflectDefault, Reflect}; /// Marker struct for labels #[derive(Component, Debug, Default, Clone, Copy, Reflect)] diff --git a/crates/bevy_ui/src/widget/text.rs b/crates/bevy_ui/src/widget/text.rs index c7942a19d9d30..3391060e18cba 100644 --- a/crates/bevy_ui/src/widget/text.rs +++ b/crates/bevy_ui/src/widget/text.rs @@ -210,7 +210,7 @@ pub fn measure_text_system( ); } } - std::mem::swap(&mut *last_scale_factors, &mut *scale_factors_buffer); + core::mem::swap(&mut *last_scale_factors, &mut *scale_factors_buffer); } #[allow(clippy::too_many_arguments)] @@ -345,5 +345,5 @@ pub fn text_system( ); } } - std::mem::swap(&mut *last_scale_factors, &mut *scale_factors_buffer); + core::mem::swap(&mut *last_scale_factors, &mut *scale_factors_buffer); } diff --git a/crates/bevy_utils/Cargo.toml b/crates/bevy_utils/Cargo.toml index 7f83ec17c9a7b..c6ebeb34e8708 100644 --- a/crates/bevy_utils/Cargo.toml +++ b/crates/bevy_utils/Cargo.toml @@ -10,25 +10,25 @@ keywords = ["bevy"] [features] default = ["std"] -std = ["alloc", "tracing/std", "ahash/std"] +std = ["alloc", "tracing/std", "ahash/std", "thread_local"] alloc = [] detailed_trace = [] [dependencies] ahash = { version = "0.8.7", default-features = false, features = [ - "runtime-rng", + "compile-time-rng", ] } tracing = { version = "0.1", default-features = false } -web-time = { version = "1.1" } hashbrown = { version = "0.14.2", features = ["serde"] } bevy_utils_proc_macros = { version = "0.15.0-dev", path = "macros" } -thread_local = "1.0" +thread_local = { version = "1.0", optional = true } [dev-dependencies] static_assertions = "1.1.0" [target.'cfg(target_arch = "wasm32")'.dependencies] getrandom = { version = "0.2.0", features = ["js"] } +web-time = { version = "1.1" } [lints] workspace = true diff --git a/crates/bevy_utils/macros/src/lib.rs b/crates/bevy_utils/macros/src/lib.rs index 78803cf079e9a..b5404d078df5f 100644 --- a/crates/bevy_utils/macros/src/lib.rs +++ b/crates/bevy_utils/macros/src/lib.rs @@ -61,7 +61,7 @@ impl Parse for AllTuples { /// ## Single parameter /// /// ``` -/// # use std::marker::PhantomData; +/// # use core::marker::PhantomData; /// # use bevy_utils_proc_macros::all_tuples; /// # /// struct Foo { @@ -201,7 +201,7 @@ pub fn all_tuples(input: TokenStream) -> TokenStream { /// ## Single parameter /// /// ``` -/// # use std::marker::PhantomData; +/// # use core::marker::PhantomData; /// # use bevy_utils_proc_macros::all_tuples_with_size; /// # /// struct Foo { diff --git a/crates/bevy_utils/src/lib.rs b/crates/bevy_utils/src/lib.rs index 53442f77222fa..a06e4ab25d7c0 100644 --- a/crates/bevy_utils/src/lib.rs +++ b/crates/bevy_utils/src/lib.rs @@ -32,15 +32,18 @@ mod default; mod object_safe; pub use object_safe::assert_object_safe; mod once; +#[cfg(feature = "std")] mod parallel_queue; +mod time; pub use ahash::{AHasher, RandomState}; pub use bevy_utils_proc_macros::*; pub use default::default; pub use hashbrown; +#[cfg(feature = "std")] pub use parallel_queue::*; +pub use time::*; pub use tracing; -pub use web_time::{Duration, Instant, SystemTime, SystemTimeError, TryFromFloatSecsError}; #[cfg(feature = "alloc")] use alloc::boxed::Box; @@ -349,7 +352,7 @@ impl Hasher for NoOpHasher { /// // Make sure the message only gets printed if a panic occurs. /// // If we remove this line, then the message will be printed regardless of whether a panic occurs /// // -- similar to a `try ... finally` block. -/// std::mem::forget(_catch); +/// core::mem::forget(_catch); /// # } /// # /// # test_panic(false, |_| unreachable!()); @@ -431,7 +434,7 @@ mod tests { 0 } fn write(&mut self, _: &[u8]) { - panic!("Hashing of std::any::TypeId changed"); + panic!("Hashing of core::any::TypeId changed"); } fn write_u64(&mut self, _: u64) {} } diff --git a/crates/bevy_utils/src/once.rs b/crates/bevy_utils/src/once.rs index ce25120a5a1ac..68aeb745559da 100644 --- a/crates/bevy_utils/src/once.rs +++ b/crates/bevy_utils/src/once.rs @@ -2,7 +2,7 @@ #[macro_export] macro_rules! once { ($expression:expr) => {{ - use ::std::sync::atomic::{AtomicBool, Ordering}; + use ::core::sync::atomic::{AtomicBool, Ordering}; static SHOULD_FIRE: AtomicBool = AtomicBool::new(true); if SHOULD_FIRE.swap(false, Ordering::Relaxed) { diff --git a/crates/bevy_utils/src/time.rs b/crates/bevy_utils/src/time.rs new file mode 100644 index 0000000000000..cd6f2e17d5ad7 --- /dev/null +++ b/crates/bevy_utils/src/time.rs @@ -0,0 +1,147 @@ +#[cfg(target_arch = "wasm32")] +pub use web_time::{Duration, Instant, SystemTime, SystemTimeError, TryFromFloatSecsError}; + +#[cfg(all(not(target_arch = "wasm32"), feature = "std"))] +pub use { + core::time::{Duration, TryFromFloatSecsError}, + std::time::{Instant, SystemTime, SystemTimeError}, +}; + +#[cfg(all(not(target_arch = "wasm32"), not(feature = "std")))] +pub use no_std::{Duration, Instant, SystemTime, SystemTimeError, TryFromFloatSecsError}; + +#[cfg(all(not(target_arch = "wasm32"), not(feature = "std")))] +mod no_std { + use core::sync::atomic::{AtomicU32, AtomicU64, Ordering}; + pub use core::time::{Duration, TryFromFloatSecsError}; + + /// Custom `no_std` compatible implementation of `Instant`. + #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] + pub struct Instant(Duration); + + /// Custom `no_std` compatible implementation of `SystemTime`. + #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] + pub struct SystemTime(Instant); + + /// Custom `no_std` compatible implementation of `SystemTimeError`. + #[derive(Clone, Debug)] + pub struct SystemTimeError(Duration); + + static SECONDS: AtomicU64 = AtomicU64::new(0); + static SUBSECOND_NANOS: AtomicU32 = AtomicU32::new(0); + + impl Instant { + /// Returns an instant corresponding to "now". + #[must_use] + pub fn now() -> Instant { + let seconds = SECONDS.load(Ordering::Relaxed); + let subsecond_nanos = SUBSECOND_NANOS.load(Ordering::Relaxed); + + Self(Duration::new(seconds, subsecond_nanos)) + } + + /// Update the current time. + /// + /// # Safety + /// + /// The provided duration must _always_ be equal to or greater than the current + /// value to preserve `Instant`'s monotonicity guarantees. + pub unsafe fn update(duration: Duration) {} + + /// Returns the amount of time elapsed from another instant to this one, + /// or zero duration if that instant is later than this one. + #[must_use] + pub fn duration_since(&self, earlier: Instant) -> Duration { + self.checked_duration_since(earlier).unwrap_or_default() + } + + /// Returns the amount of time elapsed from another instant to this one, + /// or None if that instant is later than this one. + /// + /// Due to [monotonicity bugs], even under correct logical ordering of the passed `Instant`s, + /// this method can return `None`. + /// + /// [monotonicity bugs]: Instant#monotonicity + #[must_use] + pub fn checked_duration_since(&self, earlier: Instant) -> Option { + self.0.checked_sub(earlier.0) + } + + /// Returns the amount of time elapsed from another instant to this one, + /// or zero duration if that instant is later than this one. + #[must_use] + pub fn saturating_duration_since(&self, earlier: Instant) -> Duration { + self.checked_duration_since(earlier).unwrap_or_default() + } + + /// Returns the amount of time elapsed since this instant. + #[must_use] + pub fn elapsed(&self) -> Duration { + Instant::now() - *self + } + + /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as + /// `Instant` (which means it's inside the bounds of the underlying data structure), `None` + /// otherwise. + pub fn checked_add(&self, duration: Duration) -> Option { + self.0.checked_add(duration).map(Instant) + } + + /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as + /// `Instant` (which means it's inside the bounds of the underlying data structure), `None` + /// otherwise. + pub fn checked_sub(&self, duration: Duration) -> Option { + self.0.checked_sub(duration).map(Instant) + } + } + + impl core::ops::Add for Instant { + type Output = Instant; + + /// # Panics + /// + /// This function may panic if the resulting point in time cannot be represented by the + /// underlying data structure. See [`Instant::checked_add`] for a version without panic. + fn add(self, other: Duration) -> Instant { + self.checked_add(other) + .expect("overflow when adding duration to instant") + } + } + + impl core::ops::AddAssign for Instant { + fn add_assign(&mut self, other: Duration) { + *self = *self + other; + } + } + + impl core::ops::Sub for Instant { + type Output = Instant; + + fn sub(self, other: Duration) -> Instant { + self.checked_sub(other) + .expect("overflow when subtracting duration from instant") + } + } + + impl core::ops::SubAssign for Instant { + fn sub_assign(&mut self, other: Duration) { + *self = *self - other; + } + } + + impl core::ops::Sub for Instant { + type Output = Duration; + + /// Returns the amount of time elapsed from another instant to this one, + /// or zero duration if that instant is later than this one. + fn sub(self, other: Instant) -> Duration { + self.duration_since(other) + } + } + + impl core::fmt::Debug for Instant { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + self.0.fmt(f) + } + } +} diff --git a/crates/bevy_window/src/lib.rs b/crates/bevy_window/src/lib.rs index e6e06ab49fd42..eb442e7d73812 100644 --- a/crates/bevy_window/src/lib.rs +++ b/crates/bevy_window/src/lib.rs @@ -11,7 +11,10 @@ //! The [`WindowPlugin`] sets up some global window-related parameters and //! is part of the [`DefaultPlugins`](https://docs.rs/bevy/latest/bevy/struct.DefaultPlugins.html). -use std::sync::{Arc, Mutex}; +extern crate alloc; + +use alloc::sync::Arc; +use std::sync::Mutex; use bevy_a11y::Focus; diff --git a/crates/bevy_window/src/monitor.rs b/crates/bevy_window/src/monitor.rs index 756574596b9e6..10cb3b226faf9 100644 --- a/crates/bevy_window/src/monitor.rs +++ b/crates/bevy_window/src/monitor.rs @@ -1,5 +1,4 @@ -use bevy_ecs::component::Component; -use bevy_ecs::prelude::ReflectComponent; +use bevy_ecs::{component::Component, prelude::ReflectComponent}; use bevy_math::{IVec2, UVec2}; use bevy_reflect::Reflect; diff --git a/crates/bevy_window/src/raw_handle.rs b/crates/bevy_window/src/raw_handle.rs index 81b9a37096a83..6084bc728f99e 100644 --- a/crates/bevy_window/src/raw_handle.rs +++ b/crates/bevy_window/src/raw_handle.rs @@ -1,16 +1,13 @@ #![allow(unsafe_code)] +use alloc::sync::Arc; use bevy_ecs::prelude::Component; +use core::{any::Any, marker::PhantomData, ops::Deref}; use raw_window_handle::{ DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, RawDisplayHandle, RawWindowHandle, WindowHandle, }; -use std::{ - any::Any, - marker::PhantomData, - ops::Deref, - sync::{Arc, Mutex}, -}; +use std::sync::Mutex; /// A wrapper over a window. /// diff --git a/crates/bevy_window/src/window.rs b/crates/bevy_window/src/window.rs index 6e80ed7474bb1..7587a8389c7dc 100644 --- a/crates/bevy_window/src/window.rs +++ b/crates/bevy_window/src/window.rs @@ -1,4 +1,4 @@ -use std::num::NonZero; +use core::num::NonZero; use bevy_ecs::{ entity::{Entity, EntityMapper, MapEntities}, diff --git a/crates/bevy_winit/src/accessibility.rs b/crates/bevy_winit/src/accessibility.rs index 05fc96c992568..b0b88ff220edb 100644 --- a/crates/bevy_winit/src/accessibility.rs +++ b/crates/bevy_winit/src/accessibility.rs @@ -1,21 +1,21 @@ //! Helpers for mapping window entities to accessibility types -use std::{ - collections::VecDeque, - sync::{Arc, Mutex}, -}; +use alloc::{collections::VecDeque, sync::Arc}; +use std::sync::Mutex; use accesskit_winit::Adapter; -use bevy_a11y::accesskit::{ActivationHandler, DeactivationHandler, Node}; use bevy_a11y::{ - accesskit::{ActionHandler, ActionRequest, NodeBuilder, NodeId, Role, Tree, TreeUpdate}, - AccessibilityNode, AccessibilityRequested, AccessibilitySystem, Focus, + accesskit::{ + ActionHandler, ActionRequest, ActivationHandler, DeactivationHandler, Node, NodeBuilder, + NodeId, Role, Tree, TreeUpdate, + }, + AccessibilityNode, AccessibilityRequested, AccessibilitySystem, + ActionRequest as ActionRequestWrapper, Focus, ManageAccessibilityUpdates, }; -use bevy_a11y::{ActionRequest as ActionRequestWrapper, ManageAccessibilityUpdates}; use bevy_app::{App, Plugin, PostUpdate}; use bevy_derive::{Deref, DerefMut}; -use bevy_ecs::entity::EntityHashMap; use bevy_ecs::{ + entity::EntityHashMap, prelude::{DetectChanges, Entity, EventReader, EventWriter}, query::With, schedule::IntoSystemConfigs, diff --git a/crates/bevy_winit/src/lib.rs b/crates/bevy_winit/src/lib.rs index afad99ab093ad..bd1cee59c3379 100644 --- a/crates/bevy_winit/src/lib.rs +++ b/crates/bevy_winit/src/lib.rs @@ -12,9 +12,11 @@ //! The app's [runner](bevy_app::App::runner) is set by `WinitPlugin` and handles the `winit` [`EventLoop`]. //! See `winit_runner` for details. +extern crate alloc; + use bevy_derive::Deref; use bevy_window::{RawHandleWrapperHolder, WindowEvent}; -use std::marker::PhantomData; +use core::marker::PhantomData; use winit::event_loop::EventLoop; #[cfg(target_os = "android")] pub use winit::platform::android::activity as android_activity; @@ -27,16 +29,20 @@ pub use converters::convert_system_cursor_icon; pub use state::{CursorSource, CustomCursorCache, CustomCursorCacheKey, PendingCursor}; use system::{changed_windows, despawn_windows}; pub use system::{create_monitors, create_windows}; -pub use winit::event_loop::EventLoopProxy; #[cfg(all(target_family = "wasm", target_os = "unknown"))] pub use winit::platform::web::CustomCursorExtWebSys; -pub use winit::window::{CustomCursor as WinitCustomCursor, CustomCursorSource}; +pub use winit::{ + event_loop::EventLoopProxy, + window::{CustomCursor as WinitCustomCursor, CustomCursorSource}, +}; pub use winit_config::*; pub use winit_windows::*; -use crate::accessibility::{AccessKitAdapters, AccessKitPlugin, WinitActionRequestHandlers}; -use crate::state::winit_runner; -use crate::winit_monitors::WinitMonitors; +use crate::{ + accessibility::{AccessKitAdapters, AccessKitPlugin, WinitActionRequestHandlers}, + state::winit_runner, + winit_monitors::WinitMonitors, +}; pub mod accessibility; mod converters; diff --git a/crates/bevy_winit/src/state.rs b/crates/bevy_winit/src/state.rs index 4cff720878a59..53c21e71ec8eb 100644 --- a/crates/bevy_winit/src/state.rs +++ b/crates/bevy_winit/src/state.rs @@ -1,11 +1,13 @@ use approx::relative_eq; use bevy_app::{App, AppExit, PluginsState}; -use bevy_ecs::change_detection::{DetectChanges, NonSendMut, Res}; -use bevy_ecs::entity::Entity; -use bevy_ecs::event::{EventCursor, EventWriter}; -use bevy_ecs::prelude::*; -use bevy_ecs::system::SystemState; -use bevy_ecs::world::FromWorld; +use bevy_ecs::{ + change_detection::{DetectChanges, NonSendMut, Res}, + entity::Entity, + event::{EventCursor, EventWriter}, + prelude::*, + system::SystemState, + world::FromWorld, +}; use bevy_input::{ gestures::*, keyboard::KeyboardFocusLost, @@ -16,13 +18,15 @@ use bevy_math::{ivec2, DVec2, Vec2}; #[cfg(not(target_arch = "wasm32"))] use bevy_tasks::tick_global_task_pools_on_main_thread; use bevy_utils::{HashMap, Instant}; -use std::marker::PhantomData; -use winit::application::ApplicationHandler; -use winit::dpi::PhysicalSize; -use winit::event; -use winit::event::{DeviceEvent, DeviceId, StartCause, WindowEvent}; -use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop}; -use winit::window::WindowId; +use core::marker::PhantomData; +use winit::{ + application::ApplicationHandler, + dpi::PhysicalSize, + event, + event::{DeviceEvent, DeviceId, StartCause, WindowEvent}, + event_loop::{ActiveEventLoop, ControlFlow, EventLoop}, + window::WindowId, +}; use bevy_window::{ AppLifecycle, CursorEntered, CursorLeft, CursorMoved, FileDragAndDrop, Ime, RequestRedraw, @@ -33,11 +37,12 @@ use bevy_window::{ #[cfg(target_os = "android")] use bevy_window::{PrimaryWindow, RawHandleWrapper}; -use crate::accessibility::AccessKitAdapters; -use crate::system::{create_monitors, CachedWindow}; use crate::{ - converters, create_windows, AppSendEvent, CreateMonitorParams, CreateWindowParams, - EventLoopProxyWrapper, UpdateMode, WinitSettings, WinitWindows, + accessibility::AccessKitAdapters, + converters, create_windows, + system::{create_monitors, CachedWindow}, + AppSendEvent, CreateMonitorParams, CreateWindowParams, EventLoopProxyWrapper, UpdateMode, + WinitSettings, WinitWindows, }; /// Persistent state that is used to run the [`App`] according to the current diff --git a/crates/bevy_winit/src/system.rs b/crates/bevy_winit/src/system.rs index bd9f2dee1438e..2fa86d1e5171e 100644 --- a/crates/bevy_winit/src/system.rs +++ b/crates/bevy_winit/src/system.rs @@ -12,27 +12,27 @@ use bevy_window::{ WindowClosing, WindowCreated, WindowMode, WindowResized, WindowWrapper, }; -use winit::dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize}; -use winit::event_loop::ActiveEventLoop; +use winit::{ + dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize}, + event_loop::ActiveEventLoop, +}; use bevy_app::AppExit; -use bevy_ecs::prelude::EventReader; -use bevy_ecs::query::With; -use bevy_ecs::system::Res; +use bevy_ecs::{prelude::EventReader, query::With, system::Res}; use bevy_math::{IVec2, UVec2}; #[cfg(target_os = "ios")] use winit::platform::ios::WindowExtIOS; #[cfg(target_arch = "wasm32")] use winit::platform::web::WindowExtWebSys; -use crate::state::react_to_resize; -use crate::winit_monitors::WinitMonitors; use crate::{ converters::{ convert_enabled_buttons, convert_window_level, convert_window_theme, convert_winit_theme, }, - get_best_videomode, get_fitting_videomode, select_monitor, CreateMonitorParams, - CreateWindowParams, WinitWindows, + get_best_videomode, get_fitting_videomode, select_monitor, + state::react_to_resize, + winit_monitors::WinitMonitors, + CreateMonitorParams, CreateWindowParams, WinitWindows, }; /// Creates new windows on the [`winit`] backend for each entity with a newly-added diff --git a/crates/bevy_winit/src/winit_monitors.rs b/crates/bevy_winit/src/winit_monitors.rs index 0b8c0073e8a0e..e0b0f0fd32a1b 100644 --- a/crates/bevy_winit/src/winit_monitors.rs +++ b/crates/bevy_winit/src/winit_monitors.rs @@ -1,7 +1,6 @@ use winit::monitor::MonitorHandle; -use bevy_ecs::entity::Entity; -use bevy_ecs::system::Resource; +use bevy_ecs::{entity::Entity, system::Resource}; /// Stores [`winit`] monitors and their corresponding entities /// diff --git a/crates/bevy_winit/src/winit_windows.rs b/crates/bevy_winit/src/winit_windows.rs index 90574e635dc1c..f667960cc9f10 100644 --- a/crates/bevy_winit/src/winit_windows.rs +++ b/crates/bevy_winit/src/winit_windows.rs @@ -15,12 +15,12 @@ use winit::{ window::{CursorGrabMode as WinitCursorGrabMode, Fullscreen, Window as WinitWindow, WindowId}, }; -use crate::winit_monitors::WinitMonitors; use crate::{ accessibility::{ prepare_accessibility_for_window, AccessKitAdapters, WinitActionRequestHandlers, }, converters::{convert_enabled_buttons, convert_window_level, convert_window_theme}, + winit_monitors::WinitMonitors, }; /// A resource mapping window entities to their `winit`-backend [`Window`](winit::window::Window) @@ -322,7 +322,7 @@ pub fn get_fitting_videomode(monitor: &MonitorHandle, width: u32, height: u32) - } modes.sort_by(|a, b| { - use std::cmp::Ordering::*; + use core::cmp::Ordering::*; match abs_diff(a.size().width, width).cmp(&abs_diff(b.size().width, width)) { Equal => { match abs_diff(a.size().height, height).cmp(&abs_diff(b.size().height, height)) { @@ -345,7 +345,7 @@ pub fn get_fitting_videomode(monitor: &MonitorHandle, width: u32, height: u32) - pub fn get_best_videomode(monitor: &MonitorHandle) -> VideoModeHandle { let mut modes = monitor.video_modes().collect::>(); modes.sort_by(|a, b| { - use std::cmp::Ordering::*; + use core::cmp::Ordering::*; match b.size().width.cmp(&a.size().width) { Equal => match b.size().height.cmp(&a.size().height) { Equal => b @@ -470,7 +470,7 @@ struct DisplayInfo { } impl core::fmt::Display for DisplayInfo { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "Display information:")?; write!( f, diff --git a/examples/2d/mesh2d_arcs.rs b/examples/2d/mesh2d_arcs.rs index a600c986b6bb2..b9f63ffd5bc18 100644 --- a/examples/2d/mesh2d_arcs.rs +++ b/examples/2d/mesh2d_arcs.rs @@ -1,6 +1,7 @@ //! Demonstrates UV mappings of the [`CircularSector`] and [`CircularSegment`] primitives. //! //! Also draws the bounding boxes and circles of the primitives. + use std::f32::consts::FRAC_PI_2; use bevy::{ diff --git a/examples/2d/rotation.rs b/examples/2d/rotation.rs index 421fd3fbd3353..43227ed5027be 100644 --- a/examples/2d/rotation.rs +++ b/examples/2d/rotation.rs @@ -1,7 +1,6 @@ //! Demonstrates rotating entities in 2D using quaternions. -use bevy::math::ops; -use bevy::prelude::*; +use bevy::{math::ops, prelude::*}; const BOUNDS: Vec2 = Vec2::new(1200.0, 640.0); diff --git a/examples/2d/sprite_animation.rs b/examples/2d/sprite_animation.rs index 88f51de2d32da..74d3a2bf43e8f 100644 --- a/examples/2d/sprite_animation.rs +++ b/examples/2d/sprite_animation.rs @@ -4,8 +4,7 @@ use std::time::Duration; -use bevy::input::common_conditions::input_just_pressed; -use bevy::prelude::*; +use bevy::{input::common_conditions::input_just_pressed, prelude::*}; fn main() { App::new() diff --git a/examples/3d/anti_aliasing.rs b/examples/3d/anti_aliasing.rs index 73530ef5301c6..69bafcb30a7e1 100644 --- a/examples/3d/anti_aliasing.rs +++ b/examples/3d/anti_aliasing.rs @@ -1,7 +1,6 @@ //! This example compares MSAA (Multi-Sample Anti-aliasing), FXAA (Fast Approximate Anti-aliasing), and TAA (Temporal Anti-aliasing). -use std::f32::consts::PI; -use std::fmt::Write; +use std::{f32::consts::PI, fmt::Write}; use bevy::{ core_pipeline::{ diff --git a/examples/3d/generate_custom_mesh.rs b/examples/3d/generate_custom_mesh.rs index 6a8b1315e2651..4209c12152c22 100644 --- a/examples/3d/generate_custom_mesh.rs +++ b/examples/3d/generate_custom_mesh.rs @@ -2,11 +2,13 @@ //! assign a custom UV mapping for a custom texture, //! and how to change the UV mapping at run-time. -use bevy::prelude::*; -use bevy::render::{ - mesh::{Indices, VertexAttributeValues}, - render_asset::RenderAssetUsages, - render_resource::PrimitiveTopology, +use bevy::{ + prelude::*, + render::{ + mesh::{Indices, VertexAttributeValues}, + render_asset::RenderAssetUsages, + render_resource::PrimitiveTopology, + }, }; // Define a "marker" component to mark the custom mesh. Marker components are often used in Bevy for diff --git a/examples/3d/irradiance_volumes.rs b/examples/3d/irradiance_volumes.rs index e213c1f3a28e6..69e8dddfd0650 100644 --- a/examples/3d/irradiance_volumes.rs +++ b/examples/3d/irradiance_volumes.rs @@ -13,14 +13,17 @@ //! //! * Clicking anywhere moves the object. -use bevy::color::palettes::css::*; -use bevy::core_pipeline::Skybox; -use bevy::math::{uvec3, vec3}; -use bevy::pbr::irradiance_volume::IrradianceVolume; -use bevy::pbr::{ExtendedMaterial, MaterialExtension, NotShadowCaster}; -use bevy::prelude::*; -use bevy::render::render_resource::{AsBindGroup, ShaderRef, ShaderType}; -use bevy::window::PrimaryWindow; +use bevy::{ + color::palettes::css::*, + core_pipeline::Skybox, + math::{uvec3, vec3}, + pbr::{ + irradiance_volume::IrradianceVolume, ExtendedMaterial, MaterialExtension, NotShadowCaster, + }, + prelude::*, + render::render_resource::{AsBindGroup, ShaderRef, ShaderType}, + window::PrimaryWindow, +}; /// This example uses a shader source file from the assets subdirectory const SHADER_ASSET_PATH: &str = "shaders/irradiance_volume_voxel_visualization.wgsl"; diff --git a/examples/3d/lightmaps.rs b/examples/3d/lightmaps.rs index 564a3162bbca9..a9e498492d6ea 100644 --- a/examples/3d/lightmaps.rs +++ b/examples/3d/lightmaps.rs @@ -1,7 +1,6 @@ //! Rendering a scene with baked lightmaps. -use bevy::pbr::Lightmap; -use bevy::prelude::*; +use bevy::{pbr::Lightmap, prelude::*}; fn main() { App::new() diff --git a/examples/3d/pbr.rs b/examples/3d/pbr.rs index 5a25f99fcafd8..ec5c0a492222d 100644 --- a/examples/3d/pbr.rs +++ b/examples/3d/pbr.rs @@ -1,7 +1,6 @@ //! This example shows how to configure Physically Based Rendering (PBR) parameters. -use bevy::render::camera::ScalingMode; -use bevy::{asset::LoadState, prelude::*}; +use bevy::{asset::LoadState, prelude::*, render::camera::ScalingMode}; fn main() { App::new() diff --git a/examples/3d/reflection_probes.rs b/examples/3d/reflection_probes.rs index ca8f02441dd25..e126e8da35553 100644 --- a/examples/3d/reflection_probes.rs +++ b/examples/3d/reflection_probes.rs @@ -6,8 +6,7 @@ //! //! Reflection probes don't work on WebGL 2 or WebGPU. -use bevy::core_pipeline::Skybox; -use bevy::prelude::*; +use bevy::{core_pipeline::Skybox, prelude::*}; use std::{ f32::consts::PI, diff --git a/examples/3d/scrolling_fog.rs b/examples/3d/scrolling_fog.rs index 50a029864ef99..837d4a5bca876 100644 --- a/examples/3d/scrolling_fog.rs +++ b/examples/3d/scrolling_fog.rs @@ -10,12 +10,17 @@ //! The camera is looking at a pillar with the sun peaking behind it. The light //! interactions change based on the density of the fog. -use bevy::core_pipeline::bloom::Bloom; -use bevy::core_pipeline::experimental::taa::{TemporalAntiAliasBundle, TemporalAntiAliasPlugin}; -use bevy::pbr::{DirectionalLightShadowMap, FogVolume, VolumetricFog, VolumetricLight}; -use bevy::prelude::*; -use bevy::render::texture::{ - ImageAddressMode, ImageFilterMode, ImageLoaderSettings, ImageSampler, ImageSamplerDescriptor, +use bevy::{ + core_pipeline::{ + bloom::Bloom, + experimental::taa::{TemporalAntiAliasBundle, TemporalAntiAliasPlugin}, + }, + pbr::{DirectionalLightShadowMap, FogVolume, VolumetricFog, VolumetricLight}, + prelude::*, + render::texture::{ + ImageAddressMode, ImageFilterMode, ImageLoaderSettings, ImageSampler, + ImageSamplerDescriptor, + }, }; /// Initializes the example. diff --git a/examples/3d/transparency_3d.rs b/examples/3d/transparency_3d.rs index 3ea2be7457c0d..5db6d7b693a1e 100644 --- a/examples/3d/transparency_3d.rs +++ b/examples/3d/transparency_3d.rs @@ -2,8 +2,7 @@ //! Shows the effects of different blend modes. //! The `fade_transparency` system smoothly changes the transparency over time. -use bevy::math::ops; -use bevy::prelude::*; +use bevy::{math::ops, prelude::*}; fn main() { App::new() diff --git a/examples/animation/animated_fox.rs b/examples/animation/animated_fox.rs index a167e2b171c6d..f10e2b66ee1f3 100644 --- a/examples/animation/animated_fox.rs +++ b/examples/animation/animated_fox.rs @@ -1,7 +1,6 @@ //! Plays animations from a skinned glTF. -use std::f32::consts::PI; -use std::time::Duration; +use std::{f32::consts::PI, time::Duration}; use bevy::{ animation::{animate_targets, RepeatAnimation}, diff --git a/examples/animation/animated_transform.rs b/examples/animation/animated_transform.rs index 7fae355b9becb..d5eb9780c9e4d 100644 --- a/examples/animation/animated_transform.rs +++ b/examples/animation/animated_transform.rs @@ -2,8 +2,10 @@ use std::f32::consts::PI; -use bevy::animation::{AnimationTarget, AnimationTargetId}; -use bevy::prelude::*; +use bevy::{ + animation::{AnimationTarget, AnimationTargetId}, + prelude::*, +}; fn main() { App::new() diff --git a/examples/animation/animation_graph.rs b/examples/animation/animation_graph.rs index 50423e21fb4fa..94b9a2e52295e 100644 --- a/examples/animation/animation_graph.rs +++ b/examples/animation/animation_graph.rs @@ -3,9 +3,6 @@ //! The animation graph is shown on screen. You can change the weights of the //! playing animations by clicking and dragging left or right within the nodes. -#[cfg(not(target_arch = "wasm32"))] -use std::{fs::File, path::Path}; - use bevy::{ animation::animate_targets, color::palettes::{ @@ -17,12 +14,13 @@ use bevy::{ }; use argh::FromArgs; + #[cfg(not(target_arch = "wasm32"))] -use bevy::asset::io::file::FileAssetReader; -#[cfg(not(target_arch = "wasm32"))] -use bevy::tasks::IoTaskPool; -#[cfg(not(target_arch = "wasm32"))] -use ron::ser::PrettyConfig; +use { + bevy::{asset::io::file::FileAssetReader, tasks::IoTaskPool}, + ron::ser::PrettyConfig, + std::{fs::File, path::Path}, +}; /// Where to find the serialized animation graph. static ANIMATION_GRAPH_PATH: &str = "animation_graphs/Fox.animgraph.ron"; diff --git a/examples/app/log_layers.rs b/examples/app/log_layers.rs index 31a40faf2f6a7..fa7ddd1470bde 100644 --- a/examples/app/log_layers.rs +++ b/examples/app/log_layers.rs @@ -1,7 +1,10 @@ //! This example illustrates how to add custom log layers in bevy. -use bevy::log::BoxedLayer; -use bevy::{log::tracing_subscriber::Layer, prelude::*, utils::tracing::Subscriber}; +use bevy::{ + log::{tracing_subscriber::Layer, BoxedLayer}, + prelude::*, + utils::tracing::Subscriber, +}; struct CustomLayer; diff --git a/examples/app/log_layers_ecs.rs b/examples/app/log_layers_ecs.rs index 179a4715adf61..1c8cb983c4271 100644 --- a/examples/app/log_layers_ecs.rs +++ b/examples/app/log_layers_ecs.rs @@ -13,12 +13,13 @@ use std::sync::mpsc; -use bevy::log::BoxedLayer; use bevy::{ - log::tracing_subscriber::{self, Layer}, + log::{ + tracing_subscriber::{self, Layer}, + BoxedLayer, + }, prelude::*, - utils::tracing, - utils::tracing::Subscriber, + utils::{tracing, tracing::Subscriber}, }; /// A basic message. This is what we will be sending from the [`CaptureLayer`] to [`CapturedLogEvents`] non-send resource. diff --git a/examples/app/logs.rs b/examples/app/logs.rs index ffce34ffb4217..b48bf4e977629 100644 --- a/examples/app/logs.rs +++ b/examples/app/logs.rs @@ -1,7 +1,6 @@ //! This example illustrates how to use logs in bevy. -use bevy::log::once; -use bevy::prelude::*; +use bevy::{log::once, prelude::*}; fn main() { App::new() diff --git a/examples/app/without_winit.rs b/examples/app/without_winit.rs index 6a1b3782a3350..e651efac73cc8 100644 --- a/examples/app/without_winit.rs +++ b/examples/app/without_winit.rs @@ -1,7 +1,6 @@ //! Create an application without winit (runs single time, no event loop). -use bevy::prelude::*; -use bevy::winit::WinitPlugin; +use bevy::{prelude::*, winit::WinitPlugin}; fn main() { App::new() diff --git a/examples/asset/asset_decompression.rs b/examples/asset/asset_decompression.rs index 4101d24bb2008..70c0116d19e2b 100644 --- a/examples/asset/asset_decompression.rs +++ b/examples/asset/asset_decompression.rs @@ -9,8 +9,7 @@ use bevy::{ reflect::TypePath, }; use flate2::read::GzDecoder; -use std::io::prelude::*; -use std::marker::PhantomData; +use std::{io::prelude::*, marker::PhantomData}; use thiserror::Error; #[derive(Asset, TypePath)] diff --git a/examples/asset/embedded_asset.rs b/examples/asset/embedded_asset.rs index 9066bfaba72d6..b60ec636b3750 100644 --- a/examples/asset/embedded_asset.rs +++ b/examples/asset/embedded_asset.rs @@ -1,7 +1,9 @@ //! Example of loading an embedded asset. -use bevy::asset::{embedded_asset, io::AssetSourceId, AssetPath}; -use bevy::prelude::*; +use bevy::{ + asset::{embedded_asset, io::AssetSourceId, AssetPath}, + prelude::*, +}; use std::path::Path; fn main() { diff --git a/examples/asset/extra_source.rs b/examples/asset/extra_source.rs index 04d860d7af115..4e0463e4b1c7d 100644 --- a/examples/asset/extra_source.rs +++ b/examples/asset/extra_source.rs @@ -1,11 +1,13 @@ //! An example of registering an extra asset source, and loading assets from it. //! This asset source exists in addition to the default asset source. -use bevy::asset::{ - io::{AssetSourceBuilder, AssetSourceId}, - AssetPath, +use bevy::{ + asset::{ + io::{AssetSourceBuilder, AssetSourceId}, + AssetPath, + }, + prelude::*, }; -use bevy::prelude::*; use std::path::Path; fn main() { diff --git a/examples/async_tasks/async_compute.rs b/examples/async_tasks/async_compute.rs index d48223b339293..2ac4149478eea 100644 --- a/examples/async_tasks/async_compute.rs +++ b/examples/async_tasks/async_compute.rs @@ -2,8 +2,7 @@ //! to spawn, poll, and complete tasks across systems and system ticks. use bevy::{ - ecs::system::SystemState, - ecs::world::CommandQueue, + ecs::{system::SystemState, world::CommandQueue}, prelude::*, tasks::{block_on, futures_lite::future, AsyncComputeTaskPool, Task}, }; diff --git a/examples/audio/audio_control.rs b/examples/audio/audio_control.rs index c8aef7ccf89e0..6adbded9e3240 100644 --- a/examples/audio/audio_control.rs +++ b/examples/audio/audio_control.rs @@ -1,7 +1,6 @@ //! This example illustrates how to load and play an audio file, and control how it's played. -use bevy::math::ops; -use bevy::prelude::*; +use bevy::{math::ops, prelude::*}; fn main() { App::new() diff --git a/examples/audio/decodable.rs b/examples/audio/decodable.rs index 225868e96a5d9..aa31c0e1904e0 100644 --- a/examples/audio/decodable.rs +++ b/examples/audio/decodable.rs @@ -1,11 +1,12 @@ //! Shows how to create a custom [`Decodable`] type by implementing a Sine wave. -use bevy::audio::AddAudioSource; -use bevy::audio::AudioPlugin; -use bevy::audio::Source; -use bevy::math::ops; -use bevy::prelude::*; -use bevy::reflect::TypePath; -use bevy::utils::Duration; + +use bevy::{ + audio::{AddAudioSource, AudioPlugin, Source}, + math::ops, + prelude::*, + reflect::TypePath, + utils::Duration, +}; // This struct usually contains the data for the audio being played. // This is where data read from an audio file would be stored, for example. diff --git a/examples/camera/2d_top_down_camera.rs b/examples/camera/2d_top_down_camera.rs index c94f004bf9bfc..8f49e7bba6258 100644 --- a/examples/camera/2d_top_down_camera.rs +++ b/examples/camera/2d_top_down_camera.rs @@ -9,10 +9,12 @@ //! | `A` | Move left | //! | `D` | Move right | -use bevy::core_pipeline::bloom::Bloom; -use bevy::math::vec3; -use bevy::prelude::*; -use bevy::sprite::{MaterialMesh2dBundle, Mesh2dHandle}; +use bevy::{ + core_pipeline::bloom::Bloom, + math::vec3, + prelude::*, + sprite::{MaterialMesh2dBundle, Mesh2dHandle}, +}; /// Player movement speed factor. const PLAYER_SPEED: f32 = 100.; diff --git a/examples/camera/first_person_view_model.rs b/examples/camera/first_person_view_model.rs index d3d30fc878ab9..79bec51eed2b8 100644 --- a/examples/camera/first_person_view_model.rs +++ b/examples/camera/first_person_view_model.rs @@ -44,11 +44,10 @@ use std::f32::consts::FRAC_PI_2; -use bevy::color::palettes::tailwind; -use bevy::input::mouse::AccumulatedMouseMotion; -use bevy::pbr::NotShadowCaster; -use bevy::prelude::*; -use bevy::render::view::RenderLayers; +use bevy::{ + color::palettes::tailwind, input::mouse::AccumulatedMouseMotion, pbr::NotShadowCaster, + prelude::*, render::view::RenderLayers, +}; fn main() { App::new() diff --git a/examples/ecs/component_hooks.rs b/examples/ecs/component_hooks.rs index 1828807da1d86..7598ad90ca161 100644 --- a/examples/ecs/component_hooks.rs +++ b/examples/ecs/component_hooks.rs @@ -13,8 +13,10 @@ //! - Enforcing structural rules: When you have systems that depend on specific relationships //! between components (like hierarchies or parent-child links) and need to maintain correctness. -use bevy::ecs::component::{ComponentHooks, StorageType}; -use bevy::prelude::*; +use bevy::{ + ecs::component::{ComponentHooks, StorageType}, + prelude::*, +}; use std::collections::HashMap; #[derive(Debug)] diff --git a/examples/ecs/custom_schedule.rs b/examples/ecs/custom_schedule.rs index 564d00f401cca..aa6fe63658b80 100644 --- a/examples/ecs/custom_schedule.rs +++ b/examples/ecs/custom_schedule.rs @@ -1,9 +1,11 @@ //! Demonstrates how to add custom schedules that run in Bevy's `Main` schedule, ordered relative to Bevy's built-in //! schedules such as `Update` or `Last`. -use bevy::app::MainScheduleOrder; -use bevy::ecs::schedule::{ExecutorKind, ScheduleLabel}; -use bevy::prelude::*; +use bevy::{ + app::MainScheduleOrder, + ecs::schedule::{ExecutorKind, ScheduleLabel}, + prelude::*, +}; #[derive(ScheduleLabel, Debug, Hash, PartialEq, Eq, Clone)] struct SingleThreadedUpdate; diff --git a/examples/ecs/dynamic.rs b/examples/ecs/dynamic.rs index 855ed02c12d48..fe1523dd5bd21 100644 --- a/examples/ecs/dynamic.rs +++ b/examples/ecs/dynamic.rs @@ -5,13 +5,13 @@ use std::{alloc::Layout, io::Write, ptr::NonNull}; -use bevy::prelude::*; use bevy::{ ecs::{ component::{ComponentDescriptor, ComponentId, ComponentInfo, StorageType}, query::QueryData, world::FilteredEntityMut, }, + prelude::*, ptr::{Aligned, OwningPtr}, utils::HashMap, }; diff --git a/examples/ecs/hierarchy.rs b/examples/ecs/hierarchy.rs index 2729b63b3eb88..e3356d28e36f5 100644 --- a/examples/ecs/hierarchy.rs +++ b/examples/ecs/hierarchy.rs @@ -2,8 +2,7 @@ use std::f32::consts::*; -use bevy::color::palettes::css::*; -use bevy::prelude::*; +use bevy::{color::palettes::css::*, prelude::*}; fn main() { App::new() diff --git a/examples/ecs/parallel_query.rs b/examples/ecs/parallel_query.rs index 8eebb26da1265..adf7f243da83c 100644 --- a/examples/ecs/parallel_query.rs +++ b/examples/ecs/parallel_query.rs @@ -1,7 +1,6 @@ //! Illustrates parallel queries with `ParallelIterator`. -use bevy::ecs::batching::BatchingStrategy; -use bevy::prelude::*; +use bevy::{ecs::batching::BatchingStrategy, prelude::*}; use rand::{Rng, SeedableRng}; use rand_chacha::ChaCha8Rng; diff --git a/examples/ecs/send_and_receive_events.rs b/examples/ecs/send_and_receive_events.rs index cabcc26d36886..df03b500f2cf6 100644 --- a/examples/ecs/send_and_receive_events.rs +++ b/examples/ecs/send_and_receive_events.rs @@ -19,9 +19,7 @@ //! //! Let's look at an example of each. -use bevy::core::FrameCount; -use bevy::ecs::event::EventCursor; -use bevy::prelude::*; +use bevy::{core::FrameCount, ecs::event::EventCursor, prelude::*}; fn main() { let mut app = App::new(); diff --git a/examples/ecs/system_piping.rs b/examples/ecs/system_piping.rs index 63579a2b61073..3b7879af09b9d 100644 --- a/examples/ecs/system_piping.rs +++ b/examples/ecs/system_piping.rs @@ -4,8 +4,10 @@ use bevy::prelude::*; use std::num::ParseIntError; -use bevy::log::LogPlugin; -use bevy::utils::{dbg, error, info, tracing::Level, warn}; +use bevy::{ + log::LogPlugin, + utils::{dbg, error, info, tracing::Level, warn}, +}; fn main() { App::new() diff --git a/examples/games/loading_screen.rs b/examples/games/loading_screen.rs index a90b0e769bebd..763bc1886054c 100644 --- a/examples/games/loading_screen.rs +++ b/examples/games/loading_screen.rs @@ -320,7 +320,10 @@ fn display_loading_screen( } mod pipelines_ready { - use bevy::{prelude::*, render::render_resource::*, render::*}; + use bevy::{ + prelude::*, + render::{render_resource::*, *}, + }; pub struct PipelinesReadyPlugin; impl Plugin for PipelinesReadyPlugin { diff --git a/examples/gizmos/axes.rs b/examples/gizmos/axes.rs index daaa3b3556610..69c546df8963a 100644 --- a/examples/gizmos/axes.rs +++ b/examples/gizmos/axes.rs @@ -1,7 +1,6 @@ //! This example demonstrates the implementation and behavior of the axes gizmo. -use bevy::prelude::*; -use bevy::render::primitives::Aabb; +use bevy::{prelude::*, render::primitives::Aabb}; use rand::{Rng, SeedableRng}; use rand_chacha::ChaCha8Rng; use std::f32::consts::PI; diff --git a/examples/helpers/camera_controller.rs b/examples/helpers/camera_controller.rs index 62c2a2d2e6bcf..d5b5d7d612900 100644 --- a/examples/helpers/camera_controller.rs +++ b/examples/helpers/camera_controller.rs @@ -3,9 +3,11 @@ //! - Copy the code for the [`CameraControllerPlugin`] and add the plugin to your App. //! - Attach the [`CameraController`] component to an entity with a [`Camera3dBundle`]. -use bevy::input::mouse::{AccumulatedMouseMotion, AccumulatedMouseScroll, MouseScrollUnit}; -use bevy::prelude::*; -use bevy::window::CursorGrabMode; +use bevy::{ + input::mouse::{AccumulatedMouseMotion, AccumulatedMouseScroll, MouseScrollUnit}, + prelude::*, + window::CursorGrabMode, +}; use std::{f32::consts::*, fmt}; pub struct CameraControllerPlugin; diff --git a/examples/math/sampling_primitives.rs b/examples/math/sampling_primitives.rs index 8f00d49d62295..38112989ea5a9 100644 --- a/examples/math/sampling_primitives.rs +++ b/examples/math/sampling_primitives.rs @@ -8,8 +8,7 @@ use bevy::{ math::prelude::*, prelude::*, }; -use rand::seq::SliceRandom; -use rand::{Rng, SeedableRng}; +use rand::{seq::SliceRandom, Rng, SeedableRng}; use rand_chacha::ChaCha8Rng; fn main() { diff --git a/examples/movement/smooth_follow.rs b/examples/movement/smooth_follow.rs index 8119cc203deb4..6a9fb01878228 100644 --- a/examples/movement/smooth_follow.rs +++ b/examples/movement/smooth_follow.rs @@ -1,7 +1,9 @@ //! This example demonstrates how to use interpolation to make one entity smoothly follow another. -use bevy::math::{prelude::*, vec3, NormedVectorSpace}; -use bevy::prelude::*; +use bevy::{ + math::{prelude::*, vec3, NormedVectorSpace}, + prelude::*, +}; use rand::SeedableRng; use rand_chacha::ChaCha8Rng; diff --git a/examples/reflection/custom_attributes.rs b/examples/reflection/custom_attributes.rs index d89783c85f95f..f75a0a8d3e7e0 100644 --- a/examples/reflection/custom_attributes.rs +++ b/examples/reflection/custom_attributes.rs @@ -1,8 +1,7 @@ //! Demonstrates how to register and access custom attributes on reflected types. use bevy::reflect::{Reflect, TypeInfo, Typed}; -use std::any::TypeId; -use std::ops::RangeInclusive; +use std::{any::TypeId, ops::RangeInclusive}; fn main() { // Bevy supports statically registering custom attribute data on reflected types, diff --git a/examples/reflection/function_reflection.rs b/examples/reflection/function_reflection.rs index d2334ae4a0b88..c37db7941a0d5 100644 --- a/examples/reflection/function_reflection.rs +++ b/examples/reflection/function_reflection.rs @@ -6,11 +6,13 @@ //! This can be used for things like adding scripting support to your application, //! processing deserialized reflection data, or even just storing type-erased versions of your functions. -use bevy::reflect::func::{ - ArgList, DynamicFunction, DynamicFunctionMut, FunctionInfo, FunctionResult, IntoFunction, - IntoFunctionMut, Return, +use bevy::reflect::{ + func::{ + ArgList, DynamicFunction, DynamicFunctionMut, FunctionInfo, FunctionResult, IntoFunction, + IntoFunctionMut, Return, + }, + PartialReflect, Reflect, }; -use bevy::reflect::{PartialReflect, Reflect}; // Note that the `dbg!` invocations are used purely for demonstration purposes // and are not strictly necessary for the example to work. diff --git a/examples/reflection/type_data.rs b/examples/reflection/type_data.rs index 10c21fce861b5..56dafa8522d6e 100644 --- a/examples/reflection/type_data.rs +++ b/examples/reflection/type_data.rs @@ -1,7 +1,9 @@ //! The example demonstrates what type data is, how to create it, and how to use it. -use bevy::prelude::*; -use bevy::reflect::{FromType, TypeRegistry}; +use bevy::{ + prelude::*, + reflect::{FromType, TypeRegistry}, +}; // It's recommended to read this example from top to bottom. // Comments are provided to explain the code and its purpose as you go along. diff --git a/examples/shader/texture_binding_array.rs b/examples/shader/texture_binding_array.rs index 24a8a847a1c19..28656e1862f7c 100644 --- a/examples/shader/texture_binding_array.rs +++ b/examples/shader/texture_binding_array.rs @@ -1,9 +1,8 @@ //! A shader that binds several textures onto one //! `binding_array>` shader binding slot and sample non-uniformly. -use bevy::ecs::system::lifetimeless::SRes; -use bevy::ecs::system::SystemParamItem; use bevy::{ + ecs::system::{lifetimeless::SRes, SystemParamItem}, prelude::*, reflect::TypePath, render::{ diff --git a/examples/stress_tests/many_foxes.rs b/examples/stress_tests/many_foxes.rs index fc6e689c67211..ccd3c1c8c9a9e 100644 --- a/examples/stress_tests/many_foxes.rs +++ b/examples/stress_tests/many_foxes.rs @@ -1,8 +1,7 @@ //! Loads animations from a skinned glTF, spawns many of them, and plays the //! animation to stress test skinned meshes. -use std::f32::consts::PI; -use std::time::Duration; +use std::{f32::consts::PI, time::Duration}; use argh::FromArgs; use bevy::{ diff --git a/examples/time/time.rs b/examples/time/time.rs index 0f18c63001403..c9f21d933f628 100644 --- a/examples/time/time.rs +++ b/examples/time/time.rs @@ -1,10 +1,11 @@ //! An example that illustrates how Time is handled in ECS. -use bevy::app::AppExit; -use bevy::prelude::*; +use bevy::{app::AppExit, prelude::*}; -use std::io::{self, BufRead}; -use std::time::Duration; +use std::{ + io::{self, BufRead}, + time::Duration, +}; fn banner() { println!("This example is meant to intuitively demonstrate how Time works in Bevy."); diff --git a/examples/tools/scene_viewer/scene_viewer_plugin.rs b/examples/tools/scene_viewer/scene_viewer_plugin.rs index 2ff6af4948928..f77508ab8263d 100644 --- a/examples/tools/scene_viewer/scene_viewer_plugin.rs +++ b/examples/tools/scene_viewer/scene_viewer_plugin.rs @@ -8,8 +8,7 @@ use bevy::{ scene::InstanceId, }; -use std::f32::consts::*; -use std::fmt; +use std::{f32::consts::*, fmt}; use super::camera_controller::*; diff --git a/examples/transforms/align.rs b/examples/transforms/align.rs index 1e84ca38c3cf1..4e9c9f50a5275 100644 --- a/examples/transforms/align.rs +++ b/examples/transforms/align.rs @@ -1,9 +1,11 @@ //! This example shows how to align the orientations of objects in 3D space along two axes using the `Transform::align` API. -use bevy::color::palettes::basic::{GRAY, RED, WHITE}; -use bevy::input::mouse::{AccumulatedMouseMotion, MouseButtonInput}; -use bevy::math::StableInterpolate; -use bevy::prelude::*; +use bevy::{ + color::palettes::basic::{GRAY, RED, WHITE}, + input::mouse::{AccumulatedMouseMotion, MouseButtonInput}, + math::StableInterpolate, + prelude::*, +}; use rand::{Rng, SeedableRng}; use rand_chacha::ChaCha8Rng; diff --git a/examples/ui/display_and_visibility.rs b/examples/ui/display_and_visibility.rs index 5ff0a9ecac918..bd944b1ecbe77 100644 --- a/examples/ui/display_and_visibility.rs +++ b/examples/ui/display_and_visibility.rs @@ -1,9 +1,9 @@ //! Demonstrates how Display and Visibility work in the UI. -use bevy::winit::WinitSettings; use bevy::{ color::palettes::css::{DARK_GRAY, YELLOW}, prelude::*, + winit::WinitSettings, }; const PALETTE: [&str; 4] = ["27496D", "466B7A", "669DB3", "ADCBE3"]; diff --git a/examples/ui/overflow_debug.rs b/examples/ui/overflow_debug.rs index 07b479a7cd706..68ccfb0a6dd27 100644 --- a/examples/ui/overflow_debug.rs +++ b/examples/ui/overflow_debug.rs @@ -1,4 +1,5 @@ //! Tests how different transforms behave when clipped with `Overflow::Hidden` + use bevy::{input::common_conditions::input_just_pressed, prelude::*}; use std::f32::consts::{FRAC_PI_2, PI, TAU}; diff --git a/examples/ui/text_wrap_debug.rs b/examples/ui/text_wrap_debug.rs index 0f5fdacb3f98e..57d0b12f8001b 100644 --- a/examples/ui/text_wrap_debug.rs +++ b/examples/ui/text_wrap_debug.rs @@ -1,10 +1,7 @@ //! This example demonstrates text wrapping and use of the `LineBreakOn` property. use argh::FromArgs; -use bevy::prelude::*; -use bevy::text::BreakLineOn; -use bevy::window::WindowResolution; -use bevy::winit::WinitSettings; +use bevy::{prelude::*, text::BreakLineOn, window::WindowResolution, winit::WinitSettings}; #[derive(FromArgs, Resource)] /// `text_wrap_debug` demonstrates text wrapping and use of the `LineBreakOn` property diff --git a/examples/ui/ui_material.rs b/examples/ui/ui_material.rs index 6aacc9bb8d23f..17a8ca9b60511 100644 --- a/examples/ui/ui_material.rs +++ b/examples/ui/ui_material.rs @@ -1,8 +1,6 @@ //! Demonstrates the use of [`UiMaterials`](UiMaterial) and how to change material values -use bevy::prelude::*; -use bevy::reflect::TypePath; -use bevy::render::render_resource::*; +use bevy::{prelude::*, reflect::TypePath, render::render_resource::*}; /// This example uses a shader source file from the assets subdirectory const SHADER_ASSET_PATH: &str = "shaders/custom_ui_material.wgsl"; diff --git a/examples/window/custom_user_event.rs b/examples/window/custom_user_event.rs index a088697c251c1..58c872e2ccfd9 100644 --- a/examples/window/custom_user_event.rs +++ b/examples/window/custom_user_event.rs @@ -1,7 +1,9 @@ //! Shows how to create a custom event that can be handled by `winit`'s event loop. -use bevy::prelude::*; -use bevy::winit::{EventLoopProxyWrapper, WakeUp, WinitPlugin}; +use bevy::{ + prelude::*, + winit::{EventLoopProxyWrapper, WakeUp, WinitPlugin}, +}; use std::fmt::Formatter; #[derive(Default, Debug, Event)] @@ -81,8 +83,7 @@ fn handle_event(mut events: EventReader) { pub(crate) mod wasm { use super::*; use bevy::winit::EventLoopProxy; - use wasm_bindgen::prelude::*; - use wasm_bindgen::JsCast; + use wasm_bindgen::{prelude::*, JsCast}; use web_sys::KeyboardEvent; pub(crate) fn setup_js_closure(event_loop: Res>) { diff --git a/examples/window/monitor_info.rs b/examples/window/monitor_info.rs index 43b17645f1f86..6a09a9ad35067 100644 --- a/examples/window/monitor_info.rs +++ b/examples/window/monitor_info.rs @@ -1,8 +1,10 @@ //! Displays information about available monitors (displays). -use bevy::render::camera::RenderTarget; -use bevy::window::{ExitCondition, WindowMode, WindowRef}; -use bevy::{prelude::*, window::Monitor}; +use bevy::{ + prelude::*, + render::camera::RenderTarget, + window::{ExitCondition, Monitor, WindowMode, WindowRef}, +}; fn main() { App::new() diff --git a/examples/window/screenshot.rs b/examples/window/screenshot.rs index c5c25b0fd30cd..c8dc4d0011fe0 100644 --- a/examples/window/screenshot.rs +++ b/examples/window/screenshot.rs @@ -1,11 +1,13 @@ //! An example showing how to save screenshots to disk -use bevy::prelude::*; -use bevy::render::view::{ - cursor::CursorIcon, - screenshot::{save_to_disk, Capturing, Screenshot}, +use bevy::{ + prelude::*, + render::view::{ + cursor::CursorIcon, + screenshot::{save_to_disk, Capturing, Screenshot}, + }, + window::SystemCursorIcon, }; -use bevy::window::SystemCursorIcon; fn main() { App::new() diff --git a/tools/build-templated-pages/src/examples.rs b/tools/build-templated-pages/src/examples.rs index a364d655de18a..318c5e62df9ab 100644 --- a/tools/build-templated-pages/src/examples.rs +++ b/tools/build-templated-pages/src/examples.rs @@ -1,4 +1,5 @@ -use std::{cmp::Ordering, fs::File}; +use core::cmp::Ordering; +use std::fs::File; use hashbrown::HashMap; use serde::Serialize; diff --git a/tools/build-templated-pages/src/features.rs b/tools/build-templated-pages/src/features.rs index 9ab11161a0f4e..eb7478f6c0f66 100644 --- a/tools/build-templated-pages/src/features.rs +++ b/tools/build-templated-pages/src/features.rs @@ -1,4 +1,5 @@ -use std::{cmp::Ordering, fs::File}; +use core::cmp::Ordering; +use std::fs::File; use serde::Serialize; use tera::{Context, Tera}; @@ -37,7 +38,7 @@ fn parse_features(panic_on_missing: bool) -> Vec { .unwrap() .iter() .flat_map(|v| { - std::iter::once(v.as_str().unwrap().to_string()).chain( + core::iter::once(v.as_str().unwrap().to_string()).chain( features .get(v.as_str().unwrap()) .unwrap() diff --git a/tools/ci/src/ci.rs b/tools/ci/src/ci.rs index c02fdfb31cece..beaab08e09093 100644 --- a/tools/ci/src/ci.rs +++ b/tools/ci/src/ci.rs @@ -1,5 +1,7 @@ -use crate::commands; -use crate::prepare::{Flag, Prepare, PreparedCommand}; +use crate::{ + commands, + prepare::{Flag, Prepare, PreparedCommand}, +}; use argh::FromArgs; /// The CI command line tool for Bevy. diff --git a/tools/ci/src/commands/compile.rs b/tools/ci/src/commands/compile.rs index 70234c88a5626..f3fcefabb153e 100644 --- a/tools/ci/src/commands/compile.rs +++ b/tools/ci/src/commands/compile.rs @@ -1,8 +1,10 @@ -use crate::commands::{ - BenchCheckCommand, CompileCheckCommand, CompileFailCommand, ExampleCheckCommand, - TestCheckCommand, +use crate::{ + commands::{ + BenchCheckCommand, CompileCheckCommand, CompileFailCommand, ExampleCheckCommand, + TestCheckCommand, + }, + Flag, Prepare, PreparedCommand, }; -use crate::{Flag, Prepare, PreparedCommand}; use argh::FromArgs; /// Alias for running the `compile-fail`, `bench-check`, `example-check`, `compile-check`, and `test-check` subcommands. diff --git a/tools/ci/src/commands/doc.rs b/tools/ci/src/commands/doc.rs index f4ccb089f2946..fb8074ca8cf48 100644 --- a/tools/ci/src/commands/doc.rs +++ b/tools/ci/src/commands/doc.rs @@ -1,5 +1,7 @@ -use crate::commands::{DocCheckCommand, DocTestCommand}; -use crate::{Flag, Prepare, PreparedCommand}; +use crate::{ + commands::{DocCheckCommand, DocTestCommand}, + Flag, Prepare, PreparedCommand, +}; use argh::FromArgs; /// Alias for running the `doc-test` and `doc-check` subcommands. diff --git a/tools/ci/src/commands/lints.rs b/tools/ci/src/commands/lints.rs index ae6715a08bfd9..befdaf5fc5d48 100644 --- a/tools/ci/src/commands/lints.rs +++ b/tools/ci/src/commands/lints.rs @@ -1,5 +1,7 @@ -use crate::commands::{ClippyCommand, FormatCommand}; -use crate::{Flag, Prepare, PreparedCommand}; +use crate::{ + commands::{ClippyCommand, FormatCommand}, + Flag, Prepare, PreparedCommand, +}; use argh::FromArgs; /// Alias for running the `format` and `clippy` subcommands. diff --git a/tools/ci/src/main.rs b/tools/ci/src/main.rs index 0e7681ada1659..40893a528d4cd 100644 --- a/tools/ci/src/main.rs +++ b/tools/ci/src/main.rs @@ -4,8 +4,7 @@ mod ci; mod commands; mod prepare; -pub use self::ci::*; -pub use self::prepare::*; +pub use self::{ci::*, prepare::*}; fn main() { argh::from_env::().run(); diff --git a/tools/example-showcase/disable-audio.patch b/tools/example-showcase/disable-audio.patch index 6fe4295837abb..70abd7d766eb6 100644 --- a/tools/example-showcase/disable-audio.patch +++ b/tools/example-showcase/disable-audio.patch @@ -17,7 +17,7 @@ index 3e8082e23..624769443 100644 fn default() -> Self { - if let Ok((stream, stream_handle)) = OutputStream::try_default() { - // We leak `OutputStream` to prevent the audio from stopping. -- std::mem::forget(stream); +- core::mem::forget(stream); - Self { - stream_handle: Some(stream_handle), - } diff --git a/tools/example-showcase/src/main.rs b/tools/example-showcase/src/main.rs index c9c1d9266f409..af3f4e0f699ce 100644 --- a/tools/example-showcase/src/main.rs +++ b/tools/example-showcase/src/main.rs @@ -1,15 +1,18 @@ //! Tool to run all examples or generate a showcase page for the Bevy website. +use core::{ + fmt::Display, + hash::{Hash, Hasher}, + time::Duration, +}; use std::{ collections::{hash_map::DefaultHasher, HashMap}, - fmt::Display, fs::{self, File}, - hash::{Hash, Hasher}, io::Write, path::{Path, PathBuf}, process::exit, thread, - time::{Duration, Instant}, + time::Instant, }; use clap::{error::ErrorKind, CommandFactory, Parser, ValueEnum}; @@ -119,7 +122,7 @@ enum WebApi { } impl Display for WebApi { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { WebApi::Webgl2 => write!(f, "webgl2"), WebApi::Webgpu => write!(f, "webgpu"),