repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_state/src/state/resources.rs | crates/bevy_state/src/state/resources.rs | use core::ops::Deref;
use bevy_ecs::{
change_detection::DetectChangesMut,
resource::Resource,
system::ResMut,
world::{FromWorld, World},
};
use super::{freely_mutable_state::FreelyMutableState, states::States};
#[cfg(feature = "bevy_reflect")]
use bevy_ecs::prelude::ReflectResource;
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::prelude::ReflectDefault;
/// A finite-state machine whose transitions have associated schedules
/// ([`OnEnter(state)`](crate::state::OnEnter) and [`OnExit(state)`](crate::state::OnExit)).
///
/// The current state value can be accessed through this resource. To *change* the state,
/// queue a transition in the [`NextState<S>`] resource, and it will be applied during the
/// [`StateTransition`](crate::state::StateTransition) schedule - which by default runs after `PreUpdate`.
///
/// You can also manually trigger the [`StateTransition`](crate::state::StateTransition) schedule to apply the changes
/// at an arbitrary time.
///
/// The starting state is defined via the [`Default`] implementation for `S`.
///
/// ```
/// use bevy_state::prelude::*;
/// use bevy_ecs::prelude::*;
/// use bevy_state_macros::States;
///
/// #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default, States)]
/// enum GameState {
/// #[default]
/// MainMenu,
/// SettingsMenu,
/// InGame,
/// }
///
/// fn game_logic(game_state: Res<State<GameState>>) {
/// match game_state.get() {
/// GameState::InGame => {
/// // Run game logic here...
/// },
/// _ => {},
/// }
/// }
/// ```
#[derive(Resource, Debug)]
#[cfg_attr(
feature = "bevy_reflect",
derive(bevy_reflect::Reflect),
reflect(Resource, Debug, PartialEq)
)]
pub struct State<S: States>(pub(crate) S);
impl<S: States> State<S> {
/// Creates a new state with a specific value.
///
/// To change the state use [`NextState<S>`] rather than using this to modify the `State<S>`.
pub fn new(state: S) -> Self {
Self(state)
}
/// Get the current state.
pub fn get(&self) -> &S {
&self.0
}
}
impl<S: States + FromWorld> FromWorld for State<S> {
fn from_world(world: &mut World) -> Self {
Self(S::from_world(world))
}
}
impl<S: States> PartialEq<S> for State<S> {
fn eq(&self, other: &S) -> bool {
self.get() == other
}
}
impl<S: States> Deref for State<S> {
type Target = S;
fn deref(&self) -> &Self::Target {
self.get()
}
}
/// The previous state of [`State<S>`].
///
/// This resource holds the state value that was active immediately **before** the
/// most recent state transition. It is primarily useful for logic that runs
/// during state exit or transition schedules ([`OnExit`](crate::state::OnExit), [`OnTransition`](crate::state::OnTransition)).
///
/// It is inserted into the world only after the first state transition occurs. It will
/// remain present even if the primary state is removed (e.g., when a
/// [`SubStates`](crate::state::SubStates) or [`ComputedStates`](crate::state::ComputedStates) instance ceases to exist).
///
/// Use `Option<Res<PreviousState<S>>>` to access it, as it will not exist
/// before the first transition.
///
/// ```
/// use bevy_state::prelude::*;
/// use bevy_ecs::prelude::*;
/// use bevy_state_macros::States;
///
/// #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default, States)]
/// enum GameState {
/// #[default]
/// MainMenu,
/// InGame,
/// }
///
/// // This system might run in an OnExit schedule
/// fn log_previous_state(previous_state: Option<Res<PreviousState<GameState>>>) {
/// if let Some(previous) = previous_state {
/// // If this system is in OnExit(InGame), the previous state is what we
/// // were in before InGame.
/// println!("Transitioned from: {:?}", previous.get());
/// }
/// }
/// ```
#[derive(Resource, Debug, Clone, PartialEq, Eq)]
#[cfg_attr(
feature = "bevy_reflect",
derive(bevy_reflect::Reflect),
reflect(Resource, Debug, PartialEq)
)]
pub struct PreviousState<S: States>(pub(crate) S);
impl<S: States> PreviousState<S> {
/// Get the previous state.
pub fn get(&self) -> &S {
&self.0
}
}
impl<S: States> Deref for PreviousState<S> {
type Target = S;
fn deref(&self) -> &Self::Target {
&self.0
}
}
/// The next state of [`State<S>`].
///
/// This can be fetched as a resource and used to queue state transitions.
/// To queue a transition, call [`NextState::set`] or mutate the value to [`NextState::Pending`] directly.
///
/// Note that these transitions can be overridden by other systems:
/// only the actual value of this resource during the [`StateTransition`](crate::state::StateTransition) schedule matters.
///
/// ```
/// use bevy_state::prelude::*;
/// use bevy_ecs::prelude::*;
///
/// #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default, States)]
/// enum GameState {
/// #[default]
/// MainMenu,
/// SettingsMenu,
/// InGame,
/// }
///
/// fn start_game(mut next_game_state: ResMut<NextState<GameState>>) {
/// next_game_state.set(GameState::InGame);
/// }
/// ```
#[derive(Resource, Debug, Default, Clone)]
#[cfg_attr(
feature = "bevy_reflect",
derive(bevy_reflect::Reflect),
reflect(Resource, Default, Debug)
)]
pub enum NextState<S: FreelyMutableState> {
/// No state transition is pending
#[default]
Unchanged,
/// There is a pending transition for state `S`
Pending(S),
/// There is a pending transition for state `S`
///
/// This will not trigger state transitions schedules if the target state is the same as the current one.
PendingIfNeq(S),
}
impl<S: FreelyMutableState> NextState<S> {
/// Tentatively set a pending state transition to `Some(state)`.
///
/// This will run the state transition schedules [`OnEnter`](crate::state::OnEnter) and [`OnExit`](crate::state::OnExit).
/// If you want to skip those schedules for the same where we are transitioning to the same state, use [`set_if_neq`](Self::set_if_neq) instead.
pub fn set(&mut self, state: S) {
*self = Self::Pending(state);
}
/// Tentatively set a pending state transition to `Some(state)`.
///
/// Like [`set`](Self::set), but will not run any state transition schedules if the target state is the same as the current one.
/// If [`set`](Self::set) has already been called in the same frame with the same state, the transition schedules will be run anyways.
pub fn set_if_neq(&mut self, state: S) {
if !matches!(self, Self::Pending(s) if s == &state) {
*self = Self::PendingIfNeq(state);
}
}
/// Remove any pending changes to [`State<S>`]
pub fn reset(&mut self) {
*self = Self::Unchanged;
}
}
pub(crate) fn take_next_state<S: FreelyMutableState>(
next_state: Option<ResMut<NextState<S>>>,
) -> Option<(S, bool)> {
let mut next_state = next_state?;
match core::mem::take(next_state.bypass_change_detection()) {
NextState::Pending(x) => {
next_state.set_changed();
Some((x, true))
}
NextState::PendingIfNeq(x) => {
next_state.set_changed();
Some((x, false))
}
NextState::Unchanged => None,
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_state/src/state/mod.rs | crates/bevy_state/src/state/mod.rs | mod computed_states;
mod freely_mutable_state;
mod resources;
mod state_set;
mod states;
mod sub_states;
mod transitions;
pub use bevy_state_macros::*;
pub use computed_states::*;
pub use freely_mutable_state::*;
pub use resources::*;
pub use state_set::*;
pub use states::*;
pub use sub_states::*;
pub use transitions::*;
#[cfg(test)]
mod tests {
use alloc::vec::Vec;
use bevy_ecs::{message::MessageRegistry, prelude::*};
use bevy_state_macros::{States, SubStates};
use super::*;
#[derive(States, PartialEq, Eq, Debug, Default, Hash, Clone)]
enum SimpleState {
#[default]
A,
B(bool),
}
#[derive(PartialEq, Eq, Debug, Hash, Clone)]
enum TestComputedState {
BisTrue,
BisFalse,
}
impl ComputedStates for TestComputedState {
type SourceStates = Option<SimpleState>;
fn compute(sources: Option<SimpleState>) -> Option<Self> {
sources.and_then(|source| match source {
SimpleState::A => None,
SimpleState::B(value) => Some(if value { Self::BisTrue } else { Self::BisFalse }),
})
}
}
#[test]
fn computed_state_with_a_single_source_is_correctly_derived() {
let mut world = World::new();
MessageRegistry::register_message::<StateTransitionEvent<SimpleState>>(&mut world);
MessageRegistry::register_message::<StateTransitionEvent<TestComputedState>>(&mut world);
world.init_resource::<State<SimpleState>>();
let mut schedules = Schedules::new();
let mut apply_changes = Schedule::new(StateTransition);
TestComputedState::register_computed_state_systems(&mut apply_changes);
SimpleState::register_state(&mut apply_changes);
schedules.insert(apply_changes);
world.insert_resource(schedules);
setup_state_transitions_in_world(&mut world);
world.run_schedule(StateTransition);
assert_eq!(world.resource::<State<SimpleState>>().0, SimpleState::A);
assert!(!world.contains_resource::<State<TestComputedState>>());
world.insert_resource(NextState::Pending(SimpleState::B(true)));
world.run_schedule(StateTransition);
assert_eq!(
world.resource::<State<SimpleState>>().0,
SimpleState::B(true)
);
assert_eq!(
world.resource::<State<TestComputedState>>().0,
TestComputedState::BisTrue
);
world.insert_resource(NextState::Pending(SimpleState::B(false)));
world.run_schedule(StateTransition);
assert_eq!(
world.resource::<State<SimpleState>>().0,
SimpleState::B(false)
);
assert_eq!(
world.resource::<State<TestComputedState>>().0,
TestComputedState::BisFalse
);
world.insert_resource(NextState::Pending(SimpleState::A));
world.run_schedule(StateTransition);
assert_eq!(world.resource::<State<SimpleState>>().0, SimpleState::A);
assert!(!world.contains_resource::<State<TestComputedState>>());
}
#[derive(SubStates, PartialEq, Eq, Debug, Default, Hash, Clone)]
#[source(SimpleState = SimpleState::B(true))]
enum SubState {
#[default]
One,
Two,
}
#[test]
fn sub_state_exists_only_when_allowed_but_can_be_modified_freely() {
let mut world = World::new();
MessageRegistry::register_message::<StateTransitionEvent<SimpleState>>(&mut world);
MessageRegistry::register_message::<StateTransitionEvent<SubState>>(&mut world);
world.init_resource::<State<SimpleState>>();
let mut schedules = Schedules::new();
let mut apply_changes = Schedule::new(StateTransition);
SubState::register_sub_state_systems(&mut apply_changes);
SimpleState::register_state(&mut apply_changes);
schedules.insert(apply_changes);
world.insert_resource(schedules);
setup_state_transitions_in_world(&mut world);
world.run_schedule(StateTransition);
assert_eq!(world.resource::<State<SimpleState>>().0, SimpleState::A);
assert!(!world.contains_resource::<State<SubState>>());
world.insert_resource(NextState::Pending(SubState::Two));
world.run_schedule(StateTransition);
assert_eq!(world.resource::<State<SimpleState>>().0, SimpleState::A);
assert!(!world.contains_resource::<State<SubState>>());
world.insert_resource(NextState::Pending(SimpleState::B(true)));
world.run_schedule(StateTransition);
assert_eq!(
world.resource::<State<SimpleState>>().0,
SimpleState::B(true)
);
assert_eq!(world.resource::<State<SubState>>().0, SubState::One);
world.insert_resource(NextState::Pending(SubState::Two));
world.run_schedule(StateTransition);
assert_eq!(
world.resource::<State<SimpleState>>().0,
SimpleState::B(true)
);
assert_eq!(world.resource::<State<SubState>>().0, SubState::Two);
world.insert_resource(NextState::Pending(SimpleState::B(false)));
world.run_schedule(StateTransition);
assert_eq!(
world.resource::<State<SimpleState>>().0,
SimpleState::B(false)
);
assert!(!world.contains_resource::<State<SubState>>());
}
#[derive(SubStates, PartialEq, Eq, Debug, Default, Hash, Clone)]
#[source(TestComputedState = TestComputedState::BisTrue)]
enum SubStateOfComputed {
#[default]
One,
Two,
}
#[test]
fn substate_of_computed_states_works_appropriately() {
let mut world = World::new();
MessageRegistry::register_message::<StateTransitionEvent<SimpleState>>(&mut world);
MessageRegistry::register_message::<StateTransitionEvent<TestComputedState>>(&mut world);
MessageRegistry::register_message::<StateTransitionEvent<SubStateOfComputed>>(&mut world);
world.init_resource::<State<SimpleState>>();
let mut schedules = Schedules::new();
let mut apply_changes = Schedule::new(StateTransition);
TestComputedState::register_computed_state_systems(&mut apply_changes);
SubStateOfComputed::register_sub_state_systems(&mut apply_changes);
SimpleState::register_state(&mut apply_changes);
schedules.insert(apply_changes);
world.insert_resource(schedules);
setup_state_transitions_in_world(&mut world);
world.run_schedule(StateTransition);
assert_eq!(world.resource::<State<SimpleState>>().0, SimpleState::A);
assert!(!world.contains_resource::<State<SubStateOfComputed>>());
world.insert_resource(NextState::Pending(SubStateOfComputed::Two));
world.run_schedule(StateTransition);
assert_eq!(world.resource::<State<SimpleState>>().0, SimpleState::A);
assert!(!world.contains_resource::<State<SubStateOfComputed>>());
world.insert_resource(NextState::Pending(SimpleState::B(true)));
world.run_schedule(StateTransition);
assert_eq!(
world.resource::<State<SimpleState>>().0,
SimpleState::B(true)
);
assert_eq!(
world.resource::<State<SubStateOfComputed>>().0,
SubStateOfComputed::One
);
world.insert_resource(NextState::Pending(SubStateOfComputed::Two));
world.run_schedule(StateTransition);
assert_eq!(
world.resource::<State<SimpleState>>().0,
SimpleState::B(true)
);
assert_eq!(
world.resource::<State<SubStateOfComputed>>().0,
SubStateOfComputed::Two
);
world.insert_resource(NextState::Pending(SimpleState::B(false)));
world.run_schedule(StateTransition);
assert_eq!(
world.resource::<State<SimpleState>>().0,
SimpleState::B(false)
);
assert!(!world.contains_resource::<State<SubStateOfComputed>>());
}
#[derive(States, PartialEq, Eq, Debug, Default, Hash, Clone)]
struct OtherState {
a_flexible_value: &'static str,
another_value: u8,
}
#[derive(PartialEq, Eq, Debug, Hash, Clone)]
enum ComplexComputedState {
InAAndStrIsBobOrJane,
InTrueBAndUsizeAbove8,
}
impl ComputedStates for ComplexComputedState {
type SourceStates = (Option<SimpleState>, Option<OtherState>);
fn compute(sources: (Option<SimpleState>, Option<OtherState>)) -> Option<Self> {
match sources {
(Some(simple), Some(complex)) => {
if simple == SimpleState::A
&& (complex.a_flexible_value == "bob" || complex.a_flexible_value == "jane")
{
Some(ComplexComputedState::InAAndStrIsBobOrJane)
} else if simple == SimpleState::B(true) && complex.another_value > 8 {
Some(ComplexComputedState::InTrueBAndUsizeAbove8)
} else {
None
}
}
_ => None,
}
}
}
#[test]
fn complex_computed_state_gets_derived_correctly() {
let mut world = World::new();
MessageRegistry::register_message::<StateTransitionEvent<SimpleState>>(&mut world);
MessageRegistry::register_message::<StateTransitionEvent<OtherState>>(&mut world);
MessageRegistry::register_message::<StateTransitionEvent<ComplexComputedState>>(&mut world);
world.init_resource::<State<SimpleState>>();
world.init_resource::<State<OtherState>>();
let mut schedules = Schedules::new();
let mut apply_changes = Schedule::new(StateTransition);
ComplexComputedState::register_computed_state_systems(&mut apply_changes);
SimpleState::register_state(&mut apply_changes);
OtherState::register_state(&mut apply_changes);
schedules.insert(apply_changes);
world.insert_resource(schedules);
setup_state_transitions_in_world(&mut world);
world.run_schedule(StateTransition);
assert_eq!(world.resource::<State<SimpleState>>().0, SimpleState::A);
assert_eq!(
world.resource::<State<OtherState>>().0,
OtherState::default()
);
assert!(!world.contains_resource::<State<ComplexComputedState>>());
world.insert_resource(NextState::Pending(SimpleState::B(true)));
world.run_schedule(StateTransition);
assert!(!world.contains_resource::<State<ComplexComputedState>>());
world.insert_resource(NextState::Pending(OtherState {
a_flexible_value: "felix",
another_value: 13,
}));
world.run_schedule(StateTransition);
assert_eq!(
world.resource::<State<ComplexComputedState>>().0,
ComplexComputedState::InTrueBAndUsizeAbove8
);
world.insert_resource(NextState::Pending(SimpleState::A));
world.insert_resource(NextState::Pending(OtherState {
a_flexible_value: "jane",
another_value: 13,
}));
world.run_schedule(StateTransition);
assert_eq!(
world.resource::<State<ComplexComputedState>>().0,
ComplexComputedState::InAAndStrIsBobOrJane
);
world.insert_resource(NextState::Pending(SimpleState::B(false)));
world.insert_resource(NextState::Pending(OtherState {
a_flexible_value: "jane",
another_value: 13,
}));
world.run_schedule(StateTransition);
assert!(!world.contains_resource::<State<ComplexComputedState>>());
}
#[derive(Resource, Default)]
struct ComputedStateTransitionCounter {
enter: usize,
exit: usize,
}
#[derive(States, PartialEq, Eq, Debug, Default, Hash, Clone)]
enum SimpleState2 {
#[default]
A1,
B2,
}
#[derive(PartialEq, Eq, Debug, Hash, Clone)]
enum TestNewcomputedState {
A1,
B2,
B1,
}
impl ComputedStates for TestNewcomputedState {
type SourceStates = (Option<SimpleState>, Option<SimpleState2>);
fn compute((s1, s2): (Option<SimpleState>, Option<SimpleState2>)) -> Option<Self> {
match (s1, s2) {
(Some(SimpleState::A), Some(SimpleState2::A1)) => Some(TestNewcomputedState::A1),
(Some(SimpleState::B(true)), Some(SimpleState2::B2)) => {
Some(TestNewcomputedState::B2)
}
(Some(SimpleState::B(true)), _) => Some(TestNewcomputedState::B1),
_ => None,
}
}
}
#[test]
fn computed_state_transitions_are_produced_correctly() {
let mut world = World::new();
MessageRegistry::register_message::<StateTransitionEvent<SimpleState>>(&mut world);
MessageRegistry::register_message::<StateTransitionEvent<SimpleState2>>(&mut world);
MessageRegistry::register_message::<StateTransitionEvent<TestNewcomputedState>>(&mut world);
world.init_resource::<State<SimpleState>>();
world.init_resource::<State<SimpleState2>>();
world.init_resource::<Schedules>();
setup_state_transitions_in_world(&mut world);
let mut schedules = world
.get_resource_mut::<Schedules>()
.expect("Schedules don't exist in world");
let apply_changes = schedules
.get_mut(StateTransition)
.expect("State Transition Schedule Doesn't Exist");
TestNewcomputedState::register_computed_state_systems(apply_changes);
SimpleState::register_state(apply_changes);
SimpleState2::register_state(apply_changes);
schedules.insert({
let mut schedule = Schedule::new(OnEnter(TestNewcomputedState::A1));
schedule.add_systems(|mut count: ResMut<ComputedStateTransitionCounter>| {
count.enter += 1;
});
schedule
});
schedules.insert({
let mut schedule = Schedule::new(OnExit(TestNewcomputedState::A1));
schedule.add_systems(|mut count: ResMut<ComputedStateTransitionCounter>| {
count.exit += 1;
});
schedule
});
schedules.insert({
let mut schedule = Schedule::new(OnEnter(TestNewcomputedState::B1));
schedule.add_systems(|mut count: ResMut<ComputedStateTransitionCounter>| {
count.enter += 1;
});
schedule
});
schedules.insert({
let mut schedule = Schedule::new(OnExit(TestNewcomputedState::B1));
schedule.add_systems(|mut count: ResMut<ComputedStateTransitionCounter>| {
count.exit += 1;
});
schedule
});
schedules.insert({
let mut schedule = Schedule::new(OnEnter(TestNewcomputedState::B2));
schedule.add_systems(|mut count: ResMut<ComputedStateTransitionCounter>| {
count.enter += 1;
});
schedule
});
schedules.insert({
let mut schedule = Schedule::new(OnExit(TestNewcomputedState::B2));
schedule.add_systems(|mut count: ResMut<ComputedStateTransitionCounter>| {
count.exit += 1;
});
schedule
});
world.init_resource::<ComputedStateTransitionCounter>();
setup_state_transitions_in_world(&mut world);
assert_eq!(world.resource::<State<SimpleState>>().0, SimpleState::A);
assert_eq!(world.resource::<State<SimpleState2>>().0, SimpleState2::A1);
assert!(!world.contains_resource::<State<TestNewcomputedState>>());
world.insert_resource(NextState::Pending(SimpleState::B(true)));
world.insert_resource(NextState::Pending(SimpleState2::B2));
world.run_schedule(StateTransition);
assert_eq!(
world.resource::<State<TestNewcomputedState>>().0,
TestNewcomputedState::B2
);
assert_eq!(world.resource::<ComputedStateTransitionCounter>().enter, 1);
assert_eq!(world.resource::<ComputedStateTransitionCounter>().exit, 0);
world.insert_resource(NextState::Pending(SimpleState2::A1));
world.insert_resource(NextState::Pending(SimpleState::A));
world.run_schedule(StateTransition);
assert_eq!(
world.resource::<State<TestNewcomputedState>>().0,
TestNewcomputedState::A1
);
assert_eq!(
world.resource::<ComputedStateTransitionCounter>().enter,
2,
"Should Only Enter Twice"
);
assert_eq!(
world.resource::<ComputedStateTransitionCounter>().exit,
1,
"Should Only Exit Once"
);
world.insert_resource(NextState::Pending(SimpleState::B(true)));
world.insert_resource(NextState::Pending(SimpleState2::B2));
world.run_schedule(StateTransition);
assert_eq!(
world.resource::<State<TestNewcomputedState>>().0,
TestNewcomputedState::B2
);
assert_eq!(
world.resource::<ComputedStateTransitionCounter>().enter,
3,
"Should Only Enter Three Times"
);
assert_eq!(
world.resource::<ComputedStateTransitionCounter>().exit,
2,
"Should Only Exit Twice"
);
world.insert_resource(NextState::Pending(SimpleState::A));
world.run_schedule(StateTransition);
assert!(!world.contains_resource::<State<TestNewcomputedState>>());
assert_eq!(
world.resource::<ComputedStateTransitionCounter>().enter,
3,
"Should Only Enter Three Times"
);
assert_eq!(
world.resource::<ComputedStateTransitionCounter>().exit,
3,
"Should Only Exit Twice"
);
}
#[derive(Resource, Default, PartialEq, Debug)]
struct TransitionCounter {
exit: u8,
transition: u8,
enter: u8,
}
#[test]
fn same_state_transition_should_emit_event_and_run_schedules() {
let mut world = World::new();
setup_state_transitions_in_world(&mut world);
MessageRegistry::register_message::<StateTransitionEvent<SimpleState>>(&mut world);
world.init_resource::<State<SimpleState>>();
let mut schedules = world.resource_mut::<Schedules>();
let apply_changes = schedules.get_mut(StateTransition).unwrap();
SimpleState::register_state(apply_changes);
let mut on_exit = Schedule::new(OnExit(SimpleState::A));
on_exit.add_systems(|mut c: ResMut<TransitionCounter>| c.exit += 1);
schedules.insert(on_exit);
let mut on_transition = Schedule::new(OnTransition {
exited: SimpleState::A,
entered: SimpleState::A,
});
on_transition.add_systems(|mut c: ResMut<TransitionCounter>| c.transition += 1);
schedules.insert(on_transition);
let mut on_enter = Schedule::new(OnEnter(SimpleState::A));
on_enter.add_systems(|mut c: ResMut<TransitionCounter>| c.enter += 1);
schedules.insert(on_enter);
world.insert_resource(TransitionCounter::default());
world.run_schedule(StateTransition);
assert_eq!(world.resource::<State<SimpleState>>().0, SimpleState::A);
assert!(world
.resource::<Messages<StateTransitionEvent<SimpleState>>>()
.is_empty());
world.insert_resource(TransitionCounter::default());
world.insert_resource(NextState::Pending(SimpleState::A));
world.run_schedule(StateTransition);
assert_eq!(world.resource::<State<SimpleState>>().0, SimpleState::A);
assert_eq!(
*world.resource::<TransitionCounter>(),
TransitionCounter {
exit: 1,
transition: 1,
enter: 1
}
);
assert_eq!(
world
.resource::<Messages<StateTransitionEvent<SimpleState>>>()
.len(),
1
);
}
#[test]
fn same_state_transition_should_emit_event_and_not_run_schedules_if_same_state_transitions_are_disallowed(
) {
let mut world = World::new();
setup_state_transitions_in_world(&mut world);
MessageRegistry::register_message::<StateTransitionEvent<SimpleState>>(&mut world);
world.init_resource::<State<SimpleState>>();
let mut schedules = world.resource_mut::<Schedules>();
let apply_changes = schedules.get_mut(StateTransition).unwrap();
SimpleState::register_state(apply_changes);
let mut on_exit = Schedule::new(OnExit(SimpleState::A));
on_exit.add_systems(|mut c: ResMut<TransitionCounter>| c.exit += 1);
schedules.insert(on_exit);
let mut on_transition = Schedule::new(OnTransition {
exited: SimpleState::A,
entered: SimpleState::A,
});
on_transition.add_systems(|mut c: ResMut<TransitionCounter>| c.transition += 1);
schedules.insert(on_transition);
let mut on_enter = Schedule::new(OnEnter(SimpleState::A));
on_enter.add_systems(|mut c: ResMut<TransitionCounter>| c.enter += 1);
schedules.insert(on_enter);
world.insert_resource(TransitionCounter::default());
world.run_schedule(StateTransition);
assert_eq!(world.resource::<State<SimpleState>>().0, SimpleState::A);
assert!(world
.resource::<Messages<StateTransitionEvent<SimpleState>>>()
.is_empty());
world.insert_resource(TransitionCounter::default());
world.insert_resource(NextState::PendingIfNeq(SimpleState::A));
world.run_schedule(StateTransition);
assert_eq!(world.resource::<State<SimpleState>>().0, SimpleState::A);
assert_eq!(
*world.resource::<TransitionCounter>(),
TransitionCounter {
exit: 0,
transition: 1, // Same state transitions are allowed
enter: 0
}
);
assert_eq!(
world
.resource::<Messages<StateTransitionEvent<SimpleState>>>()
.len(),
1
);
}
#[test]
fn same_state_transition_should_propagate_to_sub_state() {
let mut world = World::new();
MessageRegistry::register_message::<StateTransitionEvent<SimpleState>>(&mut world);
MessageRegistry::register_message::<StateTransitionEvent<SubState>>(&mut world);
world.insert_resource(State(SimpleState::B(true)));
world.init_resource::<State<SubState>>();
let mut schedules = Schedules::new();
let mut apply_changes = Schedule::new(StateTransition);
SimpleState::register_state(&mut apply_changes);
SubState::register_sub_state_systems(&mut apply_changes);
schedules.insert(apply_changes);
world.insert_resource(schedules);
setup_state_transitions_in_world(&mut world);
world.insert_resource(NextState::Pending(SimpleState::B(true)));
world.run_schedule(StateTransition);
assert_eq!(
world
.resource::<Messages<StateTransitionEvent<SimpleState>>>()
.len(),
1
);
assert_eq!(
world
.resource::<Messages<StateTransitionEvent<SubState>>>()
.len(),
1
);
}
#[test]
fn same_state_transition_should_propagate_to_computed_state() {
let mut world = World::new();
MessageRegistry::register_message::<StateTransitionEvent<SimpleState>>(&mut world);
MessageRegistry::register_message::<StateTransitionEvent<TestComputedState>>(&mut world);
world.insert_resource(State(SimpleState::B(true)));
world.insert_resource(State(TestComputedState::BisTrue));
let mut schedules = Schedules::new();
let mut apply_changes = Schedule::new(StateTransition);
SimpleState::register_state(&mut apply_changes);
TestComputedState::register_computed_state_systems(&mut apply_changes);
schedules.insert(apply_changes);
world.insert_resource(schedules);
setup_state_transitions_in_world(&mut world);
world.insert_resource(NextState::Pending(SimpleState::B(true)));
world.run_schedule(StateTransition);
assert_eq!(
world
.resource::<Messages<StateTransitionEvent<SimpleState>>>()
.len(),
1
);
assert_eq!(
world
.resource::<Messages<StateTransitionEvent<TestComputedState>>>()
.len(),
1
);
}
#[derive(Resource, Default, Debug)]
struct TransitionTracker(Vec<&'static str>);
#[derive(PartialEq, Eq, Debug, Hash, Clone)]
enum TransitionTestingComputedState {
IsA,
IsBAndEven,
IsBAndOdd,
}
impl ComputedStates for TransitionTestingComputedState {
type SourceStates = (Option<SimpleState>, Option<SubState>);
fn compute(sources: (Option<SimpleState>, Option<SubState>)) -> Option<Self> {
match sources {
(Some(simple), sub) => {
if simple == SimpleState::A {
Some(Self::IsA)
} else if sub == Some(SubState::One) {
Some(Self::IsBAndOdd)
} else if sub == Some(SubState::Two) {
Some(Self::IsBAndEven)
} else {
None
}
}
_ => None,
}
}
}
#[derive(PartialEq, Eq, Debug, Hash, Clone)]
enum MultiSourceComputedState {
FromSimpleBTrue,
FromSimple2B2,
FromBoth,
}
impl ComputedStates for MultiSourceComputedState {
type SourceStates = (SimpleState, SimpleState2);
fn compute((simple_state, simple_state2): (SimpleState, SimpleState2)) -> Option<Self> {
match (simple_state, simple_state2) {
// If both are in their special states, prioritize the "both" variant.
(SimpleState::B(true), SimpleState2::B2) => Some(Self::FromBoth),
// If only SimpleState is B(true).
(SimpleState::B(true), _) => Some(Self::FromSimpleBTrue),
// If only SimpleState2 is B2.
(_, SimpleState2::B2) => Some(Self::FromSimple2B2),
// Otherwise, no computed state.
_ => None,
}
}
}
/// This test ensures that [`ComputedStates`] with multiple source states
/// react when any source changes.
#[test]
fn computed_state_with_multiple_sources_should_react_to_any_source_change() {
let mut world = World::new();
MessageRegistry::register_message::<StateTransitionEvent<SimpleState>>(&mut world);
MessageRegistry::register_message::<StateTransitionEvent<SimpleState2>>(&mut world);
MessageRegistry::register_message::<StateTransitionEvent<MultiSourceComputedState>>(
&mut world,
);
world.init_resource::<State<SimpleState>>();
world.init_resource::<State<SimpleState2>>();
let mut schedules = Schedules::new();
let mut apply_changes = Schedule::new(StateTransition);
SimpleState::register_state(&mut apply_changes);
SimpleState2::register_state(&mut apply_changes);
MultiSourceComputedState::register_computed_state_systems(&mut apply_changes);
schedules.insert(apply_changes);
world.insert_resource(schedules);
setup_state_transitions_in_world(&mut world);
// Initial state: SimpleState::A, SimpleState2::A1 and
// MultiSourceComputedState should not exist yet.
world.run_schedule(StateTransition);
assert_eq!(world.resource::<State<SimpleState>>().0, SimpleState::A);
assert_eq!(world.resource::<State<SimpleState2>>().0, SimpleState2::A1);
assert!(!world.contains_resource::<State<MultiSourceComputedState>>());
// Change only SimpleState to B(true) - this should trigger
// MultiSourceComputedState.
world.insert_resource(NextState::Pending(SimpleState::B(true)));
world.run_schedule(StateTransition);
assert_eq!(
world.resource::<State<SimpleState>>().0,
SimpleState::B(true)
);
assert_eq!(world.resource::<State<SimpleState2>>().0, SimpleState2::A1);
// The computed state should exist because SimpleState changed to
// B(true).
assert!(world.contains_resource::<State<MultiSourceComputedState>>());
assert_eq!(
world.resource::<State<MultiSourceComputedState>>().0,
MultiSourceComputedState::FromSimpleBTrue
);
// Reset SimpleState to A - computed state should be removed.
world.insert_resource(NextState::Pending(SimpleState::A));
world.run_schedule(StateTransition);
assert!(!world.contains_resource::<State<MultiSourceComputedState>>());
// Now change only SimpleState2 to B2 - this should also trigger
// MultiSourceComputedState.
world.insert_resource(NextState::Pending(SimpleState2::B2));
world.run_schedule(StateTransition);
assert_eq!(world.resource::<State<SimpleState>>().0, SimpleState::A);
assert_eq!(world.resource::<State<SimpleState2>>().0, SimpleState2::B2);
// The computed state should exist because SimpleState2 changed to B2.
assert!(world.contains_resource::<State<MultiSourceComputedState>>());
assert_eq!(
world.resource::<State<MultiSourceComputedState>>().0,
MultiSourceComputedState::FromSimple2B2
);
// Test that changes to both states work.
world.insert_resource(NextState::Pending(SimpleState::B(true)));
world.insert_resource(NextState::Pending(SimpleState2::A1));
world.run_schedule(StateTransition);
assert_eq!(
world.resource::<State<MultiSourceComputedState>>().0,
MultiSourceComputedState::FromSimpleBTrue
);
}
// Test SubState that depends on multiple source states.
#[derive(PartialEq, Eq, Debug, Default, Hash, Clone)]
enum MultiSourceSubState {
#[default]
Active,
}
impl SubStates for MultiSourceSubState {
type SourceStates = (SimpleState, SimpleState2);
fn should_exist(
(simple_state, simple_state2): (SimpleState, SimpleState2),
) -> Option<Self> {
// SubState should exist when:
// - SimpleState is B(true), OR
// - SimpleState2 is B2
match (simple_state, simple_state2) {
(SimpleState::B(true), _) | (_, SimpleState2::B2) => Some(Self::Active),
_ => None,
}
}
}
impl States for MultiSourceSubState {
const DEPENDENCY_DEPTH: usize = <Self as SubStates>::SourceStates::SET_DEPENDENCY_DEPTH + 1;
}
impl FreelyMutableState for MultiSourceSubState {}
/// This test ensures that [`SubStates`] with multiple source states react
/// when any source changes.
#[test]
fn sub_state_with_multiple_sources_should_react_to_any_source_change() {
let mut world = World::new();
MessageRegistry::register_message::<StateTransitionEvent<SimpleState>>(&mut world);
MessageRegistry::register_message::<StateTransitionEvent<SimpleState2>>(&mut world);
MessageRegistry::register_message::<StateTransitionEvent<MultiSourceSubState>>(&mut world);
world.init_resource::<State<SimpleState>>();
world.init_resource::<State<SimpleState2>>();
let mut schedules = Schedules::new();
let mut apply_changes = Schedule::new(StateTransition);
SimpleState::register_state(&mut apply_changes);
SimpleState2::register_state(&mut apply_changes);
MultiSourceSubState::register_sub_state_systems(&mut apply_changes);
schedules.insert(apply_changes);
world.insert_resource(schedules);
setup_state_transitions_in_world(&mut world);
// Initial state: SimpleState::A, SimpleState2::A1 and
// MultiSourceSubState should not exist yet.
world.run_schedule(StateTransition);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_state/src/state/states.rs | crates/bevy_state/src/state/states.rs | use core::fmt::Debug;
use core::hash::Hash;
/// Types that can define world-wide states in a finite-state machine.
///
/// The [`Default`] trait defines the starting state.
/// Multiple states can be defined for the same world,
/// allowing you to classify the state of the world across orthogonal dimensions.
/// You can access the current state of type `T` with the [`State<T>`](crate::state::State) resource,
/// and the queued state with the [`NextState<T>`](crate::state::NextState) resource.
///
/// State transitions typically occur in the [`OnEnter<T::Variant>`](crate::state::OnEnter) and [`OnExit<T::Variant>`](crate::state::OnExit) schedules,
/// which can be run by triggering the [`StateTransition`](crate::state::StateTransition) schedule.
///
/// Types used as [`ComputedStates`](crate::state::ComputedStates) do not need to and should not derive [`States`].
/// [`ComputedStates`](crate::state::ComputedStates) should not be manually mutated: functionality provided
/// by the [`States`] derive and the associated [`FreelyMutableState`](crate::state::FreelyMutableState) trait.
///
/// # Example
///
/// ```
/// use bevy_state::prelude::*;
/// use bevy_ecs::prelude::IntoScheduleConfigs;
/// use bevy_ecs::system::{ResMut, ScheduleSystem};
///
///
/// #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default, States)]
/// enum GameState {
/// #[default]
/// MainMenu,
/// SettingsMenu,
/// InGame,
/// }
///
/// fn handle_escape_pressed(mut next_state: ResMut<NextState<GameState>>) {
/// # let escape_pressed = true;
/// if escape_pressed {
/// next_state.set(GameState::SettingsMenu);
/// }
/// }
///
/// fn open_settings_menu() {
/// // Show the settings menu...
/// }
///
/// # struct AppMock;
/// # impl AppMock {
/// # fn init_state<S>(&mut self) {}
/// # fn add_systems<S, M>(&mut self, schedule: S, systems: impl IntoScheduleConfigs<ScheduleSystem, M>) {}
/// # }
/// # struct Update;
/// # let mut app = AppMock;
///
/// app.init_state::<GameState>();
/// app.add_systems(Update, handle_escape_pressed.run_if(in_state(GameState::MainMenu)));
/// app.add_systems(OnEnter(GameState::SettingsMenu), open_settings_menu);
/// ```
#[diagnostic::on_unimplemented(
message = "`{Self}` can not be used as a state",
label = "invalid state",
note = "consider annotating `{Self}` with `#[derive(States)]`"
)]
pub trait States: 'static + Send + Sync + Clone + PartialEq + Eq + Hash + Debug {
/// How many other states this state depends on.
/// Used to help order transitions and de-duplicate [`ComputedStates`](crate::state::ComputedStates), as well as prevent cyclical
/// `ComputedState` dependencies.
const DEPENDENCY_DEPTH: usize = 1;
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_state/src/state/freely_mutable_state.rs | crates/bevy_state/src/state/freely_mutable_state.rs | use bevy_ecs::{
message::MessageWriter,
prelude::Schedule,
schedule::IntoScheduleConfigs,
system::{Commands, IntoSystem, ResMut},
};
use super::{states::States, take_next_state, transitions::*, NextState, PreviousState, State};
/// This trait allows a state to be mutated directly using the [`NextState<S>`](crate::state::NextState) resource.
///
/// While ordinary states are freely mutable (and implement this trait as part of their derive macro),
/// computed states are not: instead, they can *only* change when the states that drive them do.
#[diagnostic::on_unimplemented(note = "consider annotating `{Self}` with `#[derive(States)]`")]
pub trait FreelyMutableState: States {
/// This function registers all the necessary systems to apply state changes and run transition schedules
fn register_state(schedule: &mut Schedule) {
schedule.configure_sets((
ApplyStateTransition::<Self>::default()
.in_set(StateTransitionSystems::DependentTransitions),
ExitSchedules::<Self>::default().in_set(StateTransitionSystems::ExitSchedules),
TransitionSchedules::<Self>::default()
.in_set(StateTransitionSystems::TransitionSchedules),
EnterSchedules::<Self>::default().in_set(StateTransitionSystems::EnterSchedules),
));
schedule
.add_systems(
apply_state_transition::<Self>.in_set(ApplyStateTransition::<Self>::default()),
)
.add_systems(
last_transition::<Self>
.pipe(run_exit::<Self>)
.in_set(ExitSchedules::<Self>::default()),
)
.add_systems(
last_transition::<Self>
.pipe(run_transition::<Self>)
.in_set(TransitionSchedules::<Self>::default()),
)
.add_systems(
last_transition::<Self>
.pipe(run_enter::<Self>)
.in_set(EnterSchedules::<Self>::default()),
);
}
}
fn apply_state_transition<S: FreelyMutableState>(
event: MessageWriter<StateTransitionEvent<S>>,
commands: Commands,
current_state: Option<ResMut<State<S>>>,
previous_state: Option<ResMut<PreviousState<S>>>,
next_state: Option<ResMut<NextState<S>>>,
) {
let Some((next_state, allow_same_state_transitions)) = take_next_state(next_state) else {
return;
};
let Some(current_state) = current_state else {
return;
};
internal_apply_state_transition(
event,
commands,
Some(current_state),
previous_state,
Some(next_state),
allow_same_state_transitions,
);
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_android/src/lib.rs | crates/bevy_android/src/lib.rs | //! Provides Android functionality for Bevy Engine.
#[cfg(target_os = "android")]
pub use android_activity;
/// [`AndroidApp`] provides an interface to query the application state as well as monitor events
/// (for example lifecycle and input events).
#[cfg(target_os = "android")]
pub static ANDROID_APP: std::sync::OnceLock<android_activity::AndroidApp> =
std::sync::OnceLock::new();
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_dylib/src/lib.rs | crates/bevy_dylib/src/lib.rs | #![cfg_attr(docsrs, feature(doc_cfg))]
#![doc(
html_logo_url = "https://bevy.org/assets/icon.png",
html_favicon_url = "https://bevy.org/assets/icon.png"
)]
//! Forces dynamic linking of Bevy.
//!
//! Dynamic linking causes Bevy to be built and linked as a dynamic library. This will make
//! incremental builds compile much faster.
//!
//! # Warning
//!
//! Do not enable this feature for release builds because this would require you to ship
//! `libstd.so` and `libbevy_dylib.so` with your game.
//!
//! # Enabling dynamic linking
//!
//! ## The recommended way
//!
//! The easiest way to enable dynamic linking is to use the `--features bevy/dynamic_linking` flag when
//! using the `cargo run` command:
//!
//! `cargo run --features bevy/dynamic_linking`
//!
//! ## The unrecommended way
//!
//! It is also possible to enable the `dynamic_linking` feature inside of the `Cargo.toml` file. This is
//! unrecommended because it requires you to remove this feature every time you want to create a
//! release build to avoid having to ship additional files with your game.
//!
//! To enable dynamic linking inside of the `Cargo.toml` file add the `dynamic_linking` feature to the
//! bevy dependency:
//!
//! `features = ["dynamic_linking"]`
//!
//! ## The manual way
//!
//! Manually enabling dynamic linking is achieved by adding `bevy_dylib` as a dependency and
//! adding the following code to the `main.rs` file:
//!
//! ```
//! #[allow(unused_imports)]
//! use bevy_dylib;
//! ```
//!
//! It is recommended to disable the `bevy_dylib` dependency in release mode by adding the
//! following code to the `use` statement to avoid having to ship additional files with your game:
//!
//! ```
//! #[allow(unused_imports)]
//! #[cfg(debug_assertions)] // new
//! use bevy_dylib;
//! ```
// Force linking of the main bevy crate
#[expect(
unused_imports,
clippy::single_component_path_imports,
reason = "This links the main bevy crate when using dynamic linking, and as such cannot be removed or changed without affecting dynamic linking."
)]
use bevy_internal;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_diagnostic/src/entity_count_diagnostics_plugin.rs | crates/bevy_diagnostic/src/entity_count_diagnostics_plugin.rs | use bevy_app::prelude::*;
use bevy_ecs::entity::Entities;
use crate::{
Diagnostic, DiagnosticPath, Diagnostics, RegisterDiagnostic, DEFAULT_MAX_HISTORY_LENGTH,
};
/// Adds "entity count" diagnostic to an App.
///
/// # See also
///
/// [`LogDiagnosticsPlugin`](crate::LogDiagnosticsPlugin) to output diagnostics to the console.
pub struct EntityCountDiagnosticsPlugin {
/// The total number of values to keep.
pub max_history_length: usize,
}
impl Default for EntityCountDiagnosticsPlugin {
fn default() -> Self {
Self::new(DEFAULT_MAX_HISTORY_LENGTH)
}
}
impl EntityCountDiagnosticsPlugin {
/// Creates a new `EntityCountDiagnosticsPlugin` with the specified `max_history_length`.
pub fn new(max_history_length: usize) -> Self {
Self { max_history_length }
}
}
impl Plugin for EntityCountDiagnosticsPlugin {
fn build(&self, app: &mut App) {
app.register_diagnostic(
Diagnostic::new(Self::ENTITY_COUNT).with_max_history_length(self.max_history_length),
)
.add_systems(Update, Self::diagnostic_system);
}
}
impl EntityCountDiagnosticsPlugin {
/// Number of currently allocated entities.
pub const ENTITY_COUNT: DiagnosticPath = DiagnosticPath::const_new("entity_count");
/// Updates entity count measurement.
pub fn diagnostic_system(mut diagnostics: Diagnostics, entities: &Entities) {
diagnostics.add_measurement(&Self::ENTITY_COUNT, || entities.count_spawned() as f64);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_diagnostic/src/frame_count_diagnostics_plugin.rs | crates/bevy_diagnostic/src/frame_count_diagnostics_plugin.rs | use bevy_app::prelude::*;
use bevy_ecs::prelude::*;
#[cfg(feature = "serialize")]
use serde::{
de::{Error, Visitor},
Deserialize, Deserializer, Serialize, Serializer,
};
/// Maintains a count of frames rendered since the start of the application.
///
/// [`FrameCount`] is incremented during [`Last`], providing predictable
/// behavior: it will be 0 during the first update, 1 during the next, and so forth.
///
/// # Overflows
///
/// [`FrameCount`] will wrap to 0 after exceeding [`u32::MAX`]. Within reasonable
/// assumptions, one may exploit wrapping arithmetic to determine the number of frames
/// that have elapsed between two observations – see [`u32::wrapping_sub()`].
#[derive(Debug, Default, Resource, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct FrameCount(pub u32);
/// Adds frame counting functionality to Apps.
#[derive(Default)]
pub struct FrameCountPlugin;
impl Plugin for FrameCountPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<FrameCount>();
app.add_systems(Last, update_frame_count);
}
}
/// A system used to increment [`FrameCount`] with wrapping addition.
///
/// See [`FrameCount`] for more details.
pub fn update_frame_count(mut frame_count: ResMut<FrameCount>) {
frame_count.0 = frame_count.0.wrapping_add(1);
}
#[cfg(feature = "serialize")]
// Manually implementing serialize/deserialize allows us to use a more compact representation as simple integers
impl Serialize for FrameCount {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_u32(self.0)
}
}
#[cfg(feature = "serialize")]
impl<'de> Deserialize<'de> for FrameCount {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
deserializer.deserialize_u32(FrameVisitor)
}
}
#[cfg(feature = "serialize")]
struct FrameVisitor;
#[cfg(feature = "serialize")]
impl<'de> Visitor<'de> for FrameVisitor {
type Value = FrameCount;
fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
formatter.write_str(core::any::type_name::<FrameCount>())
}
fn visit_u32<E>(self, v: u32) -> Result<Self::Value, E>
where
E: Error,
{
Ok(FrameCount(v))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn frame_counter_update() {
let mut app = App::new();
app.add_plugins(FrameCountPlugin);
app.update();
let frame_count = app.world().resource::<FrameCount>();
assert_eq!(1, frame_count.0);
}
}
#[cfg(all(test, feature = "serialize"))]
mod serde_tests {
use super::*;
use serde_test::{assert_tokens, Token};
#[test]
fn test_serde_frame_count() {
let frame_count = FrameCount(100);
assert_tokens(&frame_count, &[Token::U32(100)]);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_diagnostic/src/lib.rs | crates/bevy_diagnostic/src/lib.rs | #![cfg_attr(docsrs, feature(doc_cfg))]
#![forbid(unsafe_code)]
#![doc(
html_logo_url = "https://bevy.org/assets/icon.png",
html_favicon_url = "https://bevy.org/assets/icon.png"
)]
#![no_std]
//! This crate provides a straightforward solution for integrating diagnostics in the [Bevy game engine](https://bevy.org/).
//! It allows users to easily add diagnostic functionality to their Bevy applications, enhancing
//! their ability to monitor and optimize their game's.
#[cfg(feature = "std")]
extern crate std;
extern crate alloc;
mod diagnostic;
mod entity_count_diagnostics_plugin;
mod frame_count_diagnostics_plugin;
mod frame_time_diagnostics_plugin;
mod log_diagnostics_plugin;
#[cfg(feature = "sysinfo_plugin")]
mod system_information_diagnostics_plugin;
pub use diagnostic::*;
pub use entity_count_diagnostics_plugin::EntityCountDiagnosticsPlugin;
pub use frame_count_diagnostics_plugin::{update_frame_count, FrameCount, FrameCountPlugin};
pub use frame_time_diagnostics_plugin::FrameTimeDiagnosticsPlugin;
pub use log_diagnostics_plugin::{LogDiagnosticsPlugin, LogDiagnosticsState};
#[cfg(feature = "sysinfo_plugin")]
pub use system_information_diagnostics_plugin::{SystemInfo, SystemInformationDiagnosticsPlugin};
use bevy_app::prelude::*;
/// Adds core diagnostics resources to an App.
#[derive(Default)]
pub struct DiagnosticsPlugin;
impl Plugin for DiagnosticsPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<DiagnosticsStore>();
#[cfg(feature = "sysinfo_plugin")]
app.init_resource::<SystemInfo>();
}
}
/// Default max history length for new diagnostics.
pub const DEFAULT_MAX_HISTORY_LENGTH: usize = 120;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_diagnostic/src/frame_time_diagnostics_plugin.rs | crates/bevy_diagnostic/src/frame_time_diagnostics_plugin.rs | use crate::{
Diagnostic, DiagnosticPath, Diagnostics, FrameCount, RegisterDiagnostic,
DEFAULT_MAX_HISTORY_LENGTH,
};
use bevy_app::prelude::*;
use bevy_ecs::prelude::*;
use bevy_time::{Real, Time};
/// Adds "frame time" diagnostic to an App, specifically "frame time", "fps" and "frame count"
///
/// # See also
///
/// [`LogDiagnosticsPlugin`](crate::LogDiagnosticsPlugin) to output diagnostics to the console.
pub struct FrameTimeDiagnosticsPlugin {
/// The total number of values to keep for averaging.
pub max_history_length: usize,
/// The smoothing factor for the exponential moving average. Usually `2.0 / (history_length + 1.0)`.
pub smoothing_factor: f64,
}
impl Default for FrameTimeDiagnosticsPlugin {
fn default() -> Self {
Self::new(DEFAULT_MAX_HISTORY_LENGTH)
}
}
impl FrameTimeDiagnosticsPlugin {
/// Creates a new `FrameTimeDiagnosticsPlugin` with the specified `max_history_length` and a
/// reasonable `smoothing_factor`.
pub fn new(max_history_length: usize) -> Self {
Self {
max_history_length,
smoothing_factor: 2.0 / (max_history_length as f64 + 1.0),
}
}
}
impl Plugin for FrameTimeDiagnosticsPlugin {
fn build(&self, app: &mut App) {
app.register_diagnostic(
Diagnostic::new(Self::FRAME_TIME)
.with_suffix("ms")
.with_max_history_length(self.max_history_length)
.with_smoothing_factor(self.smoothing_factor),
)
.register_diagnostic(
Diagnostic::new(Self::FPS)
.with_max_history_length(self.max_history_length)
.with_smoothing_factor(self.smoothing_factor),
)
// An average frame count would be nonsensical, so we set the max history length
// to zero and disable smoothing.
.register_diagnostic(
Diagnostic::new(Self::FRAME_COUNT)
.with_smoothing_factor(0.0)
.with_max_history_length(0),
)
.add_systems(Update, Self::diagnostic_system);
}
}
impl FrameTimeDiagnosticsPlugin {
/// Frames per second.
pub const FPS: DiagnosticPath = DiagnosticPath::const_new("fps");
/// Total frames since application start.
pub const FRAME_COUNT: DiagnosticPath = DiagnosticPath::const_new("frame_count");
/// Frame time in ms.
pub const FRAME_TIME: DiagnosticPath = DiagnosticPath::const_new("frame_time");
/// Updates frame count, frame time and fps measurements.
pub fn diagnostic_system(
mut diagnostics: Diagnostics,
time: Res<Time<Real>>,
frame_count: Res<FrameCount>,
) {
diagnostics.add_measurement(&Self::FRAME_COUNT, || frame_count.0 as f64);
let delta_seconds = time.delta_secs_f64();
if delta_seconds == 0.0 {
return;
}
diagnostics.add_measurement(&Self::FRAME_TIME, || delta_seconds * 1000.0);
diagnostics.add_measurement(&Self::FPS, || 1.0 / delta_seconds);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_diagnostic/src/system_information_diagnostics_plugin.rs | crates/bevy_diagnostic/src/system_information_diagnostics_plugin.rs | use crate::DiagnosticPath;
use alloc::string::String;
use bevy_app::prelude::*;
use bevy_ecs::resource::Resource;
/// Adds a System Information Diagnostic, specifically `cpu_usage` (in %) and `mem_usage` (in %)
///
/// Note that gathering system information is a time intensive task and therefore can't be done on every frame.
/// Any system diagnostics gathered by this plugin may not be current when you access them.
///
/// Supported targets:
/// * linux
/// * windows
/// * android
/// * macOS
///
/// NOT supported when using the `bevy/dynamic` feature even when using previously mentioned targets.
///
/// # See also
///
/// [`LogDiagnosticsPlugin`](crate::LogDiagnosticsPlugin) to output diagnostics to the console.
#[derive(Default)]
pub struct SystemInformationDiagnosticsPlugin;
impl Plugin for SystemInformationDiagnosticsPlugin {
fn build(&self, app: &mut App) {
internal::setup_plugin(app);
}
}
impl SystemInformationDiagnosticsPlugin {
/// Total system cpu usage in %
pub const SYSTEM_CPU_USAGE: DiagnosticPath = DiagnosticPath::const_new("system/cpu_usage");
/// Total system memory usage in %
pub const SYSTEM_MEM_USAGE: DiagnosticPath = DiagnosticPath::const_new("system/mem_usage");
/// Process cpu usage in %
pub const PROCESS_CPU_USAGE: DiagnosticPath = DiagnosticPath::const_new("process/cpu_usage");
/// Process memory usage in %
pub const PROCESS_MEM_USAGE: DiagnosticPath = DiagnosticPath::const_new("process/mem_usage");
}
/// A resource that stores diagnostic information about the system.
/// This information can be useful for debugging and profiling purposes.
///
/// # See also
///
/// [`SystemInformationDiagnosticsPlugin`] for more information.
#[derive(Debug, Resource)]
pub struct SystemInfo {
/// OS name and version.
pub os: String,
/// System kernel version.
pub kernel: String,
/// CPU model name.
pub cpu: String,
/// Physical core count.
pub core_count: String,
/// System RAM.
pub memory: String,
}
// NOTE: sysinfo fails to compile when using bevy dynamic or on iOS and does nothing on Wasm
#[cfg(all(
any(
target_os = "linux",
target_os = "windows",
target_os = "android",
target_os = "macos"
),
not(feature = "dynamic_linking"),
feature = "std",
))]
mod internal {
use core::{
pin::Pin,
task::{Context, Poll},
};
use std::sync::mpsc::{self, Receiver, Sender};
use alloc::{
format,
string::{String, ToString},
sync::Arc,
};
use atomic_waker::AtomicWaker;
use bevy_app::{App, First, Startup, Update};
use bevy_ecs::resource::Resource;
use bevy_ecs::{prelude::ResMut, system::Commands};
use bevy_platform::{cell::SyncCell, time::Instant};
use bevy_tasks::{AsyncComputeTaskPool, Task};
use log::info;
use sysinfo::{CpuRefreshKind, MemoryRefreshKind, RefreshKind, System};
use crate::{Diagnostic, Diagnostics, DiagnosticsStore};
use super::{SystemInfo, SystemInformationDiagnosticsPlugin};
const BYTES_TO_GIB: f64 = 1.0 / 1024.0 / 1024.0 / 1024.0;
/// Sets up the system information diagnostics plugin.
///
/// The plugin spawns a single background task in the async task pool that always reschedules.
/// The [`wake_diagnostic_task`] system wakes this task once per frame during the [`First`]
/// schedule. If enough time has passed since the last refresh, it sends [`SysinfoRefreshData`]
/// through a channel. The [`read_diagnostic_task`] system receives this data during the
/// [`Update`] schedule and adds it as diagnostic measurements.
pub(super) fn setup_plugin(app: &mut App) {
app.add_systems(Startup, setup_system)
.add_systems(First, wake_diagnostic_task)
.add_systems(Update, read_diagnostic_task);
}
fn setup_system(mut diagnostics: ResMut<DiagnosticsStore>, mut commands: Commands) {
let (tx, rx) = mpsc::channel();
let diagnostic_task = DiagnosticTask::new(tx);
let waker = Arc::clone(&diagnostic_task.waker);
let task = AsyncComputeTaskPool::get().spawn(diagnostic_task);
commands.insert_resource(SysinfoTask {
_task: task,
receiver: SyncCell::new(rx),
waker,
});
diagnostics.add(
Diagnostic::new(SystemInformationDiagnosticsPlugin::SYSTEM_CPU_USAGE).with_suffix("%"),
);
diagnostics.add(
Diagnostic::new(SystemInformationDiagnosticsPlugin::SYSTEM_MEM_USAGE).with_suffix("%"),
);
diagnostics.add(
Diagnostic::new(SystemInformationDiagnosticsPlugin::PROCESS_CPU_USAGE).with_suffix("%"),
);
diagnostics.add(
Diagnostic::new(SystemInformationDiagnosticsPlugin::PROCESS_MEM_USAGE)
.with_suffix("GiB"),
);
}
struct SysinfoRefreshData {
system_cpu_usage: f64,
system_mem_usage: f64,
process_cpu_usage: f64,
process_mem_usage: f64,
}
impl SysinfoRefreshData {
fn new(system: &mut System) -> Self {
let pid = sysinfo::get_current_pid().expect("Failed to get current process ID");
system.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true);
system.refresh_cpu_specifics(CpuRefreshKind::nothing().with_cpu_usage());
system.refresh_memory();
let system_cpu_usage = system.global_cpu_usage().into();
let total_mem = system.total_memory() as f64;
let used_mem = system.used_memory() as f64;
let system_mem_usage = used_mem / total_mem * 100.0;
let process_mem_usage = system
.process(pid)
.map(|p| p.memory() as f64 * BYTES_TO_GIB)
.unwrap_or(0.0);
let process_cpu_usage = system
.process(pid)
.map(|p| p.cpu_usage() as f64 / system.cpus().len() as f64)
.unwrap_or(0.0);
Self {
system_cpu_usage,
system_mem_usage,
process_cpu_usage,
process_mem_usage,
}
}
}
#[derive(Resource)]
struct SysinfoTask {
_task: Task<()>,
receiver: SyncCell<Receiver<SysinfoRefreshData>>,
waker: Arc<AtomicWaker>,
}
struct DiagnosticTask {
system: System,
last_refresh: Instant,
sender: Sender<SysinfoRefreshData>,
waker: Arc<AtomicWaker>,
}
impl DiagnosticTask {
fn new(sender: Sender<SysinfoRefreshData>) -> Self {
Self {
system: System::new_with_specifics(
RefreshKind::nothing()
.with_cpu(CpuRefreshKind::nothing().with_cpu_usage())
.with_memory(MemoryRefreshKind::everything()),
),
// Avoids initial delay on first refresh
last_refresh: Instant::now() - sysinfo::MINIMUM_CPU_UPDATE_INTERVAL,
sender,
waker: Arc::default(),
}
}
}
impl Future for DiagnosticTask {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.waker.register(cx.waker());
if self.last_refresh.elapsed() > sysinfo::MINIMUM_CPU_UPDATE_INTERVAL {
self.last_refresh = Instant::now();
let sysinfo_refresh_data = SysinfoRefreshData::new(&mut self.system);
self.sender.send(sysinfo_refresh_data).unwrap();
}
// Always reschedules
Poll::Pending
}
}
fn wake_diagnostic_task(task: ResMut<SysinfoTask>) {
task.waker.wake();
}
fn read_diagnostic_task(mut diagnostics: Diagnostics, mut task: ResMut<SysinfoTask>) {
while let Ok(data) = task.receiver.get().try_recv() {
diagnostics.add_measurement(
&SystemInformationDiagnosticsPlugin::SYSTEM_CPU_USAGE,
|| data.system_cpu_usage,
);
diagnostics.add_measurement(
&SystemInformationDiagnosticsPlugin::SYSTEM_MEM_USAGE,
|| data.system_mem_usage,
);
diagnostics.add_measurement(
&SystemInformationDiagnosticsPlugin::PROCESS_CPU_USAGE,
|| data.process_cpu_usage,
);
diagnostics.add_measurement(
&SystemInformationDiagnosticsPlugin::PROCESS_MEM_USAGE,
|| data.process_mem_usage,
);
}
}
impl Default for SystemInfo {
fn default() -> Self {
let sys = System::new_with_specifics(
RefreshKind::nothing()
.with_cpu(CpuRefreshKind::nothing())
.with_memory(MemoryRefreshKind::nothing().with_ram()),
);
let system_info = SystemInfo {
os: System::long_os_version().unwrap_or_else(|| String::from("not available")),
kernel: System::kernel_version().unwrap_or_else(|| String::from("not available")),
cpu: sys
.cpus()
.first()
.map(|cpu| cpu.brand().trim().to_string())
.unwrap_or_else(|| String::from("not available")),
core_count: System::physical_core_count()
.map(|x| x.to_string())
.unwrap_or_else(|| String::from("not available")),
// Convert from Bytes to GibiBytes since it's probably what people expect most of the time
memory: format!("{:.1} GiB", sys.total_memory() as f64 * BYTES_TO_GIB),
};
info!("{system_info:?}");
system_info
}
}
}
#[cfg(not(all(
any(
target_os = "linux",
target_os = "windows",
target_os = "android",
target_os = "macos"
),
not(feature = "dynamic_linking"),
feature = "std",
)))]
mod internal {
use alloc::string::ToString;
use bevy_app::{App, Startup};
pub(super) fn setup_plugin(app: &mut App) {
app.add_systems(Startup, setup_system);
}
fn setup_system() {
log::warn!("This platform and/or configuration is not supported!");
}
impl Default for super::SystemInfo {
fn default() -> Self {
let unknown = "Unknown".to_string();
Self {
os: unknown.clone(),
kernel: unknown.clone(),
cpu: unknown.clone(),
core_count: unknown.clone(),
memory: unknown.clone(),
}
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_diagnostic/src/log_diagnostics_plugin.rs | crates/bevy_diagnostic/src/log_diagnostics_plugin.rs | use super::{Diagnostic, DiagnosticPath, DiagnosticsStore};
use bevy_app::prelude::*;
use bevy_ecs::prelude::*;
use bevy_platform::collections::HashSet;
use bevy_time::{Real, Time, Timer, TimerMode};
use core::time::Duration;
use log::{debug, info};
/// An App Plugin that logs diagnostics to the console.
///
/// Diagnostics are collected by plugins such as
/// [`FrameTimeDiagnosticsPlugin`](crate::FrameTimeDiagnosticsPlugin)
/// or can be provided by the user.
///
/// When no diagnostics are provided, this plugin does nothing.
pub struct LogDiagnosticsPlugin {
/// If `true` then the `Debug` representation of each `Diagnostic` is logged.
/// If `false` then a (smoothed) current value and historical average are logged.
///
/// Defaults to `false`.
pub debug: bool,
/// Time to wait between logging diagnostics and logging them again.
pub wait_duration: Duration,
/// If `Some` then only these diagnostics are logged.
pub filter: Option<HashSet<DiagnosticPath>>,
}
/// State used by the [`LogDiagnosticsPlugin`]
#[derive(Resource)]
pub struct LogDiagnosticsState {
timer: Timer,
filter: Option<HashSet<DiagnosticPath>>,
}
impl LogDiagnosticsState {
/// Sets a new duration for the log timer
pub fn set_timer_duration(&mut self, duration: Duration) {
self.timer.set_duration(duration);
self.timer.set_elapsed(Duration::ZERO);
}
/// Add a filter to the log state, returning `true` if the [`DiagnosticPath`]
/// was not present
pub fn add_filter(&mut self, diagnostic_path: DiagnosticPath) -> bool {
if let Some(filter) = &mut self.filter {
filter.insert(diagnostic_path)
} else {
self.filter = Some(HashSet::from_iter([diagnostic_path]));
true
}
}
/// Extends the filter of the log state with multiple [`DiagnosticPaths`](DiagnosticPath)
pub fn extend_filter(&mut self, iter: impl IntoIterator<Item = DiagnosticPath>) {
if let Some(filter) = &mut self.filter {
filter.extend(iter);
} else {
self.filter = Some(HashSet::from_iter(iter));
}
}
/// Removes a filter from the log state, returning `true` if it was present
pub fn remove_filter(&mut self, diagnostic_path: &DiagnosticPath) -> bool {
if let Some(filter) = &mut self.filter {
filter.remove(diagnostic_path)
} else {
false
}
}
/// Clears the filters of the log state
pub fn clear_filter(&mut self) {
if let Some(filter) = &mut self.filter {
filter.clear();
}
}
/// Enables filtering with empty filters
pub fn enable_filtering(&mut self) {
self.filter = Some(HashSet::new());
}
/// Disables filtering
pub fn disable_filtering(&mut self) {
self.filter = None;
}
}
impl Default for LogDiagnosticsPlugin {
fn default() -> Self {
LogDiagnosticsPlugin {
debug: false,
wait_duration: Duration::from_secs(1),
filter: None,
}
}
}
impl Plugin for LogDiagnosticsPlugin {
fn build(&self, app: &mut App) {
app.insert_resource(LogDiagnosticsState {
timer: Timer::new(self.wait_duration, TimerMode::Repeating),
filter: self.filter.clone(),
});
if self.debug {
app.add_systems(PostUpdate, Self::log_diagnostics_debug_system);
} else {
app.add_systems(PostUpdate, Self::log_diagnostics_system);
}
}
}
impl LogDiagnosticsPlugin {
/// Filter logging to only the paths in `filter`.
pub fn filtered(filter: HashSet<DiagnosticPath>) -> Self {
LogDiagnosticsPlugin {
filter: Some(filter),
..Default::default()
}
}
fn for_each_diagnostic(
state: &LogDiagnosticsState,
diagnostics: &DiagnosticsStore,
mut callback: impl FnMut(&Diagnostic),
) {
if let Some(filter) = &state.filter {
for path in filter.iter() {
if let Some(diagnostic) = diagnostics.get(path)
&& diagnostic.is_enabled
{
callback(diagnostic);
}
}
} else {
for diagnostic in diagnostics.iter() {
if diagnostic.is_enabled {
callback(diagnostic);
}
}
}
}
fn log_diagnostic(path_width: usize, diagnostic: &Diagnostic) {
let Some(value) = diagnostic.smoothed() else {
return;
};
if diagnostic.get_max_history_length() > 1 {
let Some(average) = diagnostic.average() else {
return;
};
info!(
target: "bevy_diagnostic",
// Suffix is only used for 's' or 'ms' currently,
// so we reserve two columns for it; however,
// Do not reserve columns for the suffix in the average
// The ) hugging the value is more aesthetically pleasing
"{path:<path_width$}: {value:>11.6}{suffix:2} (avg {average:>.6}{suffix:})",
path = diagnostic.path(),
suffix = diagnostic.suffix,
);
} else {
info!(
target: "bevy_diagnostic",
"{path:<path_width$}: {value:>.6}{suffix:}",
path = diagnostic.path(),
suffix = diagnostic.suffix,
);
}
}
fn log_diagnostics(state: &LogDiagnosticsState, diagnostics: &DiagnosticsStore) {
let mut path_width = 0;
Self::for_each_diagnostic(state, diagnostics, |diagnostic| {
let width = diagnostic.path().as_str().len();
path_width = path_width.max(width);
});
Self::for_each_diagnostic(state, diagnostics, |diagnostic| {
Self::log_diagnostic(path_width, diagnostic);
});
}
fn log_diagnostics_system(
mut state: ResMut<LogDiagnosticsState>,
time: Res<Time<Real>>,
diagnostics: Res<DiagnosticsStore>,
) {
if state.timer.tick(time.delta()).is_finished() {
Self::log_diagnostics(&state, &diagnostics);
}
}
fn log_diagnostics_debug_system(
mut state: ResMut<LogDiagnosticsState>,
time: Res<Time<Real>>,
diagnostics: Res<DiagnosticsStore>,
) {
if state.timer.tick(time.delta()).is_finished() {
Self::for_each_diagnostic(&state, &diagnostics, |diagnostic| {
debug!("{diagnostic:#?}\n");
});
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_diagnostic/src/diagnostic.rs | crates/bevy_diagnostic/src/diagnostic.rs | use alloc::{borrow::Cow, collections::VecDeque, string::String};
use core::{
hash::{Hash, Hasher},
time::Duration,
};
use bevy_app::{App, SubApp};
use bevy_ecs::resource::Resource;
use bevy_ecs::system::{Deferred, Res, SystemBuffer, SystemParam};
use bevy_platform::{collections::HashMap, hash::PassHash, time::Instant};
use const_fnv1a_hash::fnv1a_hash_str_64;
use crate::DEFAULT_MAX_HISTORY_LENGTH;
/// Unique diagnostic path, separated by `/`.
///
/// Requirements:
/// - Can't be empty
/// - Can't have leading or trailing `/`
/// - Can't have empty components.
#[derive(Debug, Clone)]
pub struct DiagnosticPath {
path: Cow<'static, str>,
hash: u64,
}
impl DiagnosticPath {
/// Create a new `DiagnosticPath`. Usable in const contexts.
///
/// **Note**: path is not validated, so make sure it follows all the requirements.
pub const fn const_new(path: &'static str) -> DiagnosticPath {
DiagnosticPath {
path: Cow::Borrowed(path),
hash: fnv1a_hash_str_64(path),
}
}
/// Create a new `DiagnosticPath` from the specified string.
pub fn new(path: impl Into<Cow<'static, str>>) -> DiagnosticPath {
let path = path.into();
debug_assert!(!path.is_empty(), "diagnostic path should not be empty");
debug_assert!(
!path.starts_with('/'),
"diagnostic path should not start with `/`"
);
debug_assert!(
!path.ends_with('/'),
"diagnostic path should not end with `/`"
);
debug_assert!(
!path.contains("//"),
"diagnostic path should not contain empty components"
);
DiagnosticPath {
hash: fnv1a_hash_str_64(&path),
path,
}
}
/// Create a new `DiagnosticPath` from an iterator over components.
pub fn from_components<'a>(components: impl IntoIterator<Item = &'a str>) -> DiagnosticPath {
let mut buf = String::new();
for (i, component) in components.into_iter().enumerate() {
if i > 0 {
buf.push('/');
}
buf.push_str(component);
}
DiagnosticPath::new(buf)
}
/// Returns full path, joined by `/`
pub fn as_str(&self) -> &str {
&self.path
}
/// Returns an iterator over path components.
pub fn components(&self) -> impl Iterator<Item = &str> + '_ {
self.path.split('/')
}
}
impl From<DiagnosticPath> for String {
fn from(path: DiagnosticPath) -> Self {
path.path.into()
}
}
impl Eq for DiagnosticPath {}
impl PartialEq for DiagnosticPath {
fn eq(&self, other: &Self) -> bool {
self.hash == other.hash && self.path == other.path
}
}
impl Hash for DiagnosticPath {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write_u64(self.hash);
}
}
impl core::fmt::Display for DiagnosticPath {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
self.path.fmt(f)
}
}
/// A single measurement of a [`Diagnostic`].
#[derive(Debug)]
pub struct DiagnosticMeasurement {
/// When this measurement was taken.
pub time: Instant,
/// Value of the measurement.
pub value: f64,
}
/// A timeline of [`DiagnosticMeasurement`]s of a specific type.
/// Diagnostic examples: frames per second, CPU usage, network latency
#[derive(Debug)]
pub struct Diagnostic {
path: DiagnosticPath,
/// Suffix to use when logging measurements for this [`Diagnostic`], for example to show units.
pub suffix: Cow<'static, str>,
history: VecDeque<DiagnosticMeasurement>,
sum: f64,
ema: f64,
ema_smoothing_factor: f64,
max_history_length: usize,
/// Disabled [`Diagnostic`]s are not measured or logged.
pub is_enabled: bool,
}
impl Diagnostic {
/// Add a new value as a [`DiagnosticMeasurement`].
pub fn add_measurement(&mut self, measurement: DiagnosticMeasurement) {
if measurement.value.is_nan() {
// Skip calculating the moving average.
} else if let Some(previous) = self.measurement() {
let delta = (measurement.time - previous.time).as_secs_f64();
let alpha = (delta / self.ema_smoothing_factor).clamp(0.0, 1.0);
self.ema += alpha * (measurement.value - self.ema);
} else {
self.ema = measurement.value;
}
if self.max_history_length > 1 {
if self.history.len() >= self.max_history_length
&& let Some(removed_diagnostic) = self.history.pop_front()
&& !removed_diagnostic.value.is_nan()
{
self.sum -= removed_diagnostic.value;
}
if measurement.value.is_finite() {
self.sum += measurement.value;
}
} else {
self.history.clear();
if measurement.value.is_nan() {
self.sum = 0.0;
} else {
self.sum = measurement.value;
}
}
self.history.push_back(measurement);
}
/// Create a new diagnostic with the given path.
pub fn new(path: DiagnosticPath) -> Diagnostic {
Diagnostic {
path,
suffix: Cow::Borrowed(""),
history: VecDeque::with_capacity(DEFAULT_MAX_HISTORY_LENGTH),
max_history_length: DEFAULT_MAX_HISTORY_LENGTH,
sum: 0.0,
ema: 0.0,
ema_smoothing_factor: 2.0 / 21.0,
is_enabled: true,
}
}
/// Set the maximum history length.
#[must_use]
pub fn with_max_history_length(mut self, max_history_length: usize) -> Self {
self.max_history_length = max_history_length;
// reserve/reserve_exact reserve space for n *additional* elements.
let expected_capacity = self
.max_history_length
.saturating_sub(self.history.capacity());
self.history.reserve_exact(expected_capacity);
self.history.shrink_to(expected_capacity);
self
}
/// Add a suffix to use when logging the value, can be used to show a unit.
#[must_use]
pub fn with_suffix(mut self, suffix: impl Into<Cow<'static, str>>) -> Self {
self.suffix = suffix.into();
self
}
/// The smoothing factor used for the exponential smoothing used for
/// [`smoothed`](Self::smoothed).
///
/// If measurements come in less frequently than `smoothing_factor` seconds
/// apart, no smoothing will be applied. As measurements come in more
/// frequently, the smoothing takes a greater effect such that it takes
/// approximately `smoothing_factor` seconds for 83% of an instantaneous
/// change in measurement to e reflected in the smoothed value.
///
/// A smoothing factor of 0.0 will effectively disable smoothing.
#[must_use]
pub fn with_smoothing_factor(mut self, smoothing_factor: f64) -> Self {
self.ema_smoothing_factor = smoothing_factor;
self
}
/// Get the [`DiagnosticPath`] that identifies this [`Diagnostic`].
pub fn path(&self) -> &DiagnosticPath {
&self.path
}
/// Get the latest measurement from this diagnostic.
#[inline]
pub fn measurement(&self) -> Option<&DiagnosticMeasurement> {
self.history.back()
}
/// Get the latest value from this diagnostic.
pub fn value(&self) -> Option<f64> {
self.measurement().map(|measurement| measurement.value)
}
/// Return the simple moving average of this diagnostic's recent values.
/// N.B. this a cheap operation as the sum is cached.
pub fn average(&self) -> Option<f64> {
if !self.history.is_empty() {
Some(self.sum / self.history.len() as f64)
} else {
None
}
}
/// Return the exponential moving average of this diagnostic.
///
/// This is by default tuned to behave reasonably well for a typical
/// measurement that changes every frame such as frametime. This can be
/// adjusted using [`with_smoothing_factor`](Self::with_smoothing_factor).
pub fn smoothed(&self) -> Option<f64> {
if !self.history.is_empty() {
Some(self.ema)
} else {
None
}
}
/// Return the number of elements for this diagnostic.
pub fn history_len(&self) -> usize {
self.history.len()
}
/// Return the duration between the oldest and most recent values for this diagnostic.
pub fn duration(&self) -> Option<Duration> {
if self.history.len() < 2 {
return None;
}
let newest = self.history.back()?;
let oldest = self.history.front()?;
Some(newest.time.duration_since(oldest.time))
}
/// Return the maximum number of elements for this diagnostic.
pub fn get_max_history_length(&self) -> usize {
self.max_history_length
}
/// All measured values from this [`Diagnostic`], up to the configured maximum history length.
pub fn values(&self) -> impl Iterator<Item = &f64> {
self.history.iter().map(|x| &x.value)
}
/// All measurements from this [`Diagnostic`], up to the configured maximum history length.
pub fn measurements(&self) -> impl Iterator<Item = &DiagnosticMeasurement> {
self.history.iter()
}
/// Clear the history of this diagnostic.
pub fn clear_history(&mut self) {
self.history.clear();
self.sum = 0.0;
self.ema = 0.0;
}
}
/// A collection of [`Diagnostic`]s.
#[derive(Debug, Default, Resource)]
pub struct DiagnosticsStore {
diagnostics: HashMap<DiagnosticPath, Diagnostic, PassHash>,
}
impl DiagnosticsStore {
/// Add a new [`Diagnostic`].
///
/// If possible, prefer calling [`App::register_diagnostic`].
pub fn add(&mut self, diagnostic: Diagnostic) {
self.diagnostics.insert(diagnostic.path.clone(), diagnostic);
}
/// Get the [`DiagnosticMeasurement`] with the given [`DiagnosticPath`], if it exists.
pub fn get(&self, path: &DiagnosticPath) -> Option<&Diagnostic> {
self.diagnostics.get(path)
}
/// Mutably get the [`DiagnosticMeasurement`] with the given [`DiagnosticPath`], if it exists.
pub fn get_mut(&mut self, path: &DiagnosticPath) -> Option<&mut Diagnostic> {
self.diagnostics.get_mut(path)
}
/// Get the latest [`DiagnosticMeasurement`] from an enabled [`Diagnostic`].
pub fn get_measurement(&self, path: &DiagnosticPath) -> Option<&DiagnosticMeasurement> {
self.diagnostics
.get(path)
.filter(|diagnostic| diagnostic.is_enabled)
.and_then(|diagnostic| diagnostic.measurement())
}
/// Return an iterator over all [`Diagnostic`]s.
pub fn iter(&self) -> impl Iterator<Item = &Diagnostic> {
self.diagnostics.values()
}
/// Return an iterator over all [`Diagnostic`]s, by mutable reference.
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Diagnostic> {
self.diagnostics.values_mut()
}
}
/// Record new [`DiagnosticMeasurement`]'s.
#[derive(SystemParam)]
pub struct Diagnostics<'w, 's> {
store: Res<'w, DiagnosticsStore>,
queue: Deferred<'s, DiagnosticsBuffer>,
}
impl<'w, 's> Diagnostics<'w, 's> {
/// Add a measurement to an enabled [`Diagnostic`]. The measurement is passed as a function so that
/// it will be evaluated only if the [`Diagnostic`] is enabled. This can be useful if the value is
/// costly to calculate.
pub fn add_measurement<F>(&mut self, path: &DiagnosticPath, value: F)
where
F: FnOnce() -> f64,
{
if self
.store
.get(path)
.is_some_and(|diagnostic| diagnostic.is_enabled)
{
let measurement = DiagnosticMeasurement {
time: Instant::now(),
value: value(),
};
self.queue.0.insert(path.clone(), measurement);
}
}
}
#[derive(Default)]
struct DiagnosticsBuffer(HashMap<DiagnosticPath, DiagnosticMeasurement, PassHash>);
impl SystemBuffer for DiagnosticsBuffer {
fn apply(
&mut self,
_system_meta: &bevy_ecs::system::SystemMeta,
world: &mut bevy_ecs::world::World,
) {
let Some(mut diagnostics) = world.get_resource_mut::<DiagnosticsStore>() else {
// `SystemBuffer::apply` is called even if the system never runs. If a user uses
// `If<Diagnostics>`, this buffer will be applied even if we are missing
// `DiagnosticsStore`. So be permissive to allow these cases. See
// https://github.com/bevyengine/bevy/issues/21549 for more.
// Clear the buffer since we have nowhere to put those metrics and we don't want them to
// grow without bound.
self.0.clear();
return;
};
for (path, measurement) in self.0.drain() {
if let Some(diagnostic) = diagnostics.get_mut(&path) {
diagnostic.add_measurement(measurement);
}
}
}
}
/// Extend [`App`] with new `register_diagnostic` function.
pub trait RegisterDiagnostic {
/// Register a new [`Diagnostic`] with an [`App`].
///
/// Will initialize a [`DiagnosticsStore`] if it doesn't exist.
///
/// ```
/// use bevy_app::App;
/// use bevy_diagnostic::{Diagnostic, DiagnosticsPlugin, DiagnosticPath, RegisterDiagnostic};
///
/// const UNIQUE_DIAG_PATH: DiagnosticPath = DiagnosticPath::const_new("foo/bar");
///
/// App::new()
/// .register_diagnostic(Diagnostic::new(UNIQUE_DIAG_PATH))
/// .add_plugins(DiagnosticsPlugin)
/// .run();
/// ```
fn register_diagnostic(&mut self, diagnostic: Diagnostic) -> &mut Self;
}
impl RegisterDiagnostic for SubApp {
fn register_diagnostic(&mut self, diagnostic: Diagnostic) -> &mut Self {
self.init_resource::<DiagnosticsStore>();
let mut diagnostics = self.world_mut().resource_mut::<DiagnosticsStore>();
diagnostics.add(diagnostic);
self
}
}
impl RegisterDiagnostic for App {
fn register_diagnostic(&mut self, diagnostic: Diagnostic) -> &mut Self {
SubApp::register_diagnostic(self.main_mut(), diagnostic);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_clear_history() {
const MEASUREMENT: f64 = 20.0;
let mut diagnostic =
Diagnostic::new(DiagnosticPath::new("test")).with_max_history_length(5);
let mut now = Instant::now();
for _ in 0..3 {
for _ in 0..5 {
diagnostic.add_measurement(DiagnosticMeasurement {
time: now,
value: MEASUREMENT,
});
// Increase time to test smoothed average.
now += Duration::from_secs(1);
}
assert!((diagnostic.average().unwrap() - MEASUREMENT).abs() < 0.1);
assert!((diagnostic.smoothed().unwrap() - MEASUREMENT).abs() < 0.1);
diagnostic.clear_history();
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_transform/src/lib.rs | crates/bevy_transform/src/lib.rs | #![doc = include_str!("../README.md")]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc(
html_logo_url = "https://bevy.org/assets/icon.png",
html_favicon_url = "https://bevy.org/assets/icon.png"
)]
#![no_std]
#[cfg(feature = "std")]
extern crate std;
#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(feature = "bevy-support")]
pub mod commands;
/// The basic components of the transform crate
pub mod components;
/// Transform related traits
pub mod traits;
/// Transform related plugins
#[cfg(feature = "bevy-support")]
pub mod plugins;
/// [`GlobalTransform`]: components::GlobalTransform
/// Helpers related to computing global transforms
#[cfg(feature = "bevy-support")]
pub mod helper;
/// Systems responsible for transform propagation
#[cfg(feature = "bevy-support")]
pub mod systems;
/// The transform prelude.
///
/// This includes the most common types in this crate, re-exported for your convenience.
#[doc(hidden)]
pub mod prelude {
#[doc(hidden)]
pub use crate::components::*;
#[cfg(feature = "bevy-support")]
#[doc(hidden)]
pub use crate::{
commands::BuildChildrenTransformExt,
helper::TransformHelper,
plugins::{TransformPlugin, TransformSystems},
systems::StaticTransformOptimizations,
traits::TransformPoint,
};
}
#[cfg(feature = "bevy-support")]
pub use prelude::{
StaticTransformOptimizations, TransformPlugin, TransformPoint, TransformSystems,
};
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_transform/src/systems.rs | crates/bevy_transform/src/systems.rs | use crate::components::{GlobalTransform, Transform, TransformTreeChanged};
use bevy_ecs::prelude::*;
#[cfg(feature = "std")]
pub use parallel::propagate_parent_transforms;
#[cfg(not(feature = "std"))]
pub use serial::propagate_parent_transforms;
/// Update [`GlobalTransform`] component of entities that aren't in the hierarchy
///
/// Third party plugins should ensure that this is used in concert with
/// [`propagate_parent_transforms`] and [`mark_dirty_trees`].
pub fn sync_simple_transforms(
mut query: ParamSet<(
Query<
(&Transform, &mut GlobalTransform),
(
Or<(Changed<Transform>, Added<GlobalTransform>)>,
Without<ChildOf>,
Without<Children>,
),
>,
Query<(Ref<Transform>, &mut GlobalTransform), (Without<ChildOf>, Without<Children>)>,
)>,
mut orphaned: RemovedComponents<ChildOf>,
) {
// Update changed entities.
query
.p0()
.par_iter_mut()
.for_each(|(transform, mut global_transform)| {
*global_transform = GlobalTransform::from(*transform);
});
// Update orphaned entities.
let mut query = query.p1();
let mut iter = query.iter_many_mut(orphaned.read());
while let Some((transform, mut global_transform)) = iter.fetch_next() {
if !transform.is_changed() && !global_transform.is_added() {
*global_transform = GlobalTransform::from(*transform);
}
}
}
/// Configure the behavior of static scene optimizations for [`Transform`] propagation.
///
/// For scenes with many static entities, it is much faster to track trees of unchanged
/// [`Transform`]s and skip these during the expensive transform propagation step. If your scene is
/// very dynamic, the cost of tracking these trees can exceed the performance benefits. By default,
/// static scene optimization is disabled for worlds with more than 30% of its entities moving.
///
/// This resource allows you to configure that threshold at runtime.
#[derive(Resource, Debug)]
#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
pub struct StaticTransformOptimizations {
/// If the percentage of moving objects exceeds this value, skip dirty tree marking.
threshold: f32,
/// Updated every frame by [`mark_dirty_trees`].
enabled: bool,
}
impl StaticTransformOptimizations {
/// If the percentage of moving objects exceeds this threshold, disable static [`Transform`]
/// optimizations. This is done because the scene is so dynamic that the cost of tracking static
/// trees exceeds the performance benefit of skipping propagation for these trees.
///
/// - Setting this to `0.0` will result in never running static scene tracking.
/// - Setting this to `1.0` will result in always tracking static transform trees.
pub fn from_threshold(threshold: f32) -> Self {
Self {
threshold,
enabled: true,
}
}
/// Unconditionally disable static scene optimizations.
pub fn disabled() -> Self {
Self {
threshold: 0.0,
enabled: false,
}
}
/// Unconditionally enable static scene optimizations.
pub fn enabled() -> Self {
Self {
threshold: 1.0,
enabled: true,
}
}
}
impl Default for StaticTransformOptimizations {
fn default() -> Self {
Self {
// Scenes with more than 30% moving objects are considered dynamic enough to skip static
// optimizations.
threshold: 0.3,
enabled: true,
}
}
}
/// Optimization for static scenes.
///
/// Propagates a "dirty bit" up the hierarchy towards ancestors. Transform propagation can ignore
/// entire subtrees of the hierarchy if it encounters an entity without the dirty bit.
///
/// Configure behavior with [`StaticTransformOptimizations`].
pub fn mark_dirty_trees(
changed_transforms: Query<
Entity,
Or<(Changed<Transform>, Changed<ChildOf>, Added<GlobalTransform>)>,
>,
mut orphaned: RemovedComponents<ChildOf>,
mut transforms: Query<&mut TransformTreeChanged>,
parents: Query<&ChildOf>,
mut static_optimizations: ResMut<StaticTransformOptimizations>,
) {
let threshold = static_optimizations.threshold.clamp(0.0, 1.0);
match threshold {
0.0 => static_optimizations.enabled = false,
1.0 => static_optimizations.enabled = true,
_ => {
static_optimizations.enabled = true;
let n_dyn = changed_transforms.count() as f32;
let total = transforms.count() as f32;
if n_dyn / total > threshold {
static_optimizations.enabled = false;
}
}
}
if !static_optimizations.enabled {
return;
}
for entity in changed_transforms.iter().chain(orphaned.read()) {
let mut next = entity;
while let Ok(mut tree) = transforms.get_mut(next) {
if tree.is_changed() && !tree.is_added() {
// If the component was changed, this part of the tree has already been processed.
// Ignore this if the change was caused by the component being added.
break;
}
tree.set_changed();
if let Ok(parent) = parents.get(next).map(ChildOf::parent) {
next = parent;
} else {
break;
};
}
}
}
// TODO: This serial implementation isn't actually serial, it parallelizes across the roots.
// Additionally, this couples "no_std" with "single_threaded" when these two features should be
// independent.
//
// What we want to do in a future refactor is take the current "single threaded" implementation, and
// actually make it single threaded. This will remove any overhead associated with working on a task
// pool when you only have a single thread, and will have the benefit of removing the need for any
// unsafe. We would then make the multithreaded implementation work across std and no_std, but this
// is blocked a no_std compatible Channel, which is why this TODO is not yet implemented.
//
// This complexity might also not be needed. If the multithreaded implementation on a single thread
// is as fast as the single threaded implementation, we could simply remove the entire serial
// module, and make the multithreaded module no_std compatible.
//
/// Serial hierarchy traversal. Useful in `no_std` or single threaded contexts.
#[cfg(not(feature = "std"))]
mod serial {
use crate::prelude::*;
use alloc::vec::Vec;
use bevy_ecs::prelude::*;
/// Update [`GlobalTransform`] component of entities based on entity hierarchy and [`Transform`]
/// component.
///
/// Third party plugins should ensure that this is used in concert with
/// [`sync_simple_transforms`](super::sync_simple_transforms) and
/// [`mark_dirty_trees`](super::mark_dirty_trees).
pub fn propagate_parent_transforms(
mut root_query: Query<
(Entity, &Children, Ref<Transform>, &mut GlobalTransform),
Without<ChildOf>,
>,
mut orphaned: RemovedComponents<ChildOf>,
transform_query: Query<
(Ref<Transform>, &mut GlobalTransform, Option<&Children>),
With<ChildOf>,
>,
child_query: Query<(Entity, Ref<ChildOf>), With<GlobalTransform>>,
mut orphaned_entities: Local<Vec<Entity>>,
) {
orphaned_entities.clear();
orphaned_entities.extend(orphaned.read());
orphaned_entities.sort_unstable();
root_query.par_iter_mut().for_each(
|(entity, children, transform, mut global_transform)| {
let changed = transform.is_changed() || global_transform.is_added() || orphaned_entities.binary_search(&entity).is_ok();
if changed {
*global_transform = GlobalTransform::from(*transform);
}
for (child, child_of) in child_query.iter_many(children) {
assert_eq!(
child_of.parent(), entity,
"Malformed hierarchy. This probably means that your hierarchy has been improperly maintained, or contains a cycle"
);
// SAFETY:
// - `child` must have consistent parentage, or the above assertion would panic.
// Since `child` is parented to a root entity, the entire hierarchy leading to it
// is consistent.
// - We may operate as if all descendants are consistent, since
// `propagate_recursive` will panic before continuing to propagate if it
// encounters an entity with inconsistent parentage.
// - Since each root entity is unique and the hierarchy is consistent and
// forest-like, other root entities' `propagate_recursive` calls will not conflict
// with this one.
// - Since this is the only place where `transform_query` gets used, there will be
// no conflicting fetches elsewhere.
#[expect(unsafe_code, reason = "`propagate_recursive()` is unsafe due to its use of `Query::get_unchecked()`.")]
unsafe {
propagate_recursive(
&global_transform,
&transform_query,
&child_query,
child,
changed || child_of.is_changed(),
);
}
}
},
);
}
/// Recursively propagates the transforms for `entity` and all of its descendants.
///
/// # Panics
///
/// If `entity`'s descendants have a malformed hierarchy, this function will panic occur before
/// propagating the transforms of any malformed entities and their descendants.
///
/// # Safety
///
/// - While this function is running, `transform_query` must not have any fetches for `entity`,
/// nor any of its descendants.
/// - The caller must ensure that the hierarchy leading to `entity` is well-formed and must
/// remain as a tree or a forest. Each entity must have at most one parent.
#[expect(
unsafe_code,
reason = "This function uses `Query::get_unchecked()`, which can result in multiple mutable references if the preconditions are not met."
)]
unsafe fn propagate_recursive(
parent: &GlobalTransform,
transform_query: &Query<
(Ref<Transform>, &mut GlobalTransform, Option<&Children>),
With<ChildOf>,
>,
child_query: &Query<(Entity, Ref<ChildOf>), With<GlobalTransform>>,
entity: Entity,
mut changed: bool,
) {
let (global_matrix, children) = {
let Ok((transform, mut global_transform, children)) =
// SAFETY: This call cannot create aliased mutable references.
// - The top level iteration parallelizes on the roots of the hierarchy.
// - The caller ensures that each child has one and only one unique parent throughout
// the entire hierarchy.
//
// For example, consider the following malformed hierarchy:
//
// A
// / \
// B C
// \ /
// D
//
// D has two parents, B and C. If the propagation passes through C, but the ChildOf
// component on D points to B, the above check will panic as the origin parent does
// match the recorded parent.
//
// Also consider the following case, where A and B are roots:
//
// A B
// \ /
// C D
// \ /
// E
//
// Even if these A and B start two separate tasks running in parallel, one of them will
// panic before attempting to mutably access E.
(unsafe { transform_query.get_unchecked(entity) }) else {
return;
};
changed |= transform.is_changed() || global_transform.is_added();
if changed {
*global_transform = parent.mul_transform(*transform);
}
(global_transform, children)
};
let Some(children) = children else { return };
for (child, child_of) in child_query.iter_many(children) {
assert_eq!(
child_of.parent(), entity,
"Malformed hierarchy. This probably means that your hierarchy has been improperly maintained, or contains a cycle"
);
// SAFETY: The caller guarantees that `transform_query` will not be fetched for any
// descendants of `entity`, so it is safe to call `propagate_recursive` for each child.
//
// The above assertion ensures that each child has one and only one unique parent
// throughout the entire hierarchy.
unsafe {
propagate_recursive(
global_matrix.as_ref(),
transform_query,
child_query,
child,
changed || child_of.is_changed(),
);
}
}
}
}
// TODO: Relies on `std` until a `no_std` `mpsc` channel is available.
//
/// Parallel hierarchy traversal with a batched work sharing scheduler. Often 2-5 times faster than
/// the serial version.
#[cfg(feature = "std")]
mod parallel {
use crate::prelude::*;
// TODO: this implementation could be used in no_std if there are equivalents of these.
use crate::systems::StaticTransformOptimizations;
use alloc::{sync::Arc, vec::Vec};
use bevy_ecs::{entity::UniqueEntityIter, prelude::*, system::lifetimeless::Read};
use bevy_tasks::{ComputeTaskPool, TaskPool};
use bevy_utils::Parallel;
use core::sync::atomic::{AtomicI32, Ordering};
use std::sync::{
mpsc::{Receiver, Sender},
Mutex,
};
/// Update [`GlobalTransform`] component of entities based on entity hierarchy and [`Transform`]
/// component.
///
/// Third party plugins should ensure that this is used in concert with
/// [`sync_simple_transforms`](super::sync_simple_transforms) and
/// [`mark_dirty_trees`](super::mark_dirty_trees).
pub fn propagate_parent_transforms(
mut queue: Local<WorkQueue>,
mut roots: Query<
(
Entity,
Ref<Transform>,
&mut GlobalTransform,
&Children,
Ref<TransformTreeChanged>,
),
Without<ChildOf>,
>,
nodes: NodeQuery,
static_optimizations: Res<StaticTransformOptimizations>,
) {
// Process roots in parallel, seeding the work queue
roots.par_iter_mut().for_each_init(
|| queue.local_queue.borrow_local_mut(),
|outbox, (parent, transform, mut parent_transform, children, transform_tree)| {
if static_optimizations.enabled && !transform_tree.is_changed() {
// Early exit if the subtree is static and the optimization is enabled.
return;
}
*parent_transform = GlobalTransform::from(*transform);
// SAFETY: the parent entities passed into this function are taken from iterating
// over the root entity query. Queries iterate over disjoint entities, preventing
// mutable aliasing, and making this call safe.
#[expect(unsafe_code, reason = "Mutating disjoint entities in parallel")]
unsafe {
propagate_descendants_unchecked(
parent,
parent_transform,
children,
&nodes,
outbox,
&queue,
&static_optimizations,
// Need to revisit this single-max-depth by profiling more representative
// scenes. It's possible that it is actually beneficial to go deep into the
// hierarchy to build up a good task queue before starting the workers.
// However, we avoid this for now to prevent cases where only a single
// thread is going deep into the hierarchy while the others sit idle, which
// is the problem that the tasks sharing workers already solve.
1,
);
}
},
);
// Send all tasks in thread local outboxes *after* roots are processed to reduce the total
// number of channel sends by avoiding sending partial batches.
queue.send_batches();
if let Ok(rx) = queue.receiver.try_lock() {
if let Some(task) = rx.try_iter().next() {
// This is a bit silly, but the only way to see if there is any work is to grab a
// task. Peeking will remove the task even if you don't call `next`, resulting in
// dropping a task. What we do here is grab the first task if there is one, then
// immediately send it to the back of the queue.
queue.sender.send(task).ok();
} else {
return; // No work, don't bother spawning any tasks
}
}
// Spawn workers on the task pool to recursively propagate the hierarchy in parallel.
let task_pool = ComputeTaskPool::get_or_init(TaskPool::default);
task_pool.scope(|s| {
(1..task_pool.thread_num()) // First worker is run locally instead of the task pool.
.for_each(|_| {
s.spawn(async { propagation_worker(&queue, &nodes, &static_optimizations) });
});
propagation_worker(&queue, &nodes, &static_optimizations);
});
}
/// A parallel worker that will consume processed parent entities from the queue, and push
/// children to the queue once it has propagated their [`GlobalTransform`].
#[inline]
fn propagation_worker(
queue: &WorkQueue,
nodes: &NodeQuery,
static_optimizations: &StaticTransformOptimizations,
) {
#[cfg(feature = "std")]
let _span = bevy_log::info_span!("transform propagation worker").entered();
let mut outbox = queue.local_queue.borrow_local_mut();
loop {
// Try to acquire a lock on the work queue in a tight loop. Profiling shows this is much
// more efficient than relying on `.lock()`, which causes gaps to form between tasks.
let Ok(rx) = queue.receiver.try_lock() else {
core::hint::spin_loop(); // No apparent impact on profiles, but best practice.
continue;
};
// If the queue is empty and no other threads are busy processing work, we can conclude
// there is no more work to do, and end the task by exiting the loop.
let Some(mut tasks) = rx.try_iter().next() else {
if queue.busy_threads.load(Ordering::Relaxed) == 0 {
break; // All work is complete, kill the worker
}
continue; // No work to do now, but another thread is busy creating more work.
};
if tasks.is_empty() {
continue; // This shouldn't happen, but if it does, we might as well stop early.
}
// If the task queue is extremely short, it's worthwhile to gather a few more tasks to
// reduce the amount of thread synchronization needed once this very short task is
// complete.
while tasks.len() < WorkQueue::CHUNK_SIZE / 2 {
let Some(mut extra_task) = rx.try_iter().next() else {
break;
};
tasks.append(&mut extra_task);
}
// At this point, we know there is work to do, so we increment the busy thread counter,
// and drop the mutex guard *after* we have incremented the counter. This ensures that
// if another thread is able to acquire a lock, the busy thread counter will already be
// incremented.
queue.busy_threads.fetch_add(1, Ordering::Relaxed);
drop(rx); // Important: drop after atomic and before work starts.
for parent in tasks.drain(..) {
// SAFETY: each task pushed to the worker queue represents an unprocessed subtree of
// the hierarchy, guaranteeing unique access.
#[expect(unsafe_code, reason = "Mutating disjoint entities in parallel")]
unsafe {
let (_, (_, p_global_transform, _), (p_children, _)) =
nodes.get_unchecked(parent).unwrap();
propagate_descendants_unchecked(
parent,
p_global_transform,
p_children.unwrap(), // All entities in the queue should have children
nodes,
&mut outbox,
queue,
static_optimizations,
// Only affects performance. Trees deeper than this will still be fully
// propagated, but the work will be broken into multiple tasks. This number
// was chosen to be larger than any reasonable tree depth, while not being
// so large the function could hang on a deep hierarchy.
10_000,
);
}
}
WorkQueue::send_batches_with(&queue.sender, &mut outbox);
queue.busy_threads.fetch_add(-1, Ordering::Relaxed);
}
}
/// Propagate transforms from `parent` to its `children`, pushing updated child entities to the
/// `outbox`. This function will continue propagating transforms to descendants in a depth-first
/// traversal, while simultaneously pushing unvisited branches to the outbox, for other threads
/// to take when idle.
///
/// # Safety
///
/// Callers must ensure that concurrent calls to this function are given unique `parent`
/// entities. Calling this function concurrently with the same `parent` is unsound. This
/// function will validate that the entity hierarchy does not contain cycles to prevent mutable
/// aliasing during propagation, but it is unable to verify that it isn't being used to mutably
/// alias the same entity.
///
/// ## Panics
///
/// Panics if the parent of a child node is not the same as the supplied `parent`. This
/// assertion ensures that the hierarchy is acyclic, which in turn ensures that if the caller is
/// following the supplied safety rules, multi-threaded propagation is sound.
#[inline]
#[expect(unsafe_code, reason = "Mutating disjoint entities in parallel")]
unsafe fn propagate_descendants_unchecked(
parent: Entity,
p_global_transform: Mut<GlobalTransform>,
p_children: &Children,
nodes: &NodeQuery,
outbox: &mut Vec<Entity>,
queue: &WorkQueue,
static_optimizations: &StaticTransformOptimizations,
max_depth: usize,
) {
// Create mutable copies of the input variables, used for iterative depth-first traversal.
let (mut parent, mut p_global_transform, mut p_children) =
(parent, p_global_transform, p_children);
// See the optimization note at the end to understand why this loop is here.
for depth in 1..=max_depth {
// Safety: traversing the entity tree from the roots, we assert that the childof and
// children pointers match in both directions (see assert below) to ensure the hierarchy
// does not have any cycles. Because the hierarchy does not have cycles, we know we are
// visiting disjoint entities in parallel, which is safe.
#[expect(unsafe_code, reason = "Mutating disjoint entities in parallel")]
let children_iter = unsafe {
nodes.iter_many_unique_unsafe(UniqueEntityIter::from_iterator_unchecked(
p_children.iter(),
))
};
let mut last_child = None;
let new_children = children_iter.filter_map(
|(child, (transform, mut global_transform, tree), (children, child_of))| {
if static_optimizations.enabled
&& !tree.is_changed()
&& !p_global_transform.is_changed()
{
// Static scene optimization
return None;
}
assert_eq!(child_of.parent(), parent);
// Transform prop is expensive - this helps avoid updating entire subtrees if
// the GlobalTransform is unchanged, at the cost of an added equality check.
global_transform.set_if_neq(p_global_transform.mul_transform(*transform));
children.map(|children| {
// Only continue propagation if the entity has children.
last_child = Some((child, global_transform, children));
child
})
},
);
outbox.extend(new_children);
if depth >= max_depth || last_child.is_none() {
break; // Don't remove anything from the outbox or send any chunks, just exit.
}
// Optimization: tasks should consume work locally as long as they can to avoid
// thread synchronization for as long as possible.
if let Some(last_child) = last_child {
// Overwrite parent data with children, and loop to iterate through descendants.
(parent, p_global_transform, p_children) = last_child;
outbox.pop();
// Send chunks during traversal. This allows sharing tasks with other threads before
// fully completing the traversal.
if outbox.len() >= WorkQueue::CHUNK_SIZE {
WorkQueue::send_batches_with(&queue.sender, outbox);
}
}
}
}
/// Alias for a large, repeatedly used query. Queries for transform entities that have both a
/// parent and possibly children, thus they are not roots.
type NodeQuery<'w, 's> = Query<
'w,
's,
(
Entity,
(
Ref<'static, Transform>,
Mut<'static, GlobalTransform>,
Ref<'static, TransformTreeChanged>,
),
(Option<Read<Children>>, Read<ChildOf>),
),
>;
/// A queue shared between threads for transform propagation.
pub struct WorkQueue {
/// A semaphore that tracks how many threads are busy doing work. Used to determine when
/// there is no more work to do.
busy_threads: AtomicI32,
sender: Sender<Vec<Entity>>,
receiver: Arc<Mutex<Receiver<Vec<Entity>>>>,
local_queue: Parallel<Vec<Entity>>,
}
impl Default for WorkQueue {
fn default() -> Self {
let (tx, rx) = std::sync::mpsc::channel();
Self {
busy_threads: AtomicI32::default(),
sender: tx,
receiver: Arc::new(Mutex::new(rx)),
local_queue: Default::default(),
}
}
}
impl WorkQueue {
const CHUNK_SIZE: usize = 512;
#[inline]
fn send_batches_with(sender: &Sender<Vec<Entity>>, outbox: &mut Vec<Entity>) {
for chunk in outbox
.chunks(WorkQueue::CHUNK_SIZE)
.filter(|c| !c.is_empty())
{
sender.send(chunk.to_vec()).ok();
}
outbox.clear();
}
#[inline]
fn send_batches(&mut self) {
let Self {
sender,
local_queue,
..
} = self;
// Iterate over the locals to send batched tasks, avoiding the need to drain the locals
// into a larger allocation.
local_queue
.iter_mut()
.for_each(|outbox| Self::send_batches_with(sender, outbox));
}
}
}
#[cfg(test)]
mod test {
use alloc::{vec, vec::Vec};
use bevy_app::prelude::*;
use bevy_ecs::{prelude::*, world::CommandQueue};
use bevy_math::{vec3, Vec3};
use bevy_tasks::{ComputeTaskPool, TaskPool};
use crate::systems::*;
#[test]
fn correct_parent_removed() {
ComputeTaskPool::get_or_init(TaskPool::default);
let mut world = World::default();
let offset_global_transform =
|offset| GlobalTransform::from(Transform::from_xyz(offset, offset, offset));
let offset_transform = |offset| Transform::from_xyz(offset, offset, offset);
let mut schedule = Schedule::default();
schedule.add_systems(
(
mark_dirty_trees,
sync_simple_transforms,
propagate_parent_transforms,
)
.chain(),
);
world.insert_resource(StaticTransformOptimizations::default());
let mut command_queue = CommandQueue::default();
let mut commands = Commands::new(&mut command_queue, &world);
let root = commands.spawn(offset_transform(3.3)).id();
let parent = commands.spawn(offset_transform(4.4)).id();
let child = commands.spawn(offset_transform(5.5)).id();
commands.entity(parent).insert(ChildOf(root));
commands.entity(child).insert(ChildOf(parent));
command_queue.apply(&mut world);
schedule.run(&mut world);
assert_eq!(
world.get::<GlobalTransform>(parent).unwrap(),
&offset_global_transform(4.4 + 3.3),
"The transform systems didn't run, ie: `GlobalTransform` wasn't updated",
);
// Remove parent of `parent`
let mut command_queue = CommandQueue::default();
let mut commands = Commands::new(&mut command_queue, &world);
commands.entity(parent).remove::<ChildOf>();
command_queue.apply(&mut world);
schedule.run(&mut world);
assert_eq!(
world.get::<GlobalTransform>(parent).unwrap(),
&offset_global_transform(4.4),
"The global transform of an orphaned entity wasn't updated properly",
);
// Remove parent of `child`
let mut command_queue = CommandQueue::default();
let mut commands = Commands::new(&mut command_queue, &world);
commands.entity(child).remove::<ChildOf>();
command_queue.apply(&mut world);
schedule.run(&mut world);
assert_eq!(
world.get::<GlobalTransform>(child).unwrap(),
&offset_global_transform(5.5),
"The global transform of an orphaned entity wasn't updated properly",
);
}
#[test]
fn did_propagate() {
ComputeTaskPool::get_or_init(TaskPool::default);
let mut world = World::default();
let mut schedule = Schedule::default();
schedule.add_systems(
(
mark_dirty_trees,
sync_simple_transforms,
propagate_parent_transforms,
)
.chain(),
);
world.insert_resource(StaticTransformOptimizations::default());
// Root entity
world.spawn(Transform::from_xyz(1.0, 0.0, 0.0));
let mut children = Vec::new();
world
.spawn(Transform::from_xyz(1.0, 0.0, 0.0))
.with_children(|parent| {
children.push(parent.spawn(Transform::from_xyz(0.0, 2.0, 0.)).id());
children.push(parent.spawn(Transform::from_xyz(0.0, 0.0, 3.)).id());
});
schedule.run(&mut world);
assert_eq!(
*world.get::<GlobalTransform>(children[0]).unwrap(),
GlobalTransform::from_xyz(1.0, 0.0, 0.0) * Transform::from_xyz(0.0, 2.0, 0.0)
);
assert_eq!(
*world.get::<GlobalTransform>(children[1]).unwrap(),
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_transform/src/helper.rs | crates/bevy_transform/src/helper.rs | //! System parameter for computing up-to-date [`GlobalTransform`]s.
use bevy_ecs::{
entity::EntityNotSpawnedError,
hierarchy::ChildOf,
prelude::Entity,
query::QueryEntityError,
system::{Query, SystemParam},
};
use thiserror::Error;
use crate::components::{GlobalTransform, Transform};
/// System parameter for computing up-to-date [`GlobalTransform`]s.
///
/// Computing an entity's [`GlobalTransform`] can be expensive so it is recommended
/// you use the [`GlobalTransform`] component stored on the entity, unless you need
/// a [`GlobalTransform`] that reflects the changes made to any [`Transform`]s since
/// the last time the transform propagation systems ran.
#[derive(SystemParam)]
pub struct TransformHelper<'w, 's> {
parent_query: Query<'w, 's, &'static ChildOf>,
transform_query: Query<'w, 's, &'static Transform>,
}
impl<'w, 's> TransformHelper<'w, 's> {
/// Computes the [`GlobalTransform`] of the given entity from the [`Transform`] component on it and its ancestors.
pub fn compute_global_transform(
&self,
entity: Entity,
) -> Result<GlobalTransform, ComputeGlobalTransformError> {
let transform = self
.transform_query
.get(entity)
.map_err(|err| map_error(err, false))?;
let mut global_transform = GlobalTransform::from(*transform);
for entity in self.parent_query.iter_ancestors(entity) {
let transform = self
.transform_query
.get(entity)
.map_err(|err| map_error(err, true))?;
global_transform = *transform * global_transform;
}
Ok(global_transform)
}
}
fn map_error(err: QueryEntityError, ancestor: bool) -> ComputeGlobalTransformError {
use ComputeGlobalTransformError::*;
match err {
QueryEntityError::QueryDoesNotMatch(entity, _) => MissingTransform(entity),
QueryEntityError::NotSpawned(error) => {
if ancestor {
MalformedHierarchy(error)
} else {
NoSuchEntity(error)
}
}
QueryEntityError::AliasedMutability(_) => unreachable!(),
}
}
/// Error returned by [`TransformHelper::compute_global_transform`].
#[derive(Debug, Error)]
pub enum ComputeGlobalTransformError {
/// The entity or one of its ancestors is missing the [`Transform`] component.
#[error("The entity {0:?} or one of its ancestors is missing the `Transform` component")]
MissingTransform(Entity),
/// The entity does not exist.
#[error("The entity does not exist: {0}")]
NoSuchEntity(EntityNotSpawnedError),
/// An ancestor is missing.
/// This probably means that your hierarchy has been improperly maintained.
#[error("The ancestor is missing: {0}")]
MalformedHierarchy(EntityNotSpawnedError),
}
#[cfg(test)]
mod tests {
use alloc::{vec, vec::Vec};
use core::f32::consts::TAU;
use bevy_app::App;
use bevy_ecs::{hierarchy::ChildOf, system::SystemState};
use bevy_math::{Quat, Vec3};
use crate::{
components::{GlobalTransform, Transform},
helper::TransformHelper,
plugins::TransformPlugin,
};
#[test]
fn match_transform_propagation_systems() {
// Single transform
match_transform_propagation_systems_inner(vec![Transform::from_translation(Vec3::X)
.with_rotation(Quat::from_rotation_y(TAU / 4.))
.with_scale(Vec3::splat(2.))]);
// Transform hierarchy
match_transform_propagation_systems_inner(vec![
Transform::from_translation(Vec3::X)
.with_rotation(Quat::from_rotation_y(TAU / 4.))
.with_scale(Vec3::splat(2.)),
Transform::from_translation(Vec3::Y)
.with_rotation(Quat::from_rotation_z(TAU / 3.))
.with_scale(Vec3::splat(1.5)),
Transform::from_translation(Vec3::Z)
.with_rotation(Quat::from_rotation_x(TAU / 2.))
.with_scale(Vec3::splat(0.3)),
]);
}
fn match_transform_propagation_systems_inner(transforms: Vec<Transform>) {
let mut app = App::new();
app.add_plugins(TransformPlugin);
let mut entity = None;
for transform in transforms {
let mut e = app.world_mut().spawn(transform);
if let Some(parent) = entity {
e.insert(ChildOf(parent));
}
entity = Some(e.id());
}
let leaf_entity = entity.unwrap();
app.update();
let transform = *app.world().get::<GlobalTransform>(leaf_entity).unwrap();
let mut state = SystemState::<TransformHelper>::new(app.world_mut());
let helper = state.get(app.world());
let computed_transform = helper.compute_global_transform(leaf_entity).unwrap();
approx::assert_abs_diff_eq!(transform.affine(), computed_transform.affine());
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_transform/src/commands.rs | crates/bevy_transform/src/commands.rs | //! Extension to [`EntityCommands`] to modify [`bevy_ecs::hierarchy`] hierarchies.
//! while preserving [`GlobalTransform`].
use crate::prelude::{GlobalTransform, Transform};
use bevy_ecs::{entity::Entity, hierarchy::ChildOf, system::EntityCommands, world::EntityWorldMut};
/// Collection of methods similar to the built-in parenting methods on [`EntityWorldMut`] and [`EntityCommands`], but preserving each
/// entity's [`GlobalTransform`].
pub trait BuildChildrenTransformExt {
/// Change this entity's parent while preserving this entity's [`GlobalTransform`]
/// by updating its [`Transform`].
///
/// Insert the [`ChildOf`] component directly if you don't want to also update the [`Transform`].
///
/// Note that both the hierarchy and transform updates will only execute
/// the next time commands are applied
/// (during [`ApplyDeferred`](bevy_ecs::schedule::ApplyDeferred)).
fn set_parent_in_place(&mut self, parent: Entity) -> &mut Self;
/// Make this entity parentless while preserving this entity's [`GlobalTransform`]
/// by updating its [`Transform`] to be equal to its current [`GlobalTransform`].
///
/// See [`EntityWorldMut::remove::<ChildOf>`] or [`EntityCommands::remove::<ChildOf>`] for a method that doesn't update the [`Transform`].
///
/// Note that both the hierarchy and transform updates will only execute
/// the next time commands are applied
/// (during [`ApplyDeferred`](bevy_ecs::schedule::ApplyDeferred)).
fn remove_parent_in_place(&mut self) -> &mut Self;
}
impl BuildChildrenTransformExt for EntityCommands<'_> {
fn set_parent_in_place(&mut self, parent: Entity) -> &mut Self {
self.queue(move |mut entity: EntityWorldMut| {
entity.set_parent_in_place(parent);
})
}
fn remove_parent_in_place(&mut self) -> &mut Self {
self.queue(move |mut entity: EntityWorldMut| {
entity.remove_parent_in_place();
})
}
}
impl BuildChildrenTransformExt for EntityWorldMut<'_> {
fn set_parent_in_place(&mut self, parent: Entity) -> &mut Self {
// FIXME: Replace this closure with a `try` block. See: https://github.com/rust-lang/rust/issues/31436.
let mut update_transform = || {
let child = self.id();
let parent_global = self.world_scope(|world| {
world
.get_entity_mut(parent)
.ok()?
.add_child(child)
.get::<GlobalTransform>()
.copied()
})?;
let child_global = self.get::<GlobalTransform>()?;
let new_child_local = child_global.reparented_to(&parent_global);
let mut child_local = self.get_mut::<Transform>()?;
*child_local = new_child_local;
Some(())
};
update_transform();
self
}
fn remove_parent_in_place(&mut self) -> &mut Self {
self.remove::<ChildOf>();
// FIXME: Replace this closure with a `try` block. See: https://github.com/rust-lang/rust/issues/31436.
let mut update_transform = || {
let global = self.get::<GlobalTransform>()?;
let new_local = global.compute_transform();
let mut local = self.get_mut::<Transform>()?;
*local = new_local;
Some(())
};
update_transform();
self
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_transform/src/plugins.rs | crates/bevy_transform/src/plugins.rs | use crate::systems::{
mark_dirty_trees, propagate_parent_transforms, sync_simple_transforms,
StaticTransformOptimizations,
};
use bevy_app::{App, Plugin, PostStartup, PostUpdate};
use bevy_ecs::schedule::{IntoScheduleConfigs, SystemSet};
/// Set enum for the systems relating to transform propagation
#[derive(Debug, Hash, PartialEq, Eq, Clone, SystemSet)]
pub enum TransformSystems {
/// Propagates changes in transform to children's [`GlobalTransform`](crate::components::GlobalTransform)
Propagate,
}
/// The base plugin for handling [`Transform`](crate::components::Transform) components
#[derive(Default)]
pub struct TransformPlugin;
impl Plugin for TransformPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<StaticTransformOptimizations>()
// add transform systems to startup so the first update is "correct"
.add_systems(
PostStartup,
(
mark_dirty_trees,
propagate_parent_transforms,
sync_simple_transforms,
)
.chain()
.in_set(TransformSystems::Propagate),
)
.add_systems(
PostUpdate,
(
mark_dirty_trees,
propagate_parent_transforms,
// TODO: Adjust the internal parallel queries to make this system more efficiently share and fill CPU time.
sync_simple_transforms,
)
.chain()
.in_set(TransformSystems::Propagate),
);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_transform/src/traits.rs | crates/bevy_transform/src/traits.rs | use bevy_math::{Affine3A, Isometry3d, Mat4, Vec3};
use crate::prelude::{GlobalTransform, Transform};
/// A trait for point transformation methods.
pub trait TransformPoint {
/// Transform a point.
fn transform_point(&self, point: impl Into<Vec3>) -> Vec3;
}
impl TransformPoint for Transform {
#[inline]
fn transform_point(&self, point: impl Into<Vec3>) -> Vec3 {
self.transform_point(point.into())
}
}
impl TransformPoint for GlobalTransform {
#[inline]
fn transform_point(&self, point: impl Into<Vec3>) -> Vec3 {
self.transform_point(point.into())
}
}
impl TransformPoint for Mat4 {
#[inline]
fn transform_point(&self, point: impl Into<Vec3>) -> Vec3 {
self.transform_point3(point.into())
}
}
impl TransformPoint for Affine3A {
#[inline]
fn transform_point(&self, point: impl Into<Vec3>) -> Vec3 {
self.transform_point3(point.into())
}
}
impl TransformPoint for Isometry3d {
#[inline]
fn transform_point(&self, point: impl Into<Vec3>) -> Vec3 {
self.transform_point(point.into()).into()
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_transform/src/components/transform.rs | crates/bevy_transform/src/components/transform.rs | use super::GlobalTransform;
use bevy_math::{Affine3A, Dir3, Isometry3d, Mat3, Mat4, Quat, Vec3};
use core::ops::Mul;
#[cfg(feature = "bevy-support")]
use bevy_ecs::component::Component;
#[cfg(feature = "bevy_reflect")]
use {bevy_ecs::reflect::ReflectComponent, bevy_reflect::prelude::*};
/// Checks that a vector with the given squared length is normalized.
///
/// Warns for small error with a length threshold of approximately `1e-4`,
/// and panics for large error with a length threshold of approximately `1e-2`.
#[cfg(debug_assertions)]
fn assert_is_normalized(message: &str, length_squared: f32) {
use bevy_math::ops;
#[cfg(feature = "std")]
use std::eprintln;
let length_error_squared = ops::abs(length_squared - 1.0);
// Panic for large error and warn for slight error.
if length_error_squared > 2e-2 || length_error_squared.is_nan() {
// Length error is approximately 1e-2 or more.
panic!("Error: {message}",);
} else if length_error_squared > 2e-4 {
// Length error is approximately 1e-4 or more.
#[cfg(feature = "std")]
#[expect(clippy::print_stderr, reason = "Allowed behind `std` feature gate.")]
{
eprintln!("Warning: {message}",);
}
}
}
/// Describe the position of an entity. If the entity has a parent, the position is relative
/// to its parent position.
///
/// * To place or move an entity, you should set its [`Transform`].
/// * To get the global transform of an entity, you should get its [`GlobalTransform`].
/// * To be displayed, an entity must have both a [`Transform`] and a [`GlobalTransform`].
/// [`GlobalTransform`] is automatically inserted whenever [`Transform`] is inserted.
///
/// ## [`Transform`] and [`GlobalTransform`]
///
/// [`Transform`] is the position of an entity relative to its parent position, or the reference
/// frame if it doesn't have a [`ChildOf`](bevy_ecs::hierarchy::ChildOf) component.
///
/// [`GlobalTransform`] is the position of an entity relative to the reference frame.
///
/// [`GlobalTransform`] is updated from [`Transform`] in the [`TransformSystems::Propagate`]
/// system set.
///
/// This system runs during [`PostUpdate`](bevy_app::PostUpdate). If you
/// update the [`Transform`] of an entity during this set or after, you will notice a 1 frame lag
/// before the [`GlobalTransform`] is updated.
///
/// [`TransformSystems::Propagate`]: crate::TransformSystems::Propagate
///
/// # Examples
///
/// - [`transform`][transform_example]
///
/// [transform_example]: https://github.com/bevyengine/bevy/blob/latest/examples/transforms/transform.rs
#[derive(Debug, PartialEq, Clone, Copy)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy-support",
derive(Component),
require(GlobalTransform, TransformTreeChanged)
)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Component, Default, PartialEq, Debug, Clone)
)]
#[cfg_attr(
all(feature = "bevy_reflect", feature = "serialize"),
reflect(Serialize, Deserialize)
)]
pub struct Transform {
/// Position of the entity. In 2d, the last value of the `Vec3` is used for z-ordering.
///
/// See the [`translations`] example for usage.
///
/// [`translations`]: https://github.com/bevyengine/bevy/blob/latest/examples/transforms/translation.rs
pub translation: Vec3,
/// Rotation of the entity.
///
/// See the [`3d_rotation`] example for usage.
///
/// [`3d_rotation`]: https://github.com/bevyengine/bevy/blob/latest/examples/transforms/3d_rotation.rs
pub rotation: Quat,
/// Scale of the entity.
///
/// See the [`scale`] example for usage.
///
/// [`scale`]: https://github.com/bevyengine/bevy/blob/latest/examples/transforms/scale.rs
pub scale: Vec3,
}
impl Transform {
/// An identity [`Transform`] with no translation, rotation, and a scale of 1 on all axes.
pub const IDENTITY: Self = Transform {
translation: Vec3::ZERO,
rotation: Quat::IDENTITY,
scale: Vec3::ONE,
};
/// Creates a new [`Transform`] at the position `(x, y, z)`. In 2d, the `z` component
/// is used for z-ordering elements: higher `z`-value will be in front of lower
/// `z`-value.
#[inline]
pub const fn from_xyz(x: f32, y: f32, z: f32) -> Self {
Self::from_translation(Vec3::new(x, y, z))
}
/// Extracts the translation, rotation, and scale from `matrix`. It must be a 3d affine
/// transformation matrix.
#[inline]
pub fn from_matrix(world_from_local: Mat4) -> Self {
let (scale, rotation, translation) = world_from_local.to_scale_rotation_translation();
Transform {
translation,
rotation,
scale,
}
}
/// Creates a new [`Transform`], with `translation`. Rotation will be 0 and scale 1 on
/// all axes.
#[inline]
pub const fn from_translation(translation: Vec3) -> Self {
Transform {
translation,
..Self::IDENTITY
}
}
/// Creates a new [`Transform`], with `rotation`. Translation will be 0 and scale 1 on
/// all axes.
#[inline]
pub const fn from_rotation(rotation: Quat) -> Self {
Transform {
rotation,
..Self::IDENTITY
}
}
/// Creates a new [`Transform`], with `scale`. Translation will be 0 and rotation 0 on
/// all axes.
#[inline]
pub const fn from_scale(scale: Vec3) -> Self {
Transform {
scale,
..Self::IDENTITY
}
}
/// Creates a new [`Transform`] that is equivalent to the given [isometry].
///
/// [isometry]: Isometry3d
#[inline]
pub fn from_isometry(iso: Isometry3d) -> Self {
Transform {
translation: iso.translation.into(),
rotation: iso.rotation,
..Self::IDENTITY
}
}
/// Returns this [`Transform`] with a new rotation so that [`Transform::forward`]
/// points towards the `target` position and [`Transform::up`] points towards `up`.
///
/// In some cases it's not possible to construct a rotation. Another axis will be picked in those cases:
/// * if `target` is the same as the transform translation, `Vec3::Z` is used instead
/// * if `up` fails converting to `Dir3` (e.g if it is `Vec3::ZERO`), `Dir3::Y` is used instead
/// * if the resulting forward direction is parallel with `up`, an orthogonal vector is used as the "right" direction
#[inline]
#[must_use]
pub fn looking_at(mut self, target: Vec3, up: impl TryInto<Dir3>) -> Self {
self.look_at(target, up);
self
}
/// Returns this [`Transform`] with a new rotation so that [`Transform::forward`]
/// points in the given `direction` and [`Transform::up`] points towards `up`.
///
/// In some cases it's not possible to construct a rotation. Another axis will be picked in those cases:
/// * if `direction` fails converting to `Dir3` (e.g if it is `Vec3::ZERO`), `Dir3::Z` is used instead
/// * if `up` fails converting to `Dir3`, `Dir3::Y` is used instead
/// * if `direction` is parallel with `up`, an orthogonal vector is used as the "right" direction
#[inline]
#[must_use]
pub fn looking_to(mut self, direction: impl TryInto<Dir3>, up: impl TryInto<Dir3>) -> Self {
self.look_to(direction, up);
self
}
/// Rotates this [`Transform`] so that the `main_axis` vector, reinterpreted in local coordinates, points
/// in the given `main_direction`, while `secondary_axis` points towards `secondary_direction`.
/// For example, if a spaceship model has its nose pointing in the X-direction in its own local coordinates
/// and its dorsal fin pointing in the Y-direction, then `align(Dir3::X, v, Dir3::Y, w)` will make the spaceship's
/// nose point in the direction of `v`, while the dorsal fin does its best to point in the direction `w`.
///
///
/// In some cases a rotation cannot be constructed. Another axis will be picked in those cases:
/// * if `main_axis` or `main_direction` fail converting to `Dir3` (e.g are zero), `Dir3::X` takes their place
/// * if `secondary_axis` or `secondary_direction` fail converting, `Dir3::Y` takes their place
/// * if `main_axis` is parallel with `secondary_axis` or `main_direction` is parallel with `secondary_direction`,
/// a rotation is constructed which takes `main_axis` to `main_direction` along a great circle, ignoring the secondary
/// counterparts
///
/// See [`Transform::align`] for additional details.
#[inline]
#[must_use]
pub fn aligned_by(
mut self,
main_axis: impl TryInto<Dir3>,
main_direction: impl TryInto<Dir3>,
secondary_axis: impl TryInto<Dir3>,
secondary_direction: impl TryInto<Dir3>,
) -> Self {
self.align(
main_axis,
main_direction,
secondary_axis,
secondary_direction,
);
self
}
/// Returns this [`Transform`] with a new translation.
#[inline]
#[must_use]
pub const fn with_translation(mut self, translation: Vec3) -> Self {
self.translation = translation;
self
}
/// Returns this [`Transform`] with a new rotation.
#[inline]
#[must_use]
pub const fn with_rotation(mut self, rotation: Quat) -> Self {
self.rotation = rotation;
self
}
/// Returns this [`Transform`] with a new scale.
#[inline]
#[must_use]
pub const fn with_scale(mut self, scale: Vec3) -> Self {
self.scale = scale;
self
}
/// Computes the 3d affine transformation matrix from this transform's translation,
/// rotation, and scale.
#[inline]
pub fn to_matrix(&self) -> Mat4 {
Mat4::from_scale_rotation_translation(self.scale, self.rotation, self.translation)
}
/// Returns the 3d affine transformation matrix from this transforms translation,
/// rotation, and scale.
#[inline]
pub fn compute_affine(&self) -> Affine3A {
Affine3A::from_scale_rotation_translation(self.scale, self.rotation, self.translation)
}
/// Get the unit vector in the local `X` direction.
#[inline]
pub fn local_x(&self) -> Dir3 {
// Quat * unit vector is length 1
Dir3::new_unchecked(self.rotation * Vec3::X)
}
/// Equivalent to [`-local_x()`][Transform::local_x()]
#[inline]
pub fn left(&self) -> Dir3 {
-self.local_x()
}
/// Equivalent to [`local_x()`][Transform::local_x()]
#[inline]
pub fn right(&self) -> Dir3 {
self.local_x()
}
/// Get the unit vector in the local `Y` direction.
#[inline]
pub fn local_y(&self) -> Dir3 {
// Quat * unit vector is length 1
Dir3::new_unchecked(self.rotation * Vec3::Y)
}
/// Equivalent to [`local_y()`][Transform::local_y]
#[inline]
pub fn up(&self) -> Dir3 {
self.local_y()
}
/// Equivalent to [`-local_y()`][Transform::local_y]
#[inline]
pub fn down(&self) -> Dir3 {
-self.local_y()
}
/// Get the unit vector in the local `Z` direction.
#[inline]
pub fn local_z(&self) -> Dir3 {
// Quat * unit vector is length 1
Dir3::new_unchecked(self.rotation * Vec3::Z)
}
/// Equivalent to [`-local_z()`][Transform::local_z]
#[inline]
pub fn forward(&self) -> Dir3 {
-self.local_z()
}
/// Equivalent to [`local_z()`][Transform::local_z]
#[inline]
pub fn back(&self) -> Dir3 {
self.local_z()
}
/// Rotates this [`Transform`] by the given rotation.
///
/// If this [`Transform`] has a parent, the `rotation` is relative to the rotation of the parent.
///
/// # Examples
///
/// - [`3d_rotation`]
///
/// [`3d_rotation`]: https://github.com/bevyengine/bevy/blob/latest/examples/transforms/3d_rotation.rs
#[inline]
pub fn rotate(&mut self, rotation: Quat) {
self.rotation = rotation * self.rotation;
}
/// Rotates this [`Transform`] around the given `axis` by `angle` (in radians).
///
/// If this [`Transform`] has a parent, the `axis` is relative to the rotation of the parent.
///
/// # Warning
///
/// If you pass in an `axis` based on the current rotation (e.g. obtained via [`Transform::local_x`]),
/// floating point errors can accumulate exponentially when applying rotations repeatedly this way. This will
/// result in a denormalized rotation. In this case, it is recommended to normalize the [`Transform::rotation`] after
/// each call to this method.
#[inline]
pub fn rotate_axis(&mut self, axis: Dir3, angle: f32) {
#[cfg(debug_assertions)]
assert_is_normalized(
"The axis given to `Transform::rotate_axis` is not normalized. This may be a result of obtaining \
the axis from the transform. See the documentation of `Transform::rotate_axis` for more details.",
axis.length_squared(),
);
self.rotate(Quat::from_axis_angle(axis.into(), angle));
}
/// Rotates this [`Transform`] around the `X` axis by `angle` (in radians).
///
/// If this [`Transform`] has a parent, the axis is relative to the rotation of the parent.
#[inline]
pub fn rotate_x(&mut self, angle: f32) {
self.rotate(Quat::from_rotation_x(angle));
}
/// Rotates this [`Transform`] around the `Y` axis by `angle` (in radians).
///
/// If this [`Transform`] has a parent, the axis is relative to the rotation of the parent.
#[inline]
pub fn rotate_y(&mut self, angle: f32) {
self.rotate(Quat::from_rotation_y(angle));
}
/// Rotates this [`Transform`] around the `Z` axis by `angle` (in radians).
///
/// If this [`Transform`] has a parent, the axis is relative to the rotation of the parent.
#[inline]
pub fn rotate_z(&mut self, angle: f32) {
self.rotate(Quat::from_rotation_z(angle));
}
/// Rotates this [`Transform`] by the given `rotation`.
///
/// The `rotation` is relative to this [`Transform`]'s current rotation.
#[inline]
pub fn rotate_local(&mut self, rotation: Quat) {
self.rotation *= rotation;
}
/// Rotates this [`Transform`] around its local `axis` by `angle` (in radians).
///
/// # Warning
///
/// If you pass in an `axis` based on the current rotation (e.g. obtained via [`Transform::local_x`]),
/// floating point errors can accumulate exponentially when applying rotations repeatedly this way. This will
/// result in a denormalized rotation. In this case, it is recommended to normalize the [`Transform::rotation`] after
/// each call to this method.
#[inline]
pub fn rotate_local_axis(&mut self, axis: Dir3, angle: f32) {
#[cfg(debug_assertions)]
assert_is_normalized(
"The axis given to `Transform::rotate_axis_local` is not normalized. This may be a result of obtaining \
the axis from the transform. See the documentation of `Transform::rotate_axis_local` for more details.",
axis.length_squared(),
);
self.rotate_local(Quat::from_axis_angle(axis.into(), angle));
}
/// Rotates this [`Transform`] around its local `X` axis by `angle` (in radians).
#[inline]
pub fn rotate_local_x(&mut self, angle: f32) {
self.rotate_local(Quat::from_rotation_x(angle));
}
/// Rotates this [`Transform`] around its local `Y` axis by `angle` (in radians).
#[inline]
pub fn rotate_local_y(&mut self, angle: f32) {
self.rotate_local(Quat::from_rotation_y(angle));
}
/// Rotates this [`Transform`] around its local `Z` axis by `angle` (in radians).
#[inline]
pub fn rotate_local_z(&mut self, angle: f32) {
self.rotate_local(Quat::from_rotation_z(angle));
}
/// Translates this [`Transform`] around a `point` in space.
///
/// If this [`Transform`] has a parent, the `point` is relative to the [`Transform`] of the parent.
#[inline]
pub fn translate_around(&mut self, point: Vec3, rotation: Quat) {
self.translation = point + rotation * (self.translation - point);
}
/// Rotates this [`Transform`] around a `point` in space.
///
/// If this [`Transform`] has a parent, the `point` is relative to the [`Transform`] of the parent.
#[inline]
pub fn rotate_around(&mut self, point: Vec3, rotation: Quat) {
self.translate_around(point, rotation);
self.rotate(rotation);
}
/// Rotates this [`Transform`] so that [`Transform::forward`] points towards the `target` position,
/// and [`Transform::up`] points towards `up`.
///
/// In some cases it's not possible to construct a rotation. Another axis will be picked in those cases:
/// * if `target` is the same as the transform translation, `Vec3::Z` is used instead
/// * if `up` fails converting to `Dir3` (e.g if it is `Vec3::ZERO`), `Dir3::Y` is used instead
/// * if the resulting forward direction is parallel with `up`, an orthogonal vector is used as the "right" direction
#[inline]
pub fn look_at(&mut self, target: Vec3, up: impl TryInto<Dir3>) {
self.look_to(target - self.translation, up);
}
/// Rotates this [`Transform`] so that [`Transform::forward`] points in the given `direction`
/// and [`Transform::up`] points towards `up`.
///
/// In some cases it's not possible to construct a rotation. Another axis will be picked in those cases:
/// * if `direction` fails converting to `Dir3` (e.g if it is `Vec3::ZERO`), `Dir3::NEG_Z` is used instead
/// * if `up` fails converting to `Dir3`, `Dir3::Y` is used instead
/// * if `direction` is parallel with `up`, an orthogonal vector is used as the "right" direction
#[inline]
pub fn look_to(&mut self, direction: impl TryInto<Dir3>, up: impl TryInto<Dir3>) {
let back = -direction.try_into().unwrap_or(Dir3::NEG_Z);
let up = up.try_into().unwrap_or(Dir3::Y);
let right = up
.cross(back.into())
.try_normalize()
.unwrap_or_else(|| up.any_orthonormal_vector());
let up = back.cross(right);
self.rotation = Quat::from_mat3(&Mat3::from_cols(right, up, back.into()));
}
/// Rotates this [`Transform`] so that the `main_axis` vector, reinterpreted in local coordinates, points
/// in the given `main_direction`, while `secondary_axis` points towards `secondary_direction`.
///
/// For example, if a spaceship model has its nose pointing in the X-direction in its own local coordinates
/// and its dorsal fin pointing in the Y-direction, then `align(Dir3::X, v, Dir3::Y, w)` will make the spaceship's
/// nose point in the direction of `v`, while the dorsal fin does its best to point in the direction `w`.
///
/// More precisely, the [`Transform::rotation`] produced will be such that:
/// * applying it to `main_axis` results in `main_direction`
/// * applying it to `secondary_axis` produces a vector that lies in the half-plane generated by `main_direction` and
/// `secondary_direction` (with positive contribution by `secondary_direction`)
///
/// [`Transform::look_to`] is recovered, for instance, when `main_axis` is `Dir3::NEG_Z` (the [`Transform::forward`]
/// direction in the default orientation) and `secondary_axis` is `Dir3::Y` (the [`Transform::up`] direction in the default
/// orientation). (Failure cases may differ somewhat.)
///
/// In some cases a rotation cannot be constructed. Another axis will be picked in those cases:
/// * if `main_axis` or `main_direction` fail converting to `Dir3` (e.g are zero), `Dir3::X` takes their place
/// * if `secondary_axis` or `secondary_direction` fail converting, `Dir3::Y` takes their place
/// * if `main_axis` is parallel with `secondary_axis` or `main_direction` is parallel with `secondary_direction`,
/// a rotation is constructed which takes `main_axis` to `main_direction` along a great circle, ignoring the secondary
/// counterparts
///
/// Example
/// ```
/// # use bevy_math::{Dir3, Vec3, Quat};
/// # use bevy_transform::components::Transform;
/// # let mut t1 = Transform::IDENTITY;
/// # let mut t2 = Transform::IDENTITY;
/// t1.align(Dir3::X, Dir3::Y, Vec3::new(1., 1., 0.), Dir3::Z);
/// let main_axis_image = t1.rotation * Dir3::X;
/// let secondary_axis_image = t1.rotation * Vec3::new(1., 1., 0.);
/// assert!(main_axis_image.abs_diff_eq(Vec3::Y, 1e-5));
/// assert!(secondary_axis_image.abs_diff_eq(Vec3::new(0., 1., 1.), 1e-5));
///
/// t1.align(Vec3::ZERO, Dir3::Z, Vec3::ZERO, Dir3::X);
/// t2.align(Dir3::X, Dir3::Z, Dir3::Y, Dir3::X);
/// assert_eq!(t1.rotation, t2.rotation);
///
/// t1.align(Dir3::X, Dir3::Z, Dir3::X, Dir3::Y);
/// assert_eq!(t1.rotation, Quat::from_rotation_arc(Vec3::X, Vec3::Z));
/// ```
#[inline]
pub fn align(
&mut self,
main_axis: impl TryInto<Dir3>,
main_direction: impl TryInto<Dir3>,
secondary_axis: impl TryInto<Dir3>,
secondary_direction: impl TryInto<Dir3>,
) {
let main_axis = main_axis.try_into().unwrap_or(Dir3::X);
let main_direction = main_direction.try_into().unwrap_or(Dir3::X);
let secondary_axis = secondary_axis.try_into().unwrap_or(Dir3::Y);
let secondary_direction = secondary_direction.try_into().unwrap_or(Dir3::Y);
// The solution quaternion will be constructed in two steps.
// First, we start with a rotation that takes `main_axis` to `main_direction`.
let first_rotation = Quat::from_rotation_arc(main_axis.into(), main_direction.into());
// Let's follow by rotating about the `main_direction` axis so that the image of `secondary_axis`
// is taken to something that lies in the plane of `main_direction` and `secondary_direction`. Since
// `main_direction` is fixed by this rotation, the first criterion is still satisfied.
let secondary_image = first_rotation * secondary_axis;
let secondary_image_ortho = secondary_image
.reject_from_normalized(main_direction.into())
.try_normalize();
let secondary_direction_ortho = secondary_direction
.reject_from_normalized(main_direction.into())
.try_normalize();
// If one of the two weak vectors was parallel to `main_direction`, then we just do the first part
self.rotation = match (secondary_image_ortho, secondary_direction_ortho) {
(Some(secondary_img_ortho), Some(secondary_dir_ortho)) => {
let second_rotation =
Quat::from_rotation_arc(secondary_img_ortho, secondary_dir_ortho);
second_rotation * first_rotation
}
_ => first_rotation,
};
}
/// Multiplies `self` with `transform` component by component, returning the
/// resulting [`Transform`]
#[inline]
#[must_use]
pub fn mul_transform(&self, transform: Transform) -> Self {
let translation = self.transform_point(transform.translation);
let rotation = self.rotation * transform.rotation;
let scale = self.scale * transform.scale;
Transform {
translation,
rotation,
scale,
}
}
/// Transforms the given `point`, applying scale, rotation and translation.
///
/// If this [`Transform`] has an ancestor entity with a [`Transform`] component,
/// [`Transform::transform_point`] will transform a point in local space into its
/// parent transform's space.
///
/// If this [`Transform`] does not have a parent, [`Transform::transform_point`] will
/// transform a point in local space into worldspace coordinates.
///
/// If you always want to transform a point in local space to worldspace, or if you need
/// the inverse transformations, see [`GlobalTransform::transform_point()`].
#[inline]
pub fn transform_point(&self, mut point: Vec3) -> Vec3 {
point = self.scale * point;
point = self.rotation * point;
point += self.translation;
point
}
/// Returns `true` if, and only if, translation, rotation and scale all are
/// finite. If any of them contains a `NaN`, positive or negative infinity,
/// this will return `false`.
#[inline]
#[must_use]
pub fn is_finite(&self) -> bool {
self.translation.is_finite() && self.rotation.is_finite() && self.scale.is_finite()
}
/// Get the [isometry] defined by this transform's rotation and translation, ignoring scale.
///
/// [isometry]: Isometry3d
#[inline]
pub fn to_isometry(&self) -> Isometry3d {
Isometry3d::new(self.translation, self.rotation)
}
}
impl Default for Transform {
fn default() -> Self {
Self::IDENTITY
}
}
/// The transform is expected to be non-degenerate and without shearing, or the output
/// will be invalid.
impl From<GlobalTransform> for Transform {
fn from(transform: GlobalTransform) -> Self {
transform.compute_transform()
}
}
impl Mul<Transform> for Transform {
type Output = Transform;
fn mul(self, transform: Transform) -> Self::Output {
self.mul_transform(transform)
}
}
impl Mul<GlobalTransform> for Transform {
type Output = GlobalTransform;
#[inline]
fn mul(self, global_transform: GlobalTransform) -> Self::Output {
GlobalTransform::from(self) * global_transform
}
}
impl Mul<Vec3> for Transform {
type Output = Vec3;
fn mul(self, value: Vec3) -> Self::Output {
self.transform_point(value)
}
}
/// An optimization for transform propagation. This ZST marker component uses change detection to
/// mark all entities of the hierarchy as "dirty" if any of their descendants have a changed
/// `Transform`. If this component is *not* marked `is_changed()`, propagation will halt.
#[derive(Clone, Copy, Default, PartialEq, Debug)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "bevy-support", derive(Component))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Component, Default, PartialEq, Debug)
)]
#[cfg_attr(
all(feature = "bevy_reflect", feature = "serialize"),
reflect(Serialize, Deserialize)
)]
pub struct TransformTreeChanged;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_transform/src/components/mod.rs | crates/bevy_transform/src/components/mod.rs | mod global_transform;
mod transform;
pub use global_transform::*;
pub use transform::*;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_transform/src/components/global_transform.rs | crates/bevy_transform/src/components/global_transform.rs | use core::ops::Mul;
use super::Transform;
use bevy_math::{ops, Affine3A, Dir3, Isometry3d, Mat4, Quat, Vec3, Vec3A};
use derive_more::derive::From;
#[cfg(all(feature = "bevy_reflect", feature = "serialize"))]
use bevy_reflect::{ReflectDeserialize, ReflectSerialize};
#[cfg(feature = "bevy-support")]
use bevy_ecs::{component::Component, hierarchy::validate_parent_has_component};
#[cfg(feature = "bevy_reflect")]
use {
bevy_ecs::reflect::ReflectComponent,
bevy_reflect::{std_traits::ReflectDefault, Reflect},
};
/// [`GlobalTransform`] is an affine transformation from entity-local coordinates to worldspace coordinates.
///
/// You cannot directly mutate [`GlobalTransform`]; instead, you change an entity's transform by manipulating
/// its [`Transform`], which indirectly causes Bevy to update its [`GlobalTransform`].
///
/// * To get the global transform of an entity, you should get its [`GlobalTransform`].
/// * For transform hierarchies to work correctly, you must have both a [`Transform`] and a [`GlobalTransform`].
/// [`GlobalTransform`] is automatically inserted whenever [`Transform`] is inserted.
///
/// ## [`Transform`] and [`GlobalTransform`]
///
/// [`Transform`] transforms an entity relative to its parent's reference frame, or relative to world space coordinates,
/// if it doesn't have a [`ChildOf`](bevy_ecs::hierarchy::ChildOf) component.
///
/// [`GlobalTransform`] is managed by Bevy; it is computed by successively applying the [`Transform`] of each ancestor
/// entity which has a Transform. This is done automatically by Bevy-internal systems in the [`TransformSystems::Propagate`]
/// system set.
///
/// This system runs during [`PostUpdate`](bevy_app::PostUpdate). If you
/// update the [`Transform`] of an entity in this schedule or after, you will notice a 1 frame lag
/// before the [`GlobalTransform`] is updated.
///
/// [`TransformSystems::Propagate`]: crate::TransformSystems::Propagate
///
/// # Examples
///
/// - [`transform`][transform_example]
///
/// [transform_example]: https://github.com/bevyengine/bevy/blob/latest/examples/transforms/transform.rs
#[derive(Debug, PartialEq, Clone, Copy, From)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "bevy-support",
derive(Component),
component(on_insert = validate_parent_has_component::<GlobalTransform>)
)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Component, Default, PartialEq, Debug, Clone)
)]
#[cfg_attr(
all(feature = "bevy_reflect", feature = "serialize"),
reflect(Serialize, Deserialize)
)]
pub struct GlobalTransform(Affine3A);
macro_rules! impl_local_axis {
($pos_name: ident, $neg_name: ident, $axis: ident) => {
#[doc=core::concat!("Return the local ", core::stringify!($pos_name), " vector (", core::stringify!($axis) ,").")]
#[inline]
pub fn $pos_name(&self) -> Dir3 {
Dir3::new_unchecked((self.0.matrix3 * Vec3::$axis).normalize())
}
#[doc=core::concat!("Return the local ", core::stringify!($neg_name), " vector (-", core::stringify!($axis) ,").")]
#[inline]
pub fn $neg_name(&self) -> Dir3 {
-self.$pos_name()
}
};
}
impl GlobalTransform {
/// An identity [`GlobalTransform`] that maps all points in space to themselves.
pub const IDENTITY: Self = Self(Affine3A::IDENTITY);
#[doc(hidden)]
#[inline]
pub fn from_xyz(x: f32, y: f32, z: f32) -> Self {
Self::from_translation(Vec3::new(x, y, z))
}
#[doc(hidden)]
#[inline]
pub fn from_translation(translation: Vec3) -> Self {
GlobalTransform(Affine3A::from_translation(translation))
}
#[doc(hidden)]
#[inline]
pub fn from_rotation(rotation: Quat) -> Self {
GlobalTransform(Affine3A::from_rotation_translation(rotation, Vec3::ZERO))
}
#[doc(hidden)]
#[inline]
pub fn from_scale(scale: Vec3) -> Self {
GlobalTransform(Affine3A::from_scale(scale))
}
#[doc(hidden)]
#[inline]
pub fn from_isometry(iso: Isometry3d) -> Self {
Self(iso.into())
}
/// Returns the 3d affine transformation matrix as a [`Mat4`].
#[inline]
pub fn to_matrix(&self) -> Mat4 {
Mat4::from(self.0)
}
/// Returns the 3d affine transformation matrix as an [`Affine3A`].
#[inline]
pub fn affine(&self) -> Affine3A {
self.0
}
/// Returns the transformation as a [`Transform`].
///
/// The transform is expected to be non-degenerate and without shearing, or the output
/// will be invalid.
#[inline]
pub fn compute_transform(&self) -> Transform {
let (scale, rotation, translation) = self.0.to_scale_rotation_translation();
Transform {
translation,
rotation,
scale,
}
}
/// Computes a Scale-Rotation-Translation decomposition of the transformation and returns
/// the isometric part as an [isometry]. Any scaling done by the transformation will be ignored.
/// Note: this is a somewhat costly and lossy conversion.
///
/// The transform is expected to be non-degenerate and without shearing, or the output
/// will be invalid.
///
/// [isometry]: Isometry3d
#[inline]
pub fn to_isometry(&self) -> Isometry3d {
let (_, rotation, translation) = self.0.to_scale_rotation_translation();
Isometry3d::new(translation, rotation)
}
/// Returns the [`Transform`] `self` would have if it was a child of an entity
/// with the `parent` [`GlobalTransform`].
///
/// This is useful if you want to "reparent" an [`Entity`](bevy_ecs::entity::Entity).
/// Say you have an entity `e1` that you want to turn into a child of `e2`,
/// but you want `e1` to keep the same global transform, even after re-parenting. You would use:
///
/// ```
/// # use bevy_transform::prelude::{GlobalTransform, Transform};
/// # use bevy_ecs::prelude::{Entity, Query, Component, Commands, ChildOf};
/// #[derive(Component)]
/// struct ToReparent {
/// new_parent: Entity,
/// }
/// fn reparent_system(
/// mut commands: Commands,
/// mut targets: Query<(&mut Transform, Entity, &GlobalTransform, &ToReparent)>,
/// transforms: Query<&GlobalTransform>,
/// ) {
/// for (mut transform, entity, initial, to_reparent) in targets.iter_mut() {
/// if let Ok(parent_transform) = transforms.get(to_reparent.new_parent) {
/// *transform = initial.reparented_to(parent_transform);
/// commands.entity(entity)
/// .remove::<ToReparent>()
/// .insert(ChildOf(to_reparent.new_parent));
/// }
/// }
/// }
/// ```
///
/// The transform is expected to be non-degenerate and without shearing, or the output
/// will be invalid.
#[inline]
pub fn reparented_to(&self, parent: &GlobalTransform) -> Transform {
let relative_affine = parent.affine().inverse() * self.affine();
let (scale, rotation, translation) = relative_affine.to_scale_rotation_translation();
Transform {
translation,
rotation,
scale,
}
}
/// Extracts `scale`, `rotation` and `translation` from `self`.
///
/// The transform is expected to be non-degenerate and without shearing, or the output
/// will be invalid.
#[inline]
pub fn to_scale_rotation_translation(&self) -> (Vec3, Quat, Vec3) {
self.0.to_scale_rotation_translation()
}
impl_local_axis!(right, left, X);
impl_local_axis!(up, down, Y);
impl_local_axis!(back, forward, Z);
/// Get the translation as a [`Vec3`].
#[inline]
pub fn translation(&self) -> Vec3 {
self.0.translation.into()
}
/// Get the translation as a [`Vec3A`].
#[inline]
pub fn translation_vec3a(&self) -> Vec3A {
self.0.translation
}
/// Get the rotation as a [`Quat`].
///
/// The transform is expected to be non-degenerate and without shearing, or the output will be invalid.
///
/// # Warning
///
/// This is calculated using `to_scale_rotation_translation`, meaning that you
/// should probably use it directly if you also need translation or scale.
#[inline]
pub fn rotation(&self) -> Quat {
self.to_scale_rotation_translation().1
}
/// Get the scale as a [`Vec3`].
///
/// The transform is expected to be non-degenerate and without shearing, or the output will be invalid.
///
/// Some of the computations overlap with `to_scale_rotation_translation`, which means you should use
/// it instead if you also need rotation.
#[inline]
pub fn scale(&self) -> Vec3 {
//Formula based on glam's implementation https://github.com/bitshifter/glam-rs/blob/2e4443e70c709710dfb25958d866d29b11ed3e2b/src/f32/affine3a.rs#L290
let det = self.0.matrix3.determinant();
Vec3::new(
self.0.matrix3.x_axis.length() * ops::copysign(1., det),
self.0.matrix3.y_axis.length(),
self.0.matrix3.z_axis.length(),
)
}
/// Get an upper bound of the radius from the given `extents`.
#[inline]
pub fn radius_vec3a(&self, extents: Vec3A) -> f32 {
(self.0.matrix3 * extents).length()
}
/// Transforms the given point from local space to global space, applying shear, scale, rotation and translation.
///
/// It can be used like this:
///
/// ```
/// # use bevy_transform::prelude::{GlobalTransform};
/// # use bevy_math::prelude::Vec3;
/// let global_transform = GlobalTransform::from_xyz(1., 2., 3.);
/// let local_point = Vec3::new(1., 2., 3.);
/// let global_point = global_transform.transform_point(local_point);
/// assert_eq!(global_point, Vec3::new(2., 4., 6.));
/// ```
///
/// ```
/// # use bevy_transform::prelude::{GlobalTransform};
/// # use bevy_math::Vec3;
/// let global_point = Vec3::new(2., 4., 6.);
/// let global_transform = GlobalTransform::from_xyz(1., 2., 3.);
/// let local_point = global_transform.affine().inverse().transform_point3(global_point);
/// assert_eq!(local_point, Vec3::new(1., 2., 3.))
/// ```
///
/// To apply shear, scale, and rotation *without* applying translation, different functions are available:
/// ```
/// # use bevy_transform::prelude::{GlobalTransform};
/// # use bevy_math::prelude::Vec3;
/// let global_transform = GlobalTransform::from_xyz(1., 2., 3.);
/// let local_direction = Vec3::new(1., 2., 3.);
/// let global_direction = global_transform.affine().transform_vector3(local_direction);
/// assert_eq!(global_direction, Vec3::new(1., 2., 3.));
/// let roundtripped_local_direction = global_transform.affine().inverse().transform_vector3(global_direction);
/// assert_eq!(roundtripped_local_direction, local_direction);
/// ```
#[inline]
pub fn transform_point(&self, point: Vec3) -> Vec3 {
self.0.transform_point3(point)
}
/// Multiplies `self` with `transform` component by component, returning the
/// resulting [`GlobalTransform`]
#[inline]
pub fn mul_transform(&self, transform: Transform) -> Self {
Self(self.0 * transform.compute_affine())
}
}
impl Default for GlobalTransform {
fn default() -> Self {
Self::IDENTITY
}
}
impl From<Transform> for GlobalTransform {
fn from(transform: Transform) -> Self {
Self(transform.compute_affine())
}
}
impl From<Mat4> for GlobalTransform {
fn from(world_from_local: Mat4) -> Self {
Self(Affine3A::from_mat4(world_from_local))
}
}
impl Mul<GlobalTransform> for GlobalTransform {
type Output = GlobalTransform;
#[inline]
fn mul(self, global_transform: GlobalTransform) -> Self::Output {
GlobalTransform(self.0 * global_transform.0)
}
}
impl Mul<Transform> for GlobalTransform {
type Output = GlobalTransform;
#[inline]
fn mul(self, transform: Transform) -> Self::Output {
self.mul_transform(transform)
}
}
impl Mul<Vec3> for GlobalTransform {
type Output = Vec3;
#[inline]
fn mul(self, value: Vec3) -> Self::Output {
self.transform_point(value)
}
}
#[cfg(test)]
mod test {
use super::*;
use bevy_math::EulerRot::XYZ;
fn transform_equal(left: GlobalTransform, right: Transform) -> bool {
left.0.abs_diff_eq(right.compute_affine(), 0.01)
}
#[test]
fn reparented_to_transform_identity() {
fn reparent_to_same(t1: GlobalTransform, t2: GlobalTransform) -> Transform {
t2.mul_transform(t1.into()).reparented_to(&t2)
}
let t1 = GlobalTransform::from(Transform {
translation: Vec3::new(1034.0, 34.0, -1324.34),
rotation: Quat::from_euler(XYZ, 1.0, 0.9, 2.1),
scale: Vec3::new(1.0, 1.0, 1.0),
});
let t2 = GlobalTransform::from(Transform {
translation: Vec3::new(0.0, -54.493, 324.34),
rotation: Quat::from_euler(XYZ, 1.9, 0.3, 3.0),
scale: Vec3::new(1.345, 1.345, 1.345),
});
let retransformed = reparent_to_same(t1, t2);
assert!(
transform_equal(t1, retransformed),
"t1:{:#?} retransformed:{:#?}",
t1.compute_transform(),
retransformed,
);
}
#[test]
fn reparented_usecase() {
let t1 = GlobalTransform::from(Transform {
translation: Vec3::new(1034.0, 34.0, -1324.34),
rotation: Quat::from_euler(XYZ, 0.8, 1.9, 2.1),
scale: Vec3::new(10.9, 10.9, 10.9),
});
let t2 = GlobalTransform::from(Transform {
translation: Vec3::new(28.0, -54.493, 324.34),
rotation: Quat::from_euler(XYZ, 0.0, 3.1, 0.1),
scale: Vec3::new(0.9, 0.9, 0.9),
});
// goal: find `X` such as `t2 * X = t1`
let reparented = t1.reparented_to(&t2);
let t1_prime = t2 * reparented;
assert!(
transform_equal(t1, t1_prime.into()),
"t1:{:#?} t1_prime:{:#?}",
t1.compute_transform(),
t1_prime.compute_transform(),
);
}
#[test]
fn scale() {
let test_values = [-42.42, 0., 42.42];
for x in test_values {
for y in test_values {
for z in test_values {
let scale = Vec3::new(x, y, z);
let gt = GlobalTransform::from_scale(scale);
assert_eq!(gt.scale(), gt.to_scale_rotation_translation().0);
}
}
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/macros/src/lib.rs | crates/bevy_asset/macros/src/lib.rs | #![cfg_attr(docsrs, feature(doc_cfg))]
//! Macros for deriving asset traits.
use bevy_macro_utils::{as_member, BevyManifest};
use proc_macro::{Span, TokenStream};
use quote::{format_ident, quote};
use syn::{parse_macro_input, Data, DataStruct, DeriveInput, Path};
pub(crate) fn bevy_asset_path() -> Path {
BevyManifest::shared(|manifest| manifest.get_path("bevy_asset"))
}
const DEPENDENCY_ATTRIBUTE: &str = "dependency";
/// Implement the `Asset` trait.
#[proc_macro_derive(Asset, attributes(dependency))]
pub fn derive_asset(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
let bevy_asset_path: Path = bevy_asset_path();
let struct_name = &ast.ident;
let (impl_generics, type_generics, where_clause) = &ast.generics.split_for_impl();
let dependency_visitor = match derive_dependency_visitor_internal(&ast, &bevy_asset_path) {
Ok(dependency_visitor) => dependency_visitor,
Err(err) => return err.into_compile_error().into(),
};
TokenStream::from(quote! {
impl #impl_generics #bevy_asset_path::Asset for #struct_name #type_generics #where_clause { }
#dependency_visitor
})
}
/// Implement the `VisitAssetDependencies` trait.
#[proc_macro_derive(VisitAssetDependencies, attributes(dependency))]
pub fn derive_asset_dependency_visitor(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
let bevy_asset_path: Path = bevy_asset_path();
match derive_dependency_visitor_internal(&ast, &bevy_asset_path) {
Ok(dependency_visitor) => TokenStream::from(dependency_visitor),
Err(err) => err.into_compile_error().into(),
}
}
fn derive_dependency_visitor_internal(
ast: &DeriveInput,
bevy_asset_path: &Path,
) -> Result<proc_macro2::TokenStream, syn::Error> {
let struct_name = &ast.ident;
let (impl_generics, type_generics, where_clause) = &ast.generics.split_for_impl();
let visit_dep = |to_read| quote!(#bevy_asset_path::VisitAssetDependencies::visit_dependencies(#to_read, visit););
let is_dep_attribute = |a: &syn::Attribute| a.path().is_ident(DEPENDENCY_ATTRIBUTE);
let field_has_dep = |f: &syn::Field| f.attrs.iter().any(is_dep_attribute);
let body = match &ast.data {
Data::Struct(DataStruct { fields, .. }) => {
let field_visitors = fields
.iter()
.enumerate()
.filter(|(_, f)| field_has_dep(f))
.map(|(i, field)| as_member(field.ident.as_ref(), i))
.map(|member| visit_dep(quote!(&self.#member)));
Some(quote!(#(#field_visitors)*))
}
Data::Enum(data_enum) => {
let variant_has_dep = |v: &syn::Variant| v.fields.iter().any(field_has_dep);
let any_case_required = data_enum.variants.iter().any(variant_has_dep);
let cases = data_enum.variants.iter().filter(|v| variant_has_dep(v));
let cases = cases.map(|variant| {
let ident = &variant.ident;
let field_members = variant
.fields
.iter()
.enumerate()
.filter(|(_, f)| field_has_dep(f))
.map(|(i, field)| as_member(field.ident.as_ref(), i));
let field_locals = field_members.clone().map(|m| format_ident!("__self_{}", m));
let field_visitors = field_locals.clone().map(|i| visit_dep(quote!(#i)));
quote!(Self::#ident {#(#field_members: #field_locals,)* ..} => {
#(#field_visitors)*
})
});
any_case_required.then(|| quote!(match self { #(#cases)*, _ => {} }))
}
Data::Union(_) => {
return Err(syn::Error::new(
Span::call_site().into(),
"Asset derive currently doesn't work on unions",
));
}
};
// prevent unused variable warning in case there are no dependencies
let visit = if body.is_none() {
quote! { _visit }
} else {
quote! { visit }
};
Ok(quote! {
impl #impl_generics #bevy_asset_path::VisitAssetDependencies for #struct_name #type_generics #where_clause {
fn visit_dependencies(&self, #visit: &mut impl FnMut(#bevy_asset_path::UntypedAssetId)) {
#body
}
}
})
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/event.rs | crates/bevy_asset/src/event.rs | use crate::{Asset, AssetId, AssetLoadError, AssetPath, UntypedAssetId};
use bevy_ecs::message::Message;
use bevy_reflect::Reflect;
use core::fmt::Debug;
/// A [`Message`] emitted when a specific [`Asset`] fails to load.
///
/// For an untyped equivalent, see [`UntypedAssetLoadFailedEvent`].
#[derive(Message, Clone, Debug)]
pub struct AssetLoadFailedEvent<A: Asset> {
/// The stable identifier of the asset that failed to load.
pub id: AssetId<A>,
/// The asset path that was attempted.
pub path: AssetPath<'static>,
/// Why the asset failed to load.
pub error: AssetLoadError,
}
impl<A: Asset> AssetLoadFailedEvent<A> {
/// Converts this to an "untyped" / "generic-less" asset error event that stores the type information.
pub fn untyped(&self) -> UntypedAssetLoadFailedEvent {
self.into()
}
}
/// An untyped version of [`AssetLoadFailedEvent`].
#[derive(Message, Clone, Debug)]
pub struct UntypedAssetLoadFailedEvent {
/// The stable identifier of the asset that failed to load.
pub id: UntypedAssetId,
/// The asset path that was attempted.
pub path: AssetPath<'static>,
/// Why the asset failed to load.
pub error: AssetLoadError,
}
impl<A: Asset> From<&AssetLoadFailedEvent<A>> for UntypedAssetLoadFailedEvent {
fn from(value: &AssetLoadFailedEvent<A>) -> Self {
UntypedAssetLoadFailedEvent {
id: value.id.untyped(),
path: value.path.clone(),
error: value.error.clone(),
}
}
}
/// [`Message`]s that occur for a specific loaded [`Asset`], such as "value changed" events and "dependency" events.
#[expect(missing_docs, reason = "Documenting the id fields is unhelpful.")]
#[derive(Message, Reflect)]
pub enum AssetEvent<A: Asset> {
/// Emitted whenever an [`Asset`] is added.
Added { id: AssetId<A> },
/// Emitted whenever an [`Asset`] value is modified.
Modified { id: AssetId<A> },
/// Emitted whenever an [`Asset`] is removed.
Removed { id: AssetId<A> },
/// Emitted when the last [`Handle::Strong`](`super::Handle::Strong`) of an [`Asset`] is dropped.
Unused { id: AssetId<A> },
/// Emitted whenever an [`Asset`] has been fully loaded (including its dependencies and all "recursive dependencies").
LoadedWithDependencies { id: AssetId<A> },
}
impl<A: Asset> AssetEvent<A> {
/// Returns `true` if this event is [`AssetEvent::LoadedWithDependencies`] and matches the given `id`.
pub fn is_loaded_with_dependencies(&self, asset_id: impl Into<AssetId<A>>) -> bool {
matches!(self, AssetEvent::LoadedWithDependencies { id } if *id == asset_id.into())
}
/// Returns `true` if this event is [`AssetEvent::Added`] and matches the given `id`.
pub fn is_added(&self, asset_id: impl Into<AssetId<A>>) -> bool {
matches!(self, AssetEvent::Added { id } if *id == asset_id.into())
}
/// Returns `true` if this event is [`AssetEvent::Modified`] and matches the given `id`.
pub fn is_modified(&self, asset_id: impl Into<AssetId<A>>) -> bool {
matches!(self, AssetEvent::Modified { id } if *id == asset_id.into())
}
/// Returns `true` if this event is [`AssetEvent::Removed`] and matches the given `id`.
pub fn is_removed(&self, asset_id: impl Into<AssetId<A>>) -> bool {
matches!(self, AssetEvent::Removed { id } if *id == asset_id.into())
}
/// Returns `true` if this event is [`AssetEvent::Unused`] and matches the given `id`.
pub fn is_unused(&self, asset_id: impl Into<AssetId<A>>) -> bool {
matches!(self, AssetEvent::Unused { id } if *id == asset_id.into())
}
}
impl<A: Asset> Clone for AssetEvent<A> {
fn clone(&self) -> Self {
*self
}
}
impl<A: Asset> Copy for AssetEvent<A> {}
impl<A: Asset> Debug for AssetEvent<A> {
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(),
Self::Removed { id } => f.debug_struct("Removed").field("id", id).finish(),
Self::Unused { id } => f.debug_struct("Unused").field("id", id).finish(),
Self::LoadedWithDependencies { id } => f
.debug_struct("LoadedWithDependencies")
.field("id", id)
.finish(),
}
}
}
impl<A: Asset> PartialEq for AssetEvent<A> {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Added { id: l_id }, Self::Added { id: r_id })
| (Self::Modified { id: l_id }, Self::Modified { id: r_id })
| (Self::Removed { id: l_id }, Self::Removed { id: r_id })
| (Self::Unused { id: l_id }, Self::Unused { id: r_id })
| (
Self::LoadedWithDependencies { id: l_id },
Self::LoadedWithDependencies { id: r_id },
) => l_id == r_id,
_ => false,
}
}
}
impl<A: Asset> Eq for AssetEvent<A> {}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/asset_changed.rs | crates/bevy_asset/src/asset_changed.rs | //! Defines the [`AssetChanged`] query filter.
//!
//! Like [`Changed`](bevy_ecs::prelude::Changed), but for [`Asset`]s,
//! and triggers whenever the handle or the underlying asset changes.
use crate::{AsAssetId, Asset, AssetId};
use bevy_ecs::component::Components;
use bevy_ecs::{
archetype::Archetype,
change_detection::Tick,
component::ComponentId,
prelude::{Entity, Resource, World},
query::{FilteredAccess, QueryData, QueryFilter, ReadFetch, WorldQuery},
storage::{Table, TableRow},
world::unsafe_world_cell::UnsafeWorldCell,
};
use bevy_platform::collections::HashMap;
use core::marker::PhantomData;
use disqualified::ShortName;
use tracing::error;
/// A resource that stores the last tick an asset was changed. This is used by
/// the [`AssetChanged`] filter to determine if an asset has changed since the last time
/// a query ran.
///
/// This resource is automatically managed by the [`AssetEventSystems`](crate::AssetEventSystems)
/// system set and should not be exposed to the user in order to maintain safety guarantees.
/// Any additional uses of this resource should be carefully audited to ensure that they do not
/// introduce any safety issues.
#[derive(Resource)]
pub(crate) struct AssetChanges<A: Asset> {
change_ticks: HashMap<AssetId<A>, Tick>,
last_change_tick: Tick,
}
impl<A: Asset> AssetChanges<A> {
pub(crate) fn insert(&mut self, asset_id: AssetId<A>, tick: Tick) {
self.last_change_tick = tick;
self.change_ticks.insert(asset_id, tick);
}
pub(crate) fn remove(&mut self, asset_id: &AssetId<A>) {
self.change_ticks.remove(asset_id);
}
}
impl<A: Asset> Default for AssetChanges<A> {
fn default() -> Self {
Self {
change_ticks: Default::default(),
last_change_tick: Tick::new(0),
}
}
}
struct AssetChangeCheck<'w, A: AsAssetId> {
// This should never be `None` in practice, but we need to handle the case
// where the `AssetChanges` resource was removed.
change_ticks: Option<&'w HashMap<AssetId<A::Asset>, Tick>>,
last_run: Tick,
this_run: Tick,
}
impl<A: AsAssetId> Clone for AssetChangeCheck<'_, A> {
fn clone(&self) -> Self {
*self
}
}
impl<A: AsAssetId> Copy for AssetChangeCheck<'_, A> {}
impl<'w, A: AsAssetId> AssetChangeCheck<'w, A> {
fn new(changes: &'w AssetChanges<A::Asset>, last_run: Tick, this_run: Tick) -> Self {
Self {
change_ticks: Some(&changes.change_ticks),
last_run,
this_run,
}
}
// TODO(perf): some sort of caching? Each check has two levels of indirection,
// which is not optimal.
fn has_changed(&self, handle: &A) -> bool {
let is_newer = |tick: &Tick| tick.is_newer_than(self.last_run, self.this_run);
let id = handle.as_asset_id();
self.change_ticks
.is_some_and(|change_ticks| change_ticks.get(&id).is_some_and(is_newer))
}
}
/// Filter that selects entities with an `A` for an asset that changed
/// after the system last ran, where `A` is a component that implements
/// [`AsAssetId`].
///
/// Unlike `Changed<A>`, this is true whenever the asset for the `A`
/// in `ResMut<Assets<A>>` changed. For example, when a mesh changed through the
/// [`Assets<Mesh>::get_mut`] method, `AssetChanged<Mesh>` will iterate over all
/// entities with the `Handle<Mesh>` for that mesh. Meanwhile, `Changed<Handle<Mesh>>`
/// will iterate over no entities.
///
/// Swapping the actual `A` component is a common pattern. So you
/// should check for _both_ `AssetChanged<A>` and `Changed<A>` with
/// `Or<(Changed<A>, AssetChanged<A>)>`.
///
/// # Quirks
///
/// - Asset changes are registered in the [`AssetEventSystems`] system set.
/// - Removed assets are not detected.
///
/// The list of changed assets only gets updated in the [`AssetEventSystems`] system set,
/// which runs in `PostUpdate`. Therefore, `AssetChanged` will only pick up asset changes in schedules
/// following [`AssetEventSystems`] or the next frame. Consider adding the system in the `Last` schedule
/// after [`AssetEventSystems`] if you need to react without frame delay to asset changes.
///
/// # Performance
///
/// When at least one `A` is updated, this will
/// read a hashmap once per entity with an `A` component. The
/// runtime of the query is proportional to how many entities with an `A`
/// it matches.
///
/// If no `A` asset updated since the last time the system ran, then no lookups occur.
///
/// [`AssetEventSystems`]: crate::AssetEventSystems
/// [`Assets<Mesh>::get_mut`]: crate::Assets::get_mut
pub struct AssetChanged<A: AsAssetId>(PhantomData<A>);
/// [`WorldQuery`] fetch for [`AssetChanged`].
#[doc(hidden)]
pub struct AssetChangedFetch<'w, A: AsAssetId> {
inner: Option<ReadFetch<'w, A>>,
check: AssetChangeCheck<'w, A>,
}
impl<'w, A: AsAssetId> Clone for AssetChangedFetch<'w, A> {
fn clone(&self) -> Self {
Self {
inner: self.inner,
check: self.check,
}
}
}
/// [`WorldQuery`] state for [`AssetChanged`].
#[doc(hidden)]
pub struct AssetChangedState<A: AsAssetId> {
asset_id: ComponentId,
resource_id: ComponentId,
_asset: PhantomData<fn(A)>,
}
#[expect(unsafe_code, reason = "WorldQuery is an unsafe trait.")]
/// SAFETY: `ROQueryFetch<Self>` is the same as `QueryFetch<Self>`
unsafe impl<A: AsAssetId> WorldQuery for AssetChanged<A> {
type Fetch<'w> = AssetChangedFetch<'w, A>;
type State = AssetChangedState<A>;
fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
fetch
}
unsafe fn init_fetch<'w, 's>(
world: UnsafeWorldCell<'w>,
state: &'s Self::State,
last_run: Tick,
this_run: Tick,
) -> Self::Fetch<'w> {
// SAFETY:
// - `AssetChanges` is private and only accessed mutably in the `AssetEventSystems` system set.
// - `resource_id` was obtained from the type ID of `AssetChanges<A::Asset>`.
let Some(changes) = (unsafe {
world
.get_resource_by_id(state.resource_id)
.map(|ptr| ptr.deref::<AssetChanges<A::Asset>>())
}) else {
error!(
"AssetChanges<{ty}> resource was removed, please do not remove \
AssetChanges<{ty}> when using the AssetChanged<{ty}> world query",
ty = ShortName::of::<A>()
);
return AssetChangedFetch {
inner: None,
check: AssetChangeCheck {
change_ticks: None,
last_run,
this_run,
},
};
};
let has_updates = changes.last_change_tick.is_newer_than(last_run, this_run);
AssetChangedFetch {
inner: has_updates.then(||
// SAFETY: We delegate to the inner `init_fetch` for `A`
unsafe {
<&A>::init_fetch(world, &state.asset_id, last_run, this_run)
}),
check: AssetChangeCheck::new(changes, last_run, this_run),
}
}
const IS_DENSE: bool = <&A>::IS_DENSE;
unsafe fn set_archetype<'w, 's>(
fetch: &mut Self::Fetch<'w>,
state: &'s Self::State,
archetype: &'w Archetype,
table: &'w Table,
) {
if let Some(inner) = &mut fetch.inner {
// SAFETY: We delegate to the inner `set_archetype` for `A`
unsafe {
<&A>::set_archetype(inner, &state.asset_id, archetype, table);
}
}
}
unsafe fn set_table<'w, 's>(
fetch: &mut Self::Fetch<'w>,
state: &Self::State,
table: &'w Table,
) {
if let Some(inner) = &mut fetch.inner {
// SAFETY: We delegate to the inner `set_table` for `A`
unsafe {
<&A>::set_table(inner, &state.asset_id, table);
}
}
}
#[inline]
fn update_component_access(state: &Self::State, access: &mut FilteredAccess) {
<&A>::update_component_access(&state.asset_id, access);
access.add_resource_read(state.resource_id);
}
fn init_state(world: &mut World) -> AssetChangedState<A> {
let resource_id = world.init_resource::<AssetChanges<A::Asset>>();
let asset_id = world.register_component::<A>();
AssetChangedState {
asset_id,
resource_id,
_asset: PhantomData,
}
}
fn get_state(components: &Components) -> Option<Self::State> {
let resource_id = components.resource_id::<AssetChanges<A::Asset>>()?;
let asset_id = components.component_id::<A>()?;
Some(AssetChangedState {
asset_id,
resource_id,
_asset: PhantomData,
})
}
fn matches_component_set(
state: &Self::State,
set_contains_id: &impl Fn(ComponentId) -> bool,
) -> bool {
set_contains_id(state.asset_id)
}
}
#[expect(unsafe_code, reason = "QueryFilter is an unsafe trait.")]
/// SAFETY: read-only access
unsafe impl<A: AsAssetId> QueryFilter for AssetChanged<A> {
const IS_ARCHETYPAL: bool = false;
#[inline]
unsafe fn filter_fetch(
state: &Self::State,
fetch: &mut Self::Fetch<'_>,
entity: Entity,
table_row: TableRow,
) -> bool {
fetch.inner.as_mut().is_some_and(|inner| {
// SAFETY: We delegate to the inner `fetch` for `A`
unsafe {
let handle = <&A>::fetch(&state.asset_id, inner, entity, table_row);
handle.is_some_and(|handle| fetch.check.has_changed(handle))
}
})
}
}
#[cfg(test)]
#[expect(clippy::print_stdout, reason = "Allowed in tests.")]
mod tests {
use crate::tests::create_app;
use crate::{AssetEventSystems, Handle};
use alloc::{vec, vec::Vec};
use core::num::NonZero;
use std::println;
use crate::{AssetApp, Assets};
use bevy_app::{App, AppExit, PostUpdate, Startup, Update};
use bevy_ecs::schedule::IntoScheduleConfigs;
use bevy_ecs::{
component::Component,
message::MessageWriter,
resource::Resource,
system::{Commands, IntoSystem, Local, Query, Res, ResMut},
};
use bevy_reflect::TypePath;
use super::*;
#[derive(Asset, TypePath, Debug)]
struct MyAsset(usize, &'static str);
#[derive(Component)]
struct MyComponent(Handle<MyAsset>);
impl AsAssetId for MyComponent {
type Asset = MyAsset;
fn as_asset_id(&self) -> AssetId<Self::Asset> {
self.0.id()
}
}
fn run_app<Marker>(system: impl IntoSystem<(), (), Marker>) {
let mut app = create_app().0;
app.init_asset::<MyAsset>().add_systems(Update, system);
app.update();
}
// According to a comment in QueryState::new in bevy_ecs, components on filter
// position shouldn't conflict with components on query position.
#[test]
fn handle_filter_pos_ok() {
fn compatible_filter(
_query: Query<&mut MyComponent, AssetChanged<MyComponent>>,
mut exit: MessageWriter<AppExit>,
) {
exit.write(AppExit::Error(NonZero::<u8>::MIN));
}
run_app(compatible_filter);
}
#[derive(Default, PartialEq, Debug, Resource)]
struct Counter(Vec<u32>);
fn count_update(
mut counter: ResMut<Counter>,
assets: Res<Assets<MyAsset>>,
query: Query<&MyComponent, AssetChanged<MyComponent>>,
) {
for handle in query.iter() {
let asset = assets.get(&handle.0).unwrap();
counter.0[asset.0] += 1;
}
}
fn update_some(mut assets: ResMut<Assets<MyAsset>>, mut run_count: Local<u32>) {
let mut update_index = |i| {
let id = assets
.iter()
.find_map(|(h, a)| (a.0 == i).then_some(h))
.unwrap();
let asset = assets.get_mut(id).unwrap();
println!("setting new value for {}", asset.0);
asset.1 = "new_value";
};
match *run_count {
0 | 1 => update_index(0),
2 => {}
3 => {
update_index(0);
update_index(1);
}
4.. => update_index(1),
};
*run_count += 1;
}
fn add_some(
mut assets: ResMut<Assets<MyAsset>>,
mut cmds: Commands,
mut run_count: Local<u32>,
) {
match *run_count {
1 => {
cmds.spawn(MyComponent(assets.add(MyAsset(0, "init"))));
}
0 | 2 => {}
3 => {
cmds.spawn(MyComponent(assets.add(MyAsset(1, "init"))));
cmds.spawn(MyComponent(assets.add(MyAsset(2, "init"))));
}
4.. => {
cmds.spawn(MyComponent(assets.add(MyAsset(3, "init"))));
}
};
*run_count += 1;
}
#[track_caller]
fn assert_counter(app: &App, assert: Counter) {
assert_eq!(&assert, app.world().resource::<Counter>());
}
#[test]
fn added() {
let mut app = create_app().0;
app.init_asset::<MyAsset>()
.insert_resource(Counter(vec![0, 0, 0, 0]))
.add_systems(Update, add_some)
.add_systems(PostUpdate, count_update.after(AssetEventSystems));
// First run of the app, `add_systems(Startup…)` runs.
app.update(); // run_count == 0
assert_counter(&app, Counter(vec![0, 0, 0, 0]));
app.update(); // run_count == 1
assert_counter(&app, Counter(vec![1, 0, 0, 0]));
app.update(); // run_count == 2
assert_counter(&app, Counter(vec![1, 0, 0, 0]));
app.update(); // run_count == 3
assert_counter(&app, Counter(vec![1, 1, 1, 0]));
app.update(); // run_count == 4
assert_counter(&app, Counter(vec![1, 1, 1, 1]));
}
#[test]
fn changed() {
let mut app = create_app().0;
app.init_asset::<MyAsset>()
.insert_resource(Counter(vec![0, 0]))
.add_systems(
Startup,
|mut cmds: Commands, mut assets: ResMut<Assets<MyAsset>>| {
let asset0 = assets.add(MyAsset(0, "init"));
let asset1 = assets.add(MyAsset(1, "init"));
cmds.spawn(MyComponent(asset0.clone()));
cmds.spawn(MyComponent(asset0));
cmds.spawn(MyComponent(asset1.clone()));
cmds.spawn(MyComponent(asset1.clone()));
cmds.spawn(MyComponent(asset1));
},
)
.add_systems(Update, update_some)
.add_systems(PostUpdate, count_update.after(AssetEventSystems));
// First run of the app, `add_systems(Startup…)` runs.
app.update(); // run_count == 0
// First run: We count the entities that were added in the `Startup` schedule
assert_counter(&app, Counter(vec![2, 3]));
// Second run: `update_once` updates the first asset, which is
// associated with two entities, so `count_update` picks up two updates
app.update(); // run_count == 1
assert_counter(&app, Counter(vec![4, 3]));
// Third run: `update_once` doesn't update anything, same values as last
app.update(); // run_count == 2
assert_counter(&app, Counter(vec![4, 3]));
// Fourth run: We update the two assets (asset 0: 2 entities, asset 1: 3)
app.update(); // run_count == 3
assert_counter(&app, Counter(vec![6, 6]));
// Fifth run: only update second asset
app.update(); // run_count == 4
assert_counter(&app, Counter(vec![6, 9]));
// ibid
app.update(); // run_count == 5
assert_counter(&app, Counter(vec![6, 12]));
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/path.rs | crates/bevy_asset/src/path.rs | use crate::io::AssetSourceId;
use alloc::{
borrow::ToOwned,
string::{String, ToString},
};
use atomicow::CowArc;
use bevy_reflect::{Reflect, ReflectDeserialize, ReflectSerialize};
use core::{
fmt::{Debug, Display},
hash::Hash,
ops::Deref,
};
use serde::{de::Visitor, Deserialize, Serialize};
use std::path::{Path, PathBuf};
use thiserror::Error;
/// Represents a path to an asset in a "virtual filesystem".
///
/// Asset paths consist of three main parts:
/// * [`AssetPath::source`]: The name of the [`AssetSource`](crate::io::AssetSource) to load the asset from.
/// This is optional. If one is not set the default source will be used (which is the `assets` folder by default).
/// * [`AssetPath::path`]: The "virtual filesystem path" pointing to an asset source file.
/// * [`AssetPath::label`]: An optional "named sub asset". When assets are loaded, they are
/// allowed to load "sub assets" of any type, which are identified by a named "label".
///
/// Asset paths are generally constructed (and visualized) as strings:
///
/// ```no_run
/// # use bevy_asset::{Asset, AssetServer, Handle};
/// # use bevy_reflect::TypePath;
/// #
/// # #[derive(Asset, TypePath, Default)]
/// # struct Mesh;
/// #
/// # #[derive(Asset, TypePath, Default)]
/// # struct Scene;
/// #
/// # let asset_server: AssetServer = panic!();
/// // This loads the `my_scene.scn` base asset from the default asset source.
/// let scene: Handle<Scene> = asset_server.load("my_scene.scn");
///
/// // This loads the `PlayerMesh` labeled asset from the `my_scene.scn` base asset in the default asset source.
/// let mesh: Handle<Mesh> = asset_server.load("my_scene.scn#PlayerMesh");
///
/// // This loads the `my_scene.scn` base asset from a custom 'remote' asset source.
/// let scene: Handle<Scene> = asset_server.load("remote://my_scene.scn");
/// ```
///
/// [`AssetPath`] implements [`From`] for `&'static str`, `&'static Path`, and `&'a String`,
/// which allows us to optimize the static cases.
/// This means that the common case of `asset_server.load("my_scene.scn")` when it creates and
/// clones internal owned [`AssetPaths`](AssetPath).
/// This also means that you should use [`AssetPath::parse`] in cases where `&str` is the explicit type.
#[derive(Eq, PartialEq, Hash, Clone, Default, Reflect)]
#[reflect(opaque)]
#[reflect(Debug, PartialEq, Hash, Clone, Serialize, Deserialize)]
pub struct AssetPath<'a> {
source: AssetSourceId<'a>,
path: CowArc<'a, Path>,
label: Option<CowArc<'a, str>>,
}
impl<'a> Debug for AssetPath<'a> {
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 core::fmt::Formatter<'_>) -> core::fmt::Result {
if let AssetSourceId::Name(name) = self.source() {
write!(f, "{name}://")?;
}
write!(f, "{}", self.path.display())?;
if let Some(label) = &self.label {
write!(f, "#{label}")?;
}
Ok(())
}
}
/// An error that occurs when parsing a string type to create an [`AssetPath`] fails, such as during [`AssetPath::parse`].
#[derive(Error, Debug, PartialEq, Eq)]
pub enum ParseAssetPathError {
/// Error that occurs when the [`AssetPath::source`] section of a path string contains the [`AssetPath::label`] delimiter `#`. E.g. `bad#source://file.test`.
#[error("Asset source must not contain a `#` character")]
InvalidSourceSyntax,
/// Error that occurs when the [`AssetPath::label`] section of a path string contains the [`AssetPath::source`] delimiter `://`. E.g. `source://file.test#bad://label`.
#[error("Asset label must not contain a `://` substring")]
InvalidLabelSyntax,
/// Error that occurs when a path string has an [`AssetPath::source`] delimiter `://` with no characters preceding it. E.g. `://file.test`.
#[error("Asset source must be at least one character. Either specify the source before the '://' or remove the `://`")]
MissingSource,
/// Error that occurs when a path string has an [`AssetPath::label`] delimiter `#` with no characters succeeding it. E.g. `file.test#`
#[error("Asset label must be at least one character. Either specify the label after the '#' or remove the '#'")]
MissingLabel,
}
impl<'a> AssetPath<'a> {
/// Creates a new [`AssetPath`] from a string in the asset path format:
/// * An asset at the root: `"scene.gltf"`
/// * An asset nested in some folders: `"some/path/scene.gltf"`
/// * An asset with a "label": `"some/path/scene.gltf#Mesh0"`
/// * An asset with a custom "source": `"custom://some/path/scene.gltf#Mesh0"`
///
/// Prefer [`From<'static str>`] for static strings, as this will prevent allocations
/// and reference counting for [`AssetPath::into_owned`].
///
/// # Panics
/// Panics if the asset path is in an invalid format. Use [`AssetPath::try_parse`] for a fallible variant
pub fn parse(asset_path: &'a str) -> AssetPath<'a> {
Self::try_parse(asset_path).unwrap()
}
/// Creates a new [`AssetPath`] from a string in the asset path format:
/// * An asset at the root: `"scene.gltf"`
/// * An asset nested in some folders: `"some/path/scene.gltf"`
/// * An asset with a "label": `"some/path/scene.gltf#Mesh0"`
/// * An asset with a custom "source": `"custom://some/path/scene.gltf#Mesh0"`
///
/// Prefer [`From<'static str>`] for static strings, as this will prevent allocations
/// and reference counting for [`AssetPath::into_owned`].
///
/// This will return a [`ParseAssetPathError`] if `asset_path` is in an invalid format.
pub fn try_parse(asset_path: &'a str) -> Result<AssetPath<'a>, ParseAssetPathError> {
let (source, path, label) = Self::parse_internal(asset_path)?;
Ok(Self {
source: match source {
Some(source) => AssetSourceId::Name(CowArc::Borrowed(source)),
None => AssetSourceId::Default,
},
path: CowArc::Borrowed(path),
label: label.map(CowArc::Borrowed),
})
}
// Attempts to Parse a &str into an `AssetPath`'s `AssetPath::source`, `AssetPath::path`, and `AssetPath::label` components.
fn parse_internal(
asset_path: &str,
) -> Result<(Option<&str>, &Path, Option<&str>), ParseAssetPathError> {
let chars = asset_path.char_indices();
let mut source_range = None;
let mut path_range = 0..asset_path.len();
let mut label_range = None;
// Loop through the characters of the passed in &str to accomplish the following:
// 1. Search for the first instance of the `://` substring. If the `://` substring is found,
// store the range of indices representing everything before the `://` substring as the `source_range`.
// 2. Search for the last instance of the `#` character. If the `#` character is found,
// store the range of indices representing everything after the `#` character as the `label_range`
// 3. Set the `path_range` to be everything in between the `source_range` and `label_range`,
// excluding the `://` substring and `#` character.
// 4. Verify that there are no `#` characters in the `AssetPath::source` and no `://` substrings in the `AssetPath::label`
let mut source_delimiter_chars_matched = 0;
let mut last_found_source_index = 0;
for (index, char) in chars {
match char {
':' => {
source_delimiter_chars_matched = 1;
}
'/' => {
match source_delimiter_chars_matched {
1 => {
source_delimiter_chars_matched = 2;
}
2 => {
// If we haven't found our first `AssetPath::source` yet, check to make sure it is valid and then store it.
if source_range.is_none() {
// If the `AssetPath::source` contains a `#` character, it is invalid.
if label_range.is_some() {
return Err(ParseAssetPathError::InvalidSourceSyntax);
}
source_range = Some(0..index - 2);
path_range.start = index + 1;
}
last_found_source_index = index - 2;
source_delimiter_chars_matched = 0;
}
_ => {}
}
}
'#' => {
path_range.end = index;
label_range = Some(index + 1..asset_path.len());
source_delimiter_chars_matched = 0;
}
_ => {
source_delimiter_chars_matched = 0;
}
}
}
// If we found an `AssetPath::label`
if let Some(range) = label_range.clone() {
// If the `AssetPath::label` contained a `://` substring, it is invalid.
if range.start <= last_found_source_index {
return Err(ParseAssetPathError::InvalidLabelSyntax);
}
}
// Try to parse the range of indices that represents the `AssetPath::source` portion of the `AssetPath` to make sure it is not empty.
// This would be the case if the input &str was something like `://some/file.test`
let source = match source_range {
Some(source_range) => {
if source_range.is_empty() {
return Err(ParseAssetPathError::MissingSource);
}
Some(&asset_path[source_range])
}
None => None,
};
// Try to parse the range of indices that represents the `AssetPath::label` portion of the `AssetPath` to make sure it is not empty.
// This would be the case if the input &str was something like `some/file.test#`.
let label = match label_range {
Some(label_range) => {
if label_range.is_empty() {
return Err(ParseAssetPathError::MissingLabel);
}
Some(&asset_path[label_range])
}
None => None,
};
let path = Path::new(&asset_path[path_range]);
Ok((source, path, label))
}
/// Creates a new [`AssetPath`] from a [`PathBuf`].
#[inline]
pub fn from_path_buf(path_buf: PathBuf) -> AssetPath<'a> {
AssetPath {
path: CowArc::Owned(path_buf.into()),
source: AssetSourceId::Default,
label: None,
}
}
/// Creates a new [`AssetPath`] from a [`Path`].
#[inline]
pub fn from_path(path: &'a Path) -> AssetPath<'a> {
AssetPath {
path: CowArc::Borrowed(path),
source: AssetSourceId::Default,
label: None,
}
}
/// Gets the "asset source", if one was defined. If none was defined, the default source
/// will be used.
#[inline]
pub fn source(&self) -> &AssetSourceId<'_> {
&self.source
}
/// Gets the "sub-asset label".
#[inline]
pub fn label(&self) -> Option<&str> {
self.label.as_deref()
}
/// Gets the "sub-asset label".
#[inline]
pub fn label_cow(&self) -> Option<CowArc<'a, str>> {
self.label.clone()
}
/// Gets the path to the asset in the "virtual filesystem".
#[inline]
pub fn path(&self) -> &Path {
self.path.deref()
}
/// Gets the path to the asset in the "virtual filesystem" without a label (if a label is currently set).
#[inline]
pub fn without_label(&self) -> AssetPath<'_> {
Self {
source: self.source.clone(),
path: self.path.clone(),
label: None,
}
}
/// Removes a "sub-asset label" from this [`AssetPath`], if one was set.
#[inline]
pub fn remove_label(&mut self) {
self.label = None;
}
/// Takes the "sub-asset label" from this [`AssetPath`], if one was set.
#[inline]
pub fn take_label(&mut self) -> Option<CowArc<'a, str>> {
self.label.take()
}
/// Returns this asset path with the given label. This will replace the previous
/// label if it exists.
#[inline]
pub fn with_label(self, label: impl Into<CowArc<'a, str>>) -> AssetPath<'a> {
AssetPath {
source: self.source,
path: self.path,
label: Some(label.into()),
}
}
/// Returns this asset path with the given asset source. This will replace the previous asset
/// source if it exists.
#[inline]
pub fn with_source(self, source: impl Into<AssetSourceId<'a>>) -> AssetPath<'a> {
AssetPath {
source: source.into(),
path: self.path,
label: self.label,
}
}
/// Returns an [`AssetPath`] for the parent folder of this path, if there is a parent folder in the path.
pub fn parent(&self) -> Option<AssetPath<'a>> {
let path = match &self.path {
CowArc::Borrowed(path) => CowArc::Borrowed(path.parent()?),
CowArc::Static(path) => CowArc::Static(path.parent()?),
CowArc::Owned(path) => path.parent()?.to_path_buf().into(),
};
Some(AssetPath {
source: self.source.clone(),
label: None,
path,
})
}
/// Converts this into an "owned" value. If internally a value is borrowed, it will be cloned into an "owned [`Arc`]".
/// If internally a value is a static reference, the static reference will be used unchanged.
/// If internally a value is an "owned [`Arc`]", it will remain unchanged.
///
/// [`Arc`]: alloc::sync::Arc
pub fn into_owned(self) -> AssetPath<'static> {
AssetPath {
source: self.source.into_owned(),
path: self.path.into_owned(),
label: self.label.map(CowArc::into_owned),
}
}
/// Clones this into an "owned" value. If internally a value is borrowed, it will be cloned into an "owned [`Arc`]".
/// If internally a value is a static reference, the static reference will be used unchanged.
/// If internally a value is an "owned [`Arc`]", the [`Arc`] will be cloned.
///
/// [`Arc`]: alloc::sync::Arc
#[inline]
pub fn clone_owned(&self) -> AssetPath<'static> {
self.clone().into_owned()
}
/// Resolves a relative asset path via concatenation. The result will be an `AssetPath` which
/// is resolved relative to this "base" path.
///
/// ```
/// # use bevy_asset::AssetPath;
/// assert_eq!(AssetPath::parse("a/b").resolve("c"), Ok(AssetPath::parse("a/b/c")));
/// assert_eq!(AssetPath::parse("a/b").resolve("./c"), Ok(AssetPath::parse("a/b/c")));
/// assert_eq!(AssetPath::parse("a/b").resolve("../c"), Ok(AssetPath::parse("a/c")));
/// assert_eq!(AssetPath::parse("a/b").resolve("c.png"), Ok(AssetPath::parse("a/b/c.png")));
/// assert_eq!(AssetPath::parse("a/b").resolve("/c"), Ok(AssetPath::parse("c")));
/// assert_eq!(AssetPath::parse("a/b.png").resolve("#c"), Ok(AssetPath::parse("a/b.png#c")));
/// assert_eq!(AssetPath::parse("a/b.png#c").resolve("#d"), Ok(AssetPath::parse("a/b.png#d")));
/// ```
///
/// There are several cases:
///
/// If the `path` argument begins with `#`, then it is considered an asset label, in which case
/// the result is the base path with the label portion replaced.
///
/// If the path argument begins with '/', then it is considered a 'full' path, in which
/// case the result is a new `AssetPath` consisting of the base path asset source
/// (if there is one) with the path and label portions of the relative path. Note that a 'full'
/// asset path is still relative to the asset source root, and not necessarily an absolute
/// filesystem path.
///
/// If the `path` argument begins with an asset source (ex: `http://`) then the entire base
/// path is replaced - the result is the source, path and label (if any) of the `path`
/// argument.
///
/// Otherwise, the `path` argument is considered a relative path. The result is concatenated
/// using the following algorithm:
///
/// * The base path and the `path` argument are concatenated.
/// * Path elements consisting of "/." or "<name>/.." are removed.
///
/// If there are insufficient segments in the base path to match the ".." segments,
/// then any left-over ".." segments are left as-is.
pub fn resolve(&self, path: &str) -> Result<AssetPath<'static>, ParseAssetPathError> {
self.resolve_internal(path, false)
}
/// Resolves an embedded asset path via concatenation. The result will be an `AssetPath` which
/// is resolved relative to this path. This is similar in operation to `resolve`, except that
/// the 'file' portion of the base path (that is, any characters after the last '/')
/// is removed before concatenation, in accordance with the behavior specified in
/// IETF RFC 1808 "Relative URIs".
///
/// The reason for this behavior is that embedded URIs which start with "./" or "../" are
/// relative to the *directory* containing the asset, not the asset file. This is consistent
/// with the behavior of URIs in `JavaScript`, CSS, HTML and other web file formats. The
/// primary use case for this method is resolving relative paths embedded within asset files,
/// which are relative to the asset in which they are contained.
///
/// ```
/// # use bevy_asset::AssetPath;
/// assert_eq!(AssetPath::parse("a/b").resolve_embed("c"), Ok(AssetPath::parse("a/c")));
/// assert_eq!(AssetPath::parse("a/b").resolve_embed("./c"), Ok(AssetPath::parse("a/c")));
/// assert_eq!(AssetPath::parse("a/b").resolve_embed("../c"), Ok(AssetPath::parse("c")));
/// assert_eq!(AssetPath::parse("a/b").resolve_embed("c.png"), Ok(AssetPath::parse("a/c.png")));
/// assert_eq!(AssetPath::parse("a/b").resolve_embed("/c"), Ok(AssetPath::parse("c")));
/// assert_eq!(AssetPath::parse("a/b.png").resolve_embed("#c"), Ok(AssetPath::parse("a/b.png#c")));
/// assert_eq!(AssetPath::parse("a/b.png#c").resolve_embed("#d"), Ok(AssetPath::parse("a/b.png#d")));
/// ```
pub fn resolve_embed(&self, path: &str) -> Result<AssetPath<'static>, ParseAssetPathError> {
self.resolve_internal(path, true)
}
fn resolve_internal(
&self,
path: &str,
replace: bool,
) -> Result<AssetPath<'static>, ParseAssetPathError> {
if let Some(label) = path.strip_prefix('#') {
// It's a label only
Ok(self.clone_owned().with_label(label.to_owned()))
} else {
let (source, rpath, rlabel) = AssetPath::parse_internal(path)?;
let mut base_path = PathBuf::from(self.path());
if replace && !self.path.to_str().unwrap().ends_with('/') {
// No error if base is empty (per RFC 1808).
base_path.pop();
}
// Strip off leading slash
let mut is_absolute = false;
let rpath = match rpath.strip_prefix("/") {
Ok(p) => {
is_absolute = true;
p
}
_ => rpath,
};
let mut result_path = if !is_absolute && source.is_none() {
base_path
} else {
PathBuf::new()
};
result_path.push(rpath);
result_path = normalize_path(result_path.as_path());
Ok(AssetPath {
source: match source {
Some(source) => AssetSourceId::Name(CowArc::Owned(source.into())),
None => self.source.clone_owned(),
},
path: CowArc::Owned(result_path.into()),
label: rlabel.map(|l| CowArc::Owned(l.into())),
})
}
}
/// Returns the full extension (including multiple '.' values).
/// Ex: Returns `"config.ron"` for `"my_asset.config.ron"`
///
/// Also strips out anything following a `?` to handle query parameters in URIs
pub fn get_full_extension(&self) -> Option<String> {
let file_name = self.path().file_name()?.to_str()?;
let index = file_name.find('.')?;
let mut extension = file_name[index + 1..].to_owned();
// Strip off any query parameters
let query = extension.find('?');
if let Some(offset) = query {
extension.truncate(offset);
}
Some(extension)
}
pub(crate) fn iter_secondary_extensions(full_extension: &str) -> impl Iterator<Item = &str> {
full_extension.char_indices().filter_map(|(i, c)| {
if c == '.' {
Some(&full_extension[i + 1..])
} else {
None
}
})
}
/// Returns `true` if this [`AssetPath`] points to a file that is
/// outside of its [`AssetSource`](crate::io::AssetSource) folder.
///
/// ## Example
/// ```
/// # use bevy_asset::AssetPath;
/// // Inside the default AssetSource.
/// let path = AssetPath::parse("thingy.png");
/// assert!( ! path.is_unapproved());
/// let path = AssetPath::parse("gui/thingy.png");
/// assert!( ! path.is_unapproved());
///
/// // Inside a different AssetSource.
/// let path = AssetPath::parse("embedded://thingy.png");
/// assert!( ! path.is_unapproved());
///
/// // Exits the `AssetSource`s directory.
/// let path = AssetPath::parse("../thingy.png");
/// assert!(path.is_unapproved());
/// let path = AssetPath::parse("folder/../../thingy.png");
/// assert!(path.is_unapproved());
///
/// // This references the linux root directory.
/// let path = AssetPath::parse("/home/thingy.png");
/// assert!(path.is_unapproved());
/// ```
pub fn is_unapproved(&self) -> bool {
use std::path::Component;
let mut simplified = PathBuf::new();
for component in self.path.components() {
match component {
Component::Prefix(_) | Component::RootDir => return true,
Component::CurDir => {}
Component::ParentDir => {
if !simplified.pop() {
return true;
}
}
Component::Normal(os_str) => simplified.push(os_str),
}
}
false
}
}
// This is only implemented for static lifetimes to ensure `Path::clone` does not allocate
// by ensuring that this is stored as a `CowArc::Static`.
// Please read https://github.com/bevyengine/bevy/issues/19844 before changing this!
impl From<&'static str> for AssetPath<'static> {
#[inline]
fn from(asset_path: &'static str) -> Self {
let (source, path, label) = Self::parse_internal(asset_path).unwrap();
AssetPath {
source: source.into(),
path: CowArc::Static(path),
label: label.map(CowArc::Static),
}
}
}
impl<'a> From<&'a String> for AssetPath<'a> {
#[inline]
fn from(asset_path: &'a String) -> Self {
AssetPath::parse(asset_path.as_str())
}
}
impl From<String> for AssetPath<'static> {
#[inline]
fn from(asset_path: String) -> Self {
AssetPath::parse(asset_path.as_str()).into_owned()
}
}
impl From<&'static Path> for AssetPath<'static> {
#[inline]
fn from(path: &'static Path) -> Self {
Self {
source: AssetSourceId::Default,
path: CowArc::Static(path),
label: None,
}
}
}
impl From<PathBuf> for AssetPath<'static> {
#[inline]
fn from(path: PathBuf) -> Self {
Self {
source: AssetSourceId::Default,
path: path.into(),
label: None,
}
}
}
impl<'a, 'b> From<&'a AssetPath<'b>> for AssetPath<'b> {
fn from(value: &'a AssetPath<'b>) -> Self {
value.clone()
}
}
impl<'a> From<AssetPath<'a>> for PathBuf {
fn from(value: AssetPath<'a>) -> Self {
value.path().to_path_buf()
}
}
impl<'a> Serialize for AssetPath<'a> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.to_string().serialize(serializer)
}
}
impl<'de> Deserialize<'de> for AssetPath<'static> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
deserializer.deserialize_string(AssetPathVisitor)
}
}
struct AssetPathVisitor;
impl<'de> Visitor<'de> for AssetPathVisitor {
type Value = AssetPath<'static>;
fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
formatter.write_str("string AssetPath")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(AssetPath::parse(v).into_owned())
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(AssetPath::from(v))
}
}
/// Normalizes the path by collapsing all occurrences of '.' and '..' dot-segments where possible
/// as per [RFC 1808](https://datatracker.ietf.org/doc/html/rfc1808)
pub(crate) fn normalize_path(path: &Path) -> PathBuf {
let mut result_path = PathBuf::new();
for elt in path.iter() {
if elt == "." {
// Skip
} else if elt == ".." {
// Note: If the result_path ends in `..`, Path::file_name returns None, so we'll end up
// preserving it.
if result_path.file_name().is_some() {
// This assert is just a sanity check - we already know the path has a file_name, so
// we know there is something to pop.
assert!(result_path.pop());
} else {
// Preserve ".." if insufficient matches (per RFC 1808).
result_path.push(elt);
}
} else {
result_path.push(elt);
}
}
result_path
}
#[cfg(test)]
mod tests {
use crate::AssetPath;
use alloc::string::ToString;
use std::path::Path;
#[test]
fn parse_asset_path() {
let result = AssetPath::parse_internal("a/b.test");
assert_eq!(result, Ok((None, Path::new("a/b.test"), None)));
let result = AssetPath::parse_internal("http://a/b.test");
assert_eq!(result, Ok((Some("http"), Path::new("a/b.test"), None)));
let result = AssetPath::parse_internal("http://a/b.test#Foo");
assert_eq!(
result,
Ok((Some("http"), Path::new("a/b.test"), Some("Foo")))
);
let result = AssetPath::parse_internal("localhost:80/b.test");
assert_eq!(result, Ok((None, Path::new("localhost:80/b.test"), None)));
let result = AssetPath::parse_internal("http://localhost:80/b.test");
assert_eq!(
result,
Ok((Some("http"), Path::new("localhost:80/b.test"), None))
);
let result = AssetPath::parse_internal("http://localhost:80/b.test#Foo");
assert_eq!(
result,
Ok((Some("http"), Path::new("localhost:80/b.test"), Some("Foo")))
);
let result = AssetPath::parse_internal("#insource://a/b.test");
assert_eq!(result, Err(crate::ParseAssetPathError::InvalidSourceSyntax));
let result = AssetPath::parse_internal("source://a/b.test#://inlabel");
assert_eq!(result, Err(crate::ParseAssetPathError::InvalidLabelSyntax));
let result = AssetPath::parse_internal("#insource://a/b.test#://inlabel");
assert!(
result == Err(crate::ParseAssetPathError::InvalidSourceSyntax)
|| result == Err(crate::ParseAssetPathError::InvalidLabelSyntax)
);
let result = AssetPath::parse_internal("http://");
assert_eq!(result, Ok((Some("http"), Path::new(""), None)));
let result = AssetPath::parse_internal("://x");
assert_eq!(result, Err(crate::ParseAssetPathError::MissingSource));
let result = AssetPath::parse_internal("a/b.test#");
assert_eq!(result, Err(crate::ParseAssetPathError::MissingLabel));
}
#[test]
fn test_parent() {
// Parent consumes path segments, returns None when insufficient
let result = AssetPath::from("a/b.test");
assert_eq!(result.parent(), Some(AssetPath::from("a")));
assert_eq!(result.parent().unwrap().parent(), Some(AssetPath::from("")));
assert_eq!(result.parent().unwrap().parent().unwrap().parent(), None);
// Parent cannot consume asset source
let result = AssetPath::from("http://a");
assert_eq!(result.parent(), Some(AssetPath::from("http://")));
assert_eq!(result.parent().unwrap().parent(), None);
// Parent consumes labels
let result = AssetPath::from("http://a#Foo");
assert_eq!(result.parent(), Some(AssetPath::from("http://")));
}
#[test]
fn test_with_source() {
let result = AssetPath::from("http://a#Foo");
assert_eq!(result.with_source("ftp"), AssetPath::from("ftp://a#Foo"));
}
#[test]
fn test_without_label() {
let result = AssetPath::from("http://a#Foo");
assert_eq!(result.without_label(), AssetPath::from("http://a"));
}
#[test]
fn test_resolve_full() {
// A "full" path should ignore the base path.
let base = AssetPath::from("alice/bob#carol");
assert_eq!(
base.resolve("/joe/next").unwrap(),
AssetPath::from("joe/next")
);
assert_eq!(
base.resolve_embed("/joe/next").unwrap(),
AssetPath::from("joe/next")
);
assert_eq!(
base.resolve("/joe/next#dave").unwrap(),
AssetPath::from("joe/next#dave")
);
assert_eq!(
base.resolve_embed("/joe/next#dave").unwrap(),
AssetPath::from("joe/next#dave")
);
}
#[test]
fn test_resolve_implicit_relative() {
// A path with no initial directory separator should be considered relative.
let base = AssetPath::from("alice/bob#carol");
assert_eq!(
base.resolve("joe/next").unwrap(),
AssetPath::from("alice/bob/joe/next")
);
assert_eq!(
base.resolve_embed("joe/next").unwrap(),
AssetPath::from("alice/joe/next")
);
assert_eq!(
base.resolve("joe/next#dave").unwrap(),
AssetPath::from("alice/bob/joe/next#dave")
);
assert_eq!(
base.resolve_embed("joe/next#dave").unwrap(),
AssetPath::from("alice/joe/next#dave")
);
}
#[test]
fn test_resolve_explicit_relative() {
// A path which begins with "./" or "../" is treated as relative
let base = AssetPath::from("alice/bob#carol");
assert_eq!(
base.resolve("./martin#dave").unwrap(),
AssetPath::from("alice/bob/martin#dave")
);
assert_eq!(
base.resolve_embed("./martin#dave").unwrap(),
AssetPath::from("alice/martin#dave")
);
assert_eq!(
base.resolve("../martin#dave").unwrap(),
AssetPath::from("alice/martin#dave")
);
assert_eq!(
base.resolve_embed("../martin#dave").unwrap(),
AssetPath::from("martin#dave")
);
}
#[test]
fn test_resolve_trailing_slash() {
// A path which begins with "./" or "../" is treated as relative
let base = AssetPath::from("alice/bob/");
assert_eq!(
base.resolve("./martin#dave").unwrap(),
AssetPath::from("alice/bob/martin#dave")
);
assert_eq!(
base.resolve_embed("./martin#dave").unwrap(),
AssetPath::from("alice/bob/martin#dave")
);
assert_eq!(
base.resolve("../martin#dave").unwrap(),
AssetPath::from("alice/martin#dave")
);
assert_eq!(
base.resolve_embed("../martin#dave").unwrap(),
AssetPath::from("alice/martin#dave")
);
}
#[test]
fn test_resolve_canonicalize() {
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/lib.rs | crates/bevy_asset/src/lib.rs | //! In the context of game development, an "asset" is a piece of content that is loaded from disk and displayed in the game.
//! Typically, these are authored by artists and designers (in contrast to code),
//! are relatively large in size, and include everything from textures and models to sounds and music to levels and scripts.
//!
//! This presents two main challenges:
//! - Assets take up a lot of memory; simply storing a copy for each instance of an asset in the game would be prohibitively expensive.
//! - Loading assets from disk is slow, and can cause long load times and delays.
//!
//! These problems play into each other, for if assets are expensive to store in memory,
//! then larger game worlds will need to load them from disk as needed, ideally without a loading screen.
//!
//! As is common in Rust, non-blocking asset loading is done using `async`, with background tasks used to load assets while the game is running.
//! Bevy coordinates these tasks using the [`AssetServer`] resource, storing each loaded asset in a strongly-typed [`Assets<T>`] collection (also a resource).
//! [`Handle`]s serve as an id-based reference to entries in the [`Assets`] collection, allowing them to be cheaply shared between systems,
//! and providing a way to initialize objects (generally entities) before the required assets are loaded.
//! In short: [`Handle`]s are not the assets themselves, they just tell how to look them up!
//!
//! ## Loading assets
//!
//! The [`AssetServer`] is the main entry point for loading assets.
//! Typically, you'll use the [`AssetServer::load`] method to load an asset from disk, which returns a [`Handle`].
//! Note that this method does not attempt to reload the asset if it has already been loaded: as long as at least one handle has not been dropped,
//! calling [`AssetServer::load`] on the same path will return the same handle.
//! The handle that's returned can be used to instantiate various [`Component`]s that require asset data to function,
//! which will then be spawned into the world as part of an entity.
//!
//! To avoid assets "popping" into existence, you may want to check that all of the required assets are loaded before transitioning to a new scene.
//! This can be done by checking the [`LoadState`] of the asset handle using [`AssetServer::is_loaded_with_dependencies`],
//! which will be `true` when the asset is ready to use.
//!
//! Keep track of what you're waiting on by using a [`HashSet`] of asset handles or similar data structure,
//! which iterate over and poll in your update loop, and transition to the new scene once all assets are loaded.
//! Bevy's built-in states system can be very helpful for this!
//!
//! # Modifying entities that use assets
//!
//! If we later want to change the asset data a given component uses (such as changing an entity's material), we have three options:
//!
//! 1. Change the handle stored on the responsible component to the handle of a different asset
//! 2. Despawn the entity and spawn a new one with the new asset data.
//! 3. Use the [`Assets`] collection to directly modify the current handle's asset data
//!
//! The first option is the most common: just query for the component that holds the handle, and mutate it, pointing to the new asset.
//! Check how the handle was passed in to the entity when it was spawned: if a mesh-related component required a handle to a mesh asset,
//! you'll need to find that component via a query and change the handle to the new mesh asset.
//! This is so commonly done that you should think about strategies for how to store and swap handles in your game.
//!
//! The second option is the simplest, but can be slow if done frequently,
//! and can lead to frustrating bugs as references to the old entity (such as what is targeting it) and other data on the entity are lost.
//! Generally, this isn't a great strategy.
//!
//! The third option has different semantics: rather than modifying the asset data for a single entity, it modifies the asset data for *all* entities using this handle.
//! While this might be what you want, it generally isn't!
//!
//! # Hot reloading assets
//!
//! Bevy supports asset hot reloading, allowing you to change assets on disk and see the changes reflected in your game without restarting.
//! When enabled, any changes to the underlying asset file will be detected by the [`AssetServer`], which will then reload the asset,
//! mutating the asset data in the [`Assets`] collection and thus updating all entities that use the asset.
//! While it has limited uses in published games, it is very useful when developing, as it allows you to iterate quickly.
//!
//! To enable asset hot reloading on desktop platforms, enable `bevy`'s `file_watcher` cargo feature.
//! To toggle it at runtime, you can use the `watch_for_changes_override` field in the [`AssetPlugin`] to enable or disable hot reloading.
//!
//! # Procedural asset creation
//!
//! Not all assets are loaded from disk: some are generated at runtime, such as procedural materials, sounds or even levels.
//! After creating an item of a type that implements [`Asset`], you can add it to the [`Assets`] collection using [`Assets::add`].
//! Once in the asset collection, this data can be operated on like any other asset.
//!
//! Note that, unlike assets loaded from a file path, no general mechanism currently exists to deduplicate procedural assets:
//! calling [`Assets::add`] for every entity that needs the asset will create a new copy of the asset for each entity,
//! quickly consuming memory.
//!
//! ## Handles and reference counting
//!
//! [`Handle`] (or their untyped counterpart [`UntypedHandle`]) are used to reference assets in the [`Assets`] collection,
//! and are the primary way to interact with assets in Bevy.
//! As a user, you'll be working with handles a lot!
//!
//! The most important thing to know about handles is that they are reference counted: when you clone a handle, you're incrementing a reference count.
//! When the object holding the handle is dropped (generally because an entity was despawned), the reference count is decremented.
//! When the reference count hits zero, the asset it references is removed from the [`Assets`] collection.
//!
//! This reference counting is a simple, largely automatic way to avoid holding onto memory for game objects that are no longer in use.
//! However, it can lead to surprising behavior if you're not careful!
//!
//! There are two categories of problems to watch out for:
//! - never dropping a handle, causing the asset to never be removed from memory
//! - dropping a handle too early, causing the asset to be removed from memory while it's still in use
//!
//! The first problem is less critical for beginners, as for tiny games, you can often get away with simply storing all of the assets in memory at once,
//! and loading them all at the start of the game.
//! As your game grows, you'll need to be more careful about when you load and unload assets,
//! segmenting them by level or area, and loading them on-demand.
//! This problem generally arises when handles are stored in a persistent "collection" or "manifest" of possible objects (generally in a resource),
//! which is convenient for easy access and zero-latency spawning, but can result in high but stable memory usage.
//!
//! The second problem is more concerning, and looks like your models or textures suddenly disappearing from the game.
//! Debugging reveals that the *entities* are still there, but nothing is rendering!
//! This is because the assets were removed from memory while they were still in use.
//! You were probably too aggressive with the use of weak handles (which don't increment the reference count of the asset): think through the lifecycle of your assets carefully!
//! As soon as an asset is loaded, you must ensure that at least one strong handle is held to it until all matching entities are out of sight of the player.
//!
//! # Asset dependencies
//!
//! Some assets depend on other assets to be loaded before they can be loaded themselves.
//! For example, a 3D model might require both textures and meshes to be loaded,
//! or a 2D level might require a tileset to be loaded.
//!
//! The assets that are required to load another asset are called "dependencies".
//! An asset is only considered fully loaded when it and all of its dependencies are loaded.
//! Asset dependencies can be declared when implementing the [`Asset`] trait by implementing the [`VisitAssetDependencies`] trait,
//! and the `#[dependency]` attribute can be used to automatically derive this implementation.
//!
//! # Custom asset types
//!
//! While Bevy comes with implementations for a large number of common game-oriented asset types (often behind off-by-default feature flags!),
//! implementing a custom asset type can be useful when dealing with unusual, game-specific, or proprietary formats.
//!
//! Defining a new asset type is as simple as implementing the [`Asset`] trait.
//! This requires [`TypePath`] for metadata about the asset type,
//! and [`VisitAssetDependencies`] to track asset dependencies.
//! In simple cases, you can derive [`Asset`] and [`Reflect`] and be done with it: the required supertraits will be implemented for you.
//!
//! With a new asset type in place, we now need to figure out how to load it.
//! While [`AssetReader`](io::AssetReader) describes strategies to read asset bytes from various sources,
//! [`AssetLoader`] is the trait that actually turns those into your desired in-memory format.
//! Generally, (only) [`AssetLoader`] needs to be implemented for custom assets, as the [`AssetReader`](io::AssetReader) implementations are provided by Bevy.
//!
//! However, [`AssetLoader`] shouldn't be implemented for your asset type directly: instead, this is implemented for a "loader" type
//! that can store settings and any additional data required to load your asset, while your asset type is used as the [`AssetLoader::Asset`] associated type.
//! As the trait documentation explains, this allows various [`AssetLoader::Settings`] to be used to configure the loader.
//!
//! After the loader is implemented, it needs to be registered with the [`AssetServer`] using [`App::register_asset_loader`](AssetApp::register_asset_loader).
//! Once your asset type is loaded, you can use it in your game like any other asset type!
//!
//! If you want to save your assets back to disk, you should implement [`AssetSaver`](saver::AssetSaver) as well.
//! This trait mirrors [`AssetLoader`] in structure, and works in tandem with [`AssetWriter`](io::AssetWriter), which mirrors [`AssetReader`](io::AssetReader).
#![expect(missing_docs, reason = "Not all docs are written yet, see #3492.")]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc(
html_logo_url = "https://bevy.org/assets/icon.png",
html_favicon_url = "https://bevy.org/assets/icon.png"
)]
#![no_std]
extern crate alloc;
extern crate std;
// Required to make proc macros work in bevy itself.
extern crate self as bevy_asset;
pub mod io;
pub mod meta;
pub mod processor;
pub mod saver;
pub mod transformer;
/// The asset prelude.
///
/// This includes the most common types in this crate, re-exported for your convenience.
pub mod prelude {
#[doc(hidden)]
pub use crate::asset_changed::AssetChanged;
#[doc(hidden)]
pub use crate::{
Asset, AssetApp, AssetEvent, AssetId, AssetMode, AssetPlugin, AssetServer, Assets,
DirectAssetAccessExt, Handle, UntypedHandle,
};
}
mod asset_changed;
mod assets;
mod direct_access_ext;
mod event;
mod folder;
mod handle;
mod id;
mod loader;
mod loader_builders;
mod path;
mod reflect;
mod render_asset;
mod server;
pub use assets::*;
pub use bevy_asset_macros::Asset;
use bevy_diagnostic::{Diagnostic, DiagnosticsStore, RegisterDiagnostic};
pub use direct_access_ext::DirectAssetAccessExt;
pub use event::*;
pub use folder::*;
pub use futures_lite::{AsyncReadExt, AsyncWriteExt};
pub use handle::*;
pub use id::*;
pub use loader::*;
pub use loader_builders::{
Deferred, DynamicTyped, Immediate, NestedLoader, StaticTyped, UnknownTyped,
};
pub use path::*;
pub use reflect::*;
pub use render_asset::*;
pub use server::*;
pub use uuid;
use crate::{
io::{embedded::EmbeddedAssetRegistry, AssetSourceBuilder, AssetSourceBuilders, AssetSourceId},
processor::{AssetProcessor, Process},
};
use alloc::{
string::{String, ToString},
sync::Arc,
vec::Vec,
};
use bevy_app::{App, Plugin, PostUpdate, PreUpdate};
use bevy_ecs::{prelude::Component, schedule::common_conditions::resource_exists};
use bevy_ecs::{
reflect::AppTypeRegistry,
schedule::{IntoScheduleConfigs, SystemSet},
world::FromWorld,
};
use bevy_platform::collections::HashSet;
use bevy_reflect::{FromReflect, GetTypeRegistration, Reflect, TypePath};
use core::any::TypeId;
use tracing::error;
/// Provides "asset" loading and processing functionality. An [`Asset`] is a "runtime value" that is loaded from an [`AssetSource`],
/// which can be something like a filesystem, a network, etc.
///
/// Supports flexible "modes", such as [`AssetMode::Processed`] and
/// [`AssetMode::Unprocessed`] that enable using the asset workflow that best suits your project.
///
/// [`AssetSource`]: io::AssetSource
pub struct AssetPlugin {
/// The default file path to use (relative to the project root) for unprocessed assets.
pub file_path: String,
/// The default file path to use (relative to the project root) for processed assets.
pub processed_file_path: String,
/// If set, will override the default "watch for changes" setting. By default "watch for changes" will be `false` unless
/// the `watch` cargo feature is set. `watch` can be enabled manually, or it will be automatically enabled if a specific watcher
/// like `file_watcher` is enabled.
///
/// Most use cases should leave this set to [`None`] and enable a specific watcher feature such as `file_watcher` to enable
/// watching for dev-scenarios.
pub watch_for_changes_override: Option<bool>,
/// If set, will override the default "use asset processor" setting. By default "use asset
/// processor" will be `false` unless the `asset_processor` cargo feature is set.
///
/// Most use cases should leave this set to [`None`] and enable the `asset_processor` cargo
/// feature.
pub use_asset_processor_override: Option<bool>,
/// The [`AssetMode`] to use for this server.
pub mode: AssetMode,
/// How/If asset meta files should be checked.
pub meta_check: AssetMetaCheck,
/// How to handle load requests of files that are outside the approved directories.
///
/// Approved folders are [`AssetPlugin::file_path`] and the folder of each
/// [`AssetSource`](io::AssetSource). Subfolders within these folders are also valid.
pub unapproved_path_mode: UnapprovedPathMode,
}
/// Determines how to react to attempts to load assets not inside the approved folders.
///
/// Approved folders are [`AssetPlugin::file_path`] and the folder of each
/// [`AssetSource`](io::AssetSource). Subfolders within these folders are also valid.
///
/// It is strongly discouraged to use [`Allow`](UnapprovedPathMode::Allow) if your
/// app will include scripts or modding support, as it could allow arbitrary file
/// access for malicious code.
///
/// The default value is [`Forbid`](UnapprovedPathMode::Forbid).
///
/// See [`AssetPath::is_unapproved`](crate::AssetPath::is_unapproved)
#[derive(Clone, Default)]
pub enum UnapprovedPathMode {
/// Unapproved asset loading is allowed. This is strongly discouraged.
Allow,
/// Fails to load any asset that is unapproved, unless an override method is used, like
/// [`AssetServer::load_override`].
Deny,
/// Fails to load any asset that is unapproved.
#[default]
Forbid,
}
/// Controls whether or not assets are pre-processed before being loaded.
///
/// This setting is controlled by setting [`AssetPlugin::mode`].
///
/// When building on web, asset preprocessing can cause problems due to the lack of filesystem access.
/// See [bevy#10157](https://github.com/bevyengine/bevy/issues/10157) for context.
#[derive(Debug)]
pub enum AssetMode {
/// Loads assets from their [`AssetSource`]'s default [`AssetReader`] without any "preprocessing".
///
/// [`AssetReader`]: io::AssetReader
/// [`AssetSource`]: io::AssetSource
Unprocessed,
/// Assets will be "pre-processed". This enables assets to be imported / converted / optimized ahead of time.
///
/// Assets will be read from their unprocessed [`AssetSource`] (defaults to the `assets` folder),
/// processed according to their [`AssetMeta`], and written to their processed [`AssetSource`] (defaults to the `imported_assets/Default` folder).
///
/// By default, this assumes the processor _has already been run_. It will load assets from their final processed [`AssetReader`].
///
/// When developing an app, you should enable the `asset_processor` cargo feature, which will run the asset processor at startup. This should generally
/// be used in combination with the `file_watcher` cargo feature, which enables hot-reloading of assets that have changed. When both features are enabled,
/// changes to "original/source assets" will be detected, the asset will be re-processed, and then the final processed asset will be hot-reloaded in the app.
///
/// [`AssetMeta`]: meta::AssetMeta
/// [`AssetSource`]: io::AssetSource
/// [`AssetReader`]: io::AssetReader
Processed,
}
/// Configures how / if meta files will be checked. If an asset's meta file is not checked, the default meta for the asset
/// will be used.
#[derive(Debug, Default, Clone)]
pub enum AssetMetaCheck {
/// Always check if assets have meta files. If the meta does not exist, the default meta will be used.
#[default]
Always,
/// Only look up meta files for the provided paths. The default meta will be used for any paths not contained in this set.
Paths(HashSet<AssetPath<'static>>),
/// Never check if assets have meta files and always use the default meta. If meta files exist, they will be ignored and the default meta will be used.
Never,
}
impl Default for AssetPlugin {
fn default() -> Self {
Self {
mode: AssetMode::Unprocessed,
file_path: Self::DEFAULT_UNPROCESSED_FILE_PATH.to_string(),
processed_file_path: Self::DEFAULT_PROCESSED_FILE_PATH.to_string(),
watch_for_changes_override: None,
use_asset_processor_override: None,
meta_check: AssetMetaCheck::default(),
unapproved_path_mode: UnapprovedPathMode::default(),
}
}
}
impl AssetPlugin {
const DEFAULT_UNPROCESSED_FILE_PATH: &'static str = "assets";
/// NOTE: this is in the Default sub-folder to make this forward compatible with "import profiles"
/// and to allow us to put the "processor transaction log" at `imported_assets/log`
const DEFAULT_PROCESSED_FILE_PATH: &'static str = "imported_assets/Default";
}
impl Plugin for AssetPlugin {
fn build(&self, app: &mut App) {
let embedded = EmbeddedAssetRegistry::default();
{
let mut sources = app
.world_mut()
.get_resource_or_init::<AssetSourceBuilders>();
sources.init_default_source(
&self.file_path,
(!matches!(self.mode, AssetMode::Unprocessed))
.then_some(self.processed_file_path.as_str()),
);
embedded.register_source(&mut sources);
}
{
let watch = self
.watch_for_changes_override
.unwrap_or(cfg!(feature = "watch"));
match self.mode {
AssetMode::Unprocessed => {
let mut builders = app.world_mut().resource_mut::<AssetSourceBuilders>();
let sources = builders.build_sources(watch, false);
app.insert_resource(AssetServer::new_with_meta_check(
Arc::new(sources),
AssetServerMode::Unprocessed,
self.meta_check.clone(),
watch,
self.unapproved_path_mode.clone(),
));
}
AssetMode::Processed => {
let use_asset_processor = self
.use_asset_processor_override
.unwrap_or(cfg!(feature = "asset_processor"));
if use_asset_processor {
let mut builders = app.world_mut().resource_mut::<AssetSourceBuilders>();
let (processor, sources) = AssetProcessor::new(&mut builders, watch);
// the main asset server shares loaders with the processor asset server
app.insert_resource(AssetServer::new_with_loaders(
sources,
processor.server().data.loaders.clone(),
AssetServerMode::Processed,
AssetMetaCheck::Always,
watch,
self.unapproved_path_mode.clone(),
))
.insert_resource(processor)
.add_systems(bevy_app::Startup, AssetProcessor::start);
} else {
let mut builders = app.world_mut().resource_mut::<AssetSourceBuilders>();
let sources = builders.build_sources(false, watch);
app.insert_resource(AssetServer::new_with_meta_check(
Arc::new(sources),
AssetServerMode::Processed,
AssetMetaCheck::Always,
watch,
self.unapproved_path_mode.clone(),
));
}
}
}
}
app.insert_resource(embedded)
.init_asset::<LoadedFolder>()
.init_asset::<LoadedUntypedAsset>()
.init_asset::<()>()
.add_message::<UntypedAssetLoadFailedEvent>()
.configure_sets(
PreUpdate,
AssetTrackingSystems.after(handle_internal_asset_events),
)
// `handle_internal_asset_events` requires the use of `&mut World`,
// and as a result has ambiguous system ordering with all other systems in `PreUpdate`.
// This is virtually never a real problem: asset loading is async and so anything that interacts directly with it
// needs to be robust to stochastic delays anyways.
.add_systems(
PreUpdate,
(
handle_internal_asset_events.ambiguous_with_all(),
// TODO: Remove the run condition and use `If` once
// https://github.com/bevyengine/bevy/issues/21549 is resolved.
publish_asset_server_diagnostics.run_if(resource_exists::<DiagnosticsStore>),
)
.chain(),
)
.register_diagnostic(Diagnostic::new(AssetServer::STARTED_LOAD_COUNT));
}
}
/// Declares that this type is an asset,
/// which can be loaded and managed by the [`AssetServer`] and stored in [`Assets`] collections.
///
/// Generally, assets are large, complex, and/or expensive to load from disk, and are often authored by artists or designers.
///
/// [`TypePath`] is largely used for diagnostic purposes, and should almost always be implemented by deriving [`Reflect`] on your type.
/// [`VisitAssetDependencies`] is used to track asset dependencies, and an implementation is automatically generated when deriving [`Asset`].
#[diagnostic::on_unimplemented(
message = "`{Self}` is not an `Asset`",
label = "invalid `Asset`",
note = "consider annotating `{Self}` with `#[derive(Asset)]`"
)]
pub trait Asset: VisitAssetDependencies + TypePath + Send + Sync + 'static {}
/// A trait for components that can be used as asset identifiers, e.g. handle wrappers.
pub trait AsAssetId: Component {
/// The underlying asset type.
type Asset: Asset;
/// Retrieves the asset id from this component.
fn as_asset_id(&self) -> AssetId<Self::Asset>;
}
/// This trait defines how to visit the dependencies of an asset.
/// For example, a 3D model might require both textures and meshes to be loaded.
///
/// Note that this trait is automatically implemented when deriving [`Asset`].
pub trait VisitAssetDependencies {
fn visit_dependencies(&self, visit: &mut impl FnMut(UntypedAssetId));
}
impl<A: Asset> VisitAssetDependencies for Handle<A> {
fn visit_dependencies(&self, visit: &mut impl FnMut(UntypedAssetId)) {
visit(self.id().untyped());
}
}
impl<A: Asset> VisitAssetDependencies for Option<Handle<A>> {
fn visit_dependencies(&self, visit: &mut impl FnMut(UntypedAssetId)) {
if let Some(handle) = self {
visit(handle.id().untyped());
}
}
}
impl VisitAssetDependencies for UntypedHandle {
fn visit_dependencies(&self, visit: &mut impl FnMut(UntypedAssetId)) {
visit(self.id());
}
}
impl VisitAssetDependencies for Option<UntypedHandle> {
fn visit_dependencies(&self, visit: &mut impl FnMut(UntypedAssetId)) {
if let Some(handle) = self {
visit(handle.id());
}
}
}
impl<A: Asset, const N: usize> VisitAssetDependencies for [Handle<A>; N] {
fn visit_dependencies(&self, visit: &mut impl FnMut(UntypedAssetId)) {
for dependency in self {
visit(dependency.id().untyped());
}
}
}
impl<const N: usize> VisitAssetDependencies for [UntypedHandle; N] {
fn visit_dependencies(&self, visit: &mut impl FnMut(UntypedAssetId)) {
for dependency in self {
visit(dependency.id());
}
}
}
impl<A: Asset> VisitAssetDependencies for Vec<Handle<A>> {
fn visit_dependencies(&self, visit: &mut impl FnMut(UntypedAssetId)) {
for dependency in self {
visit(dependency.id().untyped());
}
}
}
impl VisitAssetDependencies for Vec<UntypedHandle> {
fn visit_dependencies(&self, visit: &mut impl FnMut(UntypedAssetId)) {
for dependency in self {
visit(dependency.id());
}
}
}
impl<A: Asset> VisitAssetDependencies for HashSet<Handle<A>> {
fn visit_dependencies(&self, visit: &mut impl FnMut(UntypedAssetId)) {
for dependency in self {
visit(dependency.id().untyped());
}
}
}
impl VisitAssetDependencies for HashSet<UntypedHandle> {
fn visit_dependencies(&self, visit: &mut impl FnMut(UntypedAssetId)) {
for dependency in self {
visit(dependency.id());
}
}
}
/// Adds asset-related builder methods to [`App`].
pub trait AssetApp {
/// Registers the given `loader` in the [`App`]'s [`AssetServer`].
fn register_asset_loader<L: AssetLoader>(&mut self, loader: L) -> &mut Self;
/// Registers the given `processor` in the [`App`]'s [`AssetProcessor`].
fn register_asset_processor<P: Process>(&mut self, processor: P) -> &mut Self;
/// Registers the given [`AssetSourceBuilder`] with the given `id`.
///
/// Note that asset sources must be registered before adding [`AssetPlugin`] to your application,
/// since registered asset sources are built at that point and not after.
fn register_asset_source(
&mut self,
id: impl Into<AssetSourceId<'static>>,
source: AssetSourceBuilder,
) -> &mut Self;
/// Sets the default asset processor for the given `extension`.
fn set_default_asset_processor<P: Process>(&mut self, extension: &str) -> &mut Self;
/// Initializes the given loader in the [`App`]'s [`AssetServer`].
fn init_asset_loader<L: AssetLoader + FromWorld>(&mut self) -> &mut Self;
/// Initializes the given [`Asset`] in the [`App`] by:
/// * Registering the [`Asset`] in the [`AssetServer`]
/// * Initializing the [`AssetEvent`] resource for the [`Asset`]
/// * Adding other relevant systems and resources for the [`Asset`]
/// * Ignoring schedule ambiguities in [`Assets`] resource. Any time a system takes
/// mutable access to this resource this causes a conflict, but they rarely actually
/// modify the same underlying asset.
fn init_asset<A: Asset>(&mut self) -> &mut Self;
/// Registers the asset type `T` using `[App::register]`,
/// and adds [`ReflectAsset`] type data to `T` and [`ReflectHandle`] type data to [`Handle<T>`] in the type registry.
///
/// This enables reflection code to access assets. For detailed information, see the docs on [`ReflectAsset`] and [`ReflectHandle`].
fn register_asset_reflect<A>(&mut self) -> &mut Self
where
A: Asset + Reflect + FromReflect + GetTypeRegistration;
/// Preregisters a loader for the given extensions, that will block asset loads until a real loader
/// is registered.
fn preregister_asset_loader<L: AssetLoader>(&mut self, extensions: &[&str]) -> &mut Self;
}
impl AssetApp for App {
fn register_asset_loader<L: AssetLoader>(&mut self, loader: L) -> &mut Self {
self.world()
.resource::<AssetServer>()
.register_loader(loader);
self
}
fn register_asset_processor<P: Process>(&mut self, processor: P) -> &mut Self {
if let Some(asset_processor) = self.world().get_resource::<AssetProcessor>() {
asset_processor.register_processor(processor);
}
self
}
fn register_asset_source(
&mut self,
id: impl Into<AssetSourceId<'static>>,
source: AssetSourceBuilder,
) -> &mut Self {
let id = id.into();
if self.world().get_resource::<AssetServer>().is_some() {
error!("{} must be registered before `AssetPlugin` (typically added as part of `DefaultPlugins`)", id);
}
{
let mut sources = self
.world_mut()
.get_resource_or_init::<AssetSourceBuilders>();
sources.insert(id, source);
}
self
}
fn set_default_asset_processor<P: Process>(&mut self, extension: &str) -> &mut Self {
if let Some(asset_processor) = self.world().get_resource::<AssetProcessor>() {
asset_processor.set_default_processor::<P>(extension);
}
self
}
fn init_asset_loader<L: AssetLoader + FromWorld>(&mut self) -> &mut Self {
let loader = L::from_world(self.world_mut());
self.register_asset_loader(loader)
}
fn init_asset<A: Asset>(&mut self) -> &mut Self {
let assets = Assets::<A>::default();
self.world()
.resource::<AssetServer>()
.register_asset(&assets);
if self.world().contains_resource::<AssetProcessor>() {
let processor = self.world().resource::<AssetProcessor>();
// The processor should have its own handle provider separate from the Asset storage
// to ensure the id spaces are entirely separate. Not _strictly_ necessary, but
// desirable.
processor
.server()
.register_handle_provider(AssetHandleProvider::new(
TypeId::of::<A>(),
Arc::new(AssetIndexAllocator::default()),
));
}
self.insert_resource(assets)
.allow_ambiguous_resource::<Assets<A>>()
.add_message::<AssetEvent<A>>()
.add_message::<AssetLoadFailedEvent<A>>()
.register_type::<Handle<A>>()
.add_systems(
PostUpdate,
Assets::<A>::asset_events
.run_if(Assets::<A>::asset_events_condition)
.in_set(AssetEventSystems),
)
.add_systems(
PreUpdate,
Assets::<A>::track_assets.in_set(AssetTrackingSystems),
)
}
fn register_asset_reflect<A>(&mut self) -> &mut Self
where
A: Asset + Reflect + FromReflect + GetTypeRegistration,
{
let type_registry = self.world().resource::<AppTypeRegistry>();
{
let mut type_registry = type_registry.write();
type_registry.register::<A>();
type_registry.register::<Handle<A>>();
type_registry.register_type_data::<A, ReflectAsset>();
type_registry.register_type_data::<Handle<A>, ReflectHandle>();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/reflect.rs | crates/bevy_asset/src/reflect.rs | use alloc::boxed::Box;
use core::any::{Any, TypeId};
use bevy_ecs::world::{unsafe_world_cell::UnsafeWorldCell, World};
use bevy_reflect::{FromReflect, FromType, PartialReflect, Reflect};
use crate::{
Asset, AssetId, Assets, Handle, InvalidGenerationError, UntypedAssetId, UntypedHandle,
};
/// Type data for the [`TypeRegistry`](bevy_reflect::TypeRegistry) used to operate on reflected [`Asset`]s.
///
/// This type provides similar methods to [`Assets<T>`] like [`get`](ReflectAsset::get),
/// [`add`](ReflectAsset::add) and [`remove`](ReflectAsset::remove), but can be used in situations where you don't know which asset type `T` you want
/// until runtime.
///
/// [`ReflectAsset`] can be obtained via [`TypeRegistration::data`](bevy_reflect::TypeRegistration::data) if the asset was registered using [`register_asset_reflect`](crate::AssetApp::register_asset_reflect).
#[derive(Clone)]
pub struct ReflectAsset {
handle_type_id: TypeId,
assets_resource_type_id: TypeId,
get: fn(&World, UntypedAssetId) -> Option<&dyn Reflect>,
// SAFETY:
// - may only be called with an [`UnsafeWorldCell`] which can be used to access the corresponding `Assets<T>` resource mutably
// - may only be used to access **at most one** access at once
get_unchecked_mut: unsafe fn(UnsafeWorldCell<'_>, UntypedAssetId) -> Option<&mut dyn Reflect>,
add: fn(&mut World, &dyn PartialReflect) -> UntypedHandle,
insert:
fn(&mut World, UntypedAssetId, &dyn PartialReflect) -> Result<(), InvalidGenerationError>,
len: fn(&World) -> usize,
ids: for<'w> fn(&'w World) -> Box<dyn Iterator<Item = UntypedAssetId> + 'w>,
remove: fn(&mut World, UntypedAssetId) -> Option<Box<dyn Reflect>>,
}
impl ReflectAsset {
/// The [`TypeId`] of the [`Handle<T>`] for this asset
pub fn handle_type_id(&self) -> TypeId {
self.handle_type_id
}
/// The [`TypeId`] of the [`Assets<T>`] resource
pub fn assets_resource_type_id(&self) -> TypeId {
self.assets_resource_type_id
}
/// Equivalent of [`Assets::get`]
pub fn get<'w>(
&self,
world: &'w World,
asset_id: impl Into<UntypedAssetId>,
) -> Option<&'w dyn Reflect> {
(self.get)(world, asset_id.into())
}
/// Equivalent of [`Assets::get_mut`]
pub fn get_mut<'w>(
&self,
world: &'w mut World,
asset_id: impl Into<UntypedAssetId>,
) -> Option<&'w mut dyn Reflect> {
#[expect(
unsafe_code,
reason = "Use of unsafe `Self::get_unchecked_mut()` function."
)]
// SAFETY: unique world access
unsafe {
(self.get_unchecked_mut)(world.as_unsafe_world_cell(), asset_id.into())
}
}
/// Equivalent of [`Assets::get_mut`], but works with an [`UnsafeWorldCell`].
///
/// Only use this method when you have ensured that you are the *only* one with access to the [`Assets`] resource of the asset type.
/// Furthermore, this does *not* allow you to have look up two distinct handles,
/// you can only have at most one alive at the same time.
/// This means that this is *not allowed*:
/// ```no_run
/// # use bevy_asset::{ReflectAsset, UntypedHandle};
/// # use bevy_ecs::prelude::World;
/// # let reflect_asset: ReflectAsset = unimplemented!();
/// # let mut world: World = unimplemented!();
/// # let handle_1: UntypedHandle = unimplemented!();
/// # let handle_2: UntypedHandle = unimplemented!();
/// let unsafe_world_cell = world.as_unsafe_world_cell();
/// let a = unsafe { reflect_asset.get_unchecked_mut(unsafe_world_cell, &handle_1).unwrap() };
/// let b = unsafe { reflect_asset.get_unchecked_mut(unsafe_world_cell, &handle_2).unwrap() };
/// // ^ not allowed, two mutable references through the same asset resource, even though the
/// // handles are distinct
///
/// println!("a = {a:?}, b = {b:?}");
/// ```
///
/// # Safety
/// This method does not prevent you from having two mutable pointers to the same data,
/// violating Rust's aliasing rules. To avoid this:
/// * Only call this method if you know that the [`UnsafeWorldCell`] may be used to access the corresponding `Assets<T>`
/// * Don't call this method more than once in the same scope.
#[expect(
unsafe_code,
reason = "This function calls unsafe code and has safety requirements."
)]
pub unsafe fn get_unchecked_mut<'w>(
&self,
world: UnsafeWorldCell<'w>,
asset_id: impl Into<UntypedAssetId>,
) -> Option<&'w mut dyn Reflect> {
// SAFETY: requirements are deferred to the caller
unsafe { (self.get_unchecked_mut)(world, asset_id.into()) }
}
/// Equivalent of [`Assets::add`]
pub fn add(&self, world: &mut World, value: &dyn PartialReflect) -> UntypedHandle {
(self.add)(world, value)
}
/// Equivalent of [`Assets::insert`]
pub fn insert(
&self,
world: &mut World,
asset_id: impl Into<UntypedAssetId>,
value: &dyn PartialReflect,
) -> Result<(), InvalidGenerationError> {
(self.insert)(world, asset_id.into(), value)
}
/// Equivalent of [`Assets::remove`]
pub fn remove(
&self,
world: &mut World,
asset_id: impl Into<UntypedAssetId>,
) -> Option<Box<dyn Reflect>> {
(self.remove)(world, asset_id.into())
}
/// Equivalent of [`Assets::len`]
pub fn len(&self, world: &World) -> usize {
(self.len)(world)
}
/// Equivalent of [`Assets::is_empty`]
pub fn is_empty(&self, world: &World) -> bool {
self.len(world) == 0
}
/// Equivalent of [`Assets::ids`]
pub fn ids<'w>(&self, world: &'w World) -> impl Iterator<Item = UntypedAssetId> + 'w {
(self.ids)(world)
}
}
impl<A: Asset + FromReflect> FromType<A> for ReflectAsset {
fn from_type() -> Self {
ReflectAsset {
handle_type_id: TypeId::of::<Handle<A>>(),
assets_resource_type_id: TypeId::of::<Assets<A>>(),
get: |world, asset_id| {
let assets = world.resource::<Assets<A>>();
let asset = assets.get(asset_id.typed_debug_checked());
asset.map(|asset| asset as &dyn Reflect)
},
get_unchecked_mut: |world, asset_id| {
// SAFETY: `get_unchecked_mut` must be called with `UnsafeWorldCell` having access to `Assets<A>`,
// and must ensure to only have at most one reference to it live at all times.
#[expect(unsafe_code, reason = "Uses `UnsafeWorldCell::get_resource_mut()`.")]
let assets = unsafe { world.get_resource_mut::<Assets<A>>().unwrap().into_inner() };
let asset = assets.get_mut(asset_id.typed_debug_checked());
asset.map(|asset| asset as &mut dyn Reflect)
},
add: |world, value| {
let mut assets = world.resource_mut::<Assets<A>>();
let value: A = FromReflect::from_reflect(value)
.expect("could not call `FromReflect::from_reflect` in `ReflectAsset::add`");
assets.add(value).untyped()
},
insert: |world, asset_id, value| {
let mut assets = world.resource_mut::<Assets<A>>();
let value: A = FromReflect::from_reflect(value)
.expect("could not call `FromReflect::from_reflect` in `ReflectAsset::set`");
assets.insert(asset_id.typed_debug_checked(), value)
},
len: |world| {
let assets = world.resource::<Assets<A>>();
assets.len()
},
ids: |world| {
let assets = world.resource::<Assets<A>>();
Box::new(assets.ids().map(AssetId::untyped))
},
remove: |world, asset_id| {
let mut assets = world.resource_mut::<Assets<A>>();
let value = assets.remove(asset_id.typed_debug_checked());
value.map(|value| Box::new(value) as Box<dyn Reflect>)
},
}
}
}
/// Reflect type data struct relating a [`Handle<T>`] back to the `T` asset type.
///
/// Say you want to look up the asset values of a list of handles when you have access to their `&dyn Reflect` form.
/// Assets can be looked up in the world using [`ReflectAsset`], but how do you determine which [`ReflectAsset`] to use when
/// only looking at the handle? [`ReflectHandle`] is stored in the type registry on each `Handle<T>` type, so you can use [`ReflectHandle::asset_type_id`] to look up
/// the [`ReflectAsset`] type data on the corresponding `T` asset type:
///
///
/// ```no_run
/// # use bevy_reflect::{TypeRegistry, prelude::*};
/// # use bevy_ecs::prelude::*;
/// use bevy_asset::{ReflectHandle, ReflectAsset};
///
/// # let world: &World = unimplemented!();
/// # let type_registry: TypeRegistry = unimplemented!();
/// let handles: Vec<&dyn Reflect> = unimplemented!();
/// for handle in handles {
/// let reflect_handle = type_registry.get_type_data::<ReflectHandle>(handle.type_id()).unwrap();
/// let reflect_asset = type_registry.get_type_data::<ReflectAsset>(reflect_handle.asset_type_id()).unwrap();
///
/// let handle = reflect_handle.downcast_handle_untyped(handle.as_any()).unwrap();
/// let value = reflect_asset.get(world, &handle).unwrap();
/// println!("{value:?}");
/// }
/// ```
#[derive(Clone)]
pub struct ReflectHandle {
asset_type_id: TypeId,
downcast_handle_untyped: fn(&dyn Any) -> Option<UntypedHandle>,
typed: fn(UntypedHandle) -> Box<dyn Reflect>,
}
impl ReflectHandle {
/// The [`TypeId`] of the asset
pub fn asset_type_id(&self) -> TypeId {
self.asset_type_id
}
/// A way to go from a [`Handle<T>`] in a `dyn Any` to a [`UntypedHandle`]
pub fn downcast_handle_untyped(&self, handle: &dyn Any) -> Option<UntypedHandle> {
(self.downcast_handle_untyped)(handle)
}
/// A way to go from a [`UntypedHandle`] to a [`Handle<T>`] in a `Box<dyn Reflect>`.
/// Equivalent of [`UntypedHandle::typed`].
pub fn typed(&self, handle: UntypedHandle) -> Box<dyn Reflect> {
(self.typed)(handle)
}
}
impl<A: Asset> FromType<Handle<A>> for ReflectHandle {
fn from_type() -> Self {
ReflectHandle {
asset_type_id: TypeId::of::<A>(),
downcast_handle_untyped: |handle: &dyn Any| {
handle
.downcast_ref::<Handle<A>>()
.map(|h| h.clone().untyped())
},
typed: |handle: UntypedHandle| Box::new(handle.typed_debug_checked::<A>()),
}
}
}
#[cfg(test)]
mod tests {
use alloc::{string::String, vec::Vec};
use core::any::TypeId;
use crate::{tests::create_app, Asset, AssetApp, ReflectAsset};
use bevy_ecs::reflect::AppTypeRegistry;
use bevy_reflect::Reflect;
#[derive(Asset, Reflect)]
struct AssetType {
field: String,
}
#[test]
fn test_reflect_asset_operations() {
let mut app = create_app().0;
app.init_asset::<AssetType>()
.register_asset_reflect::<AssetType>();
let reflect_asset = {
let type_registry = app.world().resource::<AppTypeRegistry>();
let type_registry = type_registry.read();
type_registry
.get_type_data::<ReflectAsset>(TypeId::of::<AssetType>())
.unwrap()
.clone()
};
let value = AssetType {
field: "test".into(),
};
let handle = reflect_asset.add(app.world_mut(), &value);
// struct is a reserved keyword, so we can't use it here
let strukt = reflect_asset
.get_mut(app.world_mut(), &handle)
.unwrap()
.reflect_mut()
.as_struct()
.unwrap();
strukt
.field_mut("field")
.unwrap()
.apply(&String::from("edited"));
assert_eq!(reflect_asset.len(app.world()), 1);
let ids: Vec<_> = reflect_asset.ids(app.world()).collect();
assert_eq!(ids.len(), 1);
let id = ids[0];
let asset = reflect_asset.get(app.world(), id).unwrap();
assert_eq!(asset.downcast_ref::<AssetType>().unwrap().field, "edited");
reflect_asset.remove(app.world_mut(), id).unwrap();
assert_eq!(reflect_asset.len(app.world()), 0);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/id.rs | crates/bevy_asset/src/id.rs | use crate::{Asset, AssetIndex, Handle, UntypedHandle};
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use core::{
any::TypeId,
fmt::{Debug, Display},
hash::Hash,
marker::PhantomData,
};
use derive_more::derive::From;
use thiserror::Error;
/// A unique runtime-only identifier for an [`Asset`]. This is cheap to [`Copy`]/[`Clone`] and is not directly tied to the
/// lifetime of the Asset. This means it _can_ point to an [`Asset`] that no longer exists.
///
/// For an identifier tied to the lifetime of an asset, see [`Handle`](`crate::Handle`).
///
/// For an "untyped" / "generic-less" id, see [`UntypedAssetId`].
#[derive(Reflect, Serialize, Deserialize, From)]
#[reflect(Clone, Default, Debug, PartialEq, Hash)]
pub enum AssetId<A: Asset> {
/// A small / efficient runtime identifier that can be used to efficiently look up an asset stored in [`Assets`]. This is
/// the "default" identifier used for assets. The alternative(s) (ex: [`AssetId::Uuid`]) will only be used if assets are
/// explicitly registered that way.
///
/// [`Assets`]: crate::Assets
Index {
/// The unstable, opaque index of the asset.
index: AssetIndex,
/// A marker to store the type information of the asset.
#[reflect(ignore, clone)]
marker: PhantomData<fn() -> A>,
},
/// A stable-across-runs / const asset identifier. This will only be used if an asset is explicitly registered in [`Assets`]
/// with one.
///
/// [`Assets`]: crate::Assets
Uuid {
/// The UUID provided during asset registration.
uuid: Uuid,
},
}
impl<A: Asset> AssetId<A> {
/// The uuid for the default [`AssetId`]. It is valid to assign a value to this in [`Assets`](crate::Assets)
/// and by convention (where appropriate) assets should support this pattern.
pub const DEFAULT_UUID: Uuid = Uuid::from_u128(200809721996911295814598172825939264631);
/// This asset id _should_ never be valid. Assigning a value to this in [`Assets`](crate::Assets) will
/// produce undefined behavior, so don't do it!
pub const INVALID_UUID: Uuid = Uuid::from_u128(108428345662029828789348721013522787528);
/// Returns an [`AssetId`] with [`Self::INVALID_UUID`], which _should_ never be assigned to.
#[inline]
pub const fn invalid() -> Self {
Self::Uuid {
uuid: Self::INVALID_UUID,
}
}
/// Converts this to an "untyped" / "generic-less" [`Asset`] identifier that stores the type information
/// _inside_ the [`UntypedAssetId`].
#[inline]
pub fn untyped(self) -> UntypedAssetId {
self.into()
}
#[inline]
fn internal(self) -> InternalAssetId {
match self {
AssetId::Index { index, .. } => InternalAssetId::Index(index),
AssetId::Uuid { uuid } => InternalAssetId::Uuid(uuid),
}
}
}
impl<A: Asset> Default for AssetId<A> {
fn default() -> Self {
AssetId::Uuid {
uuid: Self::DEFAULT_UUID,
}
}
}
impl<A: Asset> Clone for AssetId<A> {
fn clone(&self) -> Self {
*self
}
}
impl<A: Asset> Copy for AssetId<A> {}
impl<A: Asset> Display for AssetId<A> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
Debug::fmt(self, f)
}
}
impl<A: Asset> Debug for AssetId<A> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
AssetId::Index { index, .. } => {
write!(
f,
"AssetId<{}>{{ index: {}, generation: {}}}",
core::any::type_name::<A>(),
index.index,
index.generation
)
}
AssetId::Uuid { uuid } => {
write!(
f,
"AssetId<{}>{{uuid: {}}}",
core::any::type_name::<A>(),
uuid
)
}
}
}
}
impl<A: Asset> Hash for AssetId<A> {
#[inline]
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.internal().hash(state);
TypeId::of::<A>().hash(state);
}
}
impl<A: Asset> PartialEq for AssetId<A> {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.internal().eq(&other.internal())
}
}
impl<A: Asset> Eq for AssetId<A> {}
impl<A: Asset> PartialOrd for AssetId<A> {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl<A: Asset> Ord for AssetId<A> {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
self.internal().cmp(&other.internal())
}
}
impl<A: Asset> From<AssetIndex> for AssetId<A> {
#[inline]
fn from(value: AssetIndex) -> Self {
Self::Index {
index: value,
marker: PhantomData,
}
}
}
/// An "untyped" / "generic-less" [`Asset`] identifier that behaves much like [`AssetId`], but stores the [`Asset`] type
/// information at runtime instead of compile-time. This increases the size of the type, but it enables storing asset ids
/// across asset types together and enables comparisons between them.
#[derive(Debug, Copy, Clone, Reflect)]
pub enum UntypedAssetId {
/// A small / efficient runtime identifier that can be used to efficiently look up an asset stored in [`Assets`]. This is
/// the "default" identifier used for assets. The alternative(s) (ex: [`UntypedAssetId::Uuid`]) will only be used if assets are
/// explicitly registered that way.
///
/// [`Assets`]: crate::Assets
Index {
/// An identifier that records the underlying asset type.
type_id: TypeId,
/// The unstable, opaque index of the asset.
index: AssetIndex,
},
/// A stable-across-runs / const asset identifier. This will only be used if an asset is explicitly registered in [`Assets`]
/// with one.
///
/// [`Assets`]: crate::Assets
Uuid {
/// An identifier that records the underlying asset type.
type_id: TypeId,
/// The UUID provided during asset registration.
uuid: Uuid,
},
}
impl UntypedAssetId {
/// Converts this to a "typed" [`AssetId`] without checking the stored type to see if it matches the target `A` [`Asset`] type.
/// This should only be called if you are _absolutely certain_ the asset type matches the stored type. And even then, you should
/// consider using [`UntypedAssetId::typed_debug_checked`] instead.
#[inline]
pub fn typed_unchecked<A: Asset>(self) -> AssetId<A> {
match self {
UntypedAssetId::Index { index, .. } => AssetId::Index {
index,
marker: PhantomData,
},
UntypedAssetId::Uuid { uuid, .. } => AssetId::Uuid { uuid },
}
}
/// Converts this to a "typed" [`AssetId`]. When compiled in debug-mode it will check to see if the stored type
/// matches the target `A` [`Asset`] type. When compiled in release-mode, this check will be skipped.
///
/// # Panics
///
/// Panics if compiled in debug mode and the [`TypeId`] of `A` does not match the stored [`TypeId`].
#[inline]
pub fn typed_debug_checked<A: Asset>(self) -> AssetId<A> {
debug_assert_eq!(
self.type_id(),
TypeId::of::<A>(),
"The target AssetId<{}>'s TypeId does not match the TypeId of this UntypedAssetId",
core::any::type_name::<A>()
);
self.typed_unchecked()
}
/// Converts this to a "typed" [`AssetId`].
///
/// # Panics
///
/// Panics if the [`TypeId`] of `A` does not match the stored type id.
#[inline]
pub fn typed<A: Asset>(self) -> AssetId<A> {
let Ok(id) = self.try_typed() else {
panic!(
"The target AssetId<{}>'s TypeId does not match the TypeId of this UntypedAssetId",
core::any::type_name::<A>()
)
};
id
}
/// Try to convert this to a "typed" [`AssetId`].
#[inline]
pub fn try_typed<A: Asset>(self) -> Result<AssetId<A>, UntypedAssetIdConversionError> {
AssetId::try_from(self)
}
/// Returns the stored [`TypeId`] of the referenced [`Asset`].
#[inline]
pub fn type_id(&self) -> TypeId {
match self {
UntypedAssetId::Index { type_id, .. } | UntypedAssetId::Uuid { type_id, .. } => {
*type_id
}
}
}
#[inline]
fn internal(self) -> InternalAssetId {
match self {
UntypedAssetId::Index { index, .. } => InternalAssetId::Index(index),
UntypedAssetId::Uuid { uuid, .. } => InternalAssetId::Uuid(uuid),
}
}
}
impl Display for UntypedAssetId {
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 } => {
writer
.field("type_id", type_id)
.field("index", &index.index)
.field("generation", &index.generation);
}
UntypedAssetId::Uuid { uuid, type_id } => {
writer.field("type_id", type_id).field("uuid", uuid);
}
}
writer.finish()
}
}
impl PartialEq for UntypedAssetId {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.type_id() == other.type_id() && self.internal().eq(&other.internal())
}
}
impl Eq for UntypedAssetId {}
impl Hash for UntypedAssetId {
#[inline]
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.internal().hash(state);
self.type_id().hash(state);
}
}
impl Ord for UntypedAssetId {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
self.type_id()
.cmp(&other.type_id())
.then_with(|| self.internal().cmp(&other.internal()))
}
}
impl PartialOrd for UntypedAssetId {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}
/// An asset id without static or dynamic types associated with it.
///
/// This is provided to make implementing traits easier for the many different asset ID types.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, PartialOrd, Ord, From)]
enum InternalAssetId {
Index(AssetIndex),
Uuid(Uuid),
}
/// An asset index bundled with its (dynamic) type.
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)]
pub(crate) struct ErasedAssetIndex {
pub(crate) index: AssetIndex,
pub(crate) type_id: TypeId,
}
impl ErasedAssetIndex {
pub(crate) fn new(index: AssetIndex, type_id: TypeId) -> Self {
Self { index, type_id }
}
}
impl Display for ErasedAssetIndex {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("ErasedAssetIndex")
.field("type_id", &self.type_id)
.field("index", &self.index.index)
.field("generation", &self.index.generation)
.finish()
}
}
// Cross Operations
impl<A: Asset> PartialEq<UntypedAssetId> for AssetId<A> {
#[inline]
fn eq(&self, other: &UntypedAssetId) -> bool {
TypeId::of::<A>() == other.type_id() && self.internal().eq(&other.internal())
}
}
impl<A: Asset> PartialEq<AssetId<A>> for UntypedAssetId {
#[inline]
fn eq(&self, other: &AssetId<A>) -> bool {
other.eq(self)
}
}
impl<A: Asset> PartialOrd<UntypedAssetId> for AssetId<A> {
#[inline]
fn partial_cmp(&self, other: &UntypedAssetId) -> Option<core::cmp::Ordering> {
if TypeId::of::<A>() != other.type_id() {
None
} else {
Some(self.internal().cmp(&other.internal()))
}
}
}
impl<A: Asset> PartialOrd<AssetId<A>> for UntypedAssetId {
#[inline]
fn partial_cmp(&self, other: &AssetId<A>) -> Option<core::cmp::Ordering> {
Some(other.partial_cmp(self)?.reverse())
}
}
impl<A: Asset> From<AssetId<A>> for UntypedAssetId {
#[inline]
fn from(value: AssetId<A>) -> Self {
let type_id = TypeId::of::<A>();
match value {
AssetId::Index { index, .. } => UntypedAssetId::Index { type_id, index },
AssetId::Uuid { uuid } => UntypedAssetId::Uuid { type_id, uuid },
}
}
}
impl<A: Asset> TryFrom<UntypedAssetId> for AssetId<A> {
type Error = UntypedAssetIdConversionError;
#[inline]
fn try_from(value: UntypedAssetId) -> Result<Self, Self::Error> {
let found = value.type_id();
let expected = TypeId::of::<A>();
match value {
UntypedAssetId::Index { index, type_id } if type_id == expected => Ok(AssetId::Index {
index,
marker: PhantomData,
}),
UntypedAssetId::Uuid { uuid, type_id } if type_id == expected => {
Ok(AssetId::Uuid { uuid })
}
_ => Err(UntypedAssetIdConversionError::TypeIdMismatch { expected, found }),
}
}
}
impl TryFrom<UntypedAssetId> for ErasedAssetIndex {
type Error = UuidNotSupportedError;
fn try_from(asset_id: UntypedAssetId) -> Result<Self, Self::Error> {
match asset_id {
UntypedAssetId::Index { type_id, index } => Ok(ErasedAssetIndex { index, type_id }),
UntypedAssetId::Uuid { .. } => Err(UuidNotSupportedError),
}
}
}
impl<A: Asset> TryFrom<&Handle<A>> for ErasedAssetIndex {
type Error = UuidNotSupportedError;
fn try_from(handle: &Handle<A>) -> Result<Self, Self::Error> {
match handle {
Handle::Strong(handle) => Ok(Self::new(handle.index, handle.type_id)),
Handle::Uuid(..) => Err(UuidNotSupportedError),
}
}
}
impl TryFrom<&UntypedHandle> for ErasedAssetIndex {
type Error = UuidNotSupportedError;
fn try_from(handle: &UntypedHandle) -> Result<Self, Self::Error> {
match handle {
UntypedHandle::Strong(handle) => Ok(Self::new(handle.index, handle.type_id)),
UntypedHandle::Uuid { .. } => Err(UuidNotSupportedError),
}
}
}
impl From<ErasedAssetIndex> for UntypedAssetId {
fn from(value: ErasedAssetIndex) -> Self {
Self::Index {
type_id: value.type_id,
index: value.index,
}
}
}
#[derive(Error, Debug)]
#[error("Attempted to create a TypedAssetIndex from a Uuid")]
pub(crate) struct UuidNotSupportedError;
/// Errors preventing the conversion of to/from an [`UntypedAssetId`] and an [`AssetId`].
#[derive(Error, Debug, PartialEq, Clone)]
#[non_exhaustive]
pub enum UntypedAssetIdConversionError {
/// Caused when trying to convert an [`UntypedAssetId`] into an [`AssetId`] of the wrong type.
#[error("This UntypedAssetId is for {found:?} and cannot be converted into an AssetId<{expected:?}>")]
TypeIdMismatch {
/// The [`TypeId`] of the asset that we are trying to convert to.
expected: TypeId,
/// The [`TypeId`] of the asset that we are trying to convert from.
found: TypeId,
},
}
#[cfg(test)]
mod tests {
use super::*;
type TestAsset = ();
const UUID_1: Uuid = Uuid::from_u128(123);
const UUID_2: Uuid = Uuid::from_u128(456);
/// Simple utility to directly hash a value using a fixed hasher
fn hash<T: Hash>(data: &T) -> u64 {
use core::hash::BuildHasher;
bevy_platform::hash::FixedHasher.hash_one(data)
}
/// Typed and Untyped `AssetIds` should be equivalent to each other and themselves
#[test]
fn equality() {
let typed = AssetId::<TestAsset>::Uuid { uuid: UUID_1 };
let untyped = UntypedAssetId::Uuid {
type_id: TypeId::of::<TestAsset>(),
uuid: UUID_1,
};
assert_eq!(Ok(typed), AssetId::try_from(untyped));
assert_eq!(UntypedAssetId::from(typed), untyped);
assert_eq!(typed, untyped);
}
/// Typed and Untyped `AssetIds` should be orderable amongst each other and themselves
#[test]
fn ordering() {
assert!(UUID_1 < UUID_2);
let typed_1 = AssetId::<TestAsset>::Uuid { uuid: UUID_1 };
let typed_2 = AssetId::<TestAsset>::Uuid { uuid: UUID_2 };
let untyped_1 = UntypedAssetId::Uuid {
type_id: TypeId::of::<TestAsset>(),
uuid: UUID_1,
};
let untyped_2 = UntypedAssetId::Uuid {
type_id: TypeId::of::<TestAsset>(),
uuid: UUID_2,
};
assert!(typed_1 < typed_2);
assert!(untyped_1 < untyped_2);
assert!(UntypedAssetId::from(typed_1) < untyped_2);
assert!(untyped_1 < UntypedAssetId::from(typed_2));
assert!(AssetId::try_from(untyped_1).unwrap() < typed_2);
assert!(typed_1 < AssetId::try_from(untyped_2).unwrap());
assert!(typed_1 < untyped_2);
assert!(untyped_1 < typed_2);
}
/// Typed and Untyped `AssetIds` should be equivalently hashable to each other and themselves
#[test]
fn hashing() {
let typed = AssetId::<TestAsset>::Uuid { uuid: UUID_1 };
let untyped = UntypedAssetId::Uuid {
type_id: TypeId::of::<TestAsset>(),
uuid: UUID_1,
};
assert_eq!(
hash(&typed),
hash(&AssetId::<TestAsset>::try_from(untyped).unwrap())
);
assert_eq!(hash(&UntypedAssetId::from(typed)), hash(&untyped));
assert_eq!(hash(&typed), hash(&untyped));
}
/// Typed and Untyped `AssetIds` should be interchangeable
#[test]
fn conversion() {
let typed = AssetId::<TestAsset>::Uuid { uuid: UUID_1 };
let untyped = UntypedAssetId::Uuid {
type_id: TypeId::of::<TestAsset>(),
uuid: UUID_1,
};
assert_eq!(Ok(typed), AssetId::try_from(untyped));
assert_eq!(UntypedAssetId::from(typed), untyped);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/render_asset.rs | crates/bevy_asset/src/render_asset.rs | use bevy_reflect::{Reflect, ReflectDeserialize, ReflectSerialize};
use serde::{Deserialize, Serialize};
bitflags::bitflags! {
/// Defines where the asset will be used.
///
/// If an asset is set to the `RENDER_WORLD` but not the `MAIN_WORLD`, the asset data (pixel data,
/// mesh vertex data, etc) will be removed from the cpu-side asset once it's been extracted and prepared
/// in the render world. The asset will remain in the assets collection, but with only metadata.
///
/// Unloading the asset data saves on memory, as for most cases it is no longer necessary to keep
/// it in RAM once it's been uploaded to the GPU's VRAM. However, this means you cannot access the
/// asset data from the CPU (via the `Assets<T>` resource) once unloaded (without re-loading it).
///
/// If you never need access to the asset from the CPU past the first frame it's loaded on,
/// or only need very infrequent access, then set this to `RENDER_WORLD`. Otherwise, set this to
/// `RENDER_WORLD | MAIN_WORLD`.
///
/// If you have an asset that doesn't actually need to end up in the render world, like an Image
/// that will be decoded into another Image asset, use `MAIN_WORLD` only.
///
/// ## Platform-specific
///
/// On Wasm, it is not possible for now to free reserved memory. To control memory usage, load assets
/// in sequence and unload one before loading the next. See this
/// [discussion about memory management](https://github.com/WebAssembly/design/issues/1397) for more
/// details.
#[repr(transparent)]
#[derive(Serialize, Deserialize, Hash, Clone, Copy, PartialEq, Eq, Debug, Reflect)]
#[reflect(opaque)]
#[reflect(Serialize, Deserialize, Hash, Clone, PartialEq, Debug)]
pub struct RenderAssetUsages: u8 {
/// The bit flag for the main world.
const MAIN_WORLD = 1 << 0;
/// The bit flag for the render world.
const RENDER_WORLD = 1 << 1;
}
}
impl Default for RenderAssetUsages {
/// Returns the default render asset usage flags:
/// `RenderAssetUsages::MAIN_WORLD | RenderAssetUsages::RENDER_WORLD`
///
/// This default configuration ensures the asset persists in the main world, even after being prepared for rendering.
///
/// If your asset does not change, consider using `RenderAssetUsages::RENDER_WORLD` exclusively. This will cause
/// the asset to be unloaded from the main world once it has been prepared for rendering. If the asset does not need
/// to reach the render world at all, use `RenderAssetUsages::MAIN_WORLD` exclusively.
fn default() -> Self {
RenderAssetUsages::MAIN_WORLD | RenderAssetUsages::RENDER_WORLD
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/direct_access_ext.rs | crates/bevy_asset/src/direct_access_ext.rs | //! Add methods on `World` to simplify loading assets when all
//! you have is a `World`.
use bevy_ecs::world::World;
use crate::{meta::Settings, Asset, AssetPath, AssetServer, Assets, Handle};
/// An extension trait for methods for working with assets directly from a [`World`].
pub trait DirectAssetAccessExt {
/// Insert an asset similarly to [`Assets::add`].
fn add_asset<A: Asset>(&mut self, asset: impl Into<A>) -> Handle<A>;
/// Load an asset similarly to [`AssetServer::load`].
fn load_asset<'a, A: Asset>(&self, path: impl Into<AssetPath<'a>>) -> Handle<A>;
/// Load an asset with settings, similarly to [`AssetServer::load_with_settings`].
fn load_asset_with_settings<'a, A: Asset, S: Settings>(
&self,
path: impl Into<AssetPath<'a>>,
settings: impl Fn(&mut S) + Send + Sync + 'static,
) -> Handle<A>;
}
impl DirectAssetAccessExt for World {
/// Insert an asset similarly to [`Assets::add`].
///
/// # Panics
/// If `self` doesn't have an [`AssetServer`] resource initialized yet.
fn add_asset<'a, A: Asset>(&mut self, asset: impl Into<A>) -> Handle<A> {
self.resource_mut::<Assets<A>>().add(asset)
}
/// Load an asset similarly to [`AssetServer::load`].
///
/// # Panics
/// If `self` doesn't have an [`AssetServer`] resource initialized yet.
fn load_asset<'a, A: Asset>(&self, path: impl Into<AssetPath<'a>>) -> Handle<A> {
self.resource::<AssetServer>().load(path)
}
/// Load an asset with settings, similarly to [`AssetServer::load_with_settings`].
///
/// # Panics
/// If `self` doesn't have an [`AssetServer`] resource initialized yet.
fn load_asset_with_settings<'a, A: Asset, S: Settings>(
&self,
path: impl Into<AssetPath<'a>>,
settings: impl Fn(&mut S) + Send + Sync + 'static,
) -> Handle<A> {
self.resource::<AssetServer>()
.load_with_settings(path, settings)
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/loader.rs | crates/bevy_asset/src/loader.rs | use crate::{
io::{
AssetReaderError, MissingAssetSourceError, MissingProcessedAssetReaderError, Reader,
ReaderRequiredFeatures,
},
loader_builders::{Deferred, NestedLoader, StaticTyped},
meta::{AssetHash, AssetMeta, AssetMetaDyn, ProcessedInfo, ProcessedInfoMinimal, Settings},
path::AssetPath,
Asset, AssetIndex, AssetLoadError, AssetServer, AssetServerMode, Assets, ErasedAssetIndex,
Handle, UntypedAssetId, UntypedHandle,
};
use alloc::{
boxed::Box,
string::{String, ToString},
vec::Vec,
};
use atomicow::CowArc;
use bevy_ecs::{error::BevyError, world::World};
use bevy_platform::collections::{HashMap, HashSet};
use bevy_reflect::TypePath;
use bevy_tasks::{BoxedFuture, ConditionalSendFuture};
use core::any::{Any, TypeId};
use downcast_rs::{impl_downcast, Downcast};
use ron::error::SpannedError;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use thiserror::Error;
/// Loads an [`Asset`] from a given byte [`Reader`]. This can accept [`AssetLoader::Settings`], which configure how the [`Asset`]
/// should be loaded.
///
/// This trait is generally used in concert with [`AssetReader`](crate::io::AssetReader) to load assets from a byte source.
///
/// For a complementary version of this trait that can save assets, see [`AssetSaver`](crate::saver::AssetSaver).
pub trait AssetLoader: TypePath + Send + Sync + 'static {
/// The top level [`Asset`] loaded by this [`AssetLoader`].
type Asset: Asset;
/// 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<BevyError>;
/// Asynchronously loads [`AssetLoader::Asset`] (and any other labeled assets) from the bytes provided by [`Reader`].
fn load(
&self,
reader: &mut dyn Reader,
settings: &Self::Settings,
load_context: &mut LoadContext,
) -> impl ConditionalSendFuture<Output = Result<Self::Asset, Self::Error>>;
/// Returns the required features of the reader for this loader.
fn reader_required_features(_settings: &Self::Settings) -> ReaderRequiredFeatures {
ReaderRequiredFeatures::default()
}
/// Returns a list of extensions supported by this [`AssetLoader`], without the preceding dot.
/// Note that users of this [`AssetLoader`] may choose to load files with a non-matching extension.
fn extensions(&self) -> &[&str] {
&[]
}
}
/// Provides type-erased access to an [`AssetLoader`].
pub trait ErasedAssetLoader: Send + Sync + 'static {
/// Asynchronously loads the asset(s) from the bytes provided by [`Reader`].
fn load<'a>(
&'a self,
reader: &'a mut dyn Reader,
settings: &'a dyn Settings,
load_context: LoadContext<'a>,
) -> BoxedFuture<'a, Result<ErasedLoadedAsset, BevyError>>;
/// Returns the required features of the reader for this loader.
// Note: This takes &self just to be dyn compatible.
fn reader_required_features(&self, settings: &dyn Settings) -> ReaderRequiredFeatures;
/// Returns a list of extensions supported by this asset loader, without the preceding dot.
fn extensions(&self) -> &[&str];
/// Deserializes metadata from the input `meta` bytes into the appropriate type (erased as [`Box<dyn AssetMetaDyn>`]).
fn deserialize_meta(&self, meta: &[u8]) -> Result<Box<dyn AssetMetaDyn>, DeserializeMetaError>;
/// Returns the default meta value for the [`AssetLoader`] (erased as [`Box<dyn AssetMetaDyn>`]).
fn default_meta(&self) -> Box<dyn AssetMetaDyn>;
/// Returns the type path of the [`AssetLoader`].
fn type_path(&self) -> &'static str;
/// Returns the [`TypeId`] of the [`AssetLoader`].
fn type_id(&self) -> TypeId;
/// Returns the type name of the top-level [`Asset`] loaded by the [`AssetLoader`].
fn asset_type_name(&self) -> &'static str;
/// Returns the [`TypeId`] of the top-level [`Asset`] loaded by the [`AssetLoader`].
fn asset_type_id(&self) -> TypeId;
}
impl<L> ErasedAssetLoader for L
where
L: AssetLoader + Send + Sync,
{
/// Processes the asset in an asynchronous closure.
fn load<'a>(
&'a self,
reader: &'a mut dyn Reader,
settings: &'a dyn Settings,
mut load_context: LoadContext<'a>,
) -> BoxedFuture<'a, Result<ErasedLoadedAsset, BevyError>> {
Box::pin(async move {
let settings = settings
.downcast_ref::<L::Settings>()
.expect("AssetLoader settings should match the loader type");
let asset = <L as AssetLoader>::load(self, reader, settings, &mut load_context)
.await
.map_err(Into::into)?;
Ok(load_context.finish(asset).into())
})
}
fn reader_required_features(&self, settings: &dyn Settings) -> ReaderRequiredFeatures {
let settings = settings
.downcast_ref::<L::Settings>()
.expect("AssetLoader settings should match the loader type");
<L as AssetLoader>::reader_required_features(settings)
}
fn extensions(&self) -> &[&str] {
<L as AssetLoader>::extensions(self)
}
fn deserialize_meta(&self, meta: &[u8]) -> Result<Box<dyn AssetMetaDyn>, DeserializeMetaError> {
let meta = AssetMeta::<L, ()>::deserialize(meta)?;
Ok(Box::new(meta))
}
fn default_meta(&self) -> Box<dyn AssetMetaDyn> {
Box::new(AssetMeta::<L, ()>::new(crate::meta::AssetAction::Load {
loader: self.type_path().to_string(),
settings: L::Settings::default(),
}))
}
fn type_path(&self) -> &'static str {
L::type_path()
}
fn type_id(&self) -> TypeId {
TypeId::of::<L>()
}
fn asset_type_name(&self) -> &'static str {
core::any::type_name::<L::Asset>()
}
fn asset_type_id(&self) -> TypeId {
TypeId::of::<L::Asset>()
}
}
pub(crate) struct LabeledAsset {
pub(crate) asset: ErasedLoadedAsset,
pub(crate) handle: UntypedHandle,
}
/// The successful result of an [`AssetLoader::load`] call. This contains the loaded "root" asset and any other "labeled" assets produced
/// by the loader. It also holds the input [`AssetMeta`] (if it exists) and tracks dependencies:
/// * normal dependencies: dependencies that must be loaded as part of this asset load (ex: assets a given asset has handles to).
/// * Loader dependencies: dependencies whose actual asset values are used during the load process
pub struct LoadedAsset<A: Asset> {
pub(crate) value: A,
pub(crate) dependencies: HashSet<ErasedAssetIndex>,
pub(crate) loader_dependencies: HashMap<AssetPath<'static>, AssetHash>,
pub(crate) labeled_assets: HashMap<CowArc<'static, str>, LabeledAsset>,
}
impl<A: Asset> LoadedAsset<A> {
/// Create a new loaded asset. This will use [`VisitAssetDependencies`](crate::VisitAssetDependencies) to populate `dependencies`.
pub fn new_with_dependencies(value: A) -> Self {
let mut dependencies = <HashSet<_>>::default();
value.visit_dependencies(&mut |id| {
let Ok(asset_index) = id.try_into() else {
return;
};
dependencies.insert(asset_index);
});
LoadedAsset {
value,
dependencies,
loader_dependencies: HashMap::default(),
labeled_assets: HashMap::default(),
}
}
/// Cast (and take ownership) of the [`Asset`] value of the given type.
pub fn take(self) -> A {
self.value
}
/// Retrieves a reference to the internal [`Asset`] type.
pub fn get(&self) -> &A {
&self.value
}
/// Returns the [`ErasedLoadedAsset`] for the given label, if it exists.
pub fn get_labeled(
&self,
label: impl Into<CowArc<'static, str>>,
) -> Option<&ErasedLoadedAsset> {
self.labeled_assets.get(&label.into()).map(|a| &a.asset)
}
/// Iterate over all labels for "labeled assets" in the loaded asset
pub fn iter_labels(&self) -> impl Iterator<Item = &str> {
self.labeled_assets.keys().map(|s| &**s)
}
}
impl<A: Asset> From<A> for LoadedAsset<A> {
fn from(asset: A) -> Self {
LoadedAsset::new_with_dependencies(asset)
}
}
/// A "type erased / boxed" counterpart to [`LoadedAsset`]. This is used in places where the loaded type is not statically known.
pub struct ErasedLoadedAsset {
pub(crate) value: Box<dyn AssetContainer>,
pub(crate) dependencies: HashSet<ErasedAssetIndex>,
pub(crate) loader_dependencies: HashMap<AssetPath<'static>, AssetHash>,
pub(crate) labeled_assets: HashMap<CowArc<'static, str>, LabeledAsset>,
}
impl<A: Asset> From<LoadedAsset<A>> for ErasedLoadedAsset {
fn from(asset: LoadedAsset<A>) -> Self {
ErasedLoadedAsset {
value: Box::new(asset.value),
dependencies: asset.dependencies,
loader_dependencies: asset.loader_dependencies,
labeled_assets: asset.labeled_assets,
}
}
}
impl ErasedLoadedAsset {
/// Cast (and take ownership) of the [`Asset`] value of the given type. This will return [`Some`] if
/// the stored type matches `A` and [`None`] if it does not.
pub fn take<A: Asset>(self) -> Option<A> {
self.value.downcast::<A>().map(|a| *a).ok()
}
/// Retrieves a reference to the internal [`Asset`] type, if it matches the type `A`. Otherwise returns [`None`].
pub fn get<A: Asset>(&self) -> Option<&A> {
self.value.downcast_ref::<A>()
}
/// Retrieves the [`TypeId`] of the stored [`Asset`] type.
pub fn asset_type_id(&self) -> TypeId {
(*self.value).type_id()
}
/// Retrieves the `type_name` of the stored [`Asset`] type.
pub fn asset_type_name(&self) -> &'static str {
self.value.asset_type_name()
}
/// Returns the [`ErasedLoadedAsset`] for the given label, if it exists.
pub fn get_labeled(
&self,
label: impl Into<CowArc<'static, str>>,
) -> Option<&ErasedLoadedAsset> {
self.labeled_assets.get(&label.into()).map(|a| &a.asset)
}
/// Iterate over all labels for "labeled assets" in the loaded asset
pub fn iter_labels(&self) -> impl Iterator<Item = &str> {
self.labeled_assets.keys().map(|s| &**s)
}
/// Cast this loaded asset as the given type. If the type does not match,
/// the original type-erased asset is returned.
pub fn downcast<A: Asset>(mut self) -> Result<LoadedAsset<A>, ErasedLoadedAsset> {
match self.value.downcast::<A>() {
Ok(value) => Ok(LoadedAsset {
value: *value,
dependencies: self.dependencies,
loader_dependencies: self.loader_dependencies,
labeled_assets: self.labeled_assets,
}),
Err(value) => {
self.value = value;
Err(self)
}
}
}
}
/// A type erased container for an [`Asset`] value that is capable of inserting the [`Asset`] into a [`World`]'s [`Assets`] collection.
pub(crate) trait AssetContainer: Downcast + Any + Send + Sync + 'static {
fn insert(self: Box<Self>, id: AssetIndex, world: &mut World);
fn asset_type_name(&self) -> &'static str;
}
impl_downcast!(AssetContainer);
impl<A: Asset> AssetContainer for A {
fn insert(self: Box<Self>, index: AssetIndex, world: &mut World) {
// We only ever call this if we know the asset is still alive, so it is fine to unwrap here.
world
.resource_mut::<Assets<A>>()
.insert(index, *self)
.expect("the AssetIndex is still valid");
}
fn asset_type_name(&self) -> &'static str {
core::any::type_name::<A>()
}
}
/// An error that occurs when attempting to call [`NestedLoader::load`] which
/// is configured to work [immediately].
///
/// [`NestedLoader::load`]: crate::NestedLoader::load
/// [immediately]: crate::Immediate
#[derive(Error, Debug)]
pub enum LoadDirectError {
#[error("Requested to load an asset path ({0:?}) with a subasset, but this is unsupported. See issue #18291")]
RequestedSubasset(AssetPath<'static>),
#[error("Failed to load dependency {dependency:?} {error}")]
LoadError {
dependency: AssetPath<'static>,
error: AssetLoadError,
},
}
/// An error that occurs while deserializing [`AssetMeta`].
#[derive(Error, Debug, Clone, PartialEq, Eq)]
pub enum DeserializeMetaError {
#[error("Failed to deserialize asset meta: {0:?}")]
DeserializeSettings(#[from] SpannedError),
#[error("Failed to deserialize minimal asset meta: {0:?}")]
DeserializeMinimal(SpannedError),
}
/// A context that provides access to assets in [`AssetLoader`]s, tracks dependencies, and collects asset load state.
///
/// Any asset state accessed by [`LoadContext`] will be tracked and stored for use in dependency events and asset preprocessing.
pub struct LoadContext<'a> {
pub(crate) asset_server: &'a AssetServer,
/// Specifies whether dependencies that are loaded deferred should be loaded.
///
/// This allows us to skip loads for cases where we're never going to use the asset and we just
/// need the dependency information, for example during asset processing.
pub(crate) should_load_dependencies: bool,
populate_hashes: bool,
asset_path: AssetPath<'static>,
pub(crate) dependencies: HashSet<ErasedAssetIndex>,
/// Direct dependencies used by this loader.
pub(crate) loader_dependencies: HashMap<AssetPath<'static>, AssetHash>,
pub(crate) labeled_assets: HashMap<CowArc<'static, str>, LabeledAsset>,
}
impl<'a> LoadContext<'a> {
/// Creates a new [`LoadContext`] instance.
pub(crate) fn new(
asset_server: &'a AssetServer,
asset_path: AssetPath<'static>,
should_load_dependencies: bool,
populate_hashes: bool,
) -> Self {
Self {
asset_server,
asset_path,
populate_hashes,
should_load_dependencies,
dependencies: HashSet::default(),
loader_dependencies: HashMap::default(),
labeled_assets: HashMap::default(),
}
}
/// Begins a new labeled asset load. Use the returned [`LoadContext`] to load
/// dependencies for the new asset and call [`LoadContext::finish`] to finalize the asset load.
/// When finished, make sure you call [`LoadContext::add_loaded_labeled_asset`] to add the results back to the parent
/// context.
/// Prefer [`LoadContext::labeled_asset_scope`] when possible, which will automatically add
/// the labeled [`LoadContext`] back to the parent context.
/// [`LoadContext::begin_labeled_asset`] exists largely to enable parallel asset loading.
///
/// See [`AssetPath`] for more on labeled assets.
///
/// ```no_run
/// # use bevy_asset::{Asset, LoadContext};
/// # use bevy_reflect::TypePath;
/// # #[derive(Asset, TypePath, Default)]
/// # struct Image;
/// # let load_context: LoadContext = panic!();
/// let mut handles = Vec::new();
/// for i in 0..2 {
/// let labeled = load_context.begin_labeled_asset();
/// handles.push(std::thread::spawn(move || {
/// (i.to_string(), labeled.finish(Image::default()))
/// }));
/// }
///
/// for handle in handles {
/// let (label, loaded_asset) = handle.join().unwrap();
/// load_context.add_loaded_labeled_asset(label, loaded_asset);
/// }
/// ```
pub fn begin_labeled_asset(&self) -> LoadContext<'_> {
LoadContext::new(
self.asset_server,
self.asset_path.clone(),
self.should_load_dependencies,
self.populate_hashes,
)
}
/// Creates a new [`LoadContext`] for the given `label`. The `load` function is responsible for loading an [`Asset`] of
/// type `A`. `load` will be called immediately and the result will be used to finalize the [`LoadContext`], resulting in a new
/// [`LoadedAsset`], which is registered under the `label` label.
///
/// This exists to remove the need to manually call [`LoadContext::begin_labeled_asset`] and then manually register the
/// result with [`LoadContext::add_loaded_labeled_asset`].
///
/// See [`AssetPath`] for more on labeled assets.
pub fn labeled_asset_scope<A: Asset, E>(
&mut self,
label: String,
load: impl FnOnce(&mut LoadContext) -> Result<A, E>,
) -> Result<Handle<A>, E> {
let mut context = self.begin_labeled_asset();
let asset = load(&mut context)?;
let loaded_asset = context.finish(asset);
Ok(self.add_loaded_labeled_asset(label, loaded_asset))
}
/// This will add the given `asset` as a "labeled [`Asset`]" with the `label` label.
///
/// # Warning
///
/// This will not assign dependencies to the given `asset`. If adding an asset
/// with dependencies generated from calls such as [`LoadContext::load`], use
/// [`LoadContext::labeled_asset_scope`] or [`LoadContext::begin_labeled_asset`] to generate a
/// new [`LoadContext`] to track the dependencies for the labeled asset.
///
/// See [`AssetPath`] for more on labeled assets.
pub fn add_labeled_asset<A: Asset>(&mut self, label: String, asset: A) -> Handle<A> {
self.labeled_asset_scope(label, |_| Ok::<_, ()>(asset))
.expect("the closure returns Ok")
}
/// Add a [`LoadedAsset`] that is a "labeled sub asset" of the root path of this load context.
/// This can be used in combination with [`LoadContext::begin_labeled_asset`] to parallelize
/// sub asset loading.
///
/// See [`AssetPath`] for more on labeled assets.
pub fn add_loaded_labeled_asset<A: Asset>(
&mut self,
label: impl Into<CowArc<'static, str>>,
loaded_asset: LoadedAsset<A>,
) -> Handle<A> {
let label = label.into();
let loaded_asset: ErasedLoadedAsset = loaded_asset.into();
let labeled_path = self.asset_path.clone().with_label(label.clone());
let handle = self
.asset_server
.get_or_create_path_handle(labeled_path, None);
self.labeled_assets.insert(
label,
LabeledAsset {
asset: loaded_asset,
handle: handle.clone().untyped(),
},
);
handle
}
/// Returns `true` if an asset with the label `label` exists in this context.
///
/// See [`AssetPath`] for more on labeled assets.
pub fn has_labeled_asset<'b>(&self, label: impl Into<CowArc<'b, str>>) -> bool {
let path = self.asset_path.clone().with_label(label.into());
!self.asset_server.get_handles_untyped(&path).is_empty()
}
/// "Finishes" this context by populating the final [`Asset`] value.
pub fn finish<A: Asset>(mut self, value: A) -> LoadedAsset<A> {
// At this point, we assume the asset/subasset is "locked in" and won't be changed, so we
// can ensure all the dependencies are included (in case a handle was used without loading
// it through this `LoadContext`). If in the future we provide an API for mutating assets in
// `LoadedAsset`, `ErasedLoadedAsset`, or `LoadContext` (for mutating existing subassets),
// we should move this to some point after those mutations are not possible. This spot is
// convenient because we still have access to the static type of `A`.
value.visit_dependencies(&mut |asset_id| {
let (type_id, index) = match asset_id {
UntypedAssetId::Index { type_id, index } => (type_id, index),
// UUID assets can't be loaded anyway, so just ignore this ID.
UntypedAssetId::Uuid { .. } => return,
};
self.dependencies
.insert(ErasedAssetIndex { index, type_id });
});
LoadedAsset {
value,
dependencies: self.dependencies,
loader_dependencies: self.loader_dependencies,
labeled_assets: self.labeled_assets,
}
}
/// Gets the source asset path for this load context.
pub fn path(&self) -> &AssetPath<'static> {
&self.asset_path
}
/// Reads the asset at the given path and returns its bytes
pub async fn read_asset_bytes<'b, 'c>(
&'b mut self,
path: impl Into<AssetPath<'c>>,
) -> Result<Vec<u8>, ReadAssetBytesError> {
let path = path.into();
let source = self.asset_server.get_source(path.source())?;
let asset_reader = match self.asset_server.mode() {
AssetServerMode::Unprocessed => source.reader(),
AssetServerMode::Processed => source.processed_reader()?,
};
let mut reader = asset_reader
.read(path.path(), ReaderRequiredFeatures::default())
.await?;
let hash = if self.populate_hashes {
// NOTE: ensure meta is read while the asset bytes reader is still active to ensure transactionality
// See `ProcessorGatedReader` for more info
let meta_bytes = asset_reader.read_meta_bytes(path.path()).await?;
let minimal: ProcessedInfoMinimal = ron::de::from_bytes(&meta_bytes)
.map_err(DeserializeMetaError::DeserializeMinimal)?;
let processed_info = minimal
.processed_info
.ok_or(ReadAssetBytesError::MissingAssetHash)?;
processed_info.full_hash
} else {
Default::default()
};
let mut bytes = Vec::new();
reader
.read_to_end(&mut bytes)
.await
.map_err(|source| ReadAssetBytesError::Io {
path: path.path().to_path_buf(),
source,
})?;
self.loader_dependencies.insert(path.clone_owned(), hash);
Ok(bytes)
}
/// Returns a handle to an asset of type `A` with the label `label`. This [`LoadContext`] must produce an asset of the
/// given type and the given label or the dependencies of this asset will never be considered "fully loaded". However you
/// can call this method before _or_ after adding the labeled asset.
pub fn get_label_handle<'b, A: Asset>(
&mut self,
label: impl Into<CowArc<'b, str>>,
) -> Handle<A> {
let path = self.asset_path.clone().with_label(label);
let handle = self.asset_server.get_or_create_path_handle::<A>(path, None);
// `get_or_create_path_handle` always returns a Strong variant, so we are safe to unwrap.
let index = (&handle).try_into().unwrap();
self.dependencies.insert(index);
handle
}
pub(crate) async fn load_direct_internal(
&mut self,
path: AssetPath<'static>,
settings: &dyn Settings,
loader: &dyn ErasedAssetLoader,
reader: &mut dyn Reader,
processed_info: Option<&ProcessedInfo>,
) -> Result<ErasedLoadedAsset, LoadDirectError> {
let loaded_asset = self
.asset_server
.load_with_settings_loader_and_reader(
&path,
settings,
loader,
reader,
self.should_load_dependencies,
self.populate_hashes,
)
.await
.map_err(|error| LoadDirectError::LoadError {
dependency: path.clone(),
error,
})?;
let hash = processed_info.map(|i| i.full_hash).unwrap_or_default();
self.loader_dependencies.insert(path, hash);
Ok(loaded_asset)
}
/// Create a builder for loading nested assets in this context.
#[must_use]
pub fn loader(&mut self) -> NestedLoader<'a, '_, StaticTyped, Deferred> {
NestedLoader::new(self)
}
/// Retrieves a handle for the asset at the given path and adds that path as a dependency of the asset.
/// If the current context is a normal [`AssetServer::load`], an actual asset load will be kicked off immediately, which ensures the load happens
/// as soon as possible.
/// "Normal loads" kicked from within a normal Bevy App will generally configure the context to kick off loads immediately.
/// If the current context is configured to not load dependencies automatically (ex: [`AssetProcessor`](crate::processor::AssetProcessor)),
/// a load will not be kicked off automatically. It is then the calling context's responsibility to begin a load if necessary.
///
/// If you need to override asset settings, asset type, or load directly, please see [`LoadContext::loader`].
pub fn load<'b, A: Asset>(&mut self, path: impl Into<AssetPath<'b>>) -> Handle<A> {
self.loader().load(path)
}
}
/// An error produced when calling [`LoadContext::read_asset_bytes`]
#[derive(Error, Debug)]
pub enum ReadAssetBytesError {
#[error(transparent)]
DeserializeMetaError(#[from] DeserializeMetaError),
#[error(transparent)]
AssetReaderError(#[from] AssetReaderError),
#[error(transparent)]
MissingAssetSourceError(#[from] MissingAssetSourceError),
#[error(transparent)]
MissingProcessedAssetReaderError(#[from] MissingProcessedAssetReaderError),
/// Encountered an I/O error while loading an asset.
#[error("Encountered an io error while loading asset at `{}`: {source}", path.display())]
Io {
path: PathBuf,
source: std::io::Error,
},
#[error("The LoadContext for this read_asset_bytes call requires hash metadata, but it was not provided. This is likely an internal implementation error.")]
MissingAssetHash,
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/meta.rs | crates/bevy_asset/src/meta.rs | use alloc::{
boxed::Box,
string::{String, ToString},
vec::Vec,
};
use futures_lite::AsyncReadExt;
use crate::{
io::{AssetReaderError, Reader},
loader::AssetLoader,
processor::Process,
Asset, AssetPath, DeserializeMetaError, VisitAssetDependencies,
};
use downcast_rs::{impl_downcast, Downcast};
use ron::ser::PrettyConfig;
use serde::{Deserialize, Serialize};
use tracing::error;
pub const META_FORMAT_VERSION: &str = "1.0";
pub type MetaTransform = Box<dyn Fn(&mut dyn AssetMetaDyn) + Send + Sync>;
/// Asset metadata that informs how an [`Asset`] should be handled by the asset system.
///
/// `L` is the [`AssetLoader`] (if one is configured) for the [`AssetAction`]. This can be `()` if it is not required.
/// `P` is the [`Process`] processor, if one is configured for the [`AssetAction`]. This can be `()` if it is not required.
#[derive(Serialize, Deserialize)]
pub struct AssetMeta<L: AssetLoader, P: Process> {
/// The version of the meta format being used. This will change whenever a breaking change is made to
/// the meta format.
pub meta_format_version: String,
/// Information produced by the [`AssetProcessor`] _after_ processing this asset.
/// This will only exist alongside processed versions of assets. You should not manually set it in your asset source files.
///
/// [`AssetProcessor`]: crate::processor::AssetProcessor
#[serde(skip_serializing_if = "Option::is_none")]
pub processed_info: Option<ProcessedInfo>,
/// How to handle this asset in the asset system. See [`AssetAction`].
pub asset: AssetAction<L::Settings, P::Settings>,
}
impl<L: AssetLoader, P: Process> AssetMeta<L, P> {
pub fn new(asset: AssetAction<L::Settings, P::Settings>) -> Self {
Self {
meta_format_version: META_FORMAT_VERSION.to_string(),
processed_info: None,
asset,
}
}
/// Deserializes the given serialized byte representation of the asset meta.
pub fn deserialize(bytes: &[u8]) -> Result<Self, DeserializeMetaError> {
Ok(ron::de::from_bytes(bytes)?)
}
}
/// Configures how an asset source file should be handled by the asset system.
#[derive(Serialize, Deserialize)]
pub enum AssetAction<LoaderSettings, ProcessSettings> {
/// Load the asset with the given loader and settings
/// See [`AssetLoader`].
Load {
loader: String,
settings: LoaderSettings,
},
/// Process the asset with the given processor and settings.
/// See [`Process`] and [`AssetProcessor`].
///
/// [`AssetProcessor`]: crate::processor::AssetProcessor
Process {
processor: String,
settings: ProcessSettings,
},
/// Do nothing with the asset
Ignore,
}
/// Info produced by the [`AssetProcessor`] for a given processed asset. This is used to determine if an
/// asset source file (or its dependencies) has changed.
///
/// [`AssetProcessor`]: crate::processor::AssetProcessor
#[derive(Serialize, Deserialize, Default, Debug, Clone)]
pub struct ProcessedInfo {
/// A hash of the asset bytes and the asset .meta data
pub hash: AssetHash,
/// A hash of the asset bytes, the asset .meta data, and the `full_hash` of every `process_dependency`
pub full_hash: AssetHash,
/// Information about the "process dependencies" used to process this asset.
pub process_dependencies: Vec<ProcessDependencyInfo>,
}
/// Information about a dependency used to process an asset. This is used to determine whether an asset's "process dependency"
/// has changed.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ProcessDependencyInfo {
pub full_hash: AssetHash,
pub path: AssetPath<'static>,
}
/// This is a minimal counterpart to [`AssetMeta`] that exists to speed up (or enable) serialization in cases where the whole [`AssetMeta`] isn't
/// necessary.
// PERF:
// Currently, this is used when retrieving asset loader and processor information (when the actual type is not known yet). This could probably
// be replaced (and made more efficient) by a custom deserializer that reads the loader/processor information _first_, then deserializes the contents
// using a type registry.
#[derive(Serialize, Deserialize)]
pub struct AssetMetaMinimal {
pub asset: AssetActionMinimal,
}
/// This is a minimal counterpart to [`AssetAction`] that exists to speed up (or enable) serialization in cases where the whole [`AssetAction`]
/// isn't necessary.
#[derive(Serialize, Deserialize)]
pub enum AssetActionMinimal {
Load { loader: String },
Process { processor: String },
Ignore,
}
/// This is a minimal counterpart to [`ProcessedInfo`] that exists to speed up serialization in cases where the whole [`ProcessedInfo`] isn't
/// necessary.
#[derive(Serialize, Deserialize)]
pub struct ProcessedInfoMinimal {
pub processed_info: Option<ProcessedInfo>,
}
/// A dynamic type-erased counterpart to [`AssetMeta`] that enables passing around and interacting with [`AssetMeta`] without knowing
/// its type.
pub trait AssetMetaDyn: Downcast + Send + Sync {
/// Returns a reference to the [`AssetLoader`] settings, if they exist.
fn loader_settings(&self) -> Option<&dyn Settings>;
/// Returns a mutable reference to the [`AssetLoader`] settings, if they exist.
fn loader_settings_mut(&mut self) -> Option<&mut dyn Settings>;
/// Returns a reference to the [`Process`] settings, if they exist.
fn process_settings(&self) -> Option<&dyn Settings>;
/// Serializes the internal [`AssetMeta`].
fn serialize(&self) -> Vec<u8>;
/// Returns a reference to the [`ProcessedInfo`] if it exists.
fn processed_info(&self) -> &Option<ProcessedInfo>;
/// Returns a mutable reference to the [`ProcessedInfo`] if it exists.
fn processed_info_mut(&mut self) -> &mut Option<ProcessedInfo>;
}
impl<L: AssetLoader, P: Process> AssetMetaDyn for AssetMeta<L, P> {
fn loader_settings(&self) -> Option<&dyn Settings> {
if let AssetAction::Load { settings, .. } = &self.asset {
Some(settings)
} else {
None
}
}
fn loader_settings_mut(&mut self) -> Option<&mut dyn Settings> {
if let AssetAction::Load { settings, .. } = &mut self.asset {
Some(settings)
} else {
None
}
}
fn process_settings(&self) -> Option<&dyn Settings> {
if let AssetAction::Process { settings, .. } = &self.asset {
Some(settings)
} else {
None
}
}
fn serialize(&self) -> Vec<u8> {
ron::ser::to_string_pretty(
&self,
// This defaults to \r\n on Windows, so hard-code it to \n so it's consistent for
// testing.
PrettyConfig::default().new_line("\n"),
)
.expect("type is convertible to ron")
.into_bytes()
}
fn processed_info(&self) -> &Option<ProcessedInfo> {
&self.processed_info
}
fn processed_info_mut(&mut self) -> &mut Option<ProcessedInfo> {
&mut self.processed_info
}
}
impl_downcast!(AssetMetaDyn);
/// Settings used by the asset system, such as by [`AssetLoader`], [`Process`], and [`AssetSaver`]
///
/// [`AssetSaver`]: crate::saver::AssetSaver
pub trait Settings: Downcast + Send + Sync + 'static {}
impl<T: 'static> Settings for T where T: Send + Sync {}
impl_downcast!(Settings);
/// The () processor should never be called. This implementation exists to make the meta format nicer to work with.
impl Process for () {
type Settings = ();
type OutputLoader = ();
async fn process(
&self,
_context: &mut bevy_asset::processor::ProcessContext<'_>,
_settings: &Self::Settings,
_writer: &mut bevy_asset::io::Writer,
) -> Result<(), bevy_asset::processor::ProcessError> {
unreachable!()
}
}
impl Asset for () {}
impl VisitAssetDependencies for () {
fn visit_dependencies(&self, _visit: &mut impl FnMut(bevy_asset::UntypedAssetId)) {
unreachable!()
}
}
/// The () loader should never be called. This implementation exists to make the meta format nicer to work with.
impl AssetLoader for () {
type Asset = ();
type Settings = ();
type Error = std::io::Error;
async fn load(
&self,
_reader: &mut dyn Reader,
_settings: &Self::Settings,
_load_context: &mut crate::LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
unreachable!();
}
fn reader_required_features(_settings: &Self::Settings) -> crate::io::ReaderRequiredFeatures {
unreachable!();
}
fn extensions(&self) -> &[&str] {
unreachable!();
}
}
pub(crate) fn meta_transform_settings<S: Settings>(
meta: &mut dyn AssetMetaDyn,
settings: &(impl Fn(&mut S) + Send + Sync + 'static),
) {
if let Some(loader_settings) = meta.loader_settings_mut() {
if let Some(loader_settings) = loader_settings.downcast_mut::<S>() {
settings(loader_settings);
} else {
error!(
"Configured settings type {} does not match AssetLoader settings type",
core::any::type_name::<S>(),
);
}
}
}
pub(crate) fn loader_settings_meta_transform<S: Settings>(
settings: impl Fn(&mut S) + Send + Sync + 'static,
) -> MetaTransform {
Box::new(move |meta| meta_transform_settings(meta, &settings))
}
pub type AssetHash = [u8; 32];
/// NOTE: changing the hashing logic here is a _breaking change_ that requires a [`META_FORMAT_VERSION`] bump.
pub(crate) async fn get_asset_hash(
meta_bytes: &[u8],
asset_reader: &mut impl Reader,
) -> Result<AssetHash, AssetReaderError> {
let mut hasher = blake3::Hasher::new();
hasher.update(meta_bytes);
let mut buffer = [0; blake3::CHUNK_LEN];
loop {
let bytes_read = asset_reader.read(&mut buffer).await?;
hasher.update(&buffer[..bytes_read]);
if bytes_read == 0 {
// This means we've reached EOF, so we're done consuming asset bytes.
break;
}
}
Ok(*hasher.finalize().as_bytes())
}
/// NOTE: changing the hashing logic here is a _breaking change_ that requires a [`META_FORMAT_VERSION`] bump.
pub(crate) fn get_full_asset_hash(
asset_hash: AssetHash,
dependency_hashes: impl Iterator<Item = AssetHash>,
) -> AssetHash {
let mut hasher = blake3::Hasher::new();
hasher.update(&asset_hash);
for hash in dependency_hashes {
hasher.update(&hash);
}
*hasher.finalize().as_bytes()
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/loader_builders.rs | crates/bevy_asset/src/loader_builders.rs | //! Implementations of the builder-pattern used for loading dependent assets via
//! [`LoadContext::loader`].
use crate::{
io::Reader,
meta::{meta_transform_settings, AssetMetaDyn, MetaTransform, Settings},
Asset, AssetLoadError, AssetPath, ErasedAssetLoader, ErasedLoadedAsset, Handle, LoadContext,
LoadDirectError, LoadedAsset, LoadedUntypedAsset, UntypedHandle,
};
use alloc::{borrow::ToOwned, boxed::Box, sync::Arc};
use core::any::TypeId;
// Utility type for handling the sources of reader references
enum ReaderRef<'a> {
Borrowed(&'a mut dyn Reader),
Boxed(Box<dyn Reader + 'a>),
}
impl ReaderRef<'_> {
pub fn as_mut(&mut self) -> &mut dyn Reader {
match self {
ReaderRef::Borrowed(r) => &mut **r,
ReaderRef::Boxed(b) => &mut **b,
}
}
}
/// A builder for loading nested assets inside a [`LoadContext`].
///
/// # Loader state
///
/// The type parameters `T` and `M` determine how this will load assets:
/// - `T`: the typing of this loader. How do we know what type of asset to load?
///
/// See [`StaticTyped`] (the default), [`DynamicTyped`], and [`UnknownTyped`].
///
/// - `M`: the load mode. Do we want to load this asset right now (in which case
/// you will have to `await` the operation), or do we just want a [`Handle`],
/// and leave the actual asset loading to later?
///
/// See [`Deferred`] (the default) and [`Immediate`].
///
/// When configuring this builder, you can freely switch between these modes
/// via functions like [`deferred`] and [`immediate`].
///
/// ## Typing
///
/// To inform the loader of what type of asset to load:
/// - in [`StaticTyped`]: statically providing a type parameter `A: Asset` to
/// [`load`].
///
/// This is the simplest way to get a [`Handle<A>`] to the loaded asset, as
/// long as you know the type of `A` at compile time.
///
/// - in [`DynamicTyped`]: providing the [`TypeId`] of the asset at runtime.
///
/// If you know the type ID of the asset at runtime, but not at compile time,
/// use [`with_dynamic_type`] followed by [`load`] to start loading an asset
/// of that type. This lets you get an [`UntypedHandle`] (via [`Deferred`]),
/// or a [`ErasedLoadedAsset`] (via [`Immediate`]).
///
/// - in [`UnknownTyped`]: loading either a type-erased version of the asset
/// ([`ErasedLoadedAsset`]), or a handle *to a handle* of the actual asset
/// ([`LoadedUntypedAsset`]).
///
/// If you have no idea what type of asset you will be loading (not even at
/// runtime with a [`TypeId`]), use this.
///
/// ## Load mode
///
/// To inform the loader how you want to load the asset:
/// - in [`Deferred`]: when you request to load the asset, you get a [`Handle`]
/// for it, but the actual loading won't be completed until later.
///
/// Use this if you only need a [`Handle`] or [`UntypedHandle`].
///
/// - in [`Immediate`]: the load request will load the asset right then and
/// there, waiting until the asset is fully loaded and giving you access to
/// it.
///
/// Note that this requires you to `await` a future, so you must be in an
/// async context to use direct loading. In an asset loader, you will be in
/// an async context.
///
/// Use this if you need the *value* of another asset in order to load the
/// current asset. For example, if you are deriving a new asset from the
/// referenced asset, or you are building a collection of assets. This will
/// add the path of the asset as a "load dependency".
///
/// If the current loader is used in a [`Process`] "asset preprocessor",
/// such as a [`LoadTransformAndSave`] preprocessor, changing a "load
/// dependency" will result in re-processing of the asset.
///
/// # Load kickoff
///
/// If the current context is a normal [`AssetServer::load`], an actual asset
/// load will be kicked off immediately, which ensures the load happens as soon
/// as possible. "Normal loads" kicked from within a normal Bevy App will
/// generally configure the context to kick off loads immediately.
///
/// If the current context is configured to not load dependencies automatically
/// (ex: [`AssetProcessor`]), a load will not be kicked off automatically. It is
/// then the calling context's responsibility to begin a load if necessary.
///
/// # Lifetimes
///
/// - `ctx`: the lifetime of the associated [`AssetServer`](crate::AssetServer) reference
/// - `builder`: the lifetime of the temporary builder structs
///
/// [`deferred`]: Self::deferred
/// [`immediate`]: Self::immediate
/// [`load`]: Self::load
/// [`with_dynamic_type`]: Self::with_dynamic_type
/// [`AssetServer::load`]: crate::AssetServer::load
/// [`AssetProcessor`]: crate::processor::AssetProcessor
/// [`Process`]: crate::processor::Process
/// [`LoadTransformAndSave`]: crate::processor::LoadTransformAndSave
pub struct NestedLoader<'ctx, 'builder, T, M> {
load_context: &'builder mut LoadContext<'ctx>,
meta_transform: Option<MetaTransform>,
typing: T,
mode: M,
}
mod sealed {
pub trait Typing {}
pub trait Mode {}
}
/// [`NestedLoader`] will be provided the type of asset as a type parameter on
/// [`load`].
///
/// [`load`]: NestedLoader::load
pub struct StaticTyped(());
impl sealed::Typing for StaticTyped {}
/// [`NestedLoader`] has been configured with info on what type of asset to load
/// at runtime.
pub struct DynamicTyped {
asset_type_id: TypeId,
}
impl sealed::Typing for DynamicTyped {}
/// [`NestedLoader`] does not know what type of asset it will be loading.
pub struct UnknownTyped(());
impl sealed::Typing for UnknownTyped {}
/// [`NestedLoader`] will create and return asset handles immediately, but only
/// actually load the asset later.
pub struct Deferred(());
impl sealed::Mode for Deferred {}
/// [`NestedLoader`] will immediately load an asset when requested.
pub struct Immediate<'builder, 'reader> {
reader: Option<&'builder mut (dyn Reader + 'reader)>,
}
impl sealed::Mode for Immediate<'_, '_> {}
// common to all states
impl<'ctx, 'builder> NestedLoader<'ctx, 'builder, StaticTyped, Deferred> {
pub(crate) fn new(load_context: &'builder mut LoadContext<'ctx>) -> Self {
NestedLoader {
load_context,
meta_transform: None,
typing: StaticTyped(()),
mode: Deferred(()),
}
}
}
impl<'ctx, 'builder, T: sealed::Typing, M: sealed::Mode> NestedLoader<'ctx, 'builder, T, M> {
fn with_transform(
mut self,
transform: impl Fn(&mut dyn AssetMetaDyn) + Send + Sync + 'static,
) -> Self {
if let Some(prev_transform) = self.meta_transform {
self.meta_transform = Some(Box::new(move |meta| {
prev_transform(meta);
transform(meta);
}));
} else {
self.meta_transform = Some(Box::new(transform));
}
self
}
/// Configure the settings used to load the asset.
///
/// If the settings type `S` does not match the settings expected by `A`'s asset loader, an error will be printed to the log
/// and the asset load will fail.
#[must_use]
pub fn with_settings<S: Settings>(
self,
settings: impl Fn(&mut S) + Send + Sync + 'static,
) -> Self {
self.with_transform(move |meta| meta_transform_settings(meta, &settings))
}
// convert between `T`s
/// When [`load`]ing, you must pass in the asset type as a type parameter
/// statically.
///
/// If you don't know the type statically (at compile time), consider
/// [`with_dynamic_type`] or [`with_unknown_type`].
///
/// [`load`]: Self::load
/// [`with_dynamic_type`]: Self::with_dynamic_type
/// [`with_unknown_type`]: Self::with_unknown_type
#[must_use]
pub fn with_static_type(self) -> NestedLoader<'ctx, 'builder, StaticTyped, M> {
NestedLoader {
load_context: self.load_context,
meta_transform: self.meta_transform,
typing: StaticTyped(()),
mode: self.mode,
}
}
/// When [`load`]ing, the loader will attempt to load an asset with the
/// given [`TypeId`].
///
/// [`load`]: Self::load
#[must_use]
pub fn with_dynamic_type(
self,
asset_type_id: TypeId,
) -> NestedLoader<'ctx, 'builder, DynamicTyped, M> {
NestedLoader {
load_context: self.load_context,
meta_transform: self.meta_transform,
typing: DynamicTyped { asset_type_id },
mode: self.mode,
}
}
/// When [`load`]ing, we will infer what type of asset to load from
/// metadata.
///
/// [`load`]: Self::load
#[must_use]
pub fn with_unknown_type(self) -> NestedLoader<'ctx, 'builder, UnknownTyped, M> {
NestedLoader {
load_context: self.load_context,
meta_transform: self.meta_transform,
typing: UnknownTyped(()),
mode: self.mode,
}
}
// convert between `M`s
/// When [`load`]ing, create only asset handles, rather than returning the
/// actual asset.
///
/// [`load`]: Self::load
pub fn deferred(self) -> NestedLoader<'ctx, 'builder, T, Deferred> {
NestedLoader {
load_context: self.load_context,
meta_transform: self.meta_transform,
typing: self.typing,
mode: Deferred(()),
}
}
/// The [`load`] call itself will load an asset, rather than scheduling the
/// loading to happen later.
///
/// This gives you access to the loaded asset, but requires you to be in an
/// async context, and be able to `await` the resulting future.
///
/// [`load`]: Self::load
#[must_use]
pub fn immediate<'c>(self) -> NestedLoader<'ctx, 'builder, T, Immediate<'builder, 'c>> {
NestedLoader {
load_context: self.load_context,
meta_transform: self.meta_transform,
typing: self.typing,
mode: Immediate { reader: None },
}
}
}
// deferred loading logic
impl NestedLoader<'_, '_, StaticTyped, Deferred> {
/// Retrieves a handle for the asset at the given path and adds that path as
/// a dependency of this asset.
///
/// This requires you to know the type of asset statically.
/// - If you have runtime info for what type of asset you're loading (e.g. a
/// [`TypeId`]), use [`with_dynamic_type`].
/// - If you do not know at all what type of asset you're loading, use
/// [`with_unknown_type`].
///
/// [`with_dynamic_type`]: Self::with_dynamic_type
/// [`with_unknown_type`]: Self::with_unknown_type
pub fn load<'c, A: Asset>(self, path: impl Into<AssetPath<'c>>) -> Handle<A> {
let path = path.into().to_owned();
let handle = if self.load_context.should_load_dependencies {
self.load_context.asset_server.load_with_meta_transform(
path,
self.meta_transform,
(),
true,
)
} else {
self.load_context
.asset_server
.get_or_create_path_handle(path, self.meta_transform)
};
// `load_with_meta_transform` and `get_or_create_path_handle` always returns a Strong
// variant, so we are safe to unwrap.
let index = (&handle).try_into().unwrap();
self.load_context.dependencies.insert(index);
handle
}
}
impl NestedLoader<'_, '_, DynamicTyped, Deferred> {
/// Retrieves a handle for the asset at the given path and adds that path as
/// a dependency of this asset.
///
/// This requires you to pass in the asset type ID into
/// [`with_dynamic_type`].
///
/// [`with_dynamic_type`]: Self::with_dynamic_type
pub fn load<'p>(self, path: impl Into<AssetPath<'p>>) -> UntypedHandle {
let path = path.into().to_owned();
let handle = if self.load_context.should_load_dependencies {
self.load_context
.asset_server
.load_erased_with_meta_transform(
path,
self.typing.asset_type_id,
self.meta_transform,
(),
)
} else {
self.load_context
.asset_server
.get_or_create_path_handle_erased(
path,
self.typing.asset_type_id,
self.meta_transform,
)
};
// `load_erased_with_meta_transform` and `get_or_create_path_handle_erased` always returns a
// Strong variant, so we are safe to unwrap.
let index = (&handle).try_into().unwrap();
self.load_context.dependencies.insert(index);
handle
}
}
impl NestedLoader<'_, '_, UnknownTyped, Deferred> {
/// Retrieves a handle for the asset at the given path and adds that path as
/// a dependency of this asset.
///
/// This will infer the asset type from metadata.
pub fn load<'p>(self, path: impl Into<AssetPath<'p>>) -> Handle<LoadedUntypedAsset> {
let path = path.into().to_owned();
let handle = if self.load_context.should_load_dependencies {
self.load_context
.asset_server
.load_unknown_type_with_meta_transform(path, self.meta_transform)
} else {
self.load_context
.asset_server
.get_or_create_path_handle(path, self.meta_transform)
};
// `load_unknown_type_with_meta_transform` and `get_or_create_path_handle` always returns a
// Strong variant, so we are safe to unwrap.
let index = (&handle).try_into().unwrap();
self.load_context.dependencies.insert(index);
handle
}
}
// immediate loading logic
impl<'builder, 'reader, T> NestedLoader<'_, '_, T, Immediate<'builder, 'reader>> {
/// Specify the reader to use to read the asset data.
#[must_use]
pub fn with_reader(mut self, reader: &'builder mut (dyn Reader + 'reader)) -> Self {
self.mode.reader = Some(reader);
self
}
async fn load_internal(
self,
path: &AssetPath<'static>,
asset_type_id: Option<TypeId>,
) -> Result<(Arc<dyn ErasedAssetLoader>, ErasedLoadedAsset), LoadDirectError> {
if path.label().is_some() {
return Err(LoadDirectError::RequestedSubasset(path.clone()));
}
self.load_context
.asset_server
.write_infos()
.stats
.started_load_tasks += 1;
let (mut meta, loader, mut reader) = if let Some(reader) = self.mode.reader {
let loader = if let Some(asset_type_id) = asset_type_id {
self.load_context
.asset_server
.get_asset_loader_with_asset_type_id(asset_type_id)
.await
.map_err(|error| LoadDirectError::LoadError {
dependency: path.clone(),
error: error.into(),
})?
} else {
self.load_context
.asset_server
.get_path_asset_loader(path)
.await
.map_err(|error| LoadDirectError::LoadError {
dependency: path.clone(),
error: error.into(),
})?
};
let meta = loader.default_meta();
(meta, loader, ReaderRef::Borrowed(reader))
} else {
let (meta, loader, reader) = self
.load_context
.asset_server
.get_meta_loader_and_reader(path, asset_type_id)
.await
.map_err(|error| LoadDirectError::LoadError {
dependency: path.clone(),
error,
})?;
(meta, loader, ReaderRef::Boxed(reader))
};
if let Some(meta_transform) = self.meta_transform {
meta_transform(&mut *meta);
}
let asset = self
.load_context
.load_direct_internal(
path.clone(),
meta.loader_settings().expect("meta corresponds to a load"),
&*loader,
reader.as_mut(),
meta.processed_info().as_ref(),
)
.await?;
Ok((loader, asset))
}
}
impl NestedLoader<'_, '_, StaticTyped, Immediate<'_, '_>> {
/// Attempts to load the asset at the given `path` immediately.
///
/// This requires you to know the type of asset statically.
/// - If you have runtime info for what type of asset you're loading (e.g. a
/// [`TypeId`]), use [`with_dynamic_type`].
/// - If you do not know at all what type of asset you're loading, use
/// [`with_unknown_type`].
///
/// [`with_dynamic_type`]: Self::with_dynamic_type
/// [`with_unknown_type`]: Self::with_unknown_type
pub async fn load<'p, A: Asset>(
self,
path: impl Into<AssetPath<'p>>,
) -> Result<LoadedAsset<A>, LoadDirectError> {
let path = path.into().into_owned();
self.load_internal(&path, Some(TypeId::of::<A>()))
.await
.and_then(move |(loader, untyped_asset)| {
untyped_asset
.downcast::<A>()
.map_err(|_| LoadDirectError::LoadError {
dependency: path.clone(),
error: AssetLoadError::RequestedHandleTypeMismatch {
path,
requested: TypeId::of::<A>(),
actual_asset_name: loader.asset_type_name(),
loader_name: loader.type_path(),
},
})
})
}
}
impl NestedLoader<'_, '_, DynamicTyped, Immediate<'_, '_>> {
/// Attempts to load the asset at the given `path` immediately.
///
/// This requires you to pass in the asset type ID into
/// [`with_dynamic_type`].
///
/// [`with_dynamic_type`]: Self::with_dynamic_type
pub async fn load<'p>(
self,
path: impl Into<AssetPath<'p>>,
) -> Result<ErasedLoadedAsset, LoadDirectError> {
let path = path.into().into_owned();
let asset_type_id = Some(self.typing.asset_type_id);
self.load_internal(&path, asset_type_id)
.await
.map(|(_, asset)| asset)
}
}
impl NestedLoader<'_, '_, UnknownTyped, Immediate<'_, '_>> {
/// Attempts to load the asset at the given `path` immediately.
///
/// This will infer the asset type from metadata.
pub async fn load<'p>(
self,
path: impl Into<AssetPath<'p>>,
) -> Result<ErasedLoadedAsset, LoadDirectError> {
let path = path.into().into_owned();
self.load_internal(&path, None)
.await
.map(|(_, asset)| asset)
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/saver.rs | crates/bevy_asset/src/saver.rs | use crate::{
io::Writer, meta::Settings, transformer::TransformedAsset, Asset, AssetLoader,
ErasedLoadedAsset, Handle, LabeledAsset, UntypedHandle,
};
use alloc::boxed::Box;
use atomicow::CowArc;
use bevy_platform::collections::HashMap;
use bevy_reflect::TypePath;
use bevy_tasks::{BoxedFuture, ConditionalSendFuture};
use core::{borrow::Borrow, hash::Hash, ops::Deref};
use serde::{Deserialize, Serialize};
/// 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.
///
/// This trait is generally used in concert with [`AssetWriter`](crate::io::AssetWriter) to write assets as bytes.
///
/// For a complementary version of this trait that can load assets, see [`AssetLoader`].
pub trait AssetSaver: TypePath + Send + Sync + 'static {
/// The top level [`Asset`] saved by this [`AssetSaver`].
type Asset: Asset;
/// The settings type used by this [`AssetSaver`].
type Settings: Settings + Default + Serialize + for<'a> Deserialize<'a>;
/// 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<Box<dyn core::error::Error + Send + Sync + 'static>>;
/// 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.
fn save(
&self,
writer: &mut Writer,
asset: SavedAsset<'_, Self::Asset>,
settings: &Self::Settings,
) -> impl ConditionalSendFuture<
Output = Result<<Self::OutputLoader as AssetLoader>::Settings, Self::Error>,
>;
}
/// A type-erased dynamic variant of [`AssetSaver`] that allows callers to save assets without knowing the actual type of the [`AssetSaver`].
pub trait ErasedAssetSaver: Send + Sync + 'static {
/// Saves the given runtime [`ErasedLoadedAsset`] by writing it to a byte format using `writer`. The passed in `settings` can influence how the
/// `asset` is saved.
fn save<'a>(
&'a self,
writer: &'a mut Writer,
asset: &'a ErasedLoadedAsset,
settings: &'a dyn Settings,
) -> BoxedFuture<'a, Result<(), Box<dyn core::error::Error + Send + Sync + 'static>>>;
/// The type name of the [`AssetSaver`].
fn type_name(&self) -> &'static str;
}
impl<S: AssetSaver> ErasedAssetSaver for S {
fn save<'a>(
&'a self,
writer: &'a mut Writer,
asset: &'a ErasedLoadedAsset,
settings: &'a dyn Settings,
) -> BoxedFuture<'a, Result<(), Box<dyn core::error::Error + Send + Sync + 'static>>> {
Box::pin(async move {
let settings = settings
.downcast_ref::<S::Settings>()
.expect("AssetLoader settings should match the loader type");
let saved_asset = SavedAsset::<S::Asset>::from_loaded(asset).unwrap();
if let Err(err) = self.save(writer, saved_asset, settings).await {
return Err(err.into());
}
Ok(())
})
}
fn type_name(&self) -> &'static str {
core::any::type_name::<S>()
}
}
/// An [`Asset`] (and any labeled "sub assets") intended to be saved.
pub struct SavedAsset<'a, A: Asset> {
value: &'a A,
labeled_assets: &'a HashMap<CowArc<'static, str>, LabeledAsset>,
}
impl<'a, A: Asset> Deref for SavedAsset<'a, A> {
type Target = A;
fn deref(&self) -> &Self::Target {
self.value
}
}
impl<'a, A: Asset> SavedAsset<'a, A> {
/// Creates a new [`SavedAsset`] from `asset` if its internal value matches `A`.
pub fn from_loaded(asset: &'a ErasedLoadedAsset) -> Option<Self> {
let value = asset.value.downcast_ref::<A>()?;
Some(SavedAsset {
value,
labeled_assets: &asset.labeled_assets,
})
}
/// Creates a new [`SavedAsset`] from the a [`TransformedAsset`]
pub fn from_transformed(asset: &'a TransformedAsset<A>) -> Self {
Self {
value: &asset.value,
labeled_assets: &asset.labeled_assets,
}
}
/// Retrieves the value of this asset.
#[inline]
pub fn get(&self) -> &'a A {
self.value
}
/// Returns the labeled asset, if it exists and matches this type.
pub fn get_labeled<B: Asset, Q>(&self, label: &Q) -> Option<SavedAsset<'_, B>>
where
CowArc<'static, str>: Borrow<Q>,
Q: ?Sized + Hash + Eq,
{
let labeled = self.labeled_assets.get(label)?;
let value = labeled.asset.value.downcast_ref::<B>()?;
Some(SavedAsset {
value,
labeled_assets: &labeled.asset.labeled_assets,
})
}
/// Returns the type-erased labeled asset, if it exists and matches this type.
pub fn get_erased_labeled<Q>(&self, label: &Q) -> Option<&ErasedLoadedAsset>
where
CowArc<'static, str>: Borrow<Q>,
Q: ?Sized + Hash + Eq,
{
let labeled = self.labeled_assets.get(label)?;
Some(&labeled.asset)
}
/// Returns the [`UntypedHandle`] of the labeled asset with the provided 'label', if it exists.
pub fn get_untyped_handle<Q>(&self, label: &Q) -> Option<UntypedHandle>
where
CowArc<'static, str>: Borrow<Q>,
Q: ?Sized + Hash + Eq,
{
let labeled = self.labeled_assets.get(label)?;
Some(labeled.handle.clone())
}
/// Returns the [`Handle`] of the labeled asset with the provided 'label', if it exists and is an asset of type `B`
pub fn get_handle<Q, B: Asset>(&self, label: &Q) -> Option<Handle<B>>
where
CowArc<'static, str>: Borrow<Q>,
Q: ?Sized + Hash + Eq,
{
let labeled = self.labeled_assets.get(label)?;
if let Ok(handle) = labeled.handle.clone().try_typed::<B>() {
return Some(handle);
}
None
}
/// Iterate over all labels for "labeled assets" in the loaded asset
pub fn iter_labels(&self) -> impl Iterator<Item = &str> {
self.labeled_assets.keys().map(|s| &**s)
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/assets.rs | crates/bevy_asset/src/assets.rs | use crate::asset_changed::AssetChanges;
use crate::{Asset, AssetEvent, AssetHandleProvider, AssetId, AssetServer, Handle, UntypedHandle};
use alloc::{sync::Arc, vec::Vec};
use bevy_ecs::{
message::MessageWriter,
resource::Resource,
system::{Res, ResMut, SystemChangeTick},
};
use bevy_platform::collections::HashMap;
use bevy_reflect::{Reflect, TypePath};
use core::{any::TypeId, iter::Enumerate, marker::PhantomData, sync::atomic::AtomicU32};
use crossbeam_channel::{Receiver, Sender};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use uuid::Uuid;
/// A generational runtime-only identifier for a specific [`Asset`] stored in [`Assets`]. This is optimized for efficient runtime
/// usage and is not suitable for identifying assets across app runs.
#[derive(
Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd, Reflect, Serialize, Deserialize,
)]
pub struct AssetIndex {
pub(crate) generation: u32,
pub(crate) index: u32,
}
impl AssetIndex {
/// Convert the [`AssetIndex`] into an opaque blob of bits to transport it in circumstances where carrying a strongly typed index isn't possible.
///
/// The result of this function should not be relied upon for anything except putting it back into [`AssetIndex::from_bits`] to recover the index.
pub fn to_bits(self) -> u64 {
let Self { generation, index } = self;
((generation as u64) << 32) | index as u64
}
/// Convert an opaque `u64` acquired from [`AssetIndex::to_bits`] back into an [`AssetIndex`]. This should not be used with any inputs other than those
/// derived from [`AssetIndex::to_bits`], as there are no guarantees for what will happen with such inputs.
pub fn from_bits(bits: u64) -> Self {
let index = ((bits << 32) >> 32) as u32;
let generation = (bits >> 32) as u32;
Self { generation, index }
}
}
/// Allocates generational [`AssetIndex`] values and facilitates their reuse.
pub(crate) struct AssetIndexAllocator {
/// A monotonically increasing index.
next_index: AtomicU32,
recycled_queue_sender: Sender<AssetIndex>,
/// This receives every recycled [`AssetIndex`]. It serves as a buffer/queue to store indices ready for reuse.
recycled_queue_receiver: Receiver<AssetIndex>,
recycled_sender: Sender<AssetIndex>,
recycled_receiver: Receiver<AssetIndex>,
}
impl Default for AssetIndexAllocator {
fn default() -> Self {
let (recycled_queue_sender, recycled_queue_receiver) = crossbeam_channel::unbounded();
let (recycled_sender, recycled_receiver) = crossbeam_channel::unbounded();
Self {
recycled_queue_sender,
recycled_queue_receiver,
recycled_sender,
recycled_receiver,
next_index: Default::default(),
}
}
}
impl AssetIndexAllocator {
/// Reserves a new [`AssetIndex`], either by reusing a recycled index (with an incremented generation), or by creating a new index
/// by incrementing the index counter for a given asset type `A`.
pub fn reserve(&self) -> AssetIndex {
if let Ok(mut recycled) = self.recycled_queue_receiver.try_recv() {
recycled.generation += 1;
self.recycled_sender.send(recycled).unwrap();
recycled
} else {
AssetIndex {
index: self
.next_index
.fetch_add(1, core::sync::atomic::Ordering::Relaxed),
generation: 0,
}
}
}
/// Queues the given `index` for reuse. This should only be done if the `index` is no longer being used.
pub fn recycle(&self, index: AssetIndex) {
self.recycled_queue_sender.send(index).unwrap();
}
}
/// A "loaded asset" containing the untyped handle for an asset stored in a given [`AssetPath`].
///
/// [`AssetPath`]: crate::AssetPath
#[derive(Asset, TypePath)]
pub struct LoadedUntypedAsset {
/// The handle to the loaded asset.
#[dependency]
pub handle: UntypedHandle,
}
// PERF: do we actually need this to be an enum? Can we just use an "invalid" generation instead
#[derive(Default)]
enum Entry<A: Asset> {
/// None is an indicator that this entry does not have live handles.
#[default]
None,
/// Some is an indicator that there is a live handle active for the entry at this [`AssetIndex`]
Some { value: Option<A>, generation: u32 },
}
/// Stores [`Asset`] values in a Vec-like storage identified by [`AssetIndex`].
struct DenseAssetStorage<A: Asset> {
storage: Vec<Entry<A>>,
len: u32,
allocator: Arc<AssetIndexAllocator>,
}
impl<A: Asset> Default for DenseAssetStorage<A> {
fn default() -> Self {
Self {
len: 0,
storage: Default::default(),
allocator: Default::default(),
}
}
}
impl<A: Asset> DenseAssetStorage<A> {
// Returns the number of assets stored.
pub(crate) fn len(&self) -> usize {
self.len as usize
}
// Returns `true` if there are no assets stored.
pub(crate) fn is_empty(&self) -> bool {
self.len == 0
}
/// Insert the value at the given index. Returns true if a value already exists (and was replaced)
pub(crate) fn insert(
&mut self,
index: AssetIndex,
asset: A,
) -> Result<bool, InvalidGenerationError> {
self.flush();
let entry = &mut self.storage[index.index as usize];
if let Entry::Some { value, generation } = entry {
if *generation == index.generation {
let exists = value.is_some();
if !exists {
self.len += 1;
}
*value = Some(asset);
Ok(exists)
} else {
Err(InvalidGenerationError::Occupied {
index,
current_generation: *generation,
})
}
} else {
Err(InvalidGenerationError::Removed { index })
}
}
/// Removes the asset stored at the given `index` and returns it as [`Some`] (if the asset exists).
/// This will recycle the id and allow new entries to be inserted.
pub(crate) fn remove_dropped(&mut self, index: AssetIndex) -> Option<A> {
self.remove_internal(index, |dense_storage| {
dense_storage.storage[index.index as usize] = Entry::None;
dense_storage.allocator.recycle(index);
})
}
/// Removes the asset stored at the given `index` and returns it as [`Some`] (if the asset exists).
/// This will _not_ recycle the id. New values with the current ID can still be inserted. The ID will
/// not be reused until [`DenseAssetStorage::remove_dropped`] is called.
pub(crate) fn remove_still_alive(&mut self, index: AssetIndex) -> Option<A> {
self.remove_internal(index, |_| {})
}
fn remove_internal(
&mut self,
index: AssetIndex,
removed_action: impl FnOnce(&mut Self),
) -> Option<A> {
self.flush();
let value = match &mut self.storage[index.index as usize] {
Entry::None => return None,
Entry::Some { value, generation } => {
if *generation == index.generation {
value.take().inspect(|_| self.len -= 1)
} else {
return None;
}
}
};
removed_action(self);
value
}
pub(crate) fn get(&self, index: AssetIndex) -> Option<&A> {
let entry = self.storage.get(index.index as usize)?;
match entry {
Entry::None => None,
Entry::Some { value, generation } => {
if *generation == index.generation {
value.as_ref()
} else {
None
}
}
}
}
pub(crate) fn get_mut(&mut self, index: AssetIndex) -> Option<&mut A> {
let entry = self.storage.get_mut(index.index as usize)?;
match entry {
Entry::None => None,
Entry::Some { value, generation } => {
if *generation == index.generation {
value.as_mut()
} else {
None
}
}
}
}
pub(crate) fn flush(&mut self) {
// NOTE: this assumes the allocator index is monotonically increasing.
let new_len = self
.allocator
.next_index
.load(core::sync::atomic::Ordering::Relaxed);
self.storage.resize_with(new_len as usize, || Entry::Some {
value: None,
generation: 0,
});
while let Ok(recycled) = self.allocator.recycled_receiver.try_recv() {
let entry = &mut self.storage[recycled.index as usize];
*entry = Entry::Some {
value: None,
generation: recycled.generation,
};
}
}
pub(crate) fn get_index_allocator(&self) -> Arc<AssetIndexAllocator> {
self.allocator.clone()
}
pub(crate) fn ids(&self) -> impl Iterator<Item = AssetId<A>> + '_ {
self.storage
.iter()
.enumerate()
.filter_map(|(i, v)| match v {
Entry::None => None,
Entry::Some { value, generation } => {
if value.is_some() {
Some(AssetId::from(AssetIndex {
index: i as u32,
generation: *generation,
}))
} else {
None
}
}
})
}
}
/// Stores [`Asset`] values identified by their [`AssetId`].
///
/// Assets identified by [`AssetId::Index`] will be stored in a "dense" vec-like storage. This is more efficient, but it means that
/// the assets can only be identified at runtime. This is the default behavior.
///
/// Assets identified by [`AssetId::Uuid`] will be stored in a hashmap. This is less efficient, but it means that the assets can be referenced
/// at compile time.
///
/// This tracks (and queues) [`AssetEvent`] events whenever changes to the collection occur.
/// To check whether the asset used by a given component has changed (due to a change in the handle or the underlying asset)
/// use the [`AssetChanged`](crate::asset_changed::AssetChanged) query filter.
#[derive(Resource)]
pub struct Assets<A: Asset> {
dense_storage: DenseAssetStorage<A>,
hash_map: HashMap<Uuid, A>,
handle_provider: AssetHandleProvider,
queued_events: Vec<AssetEvent<A>>,
/// Assets managed by the `Assets` struct with live strong `Handle`s
/// originating from `get_strong_handle`.
duplicate_handles: HashMap<AssetIndex, u16>,
}
impl<A: Asset> Default for Assets<A> {
fn default() -> Self {
let dense_storage = DenseAssetStorage::default();
let handle_provider =
AssetHandleProvider::new(TypeId::of::<A>(), dense_storage.get_index_allocator());
Self {
dense_storage,
handle_provider,
hash_map: Default::default(),
queued_events: Default::default(),
duplicate_handles: Default::default(),
}
}
}
impl<A: Asset> Assets<A> {
/// Retrieves an [`AssetHandleProvider`] capable of reserving new [`Handle`] values for assets that will be stored in this
/// collection.
pub fn get_handle_provider(&self) -> AssetHandleProvider {
self.handle_provider.clone()
}
/// Reserves a new [`Handle`] for an asset that will be stored in this collection.
pub fn reserve_handle(&self) -> Handle<A> {
self.handle_provider.reserve_handle().typed::<A>()
}
/// Inserts the given `asset`, identified by the given `id`. If an asset already exists for
/// `id`, it will be replaced.
///
/// Note: This will never return an error for UUID asset IDs.
pub fn insert(
&mut self,
id: impl Into<AssetId<A>>,
asset: A,
) -> Result<(), InvalidGenerationError> {
match id.into() {
AssetId::Index { index, .. } => self.insert_with_index(index, asset).map(|_| ()),
AssetId::Uuid { uuid } => {
self.insert_with_uuid(uuid, asset);
Ok(())
}
}
}
/// Retrieves an [`Asset`] stored for the given `id` if it exists. If it does not exist, it will
/// be inserted using `insert_fn`.
///
/// Note: This will never return an error for UUID asset IDs.
// PERF: Optimize this or remove it
pub fn get_or_insert_with(
&mut self,
id: impl Into<AssetId<A>>,
insert_fn: impl FnOnce() -> A,
) -> Result<&mut A, InvalidGenerationError> {
let id: AssetId<A> = id.into();
if self.get(id).is_none() {
self.insert(id, insert_fn())?;
}
// This should be impossible since either, `self.get` was Some, in which case this succeeds,
// or `self.get` was None and we inserted it (and bailed out if there was an error).
Ok(self
.get_mut(id)
.expect("the Asset was none even though we checked or inserted"))
}
/// Returns `true` if the `id` exists in this collection. Otherwise it returns `false`.
pub fn contains(&self, id: impl Into<AssetId<A>>) -> bool {
match id.into() {
AssetId::Index { index, .. } => self.dense_storage.get(index).is_some(),
AssetId::Uuid { uuid } => self.hash_map.contains_key(&uuid),
}
}
pub(crate) fn insert_with_uuid(&mut self, uuid: Uuid, asset: A) -> Option<A> {
let result = self.hash_map.insert(uuid, asset);
if result.is_some() {
self.queued_events
.push(AssetEvent::Modified { id: uuid.into() });
} else {
self.queued_events
.push(AssetEvent::Added { id: uuid.into() });
}
result
}
pub(crate) fn insert_with_index(
&mut self,
index: AssetIndex,
asset: A,
) -> Result<bool, InvalidGenerationError> {
let replaced = self.dense_storage.insert(index, asset)?;
if replaced {
self.queued_events
.push(AssetEvent::Modified { id: index.into() });
} else {
self.queued_events
.push(AssetEvent::Added { id: index.into() });
}
Ok(replaced)
}
/// Adds the given `asset` and allocates a new strong [`Handle`] for it.
#[inline]
pub fn add(&mut self, asset: impl Into<A>) -> Handle<A> {
let index = self.dense_storage.allocator.reserve();
self.insert_with_index(index, asset.into()).unwrap();
Handle::Strong(self.handle_provider.get_handle(index, false, None, None))
}
/// Upgrade an `AssetId` into a strong `Handle` that will prevent asset drop.
///
/// Returns `None` if the provided `id` is not part of this `Assets` collection.
/// For example, it may have been dropped earlier.
#[inline]
pub fn get_strong_handle(&mut self, id: AssetId<A>) -> Option<Handle<A>> {
if !self.contains(id) {
return None;
}
let index = match id {
AssetId::Index { index, .. } => index,
// We don't support strong handles for Uuid assets.
AssetId::Uuid { .. } => return None,
};
*self.duplicate_handles.entry(index).or_insert(0) += 1;
Some(Handle::Strong(
self.handle_provider.get_handle(index, false, None, None),
))
}
/// Retrieves a reference to the [`Asset`] with the given `id`, if it exists.
/// Note that this supports anything that implements `Into<AssetId<A>>`, which includes [`Handle`] and [`AssetId`].
#[inline]
pub fn get(&self, id: impl Into<AssetId<A>>) -> Option<&A> {
match id.into() {
AssetId::Index { index, .. } => self.dense_storage.get(index),
AssetId::Uuid { uuid } => self.hash_map.get(&uuid),
}
}
/// Retrieves a mutable reference to the [`Asset`] with the given `id`, if it exists.
/// Note that this supports anything that implements `Into<AssetId<A>>`, which includes [`Handle`] and [`AssetId`].
#[inline]
pub fn get_mut(&mut self, id: impl Into<AssetId<A>>) -> Option<&mut A> {
let id: AssetId<A> = id.into();
let result = match id {
AssetId::Index { index, .. } => self.dense_storage.get_mut(index),
AssetId::Uuid { uuid } => self.hash_map.get_mut(&uuid),
};
if result.is_some() {
self.queued_events.push(AssetEvent::Modified { id });
}
result
}
/// Retrieves a mutable reference to the [`Asset`] with the given `id`, if it exists.
///
/// This is the same as [`Assets::get_mut`] except it doesn't emit [`AssetEvent::Modified`].
#[inline]
pub fn get_mut_untracked(&mut self, id: impl Into<AssetId<A>>) -> Option<&mut A> {
let id: AssetId<A> = id.into();
match id {
AssetId::Index { index, .. } => self.dense_storage.get_mut(index),
AssetId::Uuid { uuid } => self.hash_map.get_mut(&uuid),
}
}
/// Removes (and returns) the [`Asset`] with the given `id`, if it exists.
/// Note that this supports anything that implements `Into<AssetId<A>>`, which includes [`Handle`] and [`AssetId`].
pub fn remove(&mut self, id: impl Into<AssetId<A>>) -> Option<A> {
let id: AssetId<A> = id.into();
let result = self.remove_untracked(id);
if result.is_some() {
self.queued_events.push(AssetEvent::Removed { id });
}
result
}
/// Removes (and returns) the [`Asset`] with the given `id`, if it exists. This skips emitting [`AssetEvent::Removed`].
/// Note that this supports anything that implements `Into<AssetId<A>>`, which includes [`Handle`] and [`AssetId`].
///
/// This is the same as [`Assets::remove`] except it doesn't emit [`AssetEvent::Removed`].
pub fn remove_untracked(&mut self, id: impl Into<AssetId<A>>) -> Option<A> {
let id: AssetId<A> = id.into();
match id {
AssetId::Index { index, .. } => {
self.duplicate_handles.remove(&index);
self.dense_storage.remove_still_alive(index)
}
AssetId::Uuid { uuid } => self.hash_map.remove(&uuid),
}
}
/// Removes the [`Asset`] with the given `id`.
pub(crate) fn remove_dropped(&mut self, index: AssetIndex) {
match self.duplicate_handles.get_mut(&index) {
None => {}
Some(0) => {
self.duplicate_handles.remove(&index);
}
Some(value) => {
*value -= 1;
return;
}
}
let existed = self.dense_storage.remove_dropped(index).is_some();
self.queued_events
.push(AssetEvent::Unused { id: index.into() });
if existed {
self.queued_events
.push(AssetEvent::Removed { id: index.into() });
}
}
/// Returns `true` if there are no assets in this collection.
pub fn is_empty(&self) -> bool {
self.dense_storage.is_empty() && self.hash_map.is_empty()
}
/// Returns the number of assets currently stored in the collection.
pub fn len(&self) -> usize {
self.dense_storage.len() + self.hash_map.len()
}
/// Returns an iterator over the [`AssetId`] of every [`Asset`] stored in this collection.
pub fn ids(&self) -> impl Iterator<Item = AssetId<A>> + '_ {
self.dense_storage
.ids()
.chain(self.hash_map.keys().map(|uuid| AssetId::from(*uuid)))
}
/// Returns an iterator over the [`AssetId`] and [`Asset`] ref of every asset in this collection.
// PERF: this could be accelerated if we implement a skip list. Consider the cost/benefits
pub fn iter(&self) -> impl Iterator<Item = (AssetId<A>, &A)> {
self.dense_storage
.storage
.iter()
.enumerate()
.filter_map(|(i, v)| match v {
Entry::None => None,
Entry::Some { value, generation } => value.as_ref().map(|v| {
let id = AssetId::Index {
index: AssetIndex {
generation: *generation,
index: i as u32,
},
marker: PhantomData,
};
(id, v)
}),
})
.chain(
self.hash_map
.iter()
.map(|(i, v)| (AssetId::Uuid { uuid: *i }, v)),
)
}
/// Returns an iterator over the [`AssetId`] and mutable [`Asset`] ref of every asset in this collection.
// PERF: this could be accelerated if we implement a skip list. Consider the cost/benefits
pub fn iter_mut(&mut self) -> AssetsMutIterator<'_, A> {
AssetsMutIterator {
dense_storage: self.dense_storage.storage.iter_mut().enumerate(),
hash_map: self.hash_map.iter_mut(),
queued_events: &mut self.queued_events,
}
}
/// A system that synchronizes the state of assets in this collection with the [`AssetServer`]. This manages
/// [`Handle`] drop events.
pub fn track_assets(mut assets: ResMut<Self>, asset_server: Res<AssetServer>) {
let assets = &mut *assets;
// note that we must hold this lock for the entire duration of this function to ensure
// that `asset_server.load` calls that occur during it block, which ensures that
// re-loads are kicked off appropriately. This function must be "transactional" relative
// to other asset info operations
let mut infos = asset_server.write_infos();
while let Ok(drop_event) = assets.handle_provider.drop_receiver.try_recv() {
if drop_event.asset_server_managed {
// the process_handle_drop call checks whether new handles have been created since the drop event was fired, before removing the asset
if !infos.process_handle_drop(drop_event.index) {
// a new handle has been created, or the asset doesn't exist
continue;
}
}
assets.remove_dropped(drop_event.index.index);
}
}
/// A system that applies accumulated asset change events to the [`Messages`] resource.
///
/// [`Messages`]: bevy_ecs::message::Messages
pub(crate) fn asset_events(
mut assets: ResMut<Self>,
mut messages: MessageWriter<AssetEvent<A>>,
asset_changes: Option<ResMut<AssetChanges<A>>>,
ticks: SystemChangeTick,
) {
use AssetEvent::{Added, LoadedWithDependencies, Modified, Removed};
if let Some(mut asset_changes) = asset_changes {
for new_event in &assets.queued_events {
match new_event {
Removed { id } | AssetEvent::Unused { id } => asset_changes.remove(id),
Added { id } | Modified { id } | LoadedWithDependencies { id } => {
asset_changes.insert(*id, ticks.this_run());
}
};
}
}
messages.write_batch(assets.queued_events.drain(..));
}
/// A run condition for [`asset_events`]. The system will not run if there are no events to
/// flush.
///
/// [`asset_events`]: Self::asset_events
pub(crate) fn asset_events_condition(assets: Res<Self>) -> bool {
!assets.queued_events.is_empty()
}
}
/// A mutable iterator over [`Assets`].
pub struct AssetsMutIterator<'a, A: Asset> {
queued_events: &'a mut Vec<AssetEvent<A>>,
dense_storage: Enumerate<core::slice::IterMut<'a, Entry<A>>>,
hash_map: bevy_platform::collections::hash_map::IterMut<'a, Uuid, A>,
}
impl<'a, A: Asset> Iterator for AssetsMutIterator<'a, A> {
type Item = (AssetId<A>, &'a mut A);
fn next(&mut self) -> Option<Self::Item> {
for (i, entry) in &mut self.dense_storage {
match entry {
Entry::None => {
continue;
}
Entry::Some { value, generation } => {
let id = AssetId::Index {
index: AssetIndex {
generation: *generation,
index: i as u32,
},
marker: PhantomData,
};
self.queued_events.push(AssetEvent::Modified { id });
if let Some(value) = value {
return Some((id, value));
}
}
}
}
if let Some((key, value)) = self.hash_map.next() {
let id = AssetId::Uuid { uuid: *key };
self.queued_events.push(AssetEvent::Modified { id });
Some((id, value))
} else {
None
}
}
}
/// An error returned when an [`AssetIndex`] has an invalid generation.
#[derive(Error, Debug, PartialEq, Eq)]
pub enum InvalidGenerationError {
#[error("AssetIndex {index:?} has an invalid generation. The current generation is: '{current_generation}'.")]
Occupied {
index: AssetIndex,
current_generation: u32,
},
#[error("AssetIndex {index:?} has been removed")]
Removed { index: AssetIndex },
}
#[cfg(test)]
mod test {
use crate::AssetIndex;
#[test]
fn asset_index_round_trip() {
let asset_index = AssetIndex {
generation: 42,
index: 1337,
};
let roundtripped = AssetIndex::from_bits(asset_index.to_bits());
assert_eq!(asset_index, roundtripped);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/transformer.rs | crates/bevy_asset/src/transformer.rs | use crate::{meta::Settings, Asset, ErasedLoadedAsset, Handle, LabeledAsset, UntypedHandle};
use alloc::boxed::Box;
use atomicow::CowArc;
use bevy_platform::collections::HashMap;
use bevy_reflect::TypePath;
use bevy_tasks::ConditionalSendFuture;
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.
///
/// This trait is commonly used in association with [`LoadTransformAndSave`](crate::processor::LoadTransformAndSave) to accomplish common asset pipeline workflows.
pub trait AssetTransformer: TypePath + Send + Sync + 'static {
/// The [`Asset`] type which this [`AssetTransformer`] takes as and input.
type AssetInput: Asset;
/// The [`Asset`] type which this [`AssetTransformer`] outputs.
type AssetOutput: Asset;
/// 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<Box<dyn core::error::Error + Send + Sync + 'static>>;
/// Transforms the given [`TransformedAsset`] to [`AssetTransformer::AssetOutput`].
/// The [`TransformedAsset`]'s `labeled_assets` can be altered to add new Labeled Sub-Assets
/// The passed in `settings` can influence how the `asset` is transformed
fn transform<'a>(
&'a self,
asset: TransformedAsset<Self::AssetInput>,
settings: &'a Self::Settings,
) -> impl ConditionalSendFuture<Output = Result<TransformedAsset<Self::AssetOutput>, Self::Error>>;
}
/// An [`Asset`] (and any "sub assets") intended to be transformed
pub struct TransformedAsset<A: Asset> {
pub(crate) value: A,
pub(crate) labeled_assets: HashMap<CowArc<'static, str>, LabeledAsset>,
}
impl<A: Asset> Deref for TransformedAsset<A> {
type Target = A;
fn deref(&self) -> &Self::Target {
&self.value
}
}
impl<A: Asset> DerefMut for TransformedAsset<A> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.value
}
}
impl<A: Asset> TransformedAsset<A> {
/// Creates a new [`TransformedAsset`] from `asset` if its internal value matches `A`.
pub fn from_loaded(asset: ErasedLoadedAsset) -> Option<Self> {
if let Ok(value) = asset.value.downcast::<A>() {
return Some(TransformedAsset {
value: *value,
labeled_assets: asset.labeled_assets,
});
}
None
}
/// Creates a new [`TransformedAsset`] from `asset`, transferring the `labeled_assets` from this [`TransformedAsset`] to the new one
pub fn replace_asset<B: Asset>(self, asset: B) -> TransformedAsset<B> {
TransformedAsset {
value: asset,
labeled_assets: self.labeled_assets,
}
}
/// Takes the labeled assets from `labeled_source` and places them in this [`TransformedAsset`]
pub fn take_labeled_assets<B: Asset>(&mut self, labeled_source: TransformedAsset<B>) {
self.labeled_assets = labeled_source.labeled_assets;
}
/// Retrieves the value of this asset.
#[inline]
pub fn get(&self) -> &A {
&self.value
}
/// Mutably retrieves the value of this asset.
#[inline]
pub fn get_mut(&mut self) -> &mut A {
&mut self.value
}
/// Returns the labeled asset, if it exists and matches this type.
pub fn get_labeled<B: Asset, Q>(&mut self, label: &Q) -> Option<TransformedSubAsset<'_, B>>
where
CowArc<'static, str>: Borrow<Q>,
Q: ?Sized + Hash + Eq,
{
let labeled = self.labeled_assets.get_mut(label)?;
let value = labeled.asset.value.downcast_mut::<B>()?;
Some(TransformedSubAsset {
value,
labeled_assets: &mut labeled.asset.labeled_assets,
})
}
/// Returns the type-erased labeled asset, if it exists and matches this type.
pub fn get_erased_labeled<Q>(&self, label: &Q) -> Option<&ErasedLoadedAsset>
where
CowArc<'static, str>: Borrow<Q>,
Q: ?Sized + Hash + Eq,
{
let labeled = self.labeled_assets.get(label)?;
Some(&labeled.asset)
}
/// Returns the [`UntypedHandle`] of the labeled asset with the provided 'label', if it exists.
pub fn get_untyped_handle<Q>(&self, label: &Q) -> Option<UntypedHandle>
where
CowArc<'static, str>: Borrow<Q>,
Q: ?Sized + Hash + Eq,
{
let labeled = self.labeled_assets.get(label)?;
Some(labeled.handle.clone())
}
/// Returns the [`Handle`] of the labeled asset with the provided 'label', if it exists and is an asset of type `B`
pub fn get_handle<Q, B: Asset>(&self, label: &Q) -> Option<Handle<B>>
where
CowArc<'static, str>: Borrow<Q>,
Q: ?Sized + Hash + Eq,
{
let labeled = self.labeled_assets.get(label)?;
if let Ok(handle) = labeled.handle.clone().try_typed::<B>() {
return Some(handle);
}
None
}
/// Adds `asset` as a labeled sub asset using `label` and `handle`
pub fn insert_labeled(
&mut self,
label: impl Into<CowArc<'static, str>>,
handle: impl Into<UntypedHandle>,
asset: impl Into<ErasedLoadedAsset>,
) {
let labeled = LabeledAsset {
asset: asset.into(),
handle: handle.into(),
};
self.labeled_assets.insert(label.into(), labeled);
}
/// Iterate over all labels for "labeled assets" in the loaded asset
pub fn iter_labels(&self) -> impl Iterator<Item = &str> {
self.labeled_assets.keys().map(|s| &**s)
}
}
/// A labeled sub-asset of [`TransformedAsset`]
pub struct TransformedSubAsset<'a, A: Asset> {
value: &'a mut A,
labeled_assets: &'a mut HashMap<CowArc<'static, str>, LabeledAsset>,
}
impl<'a, A: Asset> Deref for TransformedSubAsset<'a, A> {
type Target = A;
fn deref(&self) -> &Self::Target {
self.value
}
}
impl<'a, A: Asset> DerefMut for TransformedSubAsset<'a, A> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.value
}
}
impl<'a, A: Asset> TransformedSubAsset<'a, A> {
/// Creates a new [`TransformedSubAsset`] from `asset` if its internal value matches `A`.
pub fn from_loaded(asset: &'a mut ErasedLoadedAsset) -> Option<Self> {
let value = asset.value.downcast_mut::<A>()?;
Some(TransformedSubAsset {
value,
labeled_assets: &mut asset.labeled_assets,
})
}
/// Retrieves the value of this asset.
#[inline]
pub fn get(&self) -> &A {
self.value
}
/// Mutably retrieves the value of this asset.
#[inline]
pub fn get_mut(&mut self) -> &mut A {
self.value
}
/// Returns the labeled asset, if it exists and matches this type.
pub fn get_labeled<B: Asset, Q>(&mut self, label: &Q) -> Option<TransformedSubAsset<'_, B>>
where
CowArc<'static, str>: Borrow<Q>,
Q: ?Sized + Hash + Eq,
{
let labeled = self.labeled_assets.get_mut(label)?;
let value = labeled.asset.value.downcast_mut::<B>()?;
Some(TransformedSubAsset {
value,
labeled_assets: &mut labeled.asset.labeled_assets,
})
}
/// Returns the type-erased labeled asset, if it exists and matches this type.
pub fn get_erased_labeled<Q>(&self, label: &Q) -> Option<&ErasedLoadedAsset>
where
CowArc<'static, str>: Borrow<Q>,
Q: ?Sized + Hash + Eq,
{
let labeled = self.labeled_assets.get(label)?;
Some(&labeled.asset)
}
/// Returns the [`UntypedHandle`] of the labeled asset with the provided 'label', if it exists.
pub fn get_untyped_handle<Q>(&self, label: &Q) -> Option<UntypedHandle>
where
CowArc<'static, str>: Borrow<Q>,
Q: ?Sized + Hash + Eq,
{
let labeled = self.labeled_assets.get(label)?;
Some(labeled.handle.clone())
}
/// Returns the [`Handle`] of the labeled asset with the provided 'label', if it exists and is an asset of type `B`
pub fn get_handle<Q, B: Asset>(&self, label: &Q) -> Option<Handle<B>>
where
CowArc<'static, str>: Borrow<Q>,
Q: ?Sized + Hash + Eq,
{
let labeled = self.labeled_assets.get(label)?;
if let Ok(handle) = labeled.handle.clone().try_typed::<B>() {
return Some(handle);
}
None
}
/// Adds `asset` as a labeled sub asset using `label` and `handle`
pub fn insert_labeled(
&mut self,
label: impl Into<CowArc<'static, str>>,
handle: impl Into<UntypedHandle>,
asset: impl Into<ErasedLoadedAsset>,
) {
let labeled = LabeledAsset {
asset: asset.into(),
handle: handle.into(),
};
self.labeled_assets.insert(label.into(), labeled);
}
/// Iterate over all labels for "labeled assets" in the loaded asset
pub fn iter_labels(&self) -> impl Iterator<Item = &str> {
self.labeled_assets.keys().map(|s| &**s)
}
}
/// An identity [`AssetTransformer`] which infallibly returns the input [`Asset`] on transformation.]
#[derive(TypePath)]
pub struct IdentityAssetTransformer<A: Asset> {
_phantom: PhantomData<fn(A) -> A>,
}
impl<A: Asset> IdentityAssetTransformer<A> {
/// Creates a new [`IdentityAssetTransformer`] with the correct internal [`PhantomData`] field.
pub const fn new() -> Self {
Self {
_phantom: PhantomData,
}
}
}
impl<A: Asset> Default for IdentityAssetTransformer<A> {
fn default() -> Self {
Self::new()
}
}
impl<A: Asset> AssetTransformer for IdentityAssetTransformer<A> {
type AssetInput = A;
type AssetOutput = A;
type Settings = ();
type Error = Infallible;
async fn transform<'a>(
&'a self,
asset: TransformedAsset<Self::AssetInput>,
_settings: &'a Self::Settings,
) -> Result<TransformedAsset<Self::AssetOutput>, Self::Error> {
Ok(asset)
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/handle.rs | crates/bevy_asset/src/handle.rs | use crate::{
meta::MetaTransform, Asset, AssetId, AssetIndex, AssetIndexAllocator, AssetPath,
ErasedAssetIndex, UntypedAssetId,
};
use alloc::sync::Arc;
use bevy_reflect::{std_traits::ReflectDefault, Reflect, TypePath};
use core::{
any::TypeId,
hash::{Hash, Hasher},
marker::PhantomData,
};
use crossbeam_channel::{Receiver, Sender};
use disqualified::ShortName;
use thiserror::Error;
use uuid::Uuid;
/// Provides [`Handle`] and [`UntypedHandle`] _for a specific asset type_.
/// This should _only_ be used for one specific asset type.
#[derive(Clone)]
pub struct AssetHandleProvider {
pub(crate) allocator: Arc<AssetIndexAllocator>,
pub(crate) drop_sender: Sender<DropEvent>,
pub(crate) drop_receiver: Receiver<DropEvent>,
pub(crate) type_id: TypeId,
}
#[derive(Debug)]
pub(crate) struct DropEvent {
pub(crate) index: ErasedAssetIndex,
pub(crate) asset_server_managed: bool,
}
impl AssetHandleProvider {
pub(crate) fn new(type_id: TypeId, allocator: Arc<AssetIndexAllocator>) -> Self {
let (drop_sender, drop_receiver) = crossbeam_channel::unbounded();
Self {
type_id,
allocator,
drop_sender,
drop_receiver,
}
}
/// Reserves a new strong [`UntypedHandle`] (with a new [`UntypedAssetId`]). The stored [`Asset`] [`TypeId`] in the
/// [`UntypedHandle`] will match the [`Asset`] [`TypeId`] assigned to this [`AssetHandleProvider`].
pub fn reserve_handle(&self) -> UntypedHandle {
let index = self.allocator.reserve();
UntypedHandle::Strong(self.get_handle(index, false, None, None))
}
pub(crate) fn get_handle(
&self,
index: AssetIndex,
asset_server_managed: bool,
path: Option<AssetPath<'static>>,
meta_transform: Option<MetaTransform>,
) -> Arc<StrongHandle> {
Arc::new(StrongHandle {
index,
type_id: self.type_id,
drop_sender: self.drop_sender.clone(),
meta_transform,
path,
asset_server_managed,
})
}
pub(crate) fn reserve_handle_internal(
&self,
asset_server_managed: bool,
path: Option<AssetPath<'static>>,
meta_transform: Option<MetaTransform>,
) -> Arc<StrongHandle> {
let index = self.allocator.reserve();
self.get_handle(index, asset_server_managed, path, meta_transform)
}
}
/// The internal "strong" [`Asset`] handle storage for [`Handle::Strong`] and [`UntypedHandle::Strong`]. When this is dropped,
/// the [`Asset`] will be freed. It also stores some asset metadata for easy access from handles.
#[derive(TypePath)]
pub struct StrongHandle {
pub(crate) index: AssetIndex,
pub(crate) type_id: TypeId,
pub(crate) asset_server_managed: bool,
pub(crate) path: Option<AssetPath<'static>>,
/// Modifies asset meta. This is stored on the handle because it is:
/// 1. configuration tied to the lifetime of a specific asset load
/// 2. configuration that must be repeatable when the asset is hot-reloaded
pub(crate) meta_transform: Option<MetaTransform>,
pub(crate) drop_sender: Sender<DropEvent>,
}
impl Drop for StrongHandle {
fn drop(&mut self) {
let _ = self.drop_sender.send(DropEvent {
index: ErasedAssetIndex::new(self.index, self.type_id),
asset_server_managed: self.asset_server_managed,
});
}
}
impl core::fmt::Debug for StrongHandle {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("StrongHandle")
.field("index", &self.index)
.field("type_id", &self.type_id)
.field("asset_server_managed", &self.asset_server_managed)
.field("path", &self.path)
.field("drop_sender", &self.drop_sender)
.finish()
}
}
/// A handle to a specific [`Asset`] of type `A`. Handles act as abstract "references" to
/// assets, whose data are stored in the [`Assets<A>`](crate::prelude::Assets) resource,
/// avoiding the need to store multiple copies of the same data.
///
/// If a [`Handle`] is [`Handle::Strong`], the [`Asset`] will be kept
/// alive until the [`Handle`] is dropped. If a [`Handle`] is [`Handle::Uuid`], it does not necessarily reference a live [`Asset`],
/// nor will it keep assets alive.
///
/// Modifying a *handle* will change which existing asset is referenced, but modifying the *asset*
/// (by mutating the [`Assets`](crate::prelude::Assets) resource) will change the asset for all handles referencing it.
///
/// [`Handle`] can be cloned. If a [`Handle::Strong`] is cloned, the referenced [`Asset`] will not be freed until _all_ instances
/// of the [`Handle`] are dropped.
///
/// [`Handle::Strong`], via [`StrongHandle`] also provides access to useful [`Asset`] metadata, such as the [`AssetPath`] (if it exists).
#[derive(Reflect)]
#[reflect(Default, Debug, Hash, PartialEq, Clone)]
pub enum Handle<A: Asset> {
/// A "strong" reference to a live (or loading) [`Asset`]. If a [`Handle`] is [`Handle::Strong`], the [`Asset`] will be kept
/// alive until the [`Handle`] is dropped. Strong handles also provide access to additional asset metadata.
Strong(Arc<StrongHandle>),
/// A reference to an [`Asset`] using a stable-across-runs / const identifier. Dropping this
/// handle will not result in the asset being dropped.
Uuid(Uuid, #[reflect(ignore, clone)] PhantomData<fn() -> A>),
}
impl<T: Asset> Clone for Handle<T> {
fn clone(&self) -> Self {
match self {
Handle::Strong(handle) => Handle::Strong(handle.clone()),
Handle::Uuid(uuid, ..) => Handle::Uuid(*uuid, PhantomData),
}
}
}
impl<A: Asset> Handle<A> {
/// Returns the [`AssetId`] of this [`Asset`].
#[inline]
pub fn id(&self) -> AssetId<A> {
match self {
Handle::Strong(handle) => AssetId::Index {
index: handle.index,
marker: PhantomData,
},
Handle::Uuid(uuid, ..) => AssetId::Uuid { uuid: *uuid },
}
}
/// Returns the path if this is (1) a strong handle and (2) the asset has a path
#[inline]
pub fn path(&self) -> Option<&AssetPath<'static>> {
match self {
Handle::Strong(handle) => handle.path.as_ref(),
Handle::Uuid(..) => None,
}
}
/// Returns `true` if this is a uuid handle.
#[inline]
pub fn is_uuid(&self) -> bool {
matches!(self, Handle::Uuid(..))
}
/// Returns `true` if this is a strong handle.
#[inline]
pub fn is_strong(&self) -> bool {
matches!(self, Handle::Strong(_))
}
/// Converts this [`Handle`] to an "untyped" / "generic-less" [`UntypedHandle`], which stores the [`Asset`] type information
/// _inside_ [`UntypedHandle`]. This will return [`UntypedHandle::Strong`] for [`Handle::Strong`] and [`UntypedHandle::Uuid`] for
/// [`Handle::Uuid`].
#[inline]
pub fn untyped(self) -> UntypedHandle {
self.into()
}
}
impl<A: Asset> Default for Handle<A> {
fn default() -> Self {
Handle::Uuid(AssetId::<A>::DEFAULT_UUID, PhantomData)
}
}
impl<A: Asset> core::fmt::Debug for Handle<A> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let name = ShortName::of::<A>();
match self {
Handle::Strong(handle) => {
write!(
f,
"StrongHandle<{name}>{{ index: {:?}, type_id: {:?}, path: {:?} }}",
handle.index, handle.type_id, handle.path
)
}
Handle::Uuid(uuid, ..) => write!(f, "UuidHandle<{name}>({uuid:?})"),
}
}
}
impl<A: Asset> Hash for Handle<A> {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
self.id().hash(state);
}
}
impl<A: Asset> PartialOrd for Handle<A> {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl<A: Asset> Ord for Handle<A> {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
self.id().cmp(&other.id())
}
}
impl<A: Asset> PartialEq for Handle<A> {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.id() == other.id()
}
}
impl<A: Asset> Eq for Handle<A> {}
impl<A: Asset> From<&Handle<A>> for AssetId<A> {
#[inline]
fn from(value: &Handle<A>) -> Self {
value.id()
}
}
impl<A: Asset> From<&Handle<A>> for UntypedAssetId {
#[inline]
fn from(value: &Handle<A>) -> Self {
value.id().into()
}
}
impl<A: Asset> From<&mut Handle<A>> for AssetId<A> {
#[inline]
fn from(value: &mut Handle<A>) -> Self {
value.id()
}
}
impl<A: Asset> From<&mut Handle<A>> for UntypedAssetId {
#[inline]
fn from(value: &mut Handle<A>) -> Self {
value.id().into()
}
}
impl<A: Asset> From<Uuid> for Handle<A> {
#[inline]
fn from(uuid: Uuid) -> Self {
Handle::Uuid(uuid, PhantomData)
}
}
/// An untyped variant of [`Handle`], which internally stores the [`Asset`] type information at runtime
/// as a [`TypeId`] instead of encoding it in the compile-time type. This allows handles across [`Asset`] types
/// to be stored together and compared.
///
/// See [`Handle`] for more information.
#[derive(Clone, Reflect)]
pub enum UntypedHandle {
/// A strong handle, which will keep the referenced [`Asset`] alive until all strong handles are dropped.
Strong(Arc<StrongHandle>),
/// A UUID handle, which does not keep the referenced [`Asset`] alive.
Uuid {
/// An identifier that records the underlying asset type.
type_id: TypeId,
/// The UUID provided during asset registration.
uuid: Uuid,
},
}
impl UntypedHandle {
/// Returns the [`UntypedAssetId`] for the referenced asset.
#[inline]
pub fn id(&self) -> UntypedAssetId {
match self {
UntypedHandle::Strong(handle) => UntypedAssetId::Index {
type_id: handle.type_id,
index: handle.index,
},
UntypedHandle::Uuid { type_id, uuid } => UntypedAssetId::Uuid {
uuid: *uuid,
type_id: *type_id,
},
}
}
/// Returns the path if this is (1) a strong handle and (2) the asset has a path
#[inline]
pub fn path(&self) -> Option<&AssetPath<'static>> {
match self {
UntypedHandle::Strong(handle) => handle.path.as_ref(),
UntypedHandle::Uuid { .. } => None,
}
}
/// Returns the [`TypeId`] of the referenced [`Asset`].
#[inline]
pub fn type_id(&self) -> TypeId {
match self {
UntypedHandle::Strong(handle) => handle.type_id,
UntypedHandle::Uuid { type_id, .. } => *type_id,
}
}
/// Converts to a typed Handle. This _will not check if the target Handle type matches_.
#[inline]
pub fn typed_unchecked<A: Asset>(self) -> Handle<A> {
match self {
UntypedHandle::Strong(handle) => Handle::Strong(handle),
UntypedHandle::Uuid { uuid, .. } => Handle::Uuid(uuid, PhantomData),
}
}
/// Converts to a typed Handle. This will check the type when compiled with debug asserts, but it
/// _will not check if the target Handle type matches in release builds_. Use this as an optimization
/// when you want some degree of validation at dev-time, but you are also very certain that the type
/// actually matches.
#[inline]
pub fn typed_debug_checked<A: Asset>(self) -> Handle<A> {
debug_assert_eq!(
self.type_id(),
TypeId::of::<A>(),
"The target Handle<A>'s TypeId does not match the TypeId of this UntypedHandle"
);
self.typed_unchecked()
}
/// Converts to a typed Handle. This will panic if the internal [`TypeId`] does not match the given asset type `A`
#[inline]
pub fn typed<A: Asset>(self) -> Handle<A> {
let Ok(handle) = self.try_typed() else {
panic!(
"The target Handle<{}>'s TypeId does not match the TypeId of this UntypedHandle",
core::any::type_name::<A>()
)
};
handle
}
/// Converts to a typed Handle. This will panic if the internal [`TypeId`] does not match the given asset type `A`
#[inline]
pub fn try_typed<A: Asset>(self) -> Result<Handle<A>, UntypedAssetConversionError> {
Handle::try_from(self)
}
/// The "meta transform" for the strong handle. This will only be [`Some`] if the handle is strong and there is a meta transform
/// associated with it.
#[inline]
pub fn meta_transform(&self) -> Option<&MetaTransform> {
match self {
UntypedHandle::Strong(handle) => handle.meta_transform.as_ref(),
UntypedHandle::Uuid { .. } => None,
}
}
}
impl PartialEq for UntypedHandle {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.id() == other.id() && self.type_id() == other.type_id()
}
}
impl Eq for UntypedHandle {}
impl Hash for UntypedHandle {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
self.id().hash(state);
}
}
impl core::fmt::Debug for UntypedHandle {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
UntypedHandle::Strong(handle) => {
write!(
f,
"StrongHandle{{ type_id: {:?}, id: {:?}, path: {:?} }}",
handle.type_id, handle.index, handle.path
)
}
UntypedHandle::Uuid { type_id, uuid } => {
write!(f, "UuidHandle{{ type_id: {type_id:?}, uuid: {uuid:?} }}",)
}
}
}
}
impl PartialOrd for UntypedHandle {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
if self.type_id() == other.type_id() {
self.id().partial_cmp(&other.id())
} else {
None
}
}
}
impl From<&UntypedHandle> for UntypedAssetId {
#[inline]
fn from(value: &UntypedHandle) -> Self {
value.id()
}
}
// Cross Operations
impl<A: Asset> PartialEq<UntypedHandle> for Handle<A> {
#[inline]
fn eq(&self, other: &UntypedHandle) -> bool {
TypeId::of::<A>() == other.type_id() && self.id() == other.id()
}
}
impl<A: Asset> PartialEq<Handle<A>> for UntypedHandle {
#[inline]
fn eq(&self, other: &Handle<A>) -> bool {
other.eq(self)
}
}
impl<A: Asset> PartialOrd<UntypedHandle> for Handle<A> {
#[inline]
fn partial_cmp(&self, other: &UntypedHandle) -> Option<core::cmp::Ordering> {
if TypeId::of::<A>() != other.type_id() {
None
} else {
self.id().partial_cmp(&other.id())
}
}
}
impl<A: Asset> PartialOrd<Handle<A>> for UntypedHandle {
#[inline]
fn partial_cmp(&self, other: &Handle<A>) -> Option<core::cmp::Ordering> {
Some(other.partial_cmp(self)?.reverse())
}
}
impl<A: Asset> From<Handle<A>> for UntypedHandle {
fn from(value: Handle<A>) -> Self {
match value {
Handle::Strong(handle) => UntypedHandle::Strong(handle),
Handle::Uuid(uuid, _) => UntypedHandle::Uuid {
type_id: TypeId::of::<A>(),
uuid,
},
}
}
}
impl<A: Asset> TryFrom<UntypedHandle> for Handle<A> {
type Error = UntypedAssetConversionError;
fn try_from(value: UntypedHandle) -> Result<Self, Self::Error> {
let found = value.type_id();
let expected = TypeId::of::<A>();
if found != expected {
return Err(UntypedAssetConversionError::TypeIdMismatch { expected, found });
}
Ok(match value {
UntypedHandle::Strong(handle) => Handle::Strong(handle),
UntypedHandle::Uuid { uuid, .. } => Handle::Uuid(uuid, PhantomData),
})
}
}
/// Creates a [`Handle`] from a string literal containing a UUID.
///
/// # Examples
///
/// ```
/// # use bevy_asset::{Handle, uuid_handle};
/// # type Image = ();
/// const IMAGE: Handle<Image> = uuid_handle!("1347c9b7-c46a-48e7-b7b8-023a354b7cac");
/// ```
#[macro_export]
macro_rules! uuid_handle {
($uuid:expr) => {{
$crate::Handle::Uuid($crate::uuid::uuid!($uuid), core::marker::PhantomData)
}};
}
#[deprecated = "Use uuid_handle! instead"]
#[macro_export]
macro_rules! weak_handle {
($uuid:expr) => {
$crate::uuid_handle!($uuid)
};
}
/// Errors preventing the conversion of to/from an [`UntypedHandle`] and a [`Handle`].
#[derive(Error, Debug, PartialEq, Clone)]
#[non_exhaustive]
pub enum UntypedAssetConversionError {
/// Caused when trying to convert an [`UntypedHandle`] into a [`Handle`] of the wrong type.
#[error(
"This UntypedHandle is for {found:?} and cannot be converted into a Handle<{expected:?}>"
)]
TypeIdMismatch {
/// The expected [`TypeId`] of the [`Handle`] being converted to.
expected: TypeId,
/// The [`TypeId`] of the [`UntypedHandle`] being converted from.
found: TypeId,
},
}
#[cfg(test)]
mod tests {
use alloc::boxed::Box;
use bevy_platform::hash::FixedHasher;
use bevy_reflect::PartialReflect;
use core::hash::BuildHasher;
use uuid::Uuid;
use crate::tests::create_app;
use super::*;
type TestAsset = ();
const UUID_1: Uuid = Uuid::from_u128(123);
const UUID_2: Uuid = Uuid::from_u128(456);
/// Simple utility to directly hash a value using a fixed hasher
fn hash<T: Hash>(data: &T) -> u64 {
FixedHasher.hash_one(data)
}
/// Typed and Untyped `Handles` should be equivalent to each other and themselves
#[test]
fn equality() {
let typed = Handle::<TestAsset>::Uuid(UUID_1, PhantomData);
let untyped = UntypedHandle::Uuid {
type_id: TypeId::of::<TestAsset>(),
uuid: UUID_1,
};
assert_eq!(
Ok(typed.clone()),
Handle::<TestAsset>::try_from(untyped.clone())
);
assert_eq!(UntypedHandle::from(typed.clone()), untyped);
assert_eq!(typed, untyped);
}
/// Typed and Untyped `Handles` should be orderable amongst each other and themselves
#[test]
#[expect(
clippy::cmp_owned,
reason = "This lints on the assertion that a typed handle converted to an untyped handle maintains its ordering compared to an untyped handle. While the conversion would normally be useless, we need to ensure that converted handles maintain their ordering, making the conversion necessary here."
)]
fn ordering() {
assert!(UUID_1 < UUID_2);
let typed_1 = Handle::<TestAsset>::Uuid(UUID_1, PhantomData);
let typed_2 = Handle::<TestAsset>::Uuid(UUID_2, PhantomData);
let untyped_1 = UntypedHandle::Uuid {
type_id: TypeId::of::<TestAsset>(),
uuid: UUID_1,
};
let untyped_2 = UntypedHandle::Uuid {
type_id: TypeId::of::<TestAsset>(),
uuid: UUID_2,
};
assert!(typed_1 < typed_2);
assert!(untyped_1 < untyped_2);
assert!(UntypedHandle::from(typed_1.clone()) < untyped_2);
assert!(untyped_1 < UntypedHandle::from(typed_2.clone()));
assert!(Handle::<TestAsset>::try_from(untyped_1.clone()).unwrap() < typed_2);
assert!(typed_1 < Handle::<TestAsset>::try_from(untyped_2.clone()).unwrap());
assert!(typed_1 < untyped_2);
assert!(untyped_1 < typed_2);
}
/// Typed and Untyped `Handles` should be equivalently hashable to each other and themselves
#[test]
fn hashing() {
let typed = Handle::<TestAsset>::Uuid(UUID_1, PhantomData);
let untyped = UntypedHandle::Uuid {
type_id: TypeId::of::<TestAsset>(),
uuid: UUID_1,
};
assert_eq!(
hash(&typed),
hash(&Handle::<TestAsset>::try_from(untyped.clone()).unwrap())
);
assert_eq!(hash(&UntypedHandle::from(typed.clone())), hash(&untyped));
assert_eq!(hash(&typed), hash(&untyped));
}
/// Typed and Untyped `Handles` should be interchangeable
#[test]
fn conversion() {
let typed = Handle::<TestAsset>::Uuid(UUID_1, PhantomData);
let untyped = UntypedHandle::Uuid {
type_id: TypeId::of::<TestAsset>(),
uuid: UUID_1,
};
assert_eq!(typed, Handle::try_from(untyped.clone()).unwrap());
assert_eq!(UntypedHandle::from(typed.clone()), untyped);
}
#[test]
fn from_uuid() {
let uuid = UUID_1;
let handle: Handle<TestAsset> = uuid.into();
assert!(handle.is_uuid());
assert_eq!(handle.id(), AssetId::Uuid { uuid });
}
/// `PartialReflect::reflect_clone`/`PartialReflect::to_dynamic` should increase the strong count of a strong handle
#[test]
fn strong_handle_reflect_clone() {
use crate::{AssetApp, Assets, VisitAssetDependencies};
use bevy_reflect::FromReflect;
#[derive(Reflect)]
struct MyAsset {
value: u32,
}
impl Asset for MyAsset {}
impl VisitAssetDependencies for MyAsset {
fn visit_dependencies(&self, _visit: &mut impl FnMut(UntypedAssetId)) {}
}
let mut app = create_app().0;
app.init_asset::<MyAsset>();
let mut assets = app.world_mut().resource_mut::<Assets<MyAsset>>();
let handle: Handle<MyAsset> = assets.add(MyAsset { value: 1 });
match &handle {
Handle::Strong(strong) => {
assert_eq!(
Arc::strong_count(strong),
1,
"Inserting the asset should result in a strong count of 1"
);
let reflected: &dyn Reflect = &handle;
let _cloned_handle: Box<dyn Reflect> = reflected.reflect_clone().unwrap();
assert_eq!(
Arc::strong_count(strong),
2,
"Cloning the handle with reflect should increase the strong count to 2"
);
let dynamic_handle: Box<dyn PartialReflect> = reflected.to_dynamic();
assert_eq!(
Arc::strong_count(strong),
3,
"Converting the handle to a dynamic should increase the strong count to 3"
);
let from_reflect_handle: Handle<MyAsset> =
FromReflect::from_reflect(&*dynamic_handle).unwrap();
assert_eq!(Arc::strong_count(strong), 4, "Converting the reflected value back to a handle should increase the strong count to 4");
assert!(
from_reflect_handle.is_strong(),
"The cloned handle should still be strong"
);
}
_ => panic!("Expected a strong handle"),
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/folder.rs | crates/bevy_asset/src/folder.rs | use alloc::vec::Vec;
use crate::{Asset, UntypedHandle};
use bevy_reflect::TypePath;
/// A "loaded folder" containing handles for all assets stored in a given [`AssetPath`].
///
/// This is produced by [`AssetServer::load_folder`](crate::prelude::AssetServer::load_folder).
///
/// [`AssetPath`]: crate::AssetPath
#[derive(Asset, TypePath)]
pub struct LoadedFolder {
/// The handles of all assets stored in the folder.
#[dependency]
pub handles: Vec<UntypedHandle>,
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/processor/process.rs | crates/bevy_asset/src/processor/process.rs | use crate::{
io::{
AssetReaderError, AssetWriterError, MissingAssetWriterError,
MissingProcessedAssetReaderError, MissingProcessedAssetWriterError, Reader,
ReaderRequiredFeatures, Writer,
},
meta::{AssetAction, AssetMeta, AssetMetaDyn, ProcessDependencyInfo, ProcessedInfo, Settings},
processor::AssetProcessor,
saver::{AssetSaver, SavedAsset},
transformer::{AssetTransformer, IdentityAssetTransformer, TransformedAsset},
AssetLoadError, AssetLoader, AssetPath, DeserializeMetaError, ErasedLoadedAsset,
MissingAssetLoaderForExtensionError, MissingAssetLoaderForTypeNameError,
};
use alloc::{
borrow::ToOwned,
boxed::Box,
string::{String, ToString},
vec::Vec,
};
use bevy_reflect::TypePath;
use bevy_tasks::{BoxedFuture, ConditionalSendFuture};
use core::marker::PhantomData;
use serde::{Deserialize, Serialize};
use thiserror::Error;
/// Asset "processor" logic that reads input asset bytes (stored on [`ProcessContext`]), processes the value in some way,
/// and then writes the final processed bytes with [`Writer`]. The resulting bytes must be loadable with the given [`Process::OutputLoader`].
///
/// This is a "low level", maximally flexible interface. Most use cases are better served by the [`LoadTransformAndSave`] implementation
/// of [`Process`].
pub trait Process: TypePath + Send + Sync + Sized + 'static {
/// The configuration / settings used to process the asset. This will be stored in the [`AssetMeta`] and is user-configurable per-asset.
type Settings: Settings + Default + Serialize + for<'a> Deserialize<'a>;
/// The [`AssetLoader`] that will be used to load the final processed asset.
type OutputLoader: AssetLoader;
/// Processes the asset stored on `context` in some way using the settings stored on `meta`. The results are written to `writer`. The
/// final written processed asset is loadable using [`Process::OutputLoader`]. This load will use the returned [`AssetLoader::Settings`].
fn process(
&self,
context: &mut ProcessContext,
settings: &Self::Settings,
writer: &mut Writer,
) -> impl ConditionalSendFuture<
Output = Result<<Self::OutputLoader as AssetLoader>::Settings, ProcessError>,
>;
/// Gets the features of the reader required to process the asset.
fn reader_required_features(_settings: &Self::Settings) -> ReaderRequiredFeatures {
ReaderRequiredFeatures::default()
}
}
/// A flexible [`Process`] implementation that loads the source [`Asset`] using the `L` [`AssetLoader`], then transforms
/// the `L` asset into an `S` [`AssetSaver`] asset using the `T` [`AssetTransformer`], and lastly saves the asset using the `S` [`AssetSaver`].
///
/// When creating custom processors, it is generally recommended to use the [`LoadTransformAndSave`] [`Process`] implementation,
/// as it encourages you to separate your code into an [`AssetLoader`] capable of loading assets without processing enabled,
/// an [`AssetTransformer`] capable of converting from an `L` asset to an `S` asset, and
/// an [`AssetSaver`] that allows you save any `S` asset. However you can
/// also implement [`Process`] directly if [`LoadTransformAndSave`] feels limiting or unnecessary.
///
/// If your [`Process`] does not need to transform the [`Asset`], you can use [`IdentityAssetTransformer`] as `T`.
/// This will directly return the input [`Asset`], allowing your [`Process`] to directly load and then save an [`Asset`].
/// However, this pattern should only be used for cases such as file format conversion.
/// Otherwise, consider refactoring your [`AssetLoader`] and [`AssetSaver`] to isolate the transformation step into an explicit [`AssetTransformer`].
///
/// This uses [`LoadTransformAndSaveSettings`] to configure the processor.
///
/// [`Asset`]: crate::Asset
#[derive(TypePath)]
pub struct LoadTransformAndSave<
L: AssetLoader,
T: AssetTransformer<AssetInput = L::Asset>,
S: AssetSaver<Asset = T::AssetOutput>,
> {
transformer: T,
saver: S,
marker: PhantomData<fn() -> L>,
}
impl<L: AssetLoader, S: AssetSaver<Asset = L::Asset>> From<S>
for LoadTransformAndSave<L, IdentityAssetTransformer<L::Asset>, S>
{
fn from(value: S) -> Self {
LoadTransformAndSave {
transformer: IdentityAssetTransformer::new(),
saver: value,
marker: PhantomData,
}
}
}
/// Settings for the [`LoadTransformAndSave`] [`Process::Settings`] implementation.
///
/// `LoaderSettings` corresponds to [`AssetLoader::Settings`], `TransformerSettings` corresponds to [`AssetTransformer::Settings`],
/// and `SaverSettings` corresponds to [`AssetSaver::Settings`].
#[derive(Serialize, Deserialize, Default)]
pub struct LoadTransformAndSaveSettings<LoaderSettings, TransformerSettings, SaverSettings> {
/// The [`AssetLoader::Settings`] for [`LoadTransformAndSave`].
pub loader_settings: LoaderSettings,
/// The [`AssetTransformer::Settings`] for [`LoadTransformAndSave`].
pub transformer_settings: TransformerSettings,
/// The [`AssetSaver::Settings`] for [`LoadTransformAndSave`].
pub saver_settings: SaverSettings,
}
impl<
L: AssetLoader,
T: AssetTransformer<AssetInput = L::Asset>,
S: AssetSaver<Asset = T::AssetOutput>,
> LoadTransformAndSave<L, T, S>
{
pub fn new(transformer: T, saver: S) -> Self {
LoadTransformAndSave {
transformer,
saver,
marker: PhantomData,
}
}
}
/// An error that is encountered during [`Process::process`].
#[derive(Error, Debug)]
pub enum ProcessError {
#[error(transparent)]
MissingAssetLoaderForExtension(#[from] MissingAssetLoaderForExtensionError),
#[error(transparent)]
MissingAssetLoaderForTypeName(#[from] MissingAssetLoaderForTypeNameError),
#[error("The processor '{0}' does not exist")]
#[from(ignore)]
MissingProcessor(String),
#[error("The processor '{processor_short_name}' is ambiguous between several processors: {ambiguous_processor_names:?}")]
AmbiguousProcessor {
processor_short_name: String,
ambiguous_processor_names: Vec<&'static str>,
},
#[error("Encountered an AssetReader error for '{path}': {err}")]
#[from(ignore)]
AssetReaderError {
path: AssetPath<'static>,
err: AssetReaderError,
},
#[error("Encountered an AssetWriter error for '{path}': {err}")]
#[from(ignore)]
AssetWriterError {
path: AssetPath<'static>,
err: AssetWriterError,
},
#[error(transparent)]
MissingAssetWriterError(#[from] MissingAssetWriterError),
#[error(transparent)]
MissingProcessedAssetReaderError(#[from] MissingProcessedAssetReaderError),
#[error(transparent)]
MissingProcessedAssetWriterError(#[from] MissingProcessedAssetWriterError),
#[error("Failed to read asset metadata for {path}: {err}")]
#[from(ignore)]
ReadAssetMetaError {
path: AssetPath<'static>,
err: AssetReaderError,
},
#[error(transparent)]
DeserializeMetaError(#[from] DeserializeMetaError),
#[error(transparent)]
AssetLoadError(#[from] AssetLoadError),
#[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}")]
#[from(ignore)]
AssetSaveError(Box<dyn core::error::Error + Send + Sync + 'static>),
#[error("Encountered an error while transforming the asset: {0}")]
#[from(ignore)]
AssetTransformError(Box<dyn core::error::Error + Send + Sync + 'static>),
#[error("Assets without extensions are not supported.")]
ExtensionRequired,
}
impl<Loader, Transformer, Saver> Process for LoadTransformAndSave<Loader, Transformer, Saver>
where
Loader: AssetLoader,
Transformer: AssetTransformer<AssetInput = Loader::Asset>,
Saver: AssetSaver<Asset = Transformer::AssetOutput>,
{
type Settings =
LoadTransformAndSaveSettings<Loader::Settings, Transformer::Settings, Saver::Settings>;
type OutputLoader = Saver::OutputLoader;
async fn process(
&self,
context: &mut ProcessContext<'_>,
settings: &Self::Settings,
writer: &mut Writer,
) -> Result<<Self::OutputLoader as AssetLoader>::Settings, ProcessError> {
let pre_transformed_asset = TransformedAsset::<Loader::Asset>::from_loaded(
context
.load_source_asset::<Loader>(&settings.loader_settings)
.await?,
)
.unwrap();
let post_transformed_asset = self
.transformer
.transform(pre_transformed_asset, &settings.transformer_settings)
.await
.map_err(|err| ProcessError::AssetTransformError(err.into()))?;
let saved_asset =
SavedAsset::<Transformer::AssetOutput>::from_transformed(&post_transformed_asset);
let output_settings = self
.saver
.save(writer, saved_asset, &settings.saver_settings)
.await
.map_err(|error| ProcessError::AssetSaveError(error.into()))?;
Ok(output_settings)
}
fn reader_required_features(settings: &Self::Settings) -> ReaderRequiredFeatures {
Loader::reader_required_features(&settings.loader_settings)
}
}
/// A type-erased variant of [`Process`] that enables interacting with processor implementations without knowing
/// their type.
pub trait ErasedProcessor: Send + Sync {
/// Type-erased variant of [`Process::process`].
fn process<'a>(
&'a self,
context: &'a mut ProcessContext,
settings: &'a dyn Settings,
writer: &'a mut Writer,
) -> BoxedFuture<'a, Result<Box<dyn AssetMetaDyn>, ProcessError>>;
/// Type-erased variant of [`Process::reader_required_features`].
// Note: This takes &self just to be dyn compatible.
#[cfg_attr(
not(target_arch = "wasm32"),
expect(
clippy::result_large_err,
reason = "this is only an error here because this isn't a future"
)
)]
fn reader_required_features(
&self,
settings: &dyn Settings,
) -> Result<ReaderRequiredFeatures, ProcessError>;
/// Deserialized `meta` as type-erased [`AssetMeta`], operating under the assumption that it matches the meta
/// for the underlying [`Process`] impl.
fn deserialize_meta(&self, meta: &[u8]) -> Result<Box<dyn AssetMetaDyn>, DeserializeMetaError>;
/// Returns the type-path of the original [`Process`].
fn type_path(&self) -> &'static str;
/// Returns the default type-erased [`AssetMeta`] for the underlying [`Process`] impl.
fn default_meta(&self) -> Box<dyn AssetMetaDyn>;
}
impl<P: Process> ErasedProcessor for P {
fn process<'a>(
&'a self,
context: &'a mut ProcessContext,
settings: &'a dyn Settings,
writer: &'a mut Writer,
) -> BoxedFuture<'a, Result<Box<dyn AssetMetaDyn>, ProcessError>> {
Box::pin(async move {
let settings = settings.downcast_ref().ok_or(ProcessError::WrongMetaType)?;
let loader_settings = <P as Process>::process(self, context, settings, writer).await?;
let output_meta: Box<dyn AssetMetaDyn> =
Box::new(AssetMeta::<P::OutputLoader, ()>::new(AssetAction::Load {
loader: P::OutputLoader::type_path().to_string(),
settings: loader_settings,
}));
Ok(output_meta)
})
}
fn reader_required_features(
&self,
settings: &dyn Settings,
) -> Result<ReaderRequiredFeatures, ProcessError> {
let settings = settings.downcast_ref().ok_or(ProcessError::WrongMetaType)?;
Ok(P::reader_required_features(settings))
}
fn deserialize_meta(&self, meta: &[u8]) -> Result<Box<dyn AssetMetaDyn>, DeserializeMetaError> {
let meta: AssetMeta<(), P> = ron::de::from_bytes(meta)?;
Ok(Box::new(meta))
}
fn type_path(&self) -> &'static str {
P::type_path()
}
fn default_meta(&self) -> Box<dyn AssetMetaDyn> {
Box::new(AssetMeta::<(), P>::new(AssetAction::Process {
processor: P::type_path().to_string(),
settings: P::Settings::default(),
}))
}
}
/// Provides scoped data access to the [`AssetProcessor`].
/// This must only expose processor data that is represented in the asset's hash.
pub struct ProcessContext<'a> {
/// The "new" processed info for the final processed asset. It is [`ProcessContext`]'s
/// job to populate `process_dependencies` with any asset dependencies used to process
/// this asset (ex: loading an asset value from the [`AssetServer`] of the [`AssetProcessor`])
///
/// DO NOT CHANGE ANY VALUES HERE OTHER THAN APPENDING TO `process_dependencies`
///
/// Do not expose this publicly as it would be too easily to invalidate state.
///
/// [`AssetServer`]: crate::server::AssetServer
pub(crate) new_processed_info: &'a mut ProcessedInfo,
/// This exists to expose access to asset values (via the [`AssetServer`]).
///
/// ANY ASSET VALUE THAT IS ACCESSED SHOULD BE ADDED TO `new_processed_info.process_dependencies`
///
/// Do not expose this publicly as it would be too easily to invalidate state by forgetting to update
/// `process_dependencies`.
///
/// [`AssetServer`]: crate::server::AssetServer
processor: &'a AssetProcessor,
path: &'a AssetPath<'static>,
reader: Box<dyn Reader + 'a>,
}
impl<'a> ProcessContext<'a> {
pub(crate) fn new(
processor: &'a AssetProcessor,
path: &'a AssetPath<'static>,
reader: Box<dyn Reader + 'a>,
new_processed_info: &'a mut ProcessedInfo,
) -> Self {
Self {
processor,
path,
reader,
new_processed_info,
}
}
/// Load the source asset using the `L` [`AssetLoader`] and the passed in `meta` config.
/// This will take the "load dependencies" (asset values used when loading with `L`]) and
/// register them as "process dependencies" because they are asset values required to process the
/// current asset.
pub async fn load_source_asset<L: AssetLoader>(
&mut self,
settings: &L::Settings,
) -> Result<ErasedLoadedAsset, AssetLoadError> {
let server = &self.processor.server;
let loader_name = L::type_path();
let loader = server.get_asset_loader_with_type_name(loader_name).await?;
let loaded_asset = server
.load_with_settings_loader_and_reader(
self.path,
settings,
&*loader,
&mut self.reader,
false,
true,
)
.await?;
for (path, full_hash) in &loaded_asset.loader_dependencies {
self.new_processed_info
.process_dependencies
.push(ProcessDependencyInfo {
full_hash: *full_hash,
path: path.to_owned(),
});
}
Ok(loaded_asset)
}
/// The path of the asset being processed.
#[inline]
pub fn path(&self) -> &AssetPath<'static> {
self.path
}
/// The reader for the asset being processed.
#[inline]
pub fn asset_reader(&mut self) -> &mut dyn Reader {
&mut self.reader
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/processor/tests.rs | crates/bevy_asset/src/processor/tests.rs | use alloc::{
boxed::Box,
collections::BTreeMap,
string::{String, ToString},
sync::Arc,
vec,
vec::Vec,
};
use async_lock::{RwLock, RwLockWriteGuard};
use bevy_platform::{
collections::HashMap,
sync::{Mutex, PoisonError},
};
use bevy_reflect::TypePath;
use core::marker::PhantomData;
use futures_lite::AsyncWriteExt;
use ron::ser::PrettyConfig;
use serde::{Deserialize, Serialize};
use std::path::Path;
use bevy_app::{App, TaskPoolPlugin};
use bevy_ecs::error::BevyError;
use bevy_tasks::BoxedFuture;
use crate::{
io::{
memory::{Dir, MemoryAssetReader, MemoryAssetWriter},
AssetReader, AssetReaderError, AssetSourceBuilder, AssetSourceBuilders, AssetSourceEvent,
AssetSourceId, AssetWatcher, PathStream, Reader, ReaderRequiredFeatures,
},
processor::{
AssetProcessor, GetProcessorError, LoadTransformAndSave, LogEntry, Process, ProcessContext,
ProcessError, ProcessorState, ProcessorTransactionLog, ProcessorTransactionLogFactory,
},
saver::AssetSaver,
tests::{
read_asset_as_string, read_meta_as_string, run_app_until, CoolText, CoolTextLoader,
CoolTextRon, SubText,
},
transformer::{AssetTransformer, TransformedAsset},
Asset, AssetApp, AssetLoader, AssetMode, AssetPath, AssetPlugin, LoadContext,
WriteDefaultMetaError,
};
#[derive(TypePath)]
struct MyProcessor<T>(PhantomData<fn() -> T>);
impl<T: TypePath + 'static> Process for MyProcessor<T> {
type OutputLoader = ();
type Settings = ();
async fn process(
&self,
_context: &mut ProcessContext<'_>,
_settings: &Self::Settings,
_writer: &mut crate::io::Writer,
) -> Result<(), ProcessError> {
Ok(())
}
}
#[derive(TypePath)]
struct Marker;
fn create_empty_asset_processor() -> AssetProcessor {
let mut sources = AssetSourceBuilders::default();
// Create an empty asset source so that AssetProcessor is happy.
let dir = Dir::default();
let memory_reader = MemoryAssetReader { root: dir.clone() };
sources.insert(
AssetSourceId::Default,
AssetSourceBuilder::new(move || Box::new(memory_reader.clone())),
);
AssetProcessor::new(&mut sources, false).0
}
#[test]
fn get_asset_processor_by_name() {
let asset_processor = create_empty_asset_processor();
asset_processor.register_processor(MyProcessor::<Marker>(PhantomData));
let long_processor = asset_processor
.get_processor(
"bevy_asset::processor::tests::MyProcessor<bevy_asset::processor::tests::Marker>",
)
.expect("Processor was previously registered");
let short_processor = asset_processor
.get_processor("MyProcessor<Marker>")
.expect("Processor was previously registered");
// We can use either the long or short processor name and we will get the same processor
// out.
assert!(Arc::ptr_eq(&long_processor, &short_processor));
}
#[test]
fn missing_processor_returns_error() {
let asset_processor = create_empty_asset_processor();
let Err(long_processor_err) = asset_processor.get_processor(
"bevy_asset::processor::tests::MyProcessor<bevy_asset::processor::tests::Marker>",
) else {
panic!("Processor was returned even though we never registered any.");
};
let GetProcessorError::Missing(long_processor_err) = &long_processor_err else {
panic!("get_processor returned incorrect error: {long_processor_err}");
};
assert_eq!(
long_processor_err,
"bevy_asset::processor::tests::MyProcessor<bevy_asset::processor::tests::Marker>"
);
// Short paths should also return an error.
let Err(long_processor_err) = asset_processor.get_processor("MyProcessor<Marker>") else {
panic!("Processor was returned even though we never registered any.");
};
let GetProcessorError::Missing(long_processor_err) = &long_processor_err else {
panic!("get_processor returned incorrect error: {long_processor_err}");
};
assert_eq!(long_processor_err, "MyProcessor<Marker>");
}
// Create another marker type whose short name will overlap `Marker`.
mod sneaky {
use bevy_reflect::TypePath;
#[derive(TypePath)]
pub struct Marker;
}
#[test]
fn ambiguous_short_path_returns_error() {
let asset_processor = create_empty_asset_processor();
asset_processor.register_processor(MyProcessor::<Marker>(PhantomData));
asset_processor.register_processor(MyProcessor::<sneaky::Marker>(PhantomData));
let Err(long_processor_err) = asset_processor.get_processor("MyProcessor<Marker>") else {
panic!("Processor was returned even though the short path is ambiguous.");
};
let GetProcessorError::Ambiguous {
processor_short_name,
ambiguous_processor_names,
} = &long_processor_err
else {
panic!("get_processor returned incorrect error: {long_processor_err}");
};
assert_eq!(processor_short_name, "MyProcessor<Marker>");
let expected_ambiguous_names = [
"bevy_asset::processor::tests::MyProcessor<bevy_asset::processor::tests::Marker>",
"bevy_asset::processor::tests::MyProcessor<bevy_asset::processor::tests::sneaky::Marker>",
];
assert_eq!(ambiguous_processor_names, &expected_ambiguous_names);
let processor_1 = asset_processor
.get_processor(
"bevy_asset::processor::tests::MyProcessor<bevy_asset::processor::tests::Marker>",
)
.expect("Processor was previously registered");
let processor_2 = asset_processor
.get_processor(
"bevy_asset::processor::tests::MyProcessor<bevy_asset::processor::tests::sneaky::Marker>",
)
.expect("Processor was previously registered");
// If we fully specify the paths, we get the two different processors.
assert!(!Arc::ptr_eq(&processor_1, &processor_2));
}
#[derive(Clone)]
struct ProcessingDirs {
source: Dir,
processed: Dir,
source_event_sender: async_channel::Sender<AssetSourceEvent>,
}
struct AppWithProcessor {
app: App,
source_gate: Arc<RwLock<()>>,
default_source_dirs: ProcessingDirs,
extra_sources_dirs: HashMap<String, ProcessingDirs>,
}
/// Similar to [`crate::io::gated::GatedReader`], but uses a lock instead of a channel to avoid
/// needing to send the "correct" number of messages.
#[derive(Clone)]
struct LockGatedReader<R: AssetReader> {
reader: R,
gate: Arc<RwLock<()>>,
}
impl<R: AssetReader> LockGatedReader<R> {
/// Creates a new [`GatedReader`], which wraps the given `reader`. Also returns a [`GateOpener`] which
/// can be used to open "path gates" for this [`GatedReader`].
fn new(gate: Arc<RwLock<()>>, reader: R) -> Self {
Self { gate, reader }
}
}
impl<R: AssetReader> AssetReader for LockGatedReader<R> {
async fn read<'a>(
&'a self,
path: &'a Path,
required_features: ReaderRequiredFeatures,
) -> Result<impl Reader + 'a, AssetReaderError> {
let _guard = self.gate.read().await;
self.reader.read(path, required_features).await
}
async fn read_meta<'a>(&'a self, path: &'a Path) -> Result<impl Reader + 'a, AssetReaderError> {
let _guard = self.gate.read().await;
self.reader.read_meta(path).await
}
async fn read_directory<'a>(
&'a self,
path: &'a Path,
) -> Result<Box<PathStream>, AssetReaderError> {
let _guard = self.gate.read().await;
self.reader.read_directory(path).await
}
async fn is_directory<'a>(&'a self, path: &'a Path) -> Result<bool, AssetReaderError> {
let _guard = self.gate.read().await;
self.reader.is_directory(path).await
}
}
/// Serializes `text` into a `CoolText` that can be loaded.
///
/// This doesn't support all the features of `CoolText`, so more complex scenarios may require doing
/// this manually.
fn serialize_as_cool_text(text: &str) -> String {
let cool_text_ron = CoolTextRon {
text: text.into(),
dependencies: vec![],
embedded_dependencies: vec![],
sub_texts: vec![],
};
ron::ser::to_string_pretty(&cool_text_ron, PrettyConfig::new().new_line("\n")).unwrap()
}
/// Sets the transaction log for the app to a fake one to prevent touching the filesystem.
fn set_fake_transaction_log(app: &mut App) {
/// A dummy transaction log factory that just creates [`FakeTransactionLog`].
struct FakeTransactionLogFactory;
impl ProcessorTransactionLogFactory for FakeTransactionLogFactory {
fn read(&self) -> BoxedFuture<'_, Result<Vec<LogEntry>, BevyError>> {
Box::pin(async move { Ok(vec![]) })
}
fn create_new_log(
&self,
) -> BoxedFuture<'_, Result<Box<dyn ProcessorTransactionLog>, BevyError>> {
Box::pin(async move { Ok(Box::new(FakeTransactionLog) as _) })
}
}
/// A dummy transaction log that just drops every log.
// TODO: In the future it's possible for us to have a test of the transaction log, so making
// this more complex may be necessary.
struct FakeTransactionLog;
impl ProcessorTransactionLog for FakeTransactionLog {
fn begin_processing<'a>(
&'a mut self,
_asset: &'a AssetPath<'_>,
) -> BoxedFuture<'a, Result<(), BevyError>> {
Box::pin(async move { Ok(()) })
}
fn end_processing<'a>(
&'a mut self,
_asset: &'a AssetPath<'_>,
) -> BoxedFuture<'a, Result<(), BevyError>> {
Box::pin(async move { Ok(()) })
}
fn unrecoverable(&mut self) -> BoxedFuture<'_, Result<(), BevyError>> {
Box::pin(async move { Ok(()) })
}
}
app.world()
.resource::<AssetProcessor>()
.data()
.set_log_factory(Box::new(FakeTransactionLogFactory))
.unwrap();
}
fn create_app_with_asset_processor(extra_sources: &[String]) -> AppWithProcessor {
let mut app = App::new();
let source_gate = Arc::new(RwLock::new(()));
struct UnfinishedProcessingDirs {
source: Dir,
processed: Dir,
// The receiver channel for the source event sender for the unprocessed source.
source_event_sender_receiver:
async_channel::Receiver<async_channel::Sender<AssetSourceEvent>>,
}
impl UnfinishedProcessingDirs {
fn finish(self) -> ProcessingDirs {
ProcessingDirs {
source: self.source,
processed: self.processed,
// The processor listens for events on the source unconditionally, and we enable
// watching for the processed source, so both of these channels will be filled.
source_event_sender: self.source_event_sender_receiver.recv_blocking().unwrap(),
}
}
}
fn create_source(
app: &mut App,
source_id: AssetSourceId<'static>,
source_gate: Arc<RwLock<()>>,
) -> UnfinishedProcessingDirs {
let source_dir = Dir::default();
let processed_dir = Dir::default();
let source_memory_reader = LockGatedReader::new(
source_gate,
MemoryAssetReader {
root: source_dir.clone(),
},
);
let source_memory_writer = MemoryAssetWriter {
root: source_dir.clone(),
};
let processed_memory_reader = MemoryAssetReader {
root: processed_dir.clone(),
};
let processed_memory_writer = MemoryAssetWriter {
root: processed_dir.clone(),
};
let (source_event_sender_sender, source_event_sender_receiver) = async_channel::bounded(1);
struct FakeWatcher;
impl AssetWatcher for FakeWatcher {}
app.register_asset_source(
source_id,
AssetSourceBuilder::new(move || Box::new(source_memory_reader.clone()))
.with_writer(move |_| Some(Box::new(source_memory_writer.clone())))
.with_watcher(move |sender: async_channel::Sender<AssetSourceEvent>| {
source_event_sender_sender.send_blocking(sender).unwrap();
Some(Box::new(FakeWatcher))
})
.with_processed_reader(move || Box::new(processed_memory_reader.clone()))
.with_processed_writer(move |_| Some(Box::new(processed_memory_writer.clone()))),
);
UnfinishedProcessingDirs {
source: source_dir,
processed: processed_dir,
source_event_sender_receiver,
}
}
let default_source_dirs = create_source(&mut app, AssetSourceId::Default, source_gate.clone());
let extra_sources_dirs = extra_sources
.iter()
.map(|source_name| {
(
source_name.clone(),
create_source(
&mut app,
AssetSourceId::Name(source_name.clone().into()),
source_gate.clone(),
),
)
})
.collect::<Vec<_>>();
app.add_plugins((
TaskPoolPlugin::default(),
AssetPlugin {
mode: AssetMode::Processed,
use_asset_processor_override: Some(true),
watch_for_changes_override: Some(true),
..Default::default()
},
));
set_fake_transaction_log(&mut app);
// Now that we've built the app, finish all the processing dirs.
AppWithProcessor {
app,
source_gate,
default_source_dirs: default_source_dirs.finish(),
extra_sources_dirs: extra_sources_dirs
.into_iter()
.map(|(name, dirs)| (name, dirs.finish()))
.collect(),
}
}
fn run_app_until_finished_processing(app: &mut App, guard: RwLockWriteGuard<'_, ()>) {
let processor = app.world().resource::<AssetProcessor>().clone();
// We can't just wait for the processor state to be finished since we could have already
// finished before, but now that something has changed, we may not have restarted processing
// yet. So wait for processing to start, then finish.
run_app_until(app, |_| {
// Before we even consider whether the processor is started, make sure that none of the
// receivers have anything left in them. This prevents us accidentally, considering the
// processor as processing before all the events have been processed.
for source in processor.sources().iter() {
let Some(recv) = source.event_receiver() else {
continue;
};
if !recv.is_empty() {
return None;
}
}
let state = bevy_tasks::block_on(processor.get_state());
(state == ProcessorState::Processing || state == ProcessorState::Initializing).then_some(())
});
drop(guard);
run_app_until(app, |_| {
(bevy_tasks::block_on(processor.get_state()) == ProcessorState::Finished).then_some(())
});
}
#[derive(TypePath)]
struct CoolTextSaver;
impl AssetSaver for CoolTextSaver {
type Asset = CoolText;
type Settings = ();
type OutputLoader = CoolTextLoader;
type Error = std::io::Error;
async fn save(
&self,
writer: &mut crate::io::Writer,
asset: crate::saver::SavedAsset<'_, Self::Asset>,
_: &Self::Settings,
) -> Result<(), Self::Error> {
let ron = CoolTextRon {
text: asset.text.clone(),
sub_texts: asset
.iter_labels()
.map(|label| asset.get_labeled::<SubText, _>(label).unwrap().text.clone())
.collect(),
dependencies: asset
.dependencies
.iter()
.map(|handle| handle.path().unwrap().path())
.map(|path| path.to_str().unwrap().to_string())
.collect(),
// NOTE: We can't handle embedded dependencies in any way, since we need to write to
// another file to do so.
embedded_dependencies: vec![],
};
let ron = ron::ser::to_string_pretty(&ron, PrettyConfig::new().new_line("\n")).unwrap();
writer.write_all(ron.as_bytes()).await?;
Ok(())
}
}
// Note: while we allow any Fn, since closures are unnameable types, creating a processor with a
// closure cannot be used (since we need to include the name of the transformer in the meta
// file).
#[derive(TypePath)]
struct RootAssetTransformer<M: MutateAsset<A>, A: Asset>(M, PhantomData<fn(&mut A)>);
trait MutateAsset<A: Asset>: TypePath + Send + Sync + 'static {
fn mutate(&self, asset: &mut A);
}
impl<M: MutateAsset<A>, A: Asset> RootAssetTransformer<M, A> {
fn new(m: M) -> Self {
Self(m, PhantomData)
}
}
impl<M: MutateAsset<A>, A: Asset> AssetTransformer for RootAssetTransformer<M, A> {
type AssetInput = A;
type AssetOutput = A;
type Error = std::io::Error;
type Settings = ();
async fn transform<'a>(
&'a self,
mut asset: TransformedAsset<A>,
_settings: &'a Self::Settings,
) -> Result<TransformedAsset<A>, Self::Error> {
self.0.mutate(asset.get_mut());
Ok(asset)
}
}
#[derive(TypePath)]
struct AddText(String);
impl MutateAsset<CoolText> for AddText {
fn mutate(&self, text: &mut CoolText) {
text.text.push_str(&self.0);
}
}
#[test]
fn no_meta_or_default_processor_copies_asset() {
// Assets without a meta file or a default processor should still be accessible in the
// processed path. Note: This isn't exactly the desired property - we don't want the assets
// to be copied to the processed directory. We just want these assets to still be loadable
// if we no longer have the source directory. This could be done with a symlink instead of a
// copy.
let AppWithProcessor {
mut app,
source_gate,
default_source_dirs:
ProcessingDirs {
source: source_dir,
processed: processed_dir,
..
},
..
} = create_app_with_asset_processor(&[]);
let guard = source_gate.write_blocking();
let path = Path::new("abc.cool.ron");
let source_asset = r#"(
text: "abc",
dependencies: [],
embedded_dependencies: [],
sub_texts: [],
)"#;
source_dir.insert_asset_text(path, source_asset);
run_app_until_finished_processing(&mut app, guard);
let processed_asset = processed_dir.get_asset(path).unwrap();
let processed_asset = str::from_utf8(processed_asset.value()).unwrap();
assert_eq!(processed_asset, source_asset);
}
#[test]
fn asset_processor_transforms_asset_default_processor() {
let AppWithProcessor {
mut app,
source_gate,
default_source_dirs:
ProcessingDirs {
source: source_dir,
processed: processed_dir,
..
},
..
} = create_app_with_asset_processor(&[]);
type CoolTextProcessor = LoadTransformAndSave<
CoolTextLoader,
RootAssetTransformer<AddText, CoolText>,
CoolTextSaver,
>;
app.register_asset_loader(CoolTextLoader)
.register_asset_processor(CoolTextProcessor::new(
RootAssetTransformer::new(AddText("_def".into())),
CoolTextSaver,
))
.set_default_asset_processor::<CoolTextProcessor>("cool.ron");
let guard = source_gate.write_blocking();
let path = Path::new("abc.cool.ron");
source_dir.insert_asset_text(
path,
r#"(
text: "abc",
dependencies: [],
embedded_dependencies: [],
sub_texts: [],
)"#,
);
run_app_until_finished_processing(&mut app, guard);
let processed_asset = processed_dir.get_asset(path).unwrap();
let processed_asset = str::from_utf8(processed_asset.value()).unwrap();
assert_eq!(
processed_asset,
r#"(
text: "abc_def",
dependencies: [],
embedded_dependencies: [],
sub_texts: [],
)"#
);
}
#[test]
fn asset_processor_transforms_asset_with_meta() {
let AppWithProcessor {
mut app,
source_gate,
default_source_dirs:
ProcessingDirs {
source: source_dir,
processed: processed_dir,
..
},
..
} = create_app_with_asset_processor(&[]);
type CoolTextProcessor = LoadTransformAndSave<
CoolTextLoader,
RootAssetTransformer<AddText, CoolText>,
CoolTextSaver,
>;
app.register_asset_loader(CoolTextLoader)
.register_asset_processor(CoolTextProcessor::new(
RootAssetTransformer::new(AddText("_def".into())),
CoolTextSaver,
));
let guard = source_gate.write_blocking();
let path = Path::new("abc.cool.ron");
source_dir.insert_asset_text(
path,
r#"(
text: "abc",
dependencies: [],
embedded_dependencies: [],
sub_texts: [],
)"#,
);
source_dir.insert_meta_text(path, r#"(
meta_format_version: "1.0",
asset: Process(
processor: "bevy_asset::processor::process::LoadTransformAndSave<bevy_asset::tests::CoolTextLoader, bevy_asset::processor::tests::RootAssetTransformer<bevy_asset::processor::tests::AddText, bevy_asset::tests::CoolText>, bevy_asset::processor::tests::CoolTextSaver>",
settings: (
loader_settings: (),
transformer_settings: (),
saver_settings: (),
),
),
)"#);
run_app_until_finished_processing(&mut app, guard);
let processed_asset = processed_dir.get_asset(path).unwrap();
let processed_asset = str::from_utf8(processed_asset.value()).unwrap();
assert_eq!(
processed_asset,
r#"(
text: "abc_def",
dependencies: [],
embedded_dependencies: [],
sub_texts: [],
)"#
);
}
#[test]
fn asset_processor_transforms_asset_with_short_path_meta() {
let AppWithProcessor {
mut app,
source_gate,
default_source_dirs:
ProcessingDirs {
source: source_dir,
processed: processed_dir,
..
},
..
} = create_app_with_asset_processor(&[]);
type CoolTextProcessor = LoadTransformAndSave<
CoolTextLoader,
RootAssetTransformer<AddText, CoolText>,
CoolTextSaver,
>;
app.register_asset_loader(CoolTextLoader)
.register_asset_processor(CoolTextProcessor::new(
RootAssetTransformer::new(AddText("_def".into())),
CoolTextSaver,
));
let guard = source_gate.write_blocking();
let path = Path::new("abc.cool.ron");
source_dir.insert_asset_text(
path,
r#"(
text: "abc",
dependencies: [],
embedded_dependencies: [],
sub_texts: [],
)"#,
);
source_dir.insert_meta_text(path, r#"(
meta_format_version: "1.0",
asset: Process(
processor: "LoadTransformAndSave<CoolTextLoader, RootAssetTransformer<AddText, CoolText>, CoolTextSaver>",
settings: (
loader_settings: (),
transformer_settings: (),
saver_settings: (),
),
),
)"#);
run_app_until_finished_processing(&mut app, guard);
let processed_asset = processed_dir.get_asset(path).unwrap();
let processed_asset = str::from_utf8(processed_asset.value()).unwrap();
assert_eq!(
processed_asset,
r#"(
text: "abc_def",
dependencies: [],
embedded_dependencies: [],
sub_texts: [],
)"#
);
}
#[derive(Asset, TypePath, Serialize, Deserialize)]
struct FakeGltf {
gltf_nodes: BTreeMap<String, String>,
}
#[derive(TypePath)]
struct FakeGltfLoader;
impl AssetLoader for FakeGltfLoader {
type Asset = FakeGltf;
type Settings = ();
type Error = std::io::Error;
async fn load(
&self,
reader: &mut dyn Reader,
_settings: &Self::Settings,
_load_context: &mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
use std::io::{Error, ErrorKind};
let mut bytes = vec![];
reader.read_to_end(&mut bytes).await?;
ron::de::from_bytes(&bytes)
.map_err(|err| Error::new(ErrorKind::InvalidData, err.to_string()))
}
fn extensions(&self) -> &[&str] {
&["gltf"]
}
}
#[derive(Asset, TypePath, Serialize, Deserialize)]
struct FakeBsn {
parent_bsn: Option<String>,
nodes: BTreeMap<String, String>,
}
// This loader loads the BSN but as an "inlined" scene. We read the original BSN and create a
// scene that holds all the data including parents.
// TODO: It would be nice if the inlining was actually done as an `AssetTransformer`, but
// `Process` currently has no way to load nested assets.
#[derive(TypePath)]
struct FakeBsnLoader;
impl AssetLoader for FakeBsnLoader {
type Asset = FakeBsn;
type Settings = ();
type Error = std::io::Error;
async fn load(
&self,
reader: &mut dyn Reader,
_settings: &Self::Settings,
load_context: &mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
use std::io::{Error, ErrorKind};
let mut bytes = vec![];
reader.read_to_end(&mut bytes).await?;
let bsn: FakeBsn = ron::de::from_bytes(&bytes)
.map_err(|err| Error::new(ErrorKind::InvalidData, err.to_string()))?;
if bsn.parent_bsn.is_none() {
return Ok(bsn);
}
let parent_bsn = bsn.parent_bsn.unwrap();
let parent_bsn = load_context
.loader()
.immediate()
.load(parent_bsn)
.await
.map_err(|err| Error::new(ErrorKind::InvalidData, err))?;
let mut new_bsn: FakeBsn = parent_bsn.take();
for (name, node) in bsn.nodes {
new_bsn.nodes.insert(name, node);
}
Ok(new_bsn)
}
fn extensions(&self) -> &[&str] {
&["bsn"]
}
}
#[derive(TypePath)]
struct GltfToBsn;
impl AssetTransformer for GltfToBsn {
type AssetInput = FakeGltf;
type AssetOutput = FakeBsn;
type Settings = ();
type Error = std::io::Error;
async fn transform<'a>(
&'a self,
mut asset: TransformedAsset<Self::AssetInput>,
_settings: &'a Self::Settings,
) -> Result<TransformedAsset<Self::AssetOutput>, Self::Error> {
let bsn = FakeBsn {
parent_bsn: None,
// Pretend we converted all the glTF nodes into BSN's format.
nodes: core::mem::take(&mut asset.get_mut().gltf_nodes),
};
Ok(asset.replace_asset(bsn))
}
}
#[derive(TypePath)]
struct FakeBsnSaver;
impl AssetSaver for FakeBsnSaver {
type Asset = FakeBsn;
type Error = std::io::Error;
type OutputLoader = FakeBsnLoader;
type Settings = ();
async fn save(
&self,
writer: &mut crate::io::Writer,
asset: crate::saver::SavedAsset<'_, Self::Asset>,
_settings: &Self::Settings,
) -> Result<(), Self::Error> {
use std::io::{Error, ErrorKind};
let ron_string =
ron::ser::to_string_pretty(asset.get(), PrettyConfig::new().new_line("\n"))
.map_err(|err| Error::new(ErrorKind::InvalidData, err))?;
writer.write_all(ron_string.as_bytes()).await
}
}
#[test]
fn asset_processor_loading_can_read_processed_assets() {
use crate::transformer::IdentityAssetTransformer;
let AppWithProcessor {
mut app,
source_gate,
default_source_dirs:
ProcessingDirs {
source: source_dir,
processed: processed_dir,
..
},
..
} = create_app_with_asset_processor(&[]);
// This processor loads a gltf file, converts it to BSN and then saves out the BSN.
type GltfProcessor = LoadTransformAndSave<FakeGltfLoader, GltfToBsn, FakeBsnSaver>;
// This processor loads a BSN file (which "inlines" parent BSNs at load), and then saves the
// inlined BSN.
type BsnProcessor =
LoadTransformAndSave<FakeBsnLoader, IdentityAssetTransformer<FakeBsn>, FakeBsnSaver>;
app.register_asset_loader(FakeBsnLoader)
.register_asset_loader(FakeGltfLoader)
.register_asset_processor(GltfProcessor::new(GltfToBsn, FakeBsnSaver))
.register_asset_processor(BsnProcessor::new(
IdentityAssetTransformer::new(),
FakeBsnSaver,
))
.set_default_asset_processor::<GltfProcessor>("gltf")
.set_default_asset_processor::<BsnProcessor>("bsn");
let guard = source_gate.write_blocking();
let gltf_path = Path::new("abc.gltf");
source_dir.insert_asset_text(
gltf_path,
r#"(
gltf_nodes: {
"name": "thing",
"position": "123",
}
)"#,
);
let bsn_path = Path::new("def.bsn");
// The bsn tries to load the gltf as a bsn. This only works if the bsn can read processed
// assets.
source_dir.insert_asset_text(
bsn_path,
r#"(
parent_bsn: Some("abc.gltf"),
nodes: {
"position": "456",
"color": "red",
},
)"#,
);
run_app_until_finished_processing(&mut app, guard);
let processed_bsn = processed_dir.get_asset(bsn_path).unwrap();
let processed_bsn = str::from_utf8(processed_bsn.value()).unwrap();
// The processed bsn should have been "inlined", so no parent and "overlaid" nodes.
assert_eq!(
processed_bsn,
r#"(
parent_bsn: None,
nodes: {
"color": "red",
"name": "thing",
"position": "456",
},
)"#
);
}
#[test]
fn asset_processor_loading_can_read_source_assets() {
let AppWithProcessor {
mut app,
source_gate,
default_source_dirs:
ProcessingDirs {
source: source_dir,
processed: processed_dir,
..
},
..
} = create_app_with_asset_processor(&[]);
#[derive(Serialize, Deserialize)]
struct FakeGltfxData {
// These are the file paths to the gltfs.
gltfs: Vec<String>,
}
#[derive(Asset, TypePath)]
struct FakeGltfx {
gltfs: Vec<FakeGltf>,
}
#[derive(TypePath)]
struct FakeGltfxLoader;
impl AssetLoader for FakeGltfxLoader {
type Asset = FakeGltfx;
type Error = std::io::Error;
type Settings = ();
async fn load(
&self,
reader: &mut dyn Reader,
_settings: &Self::Settings,
load_context: &mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
use std::io::{Error, ErrorKind};
let mut buf = vec![];
reader.read_to_end(&mut buf).await?;
let gltfx_data: FakeGltfxData =
ron::de::from_bytes(&buf).map_err(|err| Error::new(ErrorKind::InvalidData, err))?;
let mut gltfs = vec![];
for gltf in gltfx_data.gltfs.into_iter() {
// gltfx files come from "generic" software that doesn't know anything about
// Bevy, so it needs to load the source assets to make sense.
let gltf = load_context
.loader()
.immediate()
.load(gltf)
.await
.map_err(|err| Error::new(ErrorKind::InvalidData, err))?;
gltfs.push(gltf.take());
}
Ok(FakeGltfx { gltfs })
}
fn extensions(&self) -> &[&str] {
&["gltfx"]
}
}
#[derive(TypePath)]
struct GltfxToBsn;
impl AssetTransformer for GltfxToBsn {
type AssetInput = FakeGltfx;
type AssetOutput = FakeBsn;
type Settings = ();
type Error = std::io::Error;
async fn transform<'a>(
&'a self,
mut asset: TransformedAsset<Self::AssetInput>,
_settings: &'a Self::Settings,
) -> Result<TransformedAsset<Self::AssetOutput>, Self::Error> {
let gltfx = asset.get_mut();
// Merge together all the gltfs from the gltfx into one big bsn.
let bsn = gltfx.gltfs.drain(..).fold(
FakeBsn {
parent_bsn: None,
nodes: Default::default(),
},
|mut bsn, gltf| {
for (key, value) in gltf.gltf_nodes {
bsn.nodes.insert(key, value);
}
bsn
},
);
Ok(asset.replace_asset(bsn))
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/processor/log.rs | crates/bevy_asset/src/processor/log.rs | use crate::AssetPath;
use alloc::{
boxed::Box,
format,
string::{String, ToString},
vec::Vec,
};
use async_fs::File;
use bevy_ecs::error::BevyError;
use bevy_platform::collections::HashSet;
use bevy_tasks::BoxedFuture;
use futures_lite::{AsyncReadExt, AsyncWriteExt};
use std::path::PathBuf;
use thiserror::Error;
use tracing::error;
/// An in-memory representation of a single [`ProcessorTransactionLog`] entry.
#[derive(Debug)]
pub enum LogEntry {
BeginProcessing(AssetPath<'static>),
EndProcessing(AssetPath<'static>),
UnrecoverableError,
}
/// A factory of [`ProcessorTransactionLog`] that handles the state before the log has been started.
///
/// This trait also assists in recovering from partial processing by fetching the previous state of
/// the transaction log.
pub trait ProcessorTransactionLogFactory: Send + Sync + 'static {
/// Reads all entries in a previous transaction log if present.
///
/// If there is no previous transaction log, this method should return an empty Vec of entries.
fn read(&self) -> BoxedFuture<'_, Result<Vec<LogEntry>, BevyError>>;
/// Creates a new transaction log to write to.
///
/// This should remove any previous entries if they exist.
fn create_new_log(
&self,
) -> BoxedFuture<'_, Result<Box<dyn ProcessorTransactionLog>, BevyError>>;
}
/// A "write ahead" logger that helps ensure asset importing is transactional.
///
/// Prior to processing an asset, we write to the log to indicate it has started. After processing
/// an asset, we write to the log to indicate it has finished. On startup, the log can be read
/// through [`ProcessorTransactionLogFactory`] to determine if any transactions were incomplete.
pub trait ProcessorTransactionLog: Send + Sync + 'static {
/// Logs the start of an asset being processed.
///
/// If this is not followed at some point in the log by a closing
/// [`ProcessorTransactionLog::end_processing`], in the next run of the processor the asset
/// processing will be considered "incomplete" and it will be reprocessed.
fn begin_processing<'a>(
&'a mut self,
asset: &'a AssetPath<'_>,
) -> BoxedFuture<'a, Result<(), BevyError>>;
/// Logs the end of an asset being successfully processed. See
/// [`ProcessorTransactionLog::begin_processing`].
fn end_processing<'a>(
&'a mut self,
asset: &'a AssetPath<'_>,
) -> BoxedFuture<'a, Result<(), BevyError>>;
/// Logs an unrecoverable error.
///
/// On the next run of the processor, all assets will be regenerated. This should only be used
/// as a last resort. Every call to this should be considered with scrutiny and ideally replaced
/// with something more granular.
fn unrecoverable(&mut self) -> BoxedFuture<'_, Result<(), BevyError>>;
}
/// Validate the previous state of the transaction log and determine any assets that need to be
/// reprocessed.
pub(crate) async fn validate_transaction_log(
log_factory: &dyn ProcessorTransactionLogFactory,
) -> Result<(), ValidateLogError> {
let mut transactions: HashSet<AssetPath<'static>> = Default::default();
let mut errors: Vec<LogEntryError> = Vec::new();
let entries = log_factory
.read()
.await
.map_err(ValidateLogError::ReadLogError)?;
for entry in entries {
match entry {
LogEntry::BeginProcessing(path) => {
// There should never be duplicate "start transactions" in a log
// Every start should be followed by:
// * nothing (if there was an abrupt stop)
// * an End (if the transaction was completed)
if !transactions.insert(path.clone()) {
errors.push(LogEntryError::DuplicateTransaction(path));
}
}
LogEntry::EndProcessing(path) => {
if !transactions.remove(&path) {
errors.push(LogEntryError::EndedMissingTransaction(path));
}
}
LogEntry::UnrecoverableError => return Err(ValidateLogError::UnrecoverableError),
}
}
for transaction in transactions {
errors.push(LogEntryError::UnfinishedTransaction(transaction));
}
if !errors.is_empty() {
return Err(ValidateLogError::EntryErrors(errors));
}
Ok(())
}
/// A transaction log factory that uses a file as its storage.
pub struct FileTransactionLogFactory {
/// The file path that the transaction log should write to.
pub file_path: PathBuf,
}
const LOG_PATH: &str = "imported_assets/log";
impl Default for FileTransactionLogFactory {
fn default() -> Self {
#[cfg(not(target_arch = "wasm32"))]
let base_path = crate::io::file::get_base_path();
#[cfg(target_arch = "wasm32")]
let base_path = PathBuf::new();
let file_path = base_path.join(LOG_PATH);
Self { file_path }
}
}
impl ProcessorTransactionLogFactory for FileTransactionLogFactory {
fn read(&self) -> BoxedFuture<'_, Result<Vec<LogEntry>, BevyError>> {
let path = self.file_path.clone();
Box::pin(async move {
let mut log_lines = Vec::new();
let mut file = match File::open(path).await {
Ok(file) => file,
Err(err) => {
if err.kind() == futures_io::ErrorKind::NotFound {
// if the log file doesn't exist, this is equivalent to an empty file
return Ok(log_lines);
}
return Err(err.into());
}
};
let mut string = String::new();
file.read_to_string(&mut string).await?;
for line in string.lines() {
if let Some(path_str) = line.strip_prefix(ENTRY_BEGIN) {
log_lines.push(LogEntry::BeginProcessing(
AssetPath::parse(path_str).into_owned(),
));
} else if let Some(path_str) = line.strip_prefix(ENTRY_END) {
log_lines.push(LogEntry::EndProcessing(
AssetPath::parse(path_str).into_owned(),
));
} else if line.is_empty() {
continue;
} else {
return Err(ReadLogError::InvalidLine(line.to_string()).into());
}
}
Ok(log_lines)
})
}
fn create_new_log(
&self,
) -> BoxedFuture<'_, Result<Box<dyn ProcessorTransactionLog>, BevyError>> {
let path = self.file_path.clone();
Box::pin(async move {
match async_fs::remove_file(&path).await {
Ok(_) => { /* successfully removed file */ }
Err(err) => {
// if the log file is not found, we assume we are starting in a fresh (or good) state
if err.kind() != futures_io::ErrorKind::NotFound {
error!("Failed to remove previous log file {}", err);
}
}
}
if let Some(parent_folder) = path.parent() {
async_fs::create_dir_all(parent_folder).await?;
}
Ok(Box::new(FileProcessorTransactionLog {
log_file: File::create(path).await?,
}) as _)
})
}
}
/// A "write ahead" logger that helps ensure asset importing is transactional.
///
/// Prior to processing an asset, we write to the log to indicate it has started
/// After processing an asset, we write to the log to indicate it has finished.
/// On startup, the log can be read to determine if any transactions were incomplete.
struct FileProcessorTransactionLog {
/// The file to write logs to.
log_file: File,
}
impl FileProcessorTransactionLog {
/// Write `line` to the file and flush it.
async fn write(&mut self, line: &str) -> Result<(), BevyError> {
self.log_file.write_all(line.as_bytes()).await?;
self.log_file.flush().await?;
Ok(())
}
}
const ENTRY_BEGIN: &str = "Begin ";
const ENTRY_END: &str = "End ";
const UNRECOVERABLE_ERROR: &str = "UnrecoverableError";
impl ProcessorTransactionLog for FileProcessorTransactionLog {
fn begin_processing<'a>(
&'a mut self,
asset: &'a AssetPath<'_>,
) -> BoxedFuture<'a, Result<(), BevyError>> {
Box::pin(async move { self.write(&format!("{ENTRY_BEGIN}{asset}\n")).await })
}
fn end_processing<'a>(
&'a mut self,
asset: &'a AssetPath<'_>,
) -> BoxedFuture<'a, Result<(), BevyError>> {
Box::pin(async move { self.write(&format!("{ENTRY_END}{asset}\n")).await })
}
fn unrecoverable(&mut self) -> BoxedFuture<'_, Result<(), BevyError>> {
Box::pin(async move { self.write(UNRECOVERABLE_ERROR).await })
}
}
/// An error that occurs when reading from the [`ProcessorTransactionLog`] fails.
#[derive(Error, Debug)]
pub enum ReadLogError {
/// An invalid log line was encountered, consisting of the contained string.
#[error("Encountered an invalid log line: '{0}'")]
InvalidLine(String),
/// A file-system-based error occurred while reading the log file.
#[error("Failed to read log file: {0}")]
Io(#[from] futures_io::Error),
}
/// An error that occurs when writing to the [`ProcessorTransactionLog`] fails.
#[derive(Error, Debug)]
#[error(
"Failed to write {log_entry:?} to the asset processor log. This is not recoverable. {error}"
)]
pub(crate) struct WriteLogError {
pub(crate) log_entry: LogEntry,
pub(crate) error: BevyError,
}
/// An error that occurs when validating the [`ProcessorTransactionLog`] fails.
#[derive(Error, Debug)]
pub enum ValidateLogError {
/// An error that could not be recovered from. All assets will be reprocessed.
#[error("Encountered an unrecoverable error. All assets will be reprocessed.")]
UnrecoverableError,
/// A [`ReadLogError`].
#[error("Failed to read log entries: {0}")]
ReadLogError(BevyError),
/// Duplicated process asset transactions occurred.
#[error("Encountered a duplicate process asset transaction: {0:?}")]
EntryErrors(Vec<LogEntryError>),
}
/// An error that occurs when validating individual [`ProcessorTransactionLog`] entries.
#[derive(Error, Debug)]
pub enum LogEntryError {
/// A duplicate process asset transaction occurred for the given asset path.
#[error("Encountered a duplicate process asset transaction: {0}")]
DuplicateTransaction(AssetPath<'static>),
/// A transaction was ended that never started for the given asset path.
#[error("A transaction was ended that never started {0}")]
EndedMissingTransaction(AssetPath<'static>),
/// An asset started processing but never finished at the given asset path.
#[error("An asset started processing but never finished: {0}")]
UnfinishedTransaction(AssetPath<'static>),
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/processor/mod.rs | crates/bevy_asset/src/processor/mod.rs | //! Asset processing in Bevy is a framework for automatically transforming artist-authored assets into the format that best suits the needs of your particular game.
//!
//! You can think of the asset processing system as a "build system" for assets.
//! When an artist adds a new asset to the project or an asset is changed (assuming asset hot reloading is enabled), the asset processing system will automatically perform the specified processing steps on the asset.
//! This can include things like creating lightmaps for baked lighting, compressing a `.wav` file to an `.ogg`, or generating mipmaps for a texture.
//!
//! Its core values are:
//!
//! 1. Automatic: new and changed assets should be ready to use in-game without requiring any manual conversion or cleanup steps.
//! 2. Configurable: every game has its own needs, and a high level of transparency and control is required.
//! 3. Lossless: the original asset should always be preserved, ensuring artists can make changes later.
//! 4. Deterministic: performing the same processing steps on the same asset should (generally) produce the exact same result. In cases where this doesn't make sense (steps that involve a degree of randomness or uncertainty), the results across runs should be "acceptably similar", as they will be generated once for a given set of inputs and cached.
//!
//! Taken together, this means that the original asset plus the processing steps should be enough to regenerate the final asset.
//! While it may be possible to manually edit the final asset, this should be discouraged.
//! Final post-processed assets should generally not be version-controlled, except to save developer time when recomputing heavy asset processing steps.
//!
//! # Usage
//!
//! Asset processing can be enabled or disabled in [`AssetPlugin`](crate::AssetPlugin) by setting the [`AssetMode`](crate::AssetMode).\
//! Enable Bevy's `file_watcher` feature to automatically watch for changes to assets and reprocess them.
//!
//! To register a new asset processor, use [`AssetProcessor::register_processor`].
//! To set the default asset processor for a given extension, use [`AssetProcessor::set_default_processor`].
//! In most cases, these methods will be called directly on [`App`](bevy_app::App) using the [`AssetApp`](crate::AssetApp) extension trait.
//!
//! If a default asset processor is set, assets with a matching extension will be processed using that processor before loading.
//!
//! For an end-to-end example, check out the examples in the [`examples/asset/processing`](https://github.com/bevyengine/bevy/tree/latest/examples/asset/processing) directory of the Bevy repository.
//!
//! # Defining asset processors
//!
//! Bevy provides two different ways to define new asset processors:
//!
//! - [`LoadTransformAndSave`] + [`AssetTransformer`](crate::transformer::AssetTransformer): a high-level API for loading, transforming, and saving assets.
//! - [`Process`]: a flexible low-level API for processing assets in arbitrary ways.
//!
//! In most cases, [`LoadTransformAndSave`] should be sufficient.
mod log;
mod process;
use async_lock::RwLockReadGuardArc;
pub use log::*;
pub use process::*;
use crate::{
io::{
AssetReaderError, AssetSource, AssetSourceBuilders, AssetSourceEvent, AssetSourceId,
AssetSources, AssetWriterError, ErasedAssetReader, MissingAssetSourceError,
ReaderRequiredFeatures,
},
meta::{
get_asset_hash, get_full_asset_hash, AssetAction, AssetActionMinimal, AssetHash, AssetMeta,
AssetMetaDyn, AssetMetaMinimal, ProcessedInfo, ProcessedInfoMinimal,
},
AssetLoadError, AssetMetaCheck, AssetPath, AssetServer, AssetServerMode, DeserializeMetaError,
MissingAssetLoaderForExtensionError, UnapprovedPathMode, WriteDefaultMetaError,
};
use alloc::{borrow::ToOwned, boxed::Box, string::String, sync::Arc, vec, vec::Vec};
use bevy_ecs::prelude::*;
use bevy_platform::{
collections::{hash_map::Entry, HashMap, HashSet},
sync::{PoisonError, RwLock},
};
use bevy_tasks::IoTaskPool;
use futures_io::ErrorKind;
use futures_lite::{AsyncWriteExt, StreamExt};
use futures_util::{select_biased, FutureExt};
use std::{
path::{Path, PathBuf},
sync::Mutex,
};
use thiserror::Error;
use tracing::{debug, error, trace, warn};
#[cfg(feature = "trace")]
use {
alloc::string::ToString,
tracing::{info_span, instrument::Instrument},
};
/// 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),
/// processes them in some way, and writes them to a destination [`AssetSource`].
///
/// This will create .meta files (a human-editable serialized form of [`AssetMeta`]) in the source [`AssetSource`] for assets
/// that can be loaded and/or processed. This enables developers to configure how each asset should be loaded and/or processed.
///
/// [`AssetProcessor`] can be run in the background while a Bevy App is running. Changes to assets will be automatically detected and hot-reloaded.
///
/// Assets will only be re-processed if they have been changed. A hash of each asset source is stored in the metadata of the processed version of the
/// asset, which is used to determine if the asset source has actually changed.
///
/// A [`ProcessorTransactionLog`] is produced, which uses "write-ahead logging" to make the [`AssetProcessor`] crash and failure resistant. If a failed/unfinished
/// transaction from a previous run is detected, the affected asset(s) will be re-processed.
///
/// [`AssetProcessor`] can be cloned. It is backed by an [`Arc`] so clones will share state. Clones can be freely used in parallel.
#[derive(Resource, Clone)]
pub struct AssetProcessor {
server: AssetServer,
pub(crate) data: Arc<AssetProcessorData>,
}
/// Internal data stored inside an [`AssetProcessor`].
pub struct AssetProcessorData {
/// The state of processing.
pub(crate) processing_state: Arc<ProcessingState>,
/// The factory that creates the transaction log.
///
/// Note: we use a regular Mutex instead of an async mutex since we expect users to only set
/// this once, and before the asset processor starts - there is no reason to await (and it
/// avoids needing to use [`block_on`](bevy_tasks::block_on) to set the factory).
log_factory: Mutex<Option<Box<dyn ProcessorTransactionLogFactory>>>,
log: async_lock::RwLock<Option<Box<dyn ProcessorTransactionLog>>>,
/// The processors that will be used to process assets.
processors: RwLock<Processors>,
sources: Arc<AssetSources>,
}
/// The current state of processing, including the overall state and the state of all assets.
pub(crate) struct ProcessingState {
/// The overall state of processing.
state: async_lock::RwLock<ProcessorState>,
/// The channel to broadcast when the processor has completed initialization.
initialized_sender: async_broadcast::Sender<()>,
initialized_receiver: async_broadcast::Receiver<()>,
/// The channel to broadcast when the processor has completed processing.
finished_sender: async_broadcast::Sender<()>,
finished_receiver: async_broadcast::Receiver<()>,
/// The current state of the assets.
asset_infos: async_lock::RwLock<ProcessorAssetInfos>,
}
#[derive(Default)]
struct Processors {
/// Maps the type path of the processor to its instance.
type_path_to_processor: HashMap<&'static str, Arc<dyn ErasedProcessor>>,
/// Maps the short type path of the processor to its instance.
short_type_path_to_processor: HashMap<&'static str, ShortTypeProcessorEntry>,
/// Maps the file extension of an asset to the type path of the processor we should use to
/// process it by default.
file_extension_to_default_processor: HashMap<Box<str>, &'static str>,
}
enum ShortTypeProcessorEntry {
/// There is a unique processor with the given short type path.
Unique {
/// The full type path of the processor.
type_path: &'static str,
/// The processor itself.
processor: Arc<dyn ErasedProcessor>,
},
/// There are (at least) two processors with the same short type path (storing the full type
/// paths of all conflicting processors). Users must fully specify the type path in order to
/// disambiguate.
Ambiguous(Vec<&'static str>),
}
impl AssetProcessor {
/// Creates a new [`AssetProcessor`] instance.
pub fn new(
sources: &mut AssetSourceBuilders,
watch_processed: bool,
) -> (Self, Arc<AssetSources>) {
let state = Arc::new(ProcessingState::new());
let mut sources = sources.build_sources(true, watch_processed);
sources.gate_on_processor(state.clone());
let sources = Arc::new(sources);
let data = Arc::new(AssetProcessorData::new(sources.clone(), state));
// The asset processor uses its own asset server with its own id space
let server = AssetServer::new_with_meta_check(
sources.clone(),
AssetServerMode::Processed,
AssetMetaCheck::Always,
false,
UnapprovedPathMode::default(),
);
(Self { server, data }, sources)
}
/// Gets a reference to the [`Arc`] containing the [`AssetProcessorData`].
pub fn data(&self) -> &Arc<AssetProcessorData> {
&self.data
}
/// The "internal" [`AssetServer`] used by the [`AssetProcessor`]. This is _separate_ from the asset processor used by
/// the main App. It has different processor-specific configuration and a different ID space.
pub fn server(&self) -> &AssetServer {
&self.server
}
/// Retrieves the current [`ProcessorState`]
pub async fn get_state(&self) -> ProcessorState {
self.data.processing_state.get_state().await
}
/// Retrieves the [`AssetSource`] for this processor
#[inline]
pub fn get_source<'a>(
&self,
id: impl Into<AssetSourceId<'a>>,
) -> Result<&AssetSource, MissingAssetSourceError> {
self.data.sources.get(id.into())
}
#[inline]
pub fn sources(&self) -> &AssetSources {
&self.data.sources
}
/// Logs an unrecoverable error. On the next run of the processor, all assets will be regenerated. This should only be used as a last resort.
/// Every call to this should be considered with scrutiny and ideally replaced with something more granular.
async fn log_unrecoverable(&self) {
let mut log = self.data.log.write().await;
let log = log.as_mut().unwrap();
log.unrecoverable()
.await
.map_err(|error| WriteLogError {
log_entry: LogEntry::UnrecoverableError,
error,
})
.unwrap();
}
/// Logs the start of an asset being processed. If this is not followed at some point in the log by a closing [`AssetProcessor::log_end_processing`],
/// in the next run of the processor the asset processing will be considered "incomplete" and it will be reprocessed.
async fn log_begin_processing(&self, path: &AssetPath<'_>) {
let mut log = self.data.log.write().await;
let log = log.as_mut().unwrap();
log.begin_processing(path)
.await
.map_err(|error| WriteLogError {
log_entry: LogEntry::BeginProcessing(path.clone_owned()),
error,
})
.unwrap();
}
/// Logs the end of an asset being successfully processed. See [`AssetProcessor::log_begin_processing`].
async fn log_end_processing(&self, path: &AssetPath<'_>) {
let mut log = self.data.log.write().await;
let log = log.as_mut().unwrap();
log.end_processing(path)
.await
.map_err(|error| WriteLogError {
log_entry: LogEntry::EndProcessing(path.clone_owned()),
error,
})
.unwrap();
}
/// Starts the processor in a background thread.
pub fn start(processor: Res<Self>) {
let processor = processor.clone();
IoTaskPool::get()
.spawn(async move {
let start_time = std::time::Instant::now();
debug!("Processing Assets");
processor.initialize().await.unwrap();
let (new_task_sender, new_task_receiver) = async_channel::unbounded();
processor
.queue_initial_processing_tasks(&new_task_sender)
.await;
// Once all the tasks are queued for the initial processing, start actually
// executing the tasks.
{
let processor = processor.clone();
let new_task_sender = new_task_sender.clone();
IoTaskPool::get()
.spawn(async move {
processor
.execute_processing_tasks(new_task_sender, new_task_receiver)
.await;
})
.detach();
}
processor.data.wait_until_finished().await;
let end_time = std::time::Instant::now();
debug!("Processing finished in {:?}", end_time - start_time);
debug!("Listening for changes to source assets");
processor.spawn_source_change_event_listeners(&new_task_sender);
})
.detach();
}
/// Sends start task events for all assets in all processed sources into `sender`.
async fn queue_initial_processing_tasks(
&self,
sender: &async_channel::Sender<(AssetSourceId<'static>, PathBuf)>,
) {
for source in self.sources().iter_processed() {
self.queue_processing_tasks_for_folder(source, PathBuf::from(""), sender)
.await
.unwrap();
}
}
/// Spawns listeners of change events for all asset sources which will start processor tasks in
/// response.
fn spawn_source_change_event_listeners(
&self,
sender: &async_channel::Sender<(AssetSourceId<'static>, PathBuf)>,
) {
for source in self.data.sources.iter_processed() {
let Some(receiver) = source.event_receiver().cloned() else {
continue;
};
let source_id = source.id();
let processor = self.clone();
let sender = sender.clone();
IoTaskPool::get()
.spawn(async move {
while let Ok(event) = receiver.recv().await {
let Ok(source) = processor.get_source(source_id.clone()) else {
return;
};
processor
.handle_asset_source_event(source, event, &sender)
.await;
}
})
.detach();
}
}
/// Executes all tasks that come through `receiver`, and updates the processor's overall state
/// based on task starts and ends.
///
/// This future does not terminate until the channel is closed (not when the channel is empty).
/// This means that in [`AssetProcessor::start`], this execution will continue even after all
/// the initial tasks are processed.
async fn execute_processing_tasks(
&self,
new_task_sender: async_channel::Sender<(AssetSourceId<'static>, PathBuf)>,
new_task_receiver: async_channel::Receiver<(AssetSourceId<'static>, PathBuf)>,
) {
// Convert the Sender into a WeakSender so that once all task producers terminate (and drop
// their sender), this task doesn't keep itself alive. We still however need a way to get
// the sender since processing tasks can start the tasks of dependent assets.
let new_task_sender = {
let weak_sender = new_task_sender.downgrade();
drop(new_task_sender);
weak_sender
};
// If there aren't any tasks in the channel the first time around, we should immediately go
// to the finished state (otherwise we'd be sitting around stuck in the `Initialized`
// state).
if new_task_receiver.is_empty() {
self.data
.processing_state
.set_state(ProcessorState::Finished)
.await;
}
enum ProcessorTaskEvent {
Start(AssetSourceId<'static>, PathBuf),
Finished,
}
let (task_finished_sender, task_finished_receiver) = async_channel::unbounded::<()>();
let mut pending_tasks = 0;
while let Ok(event) = {
// It's ok to use `select_biased` since we prefer to start task rather than finish tasks
// anyway - since otherwise we might mark the processor as finished before all queued
// tasks are done. `select_biased` also doesn't depend on `std` which is nice!
select_biased! {
result = new_task_receiver.recv().fuse() => {
result.map(|(source_id, path)| ProcessorTaskEvent::Start(source_id, path))
},
result = task_finished_receiver.recv().fuse() => {
result.map(|()| ProcessorTaskEvent::Finished)
}
}
} {
match event {
ProcessorTaskEvent::Start(source_id, path) => {
let Some(new_task_sender) = new_task_sender.upgrade() else {
// If we can't upgrade the task sender, that means all sources of tasks
// (like the source event listeners) have been dropped. That means that the
// sources are no longer in the app, so reading/writing to them will
// probably not work, so ignoring the task is fine. This also likely means
// that the whole app is being dropped, so we can recover on the next
// initialization.
continue;
};
let processor = self.clone();
let task_finished_sender = task_finished_sender.clone();
pending_tasks += 1;
IoTaskPool::get()
.spawn(async move {
let Ok(source) = processor.get_source(source_id) else {
return;
};
processor.process_asset(source, path, new_task_sender).await;
// If the channel gets closed, that's ok. Just ignore it.
let _ = task_finished_sender.send(()).await;
})
.detach();
self.data
.processing_state
.set_state(ProcessorState::Processing)
.await;
}
ProcessorTaskEvent::Finished => {
pending_tasks -= 1;
if pending_tasks == 0 {
// clean up metadata in asset server
self.server.write_infos().consume_handle_drop_events();
self.data
.processing_state
.set_state(ProcessorState::Finished)
.await;
}
}
}
}
}
/// Writes the default meta file for the provided `path`.
///
/// This function generates the appropriate meta file to process `path` with the default
/// processor. If there is no default processor, it falls back to the default loader.
///
/// Note if there is already a meta file for `path`, this function returns
/// `Err(WriteDefaultMetaError::MetaAlreadyExists)`.
pub async fn write_default_meta_file_for_path(
&self,
path: impl Into<AssetPath<'_>>,
) -> Result<(), WriteDefaultMetaError> {
let path = path.into();
let Some(processor) = path
.get_full_extension()
.and_then(|extension| self.get_default_processor(&extension))
else {
return self
.server
.write_default_loader_meta_file_for_path(path)
.await;
};
let meta = processor.default_meta();
let serialized_meta = meta.serialize();
let source = self.get_source(path.source())?;
// Note: we get the reader rather than the processed reader, since we want to write the meta
// file for the unprocessed version of that asset (so it will be processed by the default
// processor).
let reader = source.reader();
match reader.read_meta_bytes(path.path()).await {
Ok(_) => return Err(WriteDefaultMetaError::MetaAlreadyExists),
Err(AssetReaderError::UnsupportedFeature(feature)) => panic!("reading the meta file never requests a feature, but the following feature is unsupported: {feature}"),
Err(AssetReaderError::NotFound(_)) => {
// The meta file couldn't be found so just fall through.
}
Err(AssetReaderError::Io(err)) => {
return Err(WriteDefaultMetaError::IoErrorFromExistingMetaCheck(err))
}
Err(AssetReaderError::HttpError(err)) => {
return Err(WriteDefaultMetaError::HttpErrorFromExistingMetaCheck(err))
}
}
let writer = source.writer()?;
writer
.write_meta_bytes(path.path(), &serialized_meta)
.await?;
Ok(())
}
async fn handle_asset_source_event(
&self,
source: &AssetSource,
event: AssetSourceEvent,
new_task_sender: &async_channel::Sender<(AssetSourceId<'static>, PathBuf)>,
) {
trace!("{event:?}");
match event {
AssetSourceEvent::AddedAsset(path)
| AssetSourceEvent::AddedMeta(path)
| AssetSourceEvent::ModifiedAsset(path)
| AssetSourceEvent::ModifiedMeta(path) => {
let _ = new_task_sender.send((source.id(), path)).await;
}
AssetSourceEvent::RemovedAsset(path) => {
self.handle_removed_asset(source, path).await;
}
AssetSourceEvent::RemovedMeta(path) => {
self.handle_removed_meta(source, path, new_task_sender)
.await;
}
AssetSourceEvent::AddedFolder(path) => {
self.handle_added_folder(source, path, new_task_sender)
.await;
}
// NOTE: As a heads up for future devs: this event shouldn't be run in parallel with other events that might
// touch this folder (ex: the folder might be re-created with new assets). Clean up the old state first.
// Currently this event handler is not parallel, but it could be (and likely should be) in the future.
AssetSourceEvent::RemovedFolder(path) => {
self.handle_removed_folder(source, &path).await;
}
AssetSourceEvent::RenamedAsset { old, new } => {
// If there was a rename event, but the path hasn't changed, this asset might need reprocessing.
// Sometimes this event is returned when an asset is moved "back" into the asset folder
if old == new {
let _ = new_task_sender.send((source.id(), new)).await;
} else {
self.handle_renamed_asset(source, old, new, new_task_sender)
.await;
}
}
AssetSourceEvent::RenamedMeta { old, new } => {
// If there was a rename event, but the path hasn't changed, this asset meta might need reprocessing.
// Sometimes this event is returned when an asset meta is moved "back" into the asset folder
if old == new {
let _ = new_task_sender.send((source.id(), new)).await;
} else {
debug!("Meta renamed from {old:?} to {new:?}");
// Renaming meta should not assume that an asset has also been renamed. Check both old and new assets to see
// if they should be re-imported (and/or have new meta generated)
let _ = new_task_sender.send((source.id(), old)).await;
let _ = new_task_sender.send((source.id(), new)).await;
}
}
AssetSourceEvent::RenamedFolder { old, new } => {
// If there was a rename event, but the path hasn't changed, this asset folder might need reprocessing.
// Sometimes this event is returned when an asset meta is moved "back" into the asset folder
if old == new {
self.handle_added_folder(source, new, new_task_sender).await;
} else {
// PERF: this reprocesses everything in the moved folder. this is not necessary in most cases, but
// requires some nuance when it comes to path handling.
self.handle_removed_folder(source, &old).await;
self.handle_added_folder(source, new, new_task_sender).await;
}
}
AssetSourceEvent::RemovedUnknown { path, is_meta } => {
let processed_reader = source.ungated_processed_reader().unwrap();
match processed_reader.is_directory(&path).await {
Ok(is_directory) => {
if is_directory {
self.handle_removed_folder(source, &path).await;
} else if is_meta {
self.handle_removed_meta(source, path, new_task_sender)
.await;
} else {
self.handle_removed_asset(source, path).await;
}
}
Err(err) => {
match err {
// There is never a reason for a path check to return an
// `UnsupportedFeature` error. This must be an incorrectly programmed
// `AssetReader`, so just panic to make this clearly unsupported.
AssetReaderError::UnsupportedFeature(feature) => panic!("checking whether a path is a file or folder resulted in unsupported feature: {feature}"),
AssetReaderError::NotFound(_) => {
// if the path is not found, a processed version does not exist
}
AssetReaderError::Io(err) => {
error!(
"Path '{}' was removed, but the destination reader could not determine if it \
was a folder or a file due to the following error: {err}",
AssetPath::from_path(&path).with_source(source.id())
);
}
AssetReaderError::HttpError(status) => {
error!(
"Path '{}' was removed, but the destination reader could not determine if it \
was a folder or a file due to receiving an unexpected HTTP Status {status}",
AssetPath::from_path(&path).with_source(source.id())
);
}
}
}
}
}
}
}
async fn handle_added_folder(
&self,
source: &AssetSource,
path: PathBuf,
new_task_sender: &async_channel::Sender<(AssetSourceId<'static>, PathBuf)>,
) {
debug!(
"Folder {} was added. Attempting to re-process",
AssetPath::from_path(&path).with_source(source.id())
);
self.queue_processing_tasks_for_folder(source, path, new_task_sender)
.await
.unwrap();
}
/// Responds to a removed meta event by reprocessing the asset at the given path.
async fn handle_removed_meta(
&self,
source: &AssetSource,
path: PathBuf,
new_task_sender: &async_channel::Sender<(AssetSourceId<'static>, PathBuf)>,
) {
// If meta was removed, we might need to regenerate it.
// Likewise, the user might be manually re-adding the asset.
// Therefore, we shouldn't automatically delete the asset ... that is a
// user-initiated action.
debug!(
"Meta for asset {} was removed. Attempting to re-process",
AssetPath::from_path(&path).with_source(source.id())
);
let _ = new_task_sender.send((source.id(), path)).await;
}
/// Removes all processed assets stored at the given path (respecting transactionality), then removes the folder itself.
async fn handle_removed_folder(&self, source: &AssetSource, path: &Path) {
debug!(
"Removing folder {} because source was removed",
path.display()
);
let processed_reader = source.ungated_processed_reader().unwrap();
match processed_reader.read_directory(path).await {
Ok(mut path_stream) => {
while let Some(child_path) = path_stream.next().await {
self.handle_removed_asset(source, child_path).await;
}
}
Err(err) => match err {
// There is never a reason for a directory read to return an `UnsupportedFeature`
// error. This must be an incorrectly programmed `AssetReader`, so just panic to
// make this clearly unsupported.
AssetReaderError::UnsupportedFeature(feature) => {
panic!("reading a directory resulted in unsupported feature: {feature}")
}
AssetReaderError::NotFound(_err) => {
// The processed folder does not exist. No need to update anything
}
AssetReaderError::HttpError(status) => {
self.log_unrecoverable().await;
error!(
"Unrecoverable Error: Failed to read the processed assets at {path:?} in order to remove assets that no longer exist \
in the source directory. Restart the asset processor to fully reprocess assets. HTTP Status Code {status}"
);
}
AssetReaderError::Io(err) => {
self.log_unrecoverable().await;
error!(
"Unrecoverable Error: Failed to read the processed assets at {path:?} in order to remove assets that no longer exist \
in the source directory. Restart the asset processor to fully reprocess assets. Error: {err}"
);
}
},
}
let processed_writer = source.processed_writer().unwrap();
if let Err(err) = processed_writer.remove_directory(path).await {
match err {
AssetWriterError::Io(err) => {
// we can ignore NotFound because if the "final" file in a folder was removed
// then we automatically clean up this folder
if err.kind() != ErrorKind::NotFound {
let asset_path = AssetPath::from_path(path).with_source(source.id());
error!("Failed to remove destination folder that no longer exists in {asset_path}: {err}");
}
}
}
}
}
/// Removes the processed version of an asset and associated in-memory metadata. This will block until all existing reads/writes to the
/// asset have finished, thanks to the `file_transaction_lock`.
async fn handle_removed_asset(&self, source: &AssetSource, path: PathBuf) {
let asset_path = AssetPath::from(path).with_source(source.id());
debug!("Removing processed {asset_path} because source was removed");
let lock = {
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/server/info.rs | crates/bevy_asset/src/server/info.rs | use crate::{
meta::{AssetHash, MetaTransform},
Asset, AssetHandleProvider, AssetIndex, AssetLoadError, AssetPath, DependencyLoadState,
ErasedAssetIndex, ErasedLoadedAsset, Handle, InternalAssetEvent, LoadState,
RecursiveDependencyLoadState, StrongHandle, UntypedHandle,
};
use alloc::{
borrow::ToOwned,
boxed::Box,
sync::{Arc, Weak},
vec::Vec,
};
use bevy_ecs::world::World;
use bevy_platform::collections::{hash_map::Entry, HashMap, HashSet};
use bevy_tasks::Task;
use bevy_utils::TypeIdMap;
use core::{any::TypeId, task::Waker};
use crossbeam_channel::Sender;
use either::Either;
use thiserror::Error;
use tracing::warn;
#[derive(Debug)]
pub(crate) struct AssetInfo {
weak_handle: Weak<StrongHandle>,
pub(crate) path: Option<AssetPath<'static>>,
pub(crate) load_state: LoadState,
pub(crate) dep_load_state: DependencyLoadState,
pub(crate) rec_dep_load_state: RecursiveDependencyLoadState,
loading_dependencies: HashSet<ErasedAssetIndex>,
failed_dependencies: HashSet<ErasedAssetIndex>,
loading_rec_dependencies: HashSet<ErasedAssetIndex>,
failed_rec_dependencies: HashSet<ErasedAssetIndex>,
dependents_waiting_on_load: HashSet<ErasedAssetIndex>,
dependents_waiting_on_recursive_dep_load: HashSet<ErasedAssetIndex>,
/// The asset paths required to load this asset. Hashes will only be set for processed assets.
/// This is set using the value from [`LoadedAsset`].
/// This will only be populated if [`AssetInfos::watching_for_changes`] is set to `true` to
/// save memory.
///
/// [`LoadedAsset`]: crate::loader::LoadedAsset
loader_dependencies: HashMap<AssetPath<'static>, AssetHash>,
/// The number of handle drops to skip for this asset.
/// See usage (and comments) in `get_or_create_path_handle` for context.
handle_drops_to_skip: usize,
/// List of tasks waiting for this asset to complete loading
pub(crate) waiting_tasks: Vec<Waker>,
}
impl AssetInfo {
fn new(weak_handle: Weak<StrongHandle>, path: Option<AssetPath<'static>>) -> Self {
Self {
weak_handle,
path,
load_state: LoadState::NotLoaded,
dep_load_state: DependencyLoadState::NotLoaded,
rec_dep_load_state: RecursiveDependencyLoadState::NotLoaded,
loading_dependencies: HashSet::default(),
failed_dependencies: HashSet::default(),
loading_rec_dependencies: HashSet::default(),
failed_rec_dependencies: HashSet::default(),
loader_dependencies: HashMap::default(),
dependents_waiting_on_load: HashSet::default(),
dependents_waiting_on_recursive_dep_load: HashSet::default(),
handle_drops_to_skip: 0,
waiting_tasks: Vec::new(),
}
}
}
/// Tracks statistics of the asset server.
#[derive(Default, Clone, PartialEq, Eq)]
pub(crate) struct AssetServerStats {
/// The number of load tasks that have been started.
pub(crate) started_load_tasks: usize,
}
#[derive(Default)]
pub(crate) struct AssetInfos {
path_to_index: HashMap<AssetPath<'static>, TypeIdMap<AssetIndex>>,
infos: HashMap<ErasedAssetIndex, AssetInfo>,
/// If set to `true`, this informs [`AssetInfos`] to track data relevant to watching for changes (such as `load_dependents`)
/// This should only be set at startup.
pub(crate) watching_for_changes: bool,
/// Tracks assets that depend on the "key" asset path inside their asset loaders ("loader dependencies")
/// This should only be set when watching for changes to avoid unnecessary work.
pub(crate) loader_dependents: HashMap<AssetPath<'static>, HashSet<AssetPath<'static>>>,
/// Tracks living labeled assets for a given source asset.
/// This should only be set when watching for changes to avoid unnecessary work.
pub(crate) living_labeled_assets: HashMap<AssetPath<'static>, HashSet<Box<str>>>,
pub(crate) handle_providers: TypeIdMap<AssetHandleProvider>,
pub(crate) dependency_loaded_event_sender: TypeIdMap<fn(&mut World, AssetIndex)>,
pub(crate) dependency_failed_event_sender:
TypeIdMap<fn(&mut World, AssetIndex, AssetPath<'static>, AssetLoadError)>,
pub(crate) pending_tasks: HashMap<ErasedAssetIndex, Task<()>>,
/// The stats that have collected during usage of the asset server.
pub(crate) stats: AssetServerStats,
}
impl core::fmt::Debug for AssetInfos {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("AssetInfos")
.field("path_to_index", &self.path_to_index)
.field("infos", &self.infos)
.finish()
}
}
impl AssetInfos {
pub(crate) fn create_loading_handle_untyped(
&mut self,
type_id: TypeId,
type_name: &'static str,
) -> UntypedHandle {
unwrap_with_context(
Self::create_handle_internal(
&mut self.infos,
&self.handle_providers,
&mut self.living_labeled_assets,
self.watching_for_changes,
type_id,
None,
None,
true,
),
Either::Left(type_name),
)
.unwrap()
}
fn create_handle_internal(
infos: &mut HashMap<ErasedAssetIndex, AssetInfo>,
handle_providers: &TypeIdMap<AssetHandleProvider>,
living_labeled_assets: &mut HashMap<AssetPath<'static>, HashSet<Box<str>>>,
watching_for_changes: bool,
type_id: TypeId,
path: Option<AssetPath<'static>>,
meta_transform: Option<MetaTransform>,
loading: bool,
) -> Result<UntypedHandle, GetOrCreateHandleInternalError> {
let provider = handle_providers
.get(&type_id)
.ok_or(MissingHandleProviderError(type_id))?;
if watching_for_changes && let Some(path) = &path {
let mut without_label = path.to_owned();
if let Some(label) = without_label.take_label() {
let labels = living_labeled_assets.entry(without_label).or_default();
labels.insert(label.as_ref().into());
}
}
let handle = provider.reserve_handle_internal(true, path.clone(), meta_transform);
let mut info = AssetInfo::new(Arc::downgrade(&handle), path);
if loading {
info.load_state = LoadState::Loading;
info.dep_load_state = DependencyLoadState::Loading;
info.rec_dep_load_state = RecursiveDependencyLoadState::Loading;
}
infos.insert(ErasedAssetIndex::new(handle.index, handle.type_id), info);
Ok(UntypedHandle::Strong(handle))
}
pub(crate) fn get_or_create_path_handle<A: Asset>(
&mut self,
path: AssetPath<'static>,
loading_mode: HandleLoadingMode,
meta_transform: Option<MetaTransform>,
) -> (Handle<A>, bool) {
let result = self.get_or_create_path_handle_internal(
path,
Some(TypeId::of::<A>()),
loading_mode,
meta_transform,
);
// it is ok to unwrap because TypeId was specified above
let (handle, should_load) =
unwrap_with_context(result, Either::Left(core::any::type_name::<A>())).unwrap();
(handle.typed_unchecked(), should_load)
}
pub(crate) fn get_or_create_path_handle_erased(
&mut self,
path: AssetPath<'static>,
type_id: TypeId,
type_name: Option<&str>,
loading_mode: HandleLoadingMode,
meta_transform: Option<MetaTransform>,
) -> (UntypedHandle, bool) {
let result = self.get_or_create_path_handle_internal(
path,
Some(type_id),
loading_mode,
meta_transform,
);
let type_info = match type_name {
Some(type_name) => Either::Left(type_name),
None => Either::Right(type_id),
};
unwrap_with_context(result, type_info)
.expect("type should be correct since the `TypeId` is specified above")
}
/// Retrieves asset tracking data, or creates it if it doesn't exist.
/// Returns true if an asset load should be kicked off
pub(crate) fn get_or_create_path_handle_internal(
&mut self,
path: AssetPath<'static>,
type_id: Option<TypeId>,
loading_mode: HandleLoadingMode,
meta_transform: Option<MetaTransform>,
) -> Result<(UntypedHandle, bool), GetOrCreateHandleInternalError> {
let handles = self.path_to_index.entry(path.clone()).or_default();
let type_id = type_id
.or_else(|| {
// If a TypeId is not provided, we may be able to infer it if only a single entry exists
if handles.len() == 1 {
Some(*handles.keys().next().unwrap())
} else {
None
}
})
.ok_or(GetOrCreateHandleInternalError::HandleMissingButTypeIdNotSpecified)?;
match handles.entry(type_id) {
Entry::Occupied(entry) => {
let index = *entry.get();
// if there is a path_to_id entry, info always exists
let info = self
.infos
.get_mut(&ErasedAssetIndex::new(index, type_id))
.unwrap();
let mut should_load = false;
if loading_mode == HandleLoadingMode::Force
|| (loading_mode == HandleLoadingMode::Request
&& matches!(info.load_state, LoadState::NotLoaded | LoadState::Failed(_)))
{
info.load_state = LoadState::Loading;
info.dep_load_state = DependencyLoadState::Loading;
info.rec_dep_load_state = RecursiveDependencyLoadState::Loading;
should_load = true;
}
if let Some(strong_handle) = info.weak_handle.upgrade() {
// If we can upgrade the handle, there is at least one live handle right now,
// The asset load has already kicked off (and maybe completed), so we can just
// return a strong handle
Ok((UntypedHandle::Strong(strong_handle), should_load))
} else {
// Asset meta exists, but all live handles were dropped. This means the `track_assets` system
// hasn't been run yet to remove the current asset
// (note that this is guaranteed to be transactional with the `track_assets` system
// because it locks the AssetInfos collection)
// We must create a new strong handle for the existing id and ensure that the drop of the old
// strong handle doesn't remove the asset from the Assets collection
info.handle_drops_to_skip += 1;
let provider = self
.handle_providers
.get(&type_id)
.ok_or(MissingHandleProviderError(type_id))?;
let handle = provider.get_handle(index, true, Some(path), meta_transform);
info.weak_handle = Arc::downgrade(&handle);
Ok((UntypedHandle::Strong(handle), should_load))
}
}
// The entry does not exist, so this is a "fresh" asset load. We must create a new handle
Entry::Vacant(entry) => {
let should_load = match loading_mode {
HandleLoadingMode::NotLoading => false,
HandleLoadingMode::Request | HandleLoadingMode::Force => true,
};
let handle = Self::create_handle_internal(
&mut self.infos,
&self.handle_providers,
&mut self.living_labeled_assets,
self.watching_for_changes,
type_id,
Some(path),
meta_transform,
should_load,
)?;
let index = match &handle {
UntypedHandle::Strong(handle) => handle.index,
// `create_handle_internal` always returns Strong variant.
UntypedHandle::Uuid { .. } => unreachable!(),
};
entry.insert(index);
Ok((handle, should_load))
}
}
}
pub(crate) fn get(&self, index: ErasedAssetIndex) -> Option<&AssetInfo> {
self.infos.get(&index)
}
pub(crate) fn contains_key(&self, index: ErasedAssetIndex) -> bool {
self.infos.contains_key(&index)
}
pub(crate) fn get_mut(&mut self, index: ErasedAssetIndex) -> Option<&mut AssetInfo> {
self.infos.get_mut(&index)
}
pub(crate) fn get_path_and_type_id_handle(
&self,
path: &AssetPath<'_>,
type_id: TypeId,
) -> Option<UntypedHandle> {
let index = *self.path_to_index.get(path)?.get(&type_id)?;
self.get_index_handle(ErasedAssetIndex::new(index, type_id))
}
pub(crate) fn get_path_indices<'a>(
&'a self,
path: &'a AssetPath<'_>,
) -> impl Iterator<Item = ErasedAssetIndex> + 'a {
/// Concrete type to allow returning an `impl Iterator` even if `self.path_to_id.get(&path)` is `None`
enum HandlesByPathIterator<T> {
None,
Some(T),
}
impl<T> Iterator for HandlesByPathIterator<T>
where
T: Iterator<Item = ErasedAssetIndex>,
{
type Item = ErasedAssetIndex;
fn next(&mut self) -> Option<Self::Item> {
match self {
HandlesByPathIterator::None => None,
HandlesByPathIterator::Some(iter) => iter.next(),
}
}
}
if let Some(type_id_to_id) = self.path_to_index.get(path) {
HandlesByPathIterator::Some(
type_id_to_id
.iter()
.map(|(type_id, index)| ErasedAssetIndex::new(*index, *type_id)),
)
} else {
HandlesByPathIterator::None
}
}
pub(crate) fn get_path_handles<'a>(
&'a self,
path: &'a AssetPath<'_>,
) -> impl Iterator<Item = UntypedHandle> + 'a {
self.get_path_indices(path)
.filter_map(|id| self.get_index_handle(id))
}
pub(crate) fn get_index_handle(&self, index: ErasedAssetIndex) -> Option<UntypedHandle> {
let info = self.infos.get(&index)?;
let strong_handle = info.weak_handle.upgrade()?;
Some(UntypedHandle::Strong(strong_handle))
}
/// Returns `true` if the asset this path points to is still alive
pub(crate) fn is_path_alive<'a>(&self, path: impl Into<AssetPath<'a>>) -> bool {
self.get_path_indices(&path.into())
.filter_map(|id| self.infos.get(&id))
.any(|info| info.weak_handle.strong_count() > 0)
}
/// Returns `true` if the asset at this path should be reloaded
pub(crate) fn should_reload(&self, path: &AssetPath) -> bool {
if self.is_path_alive(path) {
return true;
}
if let Some(living) = self.living_labeled_assets.get(path) {
!living.is_empty()
} else {
false
}
}
/// Returns `true` if the asset should be removed from the collection.
pub(crate) fn process_handle_drop(&mut self, index: ErasedAssetIndex) -> bool {
Self::process_handle_drop_internal(
&mut self.infos,
&mut self.path_to_index,
&mut self.loader_dependents,
&mut self.living_labeled_assets,
&mut self.pending_tasks,
self.watching_for_changes,
index,
)
}
/// Updates [`AssetInfo`] / load state for an asset that has finished loading (and relevant dependencies / dependents).
pub(crate) fn process_asset_load(
&mut self,
loaded_asset_index: ErasedAssetIndex,
loaded_asset: ErasedLoadedAsset,
world: &mut World,
sender: &Sender<InternalAssetEvent>,
) {
// Process all the labeled assets first so that they don't get skipped due to the "parent"
// not having its handle alive.
for (_, asset) in loaded_asset.labeled_assets {
let UntypedHandle::Strong(handle) = &asset.handle else {
unreachable!("Labeled assets are always strong handles");
};
self.process_asset_load(
ErasedAssetIndex {
index: handle.index,
type_id: handle.type_id,
},
asset.asset,
world,
sender,
);
}
// Check whether the handle has been dropped since the asset was loaded.
if !self.infos.contains_key(&loaded_asset_index) {
return;
}
loaded_asset.value.insert(loaded_asset_index.index, world);
let mut loading_deps = loaded_asset.dependencies;
let mut failed_deps = <HashSet<_>>::default();
let mut dep_error = None;
let mut loading_rec_deps = loading_deps.clone();
let mut failed_rec_deps = <HashSet<_>>::default();
let mut rec_dep_error = None;
loading_deps.retain(|dep_id| {
if let Some(dep_info) = self.get_mut(*dep_id) {
match dep_info.rec_dep_load_state {
RecursiveDependencyLoadState::Loading
| RecursiveDependencyLoadState::NotLoaded => {
// If dependency is loading, wait for it.
dep_info
.dependents_waiting_on_recursive_dep_load
.insert(loaded_asset_index);
}
RecursiveDependencyLoadState::Loaded => {
// If dependency is loaded, reduce our count by one
loading_rec_deps.remove(dep_id);
}
RecursiveDependencyLoadState::Failed(ref error) => {
if rec_dep_error.is_none() {
rec_dep_error = Some(error.clone());
}
failed_rec_deps.insert(*dep_id);
loading_rec_deps.remove(dep_id);
}
}
match dep_info.load_state {
LoadState::NotLoaded | LoadState::Loading => {
// If dependency is loading, wait for it.
dep_info.dependents_waiting_on_load.insert(loaded_asset_index);
true
}
LoadState::Loaded => {
// If dependency is loaded, reduce our count by one
false
}
LoadState::Failed(ref error) => {
if dep_error.is_none() {
dep_error = Some(error.clone());
}
failed_deps.insert(*dep_id);
false
}
}
} else {
// the dependency id does not exist, which implies it was manually removed or never existed in the first place
warn!(
"Dependency {} from asset {} is unknown. This asset's dependency load status will not switch to 'Loaded' until the unknown dependency is loaded.",
dep_id, loaded_asset_index
);
true
}
});
let dep_load_state = match (loading_deps.len(), failed_deps.len()) {
(0, 0) => DependencyLoadState::Loaded,
(_loading, 0) => DependencyLoadState::Loading,
(_loading, _failed) => DependencyLoadState::Failed(dep_error.unwrap()),
};
let rec_dep_load_state = match (loading_rec_deps.len(), failed_rec_deps.len()) {
(0, 0) => {
sender
.send(InternalAssetEvent::LoadedWithDependencies {
index: loaded_asset_index,
})
.unwrap();
RecursiveDependencyLoadState::Loaded
}
(_loading, 0) => RecursiveDependencyLoadState::Loading,
(_loading, _failed) => RecursiveDependencyLoadState::Failed(rec_dep_error.unwrap()),
};
let (dependents_waiting_on_load, dependents_waiting_on_rec_load) = {
let watching_for_changes = self.watching_for_changes;
// if watching for changes, track reverse loader dependencies for hot reloading
if watching_for_changes {
let info = self
.infos
.get(&loaded_asset_index)
.expect("Asset info should always exist at this point");
if let Some(asset_path) = &info.path {
for loader_dependency in loaded_asset.loader_dependencies.keys() {
let dependents = self
.loader_dependents
.entry(loader_dependency.clone())
.or_default();
dependents.insert(asset_path.clone());
}
}
}
let info = self
.get_mut(loaded_asset_index)
.expect("Asset info should always exist at this point");
info.loading_dependencies = loading_deps;
info.failed_dependencies = failed_deps;
info.loading_rec_dependencies = loading_rec_deps;
info.failed_rec_dependencies = failed_rec_deps;
info.load_state = LoadState::Loaded;
info.dep_load_state = dep_load_state;
info.rec_dep_load_state = rec_dep_load_state.clone();
if watching_for_changes {
info.loader_dependencies = loaded_asset.loader_dependencies;
}
let dependents_waiting_on_rec_load =
if rec_dep_load_state.is_loaded() || rec_dep_load_state.is_failed() {
Some(core::mem::take(
&mut info.dependents_waiting_on_recursive_dep_load,
))
} else {
None
};
(
core::mem::take(&mut info.dependents_waiting_on_load),
dependents_waiting_on_rec_load,
)
};
for id in dependents_waiting_on_load {
if let Some(info) = self.get_mut(id) {
info.loading_dependencies.remove(&loaded_asset_index);
if info.loading_dependencies.is_empty() && !info.dep_load_state.is_failed() {
// send dependencies loaded event
info.dep_load_state = DependencyLoadState::Loaded;
}
}
}
if let Some(dependents_waiting_on_rec_load) = dependents_waiting_on_rec_load {
match rec_dep_load_state {
RecursiveDependencyLoadState::Loaded => {
for dep_id in dependents_waiting_on_rec_load {
Self::propagate_loaded_state(self, loaded_asset_index, dep_id, sender);
}
}
RecursiveDependencyLoadState::Failed(ref error) => {
for dep_id in dependents_waiting_on_rec_load {
Self::propagate_failed_state(self, loaded_asset_index, dep_id, error);
}
}
RecursiveDependencyLoadState::Loading | RecursiveDependencyLoadState::NotLoaded => {
// dependents_waiting_on_rec_load should be None in this case
unreachable!("`Loading` and `NotLoaded` state should never be propagated.")
}
}
}
}
/// Recursively propagates loaded state up the dependency tree.
fn propagate_loaded_state(
infos: &mut AssetInfos,
loaded_id: ErasedAssetIndex,
waiting_id: ErasedAssetIndex,
sender: &Sender<InternalAssetEvent>,
) {
let dependents_waiting_on_rec_load = if let Some(info) = infos.get_mut(waiting_id) {
info.loading_rec_dependencies.remove(&loaded_id);
if info.loading_rec_dependencies.is_empty() && info.failed_rec_dependencies.is_empty() {
info.rec_dep_load_state = RecursiveDependencyLoadState::Loaded;
if info.load_state.is_loaded() {
sender
.send(InternalAssetEvent::LoadedWithDependencies { index: waiting_id })
.unwrap();
}
Some(core::mem::take(
&mut info.dependents_waiting_on_recursive_dep_load,
))
} else {
None
}
} else {
None
};
if let Some(dependents_waiting_on_rec_load) = dependents_waiting_on_rec_load {
for dep_id in dependents_waiting_on_rec_load {
Self::propagate_loaded_state(infos, waiting_id, dep_id, sender);
}
}
}
/// Recursively propagates failed state up the dependency tree
fn propagate_failed_state(
infos: &mut AssetInfos,
failed_id: ErasedAssetIndex,
waiting_id: ErasedAssetIndex,
error: &Arc<AssetLoadError>,
) {
let dependents_waiting_on_rec_load = if let Some(info) = infos.get_mut(waiting_id) {
info.loading_rec_dependencies.remove(&failed_id);
info.failed_rec_dependencies.insert(failed_id);
info.rec_dep_load_state = RecursiveDependencyLoadState::Failed(error.clone());
Some(core::mem::take(
&mut info.dependents_waiting_on_recursive_dep_load,
))
} else {
None
};
if let Some(dependents_waiting_on_rec_load) = dependents_waiting_on_rec_load {
for dep_id in dependents_waiting_on_rec_load {
Self::propagate_failed_state(infos, waiting_id, dep_id, error);
}
}
}
pub(crate) fn process_asset_fail(
&mut self,
failed_index: ErasedAssetIndex,
error: AssetLoadError,
) {
// Check whether the handle has been dropped since the asset was loaded.
if !self.infos.contains_key(&failed_index) {
return;
}
let error = Arc::new(error);
let (dependents_waiting_on_load, dependents_waiting_on_rec_load) = {
let Some(info) = self.get_mut(failed_index) else {
// The asset was already dropped.
return;
};
info.load_state = LoadState::Failed(error.clone());
info.dep_load_state = DependencyLoadState::Failed(error.clone());
info.rec_dep_load_state = RecursiveDependencyLoadState::Failed(error.clone());
for waker in info.waiting_tasks.drain(..) {
waker.wake();
}
(
core::mem::take(&mut info.dependents_waiting_on_load),
core::mem::take(&mut info.dependents_waiting_on_recursive_dep_load),
)
};
for waiting_id in dependents_waiting_on_load {
if let Some(info) = self.get_mut(waiting_id) {
info.loading_dependencies.remove(&failed_index);
info.failed_dependencies.insert(failed_index);
// don't overwrite DependencyLoadState if already failed to preserve first error
if !info.dep_load_state.is_failed() {
info.dep_load_state = DependencyLoadState::Failed(error.clone());
}
}
}
for waiting_id in dependents_waiting_on_rec_load {
Self::propagate_failed_state(self, failed_index, waiting_id, &error);
}
}
fn remove_dependents_and_labels(
info: &AssetInfo,
loader_dependents: &mut HashMap<AssetPath<'static>, HashSet<AssetPath<'static>>>,
path: &AssetPath<'static>,
living_labeled_assets: &mut HashMap<AssetPath<'static>, HashSet<Box<str>>>,
) {
for loader_dependency in info.loader_dependencies.keys() {
if let Some(dependents) = loader_dependents.get_mut(loader_dependency) {
dependents.remove(path);
}
}
let Some(label) = path.label() else {
return;
};
let mut without_label = path.to_owned();
without_label.remove_label();
let Entry::Occupied(mut entry) = living_labeled_assets.entry(without_label) else {
return;
};
entry.get_mut().remove(label);
if entry.get().is_empty() {
entry.remove();
}
}
fn process_handle_drop_internal(
infos: &mut HashMap<ErasedAssetIndex, AssetInfo>,
path_to_id: &mut HashMap<AssetPath<'static>, TypeIdMap<AssetIndex>>,
loader_dependents: &mut HashMap<AssetPath<'static>, HashSet<AssetPath<'static>>>,
living_labeled_assets: &mut HashMap<AssetPath<'static>, HashSet<Box<str>>>,
pending_tasks: &mut HashMap<ErasedAssetIndex, Task<()>>,
watching_for_changes: bool,
index: ErasedAssetIndex,
) -> bool {
let Entry::Occupied(mut entry) = infos.entry(index) else {
// Either the asset was already dropped, it doesn't exist, or it isn't managed by the asset server
// None of these cases should result in a removal from the Assets collection
return false;
};
if entry.get_mut().handle_drops_to_skip > 0 {
entry.get_mut().handle_drops_to_skip -= 1;
return false;
}
pending_tasks.remove(&index);
let type_id = entry.key().type_id;
let info = entry.remove();
let Some(path) = &info.path else {
return true;
};
if watching_for_changes {
Self::remove_dependents_and_labels(
&info,
loader_dependents,
path,
living_labeled_assets,
);
}
if let Some(map) = path_to_id.get_mut(path) {
map.remove(&type_id);
if map.is_empty() {
path_to_id.remove(path);
}
};
true
}
/// Consumes all current handle drop events. This will update information in [`AssetInfos`], but it
/// will not affect [`Assets`] storages. For normal use cases, prefer `Assets::track_assets()`
/// This should only be called if `Assets` storage isn't being used (such as in [`AssetProcessor`](crate::processor::AssetProcessor))
///
/// [`Assets`]: crate::Assets
pub(crate) fn consume_handle_drop_events(&mut self) {
for provider in self.handle_providers.values() {
while let Ok(drop_event) = provider.drop_receiver.try_recv() {
let id = drop_event.index;
if drop_event.asset_server_managed {
Self::process_handle_drop_internal(
&mut self.infos,
&mut self.path_to_index,
&mut self.loader_dependents,
&mut self.living_labeled_assets,
&mut self.pending_tasks,
self.watching_for_changes,
id,
);
}
}
}
}
}
/// Determines how a handle should be initialized
#[derive(Copy, Clone, PartialEq, Eq)]
pub(crate) enum HandleLoadingMode {
/// The handle is for an asset that isn't loading/loaded yet.
NotLoading,
/// The handle is for an asset that is being _requested_ to load (if it isn't already loading)
Request,
/// The handle is for an asset that is being forced to load (even if it has already loaded)
Force,
}
#[derive(Error, Debug)]
#[error("Cannot allocate a handle because no handle provider exists for asset type {0:?}")]
pub struct MissingHandleProviderError(TypeId);
/// An error encountered during [`AssetInfos::get_or_create_path_handle_internal`].
#[derive(Error, Debug)]
pub(crate) enum GetOrCreateHandleInternalError {
#[error(transparent)]
MissingHandleProviderError(#[from] MissingHandleProviderError),
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/server/mod.rs | crates/bevy_asset/src/server/mod.rs | mod info;
mod loaders;
use crate::{
folder::LoadedFolder,
io::{
AssetReaderError, AssetSource, AssetSourceEvent, AssetSourceId, AssetSources,
AssetWriterError, ErasedAssetReader, MissingAssetSourceError, MissingAssetWriterError,
MissingProcessedAssetReaderError, Reader,
},
loader::{AssetLoader, ErasedAssetLoader, LoadContext, LoadedAsset},
meta::{
loader_settings_meta_transform, AssetActionMinimal, AssetMetaDyn, AssetMetaMinimal,
MetaTransform, Settings,
},
path::AssetPath,
Asset, AssetEvent, AssetHandleProvider, AssetId, AssetIndex, AssetLoadFailedEvent,
AssetMetaCheck, Assets, DeserializeMetaError, ErasedAssetIndex, ErasedLoadedAsset, Handle,
LoadedUntypedAsset, UnapprovedPathMode, UntypedAssetId, UntypedAssetLoadFailedEvent,
UntypedHandle,
};
use alloc::{borrow::ToOwned, boxed::Box, vec, vec::Vec};
use alloc::{
format,
string::{String, ToString},
sync::Arc,
};
use atomicow::CowArc;
use bevy_diagnostic::{DiagnosticPath, Diagnostics};
use bevy_ecs::prelude::*;
use bevy_platform::{
collections::HashSet,
sync::{PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard},
};
use bevy_tasks::IoTaskPool;
use core::{any::TypeId, future::Future, panic::AssertUnwindSafe, task::Poll};
use crossbeam_channel::{Receiver, Sender};
use either::Either;
use futures_lite::{FutureExt, StreamExt};
use info::*;
use loaders::*;
use std::path::{Path, PathBuf};
use thiserror::Error;
use tracing::{error, info};
/// 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 retrieve their current load states.
///
/// The general process to load an asset is:
/// 1. Initialize a new [`Asset`] type with the [`AssetServer`] via [`AssetApp::init_asset`], which
/// will internally call [`AssetServer::register_asset`] and set up related ECS [`Assets`]
/// storage and systems.
/// 2. Register one or more [`AssetLoader`]s for that asset with [`AssetApp::init_asset_loader`]
/// 3. Add the asset to your asset folder (defaults to `assets`).
/// 4. Call [`AssetServer::load`] with a path to your asset.
///
/// [`AssetServer`] can be cloned. It is backed by an [`Arc`] so clones will share state. Clones can be freely used in parallel.
///
/// [`AssetApp::init_asset`]: crate::AssetApp::init_asset
/// [`AssetApp::init_asset_loader`]: crate::AssetApp::init_asset_loader
#[derive(Resource, Clone)]
pub struct AssetServer {
pub(crate) data: Arc<AssetServerData>,
}
/// Internal data used by [`AssetServer`]. This is intended to be used from within an [`Arc`].
pub(crate) struct AssetServerData {
pub(crate) infos: RwLock<AssetInfos>,
pub(crate) loaders: Arc<RwLock<AssetLoaders>>,
asset_event_sender: Sender<InternalAssetEvent>,
asset_event_receiver: Receiver<InternalAssetEvent>,
sources: Arc<AssetSources>,
mode: AssetServerMode,
meta_check: AssetMetaCheck,
unapproved_path_mode: UnapprovedPathMode,
}
/// The "asset mode" the server is currently in.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AssetServerMode {
/// This server loads unprocessed assets.
Unprocessed,
/// This server loads processed assets.
Processed,
}
impl AssetServer {
/// The number of loads that have been started by the server.
pub const STARTED_LOAD_COUNT: DiagnosticPath = DiagnosticPath::const_new("started_load_count");
/// Create a new instance of [`AssetServer`]. If `watch_for_changes` is true, the [`AssetReader`](crate::io::AssetReader) storage will watch for changes to
/// asset sources and hot-reload them.
pub fn new(
sources: Arc<AssetSources>,
mode: AssetServerMode,
watching_for_changes: bool,
unapproved_path_mode: UnapprovedPathMode,
) -> Self {
Self::new_with_loaders(
sources,
Default::default(),
mode,
AssetMetaCheck::Always,
watching_for_changes,
unapproved_path_mode,
)
}
/// Create a new instance of [`AssetServer`]. If `watch_for_changes` is true, the [`AssetReader`](crate::io::AssetReader) storage will watch for changes to
/// asset sources and hot-reload them.
pub fn new_with_meta_check(
sources: Arc<AssetSources>,
mode: AssetServerMode,
meta_check: AssetMetaCheck,
watching_for_changes: bool,
unapproved_path_mode: UnapprovedPathMode,
) -> Self {
Self::new_with_loaders(
sources,
Default::default(),
mode,
meta_check,
watching_for_changes,
unapproved_path_mode,
)
}
pub(crate) fn new_with_loaders(
sources: Arc<AssetSources>,
loaders: Arc<RwLock<AssetLoaders>>,
mode: AssetServerMode,
meta_check: AssetMetaCheck,
watching_for_changes: bool,
unapproved_path_mode: UnapprovedPathMode,
) -> Self {
let (asset_event_sender, asset_event_receiver) = crossbeam_channel::unbounded();
let mut infos = AssetInfos::default();
infos.watching_for_changes = watching_for_changes;
Self {
data: Arc::new(AssetServerData {
sources,
mode,
meta_check,
asset_event_sender,
asset_event_receiver,
loaders,
infos: RwLock::new(infos),
unapproved_path_mode,
}),
}
}
pub(crate) fn read_infos(&self) -> RwLockReadGuard<'_, AssetInfos> {
self.data
.infos
.read()
.unwrap_or_else(PoisonError::into_inner)
}
pub(crate) fn write_infos(&self) -> RwLockWriteGuard<'_, AssetInfos> {
self.data
.infos
.write()
.unwrap_or_else(PoisonError::into_inner)
}
fn read_loaders(&self) -> RwLockReadGuard<'_, AssetLoaders> {
self.data
.loaders
.read()
.unwrap_or_else(PoisonError::into_inner)
}
fn write_loaders(&self) -> RwLockWriteGuard<'_, AssetLoaders> {
self.data
.loaders
.write()
.unwrap_or_else(PoisonError::into_inner)
}
/// Retrieves the [`AssetSource`] for the given `source`.
pub fn get_source<'a>(
&self,
source: impl Into<AssetSourceId<'a>>,
) -> Result<&AssetSource, MissingAssetSourceError> {
self.data.sources.get(source.into())
}
/// Returns true if the [`AssetServer`] watches for changes.
pub fn watching_for_changes(&self) -> bool {
self.read_infos().watching_for_changes
}
/// Registers a new [`AssetLoader`]. [`AssetLoader`]s must be registered before they can be used.
pub fn register_loader<L: AssetLoader>(&self, loader: L) {
self.write_loaders().push(loader);
}
/// Registers a new [`Asset`] type. [`Asset`] types must be registered before assets of that type can be loaded.
pub fn register_asset<A: Asset>(&self, assets: &Assets<A>) {
self.register_handle_provider(assets.get_handle_provider());
fn sender<A: Asset>(world: &mut World, index: AssetIndex) {
world
.resource_mut::<Messages<AssetEvent<A>>>()
.write(AssetEvent::LoadedWithDependencies { id: index.into() });
}
fn failed_sender<A: Asset>(
world: &mut World,
index: AssetIndex,
path: AssetPath<'static>,
error: AssetLoadError,
) {
world
.resource_mut::<Messages<AssetLoadFailedEvent<A>>>()
.write(AssetLoadFailedEvent {
id: index.into(),
path,
error,
});
}
let mut infos = self.write_infos();
infos
.dependency_loaded_event_sender
.insert(TypeId::of::<A>(), sender::<A>);
infos
.dependency_failed_event_sender
.insert(TypeId::of::<A>(), failed_sender::<A>);
}
pub(crate) fn register_handle_provider(&self, handle_provider: AssetHandleProvider) {
self.write_infos()
.handle_providers
.insert(handle_provider.type_id, handle_provider);
}
/// Returns the registered [`AssetLoader`] associated with the given extension, if it exists.
pub async fn get_asset_loader_with_extension(
&self,
extension: &str,
) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForExtensionError> {
let error = || MissingAssetLoaderForExtensionError {
extensions: vec![extension.to_string()],
};
let loader = self
.read_loaders()
.get_by_extension(extension)
.ok_or_else(error)?;
loader.get().await.map_err(|_| error())
}
/// Returns the registered [`AssetLoader`] associated with the given type name, if it exists.
pub async fn get_asset_loader_with_type_name(
&self,
type_name: &str,
) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForTypeNameError> {
let error = || MissingAssetLoaderForTypeNameError {
type_name: type_name.to_string(),
};
let loader = self
.read_loaders()
.get_by_name(type_name)
.ok_or_else(error)?;
loader.get().await.map_err(|_| error())
}
/// Retrieves the default [`AssetLoader`] for the given path, if one can be found.
pub async fn get_path_asset_loader<'a>(
&self,
path: impl Into<AssetPath<'a>>,
) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForExtensionError> {
let path = path.into();
let error = || {
let Some(full_extension) = path.get_full_extension() else {
return MissingAssetLoaderForExtensionError {
extensions: Vec::new(),
};
};
let mut extensions = vec![full_extension.clone()];
extensions.extend(
AssetPath::iter_secondary_extensions(&full_extension).map(ToString::to_string),
);
MissingAssetLoaderForExtensionError { extensions }
};
let loader = self.read_loaders().get_by_path(&path).ok_or_else(error)?;
loader.get().await.map_err(|_| error())
}
/// Retrieves the default [`AssetLoader`] for the given [`Asset`] [`TypeId`], if one can be found.
pub async fn get_asset_loader_with_asset_type_id(
&self,
type_id: TypeId,
) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForTypeIdError> {
let error = || MissingAssetLoaderForTypeIdError { type_id };
let loader = self.read_loaders().get_by_type(type_id).ok_or_else(error)?;
loader.get().await.map_err(|_| error())
}
/// Retrieves the default [`AssetLoader`] for the given [`Asset`] type, if one can be found.
pub async fn get_asset_loader_with_asset_type<A: Asset>(
&self,
) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForTypeIdError> {
self.get_asset_loader_with_asset_type_id(TypeId::of::<A>())
.await
}
/// Begins loading an [`Asset`] of type `A` stored at `path`. This will not block on the asset load. Instead,
/// it returns a "strong" [`Handle`]. When the [`Asset`] is loaded (and enters [`LoadState::Loaded`]), it will be added to the
/// associated [`Assets`] resource.
///
/// Note that if the asset at this path is already loaded, this function will return the existing handle,
/// and will not waste work spawning a new load task.
///
/// In case the file path contains a hashtag (`#`), the `path` must be specified using [`Path`]
/// or [`AssetPath`] because otherwise the hashtag would be interpreted as separator between
/// the file path and the label. For example:
///
/// ```no_run
/// # use bevy_asset::{AssetServer, Handle, LoadedUntypedAsset};
/// # use bevy_ecs::prelude::Res;
/// # use std::path::Path;
/// // `#path` is a label.
/// # fn setup(asset_server: Res<AssetServer>) {
/// # let handle: Handle<LoadedUntypedAsset> =
/// asset_server.load("some/file#path");
///
/// // `#path` is part of the file name.
/// # let handle: Handle<LoadedUntypedAsset> =
/// asset_server.load(Path::new("some/file#path"));
/// # }
/// ```
///
/// Furthermore, if you need to load a file with a hashtag in its name _and_ a label, you can
/// manually construct an [`AssetPath`].
///
/// ```no_run
/// # use bevy_asset::{AssetPath, AssetServer, Handle, LoadedUntypedAsset};
/// # use bevy_ecs::prelude::Res;
/// # use std::path::Path;
/// # fn setup(asset_server: Res<AssetServer>) {
/// # let handle: Handle<LoadedUntypedAsset> =
/// asset_server.load(AssetPath::from_path(Path::new("some/file#path")).with_label("subasset"));
/// # }
/// ```
///
/// You can check the asset's load state by reading [`AssetEvent`] events, calling [`AssetServer::load_state`], or checking
/// the [`Assets`] storage to see if the [`Asset`] exists yet.
///
/// The asset load will fail and an error will be printed to the logs if the asset stored at `path` is not of type `A`.
#[must_use = "not using the returned strong handle may result in the unexpected release of the asset"]
pub fn load<'a, A: Asset>(&self, path: impl Into<AssetPath<'a>>) -> Handle<A> {
self.load_with_meta_transform(path, None, (), false)
}
/// Same as [`load`](AssetServer::load), but you can load assets from unapproved paths
/// if [`AssetPlugin::unapproved_path_mode`](super::AssetPlugin::unapproved_path_mode)
/// is [`Deny`](UnapprovedPathMode::Deny).
///
/// See [`UnapprovedPathMode`] and [`AssetPath::is_unapproved`]
pub fn load_override<'a, A: Asset>(&self, path: impl Into<AssetPath<'a>>) -> Handle<A> {
self.load_with_meta_transform(path, None, (), true)
}
/// Begins loading an [`Asset`] of type `A` stored at `path` while holding a guard item.
/// The guard item is dropped when either the asset is loaded or loading has failed.
///
/// This function returns a "strong" [`Handle`]. When the [`Asset`] is loaded (and enters [`LoadState::Loaded`]), it will be added to the
/// associated [`Assets`] resource.
///
/// The guard item should notify the caller in its [`Drop`] implementation. See example `multi_asset_sync`.
/// Synchronously this can be a [`Arc<AtomicU32>`] that decrements its counter, asynchronously this can be a `Barrier`.
/// This function only guarantees the asset referenced by the [`Handle`] is loaded. If your asset is separated into
/// multiple files, sub-assets referenced by the main asset might still be loading, depend on the implementation of the [`AssetLoader`].
///
/// Additionally, you can check the asset's load state by reading [`AssetEvent`] events, calling [`AssetServer::load_state`], or checking
/// the [`Assets`] storage to see if the [`Asset`] exists yet.
///
/// The asset load will fail and an error will be printed to the logs if the asset stored at `path` is not of type `A`.
#[must_use = "not using the returned strong handle may result in the unexpected release of the asset"]
pub fn load_acquire<'a, A: Asset, G: Send + Sync + 'static>(
&self,
path: impl Into<AssetPath<'a>>,
guard: G,
) -> Handle<A> {
self.load_with_meta_transform(path, None, guard, false)
}
/// Same as [`load`](AssetServer::load_acquire), but you can load assets from unapproved paths
/// if [`AssetPlugin::unapproved_path_mode`](super::AssetPlugin::unapproved_path_mode)
/// is [`Deny`](UnapprovedPathMode::Deny).
///
/// See [`UnapprovedPathMode`] and [`AssetPath::is_unapproved`]
pub fn load_acquire_override<'a, A: Asset, G: Send + Sync + 'static>(
&self,
path: impl Into<AssetPath<'a>>,
guard: G,
) -> Handle<A> {
self.load_with_meta_transform(path, None, guard, true)
}
/// Begins loading an [`Asset`] of type `A` stored at `path`. The given `settings` function will override the asset's
/// [`AssetLoader`] settings. The type `S` _must_ match the configured [`AssetLoader::Settings`] or `settings` changes
/// will be ignored and an error will be printed to the log.
#[must_use = "not using the returned strong handle may result in the unexpected release of the asset"]
pub fn load_with_settings<'a, A: Asset, S: Settings>(
&self,
path: impl Into<AssetPath<'a>>,
settings: impl Fn(&mut S) + Send + Sync + 'static,
) -> Handle<A> {
self.load_with_meta_transform(
path,
Some(loader_settings_meta_transform(settings)),
(),
false,
)
}
/// Same as [`load`](AssetServer::load_with_settings), but you can load assets from unapproved paths
/// if [`AssetPlugin::unapproved_path_mode`](super::AssetPlugin::unapproved_path_mode)
/// is [`Deny`](UnapprovedPathMode::Deny).
///
/// See [`UnapprovedPathMode`] and [`AssetPath::is_unapproved`]
pub fn load_with_settings_override<'a, A: Asset, S: Settings>(
&self,
path: impl Into<AssetPath<'a>>,
settings: impl Fn(&mut S) + Send + Sync + 'static,
) -> Handle<A> {
self.load_with_meta_transform(
path,
Some(loader_settings_meta_transform(settings)),
(),
true,
)
}
/// Begins loading an [`Asset`] of type `A` stored at `path` while holding a guard item.
/// The guard item is dropped when either the asset is loaded or loading has failed.
///
/// This function only guarantees the asset referenced by the [`Handle`] is loaded. If your asset is separated into
/// multiple files, sub-assets referenced by the main asset might still be loading, depend on the implementation of the [`AssetLoader`].
///
/// The given `settings` function will override the asset's
/// [`AssetLoader`] settings. The type `S` _must_ match the configured [`AssetLoader::Settings`] or `settings` changes
/// will be ignored and an error will be printed to the log.
#[must_use = "not using the returned strong handle may result in the unexpected release of the asset"]
pub fn load_acquire_with_settings<'a, A: Asset, S: Settings, G: Send + Sync + 'static>(
&self,
path: impl Into<AssetPath<'a>>,
settings: impl Fn(&mut S) + Send + Sync + 'static,
guard: G,
) -> Handle<A> {
self.load_with_meta_transform(
path,
Some(loader_settings_meta_transform(settings)),
guard,
false,
)
}
/// Same as [`load`](AssetServer::load_acquire_with_settings), but you can load assets from unapproved paths
/// if [`AssetPlugin::unapproved_path_mode`](super::AssetPlugin::unapproved_path_mode)
/// is [`Deny`](UnapprovedPathMode::Deny).
///
/// See [`UnapprovedPathMode`] and [`AssetPath::is_unapproved`]
pub fn load_acquire_with_settings_override<
'a,
A: Asset,
S: Settings,
G: Send + Sync + 'static,
>(
&self,
path: impl Into<AssetPath<'a>>,
settings: impl Fn(&mut S) + Send + Sync + 'static,
guard: G,
) -> Handle<A> {
self.load_with_meta_transform(
path,
Some(loader_settings_meta_transform(settings)),
guard,
true,
)
}
pub(crate) fn load_with_meta_transform<'a, A: Asset, G: Send + Sync + 'static>(
&self,
path: impl Into<AssetPath<'a>>,
meta_transform: Option<MetaTransform>,
guard: G,
override_unapproved: bool,
) -> Handle<A> {
let path = path.into().into_owned();
if path.is_unapproved() {
match (&self.data.unapproved_path_mode, override_unapproved) {
(UnapprovedPathMode::Allow, _) | (UnapprovedPathMode::Deny, true) => {}
(UnapprovedPathMode::Deny, false) | (UnapprovedPathMode::Forbid, _) => {
error!("Asset path {path} is unapproved. See UnapprovedPathMode for details.");
return Handle::default();
}
}
}
let mut infos = self.write_infos();
let (handle, should_load) = infos.get_or_create_path_handle::<A>(
path.clone(),
HandleLoadingMode::Request,
meta_transform,
);
if should_load {
self.spawn_load_task(handle.clone().untyped(), path, infos, guard);
}
handle
}
pub(crate) fn load_erased_with_meta_transform<'a, G: Send + Sync + 'static>(
&self,
path: impl Into<AssetPath<'a>>,
type_id: TypeId,
meta_transform: Option<MetaTransform>,
guard: G,
) -> UntypedHandle {
let path = path.into().into_owned();
let mut infos = self.write_infos();
let (handle, should_load) = infos.get_or_create_path_handle_erased(
path.clone(),
type_id,
None,
HandleLoadingMode::Request,
meta_transform,
);
if should_load {
self.spawn_load_task(handle.clone(), path, infos, guard);
}
handle
}
pub(crate) fn spawn_load_task<G: Send + Sync + 'static>(
&self,
handle: UntypedHandle,
path: AssetPath<'static>,
mut infos: RwLockWriteGuard<AssetInfos>,
guard: G,
) {
infos.stats.started_load_tasks += 1;
// drop the lock on `AssetInfos` before spawning a task that may block on it in single-threaded
#[cfg(any(target_arch = "wasm32", not(feature = "multi_threaded")))]
drop(infos);
let owned_handle = handle.clone();
let server = self.clone();
let task = IoTaskPool::get().spawn(async move {
if let Err(err) = server
.load_internal(Some(owned_handle), path, false, None)
.await
{
error!("{}", err);
}
drop(guard);
});
#[cfg(not(any(target_arch = "wasm32", not(feature = "multi_threaded"))))]
{
let mut infos = infos;
infos
.pending_tasks
.insert((&handle).try_into().unwrap(), task);
}
#[cfg(any(target_arch = "wasm32", not(feature = "multi_threaded")))]
task.detach();
}
/// Asynchronously load an asset that you do not know the type of statically. If you _do_ know the type of the asset,
/// you should use [`AssetServer::load`]. If you don't know the type of the asset, but you can't use an async method,
/// consider using [`AssetServer::load_untyped`].
#[must_use = "not using the returned strong handle may result in the unexpected release of the asset"]
pub async fn load_untyped_async<'a>(
&self,
path: impl Into<AssetPath<'a>>,
) -> Result<UntypedHandle, AssetLoadError> {
self.write_infos().stats.started_load_tasks += 1;
let path: AssetPath = path.into();
self.load_internal(None, path, false, None)
.await
.map(|h| h.expect("handle must be returned, since we didn't pass in an input handle"))
}
pub(crate) fn load_unknown_type_with_meta_transform<'a>(
&self,
path: impl Into<AssetPath<'a>>,
meta_transform: Option<MetaTransform>,
) -> Handle<LoadedUntypedAsset> {
let path = path.into().into_owned();
let untyped_source = AssetSourceId::Name(match path.source() {
AssetSourceId::Default => CowArc::Static(UNTYPED_SOURCE_SUFFIX),
AssetSourceId::Name(source) => {
CowArc::Owned(format!("{source}--{UNTYPED_SOURCE_SUFFIX}").into())
}
});
let mut infos = self.write_infos();
let (handle, should_load) = infos.get_or_create_path_handle::<LoadedUntypedAsset>(
path.clone().with_source(untyped_source),
HandleLoadingMode::Request,
meta_transform,
);
if !should_load {
return handle;
}
let index = (&handle).try_into().unwrap();
infos.stats.started_load_tasks += 1;
// drop the lock on `AssetInfos` before spawning a task that may block on it in single-threaded
#[cfg(any(target_arch = "wasm32", not(feature = "multi_threaded")))]
drop(infos);
let server = self.clone();
let task = IoTaskPool::get().spawn(async move {
let path_clone = path.clone();
match server
.load_internal(None, path, false, None)
.await
.map(|h| {
h.expect("handle must be returned, since we didn't pass in an input handle")
}) {
Ok(handle) => server.send_asset_event(InternalAssetEvent::Loaded {
index,
loaded_asset: LoadedAsset::new_with_dependencies(LoadedUntypedAsset { handle })
.into(),
}),
Err(err) => {
error!("{err}");
server.send_asset_event(InternalAssetEvent::Failed {
index,
path: path_clone,
error: err,
});
}
};
});
#[cfg(not(any(target_arch = "wasm32", not(feature = "multi_threaded"))))]
infos.pending_tasks.insert(index, task);
#[cfg(any(target_arch = "wasm32", not(feature = "multi_threaded")))]
task.detach();
handle
}
/// Load an asset without knowing its type. The method returns a handle to a [`LoadedUntypedAsset`].
///
/// Once the [`LoadedUntypedAsset`] is loaded, an untyped handle for the requested path can be
/// retrieved from it.
///
/// ```
/// use bevy_asset::{Assets, Handle, LoadedUntypedAsset};
/// use bevy_ecs::system::Res;
/// use bevy_ecs::resource::Resource;
///
/// #[derive(Resource)]
/// struct LoadingUntypedHandle(Handle<LoadedUntypedAsset>);
///
/// fn resolve_loaded_untyped_handle(loading_handle: Res<LoadingUntypedHandle>, loaded_untyped_assets: Res<Assets<LoadedUntypedAsset>>) {
/// if let Some(loaded_untyped_asset) = loaded_untyped_assets.get(&loading_handle.0) {
/// let handle = loaded_untyped_asset.handle.clone();
/// // continue working with `handle` which points to the asset at the originally requested path
/// }
/// }
/// ```
///
/// This indirection enables a non blocking load of an untyped asset, since I/O is
/// required to figure out the asset type before a handle can be created.
#[must_use = "not using the returned strong handle may result in the unexpected release of the assets"]
pub fn load_untyped<'a>(&self, path: impl Into<AssetPath<'a>>) -> Handle<LoadedUntypedAsset> {
self.load_unknown_type_with_meta_transform(path, None)
}
/// Performs an async asset load.
///
/// `input_handle` must only be [`Some`] if `should_load` was true when retrieving
/// `input_handle`. This is an optimization to avoid looking up `should_load` twice, but it
/// means you _must_ be sure a load is necessary when calling this function with [`Some`].
///
/// Returns the handle of the asset if one was retrieved by this function. Otherwise, may return
/// [`None`].
async fn load_internal<'a>(
&self,
input_handle: Option<UntypedHandle>,
path: AssetPath<'a>,
force: bool,
meta_transform: Option<MetaTransform>,
) -> Result<Option<UntypedHandle>, AssetLoadError> {
let input_handle_type_id = input_handle.as_ref().map(UntypedHandle::type_id);
let path = path.into_owned();
let path_clone = path.clone();
let (mut meta, loader, mut reader) = self
.get_meta_loader_and_reader(&path_clone, input_handle_type_id)
.await
.inspect_err(|e| {
// if there was an input handle, a "load" operation has already started, so we must produce a "failure" event, if
// we cannot find the meta and loader
if let Some(handle) = &input_handle {
self.send_asset_event(InternalAssetEvent::Failed {
index: handle.try_into().unwrap(),
path: path.clone_owned(),
error: e.clone(),
});
}
})?;
if let Some(meta_transform) = input_handle.as_ref().and_then(|h| h.meta_transform()) {
(*meta_transform)(&mut *meta);
}
let asset_id: Option<ErasedAssetIndex>; // The asset ID of the asset we are trying to load.
let fetched_handle; // The handle if one was looked up/created.
let should_load; // Whether we need to load the asset.
if let Some(input_handle) = input_handle {
// This must have been created with `get_or_create_path_handle_internal` at some point,
// which only produces Strong variant handles, so this is safe.
asset_id = Some((&input_handle).try_into().unwrap());
// In this case, we intentionally drop the input handle so we can cancel loading the
// asset if the handle gets dropped (externally) before it finishes loading.
fetched_handle = None;
// The handle was passed in, so the "should_load" check was already done.
should_load = true;
} else {
// TODO: multiple asset loads for the same path can happen at the same time (rather than
// "early out-ing" in the "normal" case). This would be resolved by a universal asset
// id, as we would not need to resolve the asset type to generate the ID. See this
// issue: https://github.com/bevyengine/bevy/issues/10549
let mut infos = self.write_infos();
let result = infos.get_or_create_path_handle_internal(
path.clone(),
path.label().is_none().then(|| loader.asset_type_id()),
HandleLoadingMode::Request,
meta_transform,
);
match unwrap_with_context(result, Either::Left(loader.asset_type_name())) {
// We couldn't figure out the correct handle without its type ID (which can only
// happen if we are loading a subasset).
None => {
// We don't know the expected type since the subasset may have a different type
// than the "root" asset (which is the type the loader will load).
asset_id = None;
fetched_handle = None;
// If we couldn't find an appropriate handle, then the asset certainly needs to
// be loaded.
should_load = true;
}
Some((handle, result_should_load)) => {
// `get_or_create_path_handle_internal` always returns Strong variant, so this
// is safe.
asset_id = Some((&handle).try_into().unwrap());
fetched_handle = Some(handle);
should_load = result_should_load;
}
}
}
// Verify that the expected type matches the loader's type.
if let Some(asset_type_id) = asset_id.map(|id| id.type_id) {
// If we are loading a subasset, then the subasset's type almost certainly doesn't match
// the loader's type - and that's ok.
if path.label().is_none() && asset_type_id != loader.asset_type_id() {
error!(
"Expected {:?}, got {:?}",
asset_type_id,
loader.asset_type_id()
);
return Err(AssetLoadError::RequestedHandleTypeMismatch {
path: path.into_owned(),
requested: asset_type_id,
actual_asset_name: loader.asset_type_name(),
loader_name: loader.type_path(),
});
}
}
// Bail out earlier if we don't need to load the asset.
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/server/loaders.rs | crates/bevy_asset/src/server/loaders.rs | use crate::{
loader::{AssetLoader, ErasedAssetLoader},
path::AssetPath,
};
use alloc::{boxed::Box, sync::Arc, vec::Vec};
use async_broadcast::RecvError;
use bevy_platform::collections::HashMap;
use bevy_tasks::IoTaskPool;
use bevy_utils::TypeIdMap;
use core::any::TypeId;
use thiserror::Error;
use tracing::warn;
#[derive(Default)]
pub(crate) struct AssetLoaders {
loaders: Vec<MaybeAssetLoader>,
type_id_to_loaders: TypeIdMap<Vec<usize>>,
extension_to_loaders: HashMap<Box<str>, Vec<usize>>,
type_path_to_loader: HashMap<&'static str, usize>,
type_path_to_preregistered_loader: HashMap<&'static str, usize>,
}
impl AssetLoaders {
/// Get the [`AssetLoader`] stored at the specific index
fn get_by_index(&self, index: usize) -> Option<MaybeAssetLoader> {
self.loaders.get(index).cloned()
}
/// Registers a new [`AssetLoader`]. [`AssetLoader`]s must be registered before they can be used.
pub(crate) fn push<L: AssetLoader>(&mut self, loader: L) {
let type_path = L::type_path();
// TODO: Allow using the short path of loaders.
let loader_asset_type = TypeId::of::<L::Asset>();
let loader_asset_type_name = core::any::type_name::<L::Asset>();
let loader = Arc::new(loader);
let (loader_index, is_new) =
if let Some(index) = self.type_path_to_preregistered_loader.remove(type_path) {
(index, false)
} else {
(self.loaders.len(), true)
};
if is_new {
let existing_loaders_for_type_id = self.type_id_to_loaders.get(&loader_asset_type);
let mut duplicate_extensions = Vec::new();
for extension in AssetLoader::extensions(&*loader) {
let list = self
.extension_to_loaders
.entry((*extension).into())
.or_default();
if !list.is_empty()
&& let Some(existing_loaders_for_type_id) = existing_loaders_for_type_id
&& list
.iter()
.any(|index| existing_loaders_for_type_id.contains(index))
{
duplicate_extensions.push(extension);
}
list.push(loader_index);
}
if !duplicate_extensions.is_empty() {
warn!("Duplicate AssetLoader registered for Asset type `{loader_asset_type_name}` with extensions `{duplicate_extensions:?}`. \
Loader must be specified in a .meta file in order to load assets of this type with these extensions.");
}
self.type_path_to_loader.insert(type_path, loader_index);
self.type_id_to_loaders
.entry(loader_asset_type)
.or_default()
.push(loader_index);
self.loaders.push(MaybeAssetLoader::Ready(loader));
} else {
let maybe_loader = core::mem::replace(
self.loaders.get_mut(loader_index).unwrap(),
MaybeAssetLoader::Ready(loader.clone()),
);
match maybe_loader {
MaybeAssetLoader::Ready(_) => unreachable!(),
MaybeAssetLoader::Pending { sender, .. } => {
IoTaskPool::get()
.spawn(async move {
let _ = sender.broadcast(loader).await;
})
.detach();
}
}
}
}
/// Pre-register an [`AssetLoader`] that will later be added.
///
/// Assets loaded with matching extensions will be blocked until the
/// real loader is added.
pub(crate) fn reserve<L: AssetLoader>(&mut self, extensions: &[&str]) {
let loader_asset_type = TypeId::of::<L::Asset>();
let loader_asset_type_name = core::any::type_name::<L::Asset>();
let type_path = L::type_path();
// TODO: Allow using the short path of loaders.
let loader_index = self.loaders.len();
self.type_path_to_preregistered_loader
.insert(type_path, loader_index);
self.type_path_to_loader.insert(type_path, loader_index);
let existing_loaders_for_type_id = self.type_id_to_loaders.get(&loader_asset_type);
let mut duplicate_extensions = Vec::new();
for extension in extensions {
let list = self
.extension_to_loaders
.entry((*extension).into())
.or_default();
if !list.is_empty()
&& let Some(existing_loaders_for_type_id) = existing_loaders_for_type_id
&& list
.iter()
.any(|index| existing_loaders_for_type_id.contains(index))
{
duplicate_extensions.push(extension);
}
list.push(loader_index);
}
if !duplicate_extensions.is_empty() {
warn!("Duplicate AssetLoader preregistered for Asset type `{loader_asset_type_name}` with extensions `{duplicate_extensions:?}`. \
Loader must be specified in a .meta file in order to load assets of this type with these extensions.");
}
self.type_id_to_loaders
.entry(loader_asset_type)
.or_default()
.push(loader_index);
let (mut sender, receiver) = async_broadcast::broadcast(1);
sender.set_overflow(true);
self.loaders
.push(MaybeAssetLoader::Pending { sender, receiver });
}
/// Get the [`AssetLoader`] by name
pub(crate) fn get_by_name(&self, name: &str) -> Option<MaybeAssetLoader> {
let index = self.type_path_to_loader.get(name).copied()?;
self.get_by_index(index)
}
/// Find an [`AssetLoader`] based on provided search criteria
pub(crate) fn find(
&self,
type_name: Option<&str>,
asset_type_id: Option<TypeId>,
extension: Option<&str>,
asset_path: Option<&AssetPath<'_>>,
) -> Option<MaybeAssetLoader> {
// If provided the type name of the loader, return that immediately
if let Some(type_name) = type_name {
return self.get_by_name(type_name);
}
// The presence of a label will affect loader choice
let label = asset_path.as_ref().and_then(|path| path.label());
// Try by asset type
let candidates = if let Some(type_id) = asset_type_id {
if label.is_none() {
Some(self.type_id_to_loaders.get(&type_id)?)
} else {
None
}
} else {
None
};
if let Some(candidates) = candidates {
if candidates.is_empty() {
return None;
} else if candidates.len() == 1 {
let index = candidates.first().copied().unwrap();
return self.get_by_index(index);
}
}
// Asset type is insufficient, use extension information
let try_extension = |extension| {
if let Some(indices) = self.extension_to_loaders.get(extension) {
if let Some(candidates) = candidates {
if candidates.is_empty() {
indices.last()
} else {
indices
.iter()
.rev()
.find(|index| candidates.contains(index))
}
} else {
indices.last()
}
} else {
None
}
};
// Try the provided extension
if let Some(extension) = extension
&& let Some(&index) = try_extension(extension)
{
return self.get_by_index(index);
}
// Try extracting the extension from the path
if let Some(full_extension) = asset_path.and_then(AssetPath::get_full_extension) {
if let Some(&index) = try_extension(full_extension.as_str()) {
return self.get_by_index(index);
}
// Try secondary extensions from the path
for extension in AssetPath::iter_secondary_extensions(&full_extension) {
if let Some(&index) = try_extension(extension) {
return self.get_by_index(index);
}
}
}
// Fallback if no resolution step was conclusive
match candidates?
.last()
.copied()
.and_then(|index| self.get_by_index(index))
{
Some(loader) => {
warn!(
"Multiple AssetLoaders found for Asset: {:?}; Path: {:?}; Extension: {:?}",
asset_type_id, asset_path, extension
);
Some(loader)
}
None => {
warn!(
"No AssetLoader found for Asset: {:?}; Path: {:?}; Extension: {:?}",
asset_type_id, asset_path, extension
);
None
}
}
}
/// Get the [`AssetLoader`] for a given asset type
pub(crate) fn get_by_type(&self, type_id: TypeId) -> Option<MaybeAssetLoader> {
let index = self.type_id_to_loaders.get(&type_id)?.last().copied()?;
self.get_by_index(index)
}
/// Get the [`AssetLoader`] for a given extension
pub(crate) fn get_by_extension(&self, extension: &str) -> Option<MaybeAssetLoader> {
let index = self.extension_to_loaders.get(extension)?.last().copied()?;
self.get_by_index(index)
}
/// Get the [`AssetLoader`] for a given path
pub(crate) fn get_by_path(&self, path: &AssetPath<'_>) -> Option<MaybeAssetLoader> {
let extension = path.get_full_extension()?;
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))?;
Some(result)
}
}
#[derive(Error, Debug, Clone)]
pub(crate) enum GetLoaderError {
#[error(transparent)]
CouldNotResolve(#[from] RecvError),
}
#[derive(Clone)]
pub(crate) enum MaybeAssetLoader {
Ready(Arc<dyn ErasedAssetLoader>),
Pending {
sender: async_broadcast::Sender<Arc<dyn ErasedAssetLoader>>,
receiver: async_broadcast::Receiver<Arc<dyn ErasedAssetLoader>>,
},
}
impl MaybeAssetLoader {
pub(crate) async fn get(self) -> Result<Arc<dyn ErasedAssetLoader>, GetLoaderError> {
match self {
MaybeAssetLoader::Ready(loader) => Ok(loader),
MaybeAssetLoader::Pending { mut receiver, .. } => Ok(receiver.recv().await?),
}
}
}
#[cfg(test)]
mod tests {
use alloc::{format, string::String};
use core::marker::PhantomData;
use std::{
path::Path,
sync::mpsc::{channel, Receiver, Sender},
};
use bevy_reflect::TypePath;
use bevy_tasks::block_on;
use crate::Asset;
use super::*;
#[derive(Asset, TypePath, Debug)]
struct A;
#[derive(Asset, TypePath, Debug)]
struct B;
#[derive(Asset, TypePath, Debug)]
struct C;
#[derive(TypePath)]
struct Loader<A: Asset, const N: usize, const E: usize> {
sender: Sender<()>,
_phantom: PhantomData<A>,
}
impl<T: Asset, const N: usize, const E: usize> Loader<T, N, E> {
fn new() -> (Self, Receiver<()>) {
let (tx, rx) = channel();
let loader = Self {
sender: tx,
_phantom: PhantomData,
};
(loader, rx)
}
}
impl<T: Asset, const N: usize, const E: usize> AssetLoader for Loader<T, N, E> {
type Asset = T;
type Settings = ();
type Error = String;
async fn load(
&self,
_: &mut dyn crate::io::Reader,
_: &Self::Settings,
_: &mut crate::LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
self.sender.send(()).unwrap();
Err(format!(
"Loaded {}:{}",
core::any::type_name::<Self::Asset>(),
N
))
}
fn extensions(&self) -> &[&str] {
self.sender.send(()).unwrap();
match E {
1 => &["a"],
2 => &["b"],
3 => &["c"],
4 => &["d"],
_ => &[],
}
}
}
/// Basic framework for creating, storing, loading, and checking an [`AssetLoader`] inside an [`AssetLoaders`]
#[test]
fn basic() {
let mut loaders = AssetLoaders::default();
let (loader, rx) = Loader::<A, 1, 0>::new();
assert!(rx.try_recv().is_err());
loaders.push(loader);
assert!(rx.try_recv().is_ok());
assert!(rx.try_recv().is_err());
let loader = block_on(
loaders
.get_by_name(<Loader<A, 1, 0> as TypePath>::type_path())
.unwrap()
.get(),
)
.unwrap();
loader.extensions();
assert!(rx.try_recv().is_ok());
assert!(rx.try_recv().is_err());
}
/// Ensure that if multiple loaders have different types but no extensions, they can be found
#[test]
fn type_resolution() {
let mut loaders = AssetLoaders::default();
let (loader_a1, rx_a1) = Loader::<A, 1, 0>::new();
let (loader_b1, rx_b1) = Loader::<B, 1, 0>::new();
let (loader_c1, rx_c1) = Loader::<C, 1, 0>::new();
loaders.push(loader_a1);
loaders.push(loader_b1);
loaders.push(loader_c1);
assert!(rx_a1.try_recv().is_ok());
assert!(rx_b1.try_recv().is_ok());
assert!(rx_c1.try_recv().is_ok());
let loader = block_on(loaders.get_by_type(TypeId::of::<A>()).unwrap().get()).unwrap();
loader.extensions();
assert!(rx_a1.try_recv().is_ok());
assert!(rx_b1.try_recv().is_err());
assert!(rx_c1.try_recv().is_err());
let loader = block_on(loaders.get_by_type(TypeId::of::<B>()).unwrap().get()).unwrap();
loader.extensions();
assert!(rx_a1.try_recv().is_err());
assert!(rx_b1.try_recv().is_ok());
assert!(rx_c1.try_recv().is_err());
let loader = block_on(loaders.get_by_type(TypeId::of::<C>()).unwrap().get()).unwrap();
loader.extensions();
assert!(rx_a1.try_recv().is_err());
assert!(rx_b1.try_recv().is_err());
assert!(rx_c1.try_recv().is_ok());
}
/// Ensure that the last loader added is selected
#[test]
fn type_resolution_shadow() {
let mut loaders = AssetLoaders::default();
let (loader_a1, rx_a1) = Loader::<A, 1, 0>::new();
let (loader_a2, rx_a2) = Loader::<A, 2, 0>::new();
let (loader_a3, rx_a3) = Loader::<A, 3, 0>::new();
loaders.push(loader_a1);
loaders.push(loader_a2);
loaders.push(loader_a3);
assert!(rx_a1.try_recv().is_ok());
assert!(rx_a2.try_recv().is_ok());
assert!(rx_a3.try_recv().is_ok());
let loader = block_on(loaders.get_by_type(TypeId::of::<A>()).unwrap().get()).unwrap();
loader.extensions();
assert!(rx_a1.try_recv().is_err());
assert!(rx_a2.try_recv().is_err());
assert!(rx_a3.try_recv().is_ok());
}
/// Ensure that if multiple loaders have like types but differing extensions, they can be found
#[test]
fn extension_resolution() {
let mut loaders = AssetLoaders::default();
let (loader_a1, rx_a1) = Loader::<A, 1, 1>::new();
let (loader_b1, rx_b1) = Loader::<A, 1, 2>::new();
let (loader_c1, rx_c1) = Loader::<A, 1, 3>::new();
loaders.push(loader_a1);
loaders.push(loader_b1);
loaders.push(loader_c1);
assert!(rx_a1.try_recv().is_ok());
assert!(rx_b1.try_recv().is_ok());
assert!(rx_c1.try_recv().is_ok());
let loader = block_on(loaders.get_by_extension("a").unwrap().get()).unwrap();
loader.extensions();
assert!(rx_a1.try_recv().is_ok());
assert!(rx_b1.try_recv().is_err());
assert!(rx_c1.try_recv().is_err());
let loader = block_on(loaders.get_by_extension("b").unwrap().get()).unwrap();
loader.extensions();
assert!(rx_a1.try_recv().is_err());
assert!(rx_b1.try_recv().is_ok());
assert!(rx_c1.try_recv().is_err());
let loader = block_on(loaders.get_by_extension("c").unwrap().get()).unwrap();
loader.extensions();
assert!(rx_a1.try_recv().is_err());
assert!(rx_b1.try_recv().is_err());
assert!(rx_c1.try_recv().is_ok());
}
/// Ensure that if multiple loaders have like types but differing extensions, they can be found
#[test]
fn path_resolution() {
let mut loaders = AssetLoaders::default();
let (loader_a1, rx_a1) = Loader::<A, 1, 1>::new();
let (loader_b1, rx_b1) = Loader::<A, 1, 2>::new();
let (loader_c1, rx_c1) = Loader::<A, 1, 3>::new();
loaders.push(loader_a1);
loaders.push(loader_b1);
loaders.push(loader_c1);
assert!(rx_a1.try_recv().is_ok());
assert!(rx_b1.try_recv().is_ok());
assert!(rx_c1.try_recv().is_ok());
let path = AssetPath::from_path(Path::new("asset.a"));
let loader = block_on(loaders.get_by_path(&path).unwrap().get()).unwrap();
loader.extensions();
assert!(rx_a1.try_recv().is_ok());
assert!(rx_b1.try_recv().is_err());
assert!(rx_c1.try_recv().is_err());
let path = AssetPath::from_path(Path::new("asset.b"));
let loader = block_on(loaders.get_by_path(&path).unwrap().get()).unwrap();
loader.extensions();
assert!(rx_a1.try_recv().is_err());
assert!(rx_b1.try_recv().is_ok());
assert!(rx_c1.try_recv().is_err());
let path = AssetPath::from_path(Path::new("asset.c"));
let loader = block_on(loaders.get_by_path(&path).unwrap().get()).unwrap();
loader.extensions();
assert!(rx_a1.try_recv().is_err());
assert!(rx_b1.try_recv().is_err());
assert!(rx_c1.try_recv().is_ok());
}
/// Full resolution algorithm
#[test]
fn total_resolution() {
let mut loaders = AssetLoaders::default();
let (loader_a1_a, rx_a1_a) = Loader::<A, 1, 1>::new();
let (loader_b1_b, rx_b1_b) = Loader::<B, 1, 2>::new();
let (loader_c1_a, rx_c1_a) = Loader::<C, 1, 1>::new();
let (loader_c1_b, rx_c1_b) = Loader::<C, 1, 2>::new();
let (loader_c1_c, rx_c1_c) = Loader::<C, 1, 3>::new();
loaders.push(loader_a1_a);
loaders.push(loader_b1_b);
loaders.push(loader_c1_a);
loaders.push(loader_c1_b);
loaders.push(loader_c1_c);
assert!(rx_a1_a.try_recv().is_ok());
assert!(rx_b1_b.try_recv().is_ok());
assert!(rx_c1_a.try_recv().is_ok());
assert!(rx_c1_b.try_recv().is_ok());
assert!(rx_c1_c.try_recv().is_ok());
// Type and Extension agree
let loader = block_on(
loaders
.find(
None,
Some(TypeId::of::<A>()),
None,
Some(&AssetPath::from_path(Path::new("asset.a"))),
)
.unwrap()
.get(),
)
.unwrap();
loader.extensions();
assert!(rx_a1_a.try_recv().is_ok());
assert!(rx_b1_b.try_recv().is_err());
assert!(rx_c1_a.try_recv().is_err());
assert!(rx_c1_b.try_recv().is_err());
assert!(rx_c1_c.try_recv().is_err());
let loader = block_on(
loaders
.find(
None,
Some(TypeId::of::<B>()),
None,
Some(&AssetPath::from_path(Path::new("asset.b"))),
)
.unwrap()
.get(),
)
.unwrap();
loader.extensions();
assert!(rx_a1_a.try_recv().is_err());
assert!(rx_b1_b.try_recv().is_ok());
assert!(rx_c1_a.try_recv().is_err());
assert!(rx_c1_b.try_recv().is_err());
assert!(rx_c1_c.try_recv().is_err());
let loader = block_on(
loaders
.find(
None,
Some(TypeId::of::<C>()),
None,
Some(&AssetPath::from_path(Path::new("asset.c"))),
)
.unwrap()
.get(),
)
.unwrap();
loader.extensions();
assert!(rx_a1_a.try_recv().is_err());
assert!(rx_b1_b.try_recv().is_err());
assert!(rx_c1_a.try_recv().is_err());
assert!(rx_c1_b.try_recv().is_err());
assert!(rx_c1_c.try_recv().is_ok());
// Type should override Extension
let loader = block_on(
loaders
.find(
None,
Some(TypeId::of::<C>()),
None,
Some(&AssetPath::from_path(Path::new("asset.a"))),
)
.unwrap()
.get(),
)
.unwrap();
loader.extensions();
assert!(rx_a1_a.try_recv().is_err());
assert!(rx_b1_b.try_recv().is_err());
assert!(rx_c1_a.try_recv().is_ok());
assert!(rx_c1_b.try_recv().is_err());
assert!(rx_c1_c.try_recv().is_err());
let loader = block_on(
loaders
.find(
None,
Some(TypeId::of::<C>()),
None,
Some(&AssetPath::from_path(Path::new("asset.b"))),
)
.unwrap()
.get(),
)
.unwrap();
loader.extensions();
assert!(rx_a1_a.try_recv().is_err());
assert!(rx_b1_b.try_recv().is_err());
assert!(rx_c1_a.try_recv().is_err());
assert!(rx_c1_b.try_recv().is_ok());
assert!(rx_c1_c.try_recv().is_err());
// Type should override bad / missing extension
let loader = block_on(
loaders
.find(
None,
Some(TypeId::of::<A>()),
None,
Some(&AssetPath::from_path(Path::new("asset.x"))),
)
.unwrap()
.get(),
)
.unwrap();
loader.extensions();
assert!(rx_a1_a.try_recv().is_ok());
assert!(rx_b1_b.try_recv().is_err());
assert!(rx_c1_a.try_recv().is_err());
assert!(rx_c1_b.try_recv().is_err());
assert!(rx_c1_c.try_recv().is_err());
let loader = block_on(
loaders
.find(
None,
Some(TypeId::of::<A>()),
None,
Some(&AssetPath::from_path(Path::new("asset"))),
)
.unwrap()
.get(),
)
.unwrap();
loader.extensions();
assert!(rx_a1_a.try_recv().is_ok());
assert!(rx_b1_b.try_recv().is_err());
assert!(rx_c1_a.try_recv().is_err());
assert!(rx_c1_b.try_recv().is_err());
assert!(rx_c1_c.try_recv().is_err());
}
/// Ensure that if there is a complete ambiguity in [`AssetLoader`] to use, prefer most recently registered by asset type.
#[test]
fn ambiguity_resolution() {
let mut loaders = AssetLoaders::default();
let (loader_a1_a, rx_a1_a) = Loader::<A, 1, 1>::new();
let (loader_a2_a, rx_a2_a) = Loader::<A, 2, 1>::new();
let (loader_a3_a, rx_a3_a) = Loader::<A, 3, 1>::new();
loaders.push(loader_a1_a);
loaders.push(loader_a2_a);
loaders.push(loader_a3_a);
assert!(rx_a1_a.try_recv().is_ok());
assert!(rx_a2_a.try_recv().is_ok());
assert!(rx_a3_a.try_recv().is_ok());
let loader = block_on(
loaders
.find(
None,
Some(TypeId::of::<A>()),
None,
Some(&AssetPath::from_path(Path::new("asset.a"))),
)
.unwrap()
.get(),
)
.unwrap();
loader.extensions();
assert!(rx_a1_a.try_recv().is_err());
assert!(rx_a2_a.try_recv().is_err());
assert!(rx_a3_a.try_recv().is_ok());
let loader = block_on(
loaders
.find(
None,
Some(TypeId::of::<A>()),
None,
Some(&AssetPath::from_path(Path::new("asset.x"))),
)
.unwrap()
.get(),
)
.unwrap();
loader.extensions();
assert!(rx_a1_a.try_recv().is_err());
assert!(rx_a2_a.try_recv().is_err());
assert!(rx_a3_a.try_recv().is_ok());
let loader = block_on(
loaders
.find(
None,
Some(TypeId::of::<A>()),
None,
Some(&AssetPath::from_path(Path::new("asset"))),
)
.unwrap()
.get(),
)
.unwrap();
loader.extensions();
assert!(rx_a1_a.try_recv().is_err());
assert!(rx_a2_a.try_recv().is_err());
assert!(rx_a3_a.try_recv().is_ok());
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/io/source.rs | crates/bevy_asset/src/io/source.rs | use crate::{
io::{processor_gated::ProcessorGatedReader, AssetSourceEvent, AssetWatcher},
processor::ProcessingState,
};
use alloc::{
boxed::Box,
string::{String, ToString},
sync::Arc,
};
use atomicow::CowArc;
use bevy_ecs::resource::Resource;
use bevy_platform::collections::HashMap;
use core::{fmt::Display, hash::Hash, time::Duration};
use thiserror::Error;
use tracing::warn;
use super::{ErasedAssetReader, ErasedAssetWriter};
/// A reference to an "asset source", which maps to an [`AssetReader`](crate::io::AssetReader) and/or [`AssetWriter`](crate::io::AssetWriter).
///
/// * [`AssetSourceId::Default`] corresponds to "default asset paths" that don't specify a source: `/path/to/asset.png`
/// * [`AssetSourceId::Name`] corresponds to asset paths that _do_ specify a source: `remote://path/to/asset.png`, where `remote` is the name.
#[derive(Default, Clone, Debug, Eq)]
pub enum AssetSourceId<'a> {
/// The default asset source.
#[default]
Default,
/// A non-default named asset source.
Name(CowArc<'a, str>),
}
impl<'a> Display for AssetSourceId<'a> {
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})"),
}
}
}
impl<'a> AssetSourceId<'a> {
/// Creates a new [`AssetSourceId`]
pub fn new(source: Option<impl Into<CowArc<'a, str>>>) -> AssetSourceId<'a> {
match source {
Some(source) => AssetSourceId::Name(source.into()),
None => AssetSourceId::Default,
}
}
/// Returns [`None`] if this is [`AssetSourceId::Default`] and [`Some`] containing the
/// name if this is [`AssetSourceId::Name`].
pub fn as_str(&self) -> Option<&str> {
match self {
AssetSourceId::Default => None,
AssetSourceId::Name(v) => Some(v),
}
}
/// If this is not already an owned / static id, create one. Otherwise, it will return itself (with a static lifetime).
pub fn into_owned(self) -> AssetSourceId<'static> {
match self {
AssetSourceId::Default => AssetSourceId::Default,
AssetSourceId::Name(v) => AssetSourceId::Name(v.into_owned()),
}
}
/// Clones into an owned [`AssetSourceId<'static>`].
/// This is equivalent to `.clone().into_owned()`.
#[inline]
pub fn clone_owned(&self) -> AssetSourceId<'static> {
self.clone().into_owned()
}
}
// This is only implemented for static lifetimes to ensure `Path::clone` does not allocate
// by ensuring that this is stored as a `CowArc::Static`.
// Please read https://github.com/bevyengine/bevy/issues/19844 before changing this!
impl From<&'static str> for AssetSourceId<'static> {
fn from(value: &'static str) -> Self {
AssetSourceId::Name(value.into())
}
}
impl<'a, 'b> From<&'a AssetSourceId<'b>> for AssetSourceId<'b> {
fn from(value: &'a AssetSourceId<'b>) -> Self {
value.clone()
}
}
impl From<Option<&'static str>> for AssetSourceId<'static> {
fn from(value: Option<&'static str>) -> Self {
match value {
Some(value) => AssetSourceId::Name(value.into()),
None => AssetSourceId::Default,
}
}
}
impl From<String> for AssetSourceId<'static> {
fn from(value: String) -> Self {
AssetSourceId::Name(value.into())
}
}
impl<'a> Hash for AssetSourceId<'a> {
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.as_str().hash(state);
}
}
impl<'a> PartialEq for AssetSourceId<'a> {
fn eq(&self, other: &Self) -> bool {
self.as_str().eq(&other.as_str())
}
}
/// Metadata about an "asset source", such as how to construct the [`AssetReader`](crate::io::AssetReader) and [`AssetWriter`](crate::io::AssetWriter) for the source,
/// and whether or not the source is processed.
pub struct AssetSourceBuilder {
/// The [`ErasedAssetReader`] to use on the unprocessed asset.
pub reader: Box<dyn FnMut() -> Box<dyn ErasedAssetReader> + Send + Sync>,
/// The [`ErasedAssetWriter`] to use on the unprocessed asset.
pub writer: Option<Box<dyn FnMut(bool) -> Option<Box<dyn ErasedAssetWriter>> + Send + Sync>>,
/// The [`AssetWatcher`] to use for unprocessed assets, if any.
pub watcher: Option<
Box<
dyn FnMut(async_channel::Sender<AssetSourceEvent>) -> Option<Box<dyn AssetWatcher>>
+ Send
+ Sync,
>,
>,
/// The [`ErasedAssetReader`] to use for processed assets.
pub processed_reader: Option<Box<dyn FnMut() -> Box<dyn ErasedAssetReader> + Send + Sync>>,
/// The [`ErasedAssetWriter`] to use for processed assets.
pub processed_writer:
Option<Box<dyn FnMut(bool) -> Option<Box<dyn ErasedAssetWriter>> + Send + Sync>>,
/// The [`AssetWatcher`] to use for processed assets, if any.
pub processed_watcher: Option<
Box<
dyn FnMut(async_channel::Sender<AssetSourceEvent>) -> Option<Box<dyn AssetWatcher>>
+ Send
+ Sync,
>,
>,
/// The warning message to display when watching an unprocessed asset fails.
pub watch_warning: Option<&'static str>,
/// The warning message to display when watching a processed asset fails.
pub processed_watch_warning: Option<&'static str>,
}
impl AssetSourceBuilder {
/// Creates a new builder, starting with the provided reader.
pub fn new(
reader: impl FnMut() -> Box<dyn ErasedAssetReader> + Send + Sync + 'static,
) -> AssetSourceBuilder {
Self {
reader: Box::new(reader),
writer: None,
watcher: None,
processed_reader: None,
processed_writer: None,
processed_watcher: None,
watch_warning: None,
processed_watch_warning: None,
}
}
/// Builds a new [`AssetSource`] with the given `id`. If `watch` is true, the unprocessed source will watch for changes.
/// If `watch_processed` is true, the processed source will watch for changes.
pub fn build(
&mut self,
id: AssetSourceId<'static>,
watch: bool,
watch_processed: bool,
) -> AssetSource {
let reader = self.reader.as_mut()();
let writer = self.writer.as_mut().and_then(|w| w(false));
let processed_writer = self.processed_writer.as_mut().and_then(|w| w(true));
let mut source = AssetSource {
id: id.clone(),
reader,
writer,
processed_reader: self
.processed_reader
.as_mut()
.map(|r| r())
.map(Into::<Arc<_>>::into),
ungated_processed_reader: None,
processed_writer,
event_receiver: None,
watcher: None,
processed_event_receiver: None,
processed_watcher: None,
};
if watch {
let (sender, receiver) = async_channel::unbounded();
match self.watcher.as_mut().and_then(|w| w(sender)) {
Some(w) => {
source.watcher = Some(w);
source.event_receiver = Some(receiver);
}
None => {
if let Some(warning) = self.watch_warning {
warn!("{id} does not have an AssetWatcher configured. {warning}");
}
}
}
}
if watch_processed {
let (sender, receiver) = async_channel::unbounded();
match self.processed_watcher.as_mut().and_then(|w| w(sender)) {
Some(w) => {
source.processed_watcher = Some(w);
source.processed_event_receiver = Some(receiver);
}
None => {
if let Some(warning) = self.processed_watch_warning {
warn!("{id} does not have a processed AssetWatcher configured. {warning}");
}
}
}
}
source
}
/// Will use the given `reader` function to construct unprocessed [`AssetReader`](crate::io::AssetReader) instances.
pub fn with_reader(
mut self,
reader: impl FnMut() -> Box<dyn ErasedAssetReader> + Send + Sync + 'static,
) -> Self {
self.reader = Box::new(reader);
self
}
/// Will use the given `writer` function to construct unprocessed [`AssetWriter`](crate::io::AssetWriter) instances.
pub fn with_writer(
mut self,
writer: impl FnMut(bool) -> Option<Box<dyn ErasedAssetWriter>> + Send + Sync + 'static,
) -> Self {
self.writer = Some(Box::new(writer));
self
}
/// Will use the given `watcher` function to construct unprocessed [`AssetWatcher`] instances.
pub fn with_watcher(
mut self,
watcher: impl FnMut(async_channel::Sender<AssetSourceEvent>) -> Option<Box<dyn AssetWatcher>>
+ Send
+ Sync
+ 'static,
) -> Self {
self.watcher = Some(Box::new(watcher));
self
}
/// Will use the given `reader` function to construct processed [`AssetReader`](crate::io::AssetReader) instances.
pub fn with_processed_reader(
mut self,
reader: impl FnMut() -> Box<dyn ErasedAssetReader> + Send + Sync + 'static,
) -> Self {
self.processed_reader = Some(Box::new(reader));
self
}
/// Will use the given `writer` function to construct processed [`AssetWriter`](crate::io::AssetWriter) instances.
pub fn with_processed_writer(
mut self,
writer: impl FnMut(bool) -> Option<Box<dyn ErasedAssetWriter>> + Send + Sync + 'static,
) -> Self {
self.processed_writer = Some(Box::new(writer));
self
}
/// Will use the given `watcher` function to construct processed [`AssetWatcher`] instances.
pub fn with_processed_watcher(
mut self,
watcher: impl FnMut(async_channel::Sender<AssetSourceEvent>) -> Option<Box<dyn AssetWatcher>>
+ Send
+ Sync
+ 'static,
) -> Self {
self.processed_watcher = Some(Box::new(watcher));
self
}
/// Enables a warning for the unprocessed source watcher, which will print when watching is enabled and the unprocessed source doesn't have a watcher.
pub fn with_watch_warning(mut self, warning: &'static str) -> Self {
self.watch_warning = Some(warning);
self
}
/// Enables a warning for the processed source watcher, which will print when watching is enabled and the processed source doesn't have a watcher.
pub fn with_processed_watch_warning(mut self, warning: &'static str) -> Self {
self.processed_watch_warning = Some(warning);
self
}
/// Returns a builder containing the "platform default source" for the given `path` and `processed_path`.
/// For most platforms, this will use [`FileAssetReader`](crate::io::file::FileAssetReader) / [`FileAssetWriter`](crate::io::file::FileAssetWriter),
/// but some platforms (such as Android) have their own default readers / writers / watchers.
pub fn platform_default(path: &str, processed_path: Option<&str>) -> Self {
let default = Self::new(AssetSource::get_default_reader(path.to_string()))
.with_writer(AssetSource::get_default_writer(path.to_string()))
.with_watcher(AssetSource::get_default_watcher(
path.to_string(),
Duration::from_millis(300),
))
.with_watch_warning(AssetSource::get_default_watch_warning());
if let Some(processed_path) = processed_path {
default
.with_processed_reader(AssetSource::get_default_reader(processed_path.to_string()))
.with_processed_writer(AssetSource::get_default_writer(processed_path.to_string()))
.with_processed_watcher(AssetSource::get_default_watcher(
processed_path.to_string(),
Duration::from_millis(300),
))
.with_processed_watch_warning(AssetSource::get_default_watch_warning())
} else {
default
}
}
}
/// A [`Resource`] that hold (repeatable) functions capable of producing new [`AssetReader`](crate::io::AssetReader) and [`AssetWriter`](crate::io::AssetWriter) instances
/// for a given asset source.
#[derive(Resource, Default)]
pub struct AssetSourceBuilders {
sources: HashMap<CowArc<'static, str>, AssetSourceBuilder>,
default: Option<AssetSourceBuilder>,
}
impl AssetSourceBuilders {
/// Inserts a new builder with the given `id`
pub fn insert(&mut self, id: impl Into<AssetSourceId<'static>>, source: AssetSourceBuilder) {
match id.into() {
AssetSourceId::Default => {
self.default = Some(source);
}
AssetSourceId::Name(name) => {
self.sources.insert(name, source);
}
}
}
/// Gets a mutable builder with the given `id`, if it exists.
pub fn get_mut<'a, 'b>(
&'a mut self,
id: impl Into<AssetSourceId<'b>>,
) -> Option<&'a mut AssetSourceBuilder> {
match id.into() {
AssetSourceId::Default => self.default.as_mut(),
AssetSourceId::Name(name) => self.sources.get_mut(&name.into_owned()),
}
}
/// Builds a new [`AssetSources`] collection. If `watch` is true, the unprocessed sources will watch for changes.
/// If `watch_processed` is true, the processed sources will watch for changes.
pub fn build_sources(&mut self, watch: bool, watch_processed: bool) -> AssetSources {
let mut sources = <HashMap<_, _>>::default();
for (id, source) in &mut self.sources {
let source = source.build(
AssetSourceId::Name(id.clone_owned()),
watch,
watch_processed,
);
sources.insert(id.clone_owned(), source);
}
AssetSources {
sources,
default: self
.default
.as_mut()
.map(|p| p.build(AssetSourceId::Default, watch, watch_processed))
.expect(MISSING_DEFAULT_SOURCE),
}
}
/// Initializes the default [`AssetSourceBuilder`] if it has not already been set.
pub fn init_default_source(&mut self, path: &str, processed_path: Option<&str>) {
self.default
.get_or_insert_with(|| AssetSourceBuilder::platform_default(path, processed_path));
}
}
/// A collection of unprocessed and processed [`AssetReader`](crate::io::AssetReader), [`AssetWriter`](crate::io::AssetWriter), and [`AssetWatcher`] instances
/// for a specific asset source, identified by an [`AssetSourceId`].
pub struct AssetSource {
id: AssetSourceId<'static>,
reader: Box<dyn ErasedAssetReader>,
writer: Option<Box<dyn ErasedAssetWriter>>,
processed_reader: Option<Arc<dyn ErasedAssetReader>>,
/// The ungated version of `processed_reader`.
///
/// This allows the processor to read all the processed assets to initialize itself without
/// being gated on itself (causing a deadlock).
ungated_processed_reader: Option<Arc<dyn ErasedAssetReader>>,
processed_writer: Option<Box<dyn ErasedAssetWriter>>,
watcher: Option<Box<dyn AssetWatcher>>,
processed_watcher: Option<Box<dyn AssetWatcher>>,
event_receiver: Option<async_channel::Receiver<AssetSourceEvent>>,
processed_event_receiver: Option<async_channel::Receiver<AssetSourceEvent>>,
}
impl AssetSource {
/// Returns this source's id.
#[inline]
pub fn id(&self) -> AssetSourceId<'static> {
self.id.clone()
}
/// Return's this source's unprocessed [`AssetReader`](crate::io::AssetReader).
#[inline]
pub fn reader(&self) -> &dyn ErasedAssetReader {
&*self.reader
}
/// Return's this source's unprocessed [`AssetWriter`](crate::io::AssetWriter), if it exists.
#[inline]
pub fn writer(&self) -> Result<&dyn ErasedAssetWriter, MissingAssetWriterError> {
self.writer
.as_deref()
.ok_or_else(|| MissingAssetWriterError(self.id.clone_owned()))
}
/// Return's this source's processed [`AssetReader`](crate::io::AssetReader), if it exists.
#[inline]
pub fn processed_reader(
&self,
) -> Result<&dyn ErasedAssetReader, MissingProcessedAssetReaderError> {
self.processed_reader
.as_deref()
.ok_or_else(|| MissingProcessedAssetReaderError(self.id.clone_owned()))
}
/// Return's this source's ungated processed [`AssetReader`](crate::io::AssetReader), if it
/// exists.
#[inline]
pub(crate) fn ungated_processed_reader(&self) -> Option<&dyn ErasedAssetReader> {
self.ungated_processed_reader.as_deref()
}
/// Return's this source's processed [`AssetWriter`](crate::io::AssetWriter), if it exists.
#[inline]
pub fn processed_writer(
&self,
) -> Result<&dyn ErasedAssetWriter, MissingProcessedAssetWriterError> {
self.processed_writer
.as_deref()
.ok_or_else(|| MissingProcessedAssetWriterError(self.id.clone_owned()))
}
/// Return's this source's unprocessed event receiver, if the source is currently watching for changes.
#[inline]
pub fn event_receiver(&self) -> Option<&async_channel::Receiver<AssetSourceEvent>> {
self.event_receiver.as_ref()
}
/// Return's this source's processed event receiver, if the source is currently watching for changes.
#[inline]
pub fn processed_event_receiver(&self) -> Option<&async_channel::Receiver<AssetSourceEvent>> {
self.processed_event_receiver.as_ref()
}
/// Returns true if the assets in this source should be processed.
#[inline]
pub fn should_process(&self) -> bool {
self.processed_writer.is_some()
}
/// Returns a builder function for this platform's default [`AssetReader`](crate::io::AssetReader). `path` is the relative path to
/// the asset root.
pub fn get_default_reader(
_path: String,
) -> impl FnMut() -> Box<dyn ErasedAssetReader> + Send + Sync {
move || {
#[cfg(all(not(target_arch = "wasm32"), not(target_os = "android")))]
return Box::new(super::file::FileAssetReader::new(&_path));
#[cfg(target_arch = "wasm32")]
return Box::new(super::wasm::HttpWasmAssetReader::new(&_path));
#[cfg(target_os = "android")]
return Box::new(super::android::AndroidAssetReader);
}
}
/// Returns a builder function for this platform's default [`AssetWriter`](crate::io::AssetWriter). `path` is the relative path to
/// the asset root. This will return [`None`] if this platform does not support writing assets by default.
pub fn get_default_writer(
_path: String,
) -> impl FnMut(bool) -> Option<Box<dyn ErasedAssetWriter>> + Send + Sync {
move |_create_root: bool| {
#[cfg(all(not(target_arch = "wasm32"), not(target_os = "android")))]
return Some(Box::new(super::file::FileAssetWriter::new(
&_path,
_create_root,
)));
#[cfg(any(target_arch = "wasm32", target_os = "android"))]
return None;
}
}
/// Returns the default non-existent [`AssetWatcher`] warning for the current platform.
pub fn get_default_watch_warning() -> &'static str {
#[cfg(target_arch = "wasm32")]
return "Web does not currently support watching assets.";
#[cfg(target_os = "android")]
return "Android does not currently support watching assets.";
#[cfg(all(
not(target_arch = "wasm32"),
not(target_os = "android"),
not(feature = "file_watcher")
))]
return "Consider enabling the `file_watcher` feature.";
#[cfg(all(
not(target_arch = "wasm32"),
not(target_os = "android"),
feature = "file_watcher"
))]
return "Consider adding an \"assets\" directory.";
}
/// Returns a builder function for this platform's default [`AssetWatcher`]. `path` is the relative path to
/// the asset root. This will return [`None`] if this platform does not support watching assets by default.
/// `file_debounce_time` is the amount of time to wait (and debounce duplicate events) before returning an event.
/// Higher durations reduce duplicates but increase the amount of time before a change event is processed. If the
/// duration is set too low, some systems might surface events _before_ their filesystem has the changes.
#[cfg_attr(
any(
not(feature = "file_watcher"),
target_arch = "wasm32",
target_os = "android"
),
expect(
unused_variables,
reason = "The `path` and `file_debounce_wait_time` arguments are unused when on WASM, Android, or if the `file_watcher` feature is disabled."
)
)]
pub fn get_default_watcher(
path: String,
file_debounce_wait_time: Duration,
) -> impl FnMut(async_channel::Sender<AssetSourceEvent>) -> Option<Box<dyn AssetWatcher>> + Send + Sync
{
move |sender: async_channel::Sender<AssetSourceEvent>| {
#[cfg(all(
feature = "file_watcher",
not(target_arch = "wasm32"),
not(target_os = "android")
))]
{
let path = super::file::get_base_path().join(path.clone());
if path.exists() {
Some(Box::new(
super::file::FileWatcher::new(
path.clone(),
sender,
file_debounce_wait_time,
)
.unwrap_or_else(|e| {
panic!("Failed to create file watcher from path {path:?}, {e:?}")
}),
))
} else {
warn!("Skip creating file watcher because path {path:?} does not exist.");
None
}
}
#[cfg(any(
not(feature = "file_watcher"),
target_arch = "wasm32",
target_os = "android"
))]
return None;
}
}
/// This will cause processed [`AssetReader`](crate::io::AssetReader) futures (such as [`AssetReader::read`](crate::io::AssetReader::read)) to wait until
/// the [`AssetProcessor`](crate::AssetProcessor) has finished processing the requested asset.
pub(crate) fn gate_on_processor(&mut self, processing_state: Arc<ProcessingState>) {
if let Some(reader) = self.processed_reader.take() {
self.ungated_processed_reader = Some(reader.clone());
self.processed_reader = Some(Arc::new(ProcessorGatedReader::new(
self.id(),
reader,
processing_state,
)));
}
}
}
/// A collection of [`AssetSource`]s.
pub struct AssetSources {
sources: HashMap<CowArc<'static, str>, AssetSource>,
default: AssetSource,
}
impl AssetSources {
/// Gets the [`AssetSource`] with the given `id`, if it exists.
pub fn get<'a, 'b>(
&'a self,
id: impl Into<AssetSourceId<'b>>,
) -> Result<&'a AssetSource, MissingAssetSourceError> {
match id.into().into_owned() {
AssetSourceId::Default => Ok(&self.default),
AssetSourceId::Name(name) => self
.sources
.get(&name)
.ok_or(MissingAssetSourceError(AssetSourceId::Name(name))),
}
}
/// Iterates all asset sources in the collection (including the default source).
pub fn iter(&self) -> impl Iterator<Item = &AssetSource> {
self.sources.values().chain(Some(&self.default))
}
/// Mutably iterates all asset sources in the collection (including the default source).
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut AssetSource> {
self.sources.values_mut().chain(Some(&mut self.default))
}
/// Iterates all processed asset sources in the collection (including the default source).
pub fn iter_processed(&self) -> impl Iterator<Item = &AssetSource> {
self.iter().filter(|p| p.should_process())
}
/// Mutably iterates all processed asset sources in the collection (including the default source).
pub fn iter_processed_mut(&mut self) -> impl Iterator<Item = &mut AssetSource> {
self.iter_mut().filter(|p| p.should_process())
}
/// Iterates over the [`AssetSourceId`] of every [`AssetSource`] in the collection (including the default source).
pub fn ids(&self) -> impl Iterator<Item = AssetSourceId<'static>> + '_ {
self.sources
.keys()
.map(|k| AssetSourceId::Name(k.clone_owned()))
.chain(Some(AssetSourceId::Default))
}
/// This will cause processed [`AssetReader`](crate::io::AssetReader) futures (such as [`AssetReader::read`](crate::io::AssetReader::read)) to wait until
/// the [`AssetProcessor`](crate::AssetProcessor) has finished processing the requested asset.
pub(crate) fn gate_on_processor(&mut self, processing_state: Arc<ProcessingState>) {
for source in self.iter_processed_mut() {
source.gate_on_processor(processing_state.clone());
}
}
}
/// An error returned when an [`AssetSource`] does not exist for a given id.
#[derive(Error, Debug, Clone, PartialEq, Eq)]
#[error("Asset Source '{0}' does not exist")]
pub struct MissingAssetSourceError(AssetSourceId<'static>);
/// An error returned when an [`AssetWriter`](crate::io::AssetWriter) does not exist for a given id.
#[derive(Error, Debug, Clone)]
#[error("Asset Source '{0}' does not have an AssetWriter.")]
pub struct MissingAssetWriterError(AssetSourceId<'static>);
/// An error returned when a processed [`AssetReader`](crate::io::AssetReader) does not exist for a given id.
#[derive(Error, Debug, Clone, PartialEq, Eq)]
#[error("Asset Source '{0}' does not have a processed AssetReader.")]
pub struct MissingProcessedAssetReaderError(AssetSourceId<'static>);
/// An error returned when a processed [`AssetWriter`](crate::io::AssetWriter) does not exist for a given id.
#[derive(Error, Debug, Clone)]
#[error("Asset Source '{0}' does not have a processed AssetWriter.")]
pub struct MissingProcessedAssetWriterError(AssetSourceId<'static>);
const MISSING_DEFAULT_SOURCE: &str =
"A default AssetSource is required. Add one to `AssetSourceBuilders`";
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/io/processor_gated.rs | crates/bevy_asset/src/io/processor_gated.rs | use crate::{
io::{
AssetReader, AssetReaderError, AssetSourceId, PathStream, Reader, ReaderRequiredFeatures,
},
processor::{ProcessStatus, ProcessingState},
AssetPath,
};
use alloc::{borrow::ToOwned, boxed::Box, sync::Arc, vec::Vec};
use async_lock::RwLockReadGuardArc;
use core::{pin::Pin, task::Poll};
use futures_io::AsyncRead;
use std::{io::SeekFrom, path::Path};
use tracing::trace;
use super::{AsyncSeek, ErasedAssetReader};
/// An [`AssetReader`] that will prevent asset (and asset metadata) read futures from returning for a
/// given path until that path has been processed by [`AssetProcessor`].
///
/// [`AssetProcessor`]: crate::processor::AssetProcessor
pub(crate) struct ProcessorGatedReader {
reader: Arc<dyn ErasedAssetReader>,
source: AssetSourceId<'static>,
processing_state: Arc<ProcessingState>,
}
impl ProcessorGatedReader {
/// Creates a new [`ProcessorGatedReader`].
pub(crate) fn new(
source: AssetSourceId<'static>,
reader: Arc<dyn ErasedAssetReader>,
processing_state: Arc<ProcessingState>,
) -> Self {
Self {
source,
reader,
processing_state,
}
}
}
impl AssetReader for ProcessorGatedReader {
async fn read<'a>(
&'a self,
path: &'a Path,
required_features: ReaderRequiredFeatures,
) -> Result<impl Reader + 'a, AssetReaderError> {
let asset_path = AssetPath::from(path.to_path_buf()).with_source(self.source.clone());
trace!("Waiting for processing to finish before reading {asset_path}");
let process_result = self
.processing_state
.wait_until_processed(asset_path.clone())
.await;
match process_result {
ProcessStatus::Processed => {}
ProcessStatus::Failed | ProcessStatus::NonExistent => {
return Err(AssetReaderError::NotFound(path.to_owned()));
}
}
trace!("Processing finished with {asset_path}, reading {process_result:?}",);
let lock = self
.processing_state
.get_transaction_lock(&asset_path)
.await?;
let asset_reader = self.reader.read(path, required_features).await?;
let reader = TransactionLockedReader::new(asset_reader, lock);
Ok(reader)
}
async fn read_meta<'a>(&'a self, path: &'a Path) -> Result<impl Reader + 'a, AssetReaderError> {
let asset_path = AssetPath::from(path.to_path_buf()).with_source(self.source.clone());
trace!("Waiting for processing to finish before reading meta for {asset_path}",);
let process_result = self
.processing_state
.wait_until_processed(asset_path.clone())
.await;
match process_result {
ProcessStatus::Processed => {}
ProcessStatus::Failed | ProcessStatus::NonExistent => {
return Err(AssetReaderError::NotFound(path.to_owned()));
}
}
trace!("Processing finished with {process_result:?}, reading meta for {asset_path}",);
let lock = self
.processing_state
.get_transaction_lock(&asset_path)
.await?;
let meta_reader = self.reader.read_meta(path).await?;
let reader = TransactionLockedReader::new(meta_reader, lock);
Ok(reader)
}
async fn read_directory<'a>(
&'a self,
path: &'a Path,
) -> Result<Box<PathStream>, AssetReaderError> {
trace!(
"Waiting for processing to finish before reading directory {:?}",
path
);
self.processing_state.wait_until_finished().await;
trace!("Processing finished, reading directory {:?}", path);
let result = self.reader.read_directory(path).await?;
Ok(result)
}
async fn is_directory<'a>(&'a self, path: &'a Path) -> Result<bool, AssetReaderError> {
trace!(
"Waiting for processing to finish before reading directory {:?}",
path
);
self.processing_state.wait_until_finished().await;
trace!("Processing finished, getting directory status {:?}", path);
let result = self.reader.is_directory(path).await?;
Ok(result)
}
}
/// An [`AsyncRead`] impl that will hold its asset's transaction lock until [`TransactionLockedReader`] is dropped.
pub struct TransactionLockedReader<'a> {
reader: Box<dyn Reader + 'a>,
_file_transaction_lock: RwLockReadGuardArc<()>,
}
impl<'a> TransactionLockedReader<'a> {
fn new(reader: Box<dyn Reader + 'a>, file_transaction_lock: RwLockReadGuardArc<()>) -> Self {
Self {
reader,
_file_transaction_lock: file_transaction_lock,
}
}
}
impl AsyncRead for TransactionLockedReader<'_> {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut core::task::Context<'_>,
buf: &mut [u8],
) -> Poll<futures_io::Result<usize>> {
Pin::new(&mut self.reader).poll_read(cx, buf)
}
}
impl AsyncSeek for TransactionLockedReader<'_> {
fn poll_seek(
mut self: Pin<&mut Self>,
cx: &mut core::task::Context<'_>,
pos: SeekFrom,
) -> Poll<std::io::Result<u64>> {
Pin::new(&mut self.reader).poll_seek(cx, pos)
}
}
impl Reader for TransactionLockedReader<'_> {
fn read_to_end<'a>(
&'a mut self,
buf: &'a mut Vec<u8>,
) -> stackfuture::StackFuture<'a, std::io::Result<usize>, { super::STACK_FUTURE_SIZE }> {
self.reader.read_to_end(buf)
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/io/android.rs | crates/bevy_asset/src/io/android.rs | use crate::io::{
get_meta_path, AssetReader, AssetReaderError, PathStream, Reader, ReaderRequiredFeatures,
VecReader,
};
use alloc::{borrow::ToOwned, boxed::Box, ffi::CString, vec::Vec};
use futures_lite::stream;
use std::path::Path;
/// [`AssetReader`] implementation for Android devices, built on top of Android's [`AssetManager`].
///
/// Implementation details:
///
/// - All functions use the [`AssetManager`] to load files.
/// - [`is_directory`](AssetReader::is_directory) tries to open the path
/// as a normal file and treats an error as if the path is a directory.
/// - Watching for changes is not supported. The watcher method will do nothing.
///
/// [AssetManager]: https://developer.android.com/reference/android/content/res/AssetManager
pub struct AndroidAssetReader;
impl AssetReader for AndroidAssetReader {
async fn read<'a>(
&'a self,
path: &'a Path,
_required_features: ReaderRequiredFeatures,
) -> Result<impl Reader + 'a, AssetReaderError> {
let asset_manager = bevy_android::ANDROID_APP
.get()
.expect("Bevy must be setup with the #[bevy_main] macro on Android")
.asset_manager();
let mut opened_asset = asset_manager
.open(&CString::new(path.to_str().unwrap()).unwrap())
.ok_or(AssetReaderError::NotFound(path.to_path_buf()))?;
let bytes = opened_asset.buffer()?;
let reader = VecReader::new(bytes.to_vec());
Ok(reader)
}
async fn read_meta<'a>(&'a self, path: &'a Path) -> Result<impl Reader + 'a, AssetReaderError> {
let meta_path = get_meta_path(path);
let asset_manager = bevy_android::ANDROID_APP
.get()
.expect("Bevy must be setup with the #[bevy_main] macro on Android")
.asset_manager();
let mut opened_asset = asset_manager
.open(&CString::new(meta_path.to_str().unwrap()).unwrap())
.ok_or(AssetReaderError::NotFound(meta_path))?;
let bytes = opened_asset.buffer()?;
let reader = VecReader::new(bytes.to_vec());
Ok(reader)
}
async fn read_directory<'a>(
&'a self,
path: &'a Path,
) -> Result<Box<PathStream>, AssetReaderError> {
let asset_manager = bevy_android::ANDROID_APP
.get()
.expect("Bevy must be setup with the #[bevy_main] macro on Android")
.asset_manager();
let opened_assets_dir = asset_manager
.open_dir(&CString::new(path.to_str().unwrap()).unwrap())
.ok_or(AssetReaderError::NotFound(path.to_path_buf()))?;
let mapped_stream = opened_assets_dir
.filter_map(move |f| {
let file_path = path.join(Path::new(f.to_str().unwrap()));
// filter out meta files as they are not considered assets
if let Some(ext) = file_path.extension().and_then(|e| e.to_str()) {
if ext.eq_ignore_ascii_case("meta") {
return None;
}
}
Some(file_path.to_owned())
})
.collect::<Vec<_>>();
let read_dir: Box<PathStream> = Box::new(stream::iter(mapped_stream));
Ok(read_dir)
}
async fn is_directory<'a>(&'a self, path: &'a Path) -> Result<bool, AssetReaderError> {
let asset_manager = bevy_android::ANDROID_APP
.get()
.expect("Bevy must be setup with the #[bevy_main] macro on Android")
.asset_manager();
// HACK: `AssetManager` does not provide a way to check if path
// points to a directory or a file
// `open_dir` succeeds for both files and directories and will only
// fail if the path does not exist at all
// `open` will fail for directories, but it will work for files
// The solution here was to first use `open_dir` to eliminate the case
// when the path does not exist at all, and then to use `open` to
// see if that path is a file or a directory
let cpath = CString::new(path.to_str().unwrap()).unwrap();
let _ = asset_manager
.open_dir(&cpath)
.ok_or(AssetReaderError::NotFound(path.to_path_buf()))?;
Ok(asset_manager.open(&cpath).is_none())
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/io/memory.rs | crates/bevy_asset/src/io/memory.rs | use crate::io::{
AssetReader, AssetReaderError, AssetWriter, AssetWriterError, PathStream, Reader,
ReaderRequiredFeatures,
};
use alloc::{borrow::ToOwned, boxed::Box, sync::Arc, vec, vec::Vec};
use bevy_platform::{
collections::HashMap,
sync::{PoisonError, RwLock},
};
use core::{pin::Pin, task::Poll};
use futures_io::{AsyncRead, AsyncWrite};
use futures_lite::Stream;
use std::{
io::{Error, ErrorKind, SeekFrom},
path::{Path, PathBuf},
};
use super::AsyncSeek;
#[derive(Default, Debug)]
struct DirInternal {
assets: HashMap<Box<str>, Data>,
metadata: HashMap<Box<str>, Data>,
dirs: HashMap<Box<str>, Dir>,
path: PathBuf,
}
/// A clone-able (internally Arc-ed) / thread-safe "in memory" filesystem.
/// This is built for [`MemoryAssetReader`] and is primarily intended for unit tests.
#[derive(Default, Clone, Debug)]
pub struct Dir(Arc<RwLock<DirInternal>>);
impl Dir {
/// Creates a new [`Dir`] for the given `path`.
pub fn new(path: PathBuf) -> Self {
Self(Arc::new(RwLock::new(DirInternal {
path,
..Default::default()
})))
}
pub fn insert_asset_text(&self, path: &Path, asset: &str) {
self.insert_asset(path, asset.as_bytes().to_vec());
}
pub fn insert_meta_text(&self, path: &Path, asset: &str) {
self.insert_meta(path, asset.as_bytes().to_vec());
}
pub fn insert_asset(&self, path: &Path, value: impl Into<Value>) {
let mut dir = self.clone();
if let Some(parent) = path.parent() {
dir = self.get_or_insert_dir(parent);
}
dir.0
.write()
.unwrap_or_else(PoisonError::into_inner)
.assets
.insert(
path.file_name().unwrap().to_string_lossy().into(),
Data {
value: value.into(),
path: path.to_owned(),
},
);
}
/// Removes the stored asset at `path`.
///
/// Returns the [`Data`] stored if found, [`None`] otherwise.
pub fn remove_asset(&self, path: &Path) -> Option<Data> {
let mut dir = self.clone();
if let Some(parent) = path.parent() {
dir = self.get_or_insert_dir(parent);
}
let key: Box<str> = path.file_name().unwrap().to_string_lossy().into();
dir.0
.write()
.unwrap_or_else(PoisonError::into_inner)
.assets
.remove(&key)
}
pub fn insert_meta(&self, path: &Path, value: impl Into<Value>) {
let mut dir = self.clone();
if let Some(parent) = path.parent() {
dir = self.get_or_insert_dir(parent);
}
dir.0
.write()
.unwrap_or_else(PoisonError::into_inner)
.metadata
.insert(
path.file_name().unwrap().to_string_lossy().into(),
Data {
value: value.into(),
path: path.to_owned(),
},
);
}
/// Removes the stored metadata at `path`.
///
/// Returns the [`Data`] stored if found, [`None`] otherwise.
pub fn remove_metadata(&self, path: &Path) -> Option<Data> {
let mut dir = self.clone();
if let Some(parent) = path.parent() {
dir = self.get_or_insert_dir(parent);
}
let key: Box<str> = path.file_name().unwrap().to_string_lossy().into();
dir.0
.write()
.unwrap_or_else(PoisonError::into_inner)
.metadata
.remove(&key)
}
pub fn get_or_insert_dir(&self, path: &Path) -> Dir {
let mut dir = self.clone();
let mut full_path = PathBuf::new();
for c in path.components() {
full_path.push(c);
let name = c.as_os_str().to_string_lossy().into();
dir = {
let dirs = &mut dir.0.write().unwrap_or_else(PoisonError::into_inner).dirs;
dirs.entry(name)
.or_insert_with(|| Dir::new(full_path.clone()))
.clone()
};
}
dir
}
/// Removes the dir at `path`.
///
/// Returns the [`Dir`] stored if found, [`None`] otherwise.
pub fn remove_dir(&self, path: &Path) -> Option<Dir> {
let mut dir = self.clone();
if let Some(parent) = path.parent() {
dir = self.get_or_insert_dir(parent);
}
let key: Box<str> = path.file_name().unwrap().to_string_lossy().into();
dir.0
.write()
.unwrap_or_else(PoisonError::into_inner)
.dirs
.remove(&key)
}
pub fn get_dir(&self, path: &Path) -> Option<Dir> {
let mut dir = self.clone();
for p in path.components() {
let component = p.as_os_str().to_str().unwrap();
let next_dir = dir
.0
.read()
.unwrap_or_else(PoisonError::into_inner)
.dirs
.get(component)?
.clone();
dir = next_dir;
}
Some(dir)
}
pub fn get_asset(&self, path: &Path) -> Option<Data> {
let mut dir = self.clone();
if let Some(parent) = path.parent() {
dir = dir.get_dir(parent)?;
}
path.file_name().and_then(|f| {
dir.0
.read()
.unwrap_or_else(PoisonError::into_inner)
.assets
.get(f.to_str().unwrap())
.cloned()
})
}
pub fn get_metadata(&self, path: &Path) -> Option<Data> {
let mut dir = self.clone();
if let Some(parent) = path.parent() {
dir = dir.get_dir(parent)?;
}
path.file_name().and_then(|f| {
dir.0
.read()
.unwrap_or_else(PoisonError::into_inner)
.metadata
.get(f.to_str().unwrap())
.cloned()
})
}
pub fn path(&self) -> PathBuf {
self.0
.read()
.unwrap_or_else(PoisonError::into_inner)
.path
.to_owned()
}
}
pub struct DirStream {
dir: Dir,
index: usize,
dir_index: usize,
}
impl DirStream {
fn new(dir: Dir) -> Self {
Self {
dir,
index: 0,
dir_index: 0,
}
}
}
impl Stream for DirStream {
type Item = PathBuf;
fn poll_next(
self: Pin<&mut Self>,
_cx: &mut core::task::Context<'_>,
) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
let dir = this.dir.0.read().unwrap_or_else(PoisonError::into_inner);
let dir_index = this.dir_index;
if let Some(dir_path) = dir
.dirs
.keys()
.nth(dir_index)
.map(|d| dir.path.join(d.as_ref()))
{
this.dir_index += 1;
Poll::Ready(Some(dir_path))
} else {
let index = this.index;
this.index += 1;
Poll::Ready(dir.assets.values().nth(index).map(|d| d.path().to_owned()))
}
}
}
/// In-memory [`AssetReader`] implementation.
/// This is primarily intended for unit tests.
#[derive(Default, Clone)]
pub struct MemoryAssetReader {
pub root: Dir,
}
/// In-memory [`AssetWriter`] implementation.
///
/// This is primarily intended for unit tests.
#[derive(Default, Clone)]
pub struct MemoryAssetWriter {
pub root: Dir,
}
/// Asset data stored in a [`Dir`].
#[derive(Clone, Debug)]
pub struct Data {
path: PathBuf,
value: Value,
}
/// Stores either an allocated vec of bytes or a static array of bytes.
#[derive(Clone, Debug)]
pub enum Value {
Vec(Arc<Vec<u8>>),
Static(&'static [u8]),
}
impl Data {
/// The path that this data was written to.
pub fn path(&self) -> &Path {
&self.path
}
/// The value in bytes that was written here.
pub fn value(&self) -> &[u8] {
match &self.value {
Value::Vec(vec) => vec,
Value::Static(value) => value,
}
}
}
impl From<Vec<u8>> for Value {
fn from(value: Vec<u8>) -> Self {
Self::Vec(Arc::new(value))
}
}
impl From<&'static [u8]> for Value {
fn from(value: &'static [u8]) -> Self {
Self::Static(value)
}
}
impl<const N: usize> From<&'static [u8; N]> for Value {
fn from(value: &'static [u8; N]) -> Self {
Self::Static(value)
}
}
struct DataReader {
data: Data,
bytes_read: usize,
}
impl AsyncRead for DataReader {
fn poll_read(
self: Pin<&mut Self>,
_cx: &mut core::task::Context<'_>,
buf: &mut [u8],
) -> Poll<futures_io::Result<usize>> {
// Get the mut borrow to avoid trying to borrow the pin itself multiple times.
let this = self.get_mut();
Poll::Ready(Ok(crate::io::slice_read(
this.data.value(),
&mut this.bytes_read,
buf,
)))
}
}
impl AsyncSeek for DataReader {
fn poll_seek(
self: Pin<&mut Self>,
_cx: &mut core::task::Context<'_>,
pos: SeekFrom,
) -> Poll<std::io::Result<u64>> {
// Get the mut borrow to avoid trying to borrow the pin itself multiple times.
let this = self.get_mut();
Poll::Ready(crate::io::slice_seek(
this.data.value(),
&mut this.bytes_read,
pos,
))
}
}
impl Reader for DataReader {
fn read_to_end<'a>(
&'a mut self,
buf: &'a mut Vec<u8>,
) -> stackfuture::StackFuture<'a, std::io::Result<usize>, { super::STACK_FUTURE_SIZE }> {
crate::io::read_to_end(self.data.value(), &mut self.bytes_read, buf)
}
}
impl AssetReader for MemoryAssetReader {
async fn read<'a>(
&'a self,
path: &'a Path,
_required_features: ReaderRequiredFeatures,
) -> Result<impl Reader + 'a, AssetReaderError> {
self.root
.get_asset(path)
.map(|data| DataReader {
data,
bytes_read: 0,
})
.ok_or_else(|| AssetReaderError::NotFound(path.to_path_buf()))
}
async fn read_meta<'a>(&'a self, path: &'a Path) -> Result<impl Reader + 'a, AssetReaderError> {
self.root
.get_metadata(path)
.map(|data| DataReader {
data,
bytes_read: 0,
})
.ok_or_else(|| AssetReaderError::NotFound(path.to_path_buf()))
}
async fn read_directory<'a>(
&'a self,
path: &'a Path,
) -> Result<Box<PathStream>, AssetReaderError> {
self.root
.get_dir(path)
.map(|dir| {
let stream: Box<PathStream> = Box::new(DirStream::new(dir));
stream
})
.ok_or_else(|| AssetReaderError::NotFound(path.to_path_buf()))
}
async fn is_directory<'a>(&'a self, path: &'a Path) -> Result<bool, AssetReaderError> {
Ok(self.root.get_dir(path).is_some())
}
}
/// A writer that writes into [`Dir`], buffering internally until flushed/closed.
struct DataWriter {
/// The dir to write to.
dir: Dir,
/// The path to write to.
path: PathBuf,
/// The current buffer of data.
///
/// This will include data that has been flushed already.
current_data: Vec<u8>,
/// Whether to write to the data or to the meta.
is_meta_writer: bool,
}
impl AsyncWrite for DataWriter {
fn poll_write(
self: Pin<&mut Self>,
_: &mut core::task::Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
self.get_mut().current_data.extend_from_slice(buf);
Poll::Ready(Ok(buf.len()))
}
fn poll_flush(
self: Pin<&mut Self>,
_: &mut core::task::Context<'_>,
) -> Poll<std::io::Result<()>> {
// Write the data to our fake disk. This means we will repeatedly reinsert the asset.
if self.is_meta_writer {
self.dir.insert_meta(&self.path, self.current_data.clone());
} else {
self.dir.insert_asset(&self.path, self.current_data.clone());
}
Poll::Ready(Ok(()))
}
fn poll_close(
self: Pin<&mut Self>,
cx: &mut core::task::Context<'_>,
) -> Poll<std::io::Result<()>> {
// A flush will just write the data to Dir, which is all we need to do for close.
self.poll_flush(cx)
}
}
impl AssetWriter for MemoryAssetWriter {
async fn write<'a>(&'a self, path: &'a Path) -> Result<Box<super::Writer>, AssetWriterError> {
Ok(Box::new(DataWriter {
dir: self.root.clone(),
path: path.to_owned(),
current_data: vec![],
is_meta_writer: false,
}))
}
async fn write_meta<'a>(
&'a self,
path: &'a Path,
) -> Result<Box<super::Writer>, AssetWriterError> {
Ok(Box::new(DataWriter {
dir: self.root.clone(),
path: path.to_owned(),
current_data: vec![],
is_meta_writer: true,
}))
}
async fn remove<'a>(&'a self, path: &'a Path) -> Result<(), AssetWriterError> {
if self.root.remove_asset(path).is_none() {
return Err(AssetWriterError::Io(Error::new(
ErrorKind::NotFound,
"no such file",
)));
}
Ok(())
}
async fn remove_meta<'a>(&'a self, path: &'a Path) -> Result<(), AssetWriterError> {
self.root.remove_metadata(path);
Ok(())
}
async fn rename<'a>(
&'a self,
old_path: &'a Path,
new_path: &'a Path,
) -> Result<(), AssetWriterError> {
let Some(old_asset) = self.root.get_asset(old_path) else {
return Err(AssetWriterError::Io(Error::new(
ErrorKind::NotFound,
"no such file",
)));
};
self.root.insert_asset(new_path, old_asset.value);
// Remove the asset after instead of before since otherwise there'd be a moment where the
// Dir is unlocked and missing both the old and new paths. This just prevents race
// conditions.
self.root.remove_asset(old_path);
Ok(())
}
async fn rename_meta<'a>(
&'a self,
old_path: &'a Path,
new_path: &'a Path,
) -> Result<(), AssetWriterError> {
let Some(old_meta) = self.root.get_metadata(old_path) else {
return Err(AssetWriterError::Io(Error::new(
ErrorKind::NotFound,
"no such file",
)));
};
self.root.insert_meta(new_path, old_meta.value);
// Remove the meta after instead of before since otherwise there'd be a moment where the
// Dir is unlocked and missing both the old and new paths. This just prevents race
// conditions.
self.root.remove_metadata(old_path);
Ok(())
}
async fn create_directory<'a>(&'a self, path: &'a Path) -> Result<(), AssetWriterError> {
// Just pretend we're on a file system that doesn't consider directory re-creation a
// failure.
self.root.get_or_insert_dir(path);
Ok(())
}
async fn remove_directory<'a>(&'a self, path: &'a Path) -> Result<(), AssetWriterError> {
if self.root.remove_dir(path).is_none() {
return Err(AssetWriterError::Io(Error::new(
ErrorKind::NotFound,
"no such dir",
)));
}
Ok(())
}
async fn remove_empty_directory<'a>(&'a self, path: &'a Path) -> Result<(), AssetWriterError> {
let Some(dir) = self.root.get_dir(path) else {
return Err(AssetWriterError::Io(Error::new(
ErrorKind::NotFound,
"no such dir",
)));
};
let dir = dir.0.read().unwrap();
if !dir.assets.is_empty() || !dir.metadata.is_empty() || !dir.dirs.is_empty() {
return Err(AssetWriterError::Io(Error::new(
ErrorKind::DirectoryNotEmpty,
"not empty",
)));
}
self.root.remove_dir(path);
Ok(())
}
async fn remove_assets_in_directory<'a>(
&'a self,
path: &'a Path,
) -> Result<(), AssetWriterError> {
let Some(dir) = self.root.get_dir(path) else {
return Err(AssetWriterError::Io(Error::new(
ErrorKind::NotFound,
"no such dir",
)));
};
let mut dir = dir.0.write().unwrap();
dir.assets.clear();
dir.dirs.clear();
dir.metadata.clear();
Ok(())
}
}
#[cfg(test)]
pub mod test {
use super::Dir;
use std::path::Path;
#[test]
fn memory_dir() {
let dir = Dir::default();
let a_path = Path::new("a.txt");
let a_data = "a".as_bytes().to_vec();
let a_meta = "ameta".as_bytes().to_vec();
dir.insert_asset(a_path, a_data.clone());
let asset = dir.get_asset(a_path).unwrap();
assert_eq!(asset.path(), a_path);
assert_eq!(asset.value(), a_data);
dir.insert_meta(a_path, a_meta.clone());
let meta = dir.get_metadata(a_path).unwrap();
assert_eq!(meta.path(), a_path);
assert_eq!(meta.value(), a_meta);
let b_path = Path::new("x/y/b.txt");
let b_data = "b".as_bytes().to_vec();
let b_meta = "meta".as_bytes().to_vec();
dir.insert_asset(b_path, b_data.clone());
dir.insert_meta(b_path, b_meta.clone());
let asset = dir.get_asset(b_path).unwrap();
assert_eq!(asset.path(), b_path);
assert_eq!(asset.value(), b_data);
let meta = dir.get_metadata(b_path).unwrap();
assert_eq!(meta.path(), b_path);
assert_eq!(meta.value(), b_meta);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/io/mod.rs | crates/bevy_asset/src/io/mod.rs | #[cfg(all(feature = "file_watcher", target_arch = "wasm32"))]
compile_error!(
"The \"file_watcher\" feature for hot reloading does not work \
on Wasm.\nDisable \"file_watcher\" \
when compiling to Wasm"
);
#[cfg(target_os = "android")]
pub mod android;
pub mod embedded;
#[cfg(not(target_arch = "wasm32"))]
pub mod file;
pub mod memory;
pub mod processor_gated;
#[cfg(target_arch = "wasm32")]
pub mod wasm;
#[cfg(any(feature = "http", feature = "https"))]
pub mod web;
#[cfg(test)]
pub mod gated;
mod source;
pub use futures_lite::AsyncWriteExt;
pub use source::*;
use alloc::{boxed::Box, sync::Arc, vec::Vec};
use bevy_tasks::{BoxedFuture, ConditionalSendFuture};
use core::{
mem::size_of,
pin::Pin,
task::{Context, Poll},
};
use futures_io::{AsyncRead, AsyncSeek, AsyncWrite};
use futures_lite::Stream;
use std::{
io::SeekFrom,
path::{Path, PathBuf},
};
use thiserror::Error;
/// Errors that occur while loading assets.
#[derive(Error, Debug, Clone)]
pub enum AssetReaderError {
#[error(
"A reader feature was required, but this AssetReader does not support that feature: {0}"
)]
UnsupportedFeature(#[from] UnsupportedReaderFeature),
/// Path not found.
#[error("Path not found: {}", _0.display())]
NotFound(PathBuf),
/// Encountered an I/O error while loading an asset.
#[error("Encountered an I/O error while loading asset: {0}")]
Io(Arc<std::io::Error>),
/// The HTTP request completed but returned an unhandled [HTTP response status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status).
/// - If the request returns a 404 error, expect [`AssetReaderError::NotFound`].
/// - If the request fails before getting a status code (e.g. request timeout, interrupted connection, etc), expect [`AssetReaderError::Io`].
#[error("Encountered HTTP status {0:?} when loading asset")]
HttpError(u16),
}
impl PartialEq for AssetReaderError {
/// Equality comparison for `AssetReaderError::Io` is not full (only through `ErrorKind` of inner error)
#[inline]
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::UnsupportedFeature(feature), Self::UnsupportedFeature(other_feature)) => {
feature == other_feature
}
(Self::NotFound(path), Self::NotFound(other_path)) => path == other_path,
(Self::Io(error), Self::Io(other_error)) => error.kind() == other_error.kind(),
(Self::HttpError(code), Self::HttpError(other_code)) => code == other_code,
_ => false,
}
}
}
impl Eq for AssetReaderError {}
impl From<std::io::Error> for AssetReaderError {
fn from(value: std::io::Error) -> Self {
Self::Io(Arc::new(value))
}
}
/// An error for when a particular feature in [`ReaderRequiredFeatures`] is not supported.
#[derive(Error, Debug, Clone, PartialEq, Eq)]
pub enum UnsupportedReaderFeature {
/// The caller requested to be able to seek any way (forward, backward, from start/end), but
/// this is not supported by the [`AssetReader`].
#[error("the reader cannot seek in any direction")]
AnySeek,
}
/// The required features for a `Reader` that an `AssetLoader` may use.
///
/// This allows the asset loader to communicate with the asset source what features of the reader it
/// will use. This allows the asset source to return an error early (if a feature is unsupported),
/// or use a different reader implementation based on the required features to optimize reading
/// (e.g., using a simpler reader implementation if some features are not required).
///
/// These features **only** apply to the asset itself, and not any nested loads - those loaders will
/// request their own required features.
#[derive(Clone, Copy, Default)]
pub struct ReaderRequiredFeatures {
/// The kind of seek that the reader needs to support.
pub seek: SeekKind,
}
/// The kind of seeking that the reader supports.
#[derive(Clone, Copy, Default)]
pub enum SeekKind {
/// The reader can only seek forward.
///
/// Seeking forward is always required, since at the bare minimum, the reader could choose to
/// just read that many bytes and then drop them (effectively seeking forward).
#[default]
OnlyForward,
/// The reader can seek forward, backward, seek from the start, and seek from the end.
AnySeek,
}
/// The maximum size of a future returned from [`Reader::read_to_end`].
/// This is large enough to fit ten references.
// Ideally this would be even smaller (ReadToEndFuture only needs space for two references based on its definition),
// but compiler optimizations can apparently inflate the stack size of futures due to inlining, which makes
// a higher maximum necessary.
pub const STACK_FUTURE_SIZE: usize = 10 * size_of::<&()>();
pub use stackfuture::StackFuture;
/// A type returned from [`AssetReader::read`], which is used to read the contents of a file
/// (or virtual file) corresponding to an asset.
///
/// This is essentially a trait alias for types implementing [`AsyncRead`] and [`AsyncSeek`].
/// The only reason a blanket implementation is not provided for applicable types is to allow
/// implementors to override the provided implementation of [`Reader::read_to_end`].
///
/// # Reader features
///
/// This trait includes super traits. However, this **does not** mean that your type needs to
/// support every feature of those super traits. If the caller never uses that feature, then a dummy
/// implementation that just returns an error is sufficient.
///
/// The caller can request a compatible [`Reader`] using [`ReaderRequiredFeatures`] (when using the
/// [`AssetReader`] trait). This allows the caller to state which features of the reader it will
/// use, avoiding cases where the caller uses a feature that the reader does not support.
///
/// For example, the caller may set [`ReaderRequiredFeatures::seek`] to
/// [`SeekKind::AnySeek`] to indicate that they may seek backward, or from the start/end. A reader
/// implementation may choose to support that, or may just detect those kinds of seeks and return an
/// error.
pub trait Reader: AsyncRead + AsyncSeek + Unpin + Send + Sync {
/// Reads the entire contents of this reader and appends them to a vec.
///
/// # Note for implementors
/// You should override the provided implementation if you can fill up the buffer more
/// efficiently than the default implementation, which calls `poll_read` repeatedly to
/// fill up the buffer 32 bytes at a time.
fn read_to_end<'a>(
&'a mut self,
buf: &'a mut Vec<u8>,
) -> StackFuture<'a, std::io::Result<usize>, STACK_FUTURE_SIZE> {
let future = futures_lite::AsyncReadExt::read_to_end(self, buf);
StackFuture::from(future)
}
}
impl Reader for Box<dyn Reader + '_> {
fn read_to_end<'a>(
&'a mut self,
buf: &'a mut Vec<u8>,
) -> StackFuture<'a, std::io::Result<usize>, STACK_FUTURE_SIZE> {
(**self).read_to_end(buf)
}
}
/// A future that returns a value or an [`AssetReaderError`]
pub trait AssetReaderFuture:
ConditionalSendFuture<Output = Result<Self::Value, AssetReaderError>>
{
type Value;
}
impl<F, T> AssetReaderFuture for F
where
F: ConditionalSendFuture<Output = Result<T, AssetReaderError>>,
{
type Value = T;
}
/// Performs read operations on an asset storage. [`AssetReader`] exposes a "virtual filesystem"
/// API, where asset bytes and asset metadata bytes are both stored and accessible for a given
/// `path`. This trait is not object safe, if needed use a dyn [`ErasedAssetReader`] instead.
///
/// This trait defines asset-agnostic mechanisms to read bytes from a storage system.
/// For the per-asset-type saving/loading logic, see [`AssetSaver`](crate::saver::AssetSaver) and [`AssetLoader`](crate::loader::AssetLoader).
///
/// For a complementary version of this trait that can write assets to storage, see [`AssetWriter`].
pub trait AssetReader: Send + Sync + 'static {
/// Returns a future to load the full file data at the provided path.
///
/// # Required Features
///
/// The `required_features` allows the caller to request that the returned reader implements
/// certain features, and consequently allows this trait to decide how to react to that request.
/// Namely, the implementor could:
///
/// * Return an error if the caller requests an unsupported feature. This can give a nicer error
/// message to make it clear that the caller (e.g., an asset loader) can't be used with this
/// reader.
/// * Use a different implementation of a reader to ensure support of a feature (e.g., reading
/// the entire asset into memory and then providing that buffer as a reader).
/// * Ignore the request and provide the regular reader anyway. Practically, if the caller never
/// actually uses the feature, it's fine to continue using the reader. However the caller
/// requesting a feature is a **strong signal** that they will use the given feature.
///
/// The recommendation is to simply return an error for unsupported features. Callers can
/// generally work around this and have more understanding of their constraints. For example,
/// an asset loader may know that it will only load "small" assets, so reading the entire asset
/// into memory won't consume too much memory, and so it can use the regular [`AsyncRead`] API
/// to read the whole asset into memory. If this were done by this trait, the loader may
/// accidentally be allocating too much memory for a large asset without knowing it!
///
/// # Note for implementors
/// The preferred style for implementing this method is an `async fn` returning an opaque type.
///
/// ```no_run
/// # use std::path::Path;
/// # use bevy_asset::{prelude::*, io::{AssetReader, PathStream, Reader, AssetReaderError, ReaderRequiredFeatures}};
/// # struct MyReader;
/// impl AssetReader for MyReader {
/// async fn read<'a>(&'a self, path: &'a Path, required_features: ReaderRequiredFeatures) -> Result<impl Reader + 'a, AssetReaderError> {
/// // ...
/// # let val: Box<dyn Reader> = unimplemented!(); Ok(val)
/// }
/// # async fn read_meta<'a>(&'a self, path: &'a Path) -> Result<impl Reader + 'a, AssetReaderError> {
/// # let val: Box<dyn Reader> = unimplemented!(); Ok(val) }
/// # async fn read_directory<'a>(&'a self, path: &'a Path) -> Result<Box<PathStream>, AssetReaderError> { unimplemented!() }
/// # async fn is_directory<'a>(&'a self, path: &'a Path) -> Result<bool, AssetReaderError> { unimplemented!() }
/// # async fn read_meta_bytes<'a>(&'a self, path: &'a Path) -> Result<Vec<u8>, AssetReaderError> { unimplemented!() }
/// }
/// ```
fn read<'a>(
&'a self,
path: &'a Path,
required_features: ReaderRequiredFeatures,
) -> impl AssetReaderFuture<Value: Reader + 'a>;
/// Returns a future to load the full file data at the provided path.
fn read_meta<'a>(&'a self, path: &'a Path) -> impl AssetReaderFuture<Value: Reader + 'a>;
/// Returns an iterator of directory entry names at the provided path.
fn read_directory<'a>(
&'a self,
path: &'a Path,
) -> impl ConditionalSendFuture<Output = Result<Box<PathStream>, AssetReaderError>>;
/// Returns true if the provided path points to a directory.
fn is_directory<'a>(
&'a self,
path: &'a Path,
) -> impl ConditionalSendFuture<Output = Result<bool, AssetReaderError>>;
/// Reads asset metadata bytes at the given `path` into a [`Vec<u8>`]. This is a convenience
/// function that wraps [`AssetReader::read_meta`] by default.
fn read_meta_bytes<'a>(
&'a self,
path: &'a Path,
) -> impl ConditionalSendFuture<Output = Result<Vec<u8>, AssetReaderError>> {
async {
let mut meta_reader = self.read_meta(path).await?;
let mut meta_bytes = Vec::new();
meta_reader.read_to_end(&mut meta_bytes).await?;
Ok(meta_bytes)
}
}
}
/// Equivalent to an [`AssetReader`] but using boxed futures, necessary eg. when using a `dyn AssetReader`,
/// as [`AssetReader`] isn't currently object safe.
pub trait ErasedAssetReader: Send + Sync + 'static {
/// Returns a future to load the full file data at the provided path.
fn read<'a>(
&'a self,
path: &'a Path,
required_features: ReaderRequiredFeatures,
) -> BoxedFuture<'a, Result<Box<dyn Reader + 'a>, AssetReaderError>>;
/// Returns a future to load the full file data at the provided path.
fn read_meta<'a>(
&'a self,
path: &'a Path,
) -> BoxedFuture<'a, Result<Box<dyn Reader + 'a>, AssetReaderError>>;
/// Returns an iterator of directory entry names at the provided path.
fn read_directory<'a>(
&'a self,
path: &'a Path,
) -> BoxedFuture<'a, Result<Box<PathStream>, AssetReaderError>>;
/// Returns true if the provided path points to a directory.
fn is_directory<'a>(
&'a self,
path: &'a Path,
) -> BoxedFuture<'a, Result<bool, AssetReaderError>>;
/// Reads asset metadata bytes at the given `path` into a [`Vec<u8>`]. This is a convenience
/// function that wraps [`ErasedAssetReader::read_meta`] by default.
fn read_meta_bytes<'a>(
&'a self,
path: &'a Path,
) -> BoxedFuture<'a, Result<Vec<u8>, AssetReaderError>>;
}
impl<T: AssetReader> ErasedAssetReader for T {
fn read<'a>(
&'a self,
path: &'a Path,
required_features: ReaderRequiredFeatures,
) -> BoxedFuture<'a, Result<Box<dyn Reader + 'a>, AssetReaderError>> {
Box::pin(async move {
let reader = Self::read(self, path, required_features).await?;
Ok(Box::new(reader) as Box<dyn Reader>)
})
}
fn read_meta<'a>(
&'a self,
path: &'a Path,
) -> BoxedFuture<'a, Result<Box<dyn Reader + 'a>, AssetReaderError>> {
Box::pin(async {
let reader = Self::read_meta(self, path).await?;
Ok(Box::new(reader) as Box<dyn Reader>)
})
}
fn read_directory<'a>(
&'a self,
path: &'a Path,
) -> BoxedFuture<'a, Result<Box<PathStream>, AssetReaderError>> {
Box::pin(Self::read_directory(self, path))
}
fn is_directory<'a>(
&'a self,
path: &'a Path,
) -> BoxedFuture<'a, Result<bool, AssetReaderError>> {
Box::pin(Self::is_directory(self, path))
}
fn read_meta_bytes<'a>(
&'a self,
path: &'a Path,
) -> BoxedFuture<'a, Result<Vec<u8>, AssetReaderError>> {
Box::pin(Self::read_meta_bytes(self, path))
}
}
pub type Writer = dyn AsyncWrite + Unpin + Send + Sync;
pub type PathStream = dyn Stream<Item = PathBuf> + Unpin + Send;
/// Errors that occur while loading assets.
#[derive(Error, Debug)]
pub enum AssetWriterError {
/// Encountered an I/O error while loading an asset.
#[error("encountered an io error while loading asset: {0}")]
Io(#[from] std::io::Error),
}
/// Preforms write operations on an asset storage. [`AssetWriter`] exposes a "virtual filesystem"
/// API, where asset bytes and asset metadata bytes are both stored and accessible for a given
/// `path`. This trait is not object safe, if needed use a dyn [`ErasedAssetWriter`] instead.
///
/// This trait defines asset-agnostic mechanisms to write bytes to a storage system.
/// For the per-asset-type saving/loading logic, see [`AssetSaver`](crate::saver::AssetSaver) and [`AssetLoader`](crate::loader::AssetLoader).
///
/// For a complementary version of this trait that can read assets from storage, see [`AssetReader`].
pub trait AssetWriter: Send + Sync + 'static {
/// Writes the full asset bytes at the provided path.
fn write<'a>(
&'a self,
path: &'a Path,
) -> impl ConditionalSendFuture<Output = Result<Box<Writer>, AssetWriterError>>;
/// Writes the full asset meta bytes at the provided path.
/// This _should not_ include storage specific extensions like `.meta`.
fn write_meta<'a>(
&'a self,
path: &'a Path,
) -> impl ConditionalSendFuture<Output = Result<Box<Writer>, AssetWriterError>>;
/// Removes the asset stored at the given path.
fn remove<'a>(
&'a self,
path: &'a Path,
) -> impl ConditionalSendFuture<Output = Result<(), AssetWriterError>>;
/// Removes the asset meta stored at the given path.
/// This _should not_ include storage specific extensions like `.meta`.
fn remove_meta<'a>(
&'a self,
path: &'a Path,
) -> impl ConditionalSendFuture<Output = Result<(), AssetWriterError>>;
/// Renames the asset at `old_path` to `new_path`
fn rename<'a>(
&'a self,
old_path: &'a Path,
new_path: &'a Path,
) -> impl ConditionalSendFuture<Output = Result<(), AssetWriterError>>;
/// Renames the asset meta for the asset at `old_path` to `new_path`.
/// This _should not_ include storage specific extensions like `.meta`.
fn rename_meta<'a>(
&'a self,
old_path: &'a Path,
new_path: &'a Path,
) -> impl ConditionalSendFuture<Output = Result<(), AssetWriterError>>;
/// Creates a directory at the given path, including all parent directories if they do not
/// already exist.
fn create_directory<'a>(
&'a self,
path: &'a Path,
) -> impl ConditionalSendFuture<Output = Result<(), AssetWriterError>>;
/// Removes the directory at the given path, including all assets _and_ directories in that directory.
fn remove_directory<'a>(
&'a self,
path: &'a Path,
) -> impl ConditionalSendFuture<Output = Result<(), AssetWriterError>>;
/// Removes the directory at the given path, but only if it is completely empty. This will return an error if the
/// directory is not empty.
fn remove_empty_directory<'a>(
&'a self,
path: &'a Path,
) -> impl ConditionalSendFuture<Output = Result<(), AssetWriterError>>;
/// Removes all assets (and directories) in this directory, resulting in an empty directory.
fn remove_assets_in_directory<'a>(
&'a self,
path: &'a Path,
) -> impl ConditionalSendFuture<Output = Result<(), AssetWriterError>>;
/// Writes the asset `bytes` to the given `path`.
fn write_bytes<'a>(
&'a self,
path: &'a Path,
bytes: &'a [u8],
) -> impl ConditionalSendFuture<Output = Result<(), AssetWriterError>> {
async {
let mut writer = self.write(path).await?;
writer.write_all(bytes).await?;
writer.flush().await?;
Ok(())
}
}
/// Writes the asset meta `bytes` to the given `path`.
fn write_meta_bytes<'a>(
&'a self,
path: &'a Path,
bytes: &'a [u8],
) -> impl ConditionalSendFuture<Output = Result<(), AssetWriterError>> {
async {
let mut meta_writer = self.write_meta(path).await?;
meta_writer.write_all(bytes).await?;
meta_writer.flush().await?;
Ok(())
}
}
}
/// Equivalent to an [`AssetWriter`] but using boxed futures, necessary eg. when using a `dyn AssetWriter`,
/// as [`AssetWriter`] isn't currently object safe.
pub trait ErasedAssetWriter: Send + Sync + 'static {
/// Writes the full asset bytes at the provided path.
fn write<'a>(
&'a self,
path: &'a Path,
) -> BoxedFuture<'a, Result<Box<Writer>, AssetWriterError>>;
/// Writes the full asset meta bytes at the provided path.
/// This _should not_ include storage specific extensions like `.meta`.
fn write_meta<'a>(
&'a self,
path: &'a Path,
) -> BoxedFuture<'a, Result<Box<Writer>, AssetWriterError>>;
/// Removes the asset stored at the given path.
fn remove<'a>(&'a self, path: &'a Path) -> BoxedFuture<'a, Result<(), AssetWriterError>>;
/// Removes the asset meta stored at the given path.
/// This _should not_ include storage specific extensions like `.meta`.
fn remove_meta<'a>(&'a self, path: &'a Path) -> BoxedFuture<'a, Result<(), AssetWriterError>>;
/// Renames the asset at `old_path` to `new_path`
fn rename<'a>(
&'a self,
old_path: &'a Path,
new_path: &'a Path,
) -> BoxedFuture<'a, Result<(), AssetWriterError>>;
/// Renames the asset meta for the asset at `old_path` to `new_path`.
/// This _should not_ include storage specific extensions like `.meta`.
fn rename_meta<'a>(
&'a self,
old_path: &'a Path,
new_path: &'a Path,
) -> BoxedFuture<'a, Result<(), AssetWriterError>>;
/// Creates a directory at the given path, including all parent directories if they do not
/// already exist.
fn create_directory<'a>(
&'a self,
path: &'a Path,
) -> BoxedFuture<'a, Result<(), AssetWriterError>>;
/// Removes the directory at the given path, including all assets _and_ directories in that directory.
fn remove_directory<'a>(
&'a self,
path: &'a Path,
) -> BoxedFuture<'a, Result<(), AssetWriterError>>;
/// Removes the directory at the given path, but only if it is completely empty. This will return an error if the
/// directory is not empty.
fn remove_empty_directory<'a>(
&'a self,
path: &'a Path,
) -> BoxedFuture<'a, Result<(), AssetWriterError>>;
/// Removes all assets (and directories) in this directory, resulting in an empty directory.
fn remove_assets_in_directory<'a>(
&'a self,
path: &'a Path,
) -> BoxedFuture<'a, Result<(), AssetWriterError>>;
/// Writes the asset `bytes` to the given `path`.
fn write_bytes<'a>(
&'a self,
path: &'a Path,
bytes: &'a [u8],
) -> BoxedFuture<'a, Result<(), AssetWriterError>>;
/// Writes the asset meta `bytes` to the given `path`.
fn write_meta_bytes<'a>(
&'a self,
path: &'a Path,
bytes: &'a [u8],
) -> BoxedFuture<'a, Result<(), AssetWriterError>>;
}
impl<T: AssetWriter> ErasedAssetWriter for T {
fn write<'a>(
&'a self,
path: &'a Path,
) -> BoxedFuture<'a, Result<Box<Writer>, AssetWriterError>> {
Box::pin(Self::write(self, path))
}
fn write_meta<'a>(
&'a self,
path: &'a Path,
) -> BoxedFuture<'a, Result<Box<Writer>, AssetWriterError>> {
Box::pin(Self::write_meta(self, path))
}
fn remove<'a>(&'a self, path: &'a Path) -> BoxedFuture<'a, Result<(), AssetWriterError>> {
Box::pin(Self::remove(self, path))
}
fn remove_meta<'a>(&'a self, path: &'a Path) -> BoxedFuture<'a, Result<(), AssetWriterError>> {
Box::pin(Self::remove_meta(self, path))
}
fn rename<'a>(
&'a self,
old_path: &'a Path,
new_path: &'a Path,
) -> BoxedFuture<'a, Result<(), AssetWriterError>> {
Box::pin(Self::rename(self, old_path, new_path))
}
fn rename_meta<'a>(
&'a self,
old_path: &'a Path,
new_path: &'a Path,
) -> BoxedFuture<'a, Result<(), AssetWriterError>> {
Box::pin(Self::rename_meta(self, old_path, new_path))
}
fn create_directory<'a>(
&'a self,
path: &'a Path,
) -> BoxedFuture<'a, Result<(), AssetWriterError>> {
Box::pin(Self::create_directory(self, path))
}
fn remove_directory<'a>(
&'a self,
path: &'a Path,
) -> BoxedFuture<'a, Result<(), AssetWriterError>> {
Box::pin(Self::remove_directory(self, path))
}
fn remove_empty_directory<'a>(
&'a self,
path: &'a Path,
) -> BoxedFuture<'a, Result<(), AssetWriterError>> {
Box::pin(Self::remove_empty_directory(self, path))
}
fn remove_assets_in_directory<'a>(
&'a self,
path: &'a Path,
) -> BoxedFuture<'a, Result<(), AssetWriterError>> {
Box::pin(Self::remove_assets_in_directory(self, path))
}
fn write_bytes<'a>(
&'a self,
path: &'a Path,
bytes: &'a [u8],
) -> BoxedFuture<'a, Result<(), AssetWriterError>> {
Box::pin(Self::write_bytes(self, path, bytes))
}
fn write_meta_bytes<'a>(
&'a self,
path: &'a Path,
bytes: &'a [u8],
) -> BoxedFuture<'a, Result<(), AssetWriterError>> {
Box::pin(Self::write_meta_bytes(self, path, bytes))
}
}
/// An "asset source change event" that occurs whenever asset (or asset metadata) is created/added/removed
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AssetSourceEvent {
/// An asset at this path was added.
AddedAsset(PathBuf),
/// An asset at this path was modified.
ModifiedAsset(PathBuf),
/// An asset at this path was removed.
RemovedAsset(PathBuf),
/// An asset at this path was renamed.
RenamedAsset { old: PathBuf, new: PathBuf },
/// Asset metadata at this path was added.
AddedMeta(PathBuf),
/// Asset metadata at this path was modified.
ModifiedMeta(PathBuf),
/// Asset metadata at this path was removed.
RemovedMeta(PathBuf),
/// Asset metadata at this path was renamed.
RenamedMeta { old: PathBuf, new: PathBuf },
/// A folder at the given path was added.
AddedFolder(PathBuf),
/// A folder at the given path was removed.
RemovedFolder(PathBuf),
/// A folder at the given path was renamed.
RenamedFolder { old: PathBuf, new: PathBuf },
/// Something of unknown type was removed. It is the job of the event handler to determine the type.
/// This exists because notify-rs produces "untyped" rename events without destination paths for unwatched folders, so we can't determine the type of
/// the rename.
RemovedUnknown {
/// The path of the removed asset or folder (undetermined). This could be an asset path or a folder. This will not be a "meta file" path.
path: PathBuf,
/// This field is only relevant if `path` is determined to be an asset path (and therefore not a folder). If this field is `true`,
/// then this event corresponds to a meta removal (not an asset removal) . If `false`, then this event corresponds to an asset removal
/// (not a meta removal).
is_meta: bool,
},
}
/// A handle to an "asset watcher" process, that will listen for and emit [`AssetSourceEvent`] values for as long as
/// [`AssetWatcher`] has not been dropped.
pub trait AssetWatcher: Send + Sync + 'static {}
/// An [`AsyncRead`] implementation capable of reading a [`Vec<u8>`].
pub struct VecReader {
bytes: Vec<u8>,
bytes_read: usize,
}
impl VecReader {
/// Create a new [`VecReader`] for `bytes`.
pub fn new(bytes: Vec<u8>) -> Self {
Self {
bytes_read: 0,
bytes,
}
}
}
impl AsyncRead for VecReader {
fn poll_read(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<futures_io::Result<usize>> {
// Get the mut borrow to avoid trying to borrow the pin itself multiple times.
let this = self.get_mut();
Poll::Ready(Ok(slice_read(&this.bytes, &mut this.bytes_read, buf)))
}
}
impl AsyncSeek for VecReader {
fn poll_seek(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
pos: SeekFrom,
) -> Poll<std::io::Result<u64>> {
// Get the mut borrow to avoid trying to borrow the pin itself multiple times.
let this = self.get_mut();
Poll::Ready(slice_seek(&this.bytes, &mut this.bytes_read, pos))
}
}
impl Reader for VecReader {
fn read_to_end<'a>(
&'a mut self,
buf: &'a mut Vec<u8>,
) -> StackFuture<'a, std::io::Result<usize>, STACK_FUTURE_SIZE> {
read_to_end(&self.bytes, &mut self.bytes_read, buf)
}
}
/// An [`AsyncRead`] implementation capable of reading a [`&[u8]`].
pub struct SliceReader<'a> {
bytes: &'a [u8],
bytes_read: usize,
}
impl<'a> SliceReader<'a> {
/// Create a new [`SliceReader`] for `bytes`.
pub fn new(bytes: &'a [u8]) -> Self {
Self {
bytes,
bytes_read: 0,
}
}
}
impl<'a> AsyncRead for SliceReader<'a> {
fn poll_read(
mut self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<std::io::Result<usize>> {
Poll::Ready(Ok(slice_read(self.bytes, &mut self.bytes_read, buf)))
}
}
impl<'a> AsyncSeek for SliceReader<'a> {
fn poll_seek(
mut self: Pin<&mut Self>,
_cx: &mut Context<'_>,
pos: SeekFrom,
) -> Poll<std::io::Result<u64>> {
Poll::Ready(slice_seek(self.bytes, &mut self.bytes_read, pos))
}
}
impl Reader for SliceReader<'_> {
fn read_to_end<'a>(
&'a mut self,
buf: &'a mut Vec<u8>,
) -> StackFuture<'a, std::io::Result<usize>, STACK_FUTURE_SIZE> {
read_to_end(self.bytes, &mut self.bytes_read, buf)
}
}
/// Performs a read from the `slice` into `buf`.
pub(crate) fn slice_read(slice: &[u8], bytes_read: &mut usize, buf: &mut [u8]) -> usize {
if *bytes_read >= slice.len() {
0
} else {
let n = std::io::Read::read(&mut &slice[(*bytes_read)..], buf).unwrap();
*bytes_read += n;
n
}
}
/// Performs a "seek" and updates the cursor of `bytes_read`. Returns the new byte position.
pub(crate) fn slice_seek(
slice: &[u8],
bytes_read: &mut usize,
pos: SeekFrom,
) -> std::io::Result<u64> {
let make_error = || {
Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"seek position is out of range",
))
};
let (origin, offset) = match pos {
SeekFrom::Current(offset) => (*bytes_read, Ok(offset)),
SeekFrom::Start(offset) => (0, offset.try_into()),
SeekFrom::End(offset) => (slice.len(), Ok(offset)),
};
let Ok(offset) = offset else {
return make_error();
};
let Ok(origin): Result<i64, _> = origin.try_into() else {
return make_error();
};
let Ok(new_pos) = (origin + offset).try_into() else {
return make_error();
};
*bytes_read = new_pos;
Ok(new_pos as _)
}
/// Copies bytes from source to dest, keeping track of where in the source it starts copying from.
///
/// This is effectively the impl for [`SliceReader::read_to_end`], but this is provided here so the
/// lifetimes are only tied to the buffer and not the [`SliceReader`] itself.
pub(crate) fn read_to_end<'a>(
source: &'a [u8],
bytes_read: &'a mut usize,
dest: &'a mut Vec<u8>,
) -> StackFuture<'a, std::io::Result<usize>, STACK_FUTURE_SIZE> {
StackFuture::from(async {
if *bytes_read >= source.len() {
Ok(0)
} else {
dest.extend_from_slice(&source[*bytes_read..]);
let n = source.len() - *bytes_read;
*bytes_read = source.len();
Ok(n)
}
})
}
/// Appends `.meta` to the given path:
/// - `foo` becomes `foo.meta`
/// - `foo.bar` becomes `foo.bar.meta`
pub(crate) fn get_meta_path(path: &Path) -> PathBuf {
let mut meta_path = path.to_path_buf();
let mut extension = path.extension().unwrap_or_default().to_os_string();
if !extension.is_empty() {
extension.push(".");
}
extension.push("meta");
meta_path.set_extension(extension);
meta_path
}
#[cfg(any(target_arch = "wasm32", target_os = "android"))]
/// A [`PathBuf`] [`Stream`] implementation that immediately returns nothing.
struct EmptyPathStream;
#[cfg(any(target_arch = "wasm32", target_os = "android"))]
impl Stream for EmptyPathStream {
type Item = PathBuf;
fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Poll::Ready(None)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn get_meta_path_no_extension() {
assert_eq!(
get_meta_path(Path::new("foo")).to_str().unwrap(),
"foo.meta"
);
}
#[test]
fn get_meta_path_with_extension() {
assert_eq!(
get_meta_path(Path::new("foo.bar")).to_str().unwrap(),
"foo.bar.meta"
);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/io/web.rs | crates/bevy_asset/src/io/web.rs | use crate::io::{
AssetReader, AssetReaderError, AssetSourceBuilder, PathStream, Reader, ReaderRequiredFeatures,
};
use crate::{AssetApp, AssetPlugin};
use alloc::boxed::Box;
use bevy_app::{App, Plugin};
use bevy_tasks::ConditionalSendFuture;
use std::path::{Path, PathBuf};
use tracing::warn;
/// Adds the `http` and `https` asset sources to the app.
///
/// NOTE: Make sure to add this plugin *before* `AssetPlugin` to properly register http asset sources.
///
/// WARNING: be careful about where your URLs are coming from! URLs can potentially be exploited by an
/// attacker to trigger vulnerabilities in our asset loaders, or DOS by downloading enormous files. We
/// are not aware of any such vulnerabilities at the moment, just be careful!
///
/// Any asset path that begins with `http` (when the `http` feature is enabled) or `https` (when the
/// `https` feature is enabled) will be loaded from the web via `fetch` (wasm) or `ureq` (native).
///
/// Example usage:
///
/// ```rust
/// # use bevy_app::{App, Startup, TaskPoolPlugin};
/// # use bevy_ecs::prelude::{Commands, Component, Res};
/// # use bevy_asset::{Asset, AssetApp, AssetPlugin, AssetServer, Handle, io::web::WebAssetPlugin};
/// # use bevy_reflect::TypePath;
/// # struct DefaultPlugins;
/// # impl DefaultPlugins { fn set(&self, plugin: WebAssetPlugin) -> WebAssetPlugin { plugin } }
/// # #[derive(Asset, TypePath, Default)]
/// # struct Image;
/// # #[derive(Component)]
/// # struct Sprite;
/// # impl Sprite { fn from_image(_: Handle<Image>) -> Self { Sprite } }
/// # fn main() {
/// App::new()
/// .add_plugins(DefaultPlugins.set(WebAssetPlugin {
/// silence_startup_warning: true,
/// }))
/// # .add_plugins((TaskPoolPlugin::default(), AssetPlugin::default()))
/// # .init_asset::<Image>()
/// # .add_systems(Startup, setup).run();
/// # }
/// // ...
/// # fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
/// commands.spawn(Sprite::from_image(asset_server.load("https://example.com/favicon.png")));
/// # }
/// ```
///
/// By default, `ureq`'s HTTP compression is disabled. To enable gzip and brotli decompression, add
/// the following dependency and features to your Cargo.toml. This will improve bandwidth
/// utilization when its supported by the server.
///
/// ```toml
/// [target.'cfg(not(target_family = "wasm"))'.dev-dependencies]
/// ureq = { version = "3", default-features = false, features = ["gzip", "brotli"] }
/// ```
#[derive(Default)]
pub struct WebAssetPlugin {
pub silence_startup_warning: bool,
}
impl Plugin for WebAssetPlugin {
fn build(&self, app: &mut App) {
if !self.silence_startup_warning {
warn!("WebAssetPlugin is potentially insecure! Make sure to verify asset URLs are safe to load before loading them. \
If you promise you know what you're doing, you can silence this warning by setting silence_startup_warning: true \
in the WebAssetPlugin construction.");
}
if app.is_plugin_added::<AssetPlugin>() {
warn!("WebAssetPlugin must be added before AssetPlugin for it to work!");
}
#[cfg(feature = "http")]
app.register_asset_source(
"http",
AssetSourceBuilder::new(move || Box::new(WebAssetReader::Http))
.with_processed_reader(move || Box::new(WebAssetReader::Http)),
);
#[cfg(feature = "https")]
app.register_asset_source(
"https",
AssetSourceBuilder::new(move || Box::new(WebAssetReader::Https))
.with_processed_reader(move || Box::new(WebAssetReader::Https)),
);
}
}
/// Asset reader that treats paths as urls to load assets from.
pub enum WebAssetReader {
/// Unencrypted connections.
Http,
/// Use TLS for setting up connections.
Https,
}
impl WebAssetReader {
fn make_uri(&self, path: &Path) -> PathBuf {
let prefix = match self {
Self::Http => "http://",
Self::Https => "https://",
};
PathBuf::from(prefix).join(path)
}
/// See [`io::get_meta_path`](`crate::io::get_meta_path`)
fn make_meta_uri(&self, path: &Path) -> PathBuf {
let meta_path = crate::io::get_meta_path(path);
self.make_uri(&meta_path)
}
}
#[cfg(target_arch = "wasm32")]
async fn get<'a>(path: PathBuf) -> Result<Box<dyn Reader>, AssetReaderError> {
use crate::io::wasm::HttpWasmAssetReader;
HttpWasmAssetReader::new("")
.fetch_bytes(path)
.await
.map(|r| Box::new(r) as Box<dyn Reader>)
}
#[cfg(not(target_arch = "wasm32"))]
async fn get(path: PathBuf) -> Result<Box<dyn Reader>, AssetReaderError> {
use crate::io::VecReader;
use alloc::{borrow::ToOwned, boxed::Box, vec::Vec};
use bevy_platform::sync::LazyLock;
use blocking::unblock;
use std::io::{self, BufReader, Read};
let str_path = path.to_str().ok_or_else(|| {
AssetReaderError::Io(
io::Error::other(std::format!("non-utf8 path: {}", path.display())).into(),
)
})?;
#[cfg(all(not(target_arch = "wasm32"), feature = "web_asset_cache"))]
if let Some(data) = web_asset_cache::try_load_from_cache(str_path).await? {
return Ok(Box::new(VecReader::new(data)));
}
use ureq::tls::{RootCerts, TlsConfig};
use ureq::Agent;
static AGENT: LazyLock<Agent> = LazyLock::new(|| {
Agent::config_builder()
.tls_config(
TlsConfig::builder()
.root_certs(RootCerts::PlatformVerifier)
.build(),
)
.build()
.new_agent()
});
let uri = str_path.to_owned();
// Use [`unblock`] to run the http request on a separately spawned thread as to not block bevy's
// async executor.
let response = unblock(|| AGENT.get(uri).call()).await;
match response {
Ok(mut response) => {
let mut reader = BufReader::new(response.body_mut().with_config().reader());
let mut buffer = Vec::new();
reader.read_to_end(&mut buffer)?;
#[cfg(all(not(target_arch = "wasm32"), feature = "web_asset_cache"))]
web_asset_cache::save_to_cache(str_path, &buffer).await?;
Ok(Box::new(VecReader::new(buffer)))
}
// ureq considers all >=400 status codes as errors
Err(ureq::Error::StatusCode(code)) => {
if code == 404 {
Err(AssetReaderError::NotFound(path))
} else {
Err(AssetReaderError::HttpError(code))
}
}
Err(err) => Err(AssetReaderError::Io(
io::Error::other(std::format!(
"unexpected error while loading asset {}: {}",
path.display(),
err
))
.into(),
)),
}
}
impl AssetReader for WebAssetReader {
fn read<'a>(
&'a self,
path: &'a Path,
_required_features: ReaderRequiredFeatures,
) -> impl ConditionalSendFuture<Output = Result<Box<dyn Reader>, AssetReaderError>> {
get(self.make_uri(path))
}
async fn read_meta<'a>(&'a self, path: &'a Path) -> Result<Box<dyn Reader>, AssetReaderError> {
let uri = self.make_meta_uri(path);
get(uri).await
}
async fn is_directory<'a>(&'a self, _path: &'a Path) -> Result<bool, AssetReaderError> {
Ok(false)
}
async fn read_directory<'a>(
&'a self,
path: &'a Path,
) -> Result<Box<PathStream>, AssetReaderError> {
Err(AssetReaderError::NotFound(self.make_uri(path)))
}
}
/// A naive implementation of a cache for assets downloaded from the web that never invalidates.
/// `ureq` currently does not support caching, so this is a simple workaround.
/// It should eventually be replaced by `http-cache` or similar, see [tracking issue](https://github.com/06chaynes/http-cache/issues/91)
#[cfg(all(not(target_arch = "wasm32"), feature = "web_asset_cache"))]
mod web_asset_cache {
use alloc::string::String;
use alloc::vec::Vec;
use core::hash::{Hash, Hasher};
use futures_lite::AsyncWriteExt;
use std::collections::hash_map::DefaultHasher;
use std::io;
use std::path::PathBuf;
use crate::io::Reader;
const CACHE_DIR: &str = ".web-asset-cache";
fn url_to_hash(url: &str) -> String {
let mut hasher = DefaultHasher::new();
url.hash(&mut hasher);
std::format!("{:x}", hasher.finish())
}
pub async fn try_load_from_cache(url: &str) -> Result<Option<Vec<u8>>, io::Error> {
let filename = url_to_hash(url);
let cache_path = PathBuf::from(CACHE_DIR).join(&filename);
if cache_path.exists() {
let mut file = async_fs::File::open(&cache_path).await?;
let mut buffer = Vec::new();
file.read_to_end(&mut buffer).await?;
Ok(Some(buffer))
} else {
Ok(None)
}
}
pub async fn save_to_cache(url: &str, data: &[u8]) -> Result<(), io::Error> {
let filename = url_to_hash(url);
let cache_path = PathBuf::from(CACHE_DIR).join(&filename);
async_fs::create_dir_all(CACHE_DIR).await.ok();
let mut cache_file = async_fs::File::create(&cache_path).await?;
cache_file.write_all(data).await?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn make_http_uri() {
assert_eq!(
WebAssetReader::Http
.make_uri(Path::new("example.com/favicon.png"))
.to_str()
.unwrap(),
"http://example.com/favicon.png"
);
}
#[test]
fn make_https_uri() {
assert_eq!(
WebAssetReader::Https
.make_uri(Path::new("example.com/favicon.png"))
.to_str()
.unwrap(),
"https://example.com/favicon.png"
);
}
#[test]
fn make_http_meta_uri() {
assert_eq!(
WebAssetReader::Http
.make_meta_uri(Path::new("example.com/favicon.png"))
.to_str()
.unwrap(),
"http://example.com/favicon.png.meta"
);
}
#[test]
fn make_https_meta_uri() {
assert_eq!(
WebAssetReader::Https
.make_meta_uri(Path::new("example.com/favicon.png"))
.to_str()
.unwrap(),
"https://example.com/favicon.png.meta"
);
}
#[test]
fn make_https_without_extension_meta_uri() {
assert_eq!(
WebAssetReader::Https
.make_meta_uri(Path::new("example.com/favicon"))
.to_str()
.unwrap(),
"https://example.com/favicon.meta"
);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/io/wasm.rs | crates/bevy_asset/src/io/wasm.rs | use crate::io::{
get_meta_path, AssetReader, AssetReaderError, EmptyPathStream, PathStream, Reader,
ReaderRequiredFeatures, VecReader,
};
use alloc::{borrow::ToOwned, boxed::Box, format};
use js_sys::{Uint8Array, JSON};
use std::path::{Path, PathBuf};
use tracing::error;
use wasm_bindgen::{prelude::wasm_bindgen, JsCast, JsValue};
use wasm_bindgen_futures::JsFuture;
use web_sys::Response;
/// Represents the global object in the JavaScript context
#[wasm_bindgen]
extern "C" {
/// The [Global](https://developer.mozilla.org/en-US/docs/Glossary/Global_object) object.
type Global;
/// The [window](https://developer.mozilla.org/en-US/docs/Web/API/Window) global object.
#[wasm_bindgen(method, getter, js_name = Window)]
fn window(this: &Global) -> JsValue;
/// The [WorkerGlobalScope](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope) global object.
#[wasm_bindgen(method, getter, js_name = WorkerGlobalScope)]
fn worker(this: &Global) -> JsValue;
}
/// Reader implementation for loading assets via HTTP in Wasm.
pub struct HttpWasmAssetReader {
root_path: PathBuf,
}
impl HttpWasmAssetReader {
/// Creates a new `WasmAssetReader`. The path provided will be used to build URLs to query for assets.
pub fn new<P: AsRef<Path>>(path: P) -> Self {
Self {
root_path: path.as_ref().to_owned(),
}
}
}
fn js_value_to_err(context: &str) -> impl FnOnce(JsValue) -> std::io::Error + '_ {
move |value| {
let message = match JSON::stringify(&value) {
Ok(js_str) => format!("Failed to {context}: {js_str}"),
Err(_) => {
format!("Failed to {context} and also failed to stringify the JSValue of the error")
}
};
std::io::Error::other(message)
}
}
impl HttpWasmAssetReader {
// Also used by [`WebAssetReader`](crate::web::WebAssetReader)
pub(crate) async fn fetch_bytes(
&self,
path: PathBuf,
) -> Result<impl Reader + use<>, AssetReaderError> {
// The JS global scope includes a self-reference via a specializing name, which can be used to determine the type of global context available.
let global: Global = js_sys::global().unchecked_into();
let promise = if !global.window().is_undefined() {
let window: web_sys::Window = global.unchecked_into();
window.fetch_with_str(path.to_str().unwrap())
} else if !global.worker().is_undefined() {
let worker: web_sys::WorkerGlobalScope = global.unchecked_into();
worker.fetch_with_str(path.to_str().unwrap())
} else {
let error = std::io::Error::other("Unsupported JavaScript global context");
return Err(AssetReaderError::Io(error.into()));
};
let resp_value = JsFuture::from(promise)
.await
.map_err(js_value_to_err("fetch path"))?;
let resp = resp_value
.dyn_into::<Response>()
.map_err(js_value_to_err("convert fetch to Response"))?;
match resp.status() {
200 => {
let data = JsFuture::from(resp.array_buffer().unwrap()).await.unwrap();
let bytes = Uint8Array::new(&data).to_vec();
let reader = VecReader::new(bytes);
Ok(reader)
}
// Some web servers, including itch.io's CDN, return 403 when a requested file isn't present.
// TODO: remove handling of 403 as not found when it's easier to configure
// see https://github.com/bevyengine/bevy/pull/19268#pullrequestreview-2882410105
403 | 404 => Err(AssetReaderError::NotFound(path)),
status => Err(AssetReaderError::HttpError(status)),
}
}
}
impl AssetReader for HttpWasmAssetReader {
async fn read<'a>(
&'a self,
path: &'a Path,
_required_features: ReaderRequiredFeatures,
) -> Result<impl Reader + 'a, AssetReaderError> {
let path = self.root_path.join(path);
self.fetch_bytes(path).await
}
async fn read_meta<'a>(&'a self, path: &'a Path) -> Result<impl Reader + 'a, AssetReaderError> {
let meta_path = get_meta_path(&self.root_path.join(path));
self.fetch_bytes(meta_path).await
}
async fn read_directory<'a>(
&'a self,
_path: &'a Path,
) -> Result<Box<PathStream>, AssetReaderError> {
let stream: Box<PathStream> = Box::new(EmptyPathStream);
error!("Reading directories is not supported with the HttpWasmAssetReader");
Ok(stream)
}
async fn is_directory<'a>(&'a self, _path: &'a Path) -> Result<bool, AssetReaderError> {
error!("Reading directories is not supported with the HttpWasmAssetReader");
Ok(false)
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/io/gated.rs | crates/bevy_asset/src/io/gated.rs | use crate::io::{AssetReader, AssetReaderError, PathStream, Reader, ReaderRequiredFeatures};
use alloc::{boxed::Box, sync::Arc};
use async_channel::{Receiver, Sender};
use bevy_platform::{collections::HashMap, sync::RwLock};
use std::{path::Path, sync::PoisonError};
/// A "gated" reader that will prevent asset reads from returning until
/// a given path has been "opened" using [`GateOpener`].
///
/// This is built primarily for unit tests.
pub struct GatedReader<R: AssetReader> {
reader: R,
gates: Arc<RwLock<HashMap<Box<Path>, (Sender<()>, Receiver<()>)>>>,
}
impl<R: AssetReader + Clone> Clone for GatedReader<R> {
fn clone(&self) -> Self {
Self {
reader: self.reader.clone(),
gates: self.gates.clone(),
}
}
}
/// Opens path "gates" for a [`GatedReader`].
pub struct GateOpener {
gates: Arc<RwLock<HashMap<Box<Path>, (Sender<()>, Receiver<()>)>>>,
}
impl GateOpener {
/// Opens the `path` "gate", allowing a _single_ [`AssetReader`] operation to return for that path.
/// If multiple operations are expected, call `open` the expected number of calls.
pub fn open<P: AsRef<Path>>(&self, path: P) {
let mut gates = self.gates.write().unwrap_or_else(PoisonError::into_inner);
let gates = gates
.entry_ref(path.as_ref())
.or_insert_with(async_channel::unbounded);
gates.0.send_blocking(()).unwrap();
}
}
impl<R: AssetReader> GatedReader<R> {
/// Creates a new [`GatedReader`], which wraps the given `reader`. Also returns a [`GateOpener`] which
/// can be used to open "path gates" for this [`GatedReader`].
pub fn new(reader: R) -> (Self, GateOpener) {
let gates = Arc::new(RwLock::new(HashMap::default()));
(
Self {
reader,
gates: gates.clone(),
},
GateOpener { gates },
)
}
}
impl<R: AssetReader> AssetReader for GatedReader<R> {
async fn read<'a>(
&'a self,
path: &'a Path,
required_features: ReaderRequiredFeatures,
) -> Result<impl Reader + 'a, AssetReaderError> {
let receiver = {
let mut gates = self.gates.write().unwrap_or_else(PoisonError::into_inner);
let gates = gates
.entry_ref(path.as_ref())
.or_insert_with(async_channel::unbounded);
gates.1.clone()
};
receiver.recv().await.unwrap();
let result = self.reader.read(path, required_features).await?;
Ok(result)
}
async fn read_meta<'a>(&'a self, path: &'a Path) -> Result<impl Reader + 'a, AssetReaderError> {
self.reader.read_meta(path).await
}
async fn read_directory<'a>(
&'a self,
path: &'a Path,
) -> Result<Box<PathStream>, AssetReaderError> {
self.reader.read_directory(path).await
}
async fn is_directory<'a>(&'a self, path: &'a Path) -> Result<bool, AssetReaderError> {
self.reader.is_directory(path).await
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/io/file/file_watcher.rs | crates/bevy_asset/src/io/file/file_watcher.rs | use crate::{
io::{AssetSourceEvent, AssetWatcher},
path::normalize_path,
};
use alloc::{borrow::ToOwned, vec::Vec};
use async_channel::Sender;
use core::time::Duration;
use notify_debouncer_full::{
new_debouncer,
notify::{
self,
event::{AccessKind, AccessMode, CreateKind, ModifyKind, RemoveKind, RenameMode},
RecommendedWatcher, RecursiveMode,
},
DebounceEventResult, Debouncer, RecommendedCache,
};
use std::path::{Path, PathBuf};
use tracing::error;
/// An [`AssetWatcher`] that watches the filesystem for changes to asset files in a given root folder and emits [`AssetSourceEvent`]
/// for each relevant change.
///
/// This uses [`notify_debouncer_full`] to retrieve "debounced" filesystem events.
/// "Debouncing" defines a time window to hold on to events and then removes duplicate events that fall into this window.
/// This introduces a small delay in processing events, but it helps reduce event duplicates. A small delay is also necessary
/// on some systems to avoid processing a change event before it has actually been applied.
pub struct FileWatcher {
_watcher: Debouncer<RecommendedWatcher, RecommendedCache>,
}
impl FileWatcher {
/// Creates a new [`FileWatcher`] that watches for changes to the asset files in the given `path`.
pub fn new(
path: PathBuf,
sender: Sender<AssetSourceEvent>,
debounce_wait_time: Duration,
) -> Result<Self, notify::Error> {
let root = make_absolute_path(&path)?;
let watcher = new_asset_event_debouncer(
path.clone(),
debounce_wait_time,
FileEventHandler {
root,
sender,
last_event: None,
},
)?;
Ok(FileWatcher { _watcher: watcher })
}
}
impl AssetWatcher for FileWatcher {}
/// Converts the provided path into an absolute one.
fn make_absolute_path(path: &Path) -> Result<PathBuf, std::io::Error> {
// We use `normalize` + `absolute` instead of `canonicalize` to avoid reading the filesystem to
// resolve the path. This also means that paths that no longer exist can still become absolute
// (e.g., a file that was renamed will have the "old" path no longer exist).
Ok(normalize_path(&std::path::absolute(path)?))
}
pub(crate) fn get_asset_path(root: &Path, absolute_path: &Path) -> (PathBuf, bool) {
let relative_path = absolute_path.strip_prefix(root).unwrap_or_else(|_| {
panic!(
"FileWatcher::get_asset_path() failed to strip prefix from absolute path: absolute_path={}, root={}",
absolute_path.display(),
root.display()
)
});
let is_meta = relative_path.extension().is_some_and(|e| e == "meta");
let asset_path = if is_meta {
relative_path.with_extension("")
} else {
relative_path.to_owned()
};
(asset_path, is_meta)
}
/// This is a bit more abstracted than it normally would be because we want to try _very hard_ not to duplicate this
/// event management logic across filesystem-driven [`AssetWatcher`] impls. Each operating system / platform behaves
/// a little differently and this is the result of a delicate balancing act that we should only perform once.
pub(crate) fn new_asset_event_debouncer(
root: PathBuf,
debounce_wait_time: Duration,
mut handler: impl FilesystemEventHandler,
) -> Result<Debouncer<RecommendedWatcher, RecommendedCache>, notify::Error> {
let root = super::get_base_path().join(root);
let mut debouncer = new_debouncer(
debounce_wait_time,
None,
move |result: DebounceEventResult| {
match result {
Ok(events) => {
handler.begin();
for event in events.iter() {
// Make all the paths absolute here so we don't need to do it in each
// handler.
let paths = event
.paths
.iter()
.map(PathBuf::as_path)
.map(|p| {
make_absolute_path(p).expect("paths from the debouncer are valid")
})
.collect::<Vec<_>>();
match event.kind {
notify::EventKind::Create(CreateKind::File) => {
if let Some((path, is_meta)) = handler.get_path(&paths[0]) {
if is_meta {
handler.handle(&paths, AssetSourceEvent::AddedMeta(path));
} else {
handler.handle(&paths, AssetSourceEvent::AddedAsset(path));
}
}
}
notify::EventKind::Create(CreateKind::Folder) => {
if let Some((path, _)) = handler.get_path(&paths[0]) {
handler.handle(&paths, AssetSourceEvent::AddedFolder(path));
}
}
notify::EventKind::Access(AccessKind::Close(AccessMode::Write)) => {
if let Some((path, is_meta)) = handler.get_path(&paths[0]) {
if is_meta {
handler
.handle(&paths, AssetSourceEvent::ModifiedMeta(path));
} else {
handler
.handle(&paths, AssetSourceEvent::ModifiedAsset(path));
}
}
}
// Because this is debounced over a reasonable period of time, Modify(ModifyKind::Name(RenameMode::From)
// events are assumed to be "dangling" without a follow up "To" event. Without debouncing, "From" -> "To" -> "Both"
// events are emitted for renames. If a From is dangling, it is assumed to be "removed" from the context of the asset
// system.
notify::EventKind::Remove(RemoveKind::Any)
| notify::EventKind::Modify(ModifyKind::Name(RenameMode::From)) => {
if let Some((path, is_meta)) = handler.get_path(&paths[0]) {
handler.handle(
&paths,
AssetSourceEvent::RemovedUnknown { path, is_meta },
);
}
}
notify::EventKind::Create(CreateKind::Any)
| notify::EventKind::Modify(ModifyKind::Name(RenameMode::To)) => {
if let Some((path, is_meta)) = handler.get_path(&paths[0]) {
let asset_event = if paths[0].is_dir() {
AssetSourceEvent::AddedFolder(path)
} else if is_meta {
AssetSourceEvent::AddedMeta(path)
} else {
AssetSourceEvent::AddedAsset(path)
};
handler.handle(&paths, asset_event);
}
}
notify::EventKind::Modify(ModifyKind::Name(RenameMode::Both)) => {
let Some((old_path, old_is_meta)) = handler.get_path(&paths[0])
else {
continue;
};
let Some((new_path, new_is_meta)) = handler.get_path(&paths[1])
else {
continue;
};
// only the new "real" path is considered a directory
if paths[1].is_dir() {
handler.handle(
&paths,
AssetSourceEvent::RenamedFolder {
old: old_path,
new: new_path,
},
);
} else {
match (old_is_meta, new_is_meta) {
(true, true) => {
handler.handle(
&paths,
AssetSourceEvent::RenamedMeta {
old: old_path,
new: new_path,
},
);
}
(false, false) => {
handler.handle(
&paths,
AssetSourceEvent::RenamedAsset {
old: old_path,
new: new_path,
},
);
}
(true, false) => {
error!(
"Asset metafile {old_path:?} was changed to asset file {new_path:?}, which is not supported. Try restarting your app to see if configuration is still valid"
);
}
(false, true) => {
error!(
"Asset file {old_path:?} was changed to meta file {new_path:?}, which is not supported. Try restarting your app to see if configuration is still valid"
);
}
}
}
}
notify::EventKind::Modify(_) => {
let Some((path, is_meta)) = handler.get_path(&paths[0]) else {
continue;
};
if paths[0].is_dir() {
// modified folder means nothing in this case
} else if is_meta {
handler.handle(&paths, AssetSourceEvent::ModifiedMeta(path));
} else {
handler.handle(&paths, AssetSourceEvent::ModifiedAsset(path));
};
}
notify::EventKind::Remove(RemoveKind::File) => {
let Some((path, is_meta)) = handler.get_path(&paths[0]) else {
continue;
};
if is_meta {
handler.handle(&paths, AssetSourceEvent::RemovedMeta(path));
} else {
handler.handle(&paths, AssetSourceEvent::RemovedAsset(path));
}
}
notify::EventKind::Remove(RemoveKind::Folder) => {
let Some((path, _)) = handler.get_path(&paths[0]) else {
continue;
};
handler.handle(&paths, AssetSourceEvent::RemovedFolder(path));
}
_ => {}
}
}
}
Err(errors) => errors.iter().for_each(|error| {
error!("Encountered a filesystem watcher error {error:?}");
}),
}
},
)?;
debouncer.watch(&root, RecursiveMode::Recursive)?;
Ok(debouncer)
}
pub(crate) struct FileEventHandler {
sender: Sender<AssetSourceEvent>,
root: PathBuf,
last_event: Option<AssetSourceEvent>,
}
impl FilesystemEventHandler for FileEventHandler {
fn begin(&mut self) {
self.last_event = None;
}
fn get_path(&self, absolute_path: &Path) -> Option<(PathBuf, bool)> {
Some(get_asset_path(&self.root, absolute_path))
}
fn handle(&mut self, _absolute_paths: &[PathBuf], event: AssetSourceEvent) {
if self.last_event.as_ref() != Some(&event) {
self.last_event = Some(event.clone());
self.sender.send_blocking(event).unwrap();
}
}
}
pub(crate) trait FilesystemEventHandler: Send + Sync + 'static {
/// Called each time a set of debounced events is processed
fn begin(&mut self);
/// Returns an actual asset path (if one exists for the given `absolute_path`), as well as a [`bool`] that is
/// true if the `absolute_path` corresponds to a meta file.
fn get_path(&self, absolute_path: &Path) -> Option<(PathBuf, bool)>;
/// Handle the given event
fn handle(&mut self, absolute_paths: &[PathBuf], event: AssetSourceEvent);
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/io/file/file_asset.rs | crates/bevy_asset/src/io/file/file_asset.rs | use crate::io::{
get_meta_path, AssetReader, AssetReaderError, AssetWriter, AssetWriterError, PathStream,
Reader, ReaderRequiredFeatures, Writer,
};
use async_fs::{read_dir, File};
use futures_lite::StreamExt;
use alloc::{borrow::ToOwned, boxed::Box};
use std::path::Path;
use super::{FileAssetReader, FileAssetWriter};
impl Reader for File {}
impl AssetReader for FileAssetReader {
async fn read<'a>(
&'a self,
path: &'a Path,
_required_features: ReaderRequiredFeatures,
) -> Result<impl Reader + 'a, AssetReaderError> {
let full_path = self.root_path.join(path);
File::open(&full_path).await.map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
AssetReaderError::NotFound(full_path)
} else {
e.into()
}
})
}
async fn read_meta<'a>(&'a self, path: &'a Path) -> Result<impl Reader + 'a, AssetReaderError> {
let meta_path = get_meta_path(path);
let full_path = self.root_path.join(meta_path);
File::open(&full_path).await.map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
AssetReaderError::NotFound(full_path)
} else {
e.into()
}
})
}
async fn read_directory<'a>(
&'a self,
path: &'a Path,
) -> Result<Box<PathStream>, AssetReaderError> {
let full_path = self.root_path.join(path);
match read_dir(&full_path).await {
Ok(read_dir) => {
let root_path = self.root_path.clone();
let mapped_stream = read_dir.filter_map(move |f| {
f.ok().and_then(|dir_entry| {
let path = dir_entry.path();
// filter out meta files as they are not considered assets
if let Some(ext) = path.extension().and_then(|e| e.to_str())
&& ext.eq_ignore_ascii_case("meta")
{
return None;
}
// filter out hidden files. they are not listed by default but are directly targetable
if path
.file_name()
.and_then(|file_name| file_name.to_str())
.map(|file_name| file_name.starts_with('.'))
.unwrap_or_default()
{
return None;
}
let relative_path = path.strip_prefix(&root_path).unwrap();
Some(relative_path.to_owned())
})
});
let read_dir: Box<PathStream> = Box::new(mapped_stream);
Ok(read_dir)
}
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
Err(AssetReaderError::NotFound(full_path))
} else {
Err(e.into())
}
}
}
}
async fn is_directory<'a>(&'a self, path: &'a Path) -> Result<bool, AssetReaderError> {
let full_path = self.root_path.join(path);
let metadata = full_path
.metadata()
.map_err(|_e| AssetReaderError::NotFound(path.to_owned()))?;
Ok(metadata.file_type().is_dir())
}
}
impl AssetWriter for FileAssetWriter {
async fn write<'a>(&'a self, path: &'a Path) -> Result<Box<Writer>, AssetWriterError> {
let full_path = self.root_path.join(path);
if let Some(parent) = full_path.parent() {
async_fs::create_dir_all(parent).await?;
}
let file = File::create(&full_path).await?;
let writer: Box<Writer> = Box::new(file);
Ok(writer)
}
async fn write_meta<'a>(&'a self, path: &'a Path) -> Result<Box<Writer>, AssetWriterError> {
let meta_path = get_meta_path(path);
let full_path = self.root_path.join(meta_path);
if let Some(parent) = full_path.parent() {
async_fs::create_dir_all(parent).await?;
}
let file = File::create(&full_path).await?;
let writer: Box<Writer> = Box::new(file);
Ok(writer)
}
async fn remove<'a>(&'a self, path: &'a Path) -> Result<(), AssetWriterError> {
let full_path = self.root_path.join(path);
async_fs::remove_file(full_path).await?;
Ok(())
}
async fn remove_meta<'a>(&'a self, path: &'a Path) -> Result<(), AssetWriterError> {
let meta_path = get_meta_path(path);
let full_path = self.root_path.join(meta_path);
async_fs::remove_file(full_path).await?;
Ok(())
}
async fn rename<'a>(
&'a self,
old_path: &'a Path,
new_path: &'a Path,
) -> Result<(), AssetWriterError> {
let full_old_path = self.root_path.join(old_path);
let full_new_path = self.root_path.join(new_path);
if let Some(parent) = full_new_path.parent() {
async_fs::create_dir_all(parent).await?;
}
async_fs::rename(full_old_path, full_new_path).await?;
Ok(())
}
async fn rename_meta<'a>(
&'a self,
old_path: &'a Path,
new_path: &'a Path,
) -> Result<(), AssetWriterError> {
let old_meta_path = get_meta_path(old_path);
let new_meta_path = get_meta_path(new_path);
let full_old_path = self.root_path.join(old_meta_path);
let full_new_path = self.root_path.join(new_meta_path);
if let Some(parent) = full_new_path.parent() {
async_fs::create_dir_all(parent).await?;
}
async_fs::rename(full_old_path, full_new_path).await?;
Ok(())
}
async fn create_directory<'a>(&'a self, path: &'a Path) -> Result<(), AssetWriterError> {
let full_path = self.root_path.join(path);
async_fs::create_dir_all(full_path).await?;
Ok(())
}
async fn remove_directory<'a>(&'a self, path: &'a Path) -> Result<(), AssetWriterError> {
let full_path = self.root_path.join(path);
async_fs::remove_dir_all(full_path).await?;
Ok(())
}
async fn remove_empty_directory<'a>(&'a self, path: &'a Path) -> Result<(), AssetWriterError> {
let full_path = self.root_path.join(path);
async_fs::remove_dir(full_path).await?;
Ok(())
}
async fn remove_assets_in_directory<'a>(
&'a self,
path: &'a Path,
) -> Result<(), AssetWriterError> {
let full_path = self.root_path.join(path);
async_fs::remove_dir_all(&full_path).await?;
async_fs::create_dir_all(&full_path).await?;
Ok(())
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/io/file/sync_file_asset.rs | crates/bevy_asset/src/io/file/sync_file_asset.rs | use futures_io::{AsyncRead, AsyncWrite};
use futures_lite::Stream;
use crate::io::{
get_meta_path, AssetReader, AssetReaderError, AssetWriter, AssetWriterError, AsyncSeek,
PathStream, Reader, ReaderRequiredFeatures, Writer,
};
use alloc::{borrow::ToOwned, boxed::Box, vec::Vec};
use core::{pin::Pin, task::Poll};
use std::{
fs::{read_dir, File},
io::{Read, Seek, SeekFrom, Write},
path::{Path, PathBuf},
};
use super::{FileAssetReader, FileAssetWriter};
struct FileReader(File);
impl AsyncRead for FileReader {
fn poll_read(
self: Pin<&mut Self>,
_cx: &mut core::task::Context<'_>,
buf: &mut [u8],
) -> Poll<std::io::Result<usize>> {
let this = self.get_mut();
let read = this.0.read(buf);
Poll::Ready(read)
}
}
impl AsyncSeek for FileReader {
fn poll_seek(
mut self: Pin<&mut Self>,
_cx: &mut core::task::Context<'_>,
pos: SeekFrom,
) -> Poll<std::io::Result<u64>> {
Poll::Ready(self.0.seek(pos))
}
}
impl Reader for FileReader {
fn read_to_end<'a>(
&'a mut self,
buf: &'a mut Vec<u8>,
) -> stackfuture::StackFuture<'a, std::io::Result<usize>, { crate::io::STACK_FUTURE_SIZE }>
{
stackfuture::StackFuture::from(async { self.0.read_to_end(buf) })
}
}
struct FileWriter(File);
impl AsyncWrite for FileWriter {
fn poll_write(
self: Pin<&mut Self>,
_cx: &mut core::task::Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
let this = self.get_mut();
let wrote = this.0.write(buf);
Poll::Ready(wrote)
}
fn poll_flush(
self: Pin<&mut Self>,
_cx: &mut core::task::Context<'_>,
) -> Poll<std::io::Result<()>> {
let this = self.get_mut();
let flushed = this.0.flush();
Poll::Ready(flushed)
}
fn poll_close(
self: Pin<&mut Self>,
_cx: &mut core::task::Context<'_>,
) -> Poll<std::io::Result<()>> {
Poll::Ready(Ok(()))
}
}
struct DirReader(Vec<PathBuf>);
impl Stream for DirReader {
type Item = PathBuf;
fn poll_next(
self: Pin<&mut Self>,
_cx: &mut core::task::Context<'_>,
) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
Poll::Ready(this.0.pop())
}
}
impl AssetReader for FileAssetReader {
async fn read<'a>(
&'a self,
path: &'a Path,
_required_features: ReaderRequiredFeatures,
) -> Result<impl Reader + 'a, AssetReaderError> {
let full_path = self.root_path.join(path);
match File::open(&full_path) {
Ok(file) => Ok(FileReader(file)),
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
Err(AssetReaderError::NotFound(full_path))
} else {
Err(e.into())
}
}
}
}
async fn read_meta<'a>(&'a self, path: &'a Path) -> Result<impl Reader + 'a, AssetReaderError> {
let meta_path = get_meta_path(path);
let full_path = self.root_path.join(meta_path);
match File::open(&full_path) {
Ok(file) => Ok(FileReader(file)),
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
Err(AssetReaderError::NotFound(full_path))
} else {
Err(e.into())
}
}
}
}
async fn read_directory<'a>(
&'a self,
path: &'a Path,
) -> Result<Box<PathStream>, AssetReaderError> {
let full_path = self.root_path.join(path);
match read_dir(&full_path) {
Ok(read_dir) => {
let root_path = self.root_path.clone();
let mapped_stream = read_dir.filter_map(move |f| {
f.ok().and_then(|dir_entry| {
let path = dir_entry.path();
// filter out meta files as they are not considered assets
if let Some(ext) = path.extension().and_then(|e| e.to_str())
&& ext.eq_ignore_ascii_case("meta")
{
return None;
}
// filter out hidden files. they are not listed by default but are directly targetable
if path
.file_name()
.and_then(|file_name| file_name.to_str())
.map(|file_name| file_name.starts_with('.'))
.unwrap_or_default()
{
return None;
}
let relative_path = path.strip_prefix(&root_path).unwrap();
Some(relative_path.to_owned())
})
});
let read_dir: Box<PathStream> = Box::new(DirReader(mapped_stream.collect()));
Ok(read_dir)
}
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
Err(AssetReaderError::NotFound(full_path))
} else {
Err(e.into())
}
}
}
}
async fn is_directory<'a>(&'a self, path: &'a Path) -> Result<bool, AssetReaderError> {
let full_path = self.root_path.join(path);
let metadata = full_path
.metadata()
.map_err(|_e| AssetReaderError::NotFound(path.to_owned()))?;
Ok(metadata.file_type().is_dir())
}
}
impl AssetWriter for FileAssetWriter {
async fn write<'a>(&'a self, path: &'a Path) -> Result<Box<Writer>, AssetWriterError> {
let full_path = self.root_path.join(path);
if let Some(parent) = full_path.parent() {
std::fs::create_dir_all(parent)?;
}
let file = File::create(&full_path)?;
let writer: Box<Writer> = Box::new(FileWriter(file));
Ok(writer)
}
async fn write_meta<'a>(&'a self, path: &'a Path) -> Result<Box<Writer>, AssetWriterError> {
let meta_path = get_meta_path(path);
let full_path = self.root_path.join(meta_path);
if let Some(parent) = full_path.parent() {
std::fs::create_dir_all(parent)?;
}
let file = File::create(&full_path)?;
let writer: Box<Writer> = Box::new(FileWriter(file));
Ok(writer)
}
async fn remove<'a>(&'a self, path: &'a Path) -> Result<(), AssetWriterError> {
let full_path = self.root_path.join(path);
std::fs::remove_file(full_path)?;
Ok(())
}
async fn remove_meta<'a>(&'a self, path: &'a Path) -> Result<(), AssetWriterError> {
let meta_path = get_meta_path(path);
let full_path = self.root_path.join(meta_path);
std::fs::remove_file(full_path)?;
Ok(())
}
async fn create_directory<'a>(&'a self, path: &'a Path) -> Result<(), AssetWriterError> {
let full_path = self.root_path.join(path);
std::fs::create_dir_all(full_path)?;
Ok(())
}
async fn remove_directory<'a>(&'a self, path: &'a Path) -> Result<(), AssetWriterError> {
let full_path = self.root_path.join(path);
std::fs::remove_dir_all(full_path)?;
Ok(())
}
async fn remove_empty_directory<'a>(&'a self, path: &'a Path) -> Result<(), AssetWriterError> {
let full_path = self.root_path.join(path);
std::fs::remove_dir(full_path)?;
Ok(())
}
async fn remove_assets_in_directory<'a>(
&'a self,
path: &'a Path,
) -> Result<(), AssetWriterError> {
let full_path = self.root_path.join(path);
std::fs::remove_dir_all(&full_path)?;
std::fs::create_dir_all(&full_path)?;
Ok(())
}
async fn rename<'a>(
&'a self,
old_path: &'a Path,
new_path: &'a Path,
) -> Result<(), AssetWriterError> {
let full_old_path = self.root_path.join(old_path);
let full_new_path = self.root_path.join(new_path);
if let Some(parent) = full_new_path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::rename(full_old_path, full_new_path)?;
Ok(())
}
async fn rename_meta<'a>(
&'a self,
old_path: &'a Path,
new_path: &'a Path,
) -> Result<(), AssetWriterError> {
let old_meta_path = get_meta_path(old_path);
let new_meta_path = get_meta_path(new_path);
let full_old_path = self.root_path.join(old_meta_path);
let full_new_path = self.root_path.join(new_meta_path);
if let Some(parent) = full_new_path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::rename(full_old_path, full_new_path)?;
Ok(())
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/io/file/mod.rs | crates/bevy_asset/src/io/file/mod.rs | #[cfg(feature = "file_watcher")]
mod file_watcher;
#[cfg(feature = "multi_threaded")]
mod file_asset;
#[cfg(not(feature = "multi_threaded"))]
mod sync_file_asset;
#[cfg(feature = "file_watcher")]
pub use file_watcher::*;
use tracing::{debug, error};
use alloc::borrow::ToOwned;
use std::{
env,
path::{Path, PathBuf},
};
pub(crate) fn get_base_path() -> PathBuf {
if let Ok(manifest_dir) = env::var("BEVY_ASSET_ROOT") {
PathBuf::from(manifest_dir)
} else if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
PathBuf::from(manifest_dir)
} else {
env::current_exe()
.map(|path| path.parent().map(ToOwned::to_owned).unwrap())
.unwrap()
}
}
/// I/O implementation for the local filesystem.
///
/// This asset I/O is fully featured but it's not available on `android` and `wasm` targets.
pub struct FileAssetReader {
root_path: PathBuf,
}
impl FileAssetReader {
/// Creates a new `FileAssetIo` at a path relative to the executable's directory, optionally
/// watching for changes.
///
/// See `get_base_path` below.
pub fn new<P: AsRef<Path>>(path: P) -> Self {
let root_path = Self::get_base_path().join(path.as_ref());
debug!(
"Asset Server using {} as its base path.",
root_path.display()
);
Self { root_path }
}
/// Returns the base path of the assets directory, which is normally the executable's parent
/// directory.
///
/// To change this, set [`AssetPlugin::file_path`][crate::AssetPlugin::file_path].
pub fn get_base_path() -> PathBuf {
get_base_path()
}
/// Returns the root directory where assets are loaded from.
///
/// See `get_base_path`.
pub fn root_path(&self) -> &PathBuf {
&self.root_path
}
}
/// A writer for the local filesystem.
pub struct FileAssetWriter {
root_path: PathBuf,
}
impl FileAssetWriter {
/// Creates a new [`FileAssetWriter`] at a path relative to the executable's directory, optionally
/// watching for changes.
pub fn new<P: AsRef<Path> + core::fmt::Debug>(path: P, create_root: bool) -> Self {
let root_path = get_base_path().join(path.as_ref());
if create_root && let Err(e) = std::fs::create_dir_all(&root_path) {
error!(
"Failed to create root directory {} for file asset writer: {}",
root_path.display(),
e
);
}
Self { root_path }
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/io/embedded/embedded_watcher.rs | crates/bevy_asset/src/io/embedded/embedded_watcher.rs | use crate::io::{
file::{get_asset_path, get_base_path, new_asset_event_debouncer, FilesystemEventHandler},
memory::Dir,
AssetSourceEvent, AssetWatcher,
};
use alloc::{boxed::Box, sync::Arc, vec::Vec};
use bevy_platform::collections::HashMap;
use bevy_platform::sync::{PoisonError, RwLock};
use core::time::Duration;
use notify_debouncer_full::{notify::RecommendedWatcher, Debouncer, RecommendedCache};
use std::{
fs::File,
io::{BufReader, Read},
path::{Path, PathBuf},
};
use tracing::warn;
/// A watcher for assets stored in the `embedded` asset source. Embedded assets are assets whose
/// bytes have been embedded into the Rust binary using the [`embedded_asset`](crate::embedded_asset) macro.
/// This watcher will watch for changes to the "source files", read the contents of changed files from the file system
/// and overwrite the initial static bytes of the file embedded in the binary with the new dynamically loaded bytes.
pub struct EmbeddedWatcher {
_watcher: Debouncer<RecommendedWatcher, RecommendedCache>,
}
impl EmbeddedWatcher {
/// Creates a new `EmbeddedWatcher` that watches for changes to the embedded assets in the given `dir`.
pub fn new(
dir: Dir,
root_paths: Arc<RwLock<HashMap<Box<Path>, PathBuf>>>,
sender: async_channel::Sender<AssetSourceEvent>,
debounce_wait_time: Duration,
) -> Self {
let root = get_base_path();
let handler = EmbeddedEventHandler {
dir,
root: root.clone(),
sender,
root_paths,
last_event: None,
};
let watcher = new_asset_event_debouncer(root, debounce_wait_time, handler).unwrap();
Self { _watcher: watcher }
}
}
impl AssetWatcher for EmbeddedWatcher {}
/// A [`FilesystemEventHandler`] that uses [`EmbeddedAssetRegistry`](crate::io::embedded::EmbeddedAssetRegistry) to hot-reload
/// binary-embedded Rust source files. This will read the contents of changed files from the file system and overwrite
/// the initial static bytes from the file embedded in the binary.
pub(crate) struct EmbeddedEventHandler {
sender: async_channel::Sender<AssetSourceEvent>,
root_paths: Arc<RwLock<HashMap<Box<Path>, PathBuf>>>,
root: PathBuf,
dir: Dir,
last_event: Option<AssetSourceEvent>,
}
impl FilesystemEventHandler for EmbeddedEventHandler {
fn begin(&mut self) {
self.last_event = None;
}
fn get_path(&self, absolute_path: &Path) -> Option<(PathBuf, bool)> {
let (local_path, is_meta) = get_asset_path(&self.root, absolute_path);
let final_path = self
.root_paths
.read()
.unwrap_or_else(PoisonError::into_inner)
.get(local_path.as_path())?
.clone();
if is_meta {
warn!("Meta file asset hot-reloading is not supported yet: {final_path:?}");
}
Some((final_path, false))
}
fn handle(&mut self, absolute_paths: &[PathBuf], event: AssetSourceEvent) {
if self.last_event.as_ref() != Some(&event) {
if let AssetSourceEvent::ModifiedAsset(path) = &event
&& let Ok(file) = File::open(&absolute_paths[0])
{
let mut reader = BufReader::new(file);
let mut buffer = Vec::new();
// Read file into vector.
if reader.read_to_end(&mut buffer).is_ok() {
self.dir.insert_asset(path, buffer);
}
}
self.last_event = Some(event.clone());
self.sender.send_blocking(event).unwrap();
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_asset/src/io/embedded/mod.rs | crates/bevy_asset/src/io/embedded/mod.rs | #[cfg(feature = "embedded_watcher")]
mod embedded_watcher;
#[cfg(feature = "embedded_watcher")]
pub use embedded_watcher::*;
use crate::io::{
memory::{Dir, MemoryAssetReader, Value},
AssetSourceBuilder, AssetSourceBuilders,
};
use crate::AssetServer;
use alloc::boxed::Box;
use bevy_app::App;
use bevy_ecs::{resource::Resource, world::World};
#[cfg(feature = "embedded_watcher")]
use bevy_platform::sync::{Arc, PoisonError, RwLock};
use std::path::{Path, PathBuf};
#[cfg(feature = "embedded_watcher")]
use alloc::borrow::ToOwned;
/// The name of the `embedded` [`AssetSource`](crate::io::AssetSource),
/// as stored in the [`AssetSourceBuilders`] resource.
pub const EMBEDDED: &str = "embedded";
/// A [`Resource`] that manages "rust source files" in a virtual in memory [`Dir`], which is intended
/// to be shared with a [`MemoryAssetReader`].
/// Generally this should not be interacted with directly. The [`embedded_asset`] will populate this.
///
/// [`embedded_asset`]: crate::embedded_asset
#[derive(Resource, Default)]
pub struct EmbeddedAssetRegistry {
dir: Dir,
#[cfg(feature = "embedded_watcher")]
root_paths: Arc<RwLock<bevy_platform::collections::HashMap<Box<Path>, PathBuf>>>,
}
impl EmbeddedAssetRegistry {
/// Inserts a new asset. `full_path` is the full path (as [`file`] would return for that file, if it was capable of
/// running in a non-rust file). `asset_path` is the path that will be used to identify the asset in the `embedded`
/// [`AssetSource`](crate::io::AssetSource). `value` is the bytes that will be returned for the asset. This can be
/// _either_ a `&'static [u8]` or a [`Vec<u8>`](alloc::vec::Vec).
#[cfg_attr(
not(feature = "embedded_watcher"),
expect(
unused_variables,
reason = "The `full_path` argument is not used when `embedded_watcher` is disabled."
)
)]
pub fn insert_asset(&self, full_path: PathBuf, asset_path: &Path, value: impl Into<Value>) {
#[cfg(feature = "embedded_watcher")]
self.root_paths
.write()
.unwrap_or_else(PoisonError::into_inner)
.insert(full_path.into(), asset_path.to_owned());
self.dir.insert_asset(asset_path, value);
}
/// Inserts new asset metadata. `full_path` is the full path (as [`file`] would return for that file, if it was capable of
/// running in a non-rust file). `asset_path` is the path that will be used to identify the asset in the `embedded`
/// [`AssetSource`](crate::io::AssetSource). `value` is the bytes that will be returned for the asset. This can be _either_
/// a `&'static [u8]` or a [`Vec<u8>`](alloc::vec::Vec).
#[cfg_attr(
not(feature = "embedded_watcher"),
expect(
unused_variables,
reason = "The `full_path` argument is not used when `embedded_watcher` is disabled."
)
)]
pub fn insert_meta(&self, full_path: &Path, asset_path: &Path, value: impl Into<Value>) {
#[cfg(feature = "embedded_watcher")]
self.root_paths
.write()
.unwrap_or_else(PoisonError::into_inner)
.insert(full_path.into(), asset_path.to_owned());
self.dir.insert_meta(asset_path, value);
}
/// Removes an asset stored using `full_path` (the full path as [`file`] would return for that file, if it was capable of
/// running in a non-rust file). If no asset is stored with at `full_path` its a no-op.
/// It returning `Option` contains the originally stored `Data` or `None`.
pub fn remove_asset(&self, full_path: &Path) -> Option<super::memory::Data> {
self.dir.remove_asset(full_path)
}
/// Registers the [`EMBEDDED`] [`AssetSource`](crate::io::AssetSource) with the given [`AssetSourceBuilders`].
pub fn register_source(&self, sources: &mut AssetSourceBuilders) {
let dir = self.dir.clone();
let processed_dir = self.dir.clone();
#[cfg_attr(
not(feature = "embedded_watcher"),
expect(
unused_mut,
reason = "Variable is only mutated when `embedded_watcher` feature is enabled."
)
)]
let mut source =
AssetSourceBuilder::new(move || Box::new(MemoryAssetReader { root: dir.clone() }))
.with_processed_reader(move || {
Box::new(MemoryAssetReader {
root: processed_dir.clone(),
})
})
// Note that we only add a processed watch warning because we don't want to warn
// noisily about embedded watching (which is niche) when users enable file watching.
.with_processed_watch_warning(
"Consider enabling the `embedded_watcher` cargo feature.",
);
#[cfg(feature = "embedded_watcher")]
{
let root_paths = self.root_paths.clone();
let dir = self.dir.clone();
let processed_root_paths = self.root_paths.clone();
let processed_dir = self.dir.clone();
source = source
.with_watcher(move |sender| {
Some(Box::new(EmbeddedWatcher::new(
dir.clone(),
root_paths.clone(),
sender,
core::time::Duration::from_millis(300),
)))
})
.with_processed_watcher(move |sender| {
Some(Box::new(EmbeddedWatcher::new(
processed_dir.clone(),
processed_root_paths.clone(),
sender,
core::time::Duration::from_millis(300),
)))
});
}
sources.insert(EMBEDDED, source);
}
}
/// Trait for the [`load_embedded_asset!`] macro, to access [`AssetServer`]
/// from arbitrary things.
///
/// [`load_embedded_asset!`]: crate::load_embedded_asset
pub trait GetAssetServer {
fn get_asset_server(&self) -> &AssetServer;
}
impl GetAssetServer for App {
fn get_asset_server(&self) -> &AssetServer {
self.world().get_asset_server()
}
}
impl GetAssetServer for World {
fn get_asset_server(&self) -> &AssetServer {
self.resource()
}
}
impl GetAssetServer for AssetServer {
fn get_asset_server(&self) -> &AssetServer {
self
}
}
/// Load an [embedded asset](crate::embedded_asset).
///
/// This is useful if the embedded asset in question is not publicly exposed, but
/// you need to use it internally.
///
/// # Syntax
///
/// This macro takes two arguments and an optional third one:
/// 1. The asset source. It may be `AssetServer`, `World` or `App`.
/// 2. The path to the asset to embed, as a string literal.
/// 3. Optionally, a closure of the same type as in [`AssetServer::load_with_settings`].
/// Consider explicitly typing the closure argument in case of type error.
///
/// # Usage
///
/// The advantage compared to using directly [`AssetServer::load`] is:
/// - This also accepts [`World`] and [`App`] arguments.
/// - This uses the exact same path as `embedded_asset!`, so you can keep it
/// consistent.
///
/// As a rule of thumb:
/// - If the asset in used in the same module as it is declared using `embedded_asset!`,
/// use this macro.
/// - Otherwise, use `AssetServer::load`.
#[macro_export]
macro_rules! load_embedded_asset {
(@get: $path: literal, $provider: expr) => {{
let path = $crate::embedded_path!($path);
let path = $crate::AssetPath::from_path_buf(path).with_source("embedded");
let asset_server = $crate::io::embedded::GetAssetServer::get_asset_server($provider);
(path, asset_server)
}};
($provider: expr, $path: literal, $settings: expr) => {{
let (path, asset_server) = $crate::load_embedded_asset!(@get: $path, $provider);
asset_server.load_with_settings(path, $settings)
}};
($provider: expr, $path: literal) => {{
let (path, asset_server) = $crate::load_embedded_asset!(@get: $path, $provider);
asset_server.load(path)
}};
}
/// Returns the [`Path`] for a given `embedded` asset.
/// This is used internally by [`embedded_asset`] and can be used to get a [`Path`]
/// that matches the [`AssetPath`](crate::AssetPath) used by that asset.
///
/// [`embedded_asset`]: crate::embedded_asset
#[macro_export]
macro_rules! embedded_path {
($path_str: expr) => {{
$crate::embedded_path!("src", $path_str)
}};
($source_path: expr, $path_str: expr) => {{
let crate_name = module_path!().split(':').next().unwrap();
$crate::io::embedded::_embedded_asset_path(
crate_name,
$source_path.as_ref(),
file!().as_ref(),
$path_str.as_ref(),
)
}};
}
/// Implementation detail of `embedded_path`, do not use this!
///
/// Returns an embedded asset path, given:
/// - `crate_name`: name of the crate where the asset is embedded
/// - `src_prefix`: path prefix of the crate's source directory, relative to the workspace root
/// - `file_path`: `std::file!()` path of the source file where `embedded_path!` is called
/// - `asset_path`: path of the embedded asset relative to `file_path`
#[doc(hidden)]
pub fn _embedded_asset_path(
crate_name: &str,
src_prefix: &Path,
file_path: &Path,
asset_path: &Path,
) -> PathBuf {
let file_path = if cfg!(not(target_family = "windows")) {
// Work around bug: https://github.com/bevyengine/bevy/issues/14246
// Note, this will break any paths on Linux/Mac containing "\"
PathBuf::from(file_path.to_str().unwrap().replace("\\", "/"))
} else {
PathBuf::from(file_path)
};
let mut maybe_parent = file_path.parent();
let after_src = loop {
let Some(parent) = maybe_parent else {
panic!("Failed to find src_prefix {src_prefix:?} in {file_path:?}")
};
if parent.ends_with(src_prefix) {
break file_path.strip_prefix(parent).unwrap();
}
maybe_parent = parent.parent();
};
let asset_path = after_src.parent().unwrap().join(asset_path);
Path::new(crate_name).join(asset_path)
}
/// Creates a new `embedded` asset by embedding the bytes of the given path into the current binary
/// and registering those bytes with the `embedded` [`AssetSource`](crate::io::AssetSource).
///
/// This accepts the current [`App`] as the first parameter and a path `&str` (relative to the current file) as the second.
///
/// By default this will generate an [`AssetPath`] using the following rules:
///
/// 1. Search for the first `$crate_name/src/` in the path and trim to the path past that point.
/// 2. Re-add the current `$crate_name` to the front of the path
///
/// For example, consider the following file structure in the theoretical `bevy_rock` crate, which provides a Bevy [`Plugin`](bevy_app::Plugin)
/// that renders fancy rocks for scenes.
///
/// ```text
/// bevy_rock
/// ├── src
/// │ ├── render
/// │ │ ├── rock.wgsl
/// │ │ └── mod.rs
/// │ └── lib.rs
/// └── Cargo.toml
/// ```
///
/// `rock.wgsl` is a WGSL shader asset that the `bevy_rock` plugin author wants to bundle with their crate. They invoke the following
/// in `bevy_rock/src/render/mod.rs`:
///
/// `embedded_asset!(app, "rock.wgsl")`
///
/// `rock.wgsl` can now be loaded by the [`AssetServer`] as follows:
///
/// ```no_run
/// # use bevy_asset::{Asset, AssetServer, load_embedded_asset};
/// # use bevy_reflect::TypePath;
/// # let asset_server: AssetServer = panic!();
/// # #[derive(Asset, TypePath)]
/// # struct Shader;
/// // If we are loading the shader in the same module we used `embedded_asset!`:
/// let shader = load_embedded_asset!(&asset_server, "rock.wgsl");
/// # let _: bevy_asset::Handle<Shader> = shader;
///
/// // If the goal is to expose the asset **to the end user**:
/// let shader = asset_server.load::<Shader>("embedded://bevy_rock/render/rock.wgsl");
/// ```
///
/// Some things to note in the path:
/// 1. The non-default `embedded://` [`AssetSource`](crate::io::AssetSource)
/// 2. `src` is trimmed from the path
///
/// The default behavior also works for cargo workspaces. Pretend the `bevy_rock` crate now exists in a larger workspace in
/// `$SOME_WORKSPACE/crates/bevy_rock`. The asset path would remain the same, because [`embedded_asset`] searches for the
/// _first instance_ of `bevy_rock/src` in the path.
///
/// For most "standard crate structures" the default works just fine. But for some niche cases (such as cargo examples),
/// the `src` path will not be present. You can override this behavior by adding it as the second argument to [`embedded_asset`]:
///
/// `embedded_asset!(app, "/examples/rock_stuff/", "rock.wgsl")`
///
/// When there are three arguments, the second argument will replace the default `/src/` value. Note that these two are
/// equivalent:
///
/// `embedded_asset!(app, "rock.wgsl")`
/// `embedded_asset!(app, "/src/", "rock.wgsl")`
///
/// This macro uses the [`include_bytes`] macro internally and _will not_ reallocate the bytes.
/// Generally the [`AssetPath`] generated will be predictable, but if your asset isn't
/// available for some reason, you can use the [`embedded_path`] macro to debug.
///
/// Hot-reloading `embedded` assets is supported. Just enable the `embedded_watcher` cargo feature.
///
/// [`AssetPath`]: crate::AssetPath
/// [`embedded_asset`]: crate::embedded_asset
/// [`embedded_path`]: crate::embedded_path
#[macro_export]
macro_rules! embedded_asset {
($app: expr, $path: expr) => {{
$crate::embedded_asset!($app, "src", $path)
}};
($app: expr, $source_path: expr, $path: expr) => {{
let mut embedded = $app
.world_mut()
.resource_mut::<$crate::io::embedded::EmbeddedAssetRegistry>();
let path = $crate::embedded_path!($source_path, $path);
let watched_path = $crate::io::embedded::watched_path(file!(), $path);
embedded.insert_asset(watched_path, &path, include_bytes!($path));
}};
}
/// Returns the path used by the watcher.
#[doc(hidden)]
#[cfg(feature = "embedded_watcher")]
pub fn watched_path(source_file_path: &'static str, asset_path: &'static str) -> PathBuf {
PathBuf::from(source_file_path)
.parent()
.unwrap()
.join(asset_path)
}
/// Returns an empty PathBuf.
#[doc(hidden)]
#[cfg(not(feature = "embedded_watcher"))]
pub fn watched_path(_source_file_path: &'static str, _asset_path: &'static str) -> PathBuf {
PathBuf::from("")
}
/// Loads an "internal" asset by embedding the string stored in the given `path_str` and associates it with the given handle.
#[macro_export]
macro_rules! load_internal_asset {
($app: ident, $handle: expr, $path_str: expr, $loader: expr) => {{
let mut assets = $app.world_mut().resource_mut::<$crate::Assets<_>>();
assets.insert($handle.id(), ($loader)(
include_str!($path_str),
std::path::Path::new(file!())
.parent()
.unwrap()
.join($path_str)
.to_string_lossy()
)).unwrap();
}};
// we can't support params without variadic arguments, so internal assets with additional params can't be hot-reloaded
($app: ident, $handle: ident, $path_str: expr, $loader: expr $(, $param:expr)+) => {{
let mut assets = $app.world_mut().resource_mut::<$crate::Assets<_>>();
assets.insert($handle.id(), ($loader)(
include_str!($path_str),
std::path::Path::new(file!())
.parent()
.unwrap()
.join($path_str)
.to_string_lossy(),
$($param),+
)).unwrap();
}};
}
/// Loads an "internal" binary asset by embedding the bytes stored in the given `path_str` and associates it with the given handle.
#[macro_export]
macro_rules! load_internal_binary_asset {
($app: ident, $handle: expr, $path_str: expr, $loader: expr) => {{
let mut assets = $app.world_mut().resource_mut::<$crate::Assets<_>>();
assets
.insert(
$handle.id(),
($loader)(
include_bytes!($path_str).as_ref(),
std::path::Path::new(file!())
.parent()
.unwrap()
.join($path_str)
.to_string_lossy()
.into(),
),
)
.unwrap();
}};
}
#[cfg(test)]
mod tests {
use super::{EmbeddedAssetRegistry, _embedded_asset_path};
use std::path::Path;
// Relative paths show up if this macro is being invoked by a local crate.
// In this case we know the relative path is a sub- path of the workspace
// root.
#[test]
fn embedded_asset_path_from_local_crate() {
let asset_path = _embedded_asset_path(
"my_crate",
"src".as_ref(),
"src/foo/plugin.rs".as_ref(),
"the/asset.png".as_ref(),
);
assert_eq!(asset_path, Path::new("my_crate/foo/the/asset.png"));
}
// A blank src_path removes the embedded's file path altogether only the
// asset path remains.
#[test]
fn embedded_asset_path_from_local_crate_blank_src_path_questionable() {
let asset_path = _embedded_asset_path(
"my_crate",
"".as_ref(),
"src/foo/some/deep/path/plugin.rs".as_ref(),
"the/asset.png".as_ref(),
);
assert_eq!(asset_path, Path::new("my_crate/the/asset.png"));
}
#[test]
#[should_panic(expected = "Failed to find src_prefix \"NOT-THERE\" in \"src")]
fn embedded_asset_path_from_local_crate_bad_src() {
let _asset_path = _embedded_asset_path(
"my_crate",
"NOT-THERE".as_ref(),
"src/foo/plugin.rs".as_ref(),
"the/asset.png".as_ref(),
);
}
#[test]
fn embedded_asset_path_from_local_example_crate() {
let asset_path = _embedded_asset_path(
"example_name",
"examples/foo".as_ref(),
"examples/foo/example.rs".as_ref(),
"the/asset.png".as_ref(),
);
assert_eq!(asset_path, Path::new("example_name/the/asset.png"));
}
// Absolute paths show up if this macro is being invoked by an external
// dependency, e.g. one that's being checked out from a crates repo or git.
#[test]
fn embedded_asset_path_from_external_crate() {
let asset_path = _embedded_asset_path(
"my_crate",
"src".as_ref(),
"/path/to/crate/src/foo/plugin.rs".as_ref(),
"the/asset.png".as_ref(),
);
assert_eq!(asset_path, Path::new("my_crate/foo/the/asset.png"));
}
#[test]
fn embedded_asset_path_from_external_crate_root_src_path() {
let asset_path = _embedded_asset_path(
"my_crate",
"/path/to/crate/src".as_ref(),
"/path/to/crate/src/foo/plugin.rs".as_ref(),
"the/asset.png".as_ref(),
);
assert_eq!(asset_path, Path::new("my_crate/foo/the/asset.png"));
}
// Although extraneous slashes are permitted at the end, e.g., "src////",
// one or more slashes at the beginning are not.
#[test]
#[should_panic(expected = "Failed to find src_prefix \"////src\" in")]
fn embedded_asset_path_from_external_crate_extraneous_beginning_slashes() {
let asset_path = _embedded_asset_path(
"my_crate",
"////src".as_ref(),
"/path/to/crate/src/foo/plugin.rs".as_ref(),
"the/asset.png".as_ref(),
);
assert_eq!(asset_path, Path::new("my_crate/foo/the/asset.png"));
}
// We don't handle this edge case because it is ambiguous with the
// information currently available to the embedded_path macro.
#[test]
fn embedded_asset_path_from_external_crate_is_ambiguous() {
let asset_path = _embedded_asset_path(
"my_crate",
"src".as_ref(),
"/path/to/.cargo/registry/src/crate/src/src/plugin.rs".as_ref(),
"the/asset.png".as_ref(),
);
// Really, should be "my_crate/src/the/asset.png"
assert_eq!(asset_path, Path::new("my_crate/the/asset.png"));
}
#[test]
fn remove_embedded_asset() {
let reg = EmbeddedAssetRegistry::default();
let path = std::path::PathBuf::from("a/b/asset.png");
reg.insert_asset(path.clone(), &path, &[]);
assert!(reg.dir.get_asset(&path).is_some());
assert!(reg.remove_asset(&path).is_some());
assert!(reg.dir.get_asset(&path).is_none());
assert!(reg.remove_asset(&path).is_none());
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_derive/compile_fail/src/lib.rs | crates/bevy_derive/compile_fail/src/lib.rs | // Nothing here, check out the integration tests
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_derive/compile_fail/tests/derive.rs | crates/bevy_derive/compile_fail/tests/derive.rs | fn main() -> compile_fail_utils::ui_test::Result<()> {
compile_fail_utils::test_multiple(
"derive_deref",
["tests/deref_derive", "tests/deref_mut_derive"],
)
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_derive/compile_fail/tests/deref_derive/invalid_attribute_fail.rs | crates/bevy_derive/compile_fail/tests/deref_derive/invalid_attribute_fail.rs | use bevy_derive::Deref;
// Reason: `#[deref]` doesn't take any arguments
#[derive(Deref)]
struct TupleStruct(
usize,
#[deref()] String
//~^ ERROR: unexpected token
);
#[derive(Deref)]
struct Struct {
foo: usize,
#[deref()]
//~^ ERROR: unexpected token
bar: String,
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_derive/compile_fail/tests/deref_derive/invalid_item_fail.rs | crates/bevy_derive/compile_fail/tests/deref_derive/invalid_item_fail.rs | use bevy_derive::Deref;
#[derive(Deref)]
//~^ ERROR: cannot be derived on field-less structs
struct UnitStruct;
#[derive(Deref)]
//~^ ERROR: can only be derived on structs
enum Enum {}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_derive/compile_fail/tests/deref_derive/multiple_fields_pass.rs | crates/bevy_derive/compile_fail/tests/deref_derive/multiple_fields_pass.rs | //@check-pass
use bevy_derive::Deref;
#[derive(Deref)]
struct TupleStruct(usize, #[deref] String);
#[derive(Deref)]
struct Struct {
// Works with other attributes
#[cfg(test)]
foo: usize,
#[deref]
bar: String,
/// Also works with doc comments.
baz: i32,
}
fn main() {
let value = TupleStruct(123, "Hello world!".to_string());
let _: &String = &*value;
let _ = value.0;
let value = Struct {
#[cfg(test)]
foo: 123,
bar: "Hello world!".to_string(),
baz: 321,
};
let _: &String = &*value;
let _ = value.baz;
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_derive/compile_fail/tests/deref_derive/multiple_attributes_fail.rs | crates/bevy_derive/compile_fail/tests/deref_derive/multiple_attributes_fail.rs | use bevy_derive::Deref;
#[derive(Deref)]
struct TupleStruct(
#[deref] usize,
#[deref] String
//~^ ERROR: can only be used on a single field
);
#[derive(Deref)]
struct Struct {
#[deref]
foo: usize,
#[deref]
//~^ ERROR: can only be used on a single field
bar: String,
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_derive/compile_fail/tests/deref_derive/single_field_pass.rs | crates/bevy_derive/compile_fail/tests/deref_derive/single_field_pass.rs | //@check-pass
use bevy_derive::Deref;
#[derive(Deref)]
struct TupleStruct(String);
#[derive(Deref)]
struct Struct {
bar: String,
}
fn main() {
let value = TupleStruct("Hello world!".to_string());
let _: &String = &*value;
let value = Struct {
bar: "Hello world!".to_string(),
};
let _: &String = &*value;
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_derive/compile_fail/tests/deref_derive/missing_attribute_fail.rs | crates/bevy_derive/compile_fail/tests/deref_derive/missing_attribute_fail.rs | use bevy_derive::Deref;
#[derive(Deref)]
//~^ ERROR: requires one field to have
struct TupleStruct(usize, String);
#[derive(Deref)]
//~^ ERROR: requires one field to have
struct Struct {
foo: usize,
bar: String,
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_derive/compile_fail/tests/deref_mut_derive/missing_deref_fail.rs | crates/bevy_derive/compile_fail/tests/deref_mut_derive/missing_deref_fail.rs | // I'd love to check for E0277 errors here but we can't because
// the diagnostic contains a path to the system libraries which
// isn't consistent across systems.
use bevy_derive::DerefMut;
#[derive(DerefMut)]
//~^ ERROR: trait bound
struct TupleStruct(usize, #[deref] String);
//~^ ERROR: trait bound
#[derive(DerefMut)]
//~^ ERROR: trait bound
struct Struct {
//~^ ERROR: trait bound
foo: usize,
#[deref]
bar: String,
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_derive/compile_fail/tests/deref_mut_derive/invalid_attribute_fail.rs | crates/bevy_derive/compile_fail/tests/deref_mut_derive/invalid_attribute_fail.rs | use bevy_derive::DerefMut;
use core::ops::Deref;
// Reason: `#[deref]` doesn't take any arguments
#[derive(DerefMut)]
struct TupleStruct(
usize,
#[deref()] String
//~^ ERROR: unexpected token
);
impl Deref for TupleStruct {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.1
}
}
#[derive(DerefMut)]
struct Struct {
foo: usize,
#[deref()]
//~^ ERROR: unexpected token
bar: String,
}
impl Deref for Struct {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.bar
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_derive/compile_fail/tests/deref_mut_derive/invalid_item_fail.rs | crates/bevy_derive/compile_fail/tests/deref_mut_derive/invalid_item_fail.rs | use bevy_derive::DerefMut;
#[derive(DerefMut)]
//~^ ERROR: cannot be derived on field-less structs
struct UnitStruct;
#[derive(DerefMut)]
//~^ ERROR: can only be derived on structs
enum Enum {}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_derive/compile_fail/tests/deref_mut_derive/multiple_fields_pass.rs | crates/bevy_derive/compile_fail/tests/deref_mut_derive/multiple_fields_pass.rs | //@check-pass
use bevy_derive::DerefMut;
use core::ops::Deref;
#[derive(DerefMut)]
// The first field is never read, but we want it there to check that the derive skips it.
struct TupleStruct(#[allow(dead_code)] usize, #[deref] String);
impl Deref for TupleStruct {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.1
}
}
#[derive(DerefMut)]
struct Struct {
#[allow(dead_code)]
// Same justification as above.
foo: usize,
#[deref]
bar: String,
}
impl Deref for Struct {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.bar
}
}
fn main() {
let mut value = TupleStruct(123, "Hello world!".to_string());
let _: &mut String = &mut *value;
let mut value = Struct {
foo: 123,
bar: "Hello world!".to_string(),
};
let _: &mut String = &mut *value;
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_derive/compile_fail/tests/deref_mut_derive/mismatched_target_type_fail.rs | crates/bevy_derive/compile_fail/tests/deref_mut_derive/mismatched_target_type_fail.rs | use bevy_derive::DerefMut;
use core::ops::Deref;
#[derive(DerefMut)]
//~^ E0308
struct TupleStruct(#[deref] usize, String);
impl Deref for TupleStruct {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.1
}
}
#[derive(DerefMut)]
//~^ E0308
struct Struct {
#[deref]
foo: usize,
bar: String,
}
impl Deref for Struct {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.bar
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_derive/compile_fail/tests/deref_mut_derive/multiple_attributes_fail.rs | crates/bevy_derive/compile_fail/tests/deref_mut_derive/multiple_attributes_fail.rs | use bevy_derive::DerefMut;
use core::ops::Deref;
#[derive(DerefMut)]
struct TupleStruct(
#[deref] usize,
#[deref] String
//~^ ERROR: can only be used on a single field
);
impl Deref for TupleStruct {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.1
}
}
#[derive(DerefMut)]
struct Struct {
#[deref]
foo: usize,
#[deref]
//~^ ERROR: can only be used on a single field
bar: String,
}
impl Deref for Struct {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.bar
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_derive/compile_fail/tests/deref_mut_derive/single_field_pass.rs | crates/bevy_derive/compile_fail/tests/deref_mut_derive/single_field_pass.rs | //@check-pass
use bevy_derive::DerefMut;
use core::ops::Deref;
#[derive(DerefMut)]
struct TupleStruct(#[deref] String);
impl Deref for TupleStruct {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[derive(DerefMut)]
struct Struct {
#[deref]
bar: String,
}
impl Deref for Struct {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.bar
}
}
fn main() {
let mut value = TupleStruct("Hello world!".to_string());
let _: &mut String = &mut *value;
let mut value = Struct {
bar: "Hello world!".to_string(),
};
let _: &mut String = &mut *value;
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_derive/compile_fail/tests/deref_mut_derive/missing_attribute_fail.rs | crates/bevy_derive/compile_fail/tests/deref_mut_derive/missing_attribute_fail.rs | use bevy_derive::DerefMut;
use core::ops::Deref;
#[derive(DerefMut)]
//~^ ERROR: requires one field to have
struct TupleStruct(usize, String);
impl Deref for TupleStruct {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.1
}
}
#[derive(DerefMut)]
//~^ ERROR: requires one field to have
struct Struct {
foo: usize,
bar: String,
}
impl Deref for Struct {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.bar
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_derive/src/lib.rs | crates/bevy_derive/src/lib.rs | //! Assorted proc macro derive functions.
#![forbid(unsafe_code)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc(
html_logo_url = "https://bevy.org/assets/icon.png",
html_favicon_url = "https://bevy.org/assets/icon.png"
)]
extern crate proc_macro;
mod bevy_main;
mod derefs;
mod enum_variant_meta;
use bevy_macro_utils::{derive_label, BevyManifest};
use proc_macro::TokenStream;
use quote::format_ident;
/// Implements [`Deref`] for structs. This is especially useful when utilizing the [newtype] pattern.
///
/// For single-field structs, the implementation automatically uses that field.
/// For multi-field structs, you must specify which field to use with the `#[deref]` attribute.
///
/// If you need [`DerefMut`] as well, consider using the other [derive] macro alongside
/// this one.
///
/// # Example
///
/// ## Tuple Structs
///
/// Using a single-field struct:
///
/// ```
/// use bevy_derive::Deref;
///
/// #[derive(Deref)]
/// struct MyNewtype(String);
///
/// let foo = MyNewtype(String::from("Hello"));
/// assert_eq!("Hello", *foo);
/// ```
///
/// Using a multi-field struct:
///
/// ```
/// # use std::marker::PhantomData;
/// use bevy_derive::Deref;
///
/// #[derive(Deref)]
/// struct MyStruct<T>(#[deref] String, PhantomData<T>);
///
/// let foo = MyStruct(String::from("Hello"), PhantomData::<usize>);
/// assert_eq!("Hello", *foo);
/// ```
///
/// ## Named Structs
///
/// Using a single-field struct:
///
/// ```
/// use bevy_derive::{Deref, DerefMut};
///
/// #[derive(Deref, DerefMut)]
/// struct MyStruct {
/// value: String,
/// }
///
/// let foo = MyStruct {
/// value: String::from("Hello")
/// };
/// assert_eq!("Hello", *foo);
/// ```
///
/// Using a multi-field struct:
///
/// ```
/// # use std::marker::PhantomData;
/// use bevy_derive::{Deref, DerefMut};
///
/// #[derive(Deref, DerefMut)]
/// struct MyStruct<T> {
/// #[deref]
/// value: String,
/// _phantom: PhantomData<T>,
/// }
///
/// let foo = MyStruct {
/// value:String::from("Hello"),
/// _phantom:PhantomData::<usize>
/// };
/// assert_eq!("Hello", *foo);
/// ```
///
/// [`Deref`]: std::ops::Deref
/// [newtype]: https://doc.rust-lang.org/rust-by-example/generics/new_types.html
/// [`DerefMut`]: std::ops::DerefMut
/// [derive]: crate::derive_deref_mut
#[proc_macro_derive(Deref, attributes(deref))]
pub fn derive_deref(input: TokenStream) -> TokenStream {
derefs::derive_deref(input)
}
/// Implements [`DerefMut`] for structs. This is especially useful when utilizing the [newtype] pattern.
///
/// For single-field structs, the implementation automatically uses that field.
/// For multi-field structs, you must specify which field to use with the `#[deref]` attribute.
///
/// [`DerefMut`] requires a [`Deref`] implementation. You can implement it manually or use
/// Bevy's [derive] macro for convenience.
///
/// # Example
///
/// ## Tuple Structs
///
/// Using a single-field struct:
///
/// ```
/// use bevy_derive::{Deref, DerefMut};
///
/// #[derive(Deref, DerefMut)]
/// struct MyNewtype(String);
///
/// let mut foo = MyNewtype(String::from("Hello"));
/// foo.push_str(" World!");
/// assert_eq!("Hello World!", *foo);
/// ```
///
/// Using a multi-field struct:
///
/// ```
/// # use std::marker::PhantomData;
/// use bevy_derive::{Deref, DerefMut};
///
/// #[derive(Deref, DerefMut)]
/// struct MyStruct<T>(#[deref] String, PhantomData<T>);
///
/// let mut foo = MyStruct(String::from("Hello"), PhantomData::<usize>);
/// foo.push_str(" World!");
/// assert_eq!("Hello World!", *foo);
/// ```
///
/// ## Named Structs
///
/// Using a single-field struct:
///
/// ```
/// use bevy_derive::{Deref, DerefMut};
///
/// #[derive(Deref, DerefMut)]
/// struct MyStruct {
/// value: String,
/// }
///
/// let mut foo = MyStruct {
/// value: String::from("Hello")
/// };
/// foo.push_str(" World!");
/// assert_eq!("Hello World!", *foo);
/// ```
///
/// Using a multi-field struct:
///
/// ```
/// # use std::marker::PhantomData;
/// use bevy_derive::{Deref, DerefMut};
///
/// #[derive(Deref, DerefMut)]
/// struct MyStruct<T> {
/// #[deref]
/// value: String,
/// _phantom: PhantomData<T>,
/// }
///
/// let mut foo = MyStruct {
/// value:String::from("Hello"),
/// _phantom:PhantomData::<usize>
/// };
/// foo.push_str(" World!");
/// assert_eq!("Hello World!", *foo);
/// ```
///
/// [`DerefMut`]: std::ops::DerefMut
/// [newtype]: https://doc.rust-lang.org/rust-by-example/generics/new_types.html
/// [`Deref`]: std::ops::Deref
/// [derive]: crate::derive_deref
#[proc_macro_derive(DerefMut, attributes(deref))]
pub fn derive_deref_mut(input: TokenStream) -> TokenStream {
derefs::derive_deref_mut(input)
}
/// Generates the required main function boilerplate for Android.
#[proc_macro_attribute]
pub fn bevy_main(attr: TokenStream, item: TokenStream) -> TokenStream {
bevy_main::bevy_main(attr, item)
}
/// Adds `enum_variant_index` and `enum_variant_name` functions to enums.
///
/// # Example
///
/// ```
/// use bevy_derive::{EnumVariantMeta};
///
/// #[derive(EnumVariantMeta)]
/// enum MyEnum {
/// A,
/// B,
/// }
///
/// let a = MyEnum::A;
/// let b = MyEnum::B;
///
/// assert_eq!(0, a.enum_variant_index());
/// assert_eq!("A", a.enum_variant_name());
///
/// assert_eq!(1, b.enum_variant_index());
/// assert_eq!("B", b.enum_variant_name());
/// ```
#[proc_macro_derive(EnumVariantMeta)]
pub fn derive_enum_variant_meta(input: TokenStream) -> TokenStream {
enum_variant_meta::derive_enum_variant_meta(input)
}
/// Generates an impl of the `AppLabel` trait.
///
/// This does not work for unions.
#[proc_macro_derive(AppLabel)]
pub fn derive_app_label(input: TokenStream) -> TokenStream {
let input = syn::parse_macro_input!(input as syn::DeriveInput);
let mut trait_path = BevyManifest::shared(|manifest| manifest.get_path("bevy_app"));
trait_path.segments.push(format_ident!("AppLabel").into());
derive_label(input, "AppLabel", &trait_path)
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_derive/src/derefs.rs | crates/bevy_derive/src/derefs.rs | use proc_macro::{Span, TokenStream};
use quote::quote;
use syn::{parse_macro_input, Data, DeriveInput, Field, Index, Member, Type};
const DEREF: &str = "Deref";
const DEREF_MUT: &str = "DerefMut";
const DEREF_ATTR: &str = "deref";
pub fn derive_deref(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
let ident = &ast.ident;
let (field_member, field_type) = match get_deref_field(&ast, false) {
Ok(items) => items,
Err(err) => {
return err.into_compile_error().into();
}
};
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
TokenStream::from(quote! {
impl #impl_generics ::core::ops::Deref for #ident #ty_generics #where_clause {
type Target = #field_type;
fn deref(&self) -> &Self::Target {
&self.#field_member
}
}
})
}
pub fn derive_deref_mut(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
let ident = &ast.ident;
let (field_member, _) = match get_deref_field(&ast, true) {
Ok(items) => items,
Err(err) => {
return err.into_compile_error().into();
}
};
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
TokenStream::from(quote! {
impl #impl_generics ::core::ops::DerefMut for #ident #ty_generics #where_clause {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.#field_member
}
}
})
}
fn get_deref_field(ast: &DeriveInput, is_mut: bool) -> syn::Result<(Member, &Type)> {
let deref_kind = if is_mut { DEREF_MUT } else { DEREF };
let deref_attr_str = format!("`#[{DEREF_ATTR}]`");
match &ast.data {
Data::Struct(data_struct) if data_struct.fields.is_empty() => Err(syn::Error::new(
Span::call_site().into(),
format!("{deref_kind} cannot be derived on field-less structs"),
)),
Data::Struct(data_struct) if data_struct.fields.len() == 1 => {
let field = data_struct.fields.iter().next().unwrap();
let member = to_member(field, 0);
Ok((member, &field.ty))
}
Data::Struct(data_struct) => {
let mut selected_field: Option<(Member, &Type)> = None;
for (index, field) in data_struct.fields.iter().enumerate() {
for attr in &field.attrs {
if !attr.meta.path().is_ident(DEREF_ATTR) {
continue;
}
attr.meta.require_path_only()?;
if selected_field.is_some() {
return Err(syn::Error::new_spanned(
attr,
format!(
"{deref_attr_str} attribute can only be used on a single field"
),
));
}
let member = to_member(field, index);
selected_field = Some((member, &field.ty));
}
}
if let Some(selected_field) = selected_field {
Ok(selected_field)
} else {
Err(syn::Error::new(
Span::call_site().into(),
format!("deriving {deref_kind} on multi-field structs requires one field to have the {deref_attr_str} attribute"),
))
}
}
_ => Err(syn::Error::new(
Span::call_site().into(),
format!("{deref_kind} can only be derived on structs"),
)),
}
}
fn to_member(field: &Field, index: usize) -> Member {
field
.ident
.as_ref()
.map(|name| Member::Named(name.clone()))
.unwrap_or_else(|| Member::Unnamed(Index::from(index)))
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_derive/src/enum_variant_meta.rs | crates/bevy_derive/src/enum_variant_meta.rs | use proc_macro::{Span, TokenStream};
use quote::quote;
use syn::{parse_macro_input, Data, DeriveInput};
pub fn derive_enum_variant_meta(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
let variants = match &ast.data {
Data::Enum(v) => &v.variants,
_ => {
return syn::Error::new(Span::call_site().into(), "Only enums are supported")
.into_compile_error()
.into()
}
};
let generics = ast.generics;
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
let struct_name = &ast.ident;
let idents = variants.iter().map(|v| &v.ident);
let names = variants.iter().map(|v| v.ident.to_string());
let indices = 0..names.len();
TokenStream::from(quote! {
impl #impl_generics #struct_name #ty_generics #where_clause {
pub fn enum_variant_index(&self) -> usize {
match self {
#(#struct_name::#idents {..} => #indices,)*
}
}
pub fn enum_variant_name(&self) -> &'static str {
static variants: &[&str] = &[
#(#names,)*
];
let index = self.enum_variant_index();
variants[index]
}
}
})
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_derive/src/bevy_main.rs | crates/bevy_derive/src/bevy_main.rs | use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, ItemFn};
pub fn bevy_main(_attr: TokenStream, item: TokenStream) -> TokenStream {
let input = parse_macro_input!(item as ItemFn);
assert_eq!(
input.sig.ident, "main",
"`bevy_main` can only be used on a function called 'main'."
);
TokenStream::from(quote! {
// SAFETY: `#[bevy_main]` should only be placed on a single `main` function
// TODO: Potentially make `bevy_main` and unsafe attribute as there is a safety
// guarantee required from the caller.
#[unsafe(no_mangle)]
#[cfg(target_os = "android")]
fn android_main(android_app: bevy::android::android_activity::AndroidApp) {
let _ = bevy::android::ANDROID_APP.set(android_app);
main();
}
#[allow(unused)]
#input
})
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_render/macros/src/extract_resource.rs | crates/bevy_render/macros/src/extract_resource.rs | use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, parse_quote, DeriveInput, Path};
pub fn derive_extract_resource(input: TokenStream) -> TokenStream {
let mut ast = parse_macro_input!(input as DeriveInput);
let bevy_render_path: Path = crate::bevy_render_path();
ast.generics
.make_where_clause()
.predicates
.push(parse_quote! { Self: Clone });
let struct_name = &ast.ident;
let (impl_generics, type_generics, where_clause) = &ast.generics.split_for_impl();
TokenStream::from(quote! {
impl #impl_generics #bevy_render_path::extract_resource::ExtractResource for #struct_name #type_generics #where_clause {
type Source = Self;
fn extract_resource(source: &Self::Source) -> Self {
source.clone()
}
}
})
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_render/macros/src/as_bind_group.rs | crates/bevy_render/macros/src/as_bind_group.rs | use bevy_macro_utils::{get_lit_bool, get_lit_str, BevyManifest, Symbol};
use proc_macro::TokenStream;
use proc_macro2::{Ident, Span};
use quote::{quote, ToTokens};
use syn::{
parenthesized,
parse::{Parse, ParseStream},
punctuated::Punctuated,
token::{Comma, DotDot},
Data, DataStruct, Error, Fields, LitInt, LitStr, Meta, MetaList, Result,
};
const UNIFORM_ATTRIBUTE_NAME: Symbol = Symbol("uniform");
const TEXTURE_ATTRIBUTE_NAME: Symbol = Symbol("texture");
const STORAGE_TEXTURE_ATTRIBUTE_NAME: Symbol = Symbol("storage_texture");
const SAMPLER_ATTRIBUTE_NAME: Symbol = Symbol("sampler");
const STORAGE_ATTRIBUTE_NAME: Symbol = Symbol("storage");
const BIND_GROUP_DATA_ATTRIBUTE_NAME: Symbol = Symbol("bind_group_data");
const BINDLESS_ATTRIBUTE_NAME: Symbol = Symbol("bindless");
const DATA_ATTRIBUTE_NAME: Symbol = Symbol("data");
const BINDING_ARRAY_MODIFIER_NAME: Symbol = Symbol("binding_array");
const LIMIT_MODIFIER_NAME: Symbol = Symbol("limit");
const INDEX_TABLE_MODIFIER_NAME: Symbol = Symbol("index_table");
const RANGE_MODIFIER_NAME: Symbol = Symbol("range");
const BINDING_MODIFIER_NAME: Symbol = Symbol("binding");
#[derive(Copy, Clone, Debug)]
enum BindingType {
Uniform,
Texture,
StorageTexture,
Sampler,
Storage,
}
#[derive(Clone)]
enum BindingState<'a> {
Free,
Occupied {
binding_type: BindingType,
ident: &'a Ident,
},
OccupiedConvertedUniform,
OccupiedMergeableUniform {
uniform_fields: Vec<&'a syn::Field>,
},
}
enum BindlessSlabResourceLimitAttr {
Auto,
Limit(LitInt),
}
// The `bindless(index_table(range(M..N)))` attribute.
struct BindlessIndexTableRangeAttr {
start: LitInt,
end: LitInt,
}
pub fn derive_as_bind_group(ast: syn::DeriveInput) -> Result<TokenStream> {
let (render_path, image_path, asset_path, ecs_path) = BevyManifest::shared(|manifest| {
let render_path = manifest.get_path("bevy_render");
let image_path = manifest.get_path("bevy_image");
let asset_path = manifest.get_path("bevy_asset");
let ecs_path = manifest.get_path("bevy_ecs");
(render_path, image_path, asset_path, ecs_path)
});
let mut binding_states: Vec<BindingState> = Vec::new();
let mut binding_impls = Vec::new();
let mut bindless_binding_layouts = Vec::new();
let mut non_bindless_binding_layouts = Vec::new();
let mut bindless_resource_types = Vec::new();
let mut bindless_buffer_descriptors = Vec::new();
let mut attr_prepared_data_ident = None;
// After the first attribute pass, this will be `None` if the object isn't
// bindless and `Some` if it is.
let mut attr_bindless_count = None;
let mut attr_bindless_index_table_range = None;
let mut attr_bindless_index_table_binding = None;
// `actual_bindless_slot_count` holds the actual number of bindless slots
// per bind group, taking into account whether the current platform supports
// bindless resources.
let actual_bindless_slot_count = Ident::new("actual_bindless_slot_count", Span::call_site());
let bind_group_layout_entries = Ident::new("bind_group_layout_entries", Span::call_site());
// The `BufferBindingType` and corresponding `BufferUsages` used for
// uniforms. We need this because bindless uniforms don't exist, so in
// bindless mode we must promote uniforms to storage buffers.
let uniform_binding_type = Ident::new("uniform_binding_type", Span::call_site());
let uniform_buffer_usages = Ident::new("uniform_buffer_usages", Span::call_site());
// Read struct-level attributes, first pass.
for attr in &ast.attrs {
if let Some(attr_ident) = attr.path().get_ident() {
if attr_ident == BIND_GROUP_DATA_ATTRIBUTE_NAME {
if let Ok(prepared_data_ident) =
attr.parse_args_with(|input: ParseStream| input.parse::<Ident>())
{
attr_prepared_data_ident = Some(prepared_data_ident);
}
} else if attr_ident == BINDLESS_ATTRIBUTE_NAME {
attr_bindless_count = Some(BindlessSlabResourceLimitAttr::Auto);
if let Meta::List(_) = attr.meta {
// Parse bindless features.
attr.parse_nested_meta(|submeta| {
if submeta.path.is_ident(&LIMIT_MODIFIER_NAME) {
let content;
parenthesized!(content in submeta.input);
let lit: LitInt = content.parse()?;
attr_bindless_count = Some(BindlessSlabResourceLimitAttr::Limit(lit));
return Ok(());
}
if submeta.path.is_ident(&INDEX_TABLE_MODIFIER_NAME) {
submeta.parse_nested_meta(|subsubmeta| {
if subsubmeta.path.is_ident(&RANGE_MODIFIER_NAME) {
let content;
parenthesized!(content in subsubmeta.input);
let start: LitInt = content.parse()?;
content.parse::<DotDot>()?;
let end: LitInt = content.parse()?;
attr_bindless_index_table_range =
Some(BindlessIndexTableRangeAttr { start, end });
return Ok(());
}
if subsubmeta.path.is_ident(&BINDING_MODIFIER_NAME) {
let content;
parenthesized!(content in subsubmeta.input);
let lit: LitInt = content.parse()?;
attr_bindless_index_table_binding = Some(lit);
return Ok(());
}
Err(Error::new_spanned(
attr,
"Expected `range(M..N)` or `binding(N)`",
))
})?;
return Ok(());
}
Err(Error::new_spanned(
attr,
"Expected `limit` or `index_table`",
))
})?;
}
}
}
}
// Read struct-level attributes, second pass.
for attr in &ast.attrs {
if let Some(attr_ident) = attr.path().get_ident()
&& (attr_ident == UNIFORM_ATTRIBUTE_NAME || attr_ident == DATA_ATTRIBUTE_NAME)
{
let UniformBindingAttr {
binding_type,
binding_index,
converted_shader_type,
binding_array: binding_array_binding,
} = get_uniform_binding_attr(attr)?;
match binding_type {
UniformBindingAttrType::Uniform => {
binding_impls.push(quote! {{
use #render_path::render_resource::AsBindGroupShaderType;
let mut buffer = #render_path::render_resource::encase::UniformBuffer::new(Vec::new());
let converted: #converted_shader_type = self.as_bind_group_shader_type(&images);
buffer.write(&converted).unwrap();
(
#binding_index,
#render_path::render_resource::OwnedBindingResource::Buffer(render_device.create_buffer_with_data(
&#render_path::render_resource::BufferInitDescriptor {
label: None,
usage: #uniform_buffer_usages,
contents: buffer.as_ref(),
},
))
)
}});
match (&binding_array_binding, &attr_bindless_count) {
(&None, &Some(_)) => {
return Err(Error::new_spanned(
attr,
"Must specify `binding_array(...)` with `#[uniform]` if the \
object is bindless",
));
}
(&Some(_), &None) => {
return Err(Error::new_spanned(
attr,
"`binding_array(...)` with `#[uniform]` requires the object to \
be bindless",
));
}
_ => {}
}
let binding_array_binding = binding_array_binding.unwrap_or(0);
bindless_binding_layouts.push(quote! {
#bind_group_layout_entries.push(
#render_path::render_resource::BindGroupLayoutEntry {
binding: #binding_array_binding,
visibility: #render_path::render_resource::ShaderStages::FRAGMENT | #render_path::render_resource::ShaderStages::VERTEX | #render_path::render_resource::ShaderStages::COMPUTE,
ty: #render_path::render_resource::BindingType::Buffer {
ty: #uniform_binding_type,
has_dynamic_offset: false,
min_binding_size: Some(<#converted_shader_type as #render_path::render_resource::ShaderType>::min_size()),
},
count: #actual_bindless_slot_count,
}
);
});
add_bindless_resource_type(
&render_path,
&mut bindless_resource_types,
binding_index,
quote! { #render_path::render_resource::BindlessResourceType::Buffer },
);
}
UniformBindingAttrType::Data => {
binding_impls.push(quote! {{
use #render_path::render_resource::AsBindGroupShaderType;
use #render_path::render_resource::encase::{ShaderType, internal::WriteInto};
let mut buffer: Vec<u8> = Vec::new();
let converted: #converted_shader_type = self.as_bind_group_shader_type(&images);
converted.write_into(
&mut #render_path::render_resource::encase::internal::Writer::new(
&converted,
&mut buffer,
0,
).unwrap(),
);
let min_size = <#converted_shader_type as #render_path::render_resource::ShaderType>::min_size().get() as usize;
while buffer.len() < min_size {
buffer.push(0);
}
(
#binding_index,
#render_path::render_resource::OwnedBindingResource::Data(
#render_path::render_resource::OwnedData(buffer)
)
)
}});
let binding_array_binding = binding_array_binding.unwrap_or(0);
bindless_binding_layouts.push(quote! {
#bind_group_layout_entries.push(
#render_path::render_resource::BindGroupLayoutEntry {
binding: #binding_array_binding,
visibility: #render_path::render_resource::ShaderStages::FRAGMENT | #render_path::render_resource::ShaderStages::VERTEX | #render_path::render_resource::ShaderStages::COMPUTE,
ty: #render_path::render_resource::BindingType::Buffer {
ty: #uniform_binding_type,
has_dynamic_offset: false,
min_binding_size: Some(<#converted_shader_type as #render_path::render_resource::ShaderType>::min_size()),
},
count: None,
}
);
});
add_bindless_resource_type(
&render_path,
&mut bindless_resource_types,
binding_index,
quote! { #render_path::render_resource::BindlessResourceType::DataBuffer },
);
}
}
// Push the non-bindless binding layout.
non_bindless_binding_layouts.push(quote!{
#bind_group_layout_entries.push(
#render_path::render_resource::BindGroupLayoutEntry {
binding: #binding_index,
visibility: #render_path::render_resource::ShaderStages::FRAGMENT | #render_path::render_resource::ShaderStages::VERTEX | #render_path::render_resource::ShaderStages::COMPUTE,
ty: #render_path::render_resource::BindingType::Buffer {
ty: #uniform_binding_type,
has_dynamic_offset: false,
min_binding_size: Some(<#converted_shader_type as #render_path::render_resource::ShaderType>::min_size()),
},
count: None,
}
);
});
bindless_buffer_descriptors.push(quote! {
#render_path::render_resource::BindlessBufferDescriptor {
// Note that, because this is bindless, *binding
// index* here refers to the index in the
// bindless index table (`bindless_index`), and
// the actual binding number is the *binding
// array binding*.
binding_number: #render_path::render_resource::BindingNumber(
#binding_array_binding
),
bindless_index:
#render_path::render_resource::BindlessIndex(#binding_index),
size: Some(
<
#converted_shader_type as
#render_path::render_resource::ShaderType
>::min_size().get() as usize
),
}
});
let required_len = binding_index as usize + 1;
if required_len > binding_states.len() {
binding_states.resize(required_len, BindingState::Free);
}
binding_states[binding_index as usize] = BindingState::OccupiedConvertedUniform;
}
}
let fields = match &ast.data {
Data::Struct(DataStruct {
fields: Fields::Named(fields),
..
}) => &fields.named,
_ => {
return Err(Error::new_spanned(
ast,
"Expected a struct with named fields",
));
}
};
// Count the number of sampler fields needed. We might have to disable
// bindless if bindless arrays take the GPU over the maximum number of
// samplers.
let mut sampler_binding_count: u32 = 0;
// Read field-level attributes
for field in fields {
// Search ahead for texture attributes so we can use them with any
// corresponding sampler attribute.
let mut tex_attrs = None;
for attr in &field.attrs {
let Some(attr_ident) = attr.path().get_ident() else {
continue;
};
if attr_ident == TEXTURE_ATTRIBUTE_NAME {
let (_binding_index, nested_meta_items) = get_binding_nested_attr(attr)?;
tex_attrs = Some(get_texture_attrs(nested_meta_items)?);
}
}
for attr in &field.attrs {
let Some(attr_ident) = attr.path().get_ident() else {
continue;
};
let binding_type = if attr_ident == UNIFORM_ATTRIBUTE_NAME {
BindingType::Uniform
} else if attr_ident == TEXTURE_ATTRIBUTE_NAME {
BindingType::Texture
} else if attr_ident == STORAGE_TEXTURE_ATTRIBUTE_NAME {
BindingType::StorageTexture
} else if attr_ident == SAMPLER_ATTRIBUTE_NAME {
BindingType::Sampler
} else if attr_ident == STORAGE_ATTRIBUTE_NAME {
BindingType::Storage
} else {
continue;
};
let (binding_index, nested_meta_items) = get_binding_nested_attr(attr)?;
let field_name = field.ident.as_ref().unwrap();
let required_len = binding_index as usize + 1;
if required_len > binding_states.len() {
binding_states.resize(required_len, BindingState::Free);
}
match &mut binding_states[binding_index as usize] {
value @ BindingState::Free => {
*value = match binding_type {
BindingType::Uniform => BindingState::OccupiedMergeableUniform {
uniform_fields: vec![field],
},
_ => {
// only populate bind group entries for non-uniforms
// uniform entries are deferred until the end
BindingState::Occupied {
binding_type,
ident: field_name,
}
}
}
}
BindingState::Occupied {
binding_type,
ident: occupied_ident,
} => {
return Err(Error::new_spanned(
attr,
format!("The '{field_name}' field cannot be assigned to binding {binding_index} because it is already occupied by the field '{occupied_ident}' of type {binding_type:?}.")
));
}
BindingState::OccupiedConvertedUniform => {
return Err(Error::new_spanned(
attr,
format!("The '{field_name}' field cannot be assigned to binding {binding_index} because it is already occupied by a struct-level uniform binding at the same index.")
));
}
BindingState::OccupiedMergeableUniform { uniform_fields } => match binding_type {
BindingType::Uniform => {
uniform_fields.push(field);
}
_ => {
return Err(Error::new_spanned(
attr,
format!("The '{field_name}' field cannot be assigned to binding {binding_index} because it is already occupied by a {:?}.", BindingType::Uniform)
));
}
},
}
match binding_type {
BindingType::Uniform => {
if attr_bindless_count.is_some() {
return Err(Error::new_spanned(
attr,
"Only structure-level `#[uniform]` attributes are supported in \
bindless mode",
));
}
// uniform codegen is deferred to account for combined uniform bindings
}
BindingType::Storage => {
let StorageAttrs {
visibility,
binding_array: binding_array_binding,
read_only,
buffer,
} = get_storage_binding_attr(nested_meta_items)?;
let visibility =
visibility.hygienic_quote("e! { #render_path::render_resource });
let field_name = field.ident.as_ref().unwrap();
if buffer {
binding_impls.push(quote! {
(
#binding_index,
#render_path::render_resource::OwnedBindingResource::Buffer({
self.#field_name.clone()
})
)
});
} else {
binding_impls.push(quote! {
(
#binding_index,
#render_path::render_resource::OwnedBindingResource::Buffer({
let handle: &#asset_path::Handle<#render_path::storage::ShaderStorageBuffer> = (&self.#field_name);
storage_buffers.get(handle).ok_or_else(|| #render_path::render_resource::AsBindGroupError::RetryNextUpdate)?.buffer.clone()
})
)
});
}
non_bindless_binding_layouts.push(quote! {
#bind_group_layout_entries.push(
#render_path::render_resource::BindGroupLayoutEntry {
binding: #binding_index,
visibility: #visibility,
ty: #render_path::render_resource::BindingType::Buffer {
ty: #render_path::render_resource::BufferBindingType::Storage { read_only: #read_only },
has_dynamic_offset: false,
min_binding_size: None,
},
count: #actual_bindless_slot_count,
}
);
});
if let Some(binding_array_binding) = binding_array_binding {
// Add the storage buffer to the `BindlessResourceType` list
// in the bindless descriptor.
let bindless_resource_type = quote! {
#render_path::render_resource::BindlessResourceType::Buffer
};
add_bindless_resource_type(
&render_path,
&mut bindless_resource_types,
binding_index,
bindless_resource_type,
);
// Push the buffer descriptor.
bindless_buffer_descriptors.push(quote! {
#render_path::render_resource::BindlessBufferDescriptor {
// Note that, because this is bindless, *binding
// index* here refers to the index in the bindless
// index table (`bindless_index`), and the actual
// binding number is the *binding array binding*.
binding_number: #render_path::render_resource::BindingNumber(
#binding_array_binding
),
bindless_index:
#render_path::render_resource::BindlessIndex(#binding_index),
size: None,
}
});
// Declare the binding array.
bindless_binding_layouts.push(quote!{
#bind_group_layout_entries.push(
#render_path::render_resource::BindGroupLayoutEntry {
binding: #binding_array_binding,
visibility: #render_path::render_resource::ShaderStages::FRAGMENT | #render_path::render_resource::ShaderStages::VERTEX | #render_path::render_resource::ShaderStages::COMPUTE,
ty: #render_path::render_resource::BindingType::Buffer {
ty: #render_path::render_resource::BufferBindingType::Storage {
read_only: #read_only
},
has_dynamic_offset: false,
min_binding_size: None,
},
count: #actual_bindless_slot_count,
}
);
});
}
}
BindingType::StorageTexture => {
if attr_bindless_count.is_some() {
return Err(Error::new_spanned(
attr,
"Storage textures are unsupported in bindless mode",
));
}
let StorageTextureAttrs {
dimension,
image_format,
access,
visibility,
} = get_storage_texture_binding_attr(nested_meta_items)?;
let visibility =
visibility.hygienic_quote("e! { #render_path::render_resource });
let fallback_image = get_fallback_image(&render_path, dimension);
// insert fallible texture-based entries at 0 so that if we fail here, we exit before allocating any buffers
binding_impls.insert(0, quote! {
( #binding_index,
#render_path::render_resource::OwnedBindingResource::TextureView(
#render_path::render_resource::#dimension,
{
let handle: Option<&#asset_path::Handle<#image_path::Image>> = (&self.#field_name).into();
if let Some(handle) = handle {
images.get(handle).ok_or_else(|| #render_path::render_resource::AsBindGroupError::RetryNextUpdate)?.texture_view.clone()
} else {
#fallback_image.texture_view.clone()
}
}
)
)
});
non_bindless_binding_layouts.push(quote! {
#bind_group_layout_entries.push(
#render_path::render_resource::BindGroupLayoutEntry {
binding: #binding_index,
visibility: #visibility,
ty: #render_path::render_resource::BindingType::StorageTexture {
access: #render_path::render_resource::StorageTextureAccess::#access,
format: #render_path::render_resource::TextureFormat::#image_format,
view_dimension: #render_path::render_resource::#dimension,
},
count: #actual_bindless_slot_count,
}
);
});
}
BindingType::Texture => {
let TextureAttrs {
dimension,
sample_type,
multisampled,
visibility,
} = tex_attrs.as_ref().unwrap();
let visibility =
visibility.hygienic_quote("e! { #render_path::render_resource });
let fallback_image = get_fallback_image(&render_path, *dimension);
// insert fallible texture-based entries at 0 so that if we fail here, we exit before allocating any buffers
binding_impls.insert(0, quote! {
(
#binding_index,
#render_path::render_resource::OwnedBindingResource::TextureView(
#render_path::render_resource::#dimension,
{
let handle: Option<&#asset_path::Handle<#image_path::Image>> = (&self.#field_name).into();
if let Some(handle) = handle {
images.get(handle).ok_or_else(|| #render_path::render_resource::AsBindGroupError::RetryNextUpdate)?.texture_view.clone()
} else {
#fallback_image.texture_view.clone()
}
}
)
)
});
sampler_binding_count += 1;
non_bindless_binding_layouts.push(quote! {
#bind_group_layout_entries.push(
#render_path::render_resource::BindGroupLayoutEntry {
binding: #binding_index,
visibility: #visibility,
ty: #render_path::render_resource::BindingType::Texture {
multisampled: #multisampled,
sample_type: #render_path::render_resource::#sample_type,
view_dimension: #render_path::render_resource::#dimension,
},
count: #actual_bindless_slot_count,
}
);
});
let bindless_resource_type = match *dimension {
BindingTextureDimension::D1 => {
quote! {
#render_path::render_resource::BindlessResourceType::Texture1d
}
}
BindingTextureDimension::D2 => {
quote! {
#render_path::render_resource::BindlessResourceType::Texture2d
}
}
BindingTextureDimension::D2Array => {
quote! {
#render_path::render_resource::BindlessResourceType::Texture2dArray
}
}
BindingTextureDimension::Cube => {
quote! {
#render_path::render_resource::BindlessResourceType::TextureCube
}
}
BindingTextureDimension::CubeArray => {
quote! {
#render_path::render_resource::BindlessResourceType::TextureCubeArray
}
}
BindingTextureDimension::D3 => {
quote! {
#render_path::render_resource::BindlessResourceType::Texture3d
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_render/macros/src/lib.rs | crates/bevy_render/macros/src/lib.rs | #![expect(missing_docs, reason = "Not all docs are written yet, see #3492.")]
#![cfg_attr(docsrs, feature(doc_cfg))]
mod as_bind_group;
mod extract_component;
mod extract_resource;
mod specializer;
use bevy_macro_utils::{derive_label, BevyManifest};
use proc_macro::TokenStream;
use quote::format_ident;
use syn::{parse_macro_input, DeriveInput};
pub(crate) fn bevy_render_path() -> syn::Path {
BevyManifest::shared(|manifest| manifest.get_path("bevy_render"))
}
pub(crate) fn bevy_ecs_path() -> syn::Path {
BevyManifest::shared(|manifest| manifest.get_path("bevy_ecs"))
}
#[proc_macro_derive(ExtractResource)]
pub fn derive_extract_resource(input: TokenStream) -> TokenStream {
extract_resource::derive_extract_resource(input)
}
/// Implements `ExtractComponent` trait for a component.
///
/// The component must implement [`Clone`].
/// The component will be extracted into the render world via cloning.
/// Note that this only enables extraction of the component, it does not execute the extraction.
/// See `ExtractComponentPlugin` to actually perform the extraction.
///
/// If you only want to extract a component conditionally, you may use the `extract_component_filter` attribute.
///
/// # Example
///
/// ```no_compile
/// use bevy_ecs::component::Component;
/// use bevy_render_macros::ExtractComponent;
///
/// #[derive(Component, Clone, ExtractComponent)]
/// #[extract_component_filter(With<Camera>)]
/// pub struct Foo {
/// pub should_foo: bool,
/// }
///
/// // Without a filter (unconditional).
/// #[derive(Component, Clone, ExtractComponent)]
/// pub struct Bar {
/// pub should_bar: bool,
/// }
/// ```
#[proc_macro_derive(ExtractComponent, attributes(extract_component_filter))]
pub fn derive_extract_component(input: TokenStream) -> TokenStream {
extract_component::derive_extract_component(input)
}
#[proc_macro_derive(
AsBindGroup,
attributes(
uniform,
storage_texture,
texture,
sampler,
bind_group_data,
storage,
bindless,
data
)
)]
pub fn derive_as_bind_group(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
as_bind_group::derive_as_bind_group(input).unwrap_or_else(|err| err.to_compile_error().into())
}
/// Derive macro generating an impl of the trait `RenderLabel`.
///
/// This does not work for unions.
#[proc_macro_derive(RenderLabel)]
pub fn derive_render_label(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let mut trait_path = bevy_render_path();
trait_path
.segments
.push(format_ident!("render_graph").into());
trait_path
.segments
.push(format_ident!("RenderLabel").into());
derive_label(input, "RenderLabel", &trait_path)
}
/// Derive macro generating an impl of the trait `RenderSubGraph`.
///
/// This does not work for unions.
#[proc_macro_derive(RenderSubGraph)]
pub fn derive_render_sub_graph(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let mut trait_path = bevy_render_path();
trait_path
.segments
.push(format_ident!("render_graph").into());
trait_path
.segments
.push(format_ident!("RenderSubGraph").into());
derive_label(input, "RenderSubGraph", &trait_path)
}
/// Derive macro generating an impl of the trait `Specializer`
///
/// This only works for structs whose members all implement `Specializer`
#[proc_macro_derive(Specializer, attributes(specialize, key, base_descriptor))]
pub fn derive_specialize(input: TokenStream) -> TokenStream {
specializer::impl_specializer(input)
}
/// Derive macro generating the most common impl of the trait `SpecializerKey`
#[proc_macro_derive(SpecializerKey)]
pub fn derive_specializer_key(input: TokenStream) -> TokenStream {
specializer::impl_specializer_key(input)
}
#[proc_macro_derive(ShaderLabel)]
pub fn derive_shader_label(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let mut trait_path = bevy_render_path();
trait_path
.segments
.push(format_ident!("render_phase").into());
trait_path
.segments
.push(format_ident!("ShaderLabel").into());
derive_label(input, "ShaderLabel", &trait_path)
}
#[proc_macro_derive(DrawFunctionLabel)]
pub fn derive_draw_function_label(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let mut trait_path = bevy_render_path();
trait_path
.segments
.push(format_ident!("render_phase").into());
trait_path
.segments
.push(format_ident!("DrawFunctionLabel").into());
derive_label(input, "DrawFunctionLabel", &trait_path)
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_render/macros/src/specializer.rs | crates/bevy_render/macros/src/specializer.rs | use bevy_macro_utils::{
fq_std::{FQDefault, FQResult},
get_struct_fields, require_named,
};
use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::{format_ident, quote};
use syn::{
parse::{Parse, ParseStream},
parse_macro_input, parse_quote,
punctuated::Punctuated,
spanned::Spanned,
DeriveInput, Expr, Field, Ident, Index, Member, Meta, MetaList, Pat, Path, Token, Type,
WherePredicate,
};
const SPECIALIZE_ATTR_IDENT: &str = "specialize";
const SPECIALIZE_ALL_IDENT: &str = "all";
const KEY_ATTR_IDENT: &str = "key";
const KEY_DEFAULT_IDENT: &str = "default";
enum SpecializeImplTargets {
All,
Specific(Vec<Path>),
}
impl Parse for SpecializeImplTargets {
fn parse(input: ParseStream) -> syn::Result<Self> {
let paths = input.parse_terminated(Path::parse, Token![,])?;
if paths
.first()
.is_some_and(|p| p.is_ident(SPECIALIZE_ALL_IDENT))
{
Ok(SpecializeImplTargets::All)
} else {
Ok(SpecializeImplTargets::Specific(paths.into_iter().collect()))
}
}
}
#[derive(Clone)]
enum Key {
Whole,
Default,
Index(Index),
Custom(Expr),
}
impl Key {
fn expr(&self) -> Expr {
match self {
Key::Whole => parse_quote!(key),
Key::Default => parse_quote!(#FQDefault::default()),
Key::Index(index) => {
let member = Member::Unnamed(index.clone());
parse_quote!(key.#member)
}
Key::Custom(expr) => expr.clone(),
}
}
}
const KEY_ERROR_MSG: &str = "Invalid key override. Must be either `default` or a valid Rust expression of the correct key type";
impl Parse for Key {
fn parse(input: ParseStream) -> syn::Result<Self> {
if let Ok(ident) = input.parse::<Ident>() {
if ident == KEY_DEFAULT_IDENT {
Ok(Key::Default)
} else {
Err(syn::Error::new_spanned(ident, KEY_ERROR_MSG))
}
} else {
input.parse::<Expr>().map(Key::Custom).map_err(|mut err| {
err.extend(syn::Error::new(err.span(), KEY_ERROR_MSG));
err
})
}
}
}
#[derive(Clone)]
struct FieldInfo {
ty: Type,
member: Member,
key: Key,
}
impl FieldInfo {
fn key_ty(&self, specialize_path: &Path, target_path: &Path) -> Option<Type> {
let ty = &self.ty;
matches!(self.key, Key::Whole | Key::Index(_))
.then_some(parse_quote!(<#ty as #specialize_path::Specializer<#target_path>>::Key))
}
fn key_ident(&self, ident: Ident) -> Option<Ident> {
matches!(self.key, Key::Whole | Key::Index(_)).then_some(ident)
}
fn specialize_expr(&self, specialize_path: &Path, target_path: &Path) -> Expr {
let FieldInfo {
ty, member, key, ..
} = &self;
let key_expr = key.expr();
parse_quote!(<#ty as #specialize_path::Specializer<#target_path>>::specialize(&self.#member, #key_expr, descriptor))
}
fn specialize_predicate(&self, specialize_path: &Path, target_path: &Path) -> WherePredicate {
let ty = &self.ty;
if matches!(&self.key, Key::Default) {
parse_quote!(#ty: #specialize_path::Specializer<#target_path, Key: #FQDefault>)
} else {
parse_quote!(#ty: #specialize_path::Specializer<#target_path>)
}
}
}
fn get_field_info(
fields: &Punctuated<Field, Token![,]>,
targets: &SpecializeImplTargets,
) -> syn::Result<Vec<FieldInfo>> {
let mut field_info: Vec<FieldInfo> = Vec::new();
let mut used_count = 0;
let mut single_index = 0;
for (index, field) in fields.iter().enumerate() {
let field_ty = field.ty.clone();
let field_member = field.ident.clone().map_or(
Member::Unnamed(Index {
index: index as u32,
span: field.span(),
}),
Member::Named,
);
let key_index = Index {
index: used_count,
span: field.span(),
};
let mut use_key_field = true;
let mut key = Key::Index(key_index);
for attr in &field.attrs {
match &attr.meta {
Meta::List(MetaList { path, tokens, .. }) if path.is_ident(&KEY_ATTR_IDENT) => {
let owned_tokens = tokens.clone().into();
let Ok(parsed_key) = syn::parse::<Key>(owned_tokens) else {
return Err(syn::Error::new(
attr.span(),
"Invalid key override attribute",
));
};
key = parsed_key;
if matches!(
(&key, &targets),
(Key::Custom(_), SpecializeImplTargets::All)
) {
return Err(syn::Error::new(
attr.span(),
"#[key(default)] is the only key override type allowed with #[specialize(all)]",
));
}
use_key_field = false;
}
_ => {}
}
}
if use_key_field {
used_count += 1;
single_index = index;
}
field_info.push(FieldInfo {
ty: field_ty,
member: field_member,
key,
});
}
if used_count == 1 {
field_info[single_index].key = Key::Whole;
}
Ok(field_info)
}
fn get_specialize_targets(
ast: &DeriveInput,
derive_name: &str,
) -> syn::Result<SpecializeImplTargets> {
let specialize_attr = ast.attrs.iter().find_map(|attr| {
if attr.path().is_ident(SPECIALIZE_ATTR_IDENT)
&& let Meta::List(meta_list) = &attr.meta
{
return Some(meta_list);
}
None
});
let Some(specialize_meta_list) = specialize_attr else {
return Err(syn::Error::new(
Span::call_site(),
format!("#[derive({derive_name})] must be accompanied by #[specialize(..targets)].\n Example usages: #[specialize(RenderPipeline)], #[specialize(all)]")
));
};
syn::parse::<SpecializeImplTargets>(specialize_meta_list.tokens.clone().into())
}
macro_rules! guard {
($expr: expr) => {
match $expr {
Ok(__val) => __val,
Err(err) => return err.to_compile_error().into(),
}
};
}
pub fn impl_specializer(input: TokenStream) -> TokenStream {
let bevy_render_path: Path = crate::bevy_render_path();
let specialize_path = {
let mut path = bevy_render_path.clone();
path.segments.push(format_ident!("render_resource").into());
path
};
let ecs_path = crate::bevy_ecs_path();
let ast = parse_macro_input!(input as DeriveInput);
let targets = guard!(get_specialize_targets(&ast, "Specializer"));
let fields = guard!(get_struct_fields(&ast.data, "Specializer"));
let fields = guard!(require_named(fields));
let field_info = guard!(get_field_info(fields, &targets));
let key_idents: Vec<Option<Ident>> = field_info
.iter()
.enumerate()
.map(|(i, field_info)| field_info.key_ident(format_ident!("key{i}")))
.collect();
let key_tuple_idents: Vec<Ident> = key_idents.iter().flatten().cloned().collect();
let ignore_pat: Pat = parse_quote!(_);
let key_patterns: Vec<Pat> = key_idents
.iter()
.map(|key_ident| match key_ident {
Some(key_ident) => parse_quote!(#key_ident),
None => ignore_pat.clone(),
})
.collect();
match targets {
SpecializeImplTargets::All => impl_specialize_all(
&specialize_path,
&ecs_path,
&ast,
&field_info,
&key_patterns,
&key_tuple_idents,
),
SpecializeImplTargets::Specific(targets) => targets
.iter()
.map(|target| {
impl_specialize_specific(
&specialize_path,
&ecs_path,
&ast,
&field_info,
target,
&key_patterns,
&key_tuple_idents,
)
})
.collect(),
}
}
fn impl_specialize_all(
specialize_path: &Path,
ecs_path: &Path,
ast: &DeriveInput,
field_info: &[FieldInfo],
key_patterns: &[Pat],
key_tuple_idents: &[Ident],
) -> TokenStream {
let target_path = Path::from(format_ident!("T"));
let key_elems: Vec<Type> = field_info
.iter()
.filter_map(|field_info| field_info.key_ty(specialize_path, &target_path))
.collect();
let specialize_exprs: Vec<Expr> = field_info
.iter()
.map(|field_info| field_info.specialize_expr(specialize_path, &target_path))
.collect();
let struct_name = &ast.ident;
let mut generics = ast.generics.clone();
generics.params.insert(
0,
parse_quote!(#target_path: #specialize_path::Specializable),
);
if !field_info.is_empty() {
let where_clause = generics.make_where_clause();
for field in field_info {
where_clause
.predicates
.push(field.specialize_predicate(specialize_path, &target_path));
}
}
let (_, type_generics, _) = ast.generics.split_for_impl();
let (impl_generics, _, where_clause) = &generics.split_for_impl();
TokenStream::from(quote! {
impl #impl_generics #specialize_path::Specializer<#target_path> for #struct_name #type_generics #where_clause {
type Key = (#(#key_elems),*);
fn specialize(
&self,
key: Self::Key,
descriptor: &mut <#target_path as #specialize_path::Specializable>::Descriptor
) -> #FQResult<#specialize_path::Canonical<Self::Key>, #ecs_path::error::BevyError> {
#(let #key_patterns = #specialize_exprs?;)*
#FQResult::Ok((#(#key_tuple_idents),*))
}
}
})
}
fn impl_specialize_specific(
specialize_path: &Path,
ecs_path: &Path,
ast: &DeriveInput,
field_info: &[FieldInfo],
target_path: &Path,
key_patterns: &[Pat],
key_tuple_idents: &[Ident],
) -> TokenStream {
let key_elems: Vec<Type> = field_info
.iter()
.filter_map(|field_info| field_info.key_ty(specialize_path, target_path))
.collect();
let specialize_exprs: Vec<Expr> = field_info
.iter()
.map(|field_info| field_info.specialize_expr(specialize_path, target_path))
.collect();
let struct_name = &ast.ident;
let (impl_generics, type_generics, where_clause) = &ast.generics.split_for_impl();
TokenStream::from(quote! {
impl #impl_generics #specialize_path::Specializer<#target_path> for #struct_name #type_generics #where_clause {
type Key = (#(#key_elems),*);
fn specialize(
&self,
key: Self::Key,
descriptor: &mut <#target_path as #specialize_path::Specializable>::Descriptor
) -> #FQResult<#specialize_path::Canonical<Self::Key>, #ecs_path::error::BevyError> {
#(let #key_patterns = #specialize_exprs?;)*
#FQResult::Ok((#(#key_tuple_idents),*))
}
}
})
}
pub fn impl_specializer_key(input: TokenStream) -> TokenStream {
let bevy_render_path: Path = crate::bevy_render_path();
let specialize_path = {
let mut path = bevy_render_path.clone();
path.segments.push(format_ident!("render_resource").into());
path
};
let ast = parse_macro_input!(input as DeriveInput);
let ident = ast.ident;
TokenStream::from(quote!(
impl #specialize_path::SpecializerKey for #ident {
const IS_CANONICAL: bool = true;
type Canonical = Self;
}
))
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_render/macros/src/extract_component.rs | crates/bevy_render/macros/src/extract_component.rs | use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, parse_quote, DeriveInput, Path};
pub fn derive_extract_component(input: TokenStream) -> TokenStream {
let mut ast = parse_macro_input!(input as DeriveInput);
let bevy_render_path: Path = crate::bevy_render_path();
let bevy_ecs_path: Path = bevy_macro_utils::BevyManifest::shared(|manifest| {
manifest
.maybe_get_path("bevy_ecs")
.expect("bevy_ecs should be found in manifest")
});
ast.generics
.make_where_clause()
.predicates
.push(parse_quote! { Self: Clone });
let struct_name = &ast.ident;
let (impl_generics, type_generics, where_clause) = &ast.generics.split_for_impl();
let filter = if let Some(attr) = ast
.attrs
.iter()
.find(|a| a.path().is_ident("extract_component_filter"))
{
let filter = match attr.parse_args::<syn::Type>() {
Ok(filter) => filter,
Err(e) => return e.to_compile_error().into(),
};
quote! {
#filter
}
} else {
quote! {
()
}
};
TokenStream::from(quote! {
impl #impl_generics #bevy_render_path::extract_component::ExtractComponent for #struct_name #type_generics #where_clause {
type QueryData = &'static Self;
type QueryFilter = #filter;
type Out = Self;
fn extract_component(item: #bevy_ecs_path::query::QueryItem<'_, '_, Self::QueryData>) -> Option<Self::Out> {
Some(item.clone())
}
}
})
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_render/src/settings.rs | crates/bevy_render/src/settings.rs | use crate::renderer::{
RenderAdapter, RenderAdapterInfo, RenderDevice, RenderInstance, RenderQueue,
};
use alloc::borrow::Cow;
pub use wgpu::{
Backends, Dx12Compiler, Features as WgpuFeatures, Gles3MinorVersion, InstanceFlags,
Limits as WgpuLimits, MemoryHints, PowerPreference,
};
use wgpu::{DxcShaderModel, MemoryBudgetThresholds};
/// Configures the priority used when automatically configuring the features/limits of `wgpu`.
#[derive(Clone)]
pub enum WgpuSettingsPriority {
/// WebGPU default features and limits
Compatibility,
/// The maximum supported features and limits of the adapter and backend
Functionality,
/// WebGPU default limits plus additional constraints in order to be compatible with WebGL2
WebGL2,
}
/// Provides configuration for renderer initialization. Use [`RenderDevice::features`](RenderDevice::features),
/// [`RenderDevice::limits`](RenderDevice::limits), and the [`RenderAdapterInfo`]
/// resource to get runtime information about the actual adapter, backend, features, and limits.
/// NOTE: [`Backends::DX12`](Backends::DX12), [`Backends::METAL`](Backends::METAL), and
/// [`Backends::VULKAN`](Backends::VULKAN) are enabled by default for non-web and the best choice
/// is automatically selected. Web using the `webgl` feature uses [`Backends::GL`](Backends::GL).
/// NOTE: If you want to use [`Backends::GL`](Backends::GL) in a native app on `Windows` and/or `macOS`, you must
/// use [`ANGLE`](https://github.com/gfx-rs/wgpu#angle) and enable the `gles` feature. This is
/// because wgpu requires EGL to create a GL context without a window and only ANGLE supports that.
#[derive(Clone)]
pub struct WgpuSettings {
pub device_label: Option<Cow<'static, str>>,
pub backends: Option<Backends>,
pub power_preference: PowerPreference,
pub priority: WgpuSettingsPriority,
/// The features to ensure are enabled regardless of what the adapter/backend supports.
/// Setting these explicitly may cause renderer initialization to fail.
pub features: WgpuFeatures,
/// The features to ensure are disabled regardless of what the adapter/backend supports
pub disabled_features: Option<WgpuFeatures>,
/// The imposed limits.
pub limits: WgpuLimits,
/// The constraints on limits allowed regardless of what the adapter/backend supports
pub constrained_limits: Option<WgpuLimits>,
/// The shader compiler to use for the DX12 backend.
pub dx12_shader_compiler: Dx12Compiler,
/// Allows you to choose which minor version of GLES3 to use (3.0, 3.1, 3.2, or automatic)
/// This only applies when using ANGLE and the GL backend.
pub gles3_minor_version: Gles3MinorVersion,
/// These are for controlling WGPU's debug information to eg. enable validation and shader debug info in release builds.
pub instance_flags: InstanceFlags,
/// This hints to the WGPU device about the preferred memory allocation strategy.
pub memory_hints: MemoryHints,
/// The thresholds for device memory budget.
pub instance_memory_budget_thresholds: MemoryBudgetThresholds,
/// If true, will force wgpu to use a software renderer, if available.
pub force_fallback_adapter: bool,
/// The name of the adapter to use.
pub adapter_name: Option<String>,
}
impl Default for WgpuSettings {
fn default() -> Self {
let default_backends = if cfg!(all(
feature = "webgl",
target_arch = "wasm32",
not(feature = "webgpu")
)) {
Backends::GL
} else if cfg!(all(feature = "webgpu", target_arch = "wasm32")) {
Backends::BROWSER_WEBGPU
} else {
Backends::all()
};
let backends = Some(Backends::from_env().unwrap_or(default_backends));
let power_preference =
PowerPreference::from_env().unwrap_or(PowerPreference::HighPerformance);
let priority = settings_priority_from_env().unwrap_or(WgpuSettingsPriority::Functionality);
let limits = if cfg!(all(
feature = "webgl",
target_arch = "wasm32",
not(feature = "webgpu")
)) || matches!(priority, WgpuSettingsPriority::WebGL2)
{
wgpu::Limits::downlevel_webgl2_defaults()
} else {
#[expect(clippy::allow_attributes, reason = "`unused_mut` is not always linted")]
#[allow(
unused_mut,
reason = "This variable needs to be mutable if the `ci_limits` feature is enabled"
)]
let mut limits = wgpu::Limits::default();
#[cfg(feature = "ci_limits")]
{
limits.max_storage_textures_per_shader_stage = 4;
limits.max_texture_dimension_3d = 1024;
}
limits
};
let dx12_shader_compiler =
Dx12Compiler::from_env().unwrap_or(if cfg!(feature = "statically-linked-dxc") {
Dx12Compiler::StaticDxc
} else {
let dxc = "dxcompiler.dll";
if cfg!(target_os = "windows") && std::fs::metadata(dxc).is_ok() {
Dx12Compiler::DynamicDxc {
dxc_path: String::from(dxc),
max_shader_model: DxcShaderModel::V6_7,
}
} else {
Dx12Compiler::Fxc
}
});
let gles3_minor_version = Gles3MinorVersion::from_env().unwrap_or_default();
let instance_flags = InstanceFlags::default().with_env();
Self {
device_label: Default::default(),
backends,
power_preference,
priority,
features: wgpu::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES,
disabled_features: None,
limits,
constrained_limits: None,
dx12_shader_compiler,
gles3_minor_version,
instance_flags,
memory_hints: MemoryHints::default(),
instance_memory_budget_thresholds: MemoryBudgetThresholds::default(),
force_fallback_adapter: false,
adapter_name: None,
}
}
}
#[derive(Clone)]
pub struct RenderResources(
pub RenderDevice,
pub RenderQueue,
pub RenderAdapterInfo,
pub RenderAdapter,
pub RenderInstance,
#[cfg(feature = "raw_vulkan_init")]
pub crate::renderer::raw_vulkan_init::AdditionalVulkanFeatures,
);
/// An enum describing how the renderer will initialize resources. This is used when creating the [`RenderPlugin`](crate::RenderPlugin).
#[expect(
clippy::large_enum_variant,
reason = "See https://github.com/bevyengine/bevy/issues/19220"
)]
pub enum RenderCreation {
/// Allows renderer resource initialization to happen outside of the rendering plugin.
Manual(RenderResources),
/// Lets the rendering plugin create resources itself.
Automatic(WgpuSettings),
}
impl RenderCreation {
/// Function to create a [`RenderCreation::Manual`] variant.
pub fn manual(
device: RenderDevice,
queue: RenderQueue,
adapter_info: RenderAdapterInfo,
adapter: RenderAdapter,
instance: RenderInstance,
#[cfg(feature = "raw_vulkan_init")]
additional_vulkan_features: crate::renderer::raw_vulkan_init::AdditionalVulkanFeatures,
) -> Self {
RenderResources(
device,
queue,
adapter_info,
adapter,
instance,
#[cfg(feature = "raw_vulkan_init")]
additional_vulkan_features,
)
.into()
}
}
impl From<RenderResources> for RenderCreation {
fn from(value: RenderResources) -> Self {
Self::Manual(value)
}
}
impl Default for RenderCreation {
fn default() -> Self {
Self::Automatic(Default::default())
}
}
impl From<WgpuSettings> for RenderCreation {
fn from(value: WgpuSettings) -> Self {
Self::Automatic(value)
}
}
/// Get a features/limits priority from the environment variable `WGPU_SETTINGS_PRIO`
pub fn settings_priority_from_env() -> Option<WgpuSettingsPriority> {
Some(
match std::env::var("WGPU_SETTINGS_PRIO")
.as_deref()
.map(str::to_lowercase)
.as_deref()
{
Ok("compatibility") => WgpuSettingsPriority::Compatibility,
Ok("functionality") => WgpuSettingsPriority::Functionality,
Ok("webgl2") => WgpuSettingsPriority::WebGL2,
_ => return None,
},
)
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_render/src/extract_resource.rs | crates/bevy_render/src/extract_resource.rs | use core::marker::PhantomData;
use bevy_app::{App, Plugin};
use bevy_ecs::prelude::*;
pub use bevy_render_macros::ExtractResource;
use bevy_utils::once;
use crate::{Extract, ExtractSchedule, RenderApp};
/// Describes how a resource gets extracted for rendering.
///
/// Therefore the resource is transferred from the "main world" into the "render world"
/// in the [`ExtractSchedule`] step.
pub trait ExtractResource: Resource {
type Source: Resource;
/// Defines how the resource is transferred into the "render world".
fn extract_resource(source: &Self::Source) -> Self;
}
/// This plugin extracts the resources into the "render world".
///
/// Therefore it sets up the[`ExtractSchedule`] step
/// for the specified [`Resource`].
pub struct ExtractResourcePlugin<R: ExtractResource>(PhantomData<R>);
impl<R: ExtractResource> Default for ExtractResourcePlugin<R> {
fn default() -> Self {
Self(PhantomData)
}
}
impl<R: ExtractResource> Plugin for ExtractResourcePlugin<R> {
fn build(&self, app: &mut App) {
if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
render_app.add_systems(ExtractSchedule, extract_resource::<R>);
} else {
once!(tracing::error!(
"Render app did not exist when trying to add `extract_resource` for <{}>.",
core::any::type_name::<R>()
));
}
}
}
/// This system extracts the resource of the corresponding [`Resource`] type
pub fn extract_resource<R: ExtractResource>(
mut commands: Commands,
main_resource: Extract<Option<Res<R::Source>>>,
target_resource: Option<ResMut<R>>,
) {
if let Some(main_resource) = main_resource.as_ref() {
if let Some(mut target_resource) = target_resource {
if main_resource.is_changed() {
*target_resource = R::extract_resource(main_resource);
}
} else {
#[cfg(debug_assertions)]
if !main_resource.is_added() {
once!(tracing::warn!(
"Removing resource {} from render world not expected, adding using `Commands`.
This may decrease performance",
core::any::type_name::<R>()
));
}
commands.insert_resource(R::extract_resource(main_resource));
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_render/src/lib.rs | crates/bevy_render/src/lib.rs | //! # Useful Environment Variables
//!
//! Both `bevy_render` and `wgpu` have a number of environment variable options for changing the runtime behavior
//! of both crates. Many of these may be useful in development or release environments.
//!
//! - `WGPU_DEBUG=1` enables debug labels, which can be useful in release builds.
//! - `WGPU_VALIDATION=0` disables validation layers. This can help with particularly spammy errors.
//! - `WGPU_FORCE_FALLBACK_ADAPTER=1` attempts to force software rendering. This typically matches what is used in CI.
//! - `WGPU_ADAPTER_NAME` allows selecting a specific adapter by name.
//! - `WGPU_SETTINGS_PRIO=webgl2` uses webgl2 limits.
//! - `WGPU_SETTINGS_PRIO=compatibility` uses webgpu limits.
//! - `VERBOSE_SHADER_ERROR=1` prints more detailed information about WGSL compilation errors, such as shader defs and shader entrypoint.
#![expect(missing_docs, reason = "Not all docs are written yet, see #3492.")]
#![expect(unsafe_code, reason = "Unsafe code is used to improve performance.")]
#![cfg_attr(
any(docsrs, docsrs_dep),
expect(
internal_features,
reason = "rustdoc_internals is needed for fake_variadic"
)
)]
#![cfg_attr(any(docsrs, docsrs_dep), feature(doc_cfg, rustdoc_internals))]
#![doc(
html_logo_url = "https://bevy.org/assets/icon.png",
html_favicon_url = "https://bevy.org/assets/icon.png"
)]
#[cfg(target_pointer_width = "16")]
compile_error!("bevy_render cannot compile for a 16-bit platform.");
extern crate alloc;
extern crate core;
// Required to make proc macros work in bevy itself.
extern crate self as bevy_render;
pub mod alpha;
pub mod batching;
pub mod camera;
pub mod diagnostic;
pub mod erased_render_asset;
pub mod experimental;
pub mod extract_component;
pub mod extract_instances;
mod extract_param;
pub mod extract_resource;
pub mod globals;
pub mod gpu_component_array_buffer;
pub mod gpu_readback;
pub mod mesh;
#[cfg(not(target_arch = "wasm32"))]
pub mod pipelined_rendering;
pub mod render_asset;
pub mod render_graph;
pub mod render_phase;
pub mod render_resource;
pub mod renderer;
pub mod settings;
pub mod storage;
pub mod sync_component;
pub mod sync_world;
pub mod texture;
pub mod view;
/// The render prelude.
///
/// This includes the most common types in this crate, re-exported for your convenience.
pub mod prelude {
#[doc(hidden)]
pub use crate::{
alpha::AlphaMode, camera::NormalizedRenderTargetExt as _, texture::ManualTextureViews,
view::Msaa, ExtractSchedule,
};
}
pub use extract_param::Extract;
use crate::{
camera::CameraPlugin,
gpu_readback::GpuReadbackPlugin,
mesh::{MeshRenderAssetPlugin, RenderMesh},
render_asset::prepare_assets,
render_resource::PipelineCache,
renderer::{render_system, RenderAdapterInfo},
settings::RenderCreation,
storage::StoragePlugin,
texture::TexturePlugin,
view::{ViewPlugin, WindowRenderPlugin},
};
use alloc::sync::Arc;
use batching::gpu_preprocessing::BatchingPlugin;
use bevy_app::{App, AppLabel, Plugin, SubApp};
use bevy_asset::{AssetApp, AssetServer};
use bevy_ecs::{
prelude::*,
schedule::{ScheduleBuildSettings, ScheduleLabel},
};
use bevy_image::{CompressedImageFormatSupport, CompressedImageFormats};
use bevy_shader::{load_shader_library, Shader, ShaderLoader};
use bevy_utils::prelude::default;
use bevy_window::{PrimaryWindow, RawHandleWrapperHolder};
use bitflags::bitflags;
use core::ops::{Deref, DerefMut};
use experimental::occlusion_culling::OcclusionCullingPlugin;
use globals::GlobalsPlugin;
use render_asset::{
extract_render_asset_bytes_per_frame, reset_render_asset_bytes_per_frame,
RenderAssetBytesPerFrame, RenderAssetBytesPerFrameLimiter,
};
use settings::RenderResources;
use std::sync::Mutex;
use sync_world::{despawn_temporary_render_entities, entity_sync_system, SyncWorldPlugin};
/// Contains the default Bevy rendering backend based on wgpu.
///
/// Rendering is done in a [`SubApp`], which exchanges data with the main app
/// between main schedule iterations.
///
/// Rendering can be executed between iterations of the main schedule,
/// or it can be executed in parallel with main schedule when
/// [`PipelinedRenderingPlugin`](pipelined_rendering::PipelinedRenderingPlugin) is enabled.
#[derive(Default)]
pub struct RenderPlugin {
pub render_creation: RenderCreation,
/// If `true`, disables asynchronous pipeline compilation.
/// This has no effect on macOS, Wasm, iOS, or without the `multi_threaded` feature.
pub synchronous_pipeline_compilation: bool,
/// Debugging flags that can optionally be set when constructing the renderer.
pub debug_flags: RenderDebugFlags,
}
bitflags! {
/// Debugging flags that can optionally be set when constructing the renderer.
#[derive(Clone, Copy, PartialEq, Default, Debug)]
pub struct RenderDebugFlags: u8 {
/// If true, this sets the `COPY_SRC` flag on indirect draw parameters
/// so that they can be read back to CPU.
///
/// This is a debugging feature that may reduce performance. It
/// primarily exists for the `occlusion_culling` example.
const ALLOW_COPIES_FROM_INDIRECT_PARAMETERS = 1;
}
}
/// The systems sets of the default [`App`] rendering schedule.
///
/// These can be useful for ordering, but you almost never want to add your systems to these sets.
#[derive(Debug, Hash, PartialEq, Eq, Clone, SystemSet)]
pub enum RenderSystems {
/// This is used for applying the commands from the [`ExtractSchedule`]
ExtractCommands,
/// Prepare assets that have been created/modified/removed this frame.
PrepareAssets,
/// Prepares extracted meshes.
PrepareMeshes,
/// Create any additional views such as those used for shadow mapping.
ManageViews,
/// Queue drawable entities as phase items in render phases ready for
/// sorting (if necessary)
Queue,
/// A sub-set within [`Queue`](RenderSystems::Queue) where mesh entity queue systems are executed. Ensures `prepare_assets::<RenderMesh>` is completed.
QueueMeshes,
/// A sub-set within [`Queue`](RenderSystems::Queue) where meshes that have
/// become invisible or changed phases are removed from the bins.
QueueSweep,
// TODO: This could probably be moved in favor of a system ordering
// abstraction in `Render` or `Queue`
/// Sort the [`SortedRenderPhase`](render_phase::SortedRenderPhase)s and
/// [`BinKey`](render_phase::BinnedPhaseItem::BinKey)s here.
PhaseSort,
/// Prepare render resources from extracted data for the GPU based on their sorted order.
/// Create [`BindGroups`](render_resource::BindGroup) that depend on those data.
Prepare,
/// A sub-set within [`Prepare`](RenderSystems::Prepare) for initializing buffers, textures and uniforms for use in bind groups.
PrepareResources,
/// Collect phase buffers after
/// [`PrepareResources`](RenderSystems::PrepareResources) has run.
PrepareResourcesCollectPhaseBuffers,
/// Flush buffers after [`PrepareResources`](RenderSystems::PrepareResources), but before [`PrepareBindGroups`](RenderSystems::PrepareBindGroups).
PrepareResourcesFlush,
/// A sub-set within [`Prepare`](RenderSystems::Prepare) for constructing bind groups, or other data that relies on render resources prepared in [`PrepareResources`](RenderSystems::PrepareResources).
PrepareBindGroups,
/// Actual rendering happens here.
/// In most cases, only the render backend should insert resources here.
Render,
/// Cleanup render resources here.
Cleanup,
/// Final cleanup occurs: any entities with
/// [`TemporaryRenderEntity`](sync_world::TemporaryRenderEntity) will be despawned.
///
/// Runs after [`Cleanup`](RenderSystems::Cleanup).
PostCleanup,
}
/// The startup schedule of the [`RenderApp`]
#[derive(ScheduleLabel, Debug, Hash, PartialEq, Eq, Clone, Default)]
pub struct RenderStartup;
/// The main render schedule.
#[derive(ScheduleLabel, Debug, Hash, PartialEq, Eq, Clone, Default)]
pub struct Render;
impl Render {
/// Sets up the base structure of the rendering [`Schedule`].
///
/// The sets defined in this enum are configured to run in order.
pub fn base_schedule() -> Schedule {
use RenderSystems::*;
let mut schedule = Schedule::new(Self);
schedule.configure_sets(
(
ExtractCommands,
PrepareMeshes,
ManageViews,
Queue,
PhaseSort,
Prepare,
Render,
Cleanup,
PostCleanup,
)
.chain(),
);
schedule.configure_sets((ExtractCommands, PrepareAssets, PrepareMeshes, Prepare).chain());
schedule.configure_sets(
(QueueMeshes, QueueSweep)
.chain()
.in_set(Queue)
.after(prepare_assets::<RenderMesh>),
);
schedule.configure_sets(
(
PrepareResources,
PrepareResourcesCollectPhaseBuffers,
PrepareResourcesFlush,
PrepareBindGroups,
)
.chain()
.in_set(Prepare),
);
schedule
}
}
/// Schedule in which data from the main world is 'extracted' into the render world.
///
/// This step should be kept as short as possible to increase the "pipelining potential" for
/// running the next frame while rendering the current frame.
///
/// This schedule is run on the render world, but it also has access to the main world.
/// See [`MainWorld`] and [`Extract`] for details on how to access main world data from this schedule.
#[derive(ScheduleLabel, PartialEq, Eq, Debug, Clone, Hash, Default)]
pub struct ExtractSchedule;
/// The simulation [`World`] of the application, stored as a resource.
///
/// This resource is only available during [`ExtractSchedule`] and not
/// during command application of that schedule.
/// See [`Extract`] for more details.
#[derive(Resource, Default)]
pub struct MainWorld(World);
impl Deref for MainWorld {
type Target = World;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for MainWorld {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
pub mod graph {
use crate::render_graph::RenderLabel;
#[derive(Debug, Hash, PartialEq, Eq, Clone, RenderLabel)]
pub struct CameraDriverLabel;
}
#[derive(Resource)]
struct FutureRenderResources(Arc<Mutex<Option<RenderResources>>>);
/// A label for the rendering sub-app.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, AppLabel)]
pub struct RenderApp;
impl Plugin for RenderPlugin {
/// Initializes the renderer, sets up the [`RenderSystems`] and creates the rendering sub-app.
fn build(&self, app: &mut App) {
app.init_asset::<Shader>()
.init_asset_loader::<ShaderLoader>();
match &self.render_creation {
RenderCreation::Manual(resources) => {
let future_render_resources_wrapper = Arc::new(Mutex::new(Some(resources.clone())));
app.insert_resource(FutureRenderResources(
future_render_resources_wrapper.clone(),
));
// SAFETY: Plugins should be set up on the main thread.
unsafe { initialize_render_app(app) };
}
RenderCreation::Automatic(render_creation) => {
if let Some(backends) = render_creation.backends {
let future_render_resources_wrapper = Arc::new(Mutex::new(None));
app.insert_resource(FutureRenderResources(
future_render_resources_wrapper.clone(),
));
let primary_window = app
.world_mut()
.query_filtered::<&RawHandleWrapperHolder, With<PrimaryWindow>>()
.single(app.world())
.ok()
.cloned();
let settings = render_creation.clone();
#[cfg(feature = "raw_vulkan_init")]
let raw_vulkan_init_settings = app
.world_mut()
.get_resource::<renderer::raw_vulkan_init::RawVulkanInitSettings>()
.cloned()
.unwrap_or_default();
let async_renderer = async move {
let render_resources = renderer::initialize_renderer(
backends,
primary_window,
&settings,
#[cfg(feature = "raw_vulkan_init")]
raw_vulkan_init_settings,
)
.await;
*future_render_resources_wrapper.lock().unwrap() = Some(render_resources);
};
// In wasm, spawn a task and detach it for execution
#[cfg(target_arch = "wasm32")]
bevy_tasks::IoTaskPool::get()
.spawn_local(async_renderer)
.detach();
// Otherwise, just block for it to complete
#[cfg(not(target_arch = "wasm32"))]
bevy_tasks::block_on(async_renderer);
// SAFETY: Plugins should be set up on the main thread.
unsafe { initialize_render_app(app) };
}
}
};
app.add_plugins((
WindowRenderPlugin,
CameraPlugin,
ViewPlugin,
MeshRenderAssetPlugin,
GlobalsPlugin,
#[cfg(feature = "morph")]
mesh::MorphPlugin,
TexturePlugin,
BatchingPlugin {
debug_flags: self.debug_flags,
},
SyncWorldPlugin,
StoragePlugin,
GpuReadbackPlugin::default(),
OcclusionCullingPlugin,
#[cfg(feature = "tracing-tracy")]
diagnostic::RenderDiagnosticsPlugin,
));
app.init_resource::<RenderAssetBytesPerFrame>();
if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
render_app.init_resource::<RenderAssetBytesPerFrameLimiter>();
render_app
.add_systems(ExtractSchedule, extract_render_asset_bytes_per_frame)
.add_systems(
Render,
reset_render_asset_bytes_per_frame.in_set(RenderSystems::Cleanup),
);
}
}
fn ready(&self, app: &App) -> bool {
app.world()
.get_resource::<FutureRenderResources>()
.and_then(|frr| frr.0.try_lock().map(|locked| locked.is_some()).ok())
.unwrap_or(true)
}
fn finish(&self, app: &mut App) {
load_shader_library!(app, "maths.wgsl");
load_shader_library!(app, "color_operations.wgsl");
load_shader_library!(app, "bindless.wgsl");
if let Some(future_render_resources) =
app.world_mut().remove_resource::<FutureRenderResources>()
{
let render_resources = future_render_resources.0.lock().unwrap().take().unwrap();
let RenderResources(device, queue, adapter_info, render_adapter, instance, ..) =
render_resources;
let compressed_image_format_support = CompressedImageFormatSupport(
CompressedImageFormats::from_features(device.features()),
);
app.insert_resource(device.clone())
.insert_resource(queue.clone())
.insert_resource(adapter_info.clone())
.insert_resource(render_adapter.clone())
.insert_resource(compressed_image_format_support);
let render_app = app.sub_app_mut(RenderApp);
#[cfg(feature = "raw_vulkan_init")]
{
let additional_vulkan_features: renderer::raw_vulkan_init::AdditionalVulkanFeatures =
render_resources.5;
render_app.insert_resource(additional_vulkan_features);
}
render_app
.insert_resource(instance)
.insert_resource(PipelineCache::new(
device.clone(),
render_adapter.clone(),
self.synchronous_pipeline_compilation,
))
.insert_resource(device)
.insert_resource(queue)
.insert_resource(render_adapter)
.insert_resource(adapter_info);
}
}
}
/// A "scratch" world used to avoid allocating new worlds every frame when
/// swapping out the [`MainWorld`] for [`ExtractSchedule`].
#[derive(Resource, Default)]
struct ScratchMainWorld(World);
/// Executes the [`ExtractSchedule`] step of the renderer.
/// This updates the render world with the extracted ECS data of the current frame.
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::<ScratchMainWorld>().unwrap();
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::<MainWorld>().unwrap();
let scratch_world = core::mem::replace(main_world, inserted_world.0);
main_world.insert_resource(ScratchMainWorld(scratch_world));
}
/// # Safety
/// This function must be called from the main thread.
unsafe fn initialize_render_app(app: &mut App) {
app.init_resource::<ScratchMainWorld>();
let mut render_app = SubApp::new();
render_app.update_schedule = Some(Render.intern());
let mut extract_schedule = Schedule::new(ExtractSchedule);
// We skip applying any commands during the ExtractSchedule
// so commands can be applied on the render thread.
extract_schedule.set_build_settings(ScheduleBuildSettings {
auto_insert_apply_deferred: false,
..default()
});
extract_schedule.set_apply_final_deferred(false);
render_app
.add_schedule(extract_schedule)
.add_schedule(Render::base_schedule())
.init_resource::<render_graph::RenderGraph>()
.insert_resource(app.world().resource::<AssetServer>().clone())
.add_systems(ExtractSchedule, PipelineCache::extract_shaders)
.add_systems(
Render,
(
// This set applies the commands from the extract schedule while the render schedule
// is running in parallel with the main app.
apply_extract_commands.in_set(RenderSystems::ExtractCommands),
(PipelineCache::process_pipeline_queue_system, render_system)
.chain()
.in_set(RenderSystems::Render),
despawn_temporary_render_entities.in_set(RenderSystems::PostCleanup),
),
);
// We want the closure to have a flag to only run the RenderStartup schedule once, but the only
// way to have the closure store this flag is by capturing it. This variable is otherwise
// unused.
let mut should_run_startup = true;
render_app.set_extract(move |main_world, render_world| {
if should_run_startup {
// Run the `RenderStartup` if it hasn't run yet. This does mean `RenderStartup` blocks
// the rest of the app extraction, but this is necessary since extraction itself can
// depend on resources initialized in `RenderStartup`.
render_world.run_schedule(RenderStartup);
should_run_startup = false;
}
{
#[cfg(feature = "trace")]
let _stage_span = tracing::info_span!("entity_sync").entered();
entity_sync_system(main_world, render_world);
}
// run extract schedule
extract(main_world, render_world);
});
let (sender, receiver) = bevy_time::create_time_channels();
render_app.insert_resource(sender);
app.insert_resource(receiver);
app.insert_sub_app(RenderApp, render_app);
}
/// Applies the commands from the extract schedule. This happens during
/// the render schedule rather than during extraction to allow the commands to run in parallel with the
/// main app when pipelined rendering is enabled.
fn apply_extract_commands(render_world: &mut World) {
render_world.resource_scope(|render_world, mut schedules: Mut<Schedules>| {
schedules
.get_mut(ExtractSchedule)
.unwrap()
.apply_deferred(render_world);
});
}
/// If the [`RenderAdapterInfo`] is a Qualcomm Adreno, returns its model number.
///
/// This lets us work around hardware bugs.
pub fn get_adreno_model(adapter_info: &RenderAdapterInfo) -> Option<u32> {
if !cfg!(target_os = "android") {
return None;
}
let adreno_model = adapter_info.name.strip_prefix("Adreno (TM) ")?;
// Take suffixes into account (like Adreno 642L).
Some(
adreno_model
.chars()
.map_while(|c| c.to_digit(10))
.fold(0, |acc, digit| acc * 10 + digit),
)
}
/// Get the Mali driver version if the adapter is a Mali GPU.
pub fn get_mali_driver_version(adapter_info: &RenderAdapterInfo) -> Option<u32> {
if !cfg!(target_os = "android") {
return None;
}
if !adapter_info.name.contains("Mali") {
return None;
}
let driver_info = &adapter_info.driver_info;
if let Some(start_pos) = driver_info.find("v1.r")
&& let Some(end_pos) = driver_info[start_pos..].find('p')
{
let start_idx = start_pos + 4; // Skip "v1.r"
let end_idx = start_pos + end_pos;
return driver_info[start_idx..end_idx].parse::<u32>().ok();
}
None
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_render/src/alpha.rs | crates/bevy_render/src/alpha.rs | 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.
#[derive(Debug, Default, Reflect, Copy, Clone, PartialEq)]
#[reflect(Default, Debug, Clone)]
pub enum AlphaMode {
/// Base color alpha values are overridden to be fully opaque (1.0).
#[default]
Opaque,
/// Reduce transparency to fully opaque or fully transparent
/// based on a threshold.
///
/// Compares the base color alpha value to the specified threshold.
/// If the value is below the threshold,
/// considers the color to be fully transparent (alpha is set to 0.0).
/// If it is equal to or above the threshold,
/// considers the color to be fully opaque (alpha is set to 1.0).
Mask(f32),
/// The base color alpha value defines the opacity of the color.
/// Standard alpha-blending is used to blend the fragment's color
/// with the color behind it.
Blend,
/// Similar to [`AlphaMode::Blend`], however assumes RGB channel values are
/// [premultiplied](https://en.wikipedia.org/wiki/Alpha_compositing#Straight_versus_premultiplied).
///
/// For otherwise constant RGB values, behaves more like [`AlphaMode::Blend`] for
/// alpha values closer to 1.0, and more like [`AlphaMode::Add`] for
/// alpha values closer to 0.0.
///
/// Can be used to avoid “border” or “outline” artifacts that can occur
/// when using plain alpha-blended textures.
Premultiplied,
/// Spreads the fragment out over a hardware-dependent number of sample
/// locations proportional to the alpha value. This requires multisample
/// antialiasing; if MSAA isn't on, this is identical to
/// [`AlphaMode::Mask`] with a value of 0.5.
///
/// Alpha to coverage provides improved performance and better visual
/// fidelity over [`AlphaMode::Blend`], as Bevy doesn't have to sort objects
/// when it's in use. It's especially useful for complex transparent objects
/// like foliage.
///
/// [alpha to coverage]: https://en.wikipedia.org/wiki/Alpha_to_coverage
AlphaToCoverage,
/// Combines the color of the fragments with the colors behind them in an
/// additive process, (i.e. like light) producing lighter results.
///
/// Black produces no effect. Alpha values can be used to modulate the result.
///
/// Useful for effects like holograms, ghosts, lasers and other energy beams.
Add,
/// Combines the color of the fragments with the colors behind them in a
/// multiplicative process, (i.e. like pigments) producing darker results.
///
/// White produces no effect. Alpha values can be used to modulate the result.
///
/// Useful for effects like stained glass, window tint film and some colored liquids.
Multiply,
}
impl Eq for AlphaMode {}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_render/src/gpu_readback.rs | crates/bevy_render/src/gpu_readback.rs | use crate::{
extract_component::ExtractComponentPlugin,
render_asset::RenderAssets,
render_resource::{
Buffer, BufferUsages, CommandEncoder, Extent3d, TexelCopyBufferLayout, Texture,
TextureFormat,
},
renderer::{render_system, RenderDevice},
storage::{GpuShaderStorageBuffer, ShaderStorageBuffer},
sync_world::MainEntity,
texture::GpuImage,
ExtractSchedule, MainWorld, Render, RenderApp, RenderSystems,
};
use async_channel::{Receiver, Sender};
use bevy_app::{App, Plugin};
use bevy_asset::Handle;
use bevy_derive::{Deref, DerefMut};
use bevy_ecs::schedule::IntoScheduleConfigs;
use bevy_ecs::{
change_detection::ResMut,
entity::Entity,
event::EntityEvent,
prelude::{Component, Resource, World},
system::{Query, Res},
};
use bevy_image::{Image, TextureFormatPixelInfo};
use bevy_platform::collections::HashMap;
use bevy_reflect::Reflect;
use bevy_render_macros::ExtractComponent;
use encase::internal::ReadFrom;
use encase::private::Reader;
use encase::ShaderType;
use tracing::warn;
/// A plugin that enables reading back gpu buffers and textures to the cpu.
pub struct GpuReadbackPlugin {
/// Describes the number of frames a buffer can be unused before it is removed from the pool in
/// order to avoid unnecessary reallocations.
max_unused_frames: usize,
}
impl Default for GpuReadbackPlugin {
fn default() -> Self {
Self {
max_unused_frames: 10,
}
}
}
impl Plugin for GpuReadbackPlugin {
fn build(&self, app: &mut App) {
app.add_plugins(ExtractComponentPlugin::<Readback>::default());
if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
render_app
.init_resource::<GpuReadbackBufferPool>()
.init_resource::<GpuReadbacks>()
.insert_resource(GpuReadbackMaxUnusedFrames(self.max_unused_frames))
.add_systems(ExtractSchedule, sync_readbacks.ambiguous_with_all())
.add_systems(
Render,
(
prepare_buffers.in_set(RenderSystems::PrepareResources),
map_buffers
.after(render_system)
.in_set(RenderSystems::Render),
),
);
}
}
}
/// A component that registers the wrapped handle for gpu readback, either a texture or a buffer.
///
/// Data is read asynchronously and will be triggered on the entity via the [`ReadbackComplete`] event
/// when complete. If this component is not removed, the readback will be attempted every frame
#[derive(Component, ExtractComponent, Clone, Debug)]
pub enum Readback {
Texture(Handle<Image>),
Buffer {
buffer: Handle<ShaderStorageBuffer>,
start_offset_and_size: Option<(u64, u64)>,
},
}
impl Readback {
/// Create a readback component for a texture using the given handle.
pub fn texture(image: Handle<Image>) -> Self {
Self::Texture(image)
}
/// Create a readback component for a full buffer using the given handle.
pub fn buffer(buffer: Handle<ShaderStorageBuffer>) -> Self {
Self::Buffer {
buffer,
start_offset_and_size: None,
}
}
/// Create a readback component for a buffer range using the given handle, a start offset in bytes
/// and a number of bytes to read.
pub fn buffer_range(buffer: Handle<ShaderStorageBuffer>, start_offset: u64, size: u64) -> Self {
Self::Buffer {
buffer,
start_offset_and_size: Some((start_offset, size)),
}
}
}
/// An event that is triggered when a gpu readback is complete.
///
/// The event contains the data as a `Vec<u8>`, which can be interpreted as the raw bytes of the
/// requested buffer or texture.
#[derive(EntityEvent, Deref, DerefMut, Reflect, Debug)]
#[reflect(Debug)]
pub struct ReadbackComplete {
pub entity: Entity,
#[deref]
pub data: Vec<u8>,
}
impl ReadbackComplete {
/// Convert the raw bytes of the event to a shader type.
pub fn to_shader_type<T: ShaderType + ReadFrom + Default>(&self) -> T {
let mut val = T::default();
let mut reader = Reader::new::<T>(&self.data, 0).expect("Failed to create Reader");
T::read_from(&mut val, &mut reader);
val
}
}
#[derive(Resource)]
struct GpuReadbackMaxUnusedFrames(usize);
struct GpuReadbackBuffer {
buffer: Buffer,
taken: bool,
frames_unused: usize,
}
#[derive(Resource, Default)]
struct GpuReadbackBufferPool {
// Map of buffer size to list of buffers, with a flag for whether the buffer is taken and how
// many frames it has been unused for.
// TODO: We could ideally write all readback data to one big buffer per frame, the assumption
// here is that very few entities well actually be read back at once, and their size is
// unlikely to change.
buffers: HashMap<u64, Vec<GpuReadbackBuffer>>,
}
impl GpuReadbackBufferPool {
fn get(&mut self, render_device: &RenderDevice, size: u64) -> Buffer {
let buffers = self.buffers.entry(size).or_default();
// find an untaken buffer for this size
if let Some(buf) = buffers.iter_mut().find(|x| !x.taken) {
buf.taken = true;
buf.frames_unused = 0;
return buf.buffer.clone();
}
let buffer = render_device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Readback Buffer"),
size,
usage: BufferUsages::COPY_DST | BufferUsages::MAP_READ,
mapped_at_creation: false,
});
buffers.push(GpuReadbackBuffer {
buffer: buffer.clone(),
taken: true,
frames_unused: 0,
});
buffer
}
// Returns the buffer to the pool so it can be used in a future frame
fn return_buffer(&mut self, buffer: &Buffer) {
let size = buffer.size();
let buffers = self
.buffers
.get_mut(&size)
.expect("Returned buffer of untracked size");
if let Some(buf) = buffers.iter_mut().find(|x| x.buffer.id() == buffer.id()) {
buf.taken = false;
} else {
warn!("Returned buffer that was not allocated");
}
}
fn update(&mut self, max_unused_frames: usize) {
for (_, buffers) in &mut self.buffers {
// Tick all the buffers
for buf in &mut *buffers {
if !buf.taken {
buf.frames_unused += 1;
}
}
// Remove buffers that haven't been used for MAX_UNUSED_FRAMES
buffers.retain(|x| x.frames_unused < max_unused_frames);
}
// Remove empty buffer sizes
self.buffers.retain(|_, buffers| !buffers.is_empty());
}
}
enum ReadbackSource {
Texture {
texture: Texture,
layout: TexelCopyBufferLayout,
size: Extent3d,
},
Buffer {
buffer: Buffer,
start_offset_and_size: Option<(u64, u64)>,
},
}
#[derive(Resource, Default)]
struct GpuReadbacks {
requested: Vec<GpuReadback>,
mapped: Vec<GpuReadback>,
}
struct GpuReadback {
pub entity: Entity,
pub src: ReadbackSource,
pub buffer: Buffer,
pub rx: Receiver<(Entity, Buffer, Vec<u8>)>,
pub tx: Sender<(Entity, Buffer, Vec<u8>)>,
}
fn sync_readbacks(
mut main_world: ResMut<MainWorld>,
mut buffer_pool: ResMut<GpuReadbackBufferPool>,
mut readbacks: ResMut<GpuReadbacks>,
max_unused_frames: Res<GpuReadbackMaxUnusedFrames>,
) {
readbacks.mapped.retain(|readback| {
if let Ok((entity, buffer, data)) = readback.rx.try_recv() {
main_world.trigger(ReadbackComplete { data, entity });
buffer_pool.return_buffer(&buffer);
false
} else {
true
}
});
buffer_pool.update(max_unused_frames.0);
}
fn prepare_buffers(
render_device: Res<RenderDevice>,
mut readbacks: ResMut<GpuReadbacks>,
mut buffer_pool: ResMut<GpuReadbackBufferPool>,
gpu_images: Res<RenderAssets<GpuImage>>,
ssbos: Res<RenderAssets<GpuShaderStorageBuffer>>,
handles: Query<(&MainEntity, &Readback)>,
) {
for (entity, readback) in handles.iter() {
match readback {
Readback::Texture(image) => {
if let Some(gpu_image) = gpu_images.get(image)
&& let Ok(pixel_size) = gpu_image.texture_format.pixel_size()
{
let layout = layout_data(gpu_image.size, gpu_image.texture_format);
let buffer = buffer_pool.get(
&render_device,
get_aligned_size(gpu_image.size, pixel_size as u32) as u64,
);
let (tx, rx) = async_channel::bounded(1);
readbacks.requested.push(GpuReadback {
entity: entity.id(),
src: ReadbackSource::Texture {
texture: gpu_image.texture.clone(),
layout,
size: gpu_image.size,
},
buffer,
rx,
tx,
});
}
}
Readback::Buffer {
buffer,
start_offset_and_size,
} => {
if let Some(ssbo) = ssbos.get(buffer) {
let full_size = ssbo.buffer.size();
let size = start_offset_and_size
.map(|(start, size)| {
let end = start + size;
if end > full_size {
panic!(
"Tried to read past the end of the buffer (start: {start}, \
size: {size}, buffer size: {full_size})."
);
}
size
})
.unwrap_or(full_size);
let buffer = buffer_pool.get(&render_device, size);
let (tx, rx) = async_channel::bounded(1);
readbacks.requested.push(GpuReadback {
entity: entity.id(),
src: ReadbackSource::Buffer {
start_offset_and_size: *start_offset_and_size,
buffer: ssbo.buffer.clone(),
},
buffer,
rx,
tx,
});
}
}
}
}
}
pub(crate) fn submit_readback_commands(world: &World, command_encoder: &mut CommandEncoder) {
let readbacks = world.resource::<GpuReadbacks>();
for readback in &readbacks.requested {
match &readback.src {
ReadbackSource::Texture {
texture,
layout,
size,
} => {
command_encoder.copy_texture_to_buffer(
texture.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &readback.buffer,
layout: *layout,
},
*size,
);
}
ReadbackSource::Buffer {
buffer,
start_offset_and_size,
} => {
let (src_start, size) = start_offset_and_size.unwrap_or((0, buffer.size()));
command_encoder.copy_buffer_to_buffer(buffer, src_start, &readback.buffer, 0, size);
}
}
}
}
/// Move requested readbacks to mapped readbacks after commands have been submitted in render system
fn map_buffers(mut readbacks: ResMut<GpuReadbacks>) {
let requested = readbacks.requested.drain(..).collect::<Vec<GpuReadback>>();
for readback in requested {
let slice = readback.buffer.slice(..);
let entity = readback.entity;
let buffer = readback.buffer.clone();
let tx = readback.tx.clone();
slice.map_async(wgpu::MapMode::Read, move |res| {
res.expect("Failed to map buffer");
let buffer_slice = buffer.slice(..);
let data = buffer_slice.get_mapped_range();
let result = Vec::from(&*data);
drop(data);
buffer.unmap();
if let Err(e) = tx.try_send((entity, buffer, result)) {
warn!("Failed to send readback result: {}", e);
}
});
readbacks.mapped.push(readback);
}
}
// Utils
/// Round up a given value to be a multiple of [`wgpu::COPY_BYTES_PER_ROW_ALIGNMENT`].
pub(crate) const fn align_byte_size(value: u32) -> u32 {
RenderDevice::align_copy_bytes_per_row(value as usize) as u32
}
/// Get the size of a image when the size of each row has been rounded up to [`wgpu::COPY_BYTES_PER_ROW_ALIGNMENT`].
pub(crate) const fn get_aligned_size(extent: Extent3d, pixel_size: u32) -> u32 {
extent.height * align_byte_size(extent.width * pixel_size) * extent.depth_or_array_layers
}
/// Get a [`TexelCopyBufferLayout`] aligned such that the image can be copied into a buffer.
pub(crate) fn layout_data(extent: Extent3d, format: TextureFormat) -> TexelCopyBufferLayout {
TexelCopyBufferLayout {
bytes_per_row: if extent.height > 1 || extent.depth_or_array_layers > 1 {
if let Ok(pixel_size) = format.pixel_size() {
// 1 = 1 row
Some(get_aligned_size(
Extent3d {
width: extent.width,
height: 1,
depth_or_array_layers: 1,
},
pixel_size as u32,
))
} else {
None
}
} else {
None
},
rows_per_image: if extent.depth_or_array_layers > 1 {
let (_, block_dimension_y) = format.block_dimensions();
Some(extent.height / block_dimension_y)
} else {
None
},
offset: 0,
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_render/src/render_asset.rs | crates/bevy_render/src/render_asset.rs | use crate::{
render_resource::AsBindGroupError, Extract, ExtractSchedule, MainWorld, Render, RenderApp,
RenderSystems, Res,
};
use bevy_app::{App, Plugin, SubApp};
use bevy_asset::{Asset, AssetEvent, AssetId, Assets, RenderAssetUsages};
use bevy_ecs::{
prelude::{Commands, IntoScheduleConfigs, MessageReader, ResMut, Resource},
schedule::{ScheduleConfigs, SystemSet},
system::{ScheduleSystem, StaticSystemParam, SystemParam, SystemParamItem, SystemState},
world::{FromWorld, Mut},
};
use bevy_platform::collections::{HashMap, HashSet};
use core::marker::PhantomData;
use core::sync::atomic::{AtomicUsize, Ordering};
use thiserror::Error;
use tracing::{debug, error};
#[derive(Debug, Error)]
pub enum PrepareAssetError<E: Send + Sync + 'static> {
#[error("Failed to prepare asset")]
RetryNextUpdate(E),
#[error("Failed to build bind group: {0}")]
AsBindGroupError(AsBindGroupError),
}
/// The system set during which we extract modified assets to the render world.
#[derive(SystemSet, Clone, PartialEq, Eq, Debug, Hash)]
pub struct AssetExtractionSystems;
/// Error returned when an asset due for extraction has already been extracted
#[derive(Debug, Error)]
pub enum AssetExtractionError {
#[error("The asset has already been extracted")]
AlreadyExtracted,
#[error("The asset type does not support extraction. To clone the asset to the renderworld, use `RenderAssetUsages::default()`")]
NoExtractionImplementation,
}
/// Describes how an asset gets extracted and prepared for rendering.
///
/// In the [`ExtractSchedule`] step the [`RenderAsset::SourceAsset`] is transferred
/// from the "main world" into the "render world".
///
/// After that in the [`RenderSystems::PrepareAssets`] step the extracted asset
/// is transformed into its GPU-representation of type [`RenderAsset`].
pub trait RenderAsset: Send + Sync + 'static + Sized {
/// The representation of the asset in the "main world".
type SourceAsset: Asset + Clone;
/// Specifies all ECS data required by [`RenderAsset::prepare_asset`].
///
/// For convenience use the [`lifetimeless`](bevy_ecs::system::lifetimeless) [`SystemParam`].
type Param: SystemParam;
/// Whether or not to unload the asset after extracting it to the render world.
#[inline]
fn asset_usage(_source_asset: &Self::SourceAsset) -> RenderAssetUsages {
RenderAssetUsages::default()
}
/// Size of the data the asset will upload to the gpu. Specifying a return value
/// will allow the asset to be throttled via [`RenderAssetBytesPerFrame`].
#[inline]
#[expect(
unused_variables,
reason = "The parameters here are intentionally unused by the default implementation; however, putting underscores here will result in the underscores being copied by rust-analyzer's tab completion."
)]
fn byte_len(source_asset: &Self::SourceAsset) -> Option<usize> {
None
}
/// Prepares the [`RenderAsset::SourceAsset`] for the GPU by transforming it into a [`RenderAsset`].
///
/// ECS data may be accessed via `param`.
fn prepare_asset(
source_asset: Self::SourceAsset,
asset_id: AssetId<Self::SourceAsset>,
param: &mut SystemParamItem<Self::Param>,
previous_asset: Option<&Self>,
) -> Result<Self, PrepareAssetError<Self::SourceAsset>>;
/// Called whenever the [`RenderAsset::SourceAsset`] has been removed.
///
/// You can implement this method if you need to access ECS data (via
/// `_param`) in order to perform cleanup tasks when the asset is removed.
///
/// The default implementation does nothing.
fn unload_asset(
_source_asset: AssetId<Self::SourceAsset>,
_param: &mut SystemParamItem<Self::Param>,
) {
}
/// Make a copy of the asset to be moved to the `RenderWorld` / gpu. Heavy internal data (pixels, vertex attributes)
/// should be moved into the copy, leaving this asset with only metadata.
/// An error may be returned to indicate that the asset has already been extracted, and should not
/// have been modified on the CPU side (as it cannot be transferred to GPU again).
/// The previous GPU asset is also provided, which can be used to check if the modification is valid.
fn take_gpu_data(
_source: &mut Self::SourceAsset,
_previous_gpu_asset: Option<&Self>,
) -> Result<Self::SourceAsset, AssetExtractionError> {
Err(AssetExtractionError::NoExtractionImplementation)
}
}
/// This plugin extracts the changed assets from the "app world" into the "render world"
/// and prepares them for the GPU. They can then be accessed from the [`RenderAssets`] resource.
///
/// Therefore it sets up the [`ExtractSchedule`] and
/// [`RenderSystems::PrepareAssets`] steps for the specified [`RenderAsset`].
///
/// The `AFTER` generic parameter can be used to specify that `A::prepare_asset` should not be run until
/// `prepare_assets::<AFTER>` has completed. This allows the `prepare_asset` function to depend on another
/// prepared [`RenderAsset`], for example `Mesh::prepare_asset` relies on `RenderAssets::<GpuImage>` for morph
/// targets, so the plugin is created as `RenderAssetPlugin::<RenderMesh, GpuImage>::default()`.
pub struct RenderAssetPlugin<A: RenderAsset, AFTER: RenderAssetDependency + 'static = ()> {
phantom: PhantomData<fn() -> (A, AFTER)>,
}
impl<A: RenderAsset, AFTER: RenderAssetDependency + 'static> Default
for RenderAssetPlugin<A, AFTER>
{
fn default() -> Self {
Self {
phantom: Default::default(),
}
}
}
impl<A: RenderAsset, AFTER: RenderAssetDependency + 'static> Plugin
for RenderAssetPlugin<A, AFTER>
{
fn build(&self, app: &mut App) {
app.init_resource::<CachedExtractRenderAssetSystemState<A>>();
if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
render_app
.init_resource::<ExtractedAssets<A>>()
.init_resource::<RenderAssets<A>>()
.init_resource::<PrepareNextFrameAssets<A>>()
.add_systems(
ExtractSchedule,
extract_render_asset::<A>.in_set(AssetExtractionSystems),
);
AFTER::register_system(
render_app,
prepare_assets::<A>.in_set(RenderSystems::PrepareAssets),
);
}
}
}
// helper to allow specifying dependencies between render assets
pub trait RenderAssetDependency {
fn register_system(render_app: &mut SubApp, system: ScheduleConfigs<ScheduleSystem>);
}
impl RenderAssetDependency for () {
fn register_system(render_app: &mut SubApp, system: ScheduleConfigs<ScheduleSystem>) {
render_app.add_systems(Render, system);
}
}
impl<A: RenderAsset> RenderAssetDependency for A {
fn register_system(render_app: &mut SubApp, system: ScheduleConfigs<ScheduleSystem>) {
render_app.add_systems(Render, system.after(prepare_assets::<A>));
}
}
/// Temporarily stores the extracted and removed assets of the current frame.
#[derive(Resource)]
pub struct ExtractedAssets<A: RenderAsset> {
/// The assets extracted this frame.
///
/// These are assets that were either added or modified this frame.
pub extracted: Vec<(AssetId<A::SourceAsset>, A::SourceAsset)>,
/// IDs of the assets that were removed this frame.
///
/// These assets will not be present in [`ExtractedAssets::extracted`].
pub removed: HashSet<AssetId<A::SourceAsset>>,
/// IDs of the assets that were modified this frame.
pub modified: HashSet<AssetId<A::SourceAsset>>,
/// IDs of the assets that were added this frame.
pub added: HashSet<AssetId<A::SourceAsset>>,
}
impl<A: RenderAsset> Default for ExtractedAssets<A> {
fn default() -> Self {
Self {
extracted: Default::default(),
removed: Default::default(),
modified: Default::default(),
added: Default::default(),
}
}
}
/// Stores all GPU representations ([`RenderAsset`])
/// of [`RenderAsset::SourceAsset`] as long as they exist.
#[derive(Resource)]
pub struct RenderAssets<A: RenderAsset>(HashMap<AssetId<A::SourceAsset>, A>);
impl<A: RenderAsset> Default for RenderAssets<A> {
fn default() -> Self {
Self(Default::default())
}
}
impl<A: RenderAsset> RenderAssets<A> {
pub fn get(&self, id: impl Into<AssetId<A::SourceAsset>>) -> Option<&A> {
self.0.get(&id.into())
}
pub fn get_mut(&mut self, id: impl Into<AssetId<A::SourceAsset>>) -> Option<&mut A> {
self.0.get_mut(&id.into())
}
pub fn insert(&mut self, id: impl Into<AssetId<A::SourceAsset>>, value: A) -> Option<A> {
self.0.insert(id.into(), value)
}
pub fn remove(&mut self, id: impl Into<AssetId<A::SourceAsset>>) -> Option<A> {
self.0.remove(&id.into())
}
pub fn iter(&self) -> impl Iterator<Item = (AssetId<A::SourceAsset>, &A)> {
self.0.iter().map(|(k, v)| (*k, v))
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = (AssetId<A::SourceAsset>, &mut A)> {
self.0.iter_mut().map(|(k, v)| (*k, v))
}
}
#[derive(Resource)]
struct CachedExtractRenderAssetSystemState<A: RenderAsset> {
state: SystemState<(
MessageReader<'static, 'static, AssetEvent<A::SourceAsset>>,
ResMut<'static, Assets<A::SourceAsset>>,
Option<Res<'static, RenderAssets<A>>>,
)>,
}
impl<A: RenderAsset> FromWorld for CachedExtractRenderAssetSystemState<A> {
fn from_world(world: &mut bevy_ecs::world::World) -> Self {
Self {
state: SystemState::new(world),
}
}
}
/// This system extracts all created or modified assets of the corresponding [`RenderAsset::SourceAsset`] type
/// into the "render world".
pub(crate) fn extract_render_asset<A: RenderAsset>(
mut commands: Commands,
mut main_world: ResMut<MainWorld>,
) {
main_world.resource_scope(
|world, mut cached_state: Mut<CachedExtractRenderAssetSystemState<A>>| {
let (mut events, mut assets, maybe_render_assets) = cached_state.state.get_mut(world);
let mut needs_extracting = <HashSet<_>>::default();
let mut removed = <HashSet<_>>::default();
let mut modified = <HashSet<_>>::default();
for event in events.read() {
#[expect(
clippy::match_same_arms,
reason = "LoadedWithDependencies is marked as a TODO, so it's likely this will no longer lint soon."
)]
match event {
AssetEvent::Added { id } => {
needs_extracting.insert(*id);
}
AssetEvent::Modified { id } => {
needs_extracting.insert(*id);
modified.insert(*id);
}
AssetEvent::Removed { .. } => {
// We don't care that the asset was removed from Assets<T> in the main world.
// An asset is only removed from RenderAssets<T> when its last handle is dropped (AssetEvent::Unused).
}
AssetEvent::Unused { id } => {
needs_extracting.remove(id);
modified.remove(id);
removed.insert(*id);
}
AssetEvent::LoadedWithDependencies { .. } => {
// TODO: handle this
}
}
}
let mut extracted_assets = Vec::new();
let mut added = <HashSet<_>>::default();
for id in needs_extracting.drain() {
if let Some(asset) = assets.get(id) {
let asset_usage = A::asset_usage(asset);
if asset_usage.contains(RenderAssetUsages::RENDER_WORLD) {
if asset_usage == RenderAssetUsages::RENDER_WORLD {
if let Some(asset) = assets.get_mut_untracked(id) {
let previous_asset = maybe_render_assets.as_ref().and_then(|render_assets| render_assets.get(id));
match A::take_gpu_data(asset, previous_asset) {
Ok(gpu_data_asset) => {
extracted_assets.push((id, gpu_data_asset));
added.insert(id);
}
Err(e) => {
error!("{} with RenderAssetUsages == RENDER_WORLD cannot be extracted: {e}", core::any::type_name::<A>());
}
};
}
} else {
extracted_assets.push((id, asset.clone()));
added.insert(id);
}
}
}
}
commands.insert_resource(ExtractedAssets::<A> {
extracted: extracted_assets,
removed,
modified,
added,
});
cached_state.state.apply(world);
},
);
}
// TODO: consider storing inside system?
/// All assets that should be prepared next frame.
#[derive(Resource)]
pub struct PrepareNextFrameAssets<A: RenderAsset> {
assets: Vec<(AssetId<A::SourceAsset>, A::SourceAsset)>,
}
impl<A: RenderAsset> Default for PrepareNextFrameAssets<A> {
fn default() -> Self {
Self {
assets: Default::default(),
}
}
}
/// This system prepares all assets of the corresponding [`RenderAsset::SourceAsset`] type
/// which where extracted this frame for the GPU.
pub fn prepare_assets<A: RenderAsset>(
mut extracted_assets: ResMut<ExtractedAssets<A>>,
mut render_assets: ResMut<RenderAssets<A>>,
mut prepare_next_frame: ResMut<PrepareNextFrameAssets<A>>,
param: StaticSystemParam<<A as RenderAsset>::Param>,
bpf: Res<RenderAssetBytesPerFrameLimiter>,
) {
let mut wrote_asset_count = 0;
let mut param = param.into_inner();
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
continue;
}
let write_bytes = if let Some(size) = A::byte_len(&extracted_asset) {
// we could check if available bytes > byte_len here, but we want to make some
// forward progress even if the asset is larger than the max bytes per frame.
// this way we always write at least one (sized) asset per frame.
// in future we could also consider partial asset uploads.
if bpf.exhausted() {
prepare_next_frame.assets.push((id, extracted_asset));
continue;
}
size
} else {
0
};
let previous_asset = render_assets.get(id);
match A::prepare_asset(extracted_asset, id, &mut param, previous_asset) {
Ok(prepared_asset) => {
render_assets.insert(id, prepared_asset);
bpf.write_bytes(write_bytes);
wrote_asset_count += 1;
}
Err(PrepareAssetError::RetryNextUpdate(extracted_asset)) => {
prepare_next_frame.assets.push((id, extracted_asset));
}
Err(PrepareAssetError::AsBindGroupError(e)) => {
error!(
"{} Bind group construction failed: {e}",
core::any::type_name::<A>()
);
}
}
}
for removed in extracted_assets.removed.drain() {
render_assets.remove(removed);
A::unload_asset(removed, &mut param);
}
for (id, extracted_asset) in extracted_assets.extracted.drain(..) {
// we remove previous here to ensure that if we are updating the asset then
// any users will not see the old asset after a new asset is extracted,
// even if the new asset is not yet ready or we are out of bytes to write.
let previous_asset = render_assets.remove(id);
let write_bytes = if let Some(size) = A::byte_len(&extracted_asset) {
if bpf.exhausted() {
prepare_next_frame.assets.push((id, extracted_asset));
continue;
}
size
} else {
0
};
match A::prepare_asset(extracted_asset, id, &mut param, previous_asset.as_ref()) {
Ok(prepared_asset) => {
render_assets.insert(id, prepared_asset);
bpf.write_bytes(write_bytes);
wrote_asset_count += 1;
}
Err(PrepareAssetError::RetryNextUpdate(extracted_asset)) => {
prepare_next_frame.assets.push((id, extracted_asset));
}
Err(PrepareAssetError::AsBindGroupError(e)) => {
error!(
"{} Bind group construction failed: {e}",
core::any::type_name::<A>()
);
}
}
}
if bpf.exhausted() && !prepare_next_frame.assets.is_empty() {
debug!(
"{} write budget exhausted with {} assets remaining (wrote {})",
core::any::type_name::<A>(),
prepare_next_frame.assets.len(),
wrote_asset_count
);
}
}
pub fn reset_render_asset_bytes_per_frame(
mut bpf_limiter: ResMut<RenderAssetBytesPerFrameLimiter>,
) {
bpf_limiter.reset();
}
pub fn extract_render_asset_bytes_per_frame(
bpf: Extract<Res<RenderAssetBytesPerFrame>>,
mut bpf_limiter: ResMut<RenderAssetBytesPerFrameLimiter>,
) {
bpf_limiter.max_bytes = bpf.max_bytes;
}
/// A resource that defines the amount of data allowed to be transferred from CPU to GPU
/// each frame, preventing choppy frames at the cost of waiting longer for GPU assets
/// to become available.
#[derive(Resource, Default)]
pub struct RenderAssetBytesPerFrame {
pub max_bytes: Option<usize>,
}
impl RenderAssetBytesPerFrame {
/// `max_bytes`: the number of bytes to write per frame.
///
/// This is a soft limit: only full assets are written currently, uploading stops
/// after the first asset that exceeds the limit.
///
/// To participate, assets should implement [`RenderAsset::byte_len`]. If the default
/// is not overridden, the assets are assumed to be small enough to upload without restriction.
pub fn new(max_bytes: usize) -> Self {
Self {
max_bytes: Some(max_bytes),
}
}
}
/// A render-world resource that facilitates limiting the data transferred from CPU to GPU
/// each frame, preventing choppy frames at the cost of waiting longer for GPU assets
/// to become available.
#[derive(Resource, Default)]
pub struct RenderAssetBytesPerFrameLimiter {
/// Populated by [`RenderAssetBytesPerFrame`] during extraction.
pub max_bytes: Option<usize>,
/// Bytes written this frame.
pub bytes_written: AtomicUsize,
}
impl RenderAssetBytesPerFrameLimiter {
/// Reset the available bytes. Called once per frame during extraction by [`crate::RenderPlugin`].
pub fn reset(&mut self) {
if self.max_bytes.is_none() {
return;
}
self.bytes_written.store(0, Ordering::Relaxed);
}
/// Check how many bytes are available for writing.
pub fn available_bytes(&self, required_bytes: usize) -> usize {
if let Some(max_bytes) = self.max_bytes {
let total_bytes = self
.bytes_written
.fetch_add(required_bytes, Ordering::Relaxed);
// The bytes available is the inverse of the amount we overshot max_bytes
if total_bytes >= max_bytes {
required_bytes.saturating_sub(total_bytes - max_bytes)
} else {
required_bytes
}
} else {
required_bytes
}
}
/// Decreases the available bytes for the current frame.
pub(crate) fn write_bytes(&self, bytes: usize) {
if self.max_bytes.is_some() && bytes > 0 {
self.bytes_written.fetch_add(bytes, Ordering::Relaxed);
}
}
/// Returns `true` if there are no remaining bytes available for writing this frame.
pub(crate) fn exhausted(&self) -> bool {
if let Some(max_bytes) = self.max_bytes {
let bytes_written = self.bytes_written.load(Ordering::Relaxed);
bytes_written >= max_bytes
} else {
false
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_render/src/gpu_component_array_buffer.rs | crates/bevy_render/src/gpu_component_array_buffer.rs | use crate::{
render_resource::{GpuArrayBuffer, GpuArrayBufferable},
renderer::{RenderDevice, RenderQueue},
Render, RenderApp, RenderSystems,
};
use bevy_app::{App, Plugin};
use bevy_ecs::{
prelude::{Component, Entity},
schedule::IntoScheduleConfigs,
system::{Commands, Query, Res, ResMut},
};
use core::marker::PhantomData;
/// This plugin prepares the components of the corresponding type for the GPU
/// by storing them in a [`GpuArrayBuffer`].
pub struct GpuComponentArrayBufferPlugin<C: Component + GpuArrayBufferable>(PhantomData<C>);
impl<C: Component + GpuArrayBufferable> Plugin for GpuComponentArrayBufferPlugin<C> {
fn build(&self, app: &mut App) {
if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
render_app.add_systems(
Render,
prepare_gpu_component_array_buffers::<C>.in_set(RenderSystems::PrepareResources),
);
}
}
fn finish(&self, app: &mut App) {
if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
render_app.insert_resource(GpuArrayBuffer::<C>::new(
&render_app.world().resource::<RenderDevice>().limits(),
));
}
}
}
impl<C: Component + GpuArrayBufferable> Default for GpuComponentArrayBufferPlugin<C> {
fn default() -> Self {
Self(PhantomData::<C>)
}
}
fn prepare_gpu_component_array_buffers<C: Component + GpuArrayBufferable>(
mut commands: Commands,
render_device: Res<RenderDevice>,
render_queue: Res<RenderQueue>,
mut gpu_array_buffer: ResMut<GpuArrayBuffer<C>>,
components: Query<(Entity, &C)>,
) {
gpu_array_buffer.clear();
let entities = components
.iter()
.map(|(entity, component)| (entity, gpu_array_buffer.push(component.clone())))
.collect::<Vec<_>>();
commands.try_insert_batch(entities);
gpu_array_buffer.write_buffer(&render_device, &render_queue);
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_render/src/sync_world.rs | crates/bevy_render/src/sync_world.rs | use bevy_app::Plugin;
use bevy_derive::{Deref, DerefMut};
use bevy_ecs::{
component::Component,
entity::{ContainsEntity, Entity, EntityEquivalent, EntityHash},
lifecycle::{Add, Remove},
observer::On,
query::With,
reflect::ReflectComponent,
resource::Resource,
system::{Local, Query, ResMut, SystemState},
world::{Mut, World},
};
use bevy_platform::collections::{HashMap, HashSet};
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
/// A plugin that synchronizes entities with [`SyncToRenderWorld`] between the main world and the render world.
///
/// All entities with the [`SyncToRenderWorld`] component are kept in sync. It
/// is automatically added as a required component by [`ExtractComponentPlugin`]
/// and [`SyncComponentPlugin`], so it doesn't need to be added manually when
/// spawning or as a required component when either of these plugins are used.
///
/// # Implementation
///
/// Bevy's renderer is architected independently from the main app.
/// It operates in its own separate ECS [`World`], so the renderer logic can run in parallel with the main world logic.
/// This is called "Pipelined Rendering", see [`PipelinedRenderingPlugin`] for more information.
///
/// [`SyncWorldPlugin`] is the first thing that runs every frame and it maintains an entity-to-entity mapping
/// between the main world and the render world.
/// It does so by spawning and despawning entities in the render world, to match spawned and despawned entities in the main world.
/// The link between synced entities is maintained by the [`RenderEntity`] and [`MainEntity`] components.
///
/// The [`RenderEntity`] contains the corresponding render world entity of a main world entity, while [`MainEntity`] contains
/// the corresponding main world entity of a render world entity.
/// For convenience, [`QueryData`](bevy_ecs::query::QueryData) implementations are provided for both components:
/// adding [`MainEntity`] to a query (without a `&`) will return the corresponding main world [`Entity`],
/// and adding [`RenderEntity`] will return the corresponding render world [`Entity`].
/// If you have access to the component itself, the underlying entities can be accessed by calling `.id()`.
///
/// Synchronization is necessary preparation for extraction ([`ExtractSchedule`](crate::ExtractSchedule)), which copies over component data from the main
/// to the render world for these entities.
///
/// ```text
/// |--------------------------------------------------------------------|
/// | | | Main world update |
/// | sync | extract |---------------------------------------------------|
/// | | | Render world update |
/// |--------------------------------------------------------------------|
/// ```
///
/// An example for synchronized main entities 1v1 and 18v1
///
/// ```text
/// |---------------------------Main World------------------------------|
/// | Entity | Component |
/// |-------------------------------------------------------------------|
/// | ID: 1v1 | PointLight | RenderEntity(ID: 3V1) | SyncToRenderWorld |
/// | ID: 18v1 | PointLight | RenderEntity(ID: 5V1) | SyncToRenderWorld |
/// |-------------------------------------------------------------------|
///
/// |----------Render World-----------|
/// | Entity | Component |
/// |---------------------------------|
/// | ID: 3v1 | MainEntity(ID: 1V1) |
/// | ID: 5v1 | MainEntity(ID: 18V1) |
/// |---------------------------------|
///
/// ```
///
/// Note that this effectively establishes a link between the main world entity and the render world entity.
/// Not every entity needs to be synchronized, however; only entities with the [`SyncToRenderWorld`] component are synced.
/// Adding [`SyncToRenderWorld`] to a main world component will establish such a link.
/// Once a synchronized main entity is despawned, its corresponding render entity will be automatically
/// despawned in the next `sync`.
///
/// The sync step does not copy any of component data between worlds, since its often not necessary to transfer over all
/// the components of a main world entity.
/// The render world probably cares about a `Position` component, but not a `Velocity` component.
/// The extraction happens in its own step, independently from, and after synchronization.
///
/// Moreover, [`SyncWorldPlugin`] only synchronizes *entities*. [`RenderAsset`](crate::render_asset::RenderAsset)s like meshes and textures are handled
/// differently.
///
/// [`PipelinedRenderingPlugin`]: crate::pipelined_rendering::PipelinedRenderingPlugin
/// [`ExtractComponentPlugin`]: crate::extract_component::ExtractComponentPlugin
/// [`SyncComponentPlugin`]: crate::sync_component::SyncComponentPlugin
#[derive(Default)]
pub struct SyncWorldPlugin;
impl Plugin for SyncWorldPlugin {
fn build(&self, app: &mut bevy_app::App) {
app.init_resource::<PendingSyncEntity>();
app.add_observer(
|add: On<Add, SyncToRenderWorld>, mut pending: ResMut<PendingSyncEntity>| {
pending.push(EntityRecord::Added(add.entity));
},
);
app.add_observer(
|remove: On<Remove, SyncToRenderWorld>,
mut pending: ResMut<PendingSyncEntity>,
query: Query<&RenderEntity>| {
if let Ok(e) = query.get(remove.entity) {
pending.push(EntityRecord::Removed(*e));
};
},
);
}
}
/// Marker component that indicates that its entity needs to be synchronized to the render world.
///
/// This component is automatically added as a required component by [`ExtractComponentPlugin`] and [`SyncComponentPlugin`].
/// For more information see [`SyncWorldPlugin`].
///
/// NOTE: This component should persist throughout the entity's entire lifecycle.
/// If this component is removed from its entity, the entity will be despawned.
///
/// [`ExtractComponentPlugin`]: crate::extract_component::ExtractComponentPlugin
/// [`SyncComponentPlugin`]: crate::sync_component::SyncComponentPlugin
#[derive(Component, Copy, Clone, Debug, Default, Reflect)]
#[reflect(Component, Default, Clone)]
#[component(storage = "SparseSet")]
pub struct SyncToRenderWorld;
/// Component added on the main world entities that are synced to the Render World in order to keep track of the corresponding render world entity.
///
/// Can also be used as a newtype wrapper for render world entities.
#[derive(Component, Deref, Copy, Clone, Debug, Eq, Hash, PartialEq, Reflect)]
#[component(clone_behavior = Ignore)]
#[reflect(Component, Clone)]
pub struct RenderEntity(Entity);
impl RenderEntity {
#[inline]
pub fn id(&self) -> Entity {
self.0
}
}
impl From<Entity> for RenderEntity {
fn from(entity: Entity) -> Self {
RenderEntity(entity)
}
}
impl ContainsEntity for RenderEntity {
fn entity(&self) -> Entity {
self.id()
}
}
// SAFETY: RenderEntity is a newtype around Entity that derives its comparison traits.
unsafe impl EntityEquivalent for RenderEntity {}
/// Component added on the render world entities to keep track of the corresponding main world entity.
///
/// Can also be used as a newtype wrapper for main world entities.
#[derive(Component, Deref, Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Reflect)]
#[reflect(Component, Clone)]
pub struct MainEntity(Entity);
impl MainEntity {
#[inline]
pub fn id(&self) -> Entity {
self.0
}
}
impl From<Entity> for MainEntity {
fn from(entity: Entity) -> Self {
MainEntity(entity)
}
}
impl ContainsEntity for MainEntity {
fn entity(&self) -> Entity {
self.id()
}
}
// SAFETY: RenderEntity is a newtype around Entity that derives its comparison traits.
unsafe impl EntityEquivalent for MainEntity {}
/// A [`HashMap`] pre-configured to use [`EntityHash`] hashing with a [`MainEntity`].
pub type MainEntityHashMap<V> = HashMap<MainEntity, V, EntityHash>;
/// A [`HashSet`] pre-configured to use [`EntityHash`] hashing with a [`MainEntity`]..
pub type MainEntityHashSet = HashSet<MainEntity, EntityHash>;
/// Marker component that indicates that its entity needs to be despawned at the end of the frame.
#[derive(Component, Copy, Clone, Debug, Default, Reflect)]
#[reflect(Component, Default, Clone)]
pub struct TemporaryRenderEntity;
/// A record enum to what entities with [`SyncToRenderWorld`] have been added or removed.
#[derive(Debug)]
pub(crate) enum EntityRecord {
/// When an entity is spawned on the main world, notify the render world so that it can spawn a corresponding
/// entity. This contains the main world entity.
Added(Entity),
/// When an entity is despawned on the main world, notify the render world so that the corresponding entity can be
/// despawned. This contains the render world entity.
Removed(RenderEntity),
/// When a component is removed from an entity, notify the render world so that the corresponding component can be
/// removed. This contains the main world entity.
ComponentRemoved(Entity),
}
// Entity Record in MainWorld pending to Sync
#[derive(Resource, Default, Deref, DerefMut)]
pub(crate) struct PendingSyncEntity {
records: Vec<EntityRecord>,
}
pub(crate) fn entity_sync_system(main_world: &mut World, render_world: &mut World) {
main_world.resource_scope(|world, mut pending: Mut<PendingSyncEntity>| {
// TODO : batching record
for record in pending.drain(..) {
match record {
EntityRecord::Added(e) => {
if let Ok(mut main_entity) = world.get_entity_mut(e) {
match main_entity.entry::<RenderEntity>() {
bevy_ecs::world::ComponentEntry::Occupied(_) => {
panic!("Attempting to synchronize an entity that has already been synchronized!");
}
bevy_ecs::world::ComponentEntry::Vacant(entry) => {
let id = render_world.spawn(MainEntity(e)).id();
entry.insert(RenderEntity(id));
}
};
}
}
EntityRecord::Removed(render_entity) => {
if let Ok(ec) = render_world.get_entity_mut(render_entity.id()) {
ec.despawn();
};
}
EntityRecord::ComponentRemoved(main_entity) => {
let Some(mut render_entity) = world.get_mut::<RenderEntity>(main_entity) else {
continue;
};
if let Ok(render_world_entity) = render_world.get_entity_mut(render_entity.id()) {
// In order to handle components that extract to derived components, we clear the entity
// and let the extraction system re-add the components.
render_world_entity.despawn();
let id = render_world.spawn(MainEntity(main_entity)).id();
render_entity.0 = id;
}
},
}
}
});
}
pub(crate) fn despawn_temporary_render_entities(
world: &mut World,
state: &mut SystemState<Query<Entity, With<TemporaryRenderEntity>>>,
mut local: Local<Vec<Entity>>,
) {
let query = state.get(world);
local.extend(query.iter());
// Ensure next frame allocation keeps order
local.sort_unstable_by_key(|e| e.index());
for e in local.drain(..).rev() {
world.despawn(e);
}
}
/// This module exists to keep the complex unsafe code out of the main module.
///
/// The implementations for both [`MainEntity`] and [`RenderEntity`] should stay in sync,
/// and are based off of the `&T` implementation in `bevy_ecs`.
mod render_entities_world_query_impls {
use super::{MainEntity, RenderEntity};
use bevy_ecs::{
archetype::Archetype,
change_detection::Tick,
component::{ComponentId, Components},
entity::Entity,
query::{
ArchetypeQueryData, FilteredAccess, QueryData, ReadOnlyQueryData,
ReleaseStateQueryData, WorldQuery,
},
storage::{Table, TableRow},
world::{unsafe_world_cell::UnsafeWorldCell, World},
};
/// SAFETY: defers completely to `&RenderEntity` implementation,
/// and then only modifies the output safely.
unsafe impl WorldQuery for RenderEntity {
type Fetch<'w> = <&'static RenderEntity as WorldQuery>::Fetch<'w>;
type State = <&'static RenderEntity as WorldQuery>::State;
fn shrink_fetch<'wlong: 'wshort, 'wshort>(
fetch: Self::Fetch<'wlong>,
) -> Self::Fetch<'wshort> {
fetch
}
#[inline]
unsafe fn init_fetch<'w, 's>(
world: UnsafeWorldCell<'w>,
component_id: &'s ComponentId,
last_run: Tick,
this_run: Tick,
) -> Self::Fetch<'w> {
// SAFETY: defers to the `&T` implementation, with T set to `RenderEntity`.
unsafe {
<&RenderEntity as WorldQuery>::init_fetch(world, component_id, last_run, this_run)
}
}
const IS_DENSE: bool = <&'static RenderEntity as WorldQuery>::IS_DENSE;
#[inline]
unsafe fn set_archetype<'w, 's>(
fetch: &mut Self::Fetch<'w>,
component_id: &'s ComponentId,
archetype: &'w Archetype,
table: &'w Table,
) {
// SAFETY: defers to the `&T` implementation, with T set to `RenderEntity`.
unsafe {
<&RenderEntity as WorldQuery>::set_archetype(fetch, component_id, archetype, table);
}
}
#[inline]
unsafe fn set_table<'w, 's>(
fetch: &mut Self::Fetch<'w>,
&component_id: &'s ComponentId,
table: &'w Table,
) {
// SAFETY: defers to the `&T` implementation, with T set to `RenderEntity`.
unsafe { <&RenderEntity as WorldQuery>::set_table(fetch, &component_id, table) }
}
fn update_component_access(&component_id: &ComponentId, access: &mut FilteredAccess) {
<&RenderEntity as WorldQuery>::update_component_access(&component_id, access);
}
fn init_state(world: &mut World) -> ComponentId {
<&RenderEntity as WorldQuery>::init_state(world)
}
fn get_state(components: &Components) -> Option<Self::State> {
<&RenderEntity as WorldQuery>::get_state(components)
}
fn matches_component_set(
&state: &ComponentId,
set_contains_id: &impl Fn(ComponentId) -> bool,
) -> bool {
<&RenderEntity as WorldQuery>::matches_component_set(&state, set_contains_id)
}
}
// SAFETY: Component access of Self::ReadOnly is a subset of Self.
// Self::ReadOnly matches exactly the same archetypes/tables as Self.
unsafe impl QueryData for RenderEntity {
const IS_READ_ONLY: bool = true;
const IS_ARCHETYPAL: bool = <&MainEntity as QueryData>::IS_ARCHETYPAL;
type ReadOnly = RenderEntity;
type Item<'w, 's> = Entity;
fn shrink<'wlong: 'wshort, 'wshort, 's>(
item: Self::Item<'wlong, 's>,
) -> Self::Item<'wshort, 's> {
item
}
#[inline(always)]
unsafe fn fetch<'w, 's>(
state: &'s Self::State,
fetch: &mut Self::Fetch<'w>,
entity: Entity,
table_row: TableRow,
) -> Option<Self::Item<'w, 's>> {
// SAFETY: defers to the `&T` implementation, with T set to `RenderEntity`.
let component =
unsafe { <&RenderEntity as QueryData>::fetch(state, fetch, entity, table_row) };
component.map(RenderEntity::id)
}
fn iter_access(
state: &Self::State,
) -> impl Iterator<Item = bevy_ecs::query::EcsAccessType<'_>> {
<&RenderEntity as QueryData>::iter_access(state)
}
}
// SAFETY: the underlying `Entity` is copied, and no mutable access is provided.
unsafe impl ReadOnlyQueryData for RenderEntity {}
impl ArchetypeQueryData for RenderEntity {}
impl ReleaseStateQueryData for RenderEntity {
fn release_state<'w>(item: Self::Item<'w, '_>) -> Self::Item<'w, 'static> {
item
}
}
/// SAFETY: defers completely to `&RenderEntity` implementation,
/// and then only modifies the output safely.
unsafe impl WorldQuery for MainEntity {
type Fetch<'w> = <&'static MainEntity as WorldQuery>::Fetch<'w>;
type State = <&'static MainEntity as WorldQuery>::State;
fn shrink_fetch<'wlong: 'wshort, 'wshort>(
fetch: Self::Fetch<'wlong>,
) -> Self::Fetch<'wshort> {
fetch
}
#[inline]
unsafe fn init_fetch<'w, 's>(
world: UnsafeWorldCell<'w>,
component_id: &'s ComponentId,
last_run: Tick,
this_run: Tick,
) -> Self::Fetch<'w> {
// SAFETY: defers to the `&T` implementation, with T set to `MainEntity`.
unsafe {
<&MainEntity as WorldQuery>::init_fetch(world, component_id, last_run, this_run)
}
}
const IS_DENSE: bool = <&'static MainEntity as WorldQuery>::IS_DENSE;
#[inline]
unsafe fn set_archetype<'w, 's>(
fetch: &mut Self::Fetch<'w>,
component_id: &ComponentId,
archetype: &'w Archetype,
table: &'w Table,
) {
// SAFETY: defers to the `&T` implementation, with T set to `MainEntity`.
unsafe {
<&MainEntity as WorldQuery>::set_archetype(fetch, component_id, archetype, table);
}
}
#[inline]
unsafe fn set_table<'w, 's>(
fetch: &mut Self::Fetch<'w>,
&component_id: &'s ComponentId,
table: &'w Table,
) {
// SAFETY: defers to the `&T` implementation, with T set to `MainEntity`.
unsafe { <&MainEntity as WorldQuery>::set_table(fetch, &component_id, table) }
}
fn update_component_access(&component_id: &ComponentId, access: &mut FilteredAccess) {
<&MainEntity as WorldQuery>::update_component_access(&component_id, access);
}
fn init_state(world: &mut World) -> ComponentId {
<&MainEntity as WorldQuery>::init_state(world)
}
fn get_state(components: &Components) -> Option<Self::State> {
<&MainEntity as WorldQuery>::get_state(components)
}
fn matches_component_set(
&state: &ComponentId,
set_contains_id: &impl Fn(ComponentId) -> bool,
) -> bool {
<&MainEntity as WorldQuery>::matches_component_set(&state, set_contains_id)
}
}
// SAFETY: Component access of Self::ReadOnly is a subset of Self.
// Self::ReadOnly matches exactly the same archetypes/tables as Self.
unsafe impl QueryData for MainEntity {
const IS_READ_ONLY: bool = true;
const IS_ARCHETYPAL: bool = <&MainEntity as QueryData>::IS_ARCHETYPAL;
type ReadOnly = MainEntity;
type Item<'w, 's> = Entity;
fn shrink<'wlong: 'wshort, 'wshort, 's>(
item: Self::Item<'wlong, 's>,
) -> Self::Item<'wshort, 's> {
item
}
#[inline(always)]
unsafe fn fetch<'w, 's>(
state: &'s Self::State,
fetch: &mut Self::Fetch<'w>,
entity: Entity,
table_row: TableRow,
) -> Option<Self::Item<'w, 's>> {
// SAFETY: defers to the `&T` implementation, with T set to `MainEntity`.
let component =
unsafe { <&MainEntity as QueryData>::fetch(state, fetch, entity, table_row) };
component.map(MainEntity::id)
}
fn iter_access(
state: &Self::State,
) -> impl Iterator<Item = bevy_ecs::query::EcsAccessType<'_>> {
<&MainEntity as QueryData>::iter_access(state)
}
}
// SAFETY: the underlying `Entity` is copied, and no mutable access is provided.
unsafe impl ReadOnlyQueryData for MainEntity {}
impl ArchetypeQueryData for MainEntity {}
impl ReleaseStateQueryData for MainEntity {
fn release_state<'w>(item: Self::Item<'w, '_>) -> Self::Item<'w, 'static> {
item
}
}
}
#[cfg(test)]
mod tests {
use bevy_ecs::{
component::Component,
entity::Entity,
lifecycle::{Add, Remove},
observer::On,
query::With,
system::{Query, ResMut},
world::World,
};
use super::{
entity_sync_system, EntityRecord, MainEntity, PendingSyncEntity, RenderEntity,
SyncToRenderWorld,
};
#[derive(Component)]
struct RenderDataComponent;
#[test]
fn sync_world() {
let mut main_world = World::new();
let mut render_world = World::new();
main_world.init_resource::<PendingSyncEntity>();
main_world.add_observer(
|add: On<Add, SyncToRenderWorld>, mut pending: ResMut<PendingSyncEntity>| {
pending.push(EntityRecord::Added(add.entity));
},
);
main_world.add_observer(
|remove: On<Remove, SyncToRenderWorld>,
mut pending: ResMut<PendingSyncEntity>,
query: Query<&RenderEntity>| {
if let Ok(e) = query.get(remove.entity) {
pending.push(EntityRecord::Removed(*e));
};
},
);
// spawn some empty entities for test
for _ in 0..99 {
main_world.spawn_empty();
}
// spawn
let main_entity = main_world
.spawn(RenderDataComponent)
// indicates that its entity needs to be synchronized to the render world
.insert(SyncToRenderWorld)
.id();
entity_sync_system(&mut main_world, &mut render_world);
let mut q = render_world.query_filtered::<Entity, With<MainEntity>>();
// Only one synchronized entity
assert!(q.iter(&render_world).count() == 1);
let render_entity = q.single(&render_world).unwrap();
let render_entity_component = main_world.get::<RenderEntity>(main_entity).unwrap();
assert!(render_entity_component.id() == render_entity);
let main_entity_component = render_world
.get::<MainEntity>(render_entity_component.id())
.unwrap();
assert!(main_entity_component.id() == main_entity);
// despawn
main_world.despawn(main_entity);
entity_sync_system(&mut main_world, &mut render_world);
// Only one synchronized entity
assert!(q.iter(&render_world).count() == 0);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_render/src/globals.rs | crates/bevy_render/src/globals.rs | use crate::{
extract_resource::ExtractResource,
render_resource::{ShaderType, UniformBuffer},
renderer::{RenderDevice, RenderQueue},
Extract, ExtractSchedule, Render, RenderApp, RenderSystems,
};
use bevy_app::{App, Plugin};
use bevy_diagnostic::FrameCount;
use bevy_ecs::prelude::*;
use bevy_reflect::prelude::*;
use bevy_shader::load_shader_library;
use bevy_time::Time;
pub struct GlobalsPlugin;
impl Plugin for GlobalsPlugin {
fn build(&self, app: &mut App) {
load_shader_library!(app, "globals.wgsl");
if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
render_app
.init_resource::<GlobalsBuffer>()
.init_resource::<Time>()
.add_systems(ExtractSchedule, (extract_frame_count, extract_time))
.add_systems(
Render,
prepare_globals_buffer.in_set(RenderSystems::PrepareResources),
);
}
}
}
fn extract_frame_count(mut commands: Commands, frame_count: Extract<Res<FrameCount>>) {
commands.insert_resource(**frame_count);
}
fn extract_time(mut commands: Commands, time: Extract<Res<Time>>) {
commands.insert_resource(**time);
}
/// Contains global values useful when writing shaders.
/// Currently only contains values related to time.
#[derive(Default, Clone, Resource, ExtractResource, Reflect, ShaderType)]
#[reflect(Resource, Default, Clone)]
pub struct GlobalsUniform {
/// The time since startup in seconds.
/// Wraps to 0 after 1 hour.
time: f32,
/// The delta time since the previous frame in seconds
delta_time: f32,
/// Frame count since the start of the app.
/// It wraps to zero when it reaches the maximum value of a u32.
frame_count: u32,
/// WebGL2 structs must be 16 byte aligned.
#[cfg(all(feature = "webgl", target_arch = "wasm32", not(feature = "webgpu")))]
_wasm_padding: f32,
}
/// The buffer containing the [`GlobalsUniform`]
#[derive(Resource, Default)]
pub struct GlobalsBuffer {
pub buffer: UniformBuffer<GlobalsUniform>,
}
fn prepare_globals_buffer(
render_device: Res<RenderDevice>,
render_queue: Res<RenderQueue>,
mut globals_buffer: ResMut<GlobalsBuffer>,
time: Res<Time>,
frame_count: Res<FrameCount>,
) {
let buffer = globals_buffer.buffer.get_mut();
buffer.time = time.elapsed_secs_wrapped();
buffer.delta_time = time.delta_secs();
buffer.frame_count = frame_count.0;
globals_buffer
.buffer
.write_buffer(&render_device, &render_queue);
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_render/src/extract_instances.rs | crates/bevy_render/src/extract_instances.rs | //! Convenience logic for turning components from the main world into extracted
//! instances in the render world.
//!
//! This is essentially the same as the `extract_component` module, but
//! higher-performance because it avoids the ECS overhead.
use core::marker::PhantomData;
use bevy_app::{App, Plugin};
use bevy_camera::visibility::ViewVisibility;
use bevy_derive::{Deref, DerefMut};
use bevy_ecs::{
prelude::Entity,
query::{QueryFilter, QueryItem, ReadOnlyQueryData},
resource::Resource,
system::{Query, ResMut},
};
use crate::sync_world::MainEntityHashMap;
use crate::{Extract, ExtractSchedule, RenderApp};
/// Describes how to extract data needed for rendering from a component or
/// components.
///
/// Before rendering, any applicable components will be transferred from the
/// main world to the render world in the [`ExtractSchedule`] step.
///
/// This is essentially the same as
/// [`ExtractComponent`](crate::extract_component::ExtractComponent), but
/// higher-performance because it avoids the ECS overhead.
pub trait ExtractInstance: Send + Sync + Sized + 'static {
/// ECS [`ReadOnlyQueryData`] to fetch the components to extract.
type QueryData: ReadOnlyQueryData;
/// Filters the entities with additional constraints.
type QueryFilter: QueryFilter;
/// Defines how the component is transferred into the "render world".
fn extract(item: QueryItem<'_, '_, Self::QueryData>) -> Option<Self>;
}
/// This plugin extracts one or more components into the "render world" as
/// extracted instances.
///
/// Therefore it sets up the [`ExtractSchedule`] step for the specified
/// [`ExtractedInstances`].
#[derive(Default)]
pub struct ExtractInstancesPlugin<EI>
where
EI: ExtractInstance,
{
only_extract_visible: bool,
marker: PhantomData<fn() -> EI>,
}
/// Stores all extract instances of a type in the render world.
#[derive(Resource, Deref, DerefMut)]
pub struct ExtractedInstances<EI>(MainEntityHashMap<EI>)
where
EI: ExtractInstance;
impl<EI> Default for ExtractedInstances<EI>
where
EI: ExtractInstance,
{
fn default() -> Self {
Self(Default::default())
}
}
impl<EI> ExtractInstancesPlugin<EI>
where
EI: ExtractInstance,
{
/// Creates a new [`ExtractInstancesPlugin`] that unconditionally extracts to
/// the render world, whether the entity is visible or not.
pub fn new() -> Self {
Self {
only_extract_visible: false,
marker: PhantomData,
}
}
/// Creates a new [`ExtractInstancesPlugin`] that extracts to the render world
/// if and only if the entity it's attached to is visible.
pub fn extract_visible() -> Self {
Self {
only_extract_visible: true,
marker: PhantomData,
}
}
}
impl<EI> Plugin for ExtractInstancesPlugin<EI>
where
EI: ExtractInstance,
{
fn build(&self, app: &mut App) {
if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
render_app.init_resource::<ExtractedInstances<EI>>();
if self.only_extract_visible {
render_app.add_systems(ExtractSchedule, extract_visible::<EI>);
} else {
render_app.add_systems(ExtractSchedule, extract_all::<EI>);
}
}
}
}
fn extract_all<EI>(
mut extracted_instances: ResMut<ExtractedInstances<EI>>,
query: Extract<Query<(Entity, EI::QueryData), EI::QueryFilter>>,
) where
EI: ExtractInstance,
{
extracted_instances.clear();
for (entity, other) in &query {
if let Some(extract_instance) = EI::extract(other) {
extracted_instances.insert(entity.into(), extract_instance);
}
}
}
fn extract_visible<EI>(
mut extracted_instances: ResMut<ExtractedInstances<EI>>,
query: Extract<Query<(Entity, &ViewVisibility, EI::QueryData), EI::QueryFilter>>,
) where
EI: ExtractInstance,
{
extracted_instances.clear();
for (entity, view_visibility, other) in &query {
if view_visibility.get()
&& let Some(extract_instance) = EI::extract(other)
{
extracted_instances.insert(entity.into(), extract_instance);
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_render/src/storage.rs | crates/bevy_render/src/storage.rs | use crate::{
render_asset::{AssetExtractionError, PrepareAssetError, RenderAsset, RenderAssetPlugin},
render_resource::{Buffer, BufferUsages},
renderer::RenderDevice,
};
use bevy_app::{App, Plugin};
use bevy_asset::{Asset, AssetApp, AssetId, RenderAssetUsages};
use bevy_ecs::system::{lifetimeless::SRes, SystemParamItem};
use bevy_reflect::{prelude::ReflectDefault, Reflect};
use bevy_utils::default;
use encase::{internal::WriteInto, ShaderType};
use wgpu::util::BufferInitDescriptor;
/// Adds [`ShaderStorageBuffer`] as an asset that is extracted and uploaded to the GPU.
#[derive(Default)]
pub struct StoragePlugin;
impl Plugin for StoragePlugin {
fn build(&self, app: &mut App) {
app.add_plugins(RenderAssetPlugin::<GpuShaderStorageBuffer>::default())
.init_asset::<ShaderStorageBuffer>()
.register_asset_reflect::<ShaderStorageBuffer>();
}
}
/// A storage buffer that is prepared as a [`RenderAsset`] and uploaded to the GPU.
#[derive(Asset, Reflect, Debug, Clone)]
#[reflect(opaque)]
#[reflect(Default, Debug, Clone)]
pub struct ShaderStorageBuffer {
/// Optional data used to initialize the buffer.
pub data: Option<Vec<u8>>,
/// The buffer description used to create the buffer.
pub buffer_description: wgpu::BufferDescriptor<'static>,
/// The asset usage of the storage buffer.
pub asset_usage: RenderAssetUsages,
}
impl Default for ShaderStorageBuffer {
fn default() -> Self {
Self {
data: None,
buffer_description: wgpu::BufferDescriptor {
label: None,
size: 0,
usage: BufferUsages::STORAGE,
mapped_at_creation: false,
},
asset_usage: RenderAssetUsages::default(),
}
}
}
impl ShaderStorageBuffer {
/// Creates a new storage buffer with the given data and asset usage.
pub fn new(data: &[u8], asset_usage: RenderAssetUsages) -> Self {
let mut storage = ShaderStorageBuffer {
data: Some(data.to_vec()),
..default()
};
storage.asset_usage = asset_usage;
storage
}
/// Creates a new storage buffer with the given size and asset usage.
pub fn with_size(size: usize, asset_usage: RenderAssetUsages) -> Self {
let mut storage = ShaderStorageBuffer {
data: None,
..default()
};
storage.buffer_description.size = size as u64;
storage.buffer_description.mapped_at_creation = false;
storage.asset_usage = asset_usage;
storage
}
/// Sets the data of the storage buffer to the given [`ShaderType`].
pub fn set_data<T>(&mut self, value: T)
where
T: ShaderType + WriteInto,
{
let size = value.size().get() as usize;
let mut wrapper = encase::StorageBuffer::<Vec<u8>>::new(Vec::with_capacity(size));
wrapper.write(&value).unwrap();
self.data = Some(wrapper.into_inner());
}
}
impl<T> From<T> for ShaderStorageBuffer
where
T: ShaderType + WriteInto,
{
fn from(value: T) -> Self {
let size = value.size().get() as usize;
let mut wrapper = encase::StorageBuffer::<Vec<u8>>::new(Vec::with_capacity(size));
wrapper.write(&value).unwrap();
Self::new(wrapper.as_ref(), RenderAssetUsages::default())
}
}
/// A storage buffer that is prepared as a [`RenderAsset`] and uploaded to the GPU.
pub struct GpuShaderStorageBuffer {
pub buffer: Buffer,
pub had_data: bool,
}
impl RenderAsset for GpuShaderStorageBuffer {
type SourceAsset = ShaderStorageBuffer;
type Param = SRes<RenderDevice>;
fn asset_usage(source_asset: &Self::SourceAsset) -> RenderAssetUsages {
source_asset.asset_usage
}
fn take_gpu_data(
source: &mut Self::SourceAsset,
previous_gpu_asset: Option<&Self>,
) -> Result<Self::SourceAsset, AssetExtractionError> {
let data = source.data.take();
let valid_upload = data.is_some() || previous_gpu_asset.is_none_or(|prev| !prev.had_data);
valid_upload
.then(|| Self::SourceAsset {
data,
..source.clone()
})
.ok_or(AssetExtractionError::AlreadyExtracted)
}
fn prepare_asset(
source_asset: Self::SourceAsset,
_: AssetId<Self::SourceAsset>,
render_device: &mut SystemParamItem<Self::Param>,
_: Option<&Self>,
) -> Result<Self, PrepareAssetError<Self::SourceAsset>> {
match source_asset.data {
Some(data) => {
let buffer = render_device.create_buffer_with_data(&BufferInitDescriptor {
label: source_asset.buffer_description.label,
contents: &data,
usage: source_asset.buffer_description.usage,
});
Ok(GpuShaderStorageBuffer {
buffer,
had_data: true,
})
}
None => {
let buffer = render_device.create_buffer(&source_asset.buffer_description);
Ok(GpuShaderStorageBuffer {
buffer,
had_data: false,
})
}
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_render/src/sync_component.rs | crates/bevy_render/src/sync_component.rs | use core::marker::PhantomData;
use bevy_app::{App, Plugin};
use bevy_ecs::component::Component;
use crate::sync_world::{EntityRecord, PendingSyncEntity, SyncToRenderWorld};
/// Plugin that registers a component for automatic sync to the render world. See [`SyncWorldPlugin`] for more information.
///
/// This plugin is automatically added by [`ExtractComponentPlugin`], and only needs to be added for manual extraction implementations.
///
/// # Implementation details
///
/// It adds [`SyncToRenderWorld`] as a required component to make the [`SyncWorldPlugin`] aware of the component, and
/// handles cleanup of the component in the render world when it is removed from an entity.
///
/// # Warning
/// When the component is removed from the main world entity, all components are removed from the entity in the render world.
/// This is done in order to handle components with custom extraction logic and derived state.
///
/// [`ExtractComponentPlugin`]: crate::extract_component::ExtractComponentPlugin
/// [`SyncWorldPlugin`]: crate::sync_world::SyncWorldPlugin
pub struct SyncComponentPlugin<C: Component>(PhantomData<C>);
impl<C: Component> Default for SyncComponentPlugin<C> {
fn default() -> Self {
Self(PhantomData)
}
}
impl<C: Component> Plugin for SyncComponentPlugin<C> {
fn build(&self, app: &mut App) {
app.register_required_components::<C, SyncToRenderWorld>();
app.world_mut()
.register_component_hooks::<C>()
.on_remove(|mut world, context| {
let mut pending = world.resource_mut::<PendingSyncEntity>();
pending.push(EntityRecord::ComponentRemoved(context.entity));
});
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_render/src/camera.rs | crates/bevy_render/src/camera.rs | use crate::{
batching::gpu_preprocessing::{GpuPreprocessingMode, GpuPreprocessingSupport},
extract_component::{ExtractComponent, ExtractComponentPlugin},
extract_resource::{ExtractResource, ExtractResourcePlugin},
render_asset::RenderAssets,
render_graph::{CameraDriverNode, InternedRenderSubGraph, RenderGraph, RenderSubGraph},
render_resource::TextureView,
sync_world::{RenderEntity, SyncToRenderWorld},
texture::{GpuImage, ManualTextureViews},
view::{
ColorGrading, ExtractedView, ExtractedWindows, Hdr, Msaa, NoIndirectDrawing,
RenderVisibleEntities, RetainedViewEntity, ViewUniformOffset,
},
Extract, ExtractSchedule, Render, RenderApp, RenderSystems,
};
use bevy_app::{App, Plugin, PostStartup, PostUpdate};
use bevy_asset::{AssetEvent, AssetEventSystems, AssetId, Assets};
use bevy_camera::{
primitives::Frustum,
visibility::{self, RenderLayers, VisibleEntities},
Camera, Camera2d, Camera3d, CameraMainTextureUsages, CameraOutputMode, CameraUpdateSystems,
ClearColor, ClearColorConfig, Exposure, ManualTextureViewHandle, MsaaWriteback,
NormalizedRenderTarget, Projection, RenderTarget, RenderTargetInfo, Viewport,
};
use bevy_derive::{Deref, DerefMut};
use bevy_ecs::{
change_detection::DetectChanges,
component::Component,
entity::{ContainsEntity, Entity},
error::BevyError,
lifecycle::HookContext,
message::MessageReader,
prelude::With,
query::{Has, QueryItem},
reflect::ReflectComponent,
resource::Resource,
schedule::IntoScheduleConfigs,
system::{Commands, Query, Res, ResMut},
world::DeferredWorld,
};
use bevy_image::Image;
use bevy_math::{uvec2, vec2, Mat4, URect, UVec2, UVec4, Vec2};
use bevy_platform::collections::{HashMap, HashSet};
use bevy_reflect::prelude::*;
use bevy_transform::components::GlobalTransform;
use bevy_window::{PrimaryWindow, Window, WindowCreated, WindowResized, WindowScaleFactorChanged};
use tracing::warn;
use wgpu::TextureFormat;
#[derive(Default)]
pub struct CameraPlugin;
impl Plugin for CameraPlugin {
fn build(&self, app: &mut App) {
app.register_required_components::<Camera, Msaa>()
.register_required_components::<Camera, SyncToRenderWorld>()
.register_required_components::<Camera3d, ColorGrading>()
.register_required_components::<Camera3d, Exposure>()
.add_plugins((
ExtractResourcePlugin::<ClearColor>::default(),
ExtractComponentPlugin::<CameraMainTextureUsages>::default(),
))
.add_systems(PostStartup, camera_system.in_set(CameraUpdateSystems))
.add_systems(
PostUpdate,
camera_system
.in_set(CameraUpdateSystems)
.before(AssetEventSystems)
.before(visibility::update_frusta),
);
app.world_mut()
.register_component_hooks::<Camera>()
.on_add(warn_on_no_render_graph);
if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
render_app
.init_resource::<SortedCameras>()
.add_systems(ExtractSchedule, extract_cameras)
.add_systems(Render, sort_cameras.in_set(RenderSystems::ManageViews));
let camera_driver_node = CameraDriverNode::new(render_app.world_mut());
let mut render_graph = render_app.world_mut().resource_mut::<RenderGraph>();
render_graph.add_node(crate::graph::CameraDriverLabel, camera_driver_node);
}
}
}
fn warn_on_no_render_graph(world: DeferredWorld, HookContext { entity, caller, .. }: HookContext) {
if !world.entity(entity).contains::<CameraRenderGraph>() {
warn!("{}Entity {entity} has a `Camera` component, but it doesn't have a render graph configured. Usually, adding a `Camera2d` or `Camera3d` component will work.
However, you may instead need to enable `bevy_core_pipeline`, or may want to manually add a `CameraRenderGraph` component to create a custom render graph.", caller.map(|location|format!("{location}: ")).unwrap_or_default());
}
}
impl ExtractResource for ClearColor {
type Source = Self;
fn extract_resource(source: &Self::Source) -> Self {
source.clone()
}
}
impl ExtractComponent for CameraMainTextureUsages {
type QueryData = &'static Self;
type QueryFilter = ();
type Out = Self;
fn extract_component(item: QueryItem<Self::QueryData>) -> Option<Self::Out> {
Some(*item)
}
}
impl ExtractComponent for Camera2d {
type QueryData = &'static Self;
type QueryFilter = With<Camera>;
type Out = Self;
fn extract_component(item: QueryItem<Self::QueryData>) -> Option<Self::Out> {
Some(item.clone())
}
}
impl ExtractComponent for Camera3d {
type QueryData = &'static Self;
type QueryFilter = With<Camera>;
type Out = Self;
fn extract_component(item: QueryItem<Self::QueryData>) -> Option<Self::Out> {
Some(item.clone())
}
}
/// Configures the [`RenderGraph`] name assigned to be run for a given [`Camera`] entity.
#[derive(Component, Debug, Deref, DerefMut, Reflect, Clone)]
#[reflect(opaque)]
#[reflect(Component, Debug, Clone)]
pub struct CameraRenderGraph(InternedRenderSubGraph);
impl CameraRenderGraph {
/// Creates a new [`CameraRenderGraph`] from any string-like type.
#[inline]
pub fn new<T: RenderSubGraph>(name: T) -> Self {
Self(name.intern())
}
/// Sets the graph name.
#[inline]
pub fn set<T: RenderSubGraph>(&mut self, name: T) {
self.0 = name.intern();
}
}
pub trait NormalizedRenderTargetExt {
fn get_texture_view<'a>(
&self,
windows: &'a ExtractedWindows,
images: &'a RenderAssets<GpuImage>,
manual_texture_views: &'a ManualTextureViews,
) -> Option<&'a TextureView>;
/// Retrieves the [`TextureFormat`] of this render target, if it exists.
fn get_texture_view_format<'a>(
&self,
windows: &'a ExtractedWindows,
images: &'a RenderAssets<GpuImage>,
manual_texture_views: &'a ManualTextureViews,
) -> Option<TextureFormat>;
fn get_render_target_info<'a>(
&self,
resolutions: impl IntoIterator<Item = (Entity, &'a Window)>,
images: &Assets<Image>,
manual_texture_views: &ManualTextureViews,
) -> Result<RenderTargetInfo, MissingRenderTargetInfoError>;
// Check if this render target is contained in the given changed windows or images.
fn is_changed(
&self,
changed_window_ids: &HashSet<Entity>,
changed_image_handles: &HashSet<&AssetId<Image>>,
) -> bool;
}
impl NormalizedRenderTargetExt for NormalizedRenderTarget {
fn get_texture_view<'a>(
&self,
windows: &'a ExtractedWindows,
images: &'a RenderAssets<GpuImage>,
manual_texture_views: &'a ManualTextureViews,
) -> Option<&'a TextureView> {
match self {
NormalizedRenderTarget::Window(window_ref) => windows
.get(&window_ref.entity())
.and_then(|window| window.swap_chain_texture_view.as_ref()),
NormalizedRenderTarget::Image(image_target) => images
.get(&image_target.handle)
.map(|image| &image.texture_view),
NormalizedRenderTarget::TextureView(id) => {
manual_texture_views.get(id).map(|tex| &tex.texture_view)
}
NormalizedRenderTarget::None { .. } => None,
}
}
/// Retrieves the texture view's [`TextureFormat`] of this render target, if it exists.
fn get_texture_view_format<'a>(
&self,
windows: &'a ExtractedWindows,
images: &'a RenderAssets<GpuImage>,
manual_texture_views: &'a ManualTextureViews,
) -> Option<TextureFormat> {
match self {
NormalizedRenderTarget::Window(window_ref) => windows
.get(&window_ref.entity())
.and_then(|window| window.swap_chain_texture_view_format),
NormalizedRenderTarget::Image(image_target) => images
.get(&image_target.handle)
.map(|image| image.texture_view_format.unwrap_or(image.texture_format)),
NormalizedRenderTarget::TextureView(id) => {
manual_texture_views.get(id).map(|tex| tex.view_format)
}
NormalizedRenderTarget::None { .. } => None,
}
}
fn get_render_target_info<'a>(
&self,
resolutions: impl IntoIterator<Item = (Entity, &'a Window)>,
images: &Assets<Image>,
manual_texture_views: &ManualTextureViews,
) -> Result<RenderTargetInfo, MissingRenderTargetInfoError> {
match self {
NormalizedRenderTarget::Window(window_ref) => resolutions
.into_iter()
.find(|(entity, _)| *entity == window_ref.entity())
.map(|(_, window)| RenderTargetInfo {
physical_size: window.physical_size(),
scale_factor: window.resolution.scale_factor(),
})
.ok_or(MissingRenderTargetInfoError::Window {
window: window_ref.entity(),
}),
NormalizedRenderTarget::Image(image_target) => images
.get(&image_target.handle)
.map(|image| RenderTargetInfo {
physical_size: image.size(),
scale_factor: image_target.scale_factor,
})
.ok_or(MissingRenderTargetInfoError::Image {
image: image_target.handle.id(),
}),
NormalizedRenderTarget::TextureView(id) => manual_texture_views
.get(id)
.map(|tex| RenderTargetInfo {
physical_size: tex.size,
scale_factor: 1.0,
})
.ok_or(MissingRenderTargetInfoError::TextureView { texture_view: *id }),
NormalizedRenderTarget::None { width, height } => Ok(RenderTargetInfo {
physical_size: uvec2(*width, *height),
scale_factor: 1.0,
}),
}
}
// Check if this render target is contained in the given changed windows or images.
fn is_changed(
&self,
changed_window_ids: &HashSet<Entity>,
changed_image_handles: &HashSet<&AssetId<Image>>,
) -> bool {
match self {
NormalizedRenderTarget::Window(window_ref) => {
changed_window_ids.contains(&window_ref.entity())
}
NormalizedRenderTarget::Image(image_target) => {
changed_image_handles.contains(&image_target.handle.id())
}
NormalizedRenderTarget::TextureView(_) => true,
NormalizedRenderTarget::None { .. } => false,
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum MissingRenderTargetInfoError {
#[error("RenderTarget::Window missing ({window:?}): Make sure the provided entity has a Window component.")]
Window { window: Entity },
#[error("RenderTarget::Image missing ({image:?}): Make sure the Image's usages include RenderAssetUsages::MAIN_WORLD.")]
Image { image: AssetId<Image> },
#[error("RenderTarget::TextureView missing ({texture_view:?}): make sure the texture view handle was not removed.")]
TextureView {
texture_view: ManualTextureViewHandle,
},
}
/// System in charge of updating a [`Camera`] when its window or projection changes.
///
/// The system detects window creation, resize, and scale factor change events to update the camera
/// [`Projection`] if needed.
///
/// ## World Resources
///
/// [`Res<Assets<Image>>`](Assets<Image>) -- For cameras that render to an image, this resource is used to
/// inspect information about the render target. This system will not access any other image assets.
///
/// [`OrthographicProjection`]: bevy_camera::OrthographicProjection
/// [`PerspectiveProjection`]: bevy_camera::PerspectiveProjection
pub fn camera_system(
mut window_resized_reader: MessageReader<WindowResized>,
mut window_created_reader: MessageReader<WindowCreated>,
mut window_scale_factor_changed_reader: MessageReader<WindowScaleFactorChanged>,
mut image_asset_event_reader: MessageReader<AssetEvent<Image>>,
primary_window: Query<Entity, With<PrimaryWindow>>,
windows: Query<(Entity, &Window)>,
images: Res<Assets<Image>>,
manual_texture_views: Res<ManualTextureViews>,
mut cameras: Query<(&mut Camera, &RenderTarget, &mut Projection)>,
) -> Result<(), BevyError> {
let primary_window = primary_window.iter().next();
let mut changed_window_ids = <HashSet<_>>::default();
changed_window_ids.extend(window_created_reader.read().map(|event| event.window));
changed_window_ids.extend(window_resized_reader.read().map(|event| event.window));
let scale_factor_changed_window_ids: HashSet<_> = window_scale_factor_changed_reader
.read()
.map(|event| event.window)
.collect();
changed_window_ids.extend(scale_factor_changed_window_ids.clone());
let changed_image_handles: HashSet<&AssetId<Image>> = image_asset_event_reader
.read()
.filter_map(|event| match event {
AssetEvent::Modified { id } | AssetEvent::Added { id } => Some(id),
_ => None,
})
.collect();
for (mut camera, render_target, mut camera_projection) in &mut cameras {
let mut viewport_size = camera
.viewport
.as_ref()
.map(|viewport| viewport.physical_size);
if let Some(normalized_target) = render_target.normalize(primary_window)
&& (normalized_target.is_changed(&changed_window_ids, &changed_image_handles)
|| camera.is_added()
|| camera_projection.is_changed()
|| camera.computed.old_viewport_size != viewport_size
|| camera.computed.old_sub_camera_view != camera.sub_camera_view)
{
let new_computed_target_info = normalized_target.get_render_target_info(
windows,
&images,
&manual_texture_views,
)?;
// Check for the scale factor changing, and resize the viewport if needed.
// This can happen when the window is moved between monitors with different DPIs.
// Without this, the viewport will take a smaller portion of the window moved to
// a higher DPI monitor.
if normalized_target.is_changed(&scale_factor_changed_window_ids, &HashSet::default())
&& let Some(old_scale_factor) = camera
.computed
.target_info
.as_ref()
.map(|info| info.scale_factor)
{
let resize_factor = new_computed_target_info.scale_factor / old_scale_factor;
if let Some(ref mut viewport) = camera.viewport {
let resize = |vec: UVec2| (vec.as_vec2() * resize_factor).as_uvec2();
viewport.physical_position = resize(viewport.physical_position);
viewport.physical_size = resize(viewport.physical_size);
viewport_size = Some(viewport.physical_size);
}
}
// This check is needed because when changing WindowMode to Fullscreen, the viewport may have invalid
// arguments due to a sudden change on the window size to a lower value.
// If the size of the window is lower, the viewport will match that lower value.
if let Some(viewport) = &mut camera.viewport {
viewport.clamp_to_size(new_computed_target_info.physical_size);
}
camera.computed.target_info = Some(new_computed_target_info);
if let Some(size) = camera.logical_viewport_size()
&& size.x != 0.0
&& size.y != 0.0
{
camera_projection.update(size.x, size.y);
camera.computed.clip_from_view = match &camera.sub_camera_view {
Some(sub_view) => camera_projection.get_clip_from_view_for_sub(sub_view),
None => camera_projection.get_clip_from_view(),
}
}
}
if camera.computed.old_viewport_size != viewport_size {
camera.computed.old_viewport_size = viewport_size;
}
if camera.computed.old_sub_camera_view != camera.sub_camera_view {
camera.computed.old_sub_camera_view = camera.sub_camera_view;
}
}
Ok(())
}
#[derive(Component, Debug)]
pub struct ExtractedCamera {
pub target: Option<NormalizedRenderTarget>,
pub physical_viewport_size: Option<UVec2>,
pub physical_target_size: Option<UVec2>,
pub viewport: Option<Viewport>,
pub render_graph: InternedRenderSubGraph,
pub order: isize,
pub output_mode: CameraOutputMode,
pub msaa_writeback: MsaaWriteback,
pub clear_color: ClearColorConfig,
pub sorted_camera_index_for_target: usize,
pub exposure: f32,
pub hdr: bool,
}
pub fn extract_cameras(
mut commands: Commands,
query: Extract<
Query<(
Entity,
RenderEntity,
&Camera,
&RenderTarget,
&CameraRenderGraph,
&GlobalTransform,
&VisibleEntities,
&Frustum,
(
Has<Hdr>,
Option<&ColorGrading>,
Option<&Exposure>,
Option<&TemporalJitter>,
Option<&MipBias>,
Option<&RenderLayers>,
Option<&Projection>,
Has<NoIndirectDrawing>,
),
)>,
>,
primary_window: Extract<Query<Entity, With<PrimaryWindow>>>,
gpu_preprocessing_support: Res<GpuPreprocessingSupport>,
mapper: Extract<Query<&RenderEntity>>,
) {
let primary_window = primary_window.iter().next();
type ExtractedCameraComponents = (
ExtractedCamera,
ExtractedView,
RenderVisibleEntities,
TemporalJitter,
MipBias,
RenderLayers,
Projection,
NoIndirectDrawing,
ViewUniformOffset,
);
for (
main_entity,
render_entity,
camera,
render_target,
camera_render_graph,
transform,
visible_entities,
frustum,
(
hdr,
color_grading,
exposure,
temporal_jitter,
mip_bias,
render_layers,
projection,
no_indirect_drawing,
),
) in query.iter()
{
if !camera.is_active {
commands
.entity(render_entity)
.remove::<ExtractedCameraComponents>();
continue;
}
let color_grading = color_grading.unwrap_or(&ColorGrading::default()).clone();
if let (
Some(URect {
min: viewport_origin,
..
}),
Some(viewport_size),
Some(target_size),
) = (
camera.physical_viewport_rect(),
camera.physical_viewport_size(),
camera.physical_target_size(),
) {
if target_size.x == 0 || target_size.y == 0 {
commands
.entity(render_entity)
.remove::<ExtractedCameraComponents>();
continue;
}
let render_visible_entities = RenderVisibleEntities {
entities: visible_entities
.entities
.iter()
.map(|(type_id, entities)| {
let entities = entities
.iter()
.map(|entity| {
let render_entity = mapper
.get(*entity)
.cloned()
.map(|entity| entity.id())
.unwrap_or(Entity::PLACEHOLDER);
(render_entity, (*entity).into())
})
.collect();
(*type_id, entities)
})
.collect(),
};
let mut commands = commands.entity(render_entity);
commands.insert((
ExtractedCamera {
target: render_target.normalize(primary_window),
viewport: camera.viewport.clone(),
physical_viewport_size: Some(viewport_size),
physical_target_size: Some(target_size),
render_graph: camera_render_graph.0,
order: camera.order,
output_mode: camera.output_mode,
msaa_writeback: camera.msaa_writeback,
clear_color: camera.clear_color,
// this will be set in sort_cameras
sorted_camera_index_for_target: 0,
exposure: exposure
.map(Exposure::exposure)
.unwrap_or_else(|| Exposure::default().exposure()),
hdr,
},
ExtractedView {
retained_view_entity: RetainedViewEntity::new(main_entity.into(), None, 0),
clip_from_view: camera.clip_from_view(),
world_from_view: *transform,
clip_from_world: None,
hdr,
viewport: UVec4::new(
viewport_origin.x,
viewport_origin.y,
viewport_size.x,
viewport_size.y,
),
color_grading,
invert_culling: camera.invert_culling,
},
render_visible_entities,
*frustum,
));
if let Some(temporal_jitter) = temporal_jitter {
commands.insert(temporal_jitter.clone());
} else {
commands.remove::<TemporalJitter>();
}
if let Some(mip_bias) = mip_bias {
commands.insert(mip_bias.clone());
} else {
commands.remove::<MipBias>();
}
if let Some(render_layers) = render_layers {
commands.insert(render_layers.clone());
} else {
commands.remove::<RenderLayers>();
}
if let Some(projection) = projection {
commands.insert(projection.clone());
} else {
commands.remove::<Projection>();
}
if no_indirect_drawing
|| !matches!(
gpu_preprocessing_support.max_supported_mode,
GpuPreprocessingMode::Culling
)
{
commands.insert(NoIndirectDrawing);
} else {
commands.remove::<NoIndirectDrawing>();
}
};
}
}
/// Cameras sorted by their order field. This is updated in the [`sort_cameras`] system.
#[derive(Resource, Default)]
pub struct SortedCameras(pub Vec<SortedCamera>);
pub struct SortedCamera {
pub entity: Entity,
pub order: isize,
pub target: Option<NormalizedRenderTarget>,
pub hdr: bool,
}
pub fn sort_cameras(
mut sorted_cameras: ResMut<SortedCameras>,
mut cameras: Query<(Entity, &mut ExtractedCamera)>,
) {
sorted_cameras.0.clear();
for (entity, camera) in cameras.iter() {
sorted_cameras.0.push(SortedCamera {
entity,
order: camera.order,
target: camera.target.clone(),
hdr: camera.hdr,
});
}
// sort by order and ensure within an order, RenderTargets of the same type are packed together
sorted_cameras
.0
.sort_by(|c1, c2| (c1.order, &c1.target).cmp(&(c2.order, &c2.target)));
let mut previous_order_target = None;
let mut ambiguities = <HashSet<_>>::default();
let mut target_counts = <HashMap<_, _>>::default();
for sorted_camera in &mut sorted_cameras.0 {
let new_order_target = (sorted_camera.order, sorted_camera.target.clone());
if let Some(previous_order_target) = previous_order_target
&& previous_order_target == new_order_target
{
ambiguities.insert(new_order_target.clone());
}
if let Some(target) = &sorted_camera.target {
let count = target_counts
.entry((target.clone(), sorted_camera.hdr))
.or_insert(0usize);
let (_, mut camera) = cameras.get_mut(sorted_camera.entity).unwrap();
camera.sorted_camera_index_for_target = *count;
*count += 1;
}
previous_order_target = Some(new_order_target);
}
if !ambiguities.is_empty() {
warn!(
"Camera order ambiguities detected for active cameras with the following priorities: {:?}. \
To fix this, ensure there is exactly one Camera entity spawned with a given order for a given RenderTarget. \
Ambiguities should be resolved because either (1) multiple active cameras were spawned accidentally, which will \
result in rendering multiple instances of the scene or (2) for cases where multiple active cameras is intentional, \
ambiguities could result in unpredictable render results.",
ambiguities
);
}
}
/// A subpixel offset to jitter a perspective camera's frustum by.
///
/// Useful for temporal rendering techniques.
#[derive(Component, Clone, Default, Reflect)]
#[reflect(Default, Component, Clone)]
pub struct TemporalJitter {
/// Offset is in range [-0.5, 0.5].
pub offset: Vec2,
}
impl TemporalJitter {
pub fn jitter_projection(&self, clip_from_view: &mut Mat4, view_size: Vec2) {
// https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK/blob/d7531ae47d8b36a5d4025663e731a47a38be882f/docs/techniques/media/super-resolution-temporal/jitter-space.svg
let mut jitter = (self.offset * vec2(2.0, -2.0)) / view_size;
// orthographic
if clip_from_view.w_axis.w == 1.0 {
jitter *= vec2(clip_from_view.x_axis.x, clip_from_view.y_axis.y) * 0.5;
}
clip_from_view.z_axis.x += jitter.x;
clip_from_view.z_axis.y += jitter.y;
}
}
/// Camera component specifying a mip bias to apply when sampling from material textures.
///
/// Often used in conjunction with antialiasing post-process effects to reduce textures blurriness.
#[derive(Component, Reflect, Clone)]
#[reflect(Default, Component)]
pub struct MipBias(pub f32);
impl Default for MipBias {
fn default() -> Self {
Self(-1.0)
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_render/src/extract_param.rs | crates/bevy_render/src/extract_param.rs | use crate::MainWorld;
use bevy_ecs::{
change_detection::Tick,
prelude::*,
query::FilteredAccessSet,
system::{
ReadOnlySystemParam, SystemMeta, SystemParam, SystemParamItem, SystemParamValidationError,
SystemState,
},
world::unsafe_world_cell::UnsafeWorldCell,
};
use core::ops::{Deref, DerefMut};
/// A helper for accessing [`MainWorld`] content using a system parameter.
///
/// A [`SystemParam`] adapter which applies the contained `SystemParam` to the [`World`]
/// contained in [`MainWorld`]. This parameter only works for systems run
/// during the [`ExtractSchedule`](crate::ExtractSchedule).
///
/// This requires that the contained [`SystemParam`] does not mutate the world, as it
/// uses a read-only reference to [`MainWorld`] internally.
///
/// ## Context
///
/// [`ExtractSchedule`] is used to extract (move) data from the simulation world ([`MainWorld`]) to the
/// render world. The render world drives rendering each frame (generally to a `Window`).
/// This design is used to allow performing calculations related to rendering a prior frame at the same
/// time as the next frame is simulated, which increases throughput (FPS).
///
/// [`Extract`] is used to get data from the main world during [`ExtractSchedule`].
///
/// ## Examples
///
/// ```
/// use bevy_ecs::prelude::*;
/// use bevy_render::Extract;
/// use bevy_render::sync_world::RenderEntity;
/// # #[derive(Component)]
/// // Do make sure to sync the cloud entities before extracting them.
/// # struct Cloud;
/// fn extract_clouds(mut commands: Commands, clouds: Extract<Query<RenderEntity, With<Cloud>>>) {
/// for cloud in &clouds {
/// commands.entity(cloud).insert(Cloud);
/// }
/// }
/// ```
///
/// [`ExtractSchedule`]: crate::ExtractSchedule
/// [Window]: bevy_window::Window
pub struct Extract<'w, 's, P>
where
P: ReadOnlySystemParam + 'static,
{
item: SystemParamItem<'w, 's, P>,
}
#[doc(hidden)]
pub struct ExtractState<P: SystemParam + 'static> {
state: SystemState<P>,
main_world_state: <Res<'static, MainWorld> as SystemParam>::State,
}
// SAFETY: The only `World` access (`Res<MainWorld>`) is read-only.
unsafe impl<P> ReadOnlySystemParam for Extract<'_, '_, P> where P: ReadOnlySystemParam {}
// SAFETY: The only `World` access is properly registered by `Res<MainWorld>::init_state`.
// This call will also ensure that there are no conflicts with prior params.
unsafe impl<P> SystemParam for Extract<'_, '_, P>
where
P: ReadOnlySystemParam,
{
type State = ExtractState<P>;
type Item<'w, 's> = Extract<'w, 's, P>;
fn init_state(world: &mut World) -> Self::State {
let mut main_world = world.resource_mut::<MainWorld>();
ExtractState {
state: SystemState::new(&mut main_world),
main_world_state: Res::<MainWorld>::init_state(world),
}
}
fn init_access(
state: &Self::State,
system_meta: &mut SystemMeta,
component_access_set: &mut FilteredAccessSet,
world: &mut World,
) {
Res::<MainWorld>::init_access(
&state.main_world_state,
system_meta,
component_access_set,
world,
);
}
#[inline]
unsafe fn validate_param(
state: &mut Self::State,
_system_meta: &SystemMeta,
world: UnsafeWorldCell,
) -> Result<(), SystemParamValidationError> {
// SAFETY: Read-only access to world data registered in `init_state`.
let result = unsafe { world.get_resource_by_id(state.main_world_state) };
let Some(main_world) = result else {
return Err(SystemParamValidationError::invalid::<Self>(
"`MainWorld` resource does not exist",
));
};
// SAFETY: Type is guaranteed by `SystemState`.
let main_world: &World = unsafe { main_world.deref() };
// SAFETY: We provide the main world on which this system state was initialized on.
unsafe {
SystemState::<P>::validate_param(
&mut state.state,
main_world.as_unsafe_world_cell_readonly(),
)
}
}
#[inline]
unsafe fn get_param<'w, 's>(
state: &'s mut Self::State,
system_meta: &SystemMeta,
world: UnsafeWorldCell<'w>,
change_tick: Tick,
) -> Self::Item<'w, 's> {
// SAFETY:
// - The caller ensures that `world` is the same one that `init_state` was called with.
// - The caller ensures that no other `SystemParam`s will conflict with the accesses we have registered.
let main_world = unsafe {
Res::<MainWorld>::get_param(
&mut state.main_world_state,
system_meta,
world,
change_tick,
)
};
let item = state.state.get(main_world.into_inner());
Extract { item }
}
}
impl<'w, 's, P> Deref for Extract<'w, 's, P>
where
P: ReadOnlySystemParam,
{
type Target = SystemParamItem<'w, 's, P>;
#[inline]
fn deref(&self) -> &Self::Target {
&self.item
}
}
impl<'w, 's, P> DerefMut for Extract<'w, 's, P>
where
P: ReadOnlySystemParam,
{
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.item
}
}
impl<'a, 'w, 's, P> IntoIterator for &'a Extract<'w, 's, P>
where
P: ReadOnlySystemParam,
&'a SystemParamItem<'w, 's, P>: IntoIterator,
{
type Item = <&'a SystemParamItem<'w, 's, P> as IntoIterator>::Item;
type IntoIter = <&'a SystemParamItem<'w, 's, P> as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
(&self.item).into_iter()
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_render/src/extract_component.rs | crates/bevy_render/src/extract_component.rs | use crate::{
render_resource::{encase::internal::WriteInto, DynamicUniformBuffer, ShaderType},
renderer::{RenderDevice, RenderQueue},
sync_component::SyncComponentPlugin,
sync_world::RenderEntity,
Extract, ExtractSchedule, Render, RenderApp, RenderSystems,
};
use bevy_app::{App, Plugin};
use bevy_camera::visibility::ViewVisibility;
use bevy_ecs::{
bundle::NoBundleEffect,
component::Component,
prelude::*,
query::{QueryFilter, QueryItem, ReadOnlyQueryData},
};
use core::{marker::PhantomData, ops::Deref};
pub use bevy_render_macros::ExtractComponent;
/// Stores the index of a uniform inside of [`ComponentUniforms`].
#[derive(Component)]
pub struct DynamicUniformIndex<C: Component> {
index: u32,
marker: PhantomData<C>,
}
impl<C: Component> DynamicUniformIndex<C> {
#[inline]
pub fn index(&self) -> u32 {
self.index
}
}
/// Describes how a component gets extracted for rendering.
///
/// Therefore the component is transferred from the "app world" into the "render world"
/// in the [`ExtractSchedule`] step.
pub trait ExtractComponent: Component {
/// ECS [`ReadOnlyQueryData`] to fetch the components to extract.
type QueryData: ReadOnlyQueryData;
/// Filters the entities with additional constraints.
type QueryFilter: QueryFilter;
/// The output from extraction.
///
/// Returning `None` based on the queried item will remove the component from the entity in
/// the render world. This can be used, for example, to conditionally extract camera settings
/// in order to disable a rendering feature on the basis of those settings, without removing
/// the component from the entity in the main world.
///
/// The output may be different from the queried component.
/// This can be useful for example if only a subset of the fields are useful
/// in the render world.
///
/// `Out` has a [`Bundle`] trait bound instead of a [`Component`] trait bound in order to allow use cases
/// such as tuples of components as output.
type Out: Bundle<Effect: NoBundleEffect>;
// TODO: https://github.com/rust-lang/rust/issues/29661
// type Out: Component = Self;
/// Defines how the component is transferred into the "render world".
fn extract_component(item: QueryItem<'_, '_, Self::QueryData>) -> Option<Self::Out>;
}
/// This plugin prepares the components of the corresponding type for the GPU
/// by transforming them into uniforms.
///
/// They can then be accessed from the [`ComponentUniforms`] resource.
/// For referencing the newly created uniforms a [`DynamicUniformIndex`] is inserted
/// for every processed entity.
///
/// Therefore it sets up the [`RenderSystems::Prepare`] step
/// for the specified [`ExtractComponent`].
pub struct UniformComponentPlugin<C>(PhantomData<fn() -> C>);
impl<C> Default for UniformComponentPlugin<C> {
fn default() -> Self {
Self(PhantomData)
}
}
impl<C: Component + ShaderType + WriteInto + Clone> Plugin for UniformComponentPlugin<C> {
fn build(&self, app: &mut App) {
if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
render_app
.insert_resource(ComponentUniforms::<C>::default())
.add_systems(
Render,
prepare_uniform_components::<C>.in_set(RenderSystems::PrepareResources),
);
}
}
}
/// Stores all uniforms of the component type.
#[derive(Resource)]
pub struct ComponentUniforms<C: Component + ShaderType> {
uniforms: DynamicUniformBuffer<C>,
}
impl<C: Component + ShaderType> Deref for ComponentUniforms<C> {
type Target = DynamicUniformBuffer<C>;
#[inline]
fn deref(&self) -> &Self::Target {
&self.uniforms
}
}
impl<C: Component + ShaderType> ComponentUniforms<C> {
#[inline]
pub fn uniforms(&self) -> &DynamicUniformBuffer<C> {
&self.uniforms
}
}
impl<C: Component + ShaderType> Default for ComponentUniforms<C> {
fn default() -> Self {
Self {
uniforms: Default::default(),
}
}
}
/// This system prepares all components of the corresponding component type.
/// They are transformed into uniforms and stored in the [`ComponentUniforms`] resource.
fn prepare_uniform_components<C>(
mut commands: Commands,
render_device: Res<RenderDevice>,
render_queue: Res<RenderQueue>,
mut component_uniforms: ResMut<ComponentUniforms<C>>,
components: Query<(Entity, &C)>,
) where
C: Component + ShaderType + WriteInto + Clone,
{
let components_iter = components.iter();
let count = components_iter.len();
let Some(mut writer) =
component_uniforms
.uniforms
.get_writer(count, &render_device, &render_queue)
else {
return;
};
let entities = components_iter
.map(|(entity, component)| {
(
entity,
DynamicUniformIndex::<C> {
index: writer.write(component),
marker: PhantomData,
},
)
})
.collect::<Vec<_>>();
commands.try_insert_batch(entities);
}
/// This plugin extracts the components into the render world for synced entities.
///
/// To do so, it sets up the [`ExtractSchedule`] step for the specified [`ExtractComponent`].
pub struct ExtractComponentPlugin<C, F = ()> {
only_extract_visible: bool,
marker: PhantomData<fn() -> (C, F)>,
}
impl<C, F> Default for ExtractComponentPlugin<C, F> {
fn default() -> Self {
Self {
only_extract_visible: false,
marker: PhantomData,
}
}
}
impl<C, F> ExtractComponentPlugin<C, F> {
pub fn extract_visible() -> Self {
Self {
only_extract_visible: true,
marker: PhantomData,
}
}
}
impl<C: ExtractComponent> Plugin for ExtractComponentPlugin<C> {
fn build(&self, app: &mut App) {
app.add_plugins(SyncComponentPlugin::<C>::default());
if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
if self.only_extract_visible {
render_app.add_systems(ExtractSchedule, extract_visible_components::<C>);
} else {
render_app.add_systems(ExtractSchedule, extract_components::<C>);
}
}
}
}
/// This system extracts all components of the corresponding [`ExtractComponent`], for entities that are synced via [`crate::sync_world::SyncToRenderWorld`].
fn extract_components<C: ExtractComponent>(
mut commands: Commands,
mut previous_len: Local<usize>,
query: Extract<Query<(RenderEntity, C::QueryData), C::QueryFilter>>,
) {
let mut values = Vec::with_capacity(*previous_len);
for (entity, query_item) in &query {
if let Some(component) = C::extract_component(query_item) {
values.push((entity, component));
} else {
commands.entity(entity).remove::<C::Out>();
}
}
*previous_len = values.len();
commands.try_insert_batch(values);
}
/// This system extracts all components of the corresponding [`ExtractComponent`], for entities that are visible and synced via [`crate::sync_world::SyncToRenderWorld`].
fn extract_visible_components<C: ExtractComponent>(
mut commands: Commands,
mut previous_len: Local<usize>,
query: Extract<Query<(RenderEntity, &ViewVisibility, C::QueryData), C::QueryFilter>>,
) {
let mut values = Vec::with_capacity(*previous_len);
for (entity, view_visibility, query_item) in &query {
if view_visibility.get() {
if let Some(component) = C::extract_component(query_item) {
values.push((entity, component));
} else {
commands.entity(entity).remove::<C::Out>();
}
}
}
*previous_len = values.len();
commands.try_insert_batch(values);
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.