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_ecs/examples/events.rs | crates/bevy_ecs/examples/events.rs | //! In this example a system sends a custom messages with a 50/50 chance during any frame.
//! If a message was sent, it will be printed by the console in a receiving system.
#![expect(clippy::print_stdout, reason = "Allowed in examples.")]
use bevy_ecs::{message::MessageRegistry, prelude::*};
fn main() {
// Create a new empty world.
let mut world = World::new();
// The message registry is stored as a resource, and allows us to quickly update all messages at once.
// This call adds both the registry resource and the `Messages` resource into the world.
MessageRegistry::register_message::<MyMessage>(&mut world);
// Create a schedule to store our systems
let mut schedule = Schedule::default();
// Messages need to be updated every frame in order to clear our buffers.
// This update should happen before we use the messages.
// Here, we use system sets to control the ordering.
#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
pub struct EventFlusherSystems;
schedule.add_systems(bevy_ecs::message::message_update_system.in_set(EventFlusherSystems));
// Add systems sending and receiving messages after the messages are flushed.
schedule.add_systems((
sending_system.after(EventFlusherSystems),
receiving_system.after(sending_system),
));
// Simulate 10 frames of our world
for iteration in 1..=10 {
println!("Simulating frame {iteration}/10");
schedule.run(&mut world);
}
}
// This is our message that we will send and receive in systems
#[derive(Message)]
struct MyMessage {
pub message: String,
pub random_value: f32,
}
// In every frame we will send a message with a 50/50 chance
fn sending_system(mut message_writer: MessageWriter<MyMessage>) {
let random_value: f32 = rand::random();
if random_value > 0.5 {
message_writer.write(MyMessage {
message: "A random message with value > 0.5".to_string(),
random_value,
});
}
}
// This system listens for messages of the type MyEvent
// If a message is received it will be printed to the console
fn receiving_system(mut message_reader: MessageReader<MyMessage>) {
for my_message in message_reader.read() {
println!(
" Received message {}, with random value of {}",
my_message.message, my_message.random_value
);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_input_focus/src/lib.rs | crates/bevy_input_focus/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]
//! A UI-centric focus system for Bevy.
//!
//! This crate provides a system for managing input focus in Bevy applications, including:
//! * [`InputFocus`], a resource for tracking which entity has input focus.
//! * Methods for getting and setting input focus via [`InputFocus`] and [`IsFocusedHelper`].
//! * A generic [`FocusedInput`] event for input events which bubble up from the focused entity.
//! * Various navigation frameworks for moving input focus between entities based on user input, such as [`tab_navigation`] and [`directional_navigation`].
//!
//! This crate does *not* provide any integration with UI widgets: this is the responsibility of the widget crate,
//! which should depend on [`bevy_input_focus`](crate).
#[cfg(feature = "std")]
extern crate std;
extern crate alloc;
pub mod directional_navigation;
pub mod tab_navigation;
// This module is too small / specific to be exported by the crate,
// but it's nice to have it separate for code organization.
mod autofocus;
pub use autofocus::*;
#[cfg(any(feature = "keyboard", feature = "gamepad", feature = "mouse"))]
use bevy_app::PreUpdate;
use bevy_app::{App, Plugin, PostStartup};
use bevy_ecs::{
entity::Entities, prelude::*, query::QueryData, system::SystemParam, traversal::Traversal,
};
#[cfg(feature = "gamepad")]
use bevy_input::gamepad::GamepadButtonChangedEvent;
#[cfg(feature = "keyboard")]
use bevy_input::keyboard::KeyboardInput;
#[cfg(feature = "mouse")]
use bevy_input::mouse::MouseWheel;
use bevy_window::{PrimaryWindow, Window};
use core::fmt::Debug;
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::{prelude::*, Reflect};
/// Resource representing which entity has input focus, if any. Input events (other than pointer-like inputs) will be
/// dispatched to the current focus entity, or to the primary window if no entity has focus.
///
/// Changing the input focus is as easy as modifying this resource.
///
/// # Examples
///
/// From within a system:
///
/// ```rust
/// use bevy_ecs::prelude::*;
/// use bevy_input_focus::InputFocus;
///
/// fn clear_focus(mut input_focus: ResMut<InputFocus>) {
/// input_focus.clear();
/// }
/// ```
///
/// With exclusive (or deferred) world access:
///
/// ```rust
/// use bevy_ecs::prelude::*;
/// use bevy_input_focus::InputFocus;
///
/// fn set_focus_from_world(world: &mut World) {
/// let entity = world.spawn_empty().id();
///
/// // Fetch the resource from the world
/// let mut input_focus = world.resource_mut::<InputFocus>();
/// // Then mutate it!
/// input_focus.set(entity);
///
/// // Or you can just insert a fresh copy of the resource
/// // which will overwrite the existing one.
/// world.insert_resource(InputFocus::from_entity(entity));
/// }
/// ```
#[derive(Clone, Debug, Default, Resource)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, Default, Resource, Clone)
)]
pub struct InputFocus(pub Option<Entity>);
impl InputFocus {
/// Create a new [`InputFocus`] resource with the given entity.
///
/// This is mostly useful for tests.
pub const fn from_entity(entity: Entity) -> Self {
Self(Some(entity))
}
/// Set the entity with input focus.
pub const fn set(&mut self, entity: Entity) {
self.0 = Some(entity);
}
/// Returns the entity with input focus, if any.
pub const fn get(&self) -> Option<Entity> {
self.0
}
/// Clears input focus.
pub const fn clear(&mut self) {
self.0 = None;
}
}
/// Resource representing whether the input focus indicator should be visible on UI elements.
///
/// Note that this resource is not used by [`bevy_input_focus`](crate) itself, but is provided for
/// convenience to UI widgets or frameworks that want to display a focus indicator.
/// [`InputFocus`] may still be `Some` even if the focus indicator is not visible.
///
/// The value of this resource should be set by your focus navigation solution.
/// For a desktop/web style of user interface this would be set to true when the user presses the tab key,
/// and set to false when the user clicks on a different element.
/// By contrast, a console-style UI intended to be navigated with a gamepad may always have the focus indicator visible.
///
/// To easily access information about whether focus indicators should be shown for a given entity, use the [`IsFocused`] trait.
///
/// By default, this resource is set to `false`.
#[derive(Clone, Debug, Resource, Default)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, Resource, Clone)
)]
pub struct InputFocusVisible(pub bool);
/// A bubble-able user input event that starts at the currently focused entity.
///
/// This event is normally dispatched to the current input focus entity, if any.
/// If no entity has input focus, then the event is dispatched to the main window.
///
/// To set up your own bubbling input event, add the [`dispatch_focused_input::<MyEvent>`](dispatch_focused_input) system to your app,
/// in the [`InputFocusSystems::Dispatch`] system set during [`PreUpdate`].
#[derive(EntityEvent, Clone, Debug, Component)]
#[entity_event(propagate = WindowTraversal, auto_propagate)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Component, Clone))]
pub struct FocusedInput<M: Message + Clone> {
/// The entity that has received focused input.
#[event_target]
pub focused_entity: Entity,
/// The underlying input message.
pub input: M,
/// The primary window entity.
window: Entity,
}
/// An event which is used to set input focus. Trigger this on an entity, and it will bubble
/// until it finds a focusable entity, and then set focus to it.
#[derive(Clone, EntityEvent)]
#[entity_event(propagate = WindowTraversal, auto_propagate)]
pub struct AcquireFocus {
/// The entity that has acquired focus.
#[event_target]
pub focused_entity: Entity,
/// The primary window entity.
window: Entity,
}
#[derive(QueryData)]
/// These are for accessing components defined on the targeted entity
pub struct WindowTraversal {
child_of: Option<&'static ChildOf>,
window: Option<&'static Window>,
}
impl<M: Message + Clone> Traversal<FocusedInput<M>> for WindowTraversal {
fn traverse(item: Self::Item<'_, '_>, event: &FocusedInput<M>) -> Option<Entity> {
let WindowTraversalItem { child_of, window } = item;
// Send event to parent, if it has one.
if let Some(child_of) = child_of {
return Some(child_of.parent());
};
// Otherwise, send it to the window entity (unless this is a window entity).
if window.is_none() {
return Some(event.window);
}
None
}
}
impl Traversal<AcquireFocus> for WindowTraversal {
fn traverse(item: Self::Item<'_, '_>, event: &AcquireFocus) -> Option<Entity> {
let WindowTraversalItem { child_of, window } = item;
// Send event to parent, if it has one.
if let Some(child_of) = child_of {
return Some(child_of.parent());
};
// Otherwise, send it to the window entity (unless this is a window entity).
if window.is_none() {
return Some(event.window);
}
None
}
}
/// Plugin which sets up systems for dispatching bubbling keyboard and gamepad button events to the focused entity.
///
/// To add bubbling to your own input events, add the [`dispatch_focused_input::<MyEvent>`](dispatch_focused_input) system to your app,
/// as described in the docs for [`FocusedInput`].
pub struct InputDispatchPlugin;
impl Plugin for InputDispatchPlugin {
fn build(&self, app: &mut App) {
app.add_systems(PostStartup, set_initial_focus)
.init_resource::<InputFocus>()
.init_resource::<InputFocusVisible>();
#[cfg(any(feature = "keyboard", feature = "gamepad", feature = "mouse"))]
app.add_systems(
PreUpdate,
(
#[cfg(feature = "keyboard")]
dispatch_focused_input::<KeyboardInput>,
#[cfg(feature = "gamepad")]
dispatch_focused_input::<GamepadButtonChangedEvent>,
#[cfg(feature = "mouse")]
dispatch_focused_input::<MouseWheel>,
)
.in_set(InputFocusSystems::Dispatch),
);
}
}
/// System sets for [`bevy_input_focus`](crate).
///
/// These systems run in the [`PreUpdate`] schedule.
#[derive(SystemSet, Debug, PartialEq, Eq, Hash, Clone)]
pub enum InputFocusSystems {
/// System which dispatches bubbled input events to the focused entity, or to the primary window.
Dispatch,
}
/// If no entity is focused, sets the focus to the primary window, if any.
pub fn set_initial_focus(
mut input_focus: ResMut<InputFocus>,
window: Single<Entity, With<PrimaryWindow>>,
) {
if input_focus.0.is_none() {
input_focus.0 = Some(*window);
}
}
/// System which dispatches bubbled input events to the focused entity, or to the primary window
/// if no entity has focus.
///
/// If the currently focused entity no longer exists (has been despawned), this system will
/// automatically clear the focus and dispatch events to the primary window instead.
pub fn dispatch_focused_input<M: Message + Clone>(
mut input_reader: MessageReader<M>,
mut focus: ResMut<InputFocus>,
windows: Query<Entity, With<PrimaryWindow>>,
entities: &Entities,
mut commands: Commands,
) {
if let Ok(window) = windows.single() {
// If an element has keyboard focus, then dispatch the input event to that element.
if let Some(focused_entity) = focus.0 {
// Check if the focused entity is still alive
if entities.contains(focused_entity) {
for ev in input_reader.read() {
commands.trigger(FocusedInput {
focused_entity,
input: ev.clone(),
window,
});
}
} else {
// If the focused entity no longer exists, clear focus and dispatch to window
focus.0 = None;
for ev in input_reader.read() {
commands.trigger(FocusedInput {
focused_entity: window,
input: ev.clone(),
window,
});
}
}
} else {
// If no element has input focus, then dispatch the input event to the primary window.
// There should be only one primary window.
for ev in input_reader.read() {
commands.trigger(FocusedInput {
focused_entity: window,
input: ev.clone(),
window,
});
}
}
}
}
/// Trait which defines methods to check if an entity currently has focus.
///
/// This is implemented for [`World`] and [`IsFocusedHelper`].
/// [`DeferredWorld`](bevy_ecs::world::DeferredWorld) indirectly implements it through [`Deref`].
///
/// For use within systems, use [`IsFocusedHelper`].
///
/// Modify the [`InputFocus`] resource to change the focused entity.
///
/// [`Deref`]: std::ops::Deref
pub trait IsFocused {
/// Returns true if the given entity has input focus.
fn is_focused(&self, entity: Entity) -> bool;
/// Returns true if the given entity or any of its descendants has input focus.
///
/// Note that for unusual layouts, the focus may not be within the entity's visual bounds.
fn is_focus_within(&self, entity: Entity) -> bool;
/// Returns true if the given entity has input focus and the focus indicator should be visible.
fn is_focus_visible(&self, entity: Entity) -> bool;
/// Returns true if the given entity, or any descendant, has input focus and the focus
/// indicator should be visible.
fn is_focus_within_visible(&self, entity: Entity) -> bool;
}
/// A system param that helps get information about the current focused entity.
///
/// When working with the entire [`World`], consider using the [`IsFocused`] instead.
#[derive(SystemParam)]
pub struct IsFocusedHelper<'w, 's> {
parent_query: Query<'w, 's, &'static ChildOf>,
input_focus: Option<Res<'w, InputFocus>>,
input_focus_visible: Option<Res<'w, InputFocusVisible>>,
}
impl IsFocused for IsFocusedHelper<'_, '_> {
fn is_focused(&self, entity: Entity) -> bool {
self.input_focus
.as_deref()
.and_then(|f| f.0)
.is_some_and(|e| e == entity)
}
fn is_focus_within(&self, entity: Entity) -> bool {
let Some(focus) = self.input_focus.as_deref().and_then(|f| f.0) else {
return false;
};
if focus == entity {
return true;
}
self.parent_query.iter_ancestors(focus).any(|e| e == entity)
}
fn is_focus_visible(&self, entity: Entity) -> bool {
self.input_focus_visible.as_deref().is_some_and(|vis| vis.0) && self.is_focused(entity)
}
fn is_focus_within_visible(&self, entity: Entity) -> bool {
self.input_focus_visible.as_deref().is_some_and(|vis| vis.0) && self.is_focus_within(entity)
}
}
impl IsFocused for World {
fn is_focused(&self, entity: Entity) -> bool {
self.get_resource::<InputFocus>()
.and_then(|f| f.0)
.is_some_and(|f| f == entity)
}
fn is_focus_within(&self, entity: Entity) -> bool {
let Some(focus) = self.get_resource::<InputFocus>().and_then(|f| f.0) else {
return false;
};
let mut e = focus;
loop {
if e == entity {
return true;
}
if let Some(parent) = self.entity(e).get::<ChildOf>().map(ChildOf::parent) {
e = parent;
} else {
return false;
}
}
}
fn is_focus_visible(&self, entity: Entity) -> bool {
self.get_resource::<InputFocusVisible>()
.is_some_and(|vis| vis.0)
&& self.is_focused(entity)
}
fn is_focus_within_visible(&self, entity: Entity) -> bool {
self.get_resource::<InputFocusVisible>()
.is_some_and(|vis| vis.0)
&& self.is_focus_within(entity)
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::string::String;
use bevy_app::Startup;
use bevy_ecs::{observer::On, system::RunSystemOnce, world::DeferredWorld};
use bevy_input::{
keyboard::{Key, KeyCode},
ButtonState, InputPlugin,
};
#[derive(Component, Default)]
struct GatherKeyboardEvents(String);
fn gather_keyboard_events(
event: On<FocusedInput<KeyboardInput>>,
mut query: Query<&mut GatherKeyboardEvents>,
) {
if let Ok(mut gather) = query.get_mut(event.focused_entity) {
if let Key::Character(c) = &event.input.logical_key {
gather.0.push_str(c.as_str());
}
}
}
fn key_a_message() -> KeyboardInput {
KeyboardInput {
key_code: KeyCode::KeyA,
logical_key: Key::Character("A".into()),
state: ButtonState::Pressed,
text: Some("A".into()),
repeat: false,
window: Entity::PLACEHOLDER,
}
}
#[test]
fn test_no_panics_if_resource_missing() {
let mut app = App::new();
// Note that we do not insert InputFocus here!
let entity = app.world_mut().spawn_empty().id();
assert!(!app.world().is_focused(entity));
app.world_mut()
.run_system_once(move |helper: IsFocusedHelper| {
assert!(!helper.is_focused(entity));
assert!(!helper.is_focus_within(entity));
assert!(!helper.is_focus_visible(entity));
assert!(!helper.is_focus_within_visible(entity));
})
.unwrap();
app.world_mut()
.run_system_once(move |world: DeferredWorld| {
assert!(!world.is_focused(entity));
assert!(!world.is_focus_within(entity));
assert!(!world.is_focus_visible(entity));
assert!(!world.is_focus_within_visible(entity));
})
.unwrap();
}
#[test]
fn initial_focus_unset_if_no_primary_window() {
let mut app = App::new();
app.add_plugins((InputPlugin, InputDispatchPlugin));
app.update();
assert_eq!(app.world().resource::<InputFocus>().0, None);
}
#[test]
fn initial_focus_set_to_primary_window() {
let mut app = App::new();
app.add_plugins((InputPlugin, InputDispatchPlugin));
let entity_window = app
.world_mut()
.spawn((Window::default(), PrimaryWindow))
.id();
app.update();
assert_eq!(app.world().resource::<InputFocus>().0, Some(entity_window));
}
#[test]
fn initial_focus_not_overridden() {
let mut app = App::new();
app.add_plugins((InputPlugin, InputDispatchPlugin));
app.world_mut().spawn((Window::default(), PrimaryWindow));
app.add_systems(Startup, |mut commands: Commands| {
commands.spawn(AutoFocus);
});
app.update();
let autofocus_entity = app
.world_mut()
.query_filtered::<Entity, With<AutoFocus>>()
.single(app.world())
.unwrap();
assert_eq!(
app.world().resource::<InputFocus>().0,
Some(autofocus_entity)
);
}
#[test]
fn test_keyboard_events() {
fn get_gathered(app: &App, entity: Entity) -> &str {
app.world()
.entity(entity)
.get::<GatherKeyboardEvents>()
.unwrap()
.0
.as_str()
}
let mut app = App::new();
app.add_plugins((InputPlugin, InputDispatchPlugin))
.add_observer(gather_keyboard_events);
app.world_mut().spawn((Window::default(), PrimaryWindow));
// Run the world for a single frame to set up the initial focus
app.update();
let entity_a = app
.world_mut()
.spawn((GatherKeyboardEvents::default(), AutoFocus))
.id();
let child_of_b = app
.world_mut()
.spawn((GatherKeyboardEvents::default(),))
.id();
let entity_b = app
.world_mut()
.spawn((GatherKeyboardEvents::default(),))
.add_child(child_of_b)
.id();
assert!(app.world().is_focused(entity_a));
assert!(!app.world().is_focused(entity_b));
assert!(!app.world().is_focused(child_of_b));
assert!(!app.world().is_focus_visible(entity_a));
assert!(!app.world().is_focus_visible(entity_b));
assert!(!app.world().is_focus_visible(child_of_b));
// entity_a should receive this event
app.world_mut().write_message(key_a_message());
app.update();
assert_eq!(get_gathered(&app, entity_a), "A");
assert_eq!(get_gathered(&app, entity_b), "");
assert_eq!(get_gathered(&app, child_of_b), "");
app.world_mut().insert_resource(InputFocus(None));
assert!(!app.world().is_focused(entity_a));
assert!(!app.world().is_focus_visible(entity_a));
// This event should be lost
app.world_mut().write_message(key_a_message());
app.update();
assert_eq!(get_gathered(&app, entity_a), "A");
assert_eq!(get_gathered(&app, entity_b), "");
assert_eq!(get_gathered(&app, child_of_b), "");
app.world_mut()
.insert_resource(InputFocus::from_entity(entity_b));
assert!(app.world().is_focused(entity_b));
assert!(!app.world().is_focused(child_of_b));
app.world_mut()
.run_system_once(move |mut input_focus: ResMut<InputFocus>| {
input_focus.set(child_of_b);
})
.unwrap();
assert!(app.world().is_focus_within(entity_b));
// These events should be received by entity_b and child_of_b
app.world_mut()
.write_message_batch(core::iter::repeat_n(key_a_message(), 4));
app.update();
assert_eq!(get_gathered(&app, entity_a), "A");
assert_eq!(get_gathered(&app, entity_b), "AAAA");
assert_eq!(get_gathered(&app, child_of_b), "AAAA");
app.world_mut().resource_mut::<InputFocusVisible>().0 = true;
app.world_mut()
.run_system_once(move |helper: IsFocusedHelper| {
assert!(!helper.is_focused(entity_a));
assert!(!helper.is_focus_within(entity_a));
assert!(!helper.is_focus_visible(entity_a));
assert!(!helper.is_focus_within_visible(entity_a));
assert!(!helper.is_focused(entity_b));
assert!(helper.is_focus_within(entity_b));
assert!(!helper.is_focus_visible(entity_b));
assert!(helper.is_focus_within_visible(entity_b));
assert!(helper.is_focused(child_of_b));
assert!(helper.is_focus_within(child_of_b));
assert!(helper.is_focus_visible(child_of_b));
assert!(helper.is_focus_within_visible(child_of_b));
})
.unwrap();
app.world_mut()
.run_system_once(move |world: DeferredWorld| {
assert!(!world.is_focused(entity_a));
assert!(!world.is_focus_within(entity_a));
assert!(!world.is_focus_visible(entity_a));
assert!(!world.is_focus_within_visible(entity_a));
assert!(!world.is_focused(entity_b));
assert!(world.is_focus_within(entity_b));
assert!(!world.is_focus_visible(entity_b));
assert!(world.is_focus_within_visible(entity_b));
assert!(world.is_focused(child_of_b));
assert!(world.is_focus_within(child_of_b));
assert!(world.is_focus_visible(child_of_b));
assert!(world.is_focus_within_visible(child_of_b));
})
.unwrap();
}
#[test]
fn dispatch_clears_focus_when_focused_entity_despawned() {
let mut app = App::new();
app.add_plugins((InputPlugin, InputDispatchPlugin));
app.world_mut().spawn((Window::default(), PrimaryWindow));
app.update();
let entity = app.world_mut().spawn_empty().id();
app.world_mut()
.insert_resource(InputFocus::from_entity(entity));
app.world_mut().entity_mut(entity).despawn();
assert_eq!(app.world().resource::<InputFocus>().0, Some(entity));
// Send input event - this should clear focus instead of panicking
app.world_mut().write_message(key_a_message());
app.update();
assert_eq!(app.world().resource::<InputFocus>().0, None);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_input_focus/src/autofocus.rs | crates/bevy_input_focus/src/autofocus.rs | //! Contains the [`AutoFocus`] component and related machinery.
use bevy_ecs::{lifecycle::HookContext, prelude::*, world::DeferredWorld};
use crate::InputFocus;
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::{prelude::*, Reflect};
/// Indicates that this widget should automatically receive [`InputFocus`].
///
/// This can be useful for things like dialog boxes, the first text input in a form,
/// or the first button in a game menu.
///
/// The focus is swapped when this component is added
/// or an entity with this component is spawned.
#[derive(Debug, Default, Component, Copy, Clone)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, Default, Component, Clone)
)]
#[component(on_add = on_auto_focus_added)]
pub struct AutoFocus;
fn on_auto_focus_added(mut world: DeferredWorld, HookContext { entity, .. }: HookContext) {
if let Some(mut input_focus) = world.get_resource_mut::<InputFocus>() {
input_focus.set(entity);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_input_focus/src/directional_navigation.rs | crates/bevy_input_focus/src/directional_navigation.rs | //! A navigation framework for moving between focusable elements based on directional input.
//!
//! While virtual cursors are a common way to navigate UIs with a gamepad (or arrow keys!),
//! they are generally both slow and frustrating to use.
//! Instead, directional inputs should provide a direct way to snap between focusable elements.
//!
//! Like the rest of this crate, the [`InputFocus`] resource is manipulated to track
//! the current focus.
//!
//! Navigating between focusable entities (commonly UI nodes) is done by
//! passing a [`CompassOctant`] into the [`navigate`](DirectionalNavigation::navigate) method
//! from the [`DirectionalNavigation`] system parameter. Under the hood, an entity is found
//! automatically via brute force search in the desired [`CompassOctant`] direction.
//!
//! If some manual navigation is desired, a [`DirectionalNavigationMap`] will override the brute force
//! search in a direction for a given entity. The [`DirectionalNavigationMap`] stores a directed graph
//! of focusable entities. Each entity can have up to 8 neighbors, one for each [`CompassOctant`],
//! balancing flexibility and required precision.
//!
//! # Setting up Directional Navigation
//!
//! ## Automatic Navigation (Recommended)
//!
//! The easiest way to set up navigation is to add the [`AutoDirectionalNavigation`] component
//! to your UI entities. The system will automatically compute the nearest neighbor in each direction
//! based on position and size:
//!
//! ```rust,no_run
//! # use bevy_ecs::prelude::*;
//! # use bevy_input_focus::directional_navigation::AutoDirectionalNavigation;
//! # use bevy_ui::Node;
//! fn spawn_button(mut commands: Commands) {
//! commands.spawn((
//! Node::default(),
//! // ... other UI components ...
//! AutoDirectionalNavigation::default(), // That's it!
//! ));
//! }
//! ```
//!
//! ## Manual Navigation
//!
//! You can also manually define navigation connections using methods like
//! [`add_edge`](DirectionalNavigationMap::add_edge) and
//! [`add_looping_edges`](DirectionalNavigationMap::add_looping_edges).
//!
//! ## Combining Automatic and Manual
//!
//! Following manual edges always take precedence, allowing you to use
//! automatic navigation for most UI elements while overriding specific connections for
//! special cases like wrapping menus or cross-layer navigation.
//!
//! ## When to Use Manual Navigation
//!
//! While automatic navigation is recommended for most use cases, manual navigation provides:
//!
//! - **Precise control**: Define exact navigation flow, including non-obvious connections like looping edges
//! - **Cross-layer navigation**: Connect elements across different UI layers or z-index levels
//! - **Custom behavior**: Implement domain-specific navigation patterns (e.g., spreadsheet-style wrapping)
use alloc::vec::Vec;
use bevy_app::prelude::*;
use bevy_camera::visibility::InheritedVisibility;
use bevy_ecs::{
entity::{EntityHashMap, EntityHashSet},
prelude::*,
system::SystemParam,
};
use bevy_math::{CompassOctant, Dir2, Rect, Vec2};
use bevy_ui::{ComputedNode, ComputedUiTargetCamera, UiGlobalTransform};
use thiserror::Error;
use crate::InputFocus;
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::{prelude::*, Reflect};
/// A plugin that sets up the directional navigation resources.
#[derive(Default)]
pub struct DirectionalNavigationPlugin;
impl Plugin for DirectionalNavigationPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<DirectionalNavigationMap>()
.init_resource::<AutoNavigationConfig>();
}
}
/// Marker component to enable automatic directional navigation to and from the entity.
///
/// Simply add this component to your UI entities so that the navigation algorithm will
/// consider this entity in its calculations:
///
/// ```rust
/// # use bevy_ecs::prelude::*;
/// # use bevy_input_focus::directional_navigation::AutoDirectionalNavigation;
/// fn spawn_auto_nav_button(mut commands: Commands) {
/// commands.spawn((
/// // ... Button, Node, etc. ...
/// AutoDirectionalNavigation::default(), // That's it!
/// ));
/// }
/// ```
///
/// # Multi-Layer UIs and Z-Index
///
/// **Important**: Automatic navigation is currently **z-index agnostic** and treats
/// all entities with `AutoDirectionalNavigation` as a flat set, regardless of which UI layer
/// or z-index they belong to. This means navigation may jump between different layers (e.g.,
/// from a background menu to an overlay popup).
///
/// **Workarounds** for multi-layer UIs:
///
/// 1. **Per-layer manual edge generation**: Query entities by layer and call
/// [`auto_generate_navigation_edges()`] separately for each layer:
/// ```rust,ignore
/// for layer in &layers {
/// let nodes: Vec<FocusableArea> = query_layer(layer).collect();
/// auto_generate_navigation_edges(&mut nav_map, &nodes, &config);
/// }
/// ```
///
/// 2. **Manual cross-layer navigation**: Use [`DirectionalNavigationMap::add_edge()`]
/// to define explicit connections between layers (e.g., "Back" button to main menu).
///
/// 3. **Remove component when layer is hidden**: Dynamically add/remove
/// `AutoDirectionalNavigation` based on which layers are currently active.
///
/// See issue [#21679](https://github.com/bevyengine/bevy/issues/21679) for planned
/// improvements to layer-aware automatic navigation.
///
/// # Opting Out
///
/// To disable automatic navigation for specific entities:
///
/// - **Remove the component**: Simply don't add `AutoDirectionalNavigation` to entities
/// that should only use manual navigation edges.
/// - **Dynamically toggle**: Remove/insert the component at runtime to enable/disable
/// automatic navigation as needed.
///
/// Manual edges defined via [`DirectionalNavigationMap`] are completely independent and
/// will continue to work regardless of this component.
///
/// # Requirements (for `bevy_ui`)
///
/// Entities must also have:
/// - [`ComputedNode`] - for size information
/// - [`UiGlobalTransform`] - for position information
///
/// These are automatically added by `bevy_ui` when you spawn UI entities.
///
/// # Custom UI Systems
///
/// For custom UI frameworks, you can call [`auto_generate_navigation_edges`] directly
/// in your own system instead of using this component.
#[derive(Component, Default, Debug, Clone, Copy, PartialEq)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Component, Default, Debug, PartialEq, Clone)
)]
pub struct AutoDirectionalNavigation {
/// Whether to also consider `TabIndex` for navigation order hints.
/// Currently unused but reserved for future functionality.
pub respect_tab_order: bool,
}
/// Configuration resource for automatic navigation.
///
/// This resource controls how the automatic navigation system computes which
/// nodes should be connected in each direction.
#[derive(Resource, Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Resource, Debug, PartialEq, Clone)
)]
pub struct AutoNavigationConfig {
/// Minimum overlap ratio (0.0-1.0) required along the perpendicular axis for cardinal directions.
///
/// This parameter controls how much two UI elements must overlap in the perpendicular direction
/// to be considered reachable neighbors. It only applies to cardinal directions (`North`, `South`, `East`, `West`);
/// diagonal directions (`NorthEast`, `SouthEast`, etc.) ignore this requirement entirely.
///
/// # Calculation
///
/// The overlap factor is calculated as:
/// ```text
/// overlap_factor = actual_overlap / min(origin_size, candidate_size)
/// ```
///
/// For East/West navigation, this measures vertical overlap:
/// - `actual_overlap` = overlapping height between the two elements
/// - Sizes are the heights of the origin and candidate
///
/// For North/South navigation, this measures horizontal overlap:
/// - `actual_overlap` = overlapping width between the two elements
/// - Sizes are the widths of the origin and candidate
///
/// # Examples
///
/// - `0.0` (default): Any overlap is sufficient. Even if elements barely touch, they can be neighbors.
/// - `0.5`: Elements must overlap by at least 50% of the smaller element's size.
/// - `1.0`: Perfect alignment required. The smaller element must be completely within the bounds
/// of the larger element along the perpendicular axis.
///
/// # Use Cases
///
/// - **Sparse/irregular layouts** (e.g., star constellations): Use `0.0` to allow navigation
/// between elements that don't directly align.
/// - **Grid layouts**: Use `0.5` or higher to ensure navigation only connects elements in
/// the same row or column.
/// - **Strict alignment**: Use `1.0` to require perfect alignment, though this may result
/// in disconnected navigation graphs if elements aren't precisely aligned.
pub min_alignment_factor: f32,
/// Maximum search distance in logical pixels.
///
/// Nodes beyond this distance won't be connected. `None` means unlimited.
pub max_search_distance: Option<f32>,
/// Whether to prefer nodes that are more aligned with the exact direction.
///
/// When `true`, nodes that are more directly in line with the requested direction
/// will be strongly preferred over nodes at an angle.
pub prefer_aligned: bool,
}
impl Default for AutoNavigationConfig {
fn default() -> Self {
Self {
min_alignment_factor: 0.0, // Any overlap is acceptable
max_search_distance: None, // No distance limit
prefer_aligned: true, // Prefer well-aligned nodes
}
}
}
/// The up-to-eight neighbors of a focusable entity, one for each [`CompassOctant`].
#[derive(Default, Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Debug, PartialEq, Clone)
)]
pub struct NavNeighbors {
/// The array of neighbors, one for each [`CompassOctant`].
/// The mapping between array elements and directions is determined by [`CompassOctant::to_index`].
///
/// If no neighbor exists in a given direction, the value will be [`None`].
/// In most cases, using [`NavNeighbors::set`] and [`NavNeighbors::get`]
/// will be more ergonomic than directly accessing this array.
pub neighbors: [Option<Entity>; 8],
}
impl NavNeighbors {
/// An empty set of neighbors.
pub const EMPTY: NavNeighbors = NavNeighbors {
neighbors: [None; 8],
};
/// Get the neighbor for a given [`CompassOctant`].
pub const fn get(&self, octant: CompassOctant) -> Option<Entity> {
self.neighbors[octant.to_index()]
}
/// Set the neighbor for a given [`CompassOctant`].
pub const fn set(&mut self, octant: CompassOctant, entity: Entity) {
self.neighbors[octant.to_index()] = Some(entity);
}
}
/// A resource that stores the manually specified traversable graph of focusable entities.
///
/// Each entity can have up to 8 neighbors, one for each [`CompassOctant`].
///
/// To ensure that your graph is intuitive to navigate and generally works correctly, it should be:
///
/// - **Connected**: Every focusable entity should be reachable from every other focusable entity.
/// - **Symmetric**: If entity A is a neighbor of entity B, then entity B should be a neighbor of entity A, ideally in the reverse direction.
/// - **Physical**: The direction of navigation should match the layout of the entities when possible,
/// although looping around the edges of the screen is also acceptable.
/// - **Not self-connected**: An entity should not be a neighbor of itself; use [`None`] instead.
///
/// This graph must be built and maintained manually, and the developer is responsible for ensuring that it meets the above criteria.
/// Notably, if the developer adds or removes the navigability of an entity, the developer should update the map as necessary.
#[derive(Resource, Debug, Default, Clone, PartialEq)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Resource, Debug, Default, PartialEq, Clone)
)]
pub struct DirectionalNavigationMap {
/// A directed graph of focusable entities.
///
/// Pass in the current focus as a key, and get back a collection of up to 8 neighbors,
/// each keyed by a [`CompassOctant`].
pub neighbors: EntityHashMap<NavNeighbors>,
}
impl DirectionalNavigationMap {
/// Removes an entity from the navigation map, including all connections to and from it.
///
/// Note that this is an O(n) operation, where n is the number of entities in the map,
/// as we must iterate over each entity to check for connections to the removed entity.
///
/// If you are removing multiple entities, consider using [`remove_multiple`](Self::remove_multiple) instead.
pub fn remove(&mut self, entity: Entity) {
self.neighbors.remove(&entity);
for node in self.neighbors.values_mut() {
for neighbor in node.neighbors.iter_mut() {
if *neighbor == Some(entity) {
*neighbor = None;
}
}
}
}
/// Removes a collection of entities from the navigation map.
///
/// While this is still an O(n) operation, where n is the number of entities in the map,
/// it is more efficient than calling [`remove`](Self::remove) multiple times,
/// as we can check for connections to all removed entities in a single pass.
///
/// An [`EntityHashSet`] must be provided as it is noticeably faster than the standard hasher or a [`Vec`](`alloc::vec::Vec`).
pub fn remove_multiple(&mut self, entities: EntityHashSet) {
for entity in &entities {
self.neighbors.remove(entity);
}
for node in self.neighbors.values_mut() {
for neighbor in node.neighbors.iter_mut() {
if let Some(entity) = *neighbor {
if entities.contains(&entity) {
*neighbor = None;
}
}
}
}
}
/// Completely clears the navigation map, removing all entities and connections.
pub fn clear(&mut self) {
self.neighbors.clear();
}
/// Adds an edge between two entities in the navigation map.
/// Any existing edge from A in the provided direction will be overwritten.
///
/// The reverse edge will not be added, so navigation will only be possible in one direction.
/// If you want to add a symmetrical edge, use [`add_symmetrical_edge`](Self::add_symmetrical_edge) instead.
pub fn add_edge(&mut self, a: Entity, b: Entity, direction: CompassOctant) {
self.neighbors
.entry(a)
.or_insert(NavNeighbors::EMPTY)
.set(direction, b);
}
/// Adds a symmetrical edge between two entities in the navigation map.
/// The A -> B path will use the provided direction, while B -> A will use the [`CompassOctant::opposite`] variant.
///
/// Any existing connections between the two entities will be overwritten.
pub fn add_symmetrical_edge(&mut self, a: Entity, b: Entity, direction: CompassOctant) {
self.add_edge(a, b, direction);
self.add_edge(b, a, direction.opposite());
}
/// Add symmetrical edges between each consecutive pair of entities in the provided slice.
///
/// Unlike [`add_looping_edges`](Self::add_looping_edges), this method does not loop back to the first entity.
pub fn add_edges(&mut self, entities: &[Entity], direction: CompassOctant) {
for pair in entities.windows(2) {
self.add_symmetrical_edge(pair[0], pair[1], direction);
}
}
/// Add symmetrical edges between each consecutive pair of entities in the provided slice, looping back to the first entity at the end.
///
/// This is useful for creating a circular navigation path between a set of entities, such as a menu.
pub fn add_looping_edges(&mut self, entities: &[Entity], direction: CompassOctant) {
self.add_edges(entities, direction);
if let Some((first_entity, rest)) = entities.split_first() {
if let Some(last_entity) = rest.last() {
self.add_symmetrical_edge(*last_entity, *first_entity, direction);
}
}
}
/// Gets the entity in a given direction from the current focus, if any.
pub fn get_neighbor(&self, focus: Entity, octant: CompassOctant) -> Option<Entity> {
self.neighbors
.get(&focus)
.and_then(|neighbors| neighbors.get(octant))
}
/// Looks up the neighbors of a given entity.
///
/// If the entity is not in the map, [`None`] will be returned.
/// Note that the set of neighbors is not guaranteed to be non-empty though!
pub fn get_neighbors(&self, entity: Entity) -> Option<&NavNeighbors> {
self.neighbors.get(&entity)
}
}
/// A system parameter for navigating between focusable entities in a directional way.
#[derive(SystemParam, Debug)]
pub struct DirectionalNavigation<'w, 's> {
/// The currently focused entity.
pub focus: ResMut<'w, InputFocus>,
/// The directional navigation map containing manually defined connections between entities.
pub map: Res<'w, DirectionalNavigationMap>,
/// Configuration for the automated portion of the navigation algorithm.
pub config: Res<'w, AutoNavigationConfig>,
/// The entities which can possibly be navigated to automatically.
navigable_entities_query: Query<
'w,
's,
(
Entity,
&'static ComputedUiTargetCamera,
&'static ComputedNode,
&'static UiGlobalTransform,
&'static InheritedVisibility,
),
With<AutoDirectionalNavigation>,
>,
/// A query used to get the target camera and the [`FocusableArea`] for a given entity to be used in automatic navigation.
camera_and_focusable_area_query: Query<
'w,
's,
(
Entity,
&'static ComputedUiTargetCamera,
&'static ComputedNode,
&'static UiGlobalTransform,
),
With<AutoDirectionalNavigation>,
>,
}
impl<'w, 's> DirectionalNavigation<'w, 's> {
/// Navigates to the neighbor in a given direction from the current focus, if any.
///
/// Returns the new focus if successful.
/// Returns an error if there is no focus set or if there is no neighbor in the requested direction.
///
/// If the result was `Ok`, the [`InputFocus`] resource is updated to the new focus as part of this method call.
pub fn navigate(
&mut self,
direction: CompassOctant,
) -> Result<Entity, DirectionalNavigationError> {
if let Some(current_focus) = self.focus.0 {
// Respect manual edges first
if let Some(new_focus) = self.map.get_neighbor(current_focus, direction) {
self.focus.set(new_focus);
Ok(new_focus)
} else if let Some((target_camera, origin)) =
self.entity_to_camera_and_focusable_area(current_focus)
&& let Some(new_focus) = find_best_candidate(
&origin,
direction,
&self.get_navigable_nodes(target_camera),
&self.config,
)
{
self.focus.set(new_focus);
Ok(new_focus)
} else {
Err(DirectionalNavigationError::NoNeighborInDirection {
current_focus,
direction,
})
}
} else {
Err(DirectionalNavigationError::NoFocus)
}
}
/// Returns a vec of [`FocusableArea`] representing nodes that are eligible to be automatically navigated to.
/// The camera of any navigable nodes will equal the desired `target_camera`.
fn get_navigable_nodes(&self, target_camera: Entity) -> Vec<FocusableArea> {
self.navigable_entities_query
.iter()
.filter_map(
|(entity, computed_target_camera, computed, transform, inherited_visibility)| {
// Skip hidden or zero-size nodes
if computed.is_empty() || !inherited_visibility.get() {
return None;
}
// Accept nodes that have the same target camera as the desired target camera
if let Some(tc) = computed_target_camera.get()
&& tc == target_camera
{
let (_scale, _rotation, translation) =
transform.to_scale_angle_translation();
Some(FocusableArea {
entity,
position: translation * computed.inverse_scale_factor(),
size: computed.size() * computed.inverse_scale_factor(),
})
} else {
// The node either does not have a target camera or it is not the same as the desired one.
None
}
},
)
.collect()
}
/// Gets the target camera and the [`FocusableArea`] of the provided entity, if it exists.
///
/// Returns None if there was a [`QueryEntityError`](bevy_ecs::query::QueryEntityError) or
/// if the entity does not have a target camera.
fn entity_to_camera_and_focusable_area(
&self,
entity: Entity,
) -> Option<(Entity, FocusableArea)> {
self.camera_and_focusable_area_query.get(entity).map_or(
None,
|(entity, computed_target_camera, computed, transform)| {
if let Some(target_camera) = computed_target_camera.get() {
let (_scale, _rotation, translation) = transform.to_scale_angle_translation();
Some((
target_camera,
FocusableArea {
entity,
position: translation * computed.inverse_scale_factor(),
size: computed.size() * computed.inverse_scale_factor(),
},
))
} else {
None
}
},
)
}
}
/// An error that can occur when navigating between focusable entities using [directional navigation](crate::directional_navigation).
#[derive(Debug, PartialEq, Clone, Error)]
pub enum DirectionalNavigationError {
/// No focusable entity is currently set.
#[error("No focusable entity is currently set.")]
NoFocus,
/// No neighbor in the requested direction.
#[error("No neighbor from {current_focus} in the {direction:?} direction.")]
NoNeighborInDirection {
/// The entity that was the focus when the error occurred.
current_focus: Entity,
/// The direction in which the navigation was attempted.
direction: CompassOctant,
},
}
/// A focusable area with position and size information.
///
/// This struct represents a UI element used during automatic directional navigation,
/// containing its entity ID, center position, and size for spatial navigation calculations.
///
/// The term "focusable area" avoids confusion with UI [`Node`](bevy_ui::Node) components.
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Clone)
)]
pub struct FocusableArea {
/// The entity identifier for this focusable area.
pub entity: Entity,
/// The center position in global coordinates.
pub position: Vec2,
/// The size (width, height) of the area.
pub size: Vec2,
}
/// Trait for extracting position and size from navigable UI components.
///
/// This allows the auto-navigation system to work with different UI implementations
/// as long as they can provide position and size information.
pub trait Navigable {
/// Returns the center position and size in global coordinates.
fn get_bounds(&self) -> (Vec2, Vec2);
}
// We can't directly implement this for `bevy_ui` types here without circular dependencies,
// so we'll use a more generic approach with separate functions for different component sets.
/// Calculate 1D overlap between two ranges.
///
/// Returns a value between 0.0 (no overlap) and 1.0 (perfect overlap).
fn calculate_1d_overlap(
origin_pos: f32,
origin_size: f32,
candidate_pos: f32,
candidate_size: f32,
) -> f32 {
let origin_min = origin_pos - origin_size / 2.0;
let origin_max = origin_pos + origin_size / 2.0;
let cand_min = candidate_pos - candidate_size / 2.0;
let cand_max = candidate_pos + candidate_size / 2.0;
let overlap = (origin_max.min(cand_max) - origin_min.max(cand_min)).max(0.0);
let max_overlap = origin_size.min(candidate_size);
if max_overlap > 0.0 {
overlap / max_overlap
} else {
0.0
}
}
/// Calculate the overlap factor between two nodes in the perpendicular axis.
///
/// Returns a value between 0.0 (no overlap) and 1.0 (perfect overlap).
/// For diagonal directions, always returns 1.0.
fn calculate_overlap(
origin_pos: Vec2,
origin_size: Vec2,
candidate_pos: Vec2,
candidate_size: Vec2,
octant: CompassOctant,
) -> f32 {
match octant {
CompassOctant::North | CompassOctant::South => {
// Check horizontal overlap
calculate_1d_overlap(
origin_pos.x,
origin_size.x,
candidate_pos.x,
candidate_size.x,
)
}
CompassOctant::East | CompassOctant::West => {
// Check vertical overlap
calculate_1d_overlap(
origin_pos.y,
origin_size.y,
candidate_pos.y,
candidate_size.y,
)
}
// Diagonal directions don't require strict overlap
_ => 1.0,
}
}
/// Score a candidate node for navigation in a given direction.
///
/// Lower score is better. Returns `f32::INFINITY` for unreachable nodes.
fn score_candidate(
origin_pos: Vec2,
origin_size: Vec2,
candidate_pos: Vec2,
candidate_size: Vec2,
octant: CompassOctant,
config: &AutoNavigationConfig,
) -> f32 {
// Get direction in mathematical coordinates, then flip Y for UI coordinates
let dir = Dir2::from(octant).as_vec2() * Vec2::new(1.0, -1.0);
let to_candidate = candidate_pos - origin_pos;
// Check direction first
// Convert UI coordinates (Y+ = down) to mathematical coordinates (Y+ = up) by flipping Y
let origin_math = Vec2::new(origin_pos.x, -origin_pos.y);
let candidate_math = Vec2::new(candidate_pos.x, -candidate_pos.y);
if !octant.is_in_direction(origin_math, candidate_math) {
return f32::INFINITY;
}
// Check overlap for cardinal directions
let overlap_factor = calculate_overlap(
origin_pos,
origin_size,
candidate_pos,
candidate_size,
octant,
);
if overlap_factor < config.min_alignment_factor {
return f32::INFINITY;
}
// Calculate distance between rectangle edges, not centers
let origin_rect = Rect::from_center_size(origin_pos, origin_size);
let candidate_rect = Rect::from_center_size(candidate_pos, candidate_size);
let dx = (candidate_rect.min.x - origin_rect.max.x)
.max(origin_rect.min.x - candidate_rect.max.x)
.max(0.0);
let dy = (candidate_rect.min.y - origin_rect.max.y)
.max(origin_rect.min.y - candidate_rect.max.y)
.max(0.0);
let distance = (dx * dx + dy * dy).sqrt();
// Check max distance
if let Some(max_dist) = config.max_search_distance {
if distance > max_dist {
return f32::INFINITY;
}
}
// Calculate alignment score using center-to-center direction
let center_distance = to_candidate.length();
let alignment = if center_distance > 0.0 {
to_candidate.normalize().dot(dir).max(0.0)
} else {
1.0
};
// Combine distance and alignment
// Prefer aligned nodes by penalizing misalignment
let alignment_penalty = if config.prefer_aligned {
(1.0 - alignment) * distance * 2.0 // Misalignment scales with distance
} else {
0.0
};
distance + alignment_penalty
}
/// Finds the best entity to navigate to from the origin towards the given direction.
///
/// For details on what "best" means here, refer to [`AutoNavigationConfig`].
fn find_best_candidate(
origin: &FocusableArea,
direction: CompassOctant,
candidates: &[FocusableArea],
config: &AutoNavigationConfig,
) -> Option<Entity> {
// Find best candidate in this direction
let mut best_candidate = None;
let mut best_score = f32::INFINITY;
for candidate in candidates {
// Skip self
if candidate.entity == origin.entity {
continue;
}
// Score the candidate
let score = score_candidate(
origin.position,
origin.size,
candidate.position,
candidate.size,
direction,
config,
);
if score < best_score {
best_score = score;
best_candidate = Some(candidate.entity);
}
}
best_candidate
}
/// Automatically generates directional navigation edges for a collection of nodes.
///
/// This function takes a slice of navigation nodes with their positions and sizes, and populates
/// the navigation map with edges to the nearest neighbor in each compass direction.
/// Manual edges already in the map are preserved and not overwritten.
///
/// # Arguments
///
/// * `nav_map` - The navigation map to populate
/// * `nodes` - A slice of [`FocusableArea`] structs containing entity, position, and size data
/// * `config` - Configuration for the auto-generation algorithm
///
/// # Example
///
/// ```rust
/// # use bevy_input_focus::directional_navigation::*;
/// # use bevy_ecs::entity::Entity;
/// # use bevy_math::Vec2;
/// let mut nav_map = DirectionalNavigationMap::default();
/// let config = AutoNavigationConfig::default();
///
/// let nodes = vec![
/// FocusableArea { entity: Entity::PLACEHOLDER, position: Vec2::new(100.0, 100.0), size: Vec2::new(50.0, 50.0) },
/// FocusableArea { entity: Entity::PLACEHOLDER, position: Vec2::new(200.0, 100.0), size: Vec2::new(50.0, 50.0) },
/// ];
///
/// auto_generate_navigation_edges(&mut nav_map, &nodes, &config);
/// ```
pub fn auto_generate_navigation_edges(
nav_map: &mut DirectionalNavigationMap,
nodes: &[FocusableArea],
config: &AutoNavigationConfig,
) {
// For each node, find best neighbor in each direction
for origin in nodes {
for octant in [
CompassOctant::North,
CompassOctant::NorthEast,
CompassOctant::East,
CompassOctant::SouthEast,
CompassOctant::South,
CompassOctant::SouthWest,
CompassOctant::West,
CompassOctant::NorthWest,
] {
// Skip if manual edge already exists (check inline to avoid borrow issues)
if nav_map
.get_neighbors(origin.entity)
.and_then(|neighbors| neighbors.get(octant))
.is_some()
{
continue; // Respect manual override
}
// Find best candidate in this direction
let best_candidate = find_best_candidate(origin, octant, nodes, config);
// Add edge if we found a valid candidate
if let Some(neighbor) = best_candidate {
nav_map.add_edge(origin.entity, neighbor, octant);
}
}
}
}
#[cfg(test)]
mod tests {
use alloc::vec;
use bevy_ecs::system::RunSystemOnce;
use super::*;
#[test]
fn setting_and_getting_nav_neighbors() {
let mut neighbors = NavNeighbors::EMPTY;
assert_eq!(neighbors.get(CompassOctant::SouthEast), None);
neighbors.set(CompassOctant::SouthEast, Entity::PLACEHOLDER);
for i in 0..8 {
if i == CompassOctant::SouthEast.to_index() {
assert_eq!(
neighbors.get(CompassOctant::SouthEast),
Some(Entity::PLACEHOLDER)
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_input_focus/src/tab_navigation.rs | crates/bevy_input_focus/src/tab_navigation.rs | //! This module provides a framework for handling linear tab-key navigation in Bevy applications.
//!
//! The rules of tabbing are derived from the HTML specification, and are as follows:
//!
//! * An index >= 0 means that the entity is tabbable via sequential navigation.
//! The order of tabbing is determined by the index, with lower indices being tabbed first.
//! If two entities have the same index, then the order is determined by the order of
//! the entities in the ECS hierarchy (as determined by Parent/Child).
//! * An index < 0 means that the entity is not focusable via sequential navigation, but
//! can still be focused via direct selection.
//!
//! Tabbable entities must be descendants of a [`TabGroup`] entity, which is a component that
//! marks a tree of entities as containing tabbable elements. The order of tab groups
//! is determined by the [`TabGroup::order`] field, with lower orders being tabbed first. Modal tab groups
//! are used for ui elements that should only tab within themselves, such as modal dialog boxes.
//!
//! To enable automatic tabbing, add the
//! [`TabNavigationPlugin`] and [`InputDispatchPlugin`](crate::InputDispatchPlugin) to your app.
//! This will install a keyboard event observer on the primary window which automatically handles
//! tab navigation for you.
//!
//! Alternatively, if you want to have more control over tab navigation, or are using an input-action-mapping framework,
//! you can use the [`TabNavigation`] system parameter directly instead.
//! This object can be injected into your systems, and provides a [`navigate`](`TabNavigation::navigate`) method which can be
//! used to navigate between focusable entities.
use alloc::vec::Vec;
use bevy_app::{App, Plugin, Startup};
use bevy_ecs::{
component::Component,
entity::Entity,
hierarchy::{ChildOf, Children},
observer::On,
query::{With, Without},
system::{Commands, Query, Res, ResMut, SystemParam},
};
use bevy_input::{
keyboard::{KeyCode, KeyboardInput},
ButtonInput, ButtonState,
};
use bevy_window::{PrimaryWindow, Window};
use log::warn;
use thiserror::Error;
use crate::{AcquireFocus, FocusedInput, InputFocus, InputFocusVisible};
#[cfg(feature = "bevy_reflect")]
use {
bevy_ecs::prelude::ReflectComponent,
bevy_reflect::{prelude::*, Reflect},
};
/// A component which indicates that an entity wants to participate in tab navigation.
///
/// Note that you must also add the [`TabGroup`] component to the entity's ancestor in order
/// for this component to have any effect.
#[derive(Debug, Default, Component, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, Default, Component, PartialEq, Clone)
)]
pub struct TabIndex(pub i32);
/// A component used to mark a tree of entities as containing tabbable elements.
#[derive(Debug, Default, Component, Copy, Clone)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, Default, Component, Clone)
)]
pub struct TabGroup {
/// The order of the tab group relative to other tab groups.
pub order: i32,
/// Whether this is a 'modal' group. If true, then tabbing within the group (that is,
/// if the current focus entity is a child of this group) will cycle through the children
/// of this group. If false, then tabbing within the group will cycle through all non-modal
/// tab groups.
pub modal: bool,
}
impl TabGroup {
/// Create a new tab group with the given order.
pub fn new(order: i32) -> Self {
Self {
order,
modal: false,
}
}
/// Create a modal tab group.
pub fn modal() -> Self {
Self {
order: 0,
modal: true,
}
}
}
/// A navigation action that users might take to navigate your user interface in a cyclic fashion.
///
/// These values are consumed by the [`TabNavigation`] system param.
#[derive(Clone, Copy)]
pub enum NavAction {
/// Navigate to the next focusable entity, wrapping around to the beginning if at the end.
///
/// This is commonly triggered by pressing the Tab key.
Next,
/// Navigate to the previous focusable entity, wrapping around to the end if at the beginning.
///
/// This is commonly triggered by pressing Shift+Tab.
Previous,
/// Navigate to the first focusable entity.
///
/// This is commonly triggered by pressing Home.
First,
/// Navigate to the last focusable entity.
///
/// This is commonly triggered by pressing End.
Last,
}
/// An error that can occur during [tab navigation](crate::tab_navigation).
#[derive(Debug, Error, PartialEq, Eq, Clone)]
pub enum TabNavigationError {
/// No tab groups were found.
#[error("No tab groups found")]
NoTabGroups,
/// No focusable entities were found.
#[error("No focusable entities found")]
NoFocusableEntities,
/// Could not navigate to the next focusable entity.
///
/// This can occur if your tab groups are malformed.
#[error("Failed to navigate to next focusable entity")]
FailedToNavigateToNextFocusableEntity,
/// No tab group for the current focus entity was found.
#[error("No tab group found for currently focused entity {previous_focus}. Users will not be able to navigate back to this entity.")]
NoTabGroupForCurrentFocus {
/// The entity that was previously focused,
/// and is missing its tab group.
previous_focus: Entity,
/// The new entity that will be focused.
///
/// If you want to recover from this error, set [`InputFocus`] to this entity.
new_focus: Entity,
},
}
/// An injectable helper object that provides tab navigation functionality.
#[doc(hidden)]
#[derive(SystemParam)]
pub struct TabNavigation<'w, 's> {
// Query for tab groups.
tabgroup_query: Query<'w, 's, (Entity, &'static TabGroup, &'static Children)>,
// Query for tab indices.
tabindex_query: Query<
'w,
's,
(Entity, Option<&'static TabIndex>, Option<&'static Children>),
Without<TabGroup>,
>,
// Query for parents.
parent_query: Query<'w, 's, &'static ChildOf>,
}
impl TabNavigation<'_, '_> {
/// Navigate to the desired focusable entity, relative to the current focused entity.
///
/// Change the [`NavAction`] to navigate in a different direction.
/// Focusable entities are determined by the presence of the [`TabIndex`] component.
///
/// If there is no currently focused entity, then this function will return either the first
/// or last focusable entity, depending on the direction of navigation. For example, if
/// `action` is `Next` and no focusable entities are found, then this function will return
/// the first focusable entity.
pub fn navigate(
&self,
focus: &InputFocus,
action: NavAction,
) -> Result<Entity, TabNavigationError> {
// If there are no tab groups, then there are no focusable entities.
if self.tabgroup_query.is_empty() {
return Err(TabNavigationError::NoTabGroups);
}
// Start by identifying which tab group we are in. Mainly what we want to know is if
// we're in a modal group.
let tabgroup = focus.0.and_then(|focus_ent| {
self.parent_query
.iter_ancestors(focus_ent)
.find_map(|entity| {
self.tabgroup_query
.get(entity)
.ok()
.map(|(_, tg, _)| (entity, tg))
})
});
self.navigate_internal(focus.0, action, tabgroup)
}
/// Initialize focus to a focusable child of a container, either the first or last
/// depending on [`NavAction`]. This assumes that the parent entity has a [`TabGroup`]
/// component.
///
/// Focusable entities are determined by the presence of the [`TabIndex`] component.
pub fn initialize(
&self,
parent: Entity,
action: NavAction,
) -> Result<Entity, TabNavigationError> {
// If there are no tab groups, then there are no focusable entities.
if self.tabgroup_query.is_empty() {
return Err(TabNavigationError::NoTabGroups);
}
// Look for the tab group on the parent entity.
match self.tabgroup_query.get(parent) {
Ok(tabgroup) => self.navigate_internal(None, action, Some((parent, tabgroup.1))),
Err(_) => Err(TabNavigationError::NoTabGroups),
}
}
pub fn navigate_internal(
&self,
focus: Option<Entity>,
action: NavAction,
tabgroup: Option<(Entity, &TabGroup)>,
) -> Result<Entity, TabNavigationError> {
let navigation_result = self.navigate_in_group(tabgroup, focus, action);
match navigation_result {
Ok(entity) => {
if let Some(previous_focus) = focus
&& tabgroup.is_none()
{
Err(TabNavigationError::NoTabGroupForCurrentFocus {
previous_focus,
new_focus: entity,
})
} else {
Ok(entity)
}
}
Err(e) => Err(e),
}
}
fn navigate_in_group(
&self,
tabgroup: Option<(Entity, &TabGroup)>,
focus: Option<Entity>,
action: NavAction,
) -> Result<Entity, TabNavigationError> {
// List of all focusable entities found.
let mut focusable: Vec<(Entity, TabIndex, usize)> =
Vec::with_capacity(self.tabindex_query.iter().len());
match tabgroup {
Some((tg_entity, tg)) if tg.modal => {
// We're in a modal tab group, then gather all tab indices in that group.
if let Ok((_, _, children)) = self.tabgroup_query.get(tg_entity) {
for child in children.iter() {
self.gather_focusable(&mut focusable, *child, 0);
}
}
}
_ => {
// Otherwise, gather all tab indices in all non-modal tab groups.
let mut tab_groups: Vec<(Entity, TabGroup)> = self
.tabgroup_query
.iter()
.filter(|(_, tg, _)| !tg.modal)
.map(|(e, tg, _)| (e, *tg))
.collect();
// Stable sort by group order
tab_groups.sort_by_key(|(_, tg)| tg.order);
// Search group descendants
tab_groups
.iter()
.enumerate()
.for_each(|(idx, (tg_entity, _))| {
self.gather_focusable(&mut focusable, *tg_entity, idx);
});
}
}
if focusable.is_empty() {
return Err(TabNavigationError::NoFocusableEntities);
}
// Sort by TabGroup and then TabIndex
focusable.sort_by(|(_, a_tab_idx, a_group), (_, b_tab_idx, b_group)| {
if a_group == b_group {
a_tab_idx.cmp(b_tab_idx)
} else {
a_group.cmp(b_group)
}
});
let index = focusable.iter().position(|e| Some(e.0) == focus);
let count = focusable.len();
let next = match (index, action) {
(Some(idx), NavAction::Next) => (idx + 1).rem_euclid(count),
(Some(idx), NavAction::Previous) => (idx + count - 1).rem_euclid(count),
(None, NavAction::Next) | (_, NavAction::First) => 0,
(None, NavAction::Previous) | (_, NavAction::Last) => count - 1,
};
match focusable.get(next) {
Some((entity, _, _)) => Ok(*entity),
None => Err(TabNavigationError::FailedToNavigateToNextFocusableEntity),
}
}
/// Gather all focusable entities in tree order.
fn gather_focusable(
&self,
out: &mut Vec<(Entity, TabIndex, usize)>,
parent: Entity,
tab_group_idx: usize,
) {
if let Ok((entity, tabindex, children)) = self.tabindex_query.get(parent) {
if let Some(tabindex) = tabindex {
if tabindex.0 >= 0 {
out.push((entity, *tabindex, tab_group_idx));
}
}
if let Some(children) = children {
for child in children.iter() {
// Don't traverse into tab groups, as they are handled separately.
if self.tabgroup_query.get(*child).is_err() {
self.gather_focusable(out, *child, tab_group_idx);
}
}
}
} else if let Ok((_, tabgroup, children)) = self.tabgroup_query.get(parent) {
if !tabgroup.modal {
for child in children.iter() {
self.gather_focusable(out, *child, tab_group_idx);
}
}
}
}
}
/// Observer which sets focus to the nearest ancestor that has tab index, using bubbling.
pub(crate) fn acquire_focus(
mut acquire_focus: On<AcquireFocus>,
focusable: Query<(), With<TabIndex>>,
windows: Query<(), With<Window>>,
mut focus: ResMut<InputFocus>,
) {
// If the entity has a TabIndex
if focusable.contains(acquire_focus.focused_entity) {
// Stop and focus it
acquire_focus.propagate(false);
// Don't mutate unless we need to, for change detection
if focus.0 != Some(acquire_focus.focused_entity) {
focus.0 = Some(acquire_focus.focused_entity);
}
} else if windows.contains(acquire_focus.focused_entity) {
// Stop and clear focus
acquire_focus.propagate(false);
// Don't mutate unless we need to, for change detection
if focus.0.is_some() {
focus.clear();
}
}
}
/// Plugin for navigating between focusable entities using keyboard input.
pub struct TabNavigationPlugin;
impl Plugin for TabNavigationPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, setup_tab_navigation);
app.add_observer(acquire_focus);
#[cfg(feature = "bevy_picking")]
app.add_observer(click_to_focus);
}
}
fn setup_tab_navigation(mut commands: Commands, window: Query<Entity, With<PrimaryWindow>>) {
for window in window.iter() {
commands.entity(window).observe(handle_tab_navigation);
}
}
#[cfg(feature = "bevy_picking")]
fn click_to_focus(
press: On<bevy_picking::events::Pointer<bevy_picking::events::Press>>,
mut focus_visible: ResMut<InputFocusVisible>,
windows: Query<Entity, With<PrimaryWindow>>,
mut commands: Commands,
) {
// Because `Pointer` is a bubbling event, we don't want to trigger an `AcquireFocus` event
// for every ancestor, but only for the original entity. Also, users may want to stop
// propagation on the pointer event at some point along the bubbling chain, so we need our
// own dedicated event whose propagation we can control.
if press.entity == press.original_event_target() {
// Clicking hides focus
if focus_visible.0 {
focus_visible.0 = false;
}
// Search for a focusable parent entity, defaulting to window if none.
if let Ok(window) = windows.single() {
commands.trigger(AcquireFocus {
focused_entity: press.entity,
window,
});
}
}
}
/// Observer function which handles tab navigation.
///
/// This observer responds to [`KeyCode::Tab`] events and Shift+Tab events,
/// cycling through focusable entities in the order determined by their tab index.
///
/// Any [`TabNavigationError`]s that occur during tab navigation are logged as warnings.
pub fn handle_tab_navigation(
mut event: On<FocusedInput<KeyboardInput>>,
nav: TabNavigation,
mut focus: ResMut<InputFocus>,
mut visible: ResMut<InputFocusVisible>,
keys: Res<ButtonInput<KeyCode>>,
) {
// Tab navigation.
let key_event = &event.input;
if key_event.key_code == KeyCode::Tab
&& key_event.state == ButtonState::Pressed
&& !key_event.repeat
{
let maybe_next = nav.navigate(
&focus,
if keys.pressed(KeyCode::ShiftLeft) || keys.pressed(KeyCode::ShiftRight) {
NavAction::Previous
} else {
NavAction::Next
},
);
match maybe_next {
Ok(next) => {
event.propagate(false);
focus.set(next);
visible.0 = true;
}
Err(e) => {
warn!("Tab navigation error: {e}");
// This failure mode is recoverable, but still indicates a problem.
if let TabNavigationError::NoTabGroupForCurrentFocus { new_focus, .. } = e {
event.propagate(false);
focus.set(new_focus);
visible.0 = true;
}
}
}
}
}
#[cfg(test)]
mod tests {
use bevy_ecs::system::SystemState;
use super::*;
#[test]
fn test_tab_navigation() {
let mut app = App::new();
let world = app.world_mut();
let tab_group_entity = world.spawn(TabGroup::new(0)).id();
let tab_entity_1 = world.spawn((TabIndex(0), ChildOf(tab_group_entity))).id();
let tab_entity_2 = world.spawn((TabIndex(1), ChildOf(tab_group_entity))).id();
let mut system_state: SystemState<TabNavigation> = SystemState::new(world);
let tab_navigation = system_state.get(world);
assert_eq!(tab_navigation.tabgroup_query.iter().count(), 1);
assert!(tab_navigation.tabindex_query.iter().count() >= 2);
let next_entity =
tab_navigation.navigate(&InputFocus::from_entity(tab_entity_1), NavAction::Next);
assert_eq!(next_entity, Ok(tab_entity_2));
let prev_entity =
tab_navigation.navigate(&InputFocus::from_entity(tab_entity_2), NavAction::Previous);
assert_eq!(prev_entity, Ok(tab_entity_1));
let first_entity = tab_navigation.navigate(&InputFocus::default(), NavAction::First);
assert_eq!(first_entity, Ok(tab_entity_1));
let last_entity = tab_navigation.navigate(&InputFocus::default(), NavAction::Last);
assert_eq!(last_entity, Ok(tab_entity_2));
}
#[test]
fn test_tab_navigation_between_groups_is_sorted_by_group() {
let mut app = App::new();
let world = app.world_mut();
let tab_group_1 = world.spawn(TabGroup::new(0)).id();
let tab_entity_1 = world.spawn((TabIndex(0), ChildOf(tab_group_1))).id();
let tab_entity_2 = world.spawn((TabIndex(1), ChildOf(tab_group_1))).id();
let tab_group_2 = world.spawn(TabGroup::new(1)).id();
let tab_entity_3 = world.spawn((TabIndex(0), ChildOf(tab_group_2))).id();
let tab_entity_4 = world.spawn((TabIndex(1), ChildOf(tab_group_2))).id();
let mut system_state: SystemState<TabNavigation> = SystemState::new(world);
let tab_navigation = system_state.get(world);
assert_eq!(tab_navigation.tabgroup_query.iter().count(), 2);
assert!(tab_navigation.tabindex_query.iter().count() >= 4);
let next_entity =
tab_navigation.navigate(&InputFocus::from_entity(tab_entity_1), NavAction::Next);
assert_eq!(next_entity, Ok(tab_entity_2));
let prev_entity =
tab_navigation.navigate(&InputFocus::from_entity(tab_entity_2), NavAction::Previous);
assert_eq!(prev_entity, Ok(tab_entity_1));
let first_entity = tab_navigation.navigate(&InputFocus::default(), NavAction::First);
assert_eq!(first_entity, Ok(tab_entity_1));
let last_entity = tab_navigation.navigate(&InputFocus::default(), NavAction::Last);
assert_eq!(last_entity, Ok(tab_entity_4));
let next_from_end_of_group_entity =
tab_navigation.navigate(&InputFocus::from_entity(tab_entity_2), NavAction::Next);
assert_eq!(next_from_end_of_group_entity, Ok(tab_entity_3));
let prev_entity_from_start_of_group =
tab_navigation.navigate(&InputFocus::from_entity(tab_entity_3), NavAction::Previous);
assert_eq!(prev_entity_from_start_of_group, Ok(tab_entity_2));
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_gilrs/src/lib.rs | crates/bevy_gilrs/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"
)]
//! Systems and type definitions for gamepad handling in Bevy.
//!
//! This crate is built on top of [GilRs](gilrs), a library
//! that handles abstracting over platform-specific gamepad APIs.
mod converter;
mod gilrs_system;
mod rumble;
#[cfg(not(target_arch = "wasm32"))]
use bevy_platform::cell::SyncCell;
#[cfg(target_arch = "wasm32")]
use core::cell::RefCell;
use bevy_app::{App, Plugin, PostUpdate, PreStartup, PreUpdate};
use bevy_ecs::entity::EntityHashMap;
use bevy_ecs::prelude::*;
use bevy_input::InputSystems;
use bevy_platform::collections::HashMap;
use gilrs::GilrsBuilder;
use gilrs_system::{gilrs_event_startup_system, gilrs_event_system};
use rumble::{play_gilrs_rumble, RunningRumbleEffects};
use tracing::error;
#[cfg(target_arch = "wasm32")]
thread_local! {
/// Temporary storage of gilrs data to replace usage of `!Send` resources. This will be replaced with proper
/// storage of `!Send` data after issue #17667 is complete.
///
/// Using a `thread_local!` here relies on the fact that wasm32 can only be single threaded. Previously, we used a
/// `NonSendMut` parameter, which told Bevy that the system was `!Send`, but now with the removal of `!Send`
/// resource/system parameter usage, there is no internal guarantee that the system will run in only one thread, so
/// we need to rely on the platform to make such a guarantee.
pub static GILRS: RefCell<Option<gilrs::Gilrs>> = const { RefCell::new(None) };
}
#[derive(Resource)]
pub(crate) struct Gilrs {
#[cfg(not(target_arch = "wasm32"))]
cell: SyncCell<gilrs::Gilrs>,
}
impl Gilrs {
#[inline]
pub fn with(&mut self, f: impl FnOnce(&mut gilrs::Gilrs)) {
#[cfg(target_arch = "wasm32")]
GILRS.with(|g| f(g.borrow_mut().as_mut().expect("GILRS was not initialized")));
#[cfg(not(target_arch = "wasm32"))]
f(self.cell.get());
}
}
/// A [`resource`](Resource) with the mapping of connected [`gilrs::GamepadId`] and their [`Entity`].
#[derive(Debug, Default, Resource)]
pub(crate) struct GilrsGamepads {
/// Mapping of [`Entity`] to [`gilrs::GamepadId`].
pub(crate) entity_to_id: EntityHashMap<gilrs::GamepadId>,
/// Mapping of [`gilrs::GamepadId`] to [`Entity`].
pub(crate) id_to_entity: HashMap<gilrs::GamepadId, Entity>,
}
impl GilrsGamepads {
/// Returns the [`Entity`] assigned to a connected [`gilrs::GamepadId`].
pub fn get_entity(&self, gamepad_id: gilrs::GamepadId) -> Option<Entity> {
self.id_to_entity.get(&gamepad_id).copied()
}
/// Returns the [`gilrs::GamepadId`] assigned to a gamepad [`Entity`].
pub fn get_gamepad_id(&self, entity: Entity) -> Option<gilrs::GamepadId> {
self.entity_to_id.get(&entity).copied()
}
}
/// Plugin that provides gamepad handling to an [`App`].
#[derive(Default)]
pub struct GilrsPlugin;
/// Updates the running gamepad rumble effects.
#[derive(Debug, PartialEq, Eq, Clone, Hash, SystemSet)]
pub struct RumbleSystems;
impl Plugin for GilrsPlugin {
fn build(&self, app: &mut App) {
match GilrsBuilder::new()
.with_default_filters(false)
.set_update_state(false)
.build()
{
Ok(gilrs) => {
let g = Gilrs {
#[cfg(not(target_arch = "wasm32"))]
cell: SyncCell::new(gilrs),
};
#[cfg(target_arch = "wasm32")]
GILRS.with(|g| {
g.replace(Some(gilrs));
});
app.insert_resource(g);
app.init_resource::<GilrsGamepads>();
app.init_resource::<RunningRumbleEffects>()
.add_systems(PreStartup, gilrs_event_startup_system)
.add_systems(PreUpdate, gilrs_event_system.before(InputSystems))
.add_systems(PostUpdate, play_gilrs_rumble.in_set(RumbleSystems));
}
Err(err) => error!("Failed to start Gilrs. {}", err),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
// Regression test for https://github.com/bevyengine/bevy/issues/17697
#[test]
fn world_is_truly_send() {
let mut app = App::new();
app.add_plugins(GilrsPlugin);
let world = core::mem::take(app.world_mut());
let handler = std::thread::spawn(move || {
drop(world);
});
handler.join().unwrap();
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_gilrs/src/gilrs_system.rs | crates/bevy_gilrs/src/gilrs_system.rs | use crate::{
converter::{convert_axis, convert_button},
Gilrs, GilrsGamepads,
};
use bevy_ecs::message::MessageWriter;
use bevy_ecs::prelude::Commands;
use bevy_ecs::system::ResMut;
use bevy_input::gamepad::{
GamepadConnection, GamepadConnectionEvent, RawGamepadAxisChangedEvent,
RawGamepadButtonChangedEvent, RawGamepadEvent,
};
use gilrs::{ev::filter::axis_dpad_to_button, EventType, Filter};
pub fn gilrs_event_startup_system(
mut commands: Commands,
mut gilrs: ResMut<Gilrs>,
mut gamepads: ResMut<GilrsGamepads>,
mut events: MessageWriter<GamepadConnectionEvent>,
) {
gilrs.with(|gilrs| {
for (id, gamepad) in gilrs.gamepads() {
// Create entity and add to mapping
let entity = commands.spawn_empty().id();
gamepads.id_to_entity.insert(id, entity);
gamepads.entity_to_id.insert(entity, id);
events.write(GamepadConnectionEvent {
gamepad: entity,
connection: GamepadConnection::Connected {
name: gamepad.name().to_string(),
vendor_id: gamepad.vendor_id(),
product_id: gamepad.product_id(),
},
});
}
});
}
pub fn gilrs_event_system(
mut commands: Commands,
mut gilrs: ResMut<Gilrs>,
mut gamepads: ResMut<GilrsGamepads>,
mut events: MessageWriter<RawGamepadEvent>,
mut connection_events: MessageWriter<GamepadConnectionEvent>,
mut button_events: MessageWriter<RawGamepadButtonChangedEvent>,
mut axis_event: MessageWriter<RawGamepadAxisChangedEvent>,
) {
gilrs.with(|gilrs| {
while let Some(gilrs_event) = gilrs.next_event().filter_ev(&axis_dpad_to_button, gilrs) {
gilrs.update(&gilrs_event);
match gilrs_event.event {
EventType::Connected => {
let pad = gilrs.gamepad(gilrs_event.id);
let entity = gamepads.get_entity(gilrs_event.id).unwrap_or_else(|| {
let entity = commands.spawn_empty().id();
gamepads.id_to_entity.insert(gilrs_event.id, entity);
gamepads.entity_to_id.insert(entity, gilrs_event.id);
entity
});
let event = GamepadConnectionEvent::new(
entity,
GamepadConnection::Connected {
name: pad.name().to_string(),
vendor_id: pad.vendor_id(),
product_id: pad.product_id(),
},
);
events.write(event.clone().into());
connection_events.write(event);
}
EventType::Disconnected => {
let gamepad = gamepads
.id_to_entity
.get(&gilrs_event.id)
.copied()
.expect("mapping should exist from connection");
let event =
GamepadConnectionEvent::new(gamepad, GamepadConnection::Disconnected);
events.write(event.clone().into());
connection_events.write(event);
}
EventType::ButtonChanged(gilrs_button, raw_value, _) => {
let Some(button) = convert_button(gilrs_button) else {
continue;
};
let gamepad = gamepads
.id_to_entity
.get(&gilrs_event.id)
.copied()
.expect("mapping should exist from connection");
events.write(
RawGamepadButtonChangedEvent::new(gamepad, button, raw_value).into(),
);
button_events.write(RawGamepadButtonChangedEvent::new(
gamepad, button, raw_value,
));
}
EventType::AxisChanged(gilrs_axis, raw_value, _) => {
let Some(axis) = convert_axis(gilrs_axis) else {
continue;
};
let gamepad = gamepads
.id_to_entity
.get(&gilrs_event.id)
.copied()
.expect("mapping should exist from connection");
events.write(RawGamepadAxisChangedEvent::new(gamepad, axis, raw_value).into());
axis_event.write(RawGamepadAxisChangedEvent::new(gamepad, axis, raw_value));
}
_ => (),
};
}
gilrs.inc();
});
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_gilrs/src/rumble.rs | crates/bevy_gilrs/src/rumble.rs | //! Handle user specified rumble request events.
use crate::{Gilrs, GilrsGamepads};
use bevy_ecs::prelude::{MessageReader, Res, ResMut, Resource};
use bevy_input::gamepad::{GamepadRumbleIntensity, GamepadRumbleRequest};
use bevy_platform::cell::SyncCell;
use bevy_platform::collections::HashMap;
use bevy_time::{Real, Time};
use core::time::Duration;
use gilrs::{
ff::{self, BaseEffect, BaseEffectType, Repeat, Replay},
GamepadId,
};
use thiserror::Error;
use tracing::{debug, warn};
/// A rumble effect that is currently in effect.
struct RunningRumble {
/// Duration from app startup when this effect will be finished
deadline: Duration,
/// A ref-counted handle to the specific force-feedback effect
///
/// Dropping it will cause the effect to stop
#[expect(
dead_code,
reason = "We don't need to read this field, as its purpose is to keep the rumble effect going until the field is dropped."
)]
effect: SyncCell<ff::Effect>,
}
#[derive(Error, Debug)]
enum RumbleError {
#[error("gamepad not found")]
GamepadNotFound,
#[error("gilrs error while rumbling gamepad: {0}")]
GilrsError(#[from] ff::Error),
}
/// Contains the gilrs rumble effects that are currently running for each gamepad
#[derive(Default, Resource)]
pub(crate) struct RunningRumbleEffects {
/// If multiple rumbles are running at the same time, their resulting rumble
/// will be the saturated sum of their strengths up until [`u16::MAX`]
rumbles: HashMap<GamepadId, Vec<RunningRumble>>,
}
/// gilrs uses magnitudes from 0 to [`u16::MAX`], while ours go from `0.0` to `1.0` ([`f32`])
fn to_gilrs_magnitude(ratio: f32) -> u16 {
(ratio * u16::MAX as f32) as u16
}
fn get_base_effects(
GamepadRumbleIntensity {
weak_motor,
strong_motor,
}: GamepadRumbleIntensity,
duration: Duration,
) -> Vec<BaseEffect> {
let mut effects = Vec::new();
if strong_motor > 0. {
effects.push(BaseEffect {
kind: BaseEffectType::Strong {
magnitude: to_gilrs_magnitude(strong_motor),
},
scheduling: Replay {
play_for: duration.into(),
..Default::default()
},
..Default::default()
});
}
if weak_motor > 0. {
effects.push(BaseEffect {
kind: BaseEffectType::Strong {
magnitude: to_gilrs_magnitude(weak_motor),
},
..Default::default()
});
}
effects
}
fn handle_rumble_request(
running_rumbles: &mut RunningRumbleEffects,
gilrs: &mut gilrs::Gilrs,
gamepads: &GilrsGamepads,
rumble: GamepadRumbleRequest,
current_time: Duration,
) -> Result<(), RumbleError> {
let gamepad = rumble.gamepad();
let (gamepad_id, _) = gilrs
.gamepads()
.find(|(pad_id, _)| *pad_id == gamepads.get_gamepad_id(gamepad).unwrap())
.ok_or(RumbleError::GamepadNotFound)?;
match rumble {
GamepadRumbleRequest::Stop { .. } => {
// `ff::Effect` uses RAII, dropping = deactivating
running_rumbles.rumbles.remove(&gamepad_id);
}
GamepadRumbleRequest::Add {
duration,
intensity,
..
} => {
let mut effect_builder = ff::EffectBuilder::new();
for effect in get_base_effects(intensity, duration) {
effect_builder.add_effect(effect);
effect_builder.repeat(Repeat::For(duration.into()));
}
let effect = effect_builder.gamepads(&[gamepad_id]).finish(gilrs)?;
effect.play()?;
let gamepad_rumbles = running_rumbles.rumbles.entry(gamepad_id).or_default();
let deadline = current_time + duration;
gamepad_rumbles.push(RunningRumble {
deadline,
effect: SyncCell::new(effect),
});
}
}
Ok(())
}
pub(crate) fn play_gilrs_rumble(
time: Res<Time<Real>>,
mut gilrs: ResMut<Gilrs>,
gamepads: Res<GilrsGamepads>,
mut requests: MessageReader<GamepadRumbleRequest>,
mut running_rumbles: ResMut<RunningRumbleEffects>,
) {
gilrs.with(|gilrs| {
let current_time = time.elapsed();
// Remove outdated rumble effects.
for rumbles in running_rumbles.rumbles.values_mut() {
// `ff::Effect` uses RAII, dropping = deactivating
rumbles.retain(|RunningRumble { deadline, .. }| *deadline >= current_time);
}
running_rumbles
.rumbles
.retain(|_gamepad, rumbles| !rumbles.is_empty());
// Add new effects.
for rumble in requests.read().cloned() {
let gamepad = rumble.gamepad();
match handle_rumble_request(&mut running_rumbles, gilrs, &gamepads, rumble, current_time) {
Ok(()) => {}
Err(RumbleError::GilrsError(err)) => {
if let ff::Error::FfNotSupported(_) = err {
debug!("Tried to rumble {gamepad:?}, but it doesn't support force feedback");
} else {
warn!(
"Tried to handle rumble request for {gamepad:?} but an error occurred: {err}"
);
}
}
Err(RumbleError::GamepadNotFound) => {
warn!("Tried to handle rumble request {gamepad:?} but it doesn't exist!");
}
};
}
});
}
#[cfg(test)]
mod tests {
use super::to_gilrs_magnitude;
#[test]
fn magnitude_conversion() {
assert_eq!(to_gilrs_magnitude(1.0), u16::MAX);
assert_eq!(to_gilrs_magnitude(0.0), 0);
// bevy magnitudes of 2.0 don't really make sense, but just make sure
// they convert to something sensible in gilrs anyway.
assert_eq!(to_gilrs_magnitude(2.0), u16::MAX);
// negative bevy magnitudes don't really make sense, but just make sure
// they convert to something sensible in gilrs anyway.
assert_eq!(to_gilrs_magnitude(-1.0), 0);
assert_eq!(to_gilrs_magnitude(-0.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_gilrs/src/converter.rs | crates/bevy_gilrs/src/converter.rs | use bevy_input::gamepad::{GamepadAxis, GamepadButton};
pub fn convert_button(button: gilrs::Button) -> Option<GamepadButton> {
match button {
gilrs::Button::South => Some(GamepadButton::South),
gilrs::Button::East => Some(GamepadButton::East),
gilrs::Button::North => Some(GamepadButton::North),
gilrs::Button::West => Some(GamepadButton::West),
gilrs::Button::C => Some(GamepadButton::C),
gilrs::Button::Z => Some(GamepadButton::Z),
gilrs::Button::LeftTrigger => Some(GamepadButton::LeftTrigger),
gilrs::Button::LeftTrigger2 => Some(GamepadButton::LeftTrigger2),
gilrs::Button::RightTrigger => Some(GamepadButton::RightTrigger),
gilrs::Button::RightTrigger2 => Some(GamepadButton::RightTrigger2),
gilrs::Button::Select => Some(GamepadButton::Select),
gilrs::Button::Start => Some(GamepadButton::Start),
gilrs::Button::Mode => Some(GamepadButton::Mode),
gilrs::Button::LeftThumb => Some(GamepadButton::LeftThumb),
gilrs::Button::RightThumb => Some(GamepadButton::RightThumb),
gilrs::Button::DPadUp => Some(GamepadButton::DPadUp),
gilrs::Button::DPadDown => Some(GamepadButton::DPadDown),
gilrs::Button::DPadLeft => Some(GamepadButton::DPadLeft),
gilrs::Button::DPadRight => Some(GamepadButton::DPadRight),
gilrs::Button::Unknown => None,
}
}
pub fn convert_axis(axis: gilrs::Axis) -> Option<GamepadAxis> {
match axis {
gilrs::Axis::LeftStickX => Some(GamepadAxis::LeftStickX),
gilrs::Axis::LeftStickY => Some(GamepadAxis::LeftStickY),
gilrs::Axis::LeftZ => Some(GamepadAxis::LeftZ),
gilrs::Axis::RightStickX => Some(GamepadAxis::RightStickX),
gilrs::Axis::RightStickY => Some(GamepadAxis::RightStickY),
gilrs::Axis::RightZ => Some(GamepadAxis::RightZ),
// The `axis_dpad_to_button` gilrs filter should filter out all DPadX and DPadY events. If
// it doesn't then we probably need an entry added to the following repo and an update to
// GilRs to use the updated database: https://github.com/gabomdq/SDL_GameControllerDB
gilrs::Axis::Unknown | gilrs::Axis::DPadX | gilrs::Axis::DPadY => None,
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_animation/macros/src/animation_event.rs | crates/bevy_animation/macros/src/animation_event.rs | use bevy_macro_utils::BevyManifest;
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};
pub fn derive_animation_event(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
let (bevy_ecs, bevy_animation) = BevyManifest::shared(|manifest| {
let bevy_ecs = manifest.get_path("bevy_ecs");
let bevy_animation = manifest.get_path("bevy_animation");
(bevy_ecs, bevy_animation)
});
let generics = ast.generics;
let (impl_generics, type_generics, where_clause) = generics.split_for_impl();
let struct_name = &ast.ident;
quote! {
impl #impl_generics #bevy_ecs::event::Event for #struct_name #type_generics #where_clause {
type Trigger<'a> = #bevy_animation::AnimationEventTrigger;
}
impl #impl_generics #bevy_animation::AnimationEvent for #struct_name #type_generics #where_clause {
}
}
.into()
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_animation/macros/src/lib.rs | crates/bevy_animation/macros/src/lib.rs | #![cfg_attr(docsrs, feature(doc_cfg))]
//! Macros for deriving animation behaviors.
extern crate proc_macro;
mod animation_event;
use proc_macro::TokenStream;
/// Implements the `AnimationEvent` trait for a type - see the trait
/// docs for an example usage.
#[proc_macro_derive(AnimationEvent)]
pub fn derive_animation_event(input: TokenStream) -> TokenStream {
animation_event::derive_animation_event(input)
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_animation/src/animation_event.rs | crates/bevy_animation/src/animation_event.rs | pub use bevy_animation_macros::AnimationEvent;
use bevy_ecs::{
entity::Entity,
event::{trigger_entity_internal, Event, Trigger},
observer::{CachedObservers, TriggerContext},
world::DeferredWorld,
};
/// An [`Event`] that an [`AnimationPlayer`](crate::AnimationPlayer) or an [`AnimationTargetId`](crate::AnimationTargetId) can trigger when playing an [`AnimationClip`](crate::AnimationClip).
///
/// - If you used [`AnimationClip::add_event`](crate::AnimationClip::add_event), this will be triggered by the [`AnimationPlayer`](crate::AnimationPlayer).
/// - If you used [`AnimationClip::add_event_to_target`](crate::AnimationClip::add_event_to_target), this will be triggered by the [`AnimationTargetId`](crate::AnimationTargetId).
///
/// This trait can be derived.
pub trait AnimationEvent: Clone + for<'a> Event<Trigger<'a> = AnimationEventTrigger> {}
/// The [`Trigger`] implementation for [`AnimationEvent`]. This passes in either the [`AnimationPlayer`](crate::AnimationPlayer) or the [`AnimationTargetId`](crate::AnimationTargetId)
/// context, and uses that to run any observers that target that entity. See [`AnimationEvent`] for when which entity is used.
#[derive(Debug)]
pub struct AnimationEventTrigger {
/// The [`AnimationPlayer`](crate::AnimationPlayer) or the [`AnimationTargetId`](crate::AnimationTargetId) where this [`AnimationEvent`] occurred.
/// See [`AnimationEvent`] for when which entity is used.
pub target: Entity,
}
#[expect(
unsafe_code,
reason = "We must implement this trait to define a custom Trigger, which is required to be unsafe due to safety considerations within bevy_ecs."
)]
// SAFETY:
// - `E`'s [`Event::Trigger`] is constrained to [`AnimationEventTrigger`]
// - The implementation abides by the other safety constraints defined in [`Trigger`]
unsafe impl<E: AnimationEvent + for<'a> Event<Trigger<'a> = AnimationEventTrigger>> Trigger<E>
for AnimationEventTrigger
{
unsafe fn trigger(
&mut self,
world: DeferredWorld,
observers: &CachedObservers,
trigger_context: &TriggerContext,
event: &mut E,
) {
let target = self.target;
// SAFETY:
// - `observers` come from `world` and match the event type `E`, enforced by the call to `trigger`
// - the passed in event pointer comes from `event`, which is an `Event`
// - `trigger` is a matching trigger type, as it comes from `self`, which is the Trigger for `E`
// - `trigger_context`'s event_key matches `E`, enforced by the call to `trigger`
// - this abides by the nuances defined in the `Trigger` safety docs
unsafe {
trigger_entity_internal(
world,
observers,
event.into(),
self.into(),
target,
trigger_context,
);
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_animation/src/lib.rs | crates/bevy_animation/src/lib.rs | #![cfg_attr(docsrs, feature(doc_cfg))]
#![warn(unsafe_code)]
#![doc(
html_logo_url = "https://bevy.org/assets/icon.png",
html_favicon_url = "https://bevy.org/assets/icon.png"
)]
//! Animation for the game engine Bevy
extern crate alloc;
pub mod animatable;
pub mod animation_curves;
pub mod gltf_curves;
pub mod graph;
#[cfg(feature = "bevy_mesh")]
mod morph;
pub mod transition;
mod animation_event;
mod util;
pub use animation_event::*;
use core::{
any::TypeId,
cell::RefCell,
fmt::Debug,
hash::{Hash, Hasher},
iter, slice,
};
use graph::AnimationNodeType;
use prelude::AnimationCurveEvaluator;
use crate::{
graph::{AnimationGraphHandle, ThreadedAnimationGraphs},
prelude::EvaluatorId,
};
use bevy_app::{AnimationSystems, App, Plugin, PostUpdate};
use bevy_asset::{Asset, AssetApp, AssetEventSystems, Assets};
use bevy_ecs::{prelude::*, world::EntityMutExcept};
use bevy_math::FloatOrd;
use bevy_platform::{collections::HashMap, hash::NoOpHash};
use bevy_reflect::{prelude::ReflectDefault, Reflect, TypePath};
use bevy_time::Time;
use bevy_transform::TransformSystems;
use bevy_utils::{PreHashMap, PreHashMapExt, TypeIdMap};
use serde::{Deserialize, Serialize};
use thread_local::ThreadLocal;
use tracing::{trace, warn};
use uuid::Uuid;
/// The animation prelude.
///
/// This includes the most common types in this crate, re-exported for your convenience.
pub mod prelude {
#[doc(hidden)]
pub use crate::{
animatable::*, animation_curves::*, graph::*, transition::*, AnimationClip,
AnimationPlayer, AnimationPlugin, VariableCurve,
};
}
use crate::{
animation_curves::AnimationCurve,
graph::{AnimationGraph, AnimationGraphAssetLoader, AnimationNodeIndex},
transition::{advance_transitions, expire_completed_transitions},
};
use alloc::sync::Arc;
/// The [UUID namespace] of animation targets (e.g. bones).
///
/// [UUID namespace]: https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based)
pub static ANIMATION_TARGET_NAMESPACE: Uuid = Uuid::from_u128(0x3179f519d9274ff2b5966fd077023911);
/// Contains an [animation curve] which is used to animate a property of an entity.
///
/// [animation curve]: AnimationCurve
#[derive(Debug, TypePath)]
pub struct VariableCurve(pub Box<dyn AnimationCurve>);
impl Clone for VariableCurve {
fn clone(&self) -> Self {
Self(AnimationCurve::clone_value(&*self.0))
}
}
impl VariableCurve {
/// Create a new [`VariableCurve`] from an [animation curve].
///
/// [animation curve]: AnimationCurve
pub fn new(animation_curve: impl AnimationCurve) -> Self {
Self(Box::new(animation_curve))
}
}
/// A list of [`VariableCurve`]s and the [`AnimationTargetId`]s to which they
/// apply.
///
/// Because animation clips refer to targets by UUID, they can target any
/// entity with that ID.
#[derive(Asset, Reflect, Clone, Debug, Default)]
#[reflect(Clone, Default)]
pub struct AnimationClip {
// This field is ignored by reflection because AnimationCurves can contain things that are not reflect-able
#[reflect(ignore, clone)]
curves: AnimationCurves,
events: AnimationEvents,
duration: f32,
}
#[derive(Reflect, Debug, Clone)]
#[reflect(Clone)]
struct TimedAnimationEvent {
time: f32,
event: AnimationEventData,
}
#[derive(Reflect, Debug, Clone)]
#[reflect(Clone)]
struct AnimationEventData {
#[reflect(ignore, clone)]
trigger: AnimationEventFn,
}
impl AnimationEventData {
fn trigger(&self, commands: &mut Commands, entity: Entity, time: f32, weight: f32) {
(self.trigger.0)(commands, entity, time, weight);
}
}
#[derive(Reflect, Clone)]
#[reflect(opaque)]
#[reflect(Clone, Default, Debug)]
struct AnimationEventFn(Arc<dyn Fn(&mut Commands, Entity, f32, f32) + Send + Sync>);
impl Default for AnimationEventFn {
fn default() -> Self {
Self(Arc::new(|_commands, _entity, _time, _weight| {}))
}
}
impl Debug for AnimationEventFn {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_tuple("AnimationEventFn").finish()
}
}
#[derive(Reflect, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
#[reflect(Clone)]
enum AnimationEventTarget {
Root,
Node(AnimationTargetId),
}
type AnimationEvents = HashMap<AnimationEventTarget, Vec<TimedAnimationEvent>>;
/// A mapping from [`AnimationTargetId`] (e.g. bone in a skinned mesh) to the
/// animation curves.
pub type AnimationCurves = HashMap<AnimationTargetId, Vec<VariableCurve>, NoOpHash>;
/// A component that identifies which parts of an [`AnimationClip`] asset can
/// be applied to an entity. Typically used alongside the
/// [`AnimatedBy`] component.
///
/// `AnimationTargetId` is implemented as a [UUID]. When importing an armature
/// or an animation clip, asset loaders typically use the full path name from
/// the armature to the bone to generate these UUIDs. The ID is unique to the
/// full path name and based only on the names. So, for example, any imported
/// armature with a bone at the root named `Hips` will assign the same
/// [`AnimationTargetId`] to its root bone. Likewise, any imported animation
/// clip that animates a root bone named `Hips` will reference the same
/// [`AnimationTargetId`]. Any animation is playable on any armature as long as
/// the bone names match, which allows for easy animation retargeting.
///
/// Note that asset loaders generally use the *full* path name to generate the
/// [`AnimationTargetId`]. Thus a bone named `Chest` directly connected to a
/// bone named `Hips` will have a different ID from a bone named `Chest` that's
/// connected to a bone named `Stomach`.
///
/// [UUID]: https://en.wikipedia.org/wiki/Universally_unique_identifier
#[derive(
Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Reflect, Debug, Serialize, Deserialize, Component,
)]
#[reflect(Component, Clone)]
pub struct AnimationTargetId(pub Uuid);
impl Hash for AnimationTargetId {
fn hash<H: Hasher>(&self, state: &mut H) {
let (hi, lo) = self.0.as_u64_pair();
state.write_u64(hi ^ lo);
}
}
/// A component that links an animated entity to an entity containing an
/// [`AnimationPlayer`]. Typically used alongside the [`AnimationTargetId`]
/// component - the linked `AnimationPlayer` plays [`AnimationClip`] assets, and
/// the `AnimationTargetId` identifies which curves in the `AnimationClip` will
/// affect the target entity.
///
/// By convention, asset loaders add [`AnimationTargetId`] components to the
/// descendants of an [`AnimationPlayer`], as well as to the [`AnimationPlayer`]
/// entity itself, but Bevy doesn't require this in any way. So, for example,
/// it's entirely possible for an [`AnimationPlayer`] to animate a target that
/// it isn't an ancestor of. If you add a new bone to or delete a bone from an
/// armature at runtime, you may want to update the [`AnimationTargetId`]
/// component as appropriate, as Bevy won't do this automatically.
///
/// Note that each entity can only be animated by one animation player at a
/// time. However, you can change [`AnimatedBy`] components at runtime and
/// link them to a different player.
#[derive(Clone, Copy, Component, Reflect, Debug)]
#[reflect(Component, Clone)]
pub struct AnimatedBy(#[entities] pub Entity);
impl AnimationClip {
#[inline]
/// [`VariableCurve`]s for each animation target. Indexed by the [`AnimationTargetId`].
pub fn curves(&self) -> &AnimationCurves {
&self.curves
}
#[inline]
/// Get mutable references of [`VariableCurve`]s for each animation target. Indexed by the [`AnimationTargetId`].
pub fn curves_mut(&mut self) -> &mut AnimationCurves {
&mut self.curves
}
/// Gets the curves for a single animation target.
///
/// Returns `None` if this clip doesn't animate the target.
#[inline]
pub fn curves_for_target(
&self,
target_id: AnimationTargetId,
) -> Option<&'_ Vec<VariableCurve>> {
self.curves.get(&target_id)
}
/// Gets mutable references of the curves for a single animation target.
///
/// Returns `None` if this clip doesn't animate the target.
#[inline]
pub fn curves_for_target_mut(
&mut self,
target_id: AnimationTargetId,
) -> Option<&'_ mut Vec<VariableCurve>> {
self.curves.get_mut(&target_id)
}
/// Duration of the clip, represented in seconds.
#[inline]
pub fn duration(&self) -> f32 {
self.duration
}
/// Set the duration of the clip in seconds.
#[inline]
pub fn set_duration(&mut self, duration_sec: f32) {
self.duration = duration_sec;
}
/// Adds an [`AnimationCurve`] that can target an entity with the given
/// [`AnimationTargetId`] component.
///
/// If the curve extends beyond the current duration of this clip, this
/// method lengthens this clip to include the entire time span that the
/// curve covers.
///
/// More specifically:
/// - This clip will be sampled on the interval `[0, duration]`.
/// - Each curve in the clip is sampled by first clamping the sample time to its [domain].
/// - Curves that extend forever never contribute to the duration.
///
/// For example, a curve with domain `[2, 5]` will extend the clip to cover `[0, 5]`
/// when added and will produce the same output on the entire interval `[0, 2]` because
/// these time values all get clamped to `2`.
///
/// By contrast, a curve with domain `[-10, ∞]` will never extend the clip duration when
/// added and will be sampled only on `[0, duration]`, ignoring all negative time values.
///
/// [domain]: AnimationCurve::domain
pub fn add_curve_to_target(
&mut self,
target_id: AnimationTargetId,
curve: impl AnimationCurve,
) {
// Update the duration of the animation by this curve duration if it's longer
let end = curve.domain().end();
if end.is_finite() {
self.duration = self.duration.max(end);
}
self.curves
.entry(target_id)
.or_default()
.push(VariableCurve::new(curve));
}
/// Like [`add_curve_to_target`], but adding a [`VariableCurve`] directly.
///
/// Under normal circumstances, that method is generally more convenient.
///
/// [`add_curve_to_target`]: AnimationClip::add_curve_to_target
pub fn add_variable_curve_to_target(
&mut self,
target_id: AnimationTargetId,
variable_curve: VariableCurve,
) {
let end = variable_curve.0.domain().end();
if end.is_finite() {
self.duration = self.duration.max(end);
}
self.curves
.entry(target_id)
.or_default()
.push(variable_curve);
}
/// Add an [`EntityEvent`] with no [`AnimationTargetId`].
///
/// The `event` will be cloned and triggered on the [`AnimationPlayer`] entity once the `time` (in seconds)
/// is reached in the animation.
///
/// See also [`add_event_to_target`](Self::add_event_to_target).
pub fn add_event(&mut self, time: f32, event: impl AnimationEvent) {
self.add_event_fn(
time,
move |commands: &mut Commands, target: Entity, _time: f32, _weight: f32| {
commands.trigger_with(event.clone(), AnimationEventTrigger { target });
},
);
}
/// Add an [`EntityEvent`] with an [`AnimationTargetId`].
///
/// The `event` will be cloned and triggered on the entity matching the target once the `time` (in seconds)
/// is reached in the animation.
///
/// Use [`add_event`](Self::add_event) instead if you don't have a specific target.
pub fn add_event_to_target(
&mut self,
target_id: AnimationTargetId,
time: f32,
event: impl AnimationEvent,
) {
self.add_event_fn_to_target(
target_id,
time,
move |commands: &mut Commands, target: Entity, _time: f32, _weight: f32| {
commands.trigger_with(event.clone(), AnimationEventTrigger { target });
},
);
}
/// Add an event function with no [`AnimationTargetId`] to this [`AnimationClip`].
///
/// The `func` will trigger on the [`AnimationPlayer`] entity once the `time` (in seconds)
/// is reached in the animation.
///
/// For a simpler [`EntityEvent`]-based alternative, see [`AnimationClip::add_event`].
/// See also [`add_event_to_target`](Self::add_event_to_target).
///
/// ```
/// # use bevy_animation::AnimationClip;
/// # let mut clip = AnimationClip::default();
/// clip.add_event_fn(1.0, |commands, entity, time, weight| {
/// println!("Animation event triggered {entity:#?} at time {time} with weight {weight}");
/// })
/// ```
pub fn add_event_fn(
&mut self,
time: f32,
func: impl Fn(&mut Commands, Entity, f32, f32) + Send + Sync + 'static,
) {
self.add_event_internal(AnimationEventTarget::Root, time, func);
}
/// Add an event function with an [`AnimationTargetId`].
///
/// The `func` will trigger on the entity matching the target once the `time` (in seconds)
/// is reached in the animation.
///
/// For a simpler [`EntityEvent`]-based alternative, see [`AnimationClip::add_event_to_target`].
/// Use [`add_event`](Self::add_event) instead if you don't have a specific target.
///
/// ```
/// # use bevy_animation::{AnimationClip, AnimationTargetId};
/// # let mut clip = AnimationClip::default();
/// clip.add_event_fn_to_target(AnimationTargetId::from_iter(["Arm", "Hand"]), 1.0, |commands, entity, time, weight| {
/// println!("Animation event triggered {entity:#?} at time {time} with weight {weight}");
/// })
/// ```
pub fn add_event_fn_to_target(
&mut self,
target_id: AnimationTargetId,
time: f32,
func: impl Fn(&mut Commands, Entity, f32, f32) + Send + Sync + 'static,
) {
self.add_event_internal(AnimationEventTarget::Node(target_id), time, func);
}
fn add_event_internal(
&mut self,
target: AnimationEventTarget,
time: f32,
trigger_fn: impl Fn(&mut Commands, Entity, f32, f32) + Send + Sync + 'static,
) {
self.duration = self.duration.max(time);
let triggers = self.events.entry(target).or_default();
match triggers.binary_search_by_key(&FloatOrd(time), |e| FloatOrd(e.time)) {
Ok(index) | Err(index) => triggers.insert(
index,
TimedAnimationEvent {
time,
event: AnimationEventData {
trigger: AnimationEventFn(Arc::new(trigger_fn)),
},
},
),
}
}
}
/// Repetition behavior of an animation.
#[derive(Reflect, Debug, PartialEq, Eq, Copy, Clone, Default)]
#[reflect(Clone, Default)]
pub enum RepeatAnimation {
/// The animation will finish after running once.
#[default]
Never,
/// The animation will finish after running "n" times.
Count(u32),
/// The animation will never finish.
Forever,
}
/// Why Bevy failed to evaluate an animation.
#[derive(Clone, Debug)]
pub enum AnimationEvaluationError {
/// The component to be animated isn't present on the animation target.
///
/// To fix this error, make sure the entity to be animated contains all
/// components that have animation curves.
ComponentNotPresent(TypeId),
/// The component to be animated was present, but the property on the
/// component wasn't present.
PropertyNotPresent(TypeId),
/// An internal error occurred in the implementation of
/// [`AnimationCurveEvaluator`].
///
/// You shouldn't ordinarily see this error unless you implemented
/// [`AnimationCurveEvaluator`] yourself. The contained [`TypeId`] is the ID
/// of the curve evaluator.
InconsistentEvaluatorImplementation(TypeId),
}
/// An animation that an [`AnimationPlayer`] is currently either playing or was
/// playing, but is presently paused.
///
/// A stopped animation is considered no longer active.
#[derive(Debug, Clone, Copy, Reflect)]
#[reflect(Clone, Default)]
pub struct ActiveAnimation {
/// The factor by which the weight from the [`AnimationGraph`] is multiplied.
weight: f32,
repeat: RepeatAnimation,
speed: f32,
/// Total time the animation has been played.
///
/// Note: Time does not increase when the animation is paused or after it has completed.
elapsed: f32,
/// The timestamp inside of the animation clip.
///
/// Note: This will always be in the range [0.0, animation clip duration]
seek_time: f32,
/// The `seek_time` of the previous tick, if any.
last_seek_time: Option<f32>,
/// Number of times the animation has completed.
/// If the animation is playing in reverse, this increments when the animation passes the start.
completions: u32,
/// `true` if the animation was completed at least once this tick.
just_completed: bool,
paused: bool,
}
impl Default for ActiveAnimation {
fn default() -> Self {
Self {
weight: 1.0,
repeat: RepeatAnimation::default(),
speed: 1.0,
elapsed: 0.0,
seek_time: 0.0,
last_seek_time: None,
completions: 0,
just_completed: false,
paused: false,
}
}
}
impl ActiveAnimation {
/// Check if the animation has finished, based on its repetition behavior and the number of times it has repeated.
///
/// Note: An animation with `RepeatAnimation::Forever` will never finish.
#[inline]
pub fn is_finished(&self) -> bool {
match self.repeat {
RepeatAnimation::Forever => false,
RepeatAnimation::Never => self.completions >= 1,
RepeatAnimation::Count(n) => self.completions >= n,
}
}
/// Update the animation given the delta time and the duration of the clip being played.
#[inline]
fn update(&mut self, delta: f32, clip_duration: f32) {
self.just_completed = false;
self.last_seek_time = Some(self.seek_time);
if self.is_finished() {
return;
}
self.elapsed += delta;
self.seek_time += delta * self.speed;
let over_time = self.speed > 0.0 && self.seek_time >= clip_duration;
let under_time = self.speed < 0.0 && self.seek_time < 0.0;
if over_time || under_time {
self.just_completed = true;
self.completions += 1;
if self.is_finished() {
return;
}
}
if self.seek_time >= clip_duration {
self.seek_time %= clip_duration;
}
// Note: assumes delta is never lower than -clip_duration
if self.seek_time < 0.0 {
self.seek_time += clip_duration;
}
}
/// Reset back to the initial state as if no time has elapsed.
pub fn replay(&mut self) {
self.just_completed = false;
self.completions = 0;
self.elapsed = 0.0;
self.last_seek_time = None;
self.seek_time = 0.0;
}
/// Returns the current weight of this animation.
pub fn weight(&self) -> f32 {
self.weight
}
/// Sets the weight of this animation.
pub fn set_weight(&mut self, weight: f32) -> &mut Self {
self.weight = weight;
self
}
/// Pause the animation.
pub fn pause(&mut self) -> &mut Self {
self.paused = true;
self
}
/// Unpause the animation.
pub fn resume(&mut self) -> &mut Self {
self.paused = false;
self
}
/// Returns true if this animation is currently paused.
///
/// Note that paused animations are still [`ActiveAnimation`]s.
#[inline]
pub fn is_paused(&self) -> bool {
self.paused
}
/// Sets the repeat mode for this playing animation.
pub fn set_repeat(&mut self, repeat: RepeatAnimation) -> &mut Self {
self.repeat = repeat;
self
}
/// Marks this animation as repeating forever.
pub fn repeat(&mut self) -> &mut Self {
self.set_repeat(RepeatAnimation::Forever)
}
/// Returns the repeat mode assigned to this active animation.
pub fn repeat_mode(&self) -> RepeatAnimation {
self.repeat
}
/// Returns the number of times this animation has completed.
pub fn completions(&self) -> u32 {
self.completions
}
/// Returns true if the animation is playing in reverse.
pub fn is_playback_reversed(&self) -> bool {
self.speed < 0.0
}
/// Returns the speed of the animation playback.
pub fn speed(&self) -> f32 {
self.speed
}
/// Sets the speed of the animation playback.
pub fn set_speed(&mut self, speed: f32) -> &mut Self {
self.speed = speed;
self
}
/// Returns the amount of time the animation has been playing.
pub fn elapsed(&self) -> f32 {
self.elapsed
}
/// Returns the seek time of the animation.
///
/// This is nonnegative and no more than the clip duration.
pub fn seek_time(&self) -> f32 {
self.seek_time
}
/// Seeks to a specific time in the animation.
///
/// This will not trigger events between the current time and `seek_time`.
/// Use [`seek_to`](Self::seek_to) if this is desired.
pub fn set_seek_time(&mut self, seek_time: f32) -> &mut Self {
self.last_seek_time = Some(seek_time);
self.seek_time = seek_time;
self
}
/// Seeks to a specific time in the animation.
///
/// Note that any events between the current time and `seek_time`
/// will be triggered on the next update.
/// Use [`set_seek_time`](Self::set_seek_time) if this is undesired.
pub fn seek_to(&mut self, seek_time: f32) -> &mut Self {
self.last_seek_time = Some(self.seek_time);
self.seek_time = seek_time;
self
}
/// Seeks to the beginning of the animation.
///
/// Note that any events between the current time and `0.0`
/// will be triggered on the next update.
/// Use [`set_seek_time`](Self::set_seek_time) if this is undesired.
pub fn rewind(&mut self) -> &mut Self {
self.last_seek_time = Some(self.seek_time);
self.seek_time = 0.0;
self
}
}
/// Animation controls.
///
/// Automatically added to any root animations of a scene when it is
/// spawned.
#[derive(Component, Default, Reflect)]
#[reflect(Component, Default, Clone)]
pub struct AnimationPlayer {
active_animations: HashMap<AnimationNodeIndex, ActiveAnimation>,
}
// This is needed since `#[derive(Clone)]` does not generate optimized `clone_from`.
impl Clone for AnimationPlayer {
fn clone(&self) -> Self {
Self {
active_animations: self.active_animations.clone(),
}
}
fn clone_from(&mut self, source: &Self) {
self.active_animations.clone_from(&source.active_animations);
}
}
/// Temporary data that the [`animate_targets`] system maintains.
#[derive(Default)]
pub struct AnimationEvaluationState {
/// Stores all [`AnimationCurveEvaluator`]s corresponding to properties that
/// we've seen so far.
///
/// This is a mapping from the id of an animation curve evaluator to
/// the animation curve evaluator itself.
///
/// For efficiency's sake, the [`AnimationCurveEvaluator`]s are cached from
/// frame to frame and animation target to animation target. Therefore,
/// there may be entries in this list corresponding to properties that the
/// current [`AnimationPlayer`] doesn't animate. To iterate only over the
/// properties that are currently being animated, consult the
/// [`Self::current_evaluators`] set.
evaluators: AnimationCurveEvaluators,
/// The set of [`AnimationCurveEvaluator`] types that the current
/// [`AnimationPlayer`] is animating.
///
/// This is built up as new curve evaluators are encountered during graph
/// traversal.
current_evaluators: CurrentEvaluators,
}
#[derive(Default)]
struct AnimationCurveEvaluators {
component_property_curve_evaluators:
PreHashMap<(TypeId, usize), Box<dyn AnimationCurveEvaluator>>,
type_id_curve_evaluators: TypeIdMap<Box<dyn AnimationCurveEvaluator>>,
}
impl AnimationCurveEvaluators {
#[inline]
pub(crate) fn get_mut(&mut self, id: EvaluatorId) -> Option<&mut dyn AnimationCurveEvaluator> {
match id {
EvaluatorId::ComponentField(component_property) => self
.component_property_curve_evaluators
.get_mut(component_property),
EvaluatorId::Type(type_id) => self.type_id_curve_evaluators.get_mut(&type_id),
}
.map(|e| &mut **e)
}
#[inline]
pub(crate) fn get_or_insert_with(
&mut self,
id: EvaluatorId,
func: impl FnOnce() -> Box<dyn AnimationCurveEvaluator>,
) -> &mut dyn AnimationCurveEvaluator {
match id {
EvaluatorId::ComponentField(component_property) => &mut **self
.component_property_curve_evaluators
.get_or_insert_with(component_property, func),
EvaluatorId::Type(type_id) => match self.type_id_curve_evaluators.entry(type_id) {
bevy_platform::collections::hash_map::Entry::Occupied(occupied_entry) => {
&mut **occupied_entry.into_mut()
}
bevy_platform::collections::hash_map::Entry::Vacant(vacant_entry) => {
&mut **vacant_entry.insert(func())
}
},
}
}
}
#[derive(Default)]
struct CurrentEvaluators {
component_properties: PreHashMap<(TypeId, usize), ()>,
type_ids: TypeIdMap<()>,
}
impl CurrentEvaluators {
pub(crate) fn keys(&self) -> impl Iterator<Item = EvaluatorId<'_>> {
self.component_properties
.keys()
.map(EvaluatorId::ComponentField)
.chain(self.type_ids.keys().copied().map(EvaluatorId::Type))
}
pub(crate) fn clear(
&mut self,
mut visit: impl FnMut(EvaluatorId) -> Result<(), AnimationEvaluationError>,
) -> Result<(), AnimationEvaluationError> {
for (key, _) in self.component_properties.drain() {
(visit)(EvaluatorId::ComponentField(&key))?;
}
for (key, _) in self.type_ids.drain() {
(visit)(EvaluatorId::Type(key))?;
}
Ok(())
}
#[inline]
pub(crate) fn insert(&mut self, id: EvaluatorId) {
match id {
EvaluatorId::ComponentField(component_property) => {
self.component_properties.insert(*component_property, ());
}
EvaluatorId::Type(type_id) => {
self.type_ids.insert(type_id, ());
}
}
}
}
impl AnimationPlayer {
/// Start playing an animation, restarting it if necessary.
pub fn start(&mut self, animation: AnimationNodeIndex) -> &mut ActiveAnimation {
let playing_animation = self.active_animations.entry(animation).or_default();
playing_animation.replay();
playing_animation
}
/// Start playing an animation, unless the requested animation is already playing.
pub fn play(&mut self, animation: AnimationNodeIndex) -> &mut ActiveAnimation {
self.active_animations.entry(animation).or_default()
}
/// Stops playing the given animation, removing it from the list of playing
/// animations.
pub fn stop(&mut self, animation: AnimationNodeIndex) -> &mut Self {
self.active_animations.remove(&animation);
self
}
/// Stops all currently-playing animations.
pub fn stop_all(&mut self) -> &mut Self {
self.active_animations.clear();
self
}
/// Iterates through all animations that this [`AnimationPlayer`] is
/// currently playing.
pub fn playing_animations(
&self,
) -> impl Iterator<Item = (&AnimationNodeIndex, &ActiveAnimation)> {
self.active_animations.iter()
}
/// Iterates through all animations that this [`AnimationPlayer`] is
/// currently playing, mutably.
pub fn playing_animations_mut(
&mut self,
) -> impl Iterator<Item = (&AnimationNodeIndex, &mut ActiveAnimation)> {
self.active_animations.iter_mut()
}
/// Returns true if the animation is currently playing or paused, or false
/// if the animation is stopped.
pub fn is_playing_animation(&self, animation: AnimationNodeIndex) -> bool {
self.active_animations.contains_key(&animation)
}
/// Check if all playing animations have finished, according to the repetition behavior.
pub fn all_finished(&self) -> bool {
self.active_animations
.values()
.all(ActiveAnimation::is_finished)
}
/// Check if all playing animations are paused.
#[doc(alias = "is_paused")]
pub fn all_paused(&self) -> bool {
self.active_animations
.values()
.all(ActiveAnimation::is_paused)
}
/// Pause all playing animations.
#[doc(alias = "pause")]
pub fn pause_all(&mut self) -> &mut Self {
for (_, playing_animation) in self.playing_animations_mut() {
playing_animation.pause();
}
self
}
/// Resume all active animations.
#[doc(alias = "resume")]
pub fn resume_all(&mut self) -> &mut Self {
for (_, playing_animation) in self.playing_animations_mut() {
playing_animation.resume();
}
self
}
/// Rewinds all active animations.
#[doc(alias = "rewind")]
pub fn rewind_all(&mut self) -> &mut Self {
for (_, playing_animation) in self.playing_animations_mut() {
playing_animation.rewind();
}
self
}
/// Multiplies the speed of all active animations by the given factor.
#[doc(alias = "set_speed")]
pub fn adjust_speeds(&mut self, factor: f32) -> &mut Self {
for (_, playing_animation) in self.playing_animations_mut() {
let new_speed = playing_animation.speed() * factor;
playing_animation.set_speed(new_speed);
}
self
}
/// Seeks all active animations forward or backward by the same amount.
///
/// To seek forward, pass a positive value; to seek negative, pass a
/// negative value. Values below 0.0 or beyond the end of the animation clip
/// are clamped appropriately.
#[doc(alias = "seek_to")]
pub fn seek_all_by(&mut self, amount: f32) -> &mut Self {
for (_, playing_animation) in self.playing_animations_mut() {
let new_time = playing_animation.seek_time();
playing_animation.seek_to(new_time + amount);
}
self
}
/// Returns the [`ActiveAnimation`] associated with the given animation
/// node if it's currently playing.
///
/// If the animation isn't currently active, returns `None`.
pub fn animation(&self, animation: AnimationNodeIndex) -> Option<&ActiveAnimation> {
self.active_animations.get(&animation)
}
/// Returns a mutable reference to the [`ActiveAnimation`] associated with
/// the given animation node if it's currently active.
///
/// If the animation isn't currently active, returns `None`.
pub fn animation_mut(&mut self, animation: AnimationNodeIndex) -> Option<&mut ActiveAnimation> {
self.active_animations.get_mut(&animation)
}
}
/// A system that triggers untargeted animation events for the currently-playing animations.
fn trigger_untargeted_animation_events(
mut commands: Commands,
clips: Res<Assets<AnimationClip>>,
graphs: Res<Assets<AnimationGraph>>,
players: Query<(Entity, &AnimationPlayer, &AnimationGraphHandle)>,
) {
for (entity, player, graph_id) in &players {
// The graph might not have loaded yet. Safely bail.
let Some(graph) = graphs.get(graph_id) else {
return;
};
for (index, active_animation) in player.active_animations.iter() {
if active_animation.paused {
continue;
}
let Some(clip) = graph
.get(*index)
.and_then(|node| match &node.node_type {
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_animation/src/gltf_curves.rs | crates/bevy_animation/src/gltf_curves.rs | //! Concrete curve structures used to load glTF curves into the animation system.
use bevy_math::{
curve::{cores::*, iterable::IterableCurve, *},
vec4, Quat, Vec4, VectorSpace,
};
use bevy_reflect::Reflect;
use either::Either;
use thiserror::Error;
/// A keyframe-defined curve that "interpolates" by stepping at `t = 1.0` to the next keyframe.
#[derive(Debug, Clone, Reflect)]
pub struct SteppedKeyframeCurve<T> {
core: UnevenCore<T>,
}
impl<T> Curve<T> for SteppedKeyframeCurve<T>
where
T: Clone,
{
#[inline]
fn domain(&self) -> Interval {
self.core.domain()
}
#[inline]
fn sample_clamped(&self, t: f32) -> T {
self.core
.sample_with(t, |x, y, t| if t >= 1.0 { y.clone() } else { x.clone() })
}
#[inline]
fn sample_unchecked(&self, t: f32) -> T {
self.sample_clamped(t)
}
}
impl<T> SteppedKeyframeCurve<T> {
/// Create a new [`SteppedKeyframeCurve`]. If the curve could not be constructed from the
/// given data, an error is returned.
#[inline]
pub fn new(timed_samples: impl IntoIterator<Item = (f32, T)>) -> Result<Self, UnevenCoreError> {
Ok(Self {
core: UnevenCore::new(timed_samples)?,
})
}
}
/// A keyframe-defined curve that uses cubic spline interpolation, backed by a contiguous buffer.
#[derive(Debug, Clone, Reflect)]
pub struct CubicKeyframeCurve<T> {
// Note: the sample width here should be 3.
core: ChunkedUnevenCore<T>,
}
impl<V> Curve<V> for CubicKeyframeCurve<V>
where
V: VectorSpace<Scalar = f32>,
{
#[inline]
fn domain(&self) -> Interval {
self.core.domain()
}
#[inline]
fn sample_clamped(&self, t: f32) -> V {
match self.core.sample_interp_timed(t) {
// In all the cases where only one frame matters, defer to the position within it.
InterpolationDatum::Exact((_, v))
| InterpolationDatum::LeftTail((_, v))
| InterpolationDatum::RightTail((_, v)) => v[1],
InterpolationDatum::Between((t0, u), (t1, v), s) => {
cubic_spline_interpolation(u[1], u[2], v[0], v[1], s, t1 - t0)
}
}
}
#[inline]
fn sample_unchecked(&self, t: f32) -> V {
self.sample_clamped(t)
}
}
impl<T> CubicKeyframeCurve<T> {
/// Create a new [`CubicKeyframeCurve`] from keyframe `times` and their associated `values`.
/// Because 3 values are needed to perform cubic interpolation, `values` must have triple the
/// length of `times` — each consecutive triple `a_k, v_k, b_k` associated to time `t_k`
/// consists of:
/// - The in-tangent `a_k` for the sample at time `t_k`
/// - The actual value `v_k` for the sample at time `t_k`
/// - The out-tangent `b_k` for the sample at time `t_k`
///
/// For example, for a curve built from two keyframes, the inputs would have the following form:
/// - `times`: `[t_0, t_1]`
/// - `values`: `[a_0, v_0, b_0, a_1, v_1, b_1]`
#[inline]
pub fn new(
times: impl IntoIterator<Item = f32>,
values: impl IntoIterator<Item = T>,
) -> Result<Self, ChunkedUnevenCoreError> {
Ok(Self {
core: ChunkedUnevenCore::new(times, values, 3)?,
})
}
}
// NOTE: We can probably delete `CubicRotationCurve` once we improve the `Reflect` implementations
// for the `Curve` API adaptors; this is basically a `CubicKeyframeCurve` composed with `map`.
/// A keyframe-defined curve that uses cubic spline interpolation, special-cased for quaternions
/// since it uses `Vec4` internally.
#[derive(Debug, Clone, Reflect)]
#[reflect(Clone)]
pub struct CubicRotationCurve {
// Note: The sample width here should be 3.
core: ChunkedUnevenCore<Vec4>,
}
impl Curve<Quat> for CubicRotationCurve {
#[inline]
fn domain(&self) -> Interval {
self.core.domain()
}
#[inline]
fn sample_clamped(&self, t: f32) -> Quat {
let vec = match self.core.sample_interp_timed(t) {
// In all the cases where only one frame matters, defer to the position within it.
InterpolationDatum::Exact((_, v))
| InterpolationDatum::LeftTail((_, v))
| InterpolationDatum::RightTail((_, v)) => v[1],
InterpolationDatum::Between((t0, u), (t1, v), s) => {
cubic_spline_interpolation(u[1], u[2], v[0], v[1], s, t1 - t0)
}
};
Quat::from_vec4(vec.normalize())
}
#[inline]
fn sample_unchecked(&self, t: f32) -> Quat {
self.sample_clamped(t)
}
}
impl CubicRotationCurve {
/// Create a new [`CubicRotationCurve`] from keyframe `times` and their associated `values`.
/// Because 3 values are needed to perform cubic interpolation, `values` must have triple the
/// length of `times` — each consecutive triple `a_k, v_k, b_k` associated to time `t_k`
/// consists of:
/// - The in-tangent `a_k` for the sample at time `t_k`
/// - The actual value `v_k` for the sample at time `t_k`
/// - The out-tangent `b_k` for the sample at time `t_k`
///
/// For example, for a curve built from two keyframes, the inputs would have the following form:
/// - `times`: `[t_0, t_1]`
/// - `values`: `[a_0, v_0, b_0, a_1, v_1, b_1]`
///
/// To sample quaternions from this curve, the resulting interpolated `Vec4` output is normalized
/// and interpreted as a quaternion.
pub fn new(
times: impl IntoIterator<Item = f32>,
values: impl IntoIterator<Item = Vec4>,
) -> Result<Self, ChunkedUnevenCoreError> {
Ok(Self {
core: ChunkedUnevenCore::new(times, values, 3)?,
})
}
}
/// A keyframe-defined curve that uses linear interpolation over many samples at once, backed
/// by a contiguous buffer.
#[derive(Debug, Clone, Reflect)]
pub struct WideLinearKeyframeCurve<T> {
// Here the sample width is the number of things to simultaneously interpolate.
core: ChunkedUnevenCore<T>,
}
impl<T> IterableCurve<T> for WideLinearKeyframeCurve<T>
where
T: VectorSpace<Scalar = f32>,
{
#[inline]
fn domain(&self) -> Interval {
self.core.domain()
}
#[inline]
fn sample_iter_clamped(&self, t: f32) -> impl Iterator<Item = T> {
match self.core.sample_interp(t) {
InterpolationDatum::Exact(v)
| InterpolationDatum::LeftTail(v)
| InterpolationDatum::RightTail(v) => Either::Left(v.iter().copied()),
InterpolationDatum::Between(u, v, s) => {
let interpolated = u.iter().zip(v.iter()).map(move |(x, y)| x.lerp(*y, s));
Either::Right(interpolated)
}
}
}
#[inline]
fn sample_iter_unchecked(&self, t: f32) -> impl Iterator<Item = T> {
self.sample_iter_clamped(t)
}
}
impl<T> WideLinearKeyframeCurve<T> {
/// Create a new [`WideLinearKeyframeCurve`]. An error will be returned if:
/// - `values` has length zero.
/// - `times` has less than `2` unique valid entries.
/// - The length of `values` is not divisible by that of `times` (once sorted, filtered,
/// and deduplicated).
#[inline]
pub fn new(
times: impl IntoIterator<Item = f32>,
values: impl IntoIterator<Item = T>,
) -> Result<Self, WideKeyframeCurveError> {
Ok(Self {
core: ChunkedUnevenCore::new_width_inferred(times, values)?,
})
}
}
/// A keyframe-defined curve that uses stepped "interpolation" over many samples at once, backed
/// by a contiguous buffer.
#[derive(Debug, Clone, Reflect)]
pub struct WideSteppedKeyframeCurve<T> {
// Here the sample width is the number of things to simultaneously interpolate.
core: ChunkedUnevenCore<T>,
}
impl<T> IterableCurve<T> for WideSteppedKeyframeCurve<T>
where
T: Clone,
{
#[inline]
fn domain(&self) -> Interval {
self.core.domain()
}
#[inline]
fn sample_iter_clamped(&self, t: f32) -> impl Iterator<Item = T> {
match self.core.sample_interp(t) {
InterpolationDatum::Exact(v)
| InterpolationDatum::LeftTail(v)
| InterpolationDatum::RightTail(v) => Either::Left(v.iter().cloned()),
InterpolationDatum::Between(u, v, s) => {
let interpolated =
u.iter()
.zip(v.iter())
.map(move |(x, y)| if s >= 1.0 { y.clone() } else { x.clone() });
Either::Right(interpolated)
}
}
}
#[inline]
fn sample_iter_unchecked(&self, t: f32) -> impl Iterator<Item = T> {
self.sample_iter_clamped(t)
}
}
impl<T> WideSteppedKeyframeCurve<T> {
/// Create a new [`WideSteppedKeyframeCurve`]. An error will be returned if:
/// - `values` has length zero.
/// - `times` has less than `2` unique valid entries.
/// - The length of `values` is not divisible by that of `times` (once sorted, filtered,
/// and deduplicated).
#[inline]
pub fn new(
times: impl IntoIterator<Item = f32>,
values: impl IntoIterator<Item = T>,
) -> Result<Self, WideKeyframeCurveError> {
Ok(Self {
core: ChunkedUnevenCore::new_width_inferred(times, values)?,
})
}
}
/// A keyframe-defined curve that uses cubic interpolation over many samples at once, backed by a
/// contiguous buffer.
#[derive(Debug, Clone, Reflect)]
pub struct WideCubicKeyframeCurve<T> {
core: ChunkedUnevenCore<T>,
}
impl<T> IterableCurve<T> for WideCubicKeyframeCurve<T>
where
T: VectorSpace<Scalar = f32>,
{
#[inline]
fn domain(&self) -> Interval {
self.core.domain()
}
fn sample_iter_clamped(&self, t: f32) -> impl Iterator<Item = T> {
match self.core.sample_interp_timed(t) {
InterpolationDatum::Exact((_, v))
| InterpolationDatum::LeftTail((_, v))
| InterpolationDatum::RightTail((_, v)) => {
// Pick out the part of this that actually represents the position (instead of tangents),
// which is the middle third.
let width = self.core.width();
Either::Left(v[width..(width * 2)].iter().copied())
}
InterpolationDatum::Between((t0, u), (t1, v), s) => Either::Right(
cubic_spline_interpolate_slices(self.core.width() / 3, u, v, s, t1 - t0),
),
}
}
#[inline]
fn sample_iter_unchecked(&self, t: f32) -> impl Iterator<Item = T> {
self.sample_iter_clamped(t)
}
}
/// An error indicating that a multisampling keyframe curve could not be constructed.
#[derive(Debug, Error)]
#[error("unable to construct a curve using this data")]
pub enum WideKeyframeCurveError {
/// The number of given values was not divisible by a multiple of the number of keyframes.
#[error("number of values ({values_given}) is not divisible by {divisor}")]
LengthMismatch {
/// The number of values given.
values_given: usize,
/// The number that `values_given` was supposed to be divisible by.
divisor: usize,
},
/// An error was returned by the internal core constructor.
#[error(transparent)]
CoreError(#[from] ChunkedUnevenCoreError),
}
impl<T> WideCubicKeyframeCurve<T> {
/// Create a new [`WideCubicKeyframeCurve`].
///
/// An error will be returned if:
/// - `values` has length zero.
/// - `times` has less than `2` unique valid entries.
/// - The length of `values` is not divisible by three times that of `times` (once sorted,
/// filtered, and deduplicated).
#[inline]
pub fn new(
times: impl IntoIterator<Item = f32>,
values: impl IntoIterator<Item = T>,
) -> Result<Self, WideKeyframeCurveError> {
let times: Vec<f32> = times.into_iter().collect();
let values: Vec<T> = values.into_iter().collect();
let divisor = times.len() * 3;
if !values.len().is_multiple_of(divisor) {
return Err(WideKeyframeCurveError::LengthMismatch {
values_given: values.len(),
divisor,
});
}
Ok(Self {
core: ChunkedUnevenCore::new_width_inferred(times, values)?,
})
}
}
//---------//
// HELPERS //
//---------//
/// Helper function for cubic spline interpolation.
fn cubic_spline_interpolation<T>(
value_start: T,
tangent_out_start: T,
tangent_in_end: T,
value_end: T,
lerp: f32,
step_duration: f32,
) -> T
where
T: VectorSpace<Scalar = f32>,
{
let coeffs = (vec4(2.0, 1.0, -2.0, 1.0) * lerp + vec4(-3.0, -2.0, 3.0, -1.0)) * lerp;
value_start * (coeffs.x * lerp + 1.0)
+ tangent_out_start * step_duration * lerp * (coeffs.y + 1.0)
+ value_end * lerp * coeffs.z
+ tangent_in_end * step_duration * lerp * coeffs.w
}
fn cubic_spline_interpolate_slices<'a, T: VectorSpace<Scalar = f32>>(
width: usize,
first: &'a [T],
second: &'a [T],
s: f32,
step_between: f32,
) -> impl Iterator<Item = T> + 'a {
(0..width).map(move |idx| {
cubic_spline_interpolation(
first[idx + width],
first[idx + (width * 2)],
second[idx + width],
second[idx],
s,
step_between,
)
})
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_animation/src/morph.rs | crates/bevy_animation/src/morph.rs | use crate::{
animatable::Animatable,
animation_curves::{AnimationCurve, AnimationCurveEvaluator, EvaluatorId},
graph::AnimationNodeIndex,
AnimationEntityMut, AnimationEvaluationError,
};
use bevy_math::curve::{iterable::IterableCurve, Interval};
use bevy_mesh::morph::MorphWeights;
use bevy_reflect::{FromReflect, Reflect, Reflectable};
use core::{any::TypeId, fmt::Debug};
/// This type allows an [`IterableCurve`] valued in `f32` to be used as an [`AnimationCurve`]
/// that animates [morph weights].
///
/// [morph weights]: MorphWeights
#[derive(Debug, Clone, Reflect, FromReflect)]
#[reflect(from_reflect = false)]
pub struct WeightsCurve<C>(pub C);
#[derive(Reflect)]
struct WeightsCurveEvaluator {
/// The values of the stack, in which each element is a list of morph target
/// weights.
///
/// The stack elements are concatenated and tightly packed together.
///
/// The number of elements in this stack will always be a multiple of
/// [`Self::morph_target_count`].
stack_morph_target_weights: Vec<f32>,
/// The blend weights and graph node indices for each element of the stack.
///
/// This should have as many elements as there are stack nodes. In other
/// words, `Self::stack_morph_target_weights.len() *
/// Self::morph_target_counts as usize ==
/// Self::stack_blend_weights_and_graph_nodes`.
stack_blend_weights_and_graph_nodes: Vec<(f32, AnimationNodeIndex)>,
/// The morph target weights in the blend register, if any.
///
/// This field should be ignored if [`Self::blend_register_blend_weight`] is
/// `None`. If non-empty, it will always have [`Self::morph_target_count`]
/// elements in it.
blend_register_morph_target_weights: Vec<f32>,
/// The weight in the blend register.
///
/// This will be `None` if the blend register is empty. In that case,
/// [`Self::blend_register_morph_target_weights`] will be empty.
blend_register_blend_weight: Option<f32>,
/// The number of morph targets that are to be animated.
morph_target_count: Option<u32>,
}
impl<C> AnimationCurve for WeightsCurve<C>
where
C: IterableCurve<f32> + Debug + Clone + Reflectable,
{
fn clone_value(&self) -> Box<dyn AnimationCurve> {
Box::new(self.clone())
}
fn domain(&self) -> Interval {
self.0.domain()
}
fn evaluator_id(&self) -> EvaluatorId<'_> {
EvaluatorId::Type(TypeId::of::<WeightsCurveEvaluator>())
}
fn create_evaluator(&self) -> Box<dyn AnimationCurveEvaluator> {
Box::new(WeightsCurveEvaluator {
stack_morph_target_weights: vec![],
stack_blend_weights_and_graph_nodes: vec![],
blend_register_morph_target_weights: vec![],
blend_register_blend_weight: None,
morph_target_count: None,
})
}
fn apply(
&self,
curve_evaluator: &mut dyn AnimationCurveEvaluator,
t: f32,
weight: f32,
graph_node: AnimationNodeIndex,
) -> Result<(), AnimationEvaluationError> {
let curve_evaluator = curve_evaluator
.downcast_mut::<WeightsCurveEvaluator>()
.unwrap();
let prev_morph_target_weights_len = curve_evaluator.stack_morph_target_weights.len();
curve_evaluator
.stack_morph_target_weights
.extend(self.0.sample_iter_clamped(t));
curve_evaluator.morph_target_count = Some(
(curve_evaluator.stack_morph_target_weights.len() - prev_morph_target_weights_len)
as u32,
);
curve_evaluator
.stack_blend_weights_and_graph_nodes
.push((weight, graph_node));
Ok(())
}
}
impl WeightsCurveEvaluator {
fn combine(
&mut self,
graph_node: AnimationNodeIndex,
additive: bool,
) -> Result<(), AnimationEvaluationError> {
let Some(&(_, top_graph_node)) = self.stack_blend_weights_and_graph_nodes.last() else {
return Ok(());
};
if top_graph_node != graph_node {
return Ok(());
}
let (weight_to_blend, _) = self.stack_blend_weights_and_graph_nodes.pop().unwrap();
let stack_iter = self.stack_morph_target_weights.drain(
(self.stack_morph_target_weights.len() - self.morph_target_count.unwrap() as usize)..,
);
match self.blend_register_blend_weight {
None => {
self.blend_register_blend_weight = Some(weight_to_blend);
self.blend_register_morph_target_weights.clear();
// In the additive case, the values pushed onto the blend register need
// to be scaled by the weight.
if additive {
self.blend_register_morph_target_weights
.extend(stack_iter.map(|m| m * weight_to_blend));
} else {
self.blend_register_morph_target_weights.extend(stack_iter);
}
}
Some(ref mut current_weight) => {
*current_weight += weight_to_blend;
for (dest, src) in self
.blend_register_morph_target_weights
.iter_mut()
.zip(stack_iter)
{
if additive {
*dest += src * weight_to_blend;
} else {
*dest = f32::interpolate(dest, &src, weight_to_blend / *current_weight);
}
}
}
}
Ok(())
}
}
impl AnimationCurveEvaluator for WeightsCurveEvaluator {
fn blend(&mut self, graph_node: AnimationNodeIndex) -> Result<(), AnimationEvaluationError> {
self.combine(graph_node, /*additive=*/ false)
}
fn add(&mut self, graph_node: AnimationNodeIndex) -> Result<(), AnimationEvaluationError> {
self.combine(graph_node, /*additive=*/ true)
}
fn push_blend_register(
&mut self,
weight: f32,
graph_node: AnimationNodeIndex,
) -> Result<(), AnimationEvaluationError> {
if self.blend_register_blend_weight.take().is_some() {
self.stack_morph_target_weights
.append(&mut self.blend_register_morph_target_weights);
self.stack_blend_weights_and_graph_nodes
.push((weight, graph_node));
}
Ok(())
}
fn commit(&mut self, mut entity: AnimationEntityMut) -> Result<(), AnimationEvaluationError> {
if self.stack_morph_target_weights.is_empty() {
return Ok(());
}
// Compute the index of the first morph target in the last element of
// the stack.
let index_of_first_morph_target =
self.stack_morph_target_weights.len() - self.morph_target_count.unwrap() as usize;
for (dest, src) in entity
.get_mut::<MorphWeights>()
.ok_or_else(|| {
AnimationEvaluationError::ComponentNotPresent(TypeId::of::<MorphWeights>())
})?
.weights_mut()
.iter_mut()
.zip(self.stack_morph_target_weights[index_of_first_morph_target..].iter())
{
*dest = *src;
}
self.stack_morph_target_weights.clear();
self.stack_blend_weights_and_graph_nodes.clear();
Ok(())
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_animation/src/animation_curves.rs | crates/bevy_animation/src/animation_curves.rs | //! The [`AnimationCurve`] trait and adaptors that allow curves to implement it.
//!
//! # Overview
//!
//! The flow of curves into the animation system generally begins with something that
//! implements the [`Curve`] trait. Let's imagine, for example, that we have some
//! `Curve<Vec3>` that we want to use to animate something. That could be defined in
//! a number of different ways, but let's imagine that we've defined it [using a function]:
//!
//! # use bevy_math::curve::{Curve, Interval, FunctionCurve};
//! # use bevy_math::vec3;
//! let wobble_curve = FunctionCurve::new(
//! Interval::UNIT,
//! |t| { vec3(t.cos(), 0.0, 0.0) },
//! );
//!
//! Okay, so we have a curve, but the animation system also needs to know, in some way,
//! how the values from this curve should actually be used. That is, it needs to know what
//! to animate! That's what [`AnimationCurve`] is for. In particular, what we need to do
//! is take our curve and turn it into an `AnimationCurve` which will be usable by the
//! animation system.
//!
//! For instance, let's imagine that we want to use the `Vec3` output
//! from our curve to animate the [translation component of a `Transform`]. For this, there is
//! the adaptor [`AnimatableCurve`], which wraps any [`Curve`] and [`AnimatableProperty`] and turns it into an
//! [`AnimationCurve`] that will use the given curve to animate the entity's property:
//!
//! # use bevy_math::curve::{Curve, Interval, FunctionCurve};
//! # use bevy_math::vec3;
//! # use bevy_transform::components::Transform;
//! # use bevy_animation::{animated_field, animation_curves::*};
//! # let wobble_curve = FunctionCurve::new(
//! # Interval::UNIT,
//! # |t| vec3(t.cos(), 0.0, 0.0)
//! # );
//! let wobble_animation = AnimatableCurve::new(animated_field!(Transform::translation), wobble_curve);
//!
//! And finally, this [`AnimationCurve`] needs to be added to an [`AnimationClip`] in order to
//! actually animate something. This is what that looks like:
//!
//! # use bevy_math::curve::{Curve, Interval, FunctionCurve};
//! # use bevy_animation::{AnimationClip, AnimationTargetId, animated_field, animation_curves::*};
//! # use bevy_transform::components::Transform;
//! # use bevy_ecs::name::Name;
//! # use bevy_math::vec3;
//! # let wobble_curve = FunctionCurve::new(
//! # Interval::UNIT,
//! # |t| { vec3(t.cos(), 0.0, 0.0) },
//! # );
//! # let wobble_animation = AnimatableCurve::new(animated_field!(Transform::translation), wobble_curve);
//! # let animation_target_id = AnimationTargetId::from(&Name::new("Test"));
//! let mut animation_clip = AnimationClip::default();
//! animation_clip.add_curve_to_target(
//! animation_target_id,
//! wobble_animation,
//! );
//!
//! # Making animation curves
//!
//! The overview showed one example, but in general there are a few different ways of going from
//! a [`Curve`], which produces time-related data of some kind, to an [`AnimationCurve`], which
//! knows how to apply that data to an entity.
//!
//! ## Animated Fields
//!
//! The [`animated_field`] macro (which returns an [`AnimatedField`]), in combination with [`AnimatableCurve`]
//! is the easiest way to make an animation curve (see the example above).
//!
//! This will select a field on a component and pass it to a [`Curve`] with a type that matches the field.
//!
//! ## Animatable Properties
//!
//! Animation of arbitrary aspects of entities can be accomplished using [`AnimatableProperty`] in
//! conjunction with [`AnimatableCurve`]. See the documentation [there] for details.
//!
//! ## Custom [`AnimationCurve`] and [`AnimationCurveEvaluator`]
//!
//! This is the lowest-level option with the most control, but it is also the most complicated.
//!
//! [using a function]: bevy_math::curve::FunctionCurve
//! [translation component of a `Transform`]: bevy_transform::prelude::Transform::translation
//! [`AnimationClip`]: crate::AnimationClip
//! [there]: AnimatableProperty
//! [`animated_field`]: crate::animated_field
use core::{
any::TypeId,
fmt::{self, Debug, Formatter},
marker::PhantomData,
};
#[cfg(feature = "bevy_mesh")]
pub use crate::morph::*;
use crate::{
graph::AnimationNodeIndex,
prelude::{Animatable, BlendInput},
AnimationEntityMut, AnimationEvaluationError,
};
use bevy_ecs::component::{Component, Mutable};
use bevy_math::curve::{
cores::{UnevenCore, UnevenCoreError},
Curve, Interval,
};
use bevy_platform::hash::Hashed;
use bevy_reflect::{FromReflect, Reflect, Reflectable, TypeInfo, Typed};
use downcast_rs::{impl_downcast, Downcast};
/// A trait for exposing a value in an entity so that it can be animated.
///
/// `AnimatableProperty` allows any value contained in an entity to be animated
/// as long as it can be obtained by mutable reference. This makes it more
/// flexible than [`animated_field`].
///
/// [`animated_field`]: crate::animated_field
///
/// Here, `AnimatableProperty` is used to animate a value inside an `Option`,
/// returning an error if the option is `None`.
///
/// # use bevy_animation::{prelude::AnimatableProperty, AnimationEntityMut, AnimationEvaluationError, animation_curves::EvaluatorId};
/// # use bevy_ecs::component::Component;
/// # use std::any::TypeId;
/// #[derive(Component)]
/// struct ExampleComponent {
/// power_level: Option<f32>
/// }
///
/// #[derive(Clone)]
/// struct PowerLevelProperty;
///
/// impl AnimatableProperty for PowerLevelProperty {
/// type Property = f32;
/// fn get_mut<'a>(
/// &self,
/// entity: &'a mut AnimationEntityMut
/// ) -> Result<&'a mut Self::Property, AnimationEvaluationError> {
/// let component = entity
/// .get_mut::<ExampleComponent>()
/// .ok_or(AnimationEvaluationError::ComponentNotPresent(
/// TypeId::of::<ExampleComponent>()
/// ))?
/// .into_inner();
/// component.power_level.as_mut().ok_or(AnimationEvaluationError::PropertyNotPresent(
/// TypeId::of::<Option<f32>>()
/// ))
/// }
///
/// fn evaluator_id(&self) -> EvaluatorId {
/// EvaluatorId::Type(TypeId::of::<Self>())
/// }
/// }
///
///
/// You can then create an [`AnimatableCurve`] to animate this property like so:
///
/// # use bevy_animation::{VariableCurve, AnimationEntityMut, AnimationEvaluationError, animation_curves::EvaluatorId};
/// # use bevy_animation::prelude::{AnimatableProperty, AnimatableKeyframeCurve, AnimatableCurve};
/// # use bevy_ecs::{name::Name, component::Component};
/// # use std::any::TypeId;
/// # #[derive(Component)]
/// # struct ExampleComponent { power_level: Option<f32> }
/// # #[derive(Clone)]
/// # struct PowerLevelProperty;
/// # impl AnimatableProperty for PowerLevelProperty {
/// # type Property = f32;
/// # fn get_mut<'a>(
/// # &self,
/// # entity: &'a mut AnimationEntityMut
/// # ) -> Result<&'a mut Self::Property, AnimationEvaluationError> {
/// # let component = entity
/// # .get_mut::<ExampleComponent>()
/// # .ok_or(AnimationEvaluationError::ComponentNotPresent(
/// # TypeId::of::<ExampleComponent>()
/// # ))?
/// # .into_inner();
/// # component.power_level.as_mut().ok_or(AnimationEvaluationError::PropertyNotPresent(
/// # TypeId::of::<Option<f32>>()
/// # ))
/// # }
/// # fn evaluator_id(&self) -> EvaluatorId {
/// # EvaluatorId::Type(TypeId::of::<Self>())
/// # }
/// # }
/// AnimatableCurve::new(
/// PowerLevelProperty,
/// AnimatableKeyframeCurve::new([
/// (0.0, 0.0),
/// (1.0, 9001.0),
/// ]).expect("Failed to create power level curve")
/// );
pub trait AnimatableProperty: Send + Sync + 'static {
/// The animated property type.
type Property: Animatable;
/// Retrieves the property from the given `entity`.
fn get_mut<'a>(
&self,
entity: &'a mut AnimationEntityMut,
) -> Result<&'a mut Self::Property, AnimationEvaluationError>;
/// The [`EvaluatorId`] used to look up the [`AnimationCurveEvaluator`] for this [`AnimatableProperty`].
/// For a given animated property, this ID should always be the same to allow things like animation blending to occur.
fn evaluator_id(&self) -> EvaluatorId<'_>;
}
/// A [`Component`] field that can be animated, defined by a function that reads the component and returns
/// the accessed field / property.
///
/// The best way to create an instance of this type is via the [`animated_field`] macro.
///
/// `C` is the component being animated, `A` is the type of the [`Animatable`] field on the component, and `F` is an accessor
/// function that accepts a reference to `C` and retrieves the field `A`.
///
/// [`animated_field`]: crate::animated_field
#[derive(Clone)]
pub struct AnimatedField<C, A, F: Fn(&mut C) -> &mut A> {
func: F,
/// A pre-hashed (component-type-id, reflected-field-index) pair, uniquely identifying a component field
evaluator_id: Hashed<(TypeId, usize)>,
marker: PhantomData<(C, A)>,
}
impl<C, A, F> AnimatableProperty for AnimatedField<C, A, F>
where
C: Component<Mutability = Mutable>,
A: Animatable + Clone + Sync + Debug,
F: Fn(&mut C) -> &mut A + Send + Sync + 'static,
{
type Property = A;
fn get_mut<'a>(
&self,
entity: &'a mut AnimationEntityMut,
) -> Result<&'a mut A, AnimationEvaluationError> {
let c = entity
.get_mut::<C>()
.ok_or_else(|| AnimationEvaluationError::ComponentNotPresent(TypeId::of::<C>()))?;
Ok((self.func)(c.into_inner()))
}
fn evaluator_id(&self) -> EvaluatorId<'_> {
EvaluatorId::ComponentField(&self.evaluator_id)
}
}
impl<C: Typed, P, F: Fn(&mut C) -> &mut P + 'static> AnimatedField<C, P, F> {
/// Creates a new instance of [`AnimatedField`]. This operates under the assumption that
/// `C` is a reflect-able struct, and that `field_name` is a valid field on that struct.
///
/// # Panics
/// If the type of `C` is not a struct or if the `field_name` does not exist.
pub fn new_unchecked(field_name: &str, func: F) -> Self {
let field_index;
if let TypeInfo::Struct(struct_info) = C::type_info() {
field_index = struct_info
.index_of(field_name)
.expect("Field name should exist");
} else if let TypeInfo::TupleStruct(struct_info) = C::type_info() {
field_index = field_name
.parse()
.expect("Field name should be a valid tuple index");
if field_index >= struct_info.field_len() {
panic!("Field name should be a valid tuple index");
}
} else {
panic!("Only structs are supported in `AnimatedField::new_unchecked`")
}
Self {
func,
evaluator_id: Hashed::new((TypeId::of::<C>(), field_index)),
marker: PhantomData,
}
}
}
/// This trait collects the additional requirements on top of [`Curve<T>`] needed for a
/// curve to be used as an [`AnimationCurve`].
pub trait AnimationCompatibleCurve<T>: Curve<T> + Debug + Clone + Reflectable {}
impl<T, C> AnimationCompatibleCurve<T> for C where C: Curve<T> + Debug + Clone + Reflectable {}
/// This type allows the conversion of a [curve] valued in the [property type] of an
/// [`AnimatableProperty`] into an [`AnimationCurve`] which animates that property.
///
/// [curve]: Curve
/// [property type]: AnimatableProperty::Property
#[derive(Reflect, FromReflect)]
#[reflect(from_reflect = false)]
pub struct AnimatableCurve<P, C> {
/// The property selector, which defines what component to access and how to access
/// a property on that component.
pub property: P,
/// The inner [curve] whose values are used to animate the property.
///
/// [curve]: Curve
pub curve: C,
}
/// An [`AnimatableCurveEvaluator`] for [`AnimatableProperty`] instances.
///
/// You shouldn't ordinarily need to instantiate one of these manually. Bevy
/// will automatically do so when you use an [`AnimatableCurve`] instance.
#[derive(Reflect)]
pub struct AnimatableCurveEvaluator<A: Animatable> {
evaluator: BasicAnimationCurveEvaluator<A>,
property: Box<dyn AnimatableProperty<Property = A>>,
}
impl<P, C> AnimatableCurve<P, C>
where
P: AnimatableProperty,
C: AnimationCompatibleCurve<P::Property>,
{
/// Create an [`AnimatableCurve`] (and thus an [`AnimationCurve`]) from a curve
/// valued in an [animatable property].
///
/// [animatable property]: AnimatableProperty::Property
pub fn new(property: P, curve: C) -> Self {
Self { property, curve }
}
}
impl<P, C> Clone for AnimatableCurve<P, C>
where
C: Clone,
P: Clone,
{
fn clone(&self) -> Self {
Self {
curve: self.curve.clone(),
property: self.property.clone(),
}
}
}
impl<P, C> Debug for AnimatableCurve<P, C>
where
C: Debug,
{
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("AnimatableCurve")
.field("curve", &self.curve)
.finish()
}
}
impl<P: Send + Sync + 'static, C> AnimationCurve for AnimatableCurve<P, C>
where
P: AnimatableProperty + Clone,
C: AnimationCompatibleCurve<P::Property> + Clone,
{
fn clone_value(&self) -> Box<dyn AnimationCurve> {
Box::new(self.clone())
}
fn domain(&self) -> Interval {
self.curve.domain()
}
fn evaluator_id(&self) -> EvaluatorId<'_> {
self.property.evaluator_id()
}
fn create_evaluator(&self) -> Box<dyn AnimationCurveEvaluator> {
Box::new(AnimatableCurveEvaluator::<P::Property> {
evaluator: BasicAnimationCurveEvaluator::default(),
property: Box::new(self.property.clone()),
})
}
fn apply(
&self,
curve_evaluator: &mut dyn AnimationCurveEvaluator,
t: f32,
weight: f32,
graph_node: AnimationNodeIndex,
) -> Result<(), AnimationEvaluationError> {
let curve_evaluator = curve_evaluator
.downcast_mut::<AnimatableCurveEvaluator<P::Property>>()
.unwrap();
let value = self.curve.sample_clamped(t);
curve_evaluator
.evaluator
.stack
.push(BasicAnimationCurveEvaluatorStackElement {
value,
weight,
graph_node,
});
Ok(())
}
}
impl<A: Animatable> AnimationCurveEvaluator for AnimatableCurveEvaluator<A> {
fn blend(&mut self, graph_node: AnimationNodeIndex) -> Result<(), AnimationEvaluationError> {
self.evaluator.combine(graph_node, /*additive=*/ false)
}
fn add(&mut self, graph_node: AnimationNodeIndex) -> Result<(), AnimationEvaluationError> {
self.evaluator.combine(graph_node, /*additive=*/ true)
}
fn push_blend_register(
&mut self,
weight: f32,
graph_node: AnimationNodeIndex,
) -> Result<(), AnimationEvaluationError> {
self.evaluator.push_blend_register(weight, graph_node)
}
fn commit(&mut self, mut entity: AnimationEntityMut) -> Result<(), AnimationEvaluationError> {
let property = self.property.get_mut(&mut entity)?;
*property = self
.evaluator
.stack
.pop()
.ok_or_else(inconsistent::<AnimatableCurveEvaluator<A>>)?
.value;
self.evaluator.stack.clear();
Ok(())
}
}
#[derive(Reflect)]
struct BasicAnimationCurveEvaluator<A>
where
A: Animatable,
{
stack: Vec<BasicAnimationCurveEvaluatorStackElement<A>>,
blend_register: Option<(A, f32)>,
}
#[derive(Reflect)]
struct BasicAnimationCurveEvaluatorStackElement<A>
where
A: Animatable,
{
value: A,
weight: f32,
graph_node: AnimationNodeIndex,
}
impl<A> Default for BasicAnimationCurveEvaluator<A>
where
A: Animatable,
{
fn default() -> Self {
BasicAnimationCurveEvaluator {
stack: vec![],
blend_register: None,
}
}
}
impl<A> BasicAnimationCurveEvaluator<A>
where
A: Animatable,
{
fn combine(
&mut self,
graph_node: AnimationNodeIndex,
additive: bool,
) -> Result<(), AnimationEvaluationError> {
let Some(top) = self.stack.last() else {
return Ok(());
};
if top.graph_node != graph_node {
return Ok(());
}
let BasicAnimationCurveEvaluatorStackElement {
value: value_to_blend,
weight: weight_to_blend,
graph_node: _,
} = self.stack.pop().unwrap();
match self.blend_register.take() {
None => {
self.initialize_blend_register(value_to_blend, weight_to_blend, additive);
}
Some((mut current_value, mut current_weight)) => {
current_weight += weight_to_blend;
if additive {
current_value = A::blend(
[
BlendInput {
weight: 1.0,
value: current_value,
additive: true,
},
BlendInput {
weight: weight_to_blend,
value: value_to_blend,
additive: true,
},
]
.into_iter(),
);
} else {
current_value = A::interpolate(
¤t_value,
&value_to_blend,
weight_to_blend / current_weight,
);
}
self.blend_register = Some((current_value, current_weight));
}
}
Ok(())
}
fn initialize_blend_register(&mut self, value: A, weight: f32, additive: bool) {
if additive {
let scaled_value = A::blend(
[BlendInput {
weight,
value,
additive: true,
}]
.into_iter(),
);
self.blend_register = Some((scaled_value, weight));
} else {
self.blend_register = Some((value, weight));
}
}
fn push_blend_register(
&mut self,
weight: f32,
graph_node: AnimationNodeIndex,
) -> Result<(), AnimationEvaluationError> {
if let Some((value, _)) = self.blend_register.take() {
self.stack.push(BasicAnimationCurveEvaluatorStackElement {
value,
weight,
graph_node,
});
}
Ok(())
}
}
/// A low-level trait that provides control over how curves are actually applied
/// to entities by the animation system.
///
/// Typically, this will not need to be implemented manually, since it is
/// automatically implemented by [`AnimatableCurve`] and other curves used by
/// the animation system (e.g. those that animate parts of transforms or morph
/// weights). However, this can be implemented manually when `AnimatableCurve`
/// is not sufficiently expressive.
///
/// In many respects, this behaves like a type-erased form of [`Curve`], where
/// the output type of the curve is remembered only in the components that are
/// mutated in the implementation of [`apply`].
///
/// [`apply`]: AnimationCurve::apply
pub trait AnimationCurve: Debug + Send + Sync + 'static {
/// Returns a boxed clone of this value.
fn clone_value(&self) -> Box<dyn AnimationCurve>;
/// The range of times for which this animation is defined.
fn domain(&self) -> Interval;
/// Returns the type ID of the [`AnimationCurveEvaluator`].
///
/// This must match the type returned by [`Self::create_evaluator`]. It must
/// be a single type that doesn't depend on the type of the curve.
fn evaluator_id(&self) -> EvaluatorId<'_>;
/// Returns a newly-instantiated [`AnimationCurveEvaluator`] for use with
/// this curve.
///
/// All curve types must return the same type of
/// [`AnimationCurveEvaluator`]. The returned value must match the type
/// returned by [`Self::evaluator_id`].
fn create_evaluator(&self) -> Box<dyn AnimationCurveEvaluator>;
/// Samples the curve at the given time `t`, and pushes the sampled value
/// onto the evaluation stack of the `curve_evaluator`.
///
/// The `curve_evaluator` parameter points to the value returned by
/// [`Self::create_evaluator`], upcast to an `&mut dyn
/// AnimationCurveEvaluator`. Typically, implementations of [`Self::apply`]
/// will want to downcast the `curve_evaluator` parameter to the concrete
/// type [`Self::evaluator_id`] in order to push values of the appropriate
/// type onto its evaluation stack.
///
/// Be sure not to confuse the `t` and `weight` values. The former
/// determines the position at which the *curve* is sampled, while `weight`
/// ultimately determines how much the *stack values* will be blended
/// together (see the definition of [`AnimationCurveEvaluator::blend`]).
fn apply(
&self,
curve_evaluator: &mut dyn AnimationCurveEvaluator,
t: f32,
weight: f32,
graph_node: AnimationNodeIndex,
) -> Result<(), AnimationEvaluationError>;
}
/// The [`EvaluatorId`] is used to look up the [`AnimationCurveEvaluator`] for an [`AnimatableProperty`].
/// For a given animated property, this ID should always be the same to allow things like animation blending to occur.
#[derive(Clone)]
pub enum EvaluatorId<'a> {
/// Corresponds to a specific field on a specific component type.
/// The `TypeId` should correspond to the component type, and the `usize`
/// should correspond to the Reflect-ed field index of the field.
//
// IMPLEMENTATION NOTE: The Hashed<(TypeId, usize) is intentionally cheap to clone, as it will be cloned per frame by the evaluator
// Switching the field index `usize` for something like a field name `String` would probably be too expensive to justify
ComponentField(&'a Hashed<(TypeId, usize)>),
/// Corresponds to a custom property of a given type. This should be the [`TypeId`]
/// of the custom [`AnimatableProperty`].
Type(TypeId),
}
/// A low-level trait for use in [`VariableCurve`](`crate::VariableCurve`) that provides fine
/// control over how animations are evaluated.
///
/// You can implement this trait when the generic [`AnimatableCurveEvaluator`]
/// isn't sufficiently-expressive for your needs. For example, `MorphWeights`
/// implements this trait instead of using [`AnimatableCurveEvaluator`] because
/// it needs to animate arbitrarily many weights at once, which can't be done
/// with [`Animatable`] as that works on fixed-size values only.
///
/// If you implement this trait, you should also implement [`AnimationCurve`] on
/// your curve type, as that trait allows creating instances of this one.
///
/// Implementations of [`AnimatableCurveEvaluator`] should maintain a *stack* of
/// (value, weight, node index) triples, as well as a *blend register*, which is
/// either a (value, weight) pair or empty. *Value* here refers to an instance
/// of the value being animated: for example, [`Vec3`] in the case of
/// translation keyframes. The stack stores intermediate values generated while
/// evaluating the [`AnimationGraph`](`crate::graph::AnimationGraph`), while the blend register
/// stores the result of a blend operation.
///
/// [`Vec3`]: bevy_math::Vec3
pub trait AnimationCurveEvaluator: Downcast + Send + Sync + 'static {
/// Blends the top element of the stack with the blend register.
///
/// The semantics of this method are as follows:
///
/// 1. Pop the top element of the stack. Call its value vₘ and its weight
/// wₘ. If the stack was empty, return success.
///
/// 2. If the blend register is empty, set the blend register value to vₘ
/// and the blend register weight to wₘ; then, return success.
///
/// 3. If the blend register is nonempty, call its current value vₙ and its
/// current weight wₙ. Then, set the value of the blend register to
/// `interpolate(vₙ, vₘ, wₘ / (wₘ + wₙ))`, and set the weight of the blend
/// register to wₘ + wₙ.
///
/// 4. Return success.
fn blend(&mut self, graph_node: AnimationNodeIndex) -> Result<(), AnimationEvaluationError>;
/// Additively blends the top element of the stack with the blend register.
///
/// The semantics of this method are as follows:
///
/// 1. Pop the top element of the stack. Call its value vₘ and its weight
/// wₘ. If the stack was empty, return success.
///
/// 2. If the blend register is empty, set the blend register value to vₘ
/// and the blend register weight to wₘ; then, return success.
///
/// 3. If the blend register is nonempty, call its current value vₙ.
/// Then, set the value of the blend register to vₙ + vₘwₘ.
///
/// 4. Return success.
fn add(&mut self, graph_node: AnimationNodeIndex) -> Result<(), AnimationEvaluationError>;
/// Pushes the current value of the blend register onto the stack.
///
/// If the blend register is empty, this method does nothing successfully.
/// Otherwise, this method pushes the current value of the blend register
/// onto the stack, alongside the weight and graph node supplied to this
/// function. The weight present in the blend register is discarded; only
/// the weight parameter to this function is pushed onto the stack. The
/// blend register is emptied after this process.
fn push_blend_register(
&mut self,
weight: f32,
graph_node: AnimationNodeIndex,
) -> Result<(), AnimationEvaluationError>;
/// Pops the top value off the stack and writes it into the appropriate
/// component.
///
/// If the stack is empty, this method does nothing successfully. Otherwise,
/// it pops the top value off the stack, fetches the associated component
/// from either the `transform` or `entity` values as appropriate, and
/// updates the appropriate property with the value popped from the stack.
/// The weight and node index associated with the popped stack element are
/// discarded. After doing this, the stack is emptied.
///
/// The property on the component must be overwritten with the value from
/// the stack, not blended with it.
fn commit(&mut self, entity: AnimationEntityMut) -> Result<(), AnimationEvaluationError>;
}
impl_downcast!(AnimationCurveEvaluator);
/// A [curve] defined by keyframes with values in an [animatable] type.
///
/// The keyframes are interpolated using the type's [`Animatable::interpolate`] implementation.
///
/// [curve]: Curve
/// [animatable]: Animatable
#[derive(Debug, Clone, Reflect)]
pub struct AnimatableKeyframeCurve<T> {
core: UnevenCore<T>,
}
impl<T> Curve<T> for AnimatableKeyframeCurve<T>
where
T: Animatable + Clone,
{
#[inline]
fn domain(&self) -> Interval {
self.core.domain()
}
#[inline]
fn sample_clamped(&self, t: f32) -> T {
// `UnevenCore::sample_with` is implicitly clamped.
self.core.sample_with(t, <T as Animatable>::interpolate)
}
#[inline]
fn sample_unchecked(&self, t: f32) -> T {
self.sample_clamped(t)
}
}
impl<T> AnimatableKeyframeCurve<T>
where
T: Animatable,
{
/// Create a new [`AnimatableKeyframeCurve`] from the given `keyframes`. The values of this
/// curve are interpolated from the keyframes using the output type's implementation of
/// [`Animatable::interpolate`].
///
/// There must be at least two samples in order for this method to succeed.
pub fn new(keyframes: impl IntoIterator<Item = (f32, T)>) -> Result<Self, UnevenCoreError> {
Ok(Self {
core: UnevenCore::new(keyframes)?,
})
}
}
fn inconsistent<P>() -> AnimationEvaluationError
where
P: 'static + ?Sized,
{
AnimationEvaluationError::InconsistentEvaluatorImplementation(TypeId::of::<P>())
}
/// Returns an [`AnimatedField`] with a given `$component` and `$field`.
///
/// This can be used in the following way:
///
/// ```
/// # use bevy_animation::{animation_curves::AnimatedField, animated_field};
/// # use bevy_color::Srgba;
/// # use bevy_ecs::component::Component;
/// # use bevy_math::Vec3;
/// # use bevy_reflect::Reflect;
/// #[derive(Component, Reflect)]
/// struct Transform {
/// translation: Vec3,
/// }
///
/// let field = animated_field!(Transform::translation);
///
/// #[derive(Component, Reflect)]
/// struct Color(Srgba);
///
/// let tuple_field = animated_field!(Color::0);
/// ```
#[macro_export]
macro_rules! animated_field {
($component:ident::$field:tt) => {
AnimatedField::new_unchecked(stringify!($field), |component: &mut $component| {
&mut component.$field
})
};
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_animated_field_tuple_struct_simple_uses() {
#[derive(Clone, Debug, Component, Reflect)]
struct A(f32);
let _ = AnimatedField::new_unchecked("0", |a: &mut A| &mut a.0);
#[derive(Clone, Debug, Component, Reflect)]
struct B(f32, f64, f32);
let _ = AnimatedField::new_unchecked("0", |b: &mut B| &mut b.0);
let _ = AnimatedField::new_unchecked("1", |b: &mut B| &mut b.1);
let _ = AnimatedField::new_unchecked("2", |b: &mut B| &mut b.2);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_animation/src/transition.rs | crates/bevy_animation/src/transition.rs | //! Animation transitions.
//!
//! Please note that this is an unstable temporary API. It may be replaced by a
//! state machine in the future.
use bevy_ecs::{
component::Component,
reflect::ReflectComponent,
system::{Query, Res},
};
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
use bevy_time::Time;
use core::time::Duration;
use crate::{graph::AnimationNodeIndex, ActiveAnimation, AnimationPlayer};
/// Manages fade-out of animation blend factors, allowing for smooth transitions
/// between animations.
///
/// To use this component, place it on the same entity as the
/// [`AnimationPlayer`] and [`AnimationGraphHandle`](crate::AnimationGraphHandle). It'll take
/// responsibility for adjusting the weight on the [`ActiveAnimation`] in order
/// to fade out animations smoothly.
///
/// When using an [`AnimationTransitions`] component, you should play all
/// animations through the [`AnimationTransitions::play`] method, rather than by
/// directly manipulating the [`AnimationPlayer`]. Playing animations through
/// the [`AnimationPlayer`] directly will cause the [`AnimationTransitions`]
/// component to get confused about which animation is the "main" animation, and
/// transitions will usually be incorrect as a result.
#[derive(Component, Default, Reflect)]
#[reflect(Component, Default, Clone)]
pub struct AnimationTransitions {
main_animation: Option<AnimationNodeIndex>,
transitions: Vec<AnimationTransition>,
}
// This is needed since `#[derive(Clone)]` does not generate optimized `clone_from`.
impl Clone for AnimationTransitions {
fn clone(&self) -> Self {
Self {
main_animation: self.main_animation,
transitions: self.transitions.clone(),
}
}
fn clone_from(&mut self, source: &Self) {
self.main_animation = source.main_animation;
self.transitions.clone_from(&source.transitions);
}
}
/// An animation that is being faded out as part of a transition
#[derive(Debug, Clone, Copy, Reflect)]
#[reflect(Clone)]
pub struct AnimationTransition {
/// The current weight. Starts at 1.0 and goes to 0.0 during the fade-out.
current_weight: f32,
/// How much to decrease `current_weight` per second
weight_decline_per_sec: f32,
/// The animation that is being faded out
animation: AnimationNodeIndex,
}
impl AnimationTransitions {
/// Creates a new [`AnimationTransitions`] component, ready to be added to
/// an entity with an [`AnimationPlayer`].
pub fn new() -> AnimationTransitions {
AnimationTransitions::default()
}
/// Plays a new animation on the given [`AnimationPlayer`], fading out any
/// existing animations that were already playing over the
/// `transition_duration`.
///
/// Pass [`Duration::ZERO`] to instantly switch to a new animation, avoiding
/// any transition.
pub fn play<'p>(
&mut self,
player: &'p mut AnimationPlayer,
new_animation: AnimationNodeIndex,
transition_duration: Duration,
) -> &'p mut ActiveAnimation {
if let Some(old_animation_index) = self.main_animation.replace(new_animation)
&& let Some(old_animation) = player.animation_mut(old_animation_index)
&& !old_animation.is_paused()
{
self.transitions.push(AnimationTransition {
current_weight: old_animation.weight,
weight_decline_per_sec: 1.0 / transition_duration.as_secs_f32(),
animation: old_animation_index,
});
}
// If already transitioning away from this animation, cancel the transition.
// Otherwise the transition ending would incorrectly stop the new animation.
self.transitions
.retain(|transition| transition.animation != new_animation);
player.start(new_animation)
}
/// Obtain the currently playing main animation.
pub fn get_main_animation(&self) -> Option<AnimationNodeIndex> {
self.main_animation
}
}
/// A system that alters the weight of currently-playing transitions based on
/// the current time and decline amount.
pub fn advance_transitions(
mut query: Query<(&mut AnimationTransitions, &mut AnimationPlayer)>,
time: Res<Time>,
) {
// We use a "greedy layer" system here. The top layer (most recent
// transition) gets as much as weight as it wants, and the remaining amount
// is divided between all the other layers, eventually culminating in the
// currently-playing animation receiving whatever's left. This results in a
// nicely normalized weight.
for (mut animation_transitions, mut player) in query.iter_mut() {
let mut remaining_weight = 1.0;
for transition in &mut animation_transitions.transitions.iter_mut().rev() {
// Decrease weight.
transition.current_weight = (transition.current_weight
- transition.weight_decline_per_sec * time.delta_secs())
.max(0.0);
// Update weight.
let Some(ref mut animation) = player.animation_mut(transition.animation) else {
continue;
};
animation.weight = transition.current_weight * remaining_weight;
remaining_weight -= animation.weight;
}
if let Some(main_animation_index) = animation_transitions.main_animation
&& let Some(ref mut animation) = player.animation_mut(main_animation_index)
{
animation.weight = remaining_weight;
}
}
}
/// A system that removed transitions that have completed from the
/// [`AnimationTransitions`] object.
pub fn expire_completed_transitions(
mut query: Query<(&mut AnimationTransitions, &mut AnimationPlayer)>,
) {
for (mut animation_transitions, mut player) in query.iter_mut() {
animation_transitions.transitions.retain(|transition| {
let expire = transition.current_weight <= 0.0;
if expire {
player.stop(transition.animation);
}
!expire
});
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_animation/src/util.rs | crates/bevy_animation/src/util.rs | /// Steps between two different discrete values of any type.
/// Returns `a` if `t < 1.0`, otherwise returns `b`.
#[inline]
pub(crate) fn step_unclamped<T>(a: T, b: T, t: f32) -> T {
if t < 1.0 {
a
} else {
b
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_animation/src/animatable.rs | crates/bevy_animation/src/animatable.rs | //! Traits and type for interpolating between values.
use crate::util;
use bevy_color::{Laba, LinearRgba, Oklaba, Srgba, Xyza};
use bevy_math::*;
use bevy_reflect::Reflect;
use bevy_transform::prelude::Transform;
/// An individual input for [`Animatable::blend`].
pub struct BlendInput<T> {
/// The individual item's weight. This may not be bound to the range `[0.0, 1.0]`.
pub weight: f32,
/// The input value to be blended.
pub value: T,
/// Whether or not to additively blend this input into the final result.
pub additive: bool,
}
/// An animatable value type.
pub trait Animatable: Reflect + Sized + Send + Sync + 'static {
/// Interpolates between `a` and `b` with an interpolation factor of `time`.
///
/// The `time` parameter here may not be clamped to the range `[0.0, 1.0]`.
fn interpolate(a: &Self, b: &Self, time: f32) -> Self;
/// Blends one or more values together.
///
/// Implementors should return a default value when no inputs are provided here.
fn blend(inputs: impl Iterator<Item = BlendInput<Self>>) -> Self;
}
macro_rules! impl_float_animatable {
($ty: ty, $base: ty) => {
impl Animatable for $ty {
#[inline]
fn interpolate(a: &Self, b: &Self, t: f32) -> Self {
let t = <$base>::from(t);
(*a) * (1.0 - t) + (*b) * t
}
#[inline]
fn blend(inputs: impl Iterator<Item = BlendInput<Self>>) -> Self {
let mut value = Default::default();
for input in inputs {
if input.additive {
value += <$base>::from(input.weight) * input.value;
} else {
value = Self::interpolate(&value, &input.value, input.weight);
}
}
value
}
}
};
}
macro_rules! impl_color_animatable {
($ty: ident) => {
impl Animatable for $ty {
#[inline]
fn interpolate(a: &Self, b: &Self, t: f32) -> Self {
let value = *a * (1. - t) + *b * t;
value
}
#[inline]
fn blend(inputs: impl Iterator<Item = BlendInput<Self>>) -> Self {
let mut value = Default::default();
for input in inputs {
if input.additive {
value += input.weight * input.value;
} else {
value = Self::interpolate(&value, &input.value, input.weight);
}
}
value
}
}
};
}
impl_float_animatable!(f32, f32);
impl_float_animatable!(Vec2, f32);
impl_float_animatable!(Vec3A, f32);
impl_float_animatable!(Vec4, f32);
impl_float_animatable!(f64, f64);
impl_float_animatable!(DVec2, f64);
impl_float_animatable!(DVec3, f64);
impl_float_animatable!(DVec4, f64);
impl_color_animatable!(LinearRgba);
impl_color_animatable!(Laba);
impl_color_animatable!(Oklaba);
impl_color_animatable!(Srgba);
impl_color_animatable!(Xyza);
// Vec3 is special cased to use Vec3A internally for blending
impl Animatable for Vec3 {
#[inline]
fn interpolate(a: &Self, b: &Self, t: f32) -> Self {
(*a) * (1.0 - t) + (*b) * t
}
#[inline]
fn blend(inputs: impl Iterator<Item = BlendInput<Self>>) -> Self {
let mut value = Vec3A::ZERO;
for input in inputs {
if input.additive {
value += input.weight * Vec3A::from(input.value);
} else {
value = Vec3A::interpolate(&value, &Vec3A::from(input.value), input.weight);
}
}
Self::from(value)
}
}
impl Animatable for bool {
#[inline]
fn interpolate(a: &Self, b: &Self, t: f32) -> Self {
util::step_unclamped(*a, *b, t)
}
#[inline]
fn blend(inputs: impl Iterator<Item = BlendInput<Self>>) -> Self {
inputs
.max_by_key(|x| FloatOrd(x.weight))
.is_some_and(|input| input.value)
}
}
impl Animatable for Transform {
fn interpolate(a: &Self, b: &Self, t: f32) -> Self {
Self {
translation: Vec3::interpolate(&a.translation, &b.translation, t),
rotation: Quat::interpolate(&a.rotation, &b.rotation, t),
scale: Vec3::interpolate(&a.scale, &b.scale, t),
}
}
fn blend(inputs: impl Iterator<Item = BlendInput<Self>>) -> Self {
let mut translation = Vec3A::ZERO;
let mut scale = Vec3A::ZERO;
let mut rotation = Quat::IDENTITY;
for input in inputs {
if input.additive {
translation += input.weight * Vec3A::from(input.value.translation);
scale += input.weight * Vec3A::from(input.value.scale);
rotation =
Quat::slerp(Quat::IDENTITY, input.value.rotation, input.weight) * rotation;
} else {
translation = Vec3A::interpolate(
&translation,
&Vec3A::from(input.value.translation),
input.weight,
);
scale = Vec3A::interpolate(&scale, &Vec3A::from(input.value.scale), input.weight);
rotation = Quat::interpolate(&rotation, &input.value.rotation, input.weight);
}
}
Self {
translation: Vec3::from(translation),
rotation,
scale: Vec3::from(scale),
}
}
}
impl Animatable for Quat {
/// Performs a slerp to smoothly interpolate between quaternions.
#[inline]
fn interpolate(a: &Self, b: &Self, t: f32) -> Self {
// We want to smoothly interpolate between the two quaternions by default,
// rather than using a quicker but less correct linear interpolation.
a.slerp(*b, t)
}
#[inline]
fn blend(inputs: impl Iterator<Item = BlendInput<Self>>) -> Self {
let mut value = Self::IDENTITY;
for BlendInput {
weight,
value: incoming_value,
additive,
} in inputs
{
if additive {
value = Self::slerp(Self::IDENTITY, incoming_value, weight) * value;
} else {
value = Self::interpolate(&value, &incoming_value, weight);
}
}
value
}
}
/// Evaluates a cubic Bézier curve at a value `t`, given two endpoints and the
/// derivatives at those endpoints.
///
/// The derivatives are linearly scaled by `duration`.
pub fn interpolate_with_cubic_bezier<T>(p0: &T, d0: &T, d3: &T, p3: &T, t: f32, duration: f32) -> T
where
T: Animatable + Clone,
{
// We're given two endpoints, along with the derivatives at those endpoints,
// and have to evaluate the cubic Bézier curve at time t using only
// (additive) blending and linear interpolation.
//
// Evaluating a Bézier curve via repeated linear interpolation when the
// control points are known is straightforward via [de Casteljau
// subdivision]. So the only remaining problem is to get the two off-curve
// control points. The [derivative of the cubic Bézier curve] is:
//
// B′(t) = 3(1 - t)²(P₁ - P₀) + 6(1 - t)t(P₂ - P₁) + 3t²(P₃ - P₂)
//
// Setting t = 0 and t = 1 and solving gives us:
//
// P₁ = P₀ + B′(0) / 3
// P₂ = P₃ - B′(1) / 3
//
// These P₁ and P₂ formulas can be expressed as additive blends.
//
// So, to sum up, first we calculate the off-curve control points via
// additive blending, and then we use repeated linear interpolation to
// evaluate the curve.
//
// [de Casteljau subdivision]: https://en.wikipedia.org/wiki/De_Casteljau%27s_algorithm
// [derivative of the cubic Bézier curve]: https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Cubic_B%C3%A9zier_curves
// Compute control points from derivatives.
let p1 = T::blend(
[
BlendInput {
weight: duration / 3.0,
value: (*d0).clone(),
additive: true,
},
BlendInput {
weight: 1.0,
value: (*p0).clone(),
additive: true,
},
]
.into_iter(),
);
let p2 = T::blend(
[
BlendInput {
weight: duration / -3.0,
value: (*d3).clone(),
additive: true,
},
BlendInput {
weight: 1.0,
value: (*p3).clone(),
additive: true,
},
]
.into_iter(),
);
// Use de Casteljau subdivision to evaluate.
let p0p1 = T::interpolate(p0, &p1, t);
let p1p2 = T::interpolate(&p1, &p2, t);
let p2p3 = T::interpolate(&p2, p3, t);
let p0p1p2 = T::interpolate(&p0p1, &p1p2, t);
let p1p2p3 = T::interpolate(&p1p2, &p2p3, t);
T::interpolate(&p0p1p2, &p1p2p3, t)
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_animation/src/graph.rs | crates/bevy_animation/src/graph.rs | //! The animation graph, which allows animations to be blended together.
use core::{
fmt::Write,
iter,
ops::{Index, IndexMut, Range},
};
use std::io;
use bevy_asset::{
io::Reader, Asset, AssetEvent, AssetId, AssetLoader, AssetPath, Assets, Handle, LoadContext,
};
use bevy_derive::{Deref, DerefMut};
use bevy_ecs::{
component::Component,
message::MessageReader,
reflect::ReflectComponent,
resource::Resource,
system::{Res, ResMut},
};
use bevy_platform::collections::HashMap;
use bevy_reflect::{prelude::ReflectDefault, Reflect, TypePath};
use derive_more::derive::From;
use petgraph::{
graph::{DiGraph, NodeIndex},
Direction,
};
use ron::de::SpannedError;
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
use thiserror::Error;
use crate::{AnimationClip, AnimationTargetId};
/// A graph structure that describes how animation clips are to be blended
/// together.
///
/// Applications frequently want to be able to play multiple animations at once
/// and to fine-tune the influence that animations have on a skinned mesh. Bevy
/// uses an *animation graph* to store this information. Animation graphs are a
/// directed acyclic graph (DAG) that describes how animations are to be
/// weighted and combined together. Every frame, Bevy evaluates the graph from
/// the root and blends the animations together in a bottom-up fashion to
/// produce the final pose.
///
/// There are three types of nodes: *blend nodes*, *add nodes*, and *clip
/// nodes*, all of which can have an associated weight. Blend nodes and add
/// nodes have no associated animation clip and combine the animations of their
/// children according to those children's weights. Clip nodes specify an
/// animation clip to play. When a graph is created, it starts with only a
/// single blend node, the root node.
///
/// For example, consider the following graph:
///
/// ```text
/// ┌────────────┐
/// │ │
/// │ Idle ├─────────────────────┐
/// │ │ │
/// └────────────┘ │
/// │
/// ┌────────────┐ │ ┌────────────┐
/// │ │ │ │ │
/// │ Run ├──┐ ├──┤ Root │
/// │ │ │ ┌────────────┐ │ │ │
/// └────────────┘ │ │ Blend │ │ └────────────┘
/// ├──┤ ├──┘
/// ┌────────────┐ │ │ 0.5 │
/// │ │ │ └────────────┘
/// │ Walk ├──┘
/// │ │
/// └────────────┘
/// ```
///
/// In this case, assuming that Idle, Run, and Walk are all playing with weight
/// 1.0, the Run and Walk animations will be equally blended together, then
/// their weights will be halved and finally blended with the Idle animation.
/// Thus the weight of Run and Walk are effectively half of the weight of Idle.
///
/// Nodes can optionally have a *mask*, a bitfield that restricts the set of
/// animation targets that the node and its descendants affect. Each bit in the
/// mask corresponds to a *mask group*, which is a set of animation targets
/// (bones). An animation target can belong to any number of mask groups within
/// the context of an animation graph.
///
/// When the appropriate bit is set in a node's mask, neither the node nor its
/// descendants will animate any animation targets belonging to that mask group.
/// That is, setting a mask bit to 1 *disables* the animation targets in that
/// group. If an animation target belongs to multiple mask groups, masking any
/// one of the mask groups that it belongs to will mask that animation target.
/// (Thus an animation target will only be animated if *all* of its mask groups
/// are unmasked.)
///
/// A common use of masks is to allow characters to hold objects. For this, the
/// typical workflow is to assign each character's hand to a mask group. Then,
/// when the character picks up an object, the application masks out the hand
/// that the object is held in for the character's animation set, then positions
/// the hand's digits as necessary to grasp the object. The character's
/// animations will continue to play but will not affect the hand, which will
/// continue to be depicted as holding the object.
///
/// Animation graphs are assets and can be serialized to and loaded from [RON]
/// files. Canonically, such files have an `.animgraph.ron` extension.
///
/// The animation graph implements [RFC 51]. See that document for more
/// information.
///
/// [RON]: https://github.com/ron-rs/ron
///
/// [RFC 51]: https://github.com/bevyengine/rfcs/blob/main/rfcs/51-animation-composition.md
#[derive(Asset, Reflect, Clone, Debug)]
#[reflect(Debug, Clone)]
pub struct AnimationGraph {
/// The `petgraph` data structure that defines the animation graph.
pub graph: AnimationDiGraph,
/// The index of the root node in the animation graph.
pub root: NodeIndex,
/// The mask groups that each animation target (bone) belongs to.
///
/// Each value in this map is a bitfield, in which 0 in bit position N
/// indicates that the animation target doesn't belong to mask group N, and
/// a 1 in position N indicates that the animation target does belong to
/// mask group N.
///
/// Animation targets not in this collection are treated as though they
/// don't belong to any mask groups.
pub mask_groups: HashMap<AnimationTargetId, AnimationMask>,
}
/// A [`Handle`] to the [`AnimationGraph`] to be used by the [`AnimationPlayer`](crate::AnimationPlayer) on the same entity.
#[derive(Component, Clone, Debug, Default, Deref, DerefMut, Reflect, PartialEq, Eq, From)]
#[reflect(Component, Default, Clone)]
pub struct AnimationGraphHandle(pub Handle<AnimationGraph>);
impl From<AnimationGraphHandle> for AssetId<AnimationGraph> {
fn from(handle: AnimationGraphHandle) -> Self {
handle.id()
}
}
impl From<&AnimationGraphHandle> for AssetId<AnimationGraph> {
fn from(handle: &AnimationGraphHandle) -> Self {
handle.id()
}
}
/// A type alias for the `petgraph` data structure that defines the animation
/// graph.
pub type AnimationDiGraph = DiGraph<AnimationGraphNode, (), u32>;
/// The index of either an animation or blend node in the animation graph.
///
/// These indices are the way that [animation players] identify each animation.
///
/// [animation players]: crate::AnimationPlayer
pub type AnimationNodeIndex = NodeIndex<u32>;
/// An individual node within an animation graph.
///
/// The [`AnimationGraphNode::node_type`] field specifies the type of node: one
/// of a *clip node*, a *blend node*, or an *add node*. Clip nodes, the leaves
/// of the graph, contain animation clips to play. Blend and add nodes describe
/// how to combine their children to produce a final animation.
#[derive(Clone, Reflect, Debug)]
#[reflect(Clone)]
pub struct AnimationGraphNode {
/// Animation node data specific to the type of node (clip, blend, or add).
///
/// In the case of clip nodes, this contains the actual animation clip
/// associated with the node.
pub node_type: AnimationNodeType,
/// A bitfield specifying the mask groups that this node and its descendants
/// will not affect.
///
/// A 0 in bit N indicates that this node and its descendants *can* animate
/// animation targets in mask group N, while a 1 in bit N indicates that
/// this node and its descendants *cannot* animate mask group N.
pub mask: AnimationMask,
/// The weight of this node, which signifies its contribution in blending.
///
/// Note that this does not propagate down the graph hierarchy; rather,
/// each [Blend] and [Add] node uses the weights of its children to determine
/// the total animation that is accumulated at that node. The parent node's
/// weight is used only to determine the contribution of that total animation
/// in *further* blending.
///
/// In other words, it is as if the blend node is replaced by a single clip
/// node consisting of the blended animation with the weight specified at the
/// blend node.
///
/// For animation clips, this weight is also multiplied by the [active animation weight]
/// before being applied.
///
/// [Blend]: AnimationNodeType::Blend
/// [Add]: AnimationNodeType::Add
/// [active animation weight]: crate::ActiveAnimation::weight
pub weight: f32,
}
/// Animation node data specific to the type of node (clip, blend, or add).
///
/// In the case of clip nodes, this contains the actual animation clip
/// associated with the node.
#[derive(Clone, Default, Reflect, Debug)]
#[reflect(Clone)]
pub enum AnimationNodeType {
/// A *clip node*, which plays an animation clip.
///
/// These are always the leaves of the graph.
Clip(Handle<AnimationClip>),
/// A *blend node*, which blends its children according to their weights.
///
/// The weights of all the children of this node are normalized to 1.0.
#[default]
Blend,
/// An *additive blend node*, which combines the animations of its children
/// additively.
///
/// The weights of all the children of this node are *not* normalized to
/// 1.0. Rather, each child is multiplied by its respective weight and
/// added in sequence.
///
/// Add nodes are primarily useful for superimposing an animation for a
/// portion of a rig on top of the main animation. For example, an add node
/// could superimpose a weapon attack animation for a character's limb on
/// top of a running animation to produce an animation of a character
/// attacking while running.
Add,
}
/// An [`AssetLoader`] that can load [`AnimationGraph`]s as assets.
///
/// The canonical extension for [`AnimationGraph`]s is `.animgraph.ron`. Plain
/// `.animgraph` is supported as well.
#[derive(Default, TypePath)]
pub struct AnimationGraphAssetLoader;
/// Errors that can occur when serializing animation graphs to RON.
#[derive(Error, Debug)]
pub enum AnimationGraphSaveError {
/// An I/O error occurred.
#[error(transparent)]
Io(#[from] io::Error),
/// An error occurred in RON serialization.
#[error(transparent)]
Ron(#[from] ron::Error),
/// An error occurred converting the graph to its serialization form.
#[error(transparent)]
ConvertToSerialized(#[from] NonPathHandleError),
}
/// Errors that can occur when deserializing animation graphs from RON.
#[derive(Error, Debug)]
pub enum AnimationGraphLoadError {
/// An I/O error occurred.
#[error(transparent)]
Io(#[from] io::Error),
/// An error occurred in RON deserialization.
#[error(transparent)]
Ron(#[from] ron::Error),
/// An error occurred in RON deserialization, and the location of the error
/// is supplied.
#[error(transparent)]
SpannedRon(#[from] SpannedError),
/// The deserialized graph contained legacy data that we no longer support.
#[error(
"The deserialized AnimationGraph contained an AnimationClip referenced by an AssetId, \
which is no longer supported. Consider manually deserializing the SerializedAnimationGraph \
type and determine how to migrate any SerializedAnimationClip::AssetId animation clips"
)]
GraphContainsLegacyAssetId,
}
/// Acceleration structures for animation graphs that allows Bevy to evaluate
/// them quickly.
///
/// These are kept up to date as [`AnimationGraph`] instances are added,
/// modified, and removed.
#[derive(Default, Reflect, Resource)]
pub struct ThreadedAnimationGraphs(
pub(crate) HashMap<AssetId<AnimationGraph>, ThreadedAnimationGraph>,
);
/// An acceleration structure for an animation graph that allows Bevy to
/// evaluate it quickly.
///
/// This is kept up to date as the associated [`AnimationGraph`] instance is
/// added, modified, or removed.
#[derive(Default, Reflect)]
pub struct ThreadedAnimationGraph {
/// A cached postorder traversal of the graph.
///
/// The node indices here are stored in postorder. Siblings are stored in
/// descending order. This is because the
/// [`AnimationCurveEvaluator`](`crate::animation_curves::AnimationCurveEvaluator`) uses a stack for
/// evaluation. Consider this graph:
///
/// ```text
/// ┌─────┐
/// │ │
/// │ 1 │
/// │ │
/// └──┬──┘
/// │
/// ┌───────┼───────┐
/// │ │ │
/// ▼ ▼ ▼
/// ┌─────┐ ┌─────┐ ┌─────┐
/// │ │ │ │ │ │
/// │ 2 │ │ 3 │ │ 4 │
/// │ │ │ │ │ │
/// └──┬──┘ └─────┘ └─────┘
/// │
/// ┌───┴───┐
/// │ │
/// ▼ ▼
/// ┌─────┐ ┌─────┐
/// │ │ │ │
/// │ 5 │ │ 6 │
/// │ │ │ │
/// └─────┘ └─────┘
/// ```
///
/// The postorder traversal in this case will be (4, 3, 6, 5, 2, 1).
///
/// The fact that the children of each node are sorted in reverse ensures
/// that, at each level, the order of blending proceeds in ascending order
/// by node index, as we guarantee. To illustrate this, consider the way
/// the graph above is evaluated. (Interpolation is represented with the ⊕
/// symbol.)
///
/// | Step | Node | Operation | Stack (after operation) | Blend Register |
/// | ---- | ---- | ---------- | ----------------------- | -------------- |
/// | 1 | 4 | Push | 4 | |
/// | 2 | 3 | Push | 4 3 | |
/// | 3 | 6 | Push | 4 3 6 | |
/// | 4 | 5 | Push | 4 3 6 5 | |
/// | 5 | 2 | Blend 5 | 4 3 6 | 5 |
/// | 6 | 2 | Blend 6 | 4 3 | 5 ⊕ 6 |
/// | 7 | 2 | Push Blend | 4 3 2 | |
/// | 8 | 1 | Blend 2 | 4 3 | 2 |
/// | 9 | 1 | Blend 3 | 4 | 2 ⊕ 3 |
/// | 10 | 1 | Blend 4 | | 2 ⊕ 3 ⊕ 4 |
/// | 11 | 1 | Push Blend | 1 | |
/// | 12 | | Commit | | |
pub threaded_graph: Vec<AnimationNodeIndex>,
/// A mapping from each parent node index to the range within
/// [`Self::sorted_edges`].
///
/// This allows for quick lookup of the children of each node, sorted in
/// ascending order of node index, without having to sort the result of the
/// `petgraph` traversal functions every frame.
pub sorted_edge_ranges: Vec<Range<u32>>,
/// A list of the children of each node, sorted in ascending order.
pub sorted_edges: Vec<AnimationNodeIndex>,
/// A mapping from node index to a bitfield specifying the mask groups that
/// this node masks *out* (i.e. doesn't animate).
///
/// A 1 in bit position N indicates that this node doesn't animate any
/// targets of mask group N.
pub computed_masks: Vec<u64>,
}
/// A version of [`AnimationGraph`] suitable for serializing as an asset.
///
/// Animation nodes can refer to external animation clips, and the [`AssetId`]
/// is typically not sufficient to identify the clips, since the
/// [`bevy_asset::AssetServer`] assigns IDs in unpredictable ways. That fact
/// motivates this type, which replaces the `Handle<AnimationClip>` with an
/// asset path. Loading an animation graph via the [`bevy_asset::AssetServer`]
/// actually loads a serialized instance of this type, as does serializing an
/// [`AnimationGraph`] through `serde`.
#[derive(Serialize, Deserialize)]
pub struct SerializedAnimationGraph {
/// Corresponds to the `graph` field on [`AnimationGraph`].
pub graph: DiGraph<SerializedAnimationGraphNode, (), u32>,
/// Corresponds to the `root` field on [`AnimationGraph`].
pub root: NodeIndex,
/// Corresponds to the `mask_groups` field on [`AnimationGraph`].
pub mask_groups: HashMap<AnimationTargetId, AnimationMask>,
}
/// A version of [`AnimationGraphNode`] suitable for serializing as an asset.
///
/// See the comments in [`SerializedAnimationGraph`] for more information.
#[derive(Serialize, Deserialize)]
pub struct SerializedAnimationGraphNode {
/// Corresponds to the `node_type` field on [`AnimationGraphNode`].
pub node_type: SerializedAnimationNodeType,
/// Corresponds to the `mask` field on [`AnimationGraphNode`].
pub mask: AnimationMask,
/// Corresponds to the `weight` field on [`AnimationGraphNode`].
pub weight: f32,
}
/// A version of [`AnimationNodeType`] suitable for serializing as part of a
/// [`SerializedAnimationGraphNode`] asset.
#[derive(Serialize, Deserialize)]
pub enum SerializedAnimationNodeType {
/// Corresponds to [`AnimationNodeType::Clip`].
Clip(AssetPath<'static>),
/// Corresponds to [`AnimationNodeType::Blend`].
Blend,
/// Corresponds to [`AnimationNodeType::Add`].
Add,
}
/// The type of an animation mask bitfield.
///
/// Bit N corresponds to mask group N.
///
/// Because this is a 64-bit value, there is currently a limitation of 64 mask
/// groups per animation graph.
pub type AnimationMask = u64;
impl AnimationGraph {
/// Creates a new animation graph with a root node and no other nodes.
pub fn new() -> Self {
let mut graph = DiGraph::default();
let root = graph.add_node(AnimationGraphNode::default());
Self {
graph,
root,
mask_groups: HashMap::default(),
}
}
/// A convenience function for creating an [`AnimationGraph`] from a single
/// [`AnimationClip`].
///
/// The clip will be a direct child of the root with weight 1.0. Both the
/// graph and the index of the added node are returned as a tuple.
pub fn from_clip(clip: Handle<AnimationClip>) -> (Self, AnimationNodeIndex) {
let mut graph = Self::new();
let node_index = graph.add_clip(clip, 1.0, graph.root);
(graph, node_index)
}
/// A convenience method to create an [`AnimationGraph`]s with an iterator
/// of clips.
///
/// All of the animation clips will be direct children of the root with
/// weight 1.0.
///
/// Returns the graph and indices of the new nodes.
pub fn from_clips<'a, I>(clips: I) -> (Self, Vec<AnimationNodeIndex>)
where
I: IntoIterator<Item = Handle<AnimationClip>>,
<I as IntoIterator>::IntoIter: 'a,
{
let mut graph = Self::new();
let indices = graph.add_clips(clips, 1.0, graph.root).collect();
(graph, indices)
}
/// Adds an [`AnimationClip`] to the animation graph with the given weight
/// and returns its index.
///
/// The animation clip will be the child of the given parent. The resulting
/// node will have no mask.
pub fn add_clip(
&mut self,
clip: Handle<AnimationClip>,
weight: f32,
parent: AnimationNodeIndex,
) -> AnimationNodeIndex {
let node_index = self.graph.add_node(AnimationGraphNode {
node_type: AnimationNodeType::Clip(clip),
mask: 0,
weight,
});
self.graph.add_edge(parent, node_index, ());
node_index
}
/// Adds an [`AnimationClip`] to the animation graph with the given weight
/// and mask, and returns its index.
///
/// The animation clip will be the child of the given parent.
pub fn add_clip_with_mask(
&mut self,
clip: Handle<AnimationClip>,
mask: AnimationMask,
weight: f32,
parent: AnimationNodeIndex,
) -> AnimationNodeIndex {
let node_index = self.graph.add_node(AnimationGraphNode {
node_type: AnimationNodeType::Clip(clip),
mask,
weight,
});
self.graph.add_edge(parent, node_index, ());
node_index
}
/// A convenience method to add multiple [`AnimationClip`]s to the animation
/// graph.
///
/// All of the animation clips will have the same weight and will be
/// parented to the same node.
///
/// Returns the indices of the new nodes.
pub fn add_clips<'a, I>(
&'a mut self,
clips: I,
weight: f32,
parent: AnimationNodeIndex,
) -> impl Iterator<Item = AnimationNodeIndex> + 'a
where
I: IntoIterator<Item = Handle<AnimationClip>>,
<I as IntoIterator>::IntoIter: 'a,
{
clips
.into_iter()
.map(move |clip| self.add_clip(clip, weight, parent))
}
/// Adds a blend node to the animation graph with the given weight and
/// returns its index.
///
/// The blend node will be placed under the supplied `parent` node. During
/// animation evaluation, the descendants of this blend node will have their
/// weights multiplied by the weight of the blend. The blend node will have
/// no mask.
pub fn add_blend(&mut self, weight: f32, parent: AnimationNodeIndex) -> AnimationNodeIndex {
let node_index = self.graph.add_node(AnimationGraphNode {
node_type: AnimationNodeType::Blend,
mask: 0,
weight,
});
self.graph.add_edge(parent, node_index, ());
node_index
}
/// Adds a blend node to the animation graph with the given weight and
/// returns its index.
///
/// The blend node will be placed under the supplied `parent` node. During
/// animation evaluation, the descendants of this blend node will have their
/// weights multiplied by the weight of the blend. Neither this node nor its
/// descendants will affect animation targets that belong to mask groups not
/// in the given `mask`.
pub fn add_blend_with_mask(
&mut self,
mask: AnimationMask,
weight: f32,
parent: AnimationNodeIndex,
) -> AnimationNodeIndex {
let node_index = self.graph.add_node(AnimationGraphNode {
node_type: AnimationNodeType::Blend,
mask,
weight,
});
self.graph.add_edge(parent, node_index, ());
node_index
}
/// Adds a blend node to the animation graph with the given weight and
/// returns its index.
///
/// The blend node will be placed under the supplied `parent` node. During
/// animation evaluation, the descendants of this blend node will have their
/// weights multiplied by the weight of the blend. The blend node will have
/// no mask.
pub fn add_additive_blend(
&mut self,
weight: f32,
parent: AnimationNodeIndex,
) -> AnimationNodeIndex {
let node_index = self.graph.add_node(AnimationGraphNode {
node_type: AnimationNodeType::Add,
mask: 0,
weight,
});
self.graph.add_edge(parent, node_index, ());
node_index
}
/// Adds a blend node to the animation graph with the given weight and
/// returns its index.
///
/// The blend node will be placed under the supplied `parent` node. During
/// animation evaluation, the descendants of this blend node will have their
/// weights multiplied by the weight of the blend. Neither this node nor its
/// descendants will affect animation targets that belong to mask groups not
/// in the given `mask`.
pub fn add_additive_blend_with_mask(
&mut self,
mask: AnimationMask,
weight: f32,
parent: AnimationNodeIndex,
) -> AnimationNodeIndex {
let node_index = self.graph.add_node(AnimationGraphNode {
node_type: AnimationNodeType::Add,
mask,
weight,
});
self.graph.add_edge(parent, node_index, ());
node_index
}
/// Adds an edge from the edge `from` to `to`, making `to` a child of
/// `from`.
///
/// The behavior is unspecified if adding this produces a cycle in the
/// graph.
pub fn add_edge(&mut self, from: NodeIndex, to: NodeIndex) {
self.graph.add_edge(from, to, ());
}
/// Removes an edge between `from` and `to` if it exists.
///
/// Returns true if the edge was successfully removed or false if no such
/// edge existed.
pub fn remove_edge(&mut self, from: NodeIndex, to: NodeIndex) -> bool {
self.graph
.find_edge(from, to)
.map(|edge| self.graph.remove_edge(edge))
.is_some()
}
/// Returns the [`AnimationGraphNode`] associated with the given index.
///
/// If no node with the given index exists, returns `None`.
pub fn get(&self, animation: AnimationNodeIndex) -> Option<&AnimationGraphNode> {
self.graph.node_weight(animation)
}
/// Returns a mutable reference to the [`AnimationGraphNode`] associated
/// with the given index.
///
/// If no node with the given index exists, returns `None`.
pub fn get_mut(&mut self, animation: AnimationNodeIndex) -> Option<&mut AnimationGraphNode> {
self.graph.node_weight_mut(animation)
}
/// Returns an iterator over the [`AnimationGraphNode`]s in this graph.
pub fn nodes(&self) -> impl Iterator<Item = AnimationNodeIndex> {
self.graph.node_indices()
}
/// Serializes the animation graph to the given [`Write`]r in RON format.
///
/// If writing to a file, it can later be loaded with the
/// [`AnimationGraphAssetLoader`] to reconstruct the graph.
pub fn save<W>(&self, writer: &mut W) -> Result<(), AnimationGraphSaveError>
where
W: Write,
{
let mut ron_serializer = ron::ser::Serializer::new(writer, None)?;
let serialized_graph: SerializedAnimationGraph = self.clone().try_into()?;
Ok(serialized_graph.serialize(&mut ron_serializer)?)
}
/// Adds an animation target (bone) to the mask group with the given ID.
///
/// Calling this method multiple times with the same animation target but
/// different mask groups will result in that target being added to all of
/// the specified groups.
pub fn add_target_to_mask_group(&mut self, target: AnimationTargetId, mask_group: u32) {
*self.mask_groups.entry(target).or_default() |= 1 << mask_group;
}
}
impl AnimationGraphNode {
/// Masks out the mask groups specified by the given `mask` bitfield.
///
/// A 1 in bit position N causes this function to mask out mask group N, and
/// thus neither this node nor its descendants will animate any animation
/// targets that belong to group N.
pub fn add_mask(&mut self, mask: AnimationMask) -> &mut Self {
self.mask |= mask;
self
}
/// Unmasks the mask groups specified by the given `mask` bitfield.
///
/// A 1 in bit position N causes this function to unmask mask group N, and
/// thus this node and its descendants will be allowed to animate animation
/// targets that belong to group N, unless another mask masks those targets
/// out.
pub fn remove_mask(&mut self, mask: AnimationMask) -> &mut Self {
self.mask &= !mask;
self
}
/// Masks out the single mask group specified by `group`.
///
/// After calling this function, neither this node nor its descendants will
/// animate any animation targets that belong to the given `group`.
pub fn add_mask_group(&mut self, group: u32) -> &mut Self {
self.add_mask(1 << group)
}
/// Unmasks the single mask group specified by `group`.
///
/// After calling this function, this node and its descendants will be
/// allowed to animate animation targets that belong to the given `group`,
/// unless another mask masks those targets out.
pub fn remove_mask_group(&mut self, group: u32) -> &mut Self {
self.remove_mask(1 << group)
}
}
impl Index<AnimationNodeIndex> for AnimationGraph {
type Output = AnimationGraphNode;
fn index(&self, index: AnimationNodeIndex) -> &Self::Output {
&self.graph[index]
}
}
impl IndexMut<AnimationNodeIndex> for AnimationGraph {
fn index_mut(&mut self, index: AnimationNodeIndex) -> &mut Self::Output {
&mut self.graph[index]
}
}
impl Default for AnimationGraphNode {
fn default() -> Self {
Self {
node_type: Default::default(),
mask: 0,
weight: 1.0,
}
}
}
impl Default for AnimationGraph {
fn default() -> Self {
Self::new()
}
}
impl AssetLoader for AnimationGraphAssetLoader {
type Asset = AnimationGraph;
type Settings = ();
type Error = AnimationGraphLoadError;
async fn load(
&self,
reader: &mut dyn Reader,
_: &Self::Settings,
load_context: &mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
// Deserialize a `SerializedAnimationGraph` directly, so that we can
// get the list of the animation clips it refers to and load them.
let mut deserializer = ron::de::Deserializer::from_bytes(&bytes)?;
let serialized_animation_graph = SerializedAnimationGraph::deserialize(&mut deserializer)
.map_err(|err| deserializer.span_error(err))?;
// Load all `AssetPath`s to convert from a `SerializedAnimationGraph` to a real
// `AnimationGraph`. This is effectively a `DiGraph::map`, but this allows us to return
// errors.
let mut animation_graph = DiGraph::with_capacity(
serialized_animation_graph.graph.node_count(),
serialized_animation_graph.graph.edge_count(),
);
for serialized_node in serialized_animation_graph.graph.node_weights() {
animation_graph.add_node(AnimationGraphNode {
node_type: match serialized_node.node_type {
SerializedAnimationNodeType::Clip(ref path) => {
AnimationNodeType::Clip(load_context.load(path.clone()))
}
SerializedAnimationNodeType::Blend => AnimationNodeType::Blend,
SerializedAnimationNodeType::Add => AnimationNodeType::Add,
},
mask: serialized_node.mask,
weight: serialized_node.weight,
});
}
for edge in serialized_animation_graph.graph.raw_edges() {
animation_graph.add_edge(edge.source(), edge.target(), ());
}
Ok(AnimationGraph {
graph: animation_graph,
root: serialized_animation_graph.root,
mask_groups: serialized_animation_graph.mask_groups,
})
}
fn extensions(&self) -> &[&str] {
&["animgraph", "animgraph.ron"]
}
}
impl TryFrom<AnimationGraph> for SerializedAnimationGraph {
type Error = NonPathHandleError;
fn try_from(animation_graph: AnimationGraph) -> Result<Self, NonPathHandleError> {
// Convert all the `Handle<AnimationClip>` to AssetPath, so that
// `AnimationGraphAssetLoader` can load them. This is effectively just doing a
// `DiGraph::map`, except we need to return an error if any handles aren't associated to a
// path.
let mut serialized_graph = DiGraph::with_capacity(
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_color/src/lib.rs | crates/bevy_color/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]
//! Representations of colors in various color spaces.
//!
//! This crate provides a number of color representations, including:
//!
//! - [`Srgba`] (standard RGBA, with gamma correction)
//! - [`LinearRgba`] (linear RGBA, without gamma correction)
//! - [`Hsla`] (hue, saturation, lightness, alpha)
//! - [`Hsva`] (hue, saturation, value, alpha)
//! - [`Hwba`] (hue, whiteness, blackness, alpha)
//! - [`Laba`] (lightness, a-axis, b-axis, alpha)
//! - [`Lcha`] (lightness, chroma, hue, alpha)
//! - [`Oklaba`] (lightness, a-axis, b-axis, alpha)
//! - [`Oklcha`] (lightness, chroma, hue, alpha)
//! - [`Xyza`] (x-axis, y-axis, z-axis, alpha)
//!
//! Each of these color spaces is represented as a distinct Rust type.
//!
//! # Color Space Usage
//!
//! Rendering engines typically use linear RGBA colors, which allow for physically accurate
//! lighting calculations. However, linear RGBA colors are not perceptually uniform, because
//! both human eyes and computer monitors have non-linear responses to light. "Standard" RGBA
//! represents an industry-wide compromise designed to encode colors in a way that looks good to
//! humans in as few bits as possible, but it is not suitable for lighting calculations.
//!
//! Most image file formats and scene graph formats use standard RGBA, because graphic design
//! tools are intended to be used by humans. However, 3D lighting calculations operate in linear
//! RGBA, so it is important to convert standard colors to linear before sending them to the GPU.
//! Most Bevy APIs will handle this conversion automatically, but if you are writing a custom
//! shader, you will need to do this conversion yourself.
//!
//! HSL and LCH are "cylindrical" color spaces, which means they represent colors as a combination
//! of hue, saturation, and lightness (or chroma). These color spaces are useful for working
//! with colors in an artistic way - for example, when creating gradients or color palettes.
//! A gradient in HSL space from red to violet will produce a rainbow. The LCH color space is
//! more perceptually accurate than HSL, but is less intuitive to work with.
//!
//! HSV and HWB are very closely related to HSL in their derivation, having identical definitions for
//! hue. Where HSL uses saturation and lightness, HSV uses a slightly modified definition of saturation,
//! and an analog of lightness in the form of value. In contrast, HWB instead uses whiteness and blackness
//! parameters, which can be used to lighten and darken a particular hue respectively.
//!
//! Oklab and Oklch are perceptually uniform color spaces that are designed to be used for tasks such
//! as image processing. They are not as widely used as the other color spaces, but are useful
//! for tasks such as color correction and image analysis, where it is important to be able
//! to do things like change color saturation without causing hue shifts.
//!
//! XYZ is a foundational space commonly used in the definition of other more modern color
//! spaces. The space is more formally known as CIE 1931, where the `x` and `z` axes represent
//! a form of chromaticity, while `y` defines an illuminance level.
//!
//! See also the [Wikipedia article on color spaces](https://en.wikipedia.org/wiki/Color_space).
#![doc = include_str!("../docs/conversion.md")]
//! <div>
#![doc = include_str!("../docs/diagrams/model_graph.svg")]
//! </div>
//!
//! # Other Utilities
//!
//! The crate also provides a number of color operations, such as blending, color difference,
//! and color range operations.
//!
//! In addition, there is a [`Color`] enum that can represent any of the color
//! types in this crate. This is useful when you need to store a color in a data structure
//! that can't be generic over the color type.
//!
//! Color types that are either physically or perceptually linear also implement `Add<Self>`, `Sub<Self>`, `Mul<f32>` and `Div<f32>`
//! allowing you to use them with splines.
//!
//! Please note that most often adding or subtracting colors is not what you may want.
//! Please have a look at other operations like blending, lightening or mixing colors using e.g. [`Mix`] or [`Luminance`] instead.
//!
//! # Example
//!
//! ```
//! use bevy_color::{Srgba, Hsla};
//!
//! let srgba = Srgba::new(0.5, 0.2, 0.8, 1.0);
//! let hsla: Hsla = srgba.into();
//!
//! println!("Srgba: {:?}", srgba);
//! println!("Hsla: {:?}", hsla);
//! ```
#[cfg(feature = "std")]
extern crate std;
#[cfg(feature = "alloc")]
extern crate alloc;
mod color;
pub mod color_difference;
#[cfg(feature = "alloc")]
mod color_gradient;
mod color_ops;
mod color_range;
mod hsla;
mod hsva;
mod hwba;
mod interpolate;
mod laba;
mod lcha;
mod linear_rgba;
mod oklaba;
mod oklcha;
pub mod palettes;
mod srgba;
#[cfg(test)]
mod test_colors;
#[cfg(test)]
mod testing;
mod xyza;
/// The color prelude.
///
/// This includes the most common types in this crate, re-exported for your convenience.
pub mod prelude {
pub use crate::{
color::*, color_ops::*, hsla::*, hsva::*, hwba::*, laba::*, lcha::*, linear_rgba::*,
oklaba::*, oklcha::*, srgba::*, xyza::*,
};
}
pub use color::*;
#[cfg(feature = "alloc")]
pub use color_gradient::*;
pub use color_ops::*;
pub use color_range::*;
pub use hsla::*;
pub use hsva::*;
pub use hwba::*;
pub use laba::*;
pub use lcha::*;
pub use linear_rgba::*;
pub use oklaba::*;
pub use oklcha::*;
pub use srgba::*;
pub use xyza::*;
/// Describes the traits that a color should implement for consistency.
#[expect(
clippy::allow_attributes,
reason = "If the below attribute on `dead_code` is removed, then rustc complains that `StandardColor` is dead code. However, if we `expect` the `dead_code` lint, then rustc complains of an unfulfilled expectation."
)]
#[allow(
dead_code,
reason = "This is an internal marker trait used to ensure that our color types impl the required traits"
)]
pub(crate) trait StandardColor
where
Self: core::fmt::Debug,
Self: Clone + Copy,
Self: PartialEq,
Self: Default,
Self: From<Color> + Into<Color>,
Self: From<Srgba> + Into<Srgba>,
Self: From<LinearRgba> + Into<LinearRgba>,
Self: From<Hsla> + Into<Hsla>,
Self: From<Hsva> + Into<Hsva>,
Self: From<Hwba> + Into<Hwba>,
Self: From<Laba> + Into<Laba>,
Self: From<Lcha> + Into<Lcha>,
Self: From<Oklaba> + Into<Oklaba>,
Self: From<Oklcha> + Into<Oklcha>,
Self: From<Xyza> + Into<Xyza>,
Self: Alpha,
{
}
macro_rules! impl_componentwise_vector_space {
($ty: ident, [$($element: ident),+]) => {
impl core::ops::Add<Self> for $ty {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self::Output {
$($element: self.$element + rhs.$element,)+
}
}
}
impl core::ops::AddAssign<Self> for $ty {
fn add_assign(&mut self, rhs: Self) {
*self = *self + rhs;
}
}
impl core::ops::Neg for $ty {
type Output = Self;
fn neg(self) -> Self::Output {
Self::Output {
$($element: -self.$element,)+
}
}
}
impl core::ops::Sub<Self> for $ty {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
Self::Output {
$($element: self.$element - rhs.$element,)+
}
}
}
impl core::ops::SubAssign<Self> for $ty {
fn sub_assign(&mut self, rhs: Self) {
*self = *self - rhs;
}
}
impl core::ops::Mul<f32> for $ty {
type Output = Self;
fn mul(self, rhs: f32) -> Self::Output {
Self::Output {
$($element: self.$element * rhs,)+
}
}
}
impl core::ops::Mul<$ty> for f32 {
type Output = $ty;
fn mul(self, rhs: $ty) -> Self::Output {
Self::Output {
$($element: self * rhs.$element,)+
}
}
}
impl core::ops::MulAssign<f32> for $ty {
fn mul_assign(&mut self, rhs: f32) {
*self = *self * rhs;
}
}
impl core::ops::Div<f32> for $ty {
type Output = Self;
fn div(self, rhs: f32) -> Self::Output {
Self::Output {
$($element: self.$element / rhs,)+
}
}
}
impl core::ops::DivAssign<f32> for $ty {
fn div_assign(&mut self, rhs: f32) {
*self = *self / rhs;
}
}
impl bevy_math::VectorSpace for $ty {
type Scalar = f32;
const ZERO: Self = Self {
$($element: 0.0,)+
};
}
impl bevy_math::StableInterpolate for $ty {
fn interpolate_stable(&self, other: &Self, t: f32) -> Self {
bevy_math::VectorSpace::lerp(*self, *other, t)
}
}
};
}
pub(crate) use impl_componentwise_vector_space;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_color/src/oklaba.rs | crates/bevy_color/src/oklaba.rs | use crate::{
color_difference::EuclideanDistance, impl_componentwise_vector_space, Alpha, ColorToComponents,
Gray, Hsla, Hsva, Hwba, Lcha, LinearRgba, Luminance, Mix, Srgba, StandardColor, Xyza,
};
use bevy_math::{ops, FloatPow, Vec3, Vec4};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::prelude::*;
/// Color in Oklab color space, with alpha
#[doc = include_str!("../docs/conversion.md")]
/// <div>
#[doc = include_str!("../docs/diagrams/model_graph.svg")]
/// </div>
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Clone, PartialEq, Default)
)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Oklaba {
/// The 'lightness' channel. [0.0, 1.0]
pub lightness: f32,
/// The 'a' channel. [-1.0, 1.0]
pub a: f32,
/// The 'b' channel. [-1.0, 1.0]
pub b: f32,
/// The alpha channel. [0.0, 1.0]
pub alpha: f32,
}
impl StandardColor for Oklaba {}
impl_componentwise_vector_space!(Oklaba, [lightness, a, b, alpha]);
impl Oklaba {
/// Construct a new [`Oklaba`] color from components.
///
/// # Arguments
///
/// * `lightness` - Lightness channel. [0.0, 1.0]
/// * `a` - Green-red channel. [-1.0, 1.0]
/// * `b` - Blue-yellow channel. [-1.0, 1.0]
/// * `alpha` - Alpha channel. [0.0, 1.0]
pub const fn new(lightness: f32, a: f32, b: f32, alpha: f32) -> Self {
Self {
lightness,
a,
b,
alpha,
}
}
/// Construct a new [`Oklaba`] color from (l, a, b) components, with the default alpha (1.0).
///
/// # Arguments
///
/// * `lightness` - Lightness channel. [0.0, 1.0]
/// * `a` - Green-red channel. [-1.0, 1.0]
/// * `b` - Blue-yellow channel. [-1.0, 1.0]
pub const fn lab(lightness: f32, a: f32, b: f32) -> Self {
Self {
lightness,
a,
b,
alpha: 1.0,
}
}
/// Return a copy of this color with the 'lightness' channel set to the given value.
pub const fn with_lightness(self, lightness: f32) -> Self {
Self { lightness, ..self }
}
/// Return a copy of this color with the 'a' channel set to the given value.
pub const fn with_a(self, a: f32) -> Self {
Self { a, ..self }
}
/// Return a copy of this color with the 'b' channel set to the given value.
pub const fn with_b(self, b: f32) -> Self {
Self { b, ..self }
}
}
impl Default for Oklaba {
fn default() -> Self {
Self::new(1., 0., 0., 1.)
}
}
impl Mix for Oklaba {
#[inline]
fn mix(&self, other: &Self, factor: f32) -> Self {
let n_factor = 1.0 - factor;
Self {
lightness: self.lightness * n_factor + other.lightness * factor,
a: self.a * n_factor + other.a * factor,
b: self.b * n_factor + other.b * factor,
alpha: self.alpha * n_factor + other.alpha * factor,
}
}
}
impl Gray for Oklaba {
const BLACK: Self = Self::new(0., 0., 0., 1.);
const WHITE: Self = Self::new(1.0, 0.0, 0.000000059604645, 1.0);
}
impl Alpha for Oklaba {
#[inline]
fn with_alpha(&self, alpha: f32) -> Self {
Self { alpha, ..*self }
}
#[inline]
fn alpha(&self) -> f32 {
self.alpha
}
#[inline]
fn set_alpha(&mut self, alpha: f32) {
self.alpha = alpha;
}
}
impl Luminance for Oklaba {
#[inline]
fn with_luminance(&self, lightness: f32) -> Self {
Self { lightness, ..*self }
}
fn luminance(&self) -> f32 {
self.lightness
}
fn darker(&self, amount: f32) -> Self {
Self::new(
(self.lightness - amount).max(0.),
self.a,
self.b,
self.alpha,
)
}
fn lighter(&self, amount: f32) -> Self {
Self::new(
(self.lightness + amount).min(1.),
self.a,
self.b,
self.alpha,
)
}
}
impl EuclideanDistance for Oklaba {
#[inline]
fn distance_squared(&self, other: &Self) -> f32 {
(self.lightness - other.lightness).squared()
+ (self.a - other.a).squared()
+ (self.b - other.b).squared()
}
}
impl ColorToComponents for Oklaba {
fn to_f32_array(self) -> [f32; 4] {
[self.lightness, self.a, self.b, self.alpha]
}
fn to_f32_array_no_alpha(self) -> [f32; 3] {
[self.lightness, self.a, self.b]
}
fn to_vec4(self) -> Vec4 {
Vec4::new(self.lightness, self.a, self.b, self.alpha)
}
fn to_vec3(self) -> Vec3 {
Vec3::new(self.lightness, self.a, self.b)
}
fn from_f32_array(color: [f32; 4]) -> Self {
Self {
lightness: color[0],
a: color[1],
b: color[2],
alpha: color[3],
}
}
fn from_f32_array_no_alpha(color: [f32; 3]) -> Self {
Self {
lightness: color[0],
a: color[1],
b: color[2],
alpha: 1.0,
}
}
fn from_vec4(color: Vec4) -> Self {
Self {
lightness: color[0],
a: color[1],
b: color[2],
alpha: color[3],
}
}
fn from_vec3(color: Vec3) -> Self {
Self {
lightness: color[0],
a: color[1],
b: color[2],
alpha: 1.0,
}
}
}
impl From<LinearRgba> for Oklaba {
fn from(value: LinearRgba) -> Self {
let LinearRgba {
red,
green,
blue,
alpha,
} = value;
// From https://bottosson.github.io/posts/oklab/#converting-from-linear-srgb-to-oklab
// Float literals are truncated to avoid excessive precision.
let l = 0.41222146 * red + 0.53633255 * green + 0.051445995 * blue;
let m = 0.2119035 * red + 0.6806995 * green + 0.10739696 * blue;
let s = 0.08830246 * red + 0.28171885 * green + 0.6299787 * blue;
let l_ = ops::cbrt(l);
let m_ = ops::cbrt(m);
let s_ = ops::cbrt(s);
let l = 0.21045426 * l_ + 0.7936178 * m_ - 0.004072047 * s_;
let a = 1.9779985 * l_ - 2.4285922 * m_ + 0.4505937 * s_;
let b = 0.025904037 * l_ + 0.78277177 * m_ - 0.80867577 * s_;
Oklaba::new(l, a, b, alpha)
}
}
impl From<Oklaba> for LinearRgba {
fn from(value: Oklaba) -> Self {
let Oklaba {
lightness,
a,
b,
alpha,
} = value;
// From https://bottosson.github.io/posts/oklab/#converting-from-linear-srgb-to-oklab
// Float literals are truncated to avoid excessive precision.
let l_ = lightness + 0.39633778 * a + 0.21580376 * b;
let m_ = lightness - 0.105561346 * a - 0.06385417 * b;
let s_ = lightness - 0.08948418 * a - 1.2914855 * b;
let l = l_ * l_ * l_;
let m = m_ * m_ * m_;
let s = s_ * s_ * s_;
let red = 4.0767417 * l - 3.3077116 * m + 0.23096994 * s;
let green = -1.268438 * l + 2.6097574 * m - 0.34131938 * s;
let blue = -0.0041960863 * l - 0.7034186 * m + 1.7076147 * s;
Self {
red,
green,
blue,
alpha,
}
}
}
// Derived Conversions
impl From<Hsla> for Oklaba {
fn from(value: Hsla) -> Self {
LinearRgba::from(value).into()
}
}
impl From<Oklaba> for Hsla {
fn from(value: Oklaba) -> Self {
LinearRgba::from(value).into()
}
}
impl From<Hsva> for Oklaba {
fn from(value: Hsva) -> Self {
LinearRgba::from(value).into()
}
}
impl From<Oklaba> for Hsva {
fn from(value: Oklaba) -> Self {
LinearRgba::from(value).into()
}
}
impl From<Hwba> for Oklaba {
fn from(value: Hwba) -> Self {
LinearRgba::from(value).into()
}
}
impl From<Oklaba> for Hwba {
fn from(value: Oklaba) -> Self {
LinearRgba::from(value).into()
}
}
impl From<Lcha> for Oklaba {
fn from(value: Lcha) -> Self {
LinearRgba::from(value).into()
}
}
impl From<Oklaba> for Lcha {
fn from(value: Oklaba) -> Self {
LinearRgba::from(value).into()
}
}
impl From<Srgba> for Oklaba {
fn from(value: Srgba) -> Self {
LinearRgba::from(value).into()
}
}
impl From<Oklaba> for Srgba {
fn from(value: Oklaba) -> Self {
LinearRgba::from(value).into()
}
}
impl From<Xyza> for Oklaba {
fn from(value: Xyza) -> Self {
LinearRgba::from(value).into()
}
}
impl From<Oklaba> for Xyza {
fn from(value: Oklaba) -> Self {
LinearRgba::from(value).into()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{test_colors::TEST_COLORS, testing::assert_approx_eq};
#[test]
fn test_to_from_srgba() {
let oklaba = Oklaba::new(0.5, 0.5, 0.5, 1.0);
let srgba: Srgba = oklaba.into();
let oklaba2: Oklaba = srgba.into();
assert_approx_eq!(oklaba.lightness, oklaba2.lightness, 0.001);
assert_approx_eq!(oklaba.a, oklaba2.a, 0.001);
assert_approx_eq!(oklaba.b, oklaba2.b, 0.001);
assert_approx_eq!(oklaba.alpha, oklaba2.alpha, 0.001);
}
#[test]
fn test_to_from_srgba_2() {
for color in TEST_COLORS.iter() {
let rgb2: Srgba = (color.oklab).into();
let oklab: Oklaba = (color.rgb).into();
assert!(
color.rgb.distance(&rgb2) < 0.0001,
"{}: {:?} != {:?}",
color.name,
color.rgb,
rgb2
);
assert!(
color.oklab.distance(&oklab) < 0.0001,
"{}: {:?} != {:?}",
color.name,
color.oklab,
oklab
);
}
}
#[test]
fn test_to_from_linear() {
let oklaba = Oklaba::new(0.5, 0.5, 0.5, 1.0);
let linear: LinearRgba = oklaba.into();
let oklaba2: Oklaba = linear.into();
assert_approx_eq!(oklaba.lightness, oklaba2.lightness, 0.001);
assert_approx_eq!(oklaba.a, oklaba2.a, 0.001);
assert_approx_eq!(oklaba.b, oklaba2.b, 0.001);
assert_approx_eq!(oklaba.alpha, oklaba2.alpha, 0.001);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_color/src/color_range.rs | crates/bevy_color/src/color_range.rs | use core::ops::Range;
use crate::Mix;
/// Represents a range of colors that can be linearly interpolated, defined by a start and
/// end point which must be in the same color space. It works for any color type that
/// implements [`Mix`].
///
/// This is useful for defining gradients or animated color transitions.
pub trait ColorRange<T: Mix> {
/// Get the color value at the given interpolation factor, which should be between 0.0 (start)
/// and 1.0 (end).
fn at(&self, factor: f32) -> T;
}
impl<T: Mix> ColorRange<T> for Range<T> {
fn at(&self, factor: f32) -> T {
self.start.mix(&self.end, factor.clamp(0.0, 1.0))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{palettes::basic, LinearRgba, Srgba};
#[test]
fn test_color_range() {
let range = basic::RED..basic::BLUE;
assert_eq!(range.at(-0.5), basic::RED);
assert_eq!(range.at(0.0), basic::RED);
assert_eq!(range.at(0.5), Srgba::new(0.5, 0.0, 0.5, 1.0));
assert_eq!(range.at(1.0), basic::BLUE);
assert_eq!(range.at(1.5), basic::BLUE);
let lred: LinearRgba = basic::RED.into();
let lblue: LinearRgba = basic::BLUE.into();
let range = lred..lblue;
assert_eq!(range.at(-0.5), lred);
assert_eq!(range.at(0.0), lred);
assert_eq!(range.at(0.5), LinearRgba::new(0.5, 0.0, 0.5, 1.0));
assert_eq!(range.at(1.0), lblue);
assert_eq!(range.at(1.5), lblue);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_color/src/interpolate.rs | crates/bevy_color/src/interpolate.rs | //! TODO: Implement for non-linear colors.
#[cfg(test)]
mod test {
use bevy_math::StableInterpolate;
use crate::{Gray, Laba, LinearRgba, Oklaba, Srgba, Xyza};
#[test]
pub fn test_color_stable_interpolate() {
let b = Srgba::BLACK;
let w = Srgba::WHITE;
assert_eq!(
b.interpolate_stable(&w, 0.5),
Srgba::new(0.5, 0.5, 0.5, 1.0),
);
let b = LinearRgba::BLACK;
let w = LinearRgba::WHITE;
assert_eq!(
b.interpolate_stable(&w, 0.5),
LinearRgba::new(0.5, 0.5, 0.5, 1.0),
);
let b = Xyza::BLACK;
let w = Xyza::WHITE;
assert_eq!(b.interpolate_stable(&w, 0.5), Xyza::gray(0.5),);
let b = Laba::BLACK;
let w = Laba::WHITE;
assert_eq!(b.interpolate_stable(&w, 0.5), Laba::new(0.5, 0.0, 0.0, 1.0),);
let b = Oklaba::BLACK;
let w = Oklaba::WHITE;
assert_eq!(b.interpolate_stable(&w, 0.5), Oklaba::gray(0.5),);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_color/src/color_difference.rs | crates/bevy_color/src/color_difference.rs | //! Module for calculating distance between two colors in the same color space.
use bevy_math::ops;
/// Calculate the distance between this and another color as if they were coordinates
/// in a Euclidean space. Alpha is not considered in the distance calculation.
pub trait EuclideanDistance: Sized {
/// Distance from `self` to `other`.
fn distance(&self, other: &Self) -> f32 {
ops::sqrt(self.distance_squared(other))
}
/// Distance squared from `self` to `other`.
fn distance_squared(&self, other: &Self) -> f32;
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_color/src/hwba.rs | crates/bevy_color/src/hwba.rs | //! Implementation of the Hue-Whiteness-Blackness (HWB) color model as described
//! in [_HWB - A More Intuitive Hue-Based Color Model_] by _Smith et al_.
//!
//! [_HWB - A More Intuitive Hue-Based Color Model_]: https://web.archive.org/web/20240226005220/http://alvyray.com/Papers/CG/HWB_JGTv208.pdf
use crate::{
Alpha, ColorToComponents, Gray, Hue, Lcha, LinearRgba, Mix, Srgba, StandardColor, Xyza,
};
use bevy_math::{ops, Vec3, Vec4};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::prelude::*;
/// Color in Hue-Whiteness-Blackness (HWB) color space with alpha.
/// Further information on this color model can be found on [Wikipedia](https://en.wikipedia.org/wiki/HWB_color_model).
#[doc = include_str!("../docs/conversion.md")]
/// <div>
#[doc = include_str!("../docs/diagrams/model_graph.svg")]
/// </div>
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Clone, PartialEq, Default)
)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Hwba {
/// The hue channel. [0.0, 360.0]
pub hue: f32,
/// The whiteness channel. [0.0, 1.0]
pub whiteness: f32,
/// The blackness channel. [0.0, 1.0]
pub blackness: f32,
/// The alpha channel. [0.0, 1.0]
pub alpha: f32,
}
impl StandardColor for Hwba {}
impl Hwba {
/// Construct a new [`Hwba`] color from components.
///
/// # Arguments
///
/// * `hue` - Hue channel. [0.0, 360.0]
/// * `whiteness` - Whiteness channel. [0.0, 1.0]
/// * `blackness` - Blackness channel. [0.0, 1.0]
/// * `alpha` - Alpha channel. [0.0, 1.0]
pub const fn new(hue: f32, whiteness: f32, blackness: f32, alpha: f32) -> Self {
Self {
hue,
whiteness,
blackness,
alpha,
}
}
/// Construct a new [`Hwba`] color from (h, s, l) components, with the default alpha (1.0).
///
/// # Arguments
///
/// * `hue` - Hue channel. [0.0, 360.0]
/// * `whiteness` - Whiteness channel. [0.0, 1.0]
/// * `blackness` - Blackness channel. [0.0, 1.0]
pub const fn hwb(hue: f32, whiteness: f32, blackness: f32) -> Self {
Self::new(hue, whiteness, blackness, 1.0)
}
/// Return a copy of this color with the whiteness channel set to the given value.
pub const fn with_whiteness(self, whiteness: f32) -> Self {
Self { whiteness, ..self }
}
/// Return a copy of this color with the blackness channel set to the given value.
pub const fn with_blackness(self, blackness: f32) -> Self {
Self { blackness, ..self }
}
}
impl Default for Hwba {
fn default() -> Self {
Self::new(0., 0., 1., 1.)
}
}
impl Mix for Hwba {
#[inline]
fn mix(&self, other: &Self, factor: f32) -> Self {
let n_factor = 1.0 - factor;
Self {
hue: crate::color_ops::lerp_hue(self.hue, other.hue, factor),
whiteness: self.whiteness * n_factor + other.whiteness * factor,
blackness: self.blackness * n_factor + other.blackness * factor,
alpha: self.alpha * n_factor + other.alpha * factor,
}
}
}
impl Gray for Hwba {
const BLACK: Self = Self::new(0., 0., 1., 1.);
const WHITE: Self = Self::new(0., 1., 0., 1.);
}
impl Alpha for Hwba {
#[inline]
fn with_alpha(&self, alpha: f32) -> Self {
Self { alpha, ..*self }
}
#[inline]
fn alpha(&self) -> f32 {
self.alpha
}
#[inline]
fn set_alpha(&mut self, alpha: f32) {
self.alpha = alpha;
}
}
impl Hue for Hwba {
#[inline]
fn with_hue(&self, hue: f32) -> Self {
Self { hue, ..*self }
}
#[inline]
fn hue(&self) -> f32 {
self.hue
}
#[inline]
fn set_hue(&mut self, hue: f32) {
self.hue = hue;
}
}
impl ColorToComponents for Hwba {
fn to_f32_array(self) -> [f32; 4] {
[self.hue, self.whiteness, self.blackness, self.alpha]
}
fn to_f32_array_no_alpha(self) -> [f32; 3] {
[self.hue, self.whiteness, self.blackness]
}
fn to_vec4(self) -> Vec4 {
Vec4::new(self.hue, self.whiteness, self.blackness, self.alpha)
}
fn to_vec3(self) -> Vec3 {
Vec3::new(self.hue, self.whiteness, self.blackness)
}
fn from_f32_array(color: [f32; 4]) -> Self {
Self {
hue: color[0],
whiteness: color[1],
blackness: color[2],
alpha: color[3],
}
}
fn from_f32_array_no_alpha(color: [f32; 3]) -> Self {
Self {
hue: color[0],
whiteness: color[1],
blackness: color[2],
alpha: 1.0,
}
}
fn from_vec4(color: Vec4) -> Self {
Self {
hue: color[0],
whiteness: color[1],
blackness: color[2],
alpha: color[3],
}
}
fn from_vec3(color: Vec3) -> Self {
Self {
hue: color[0],
whiteness: color[1],
blackness: color[2],
alpha: 1.0,
}
}
}
impl From<Srgba> for Hwba {
fn from(
Srgba {
red,
green,
blue,
alpha,
}: Srgba,
) -> Self {
// Based on "HWB - A More Intuitive Hue-Based Color Model" Appendix B
let x_max = 0f32.max(red).max(green).max(blue);
let x_min = 1f32.min(red).min(green).min(blue);
let chroma = x_max - x_min;
let hue = if chroma == 0.0 {
0.0
} else if red == x_max {
60.0 * (green - blue) / chroma
} else if green == x_max {
60.0 * (2.0 + (blue - red) / chroma)
} else {
60.0 * (4.0 + (red - green) / chroma)
};
let hue = if hue < 0.0 { 360.0 + hue } else { hue };
let whiteness = x_min;
let blackness = 1.0 - x_max;
Hwba {
hue,
whiteness,
blackness,
alpha,
}
}
}
impl From<Hwba> for Srgba {
fn from(
Hwba {
hue,
whiteness,
blackness,
alpha,
}: Hwba,
) -> Self {
// Based on "HWB - A More Intuitive Hue-Based Color Model" Appendix B
let w = whiteness;
let v = 1. - blackness;
let h = (hue % 360.) / 60.;
let i = ops::floor(h);
let f = h - i;
let i = i as u8;
let f = if i % 2 == 0 { f } else { 1. - f };
let n = w + f * (v - w);
let (red, green, blue) = match i {
0 => (v, n, w),
1 => (n, v, w),
2 => (w, v, n),
3 => (w, n, v),
4 => (n, w, v),
5 => (v, w, n),
_ => unreachable!("i is bounded in [0, 6)"),
};
Srgba::new(red, green, blue, alpha)
}
}
// Derived Conversions
impl From<LinearRgba> for Hwba {
fn from(value: LinearRgba) -> Self {
Srgba::from(value).into()
}
}
impl From<Hwba> for LinearRgba {
fn from(value: Hwba) -> Self {
Srgba::from(value).into()
}
}
impl From<Lcha> for Hwba {
fn from(value: Lcha) -> Self {
Srgba::from(value).into()
}
}
impl From<Hwba> for Lcha {
fn from(value: Hwba) -> Self {
Srgba::from(value).into()
}
}
impl From<Xyza> for Hwba {
fn from(value: Xyza) -> Self {
Srgba::from(value).into()
}
}
impl From<Hwba> for Xyza {
fn from(value: Hwba) -> Self {
Srgba::from(value).into()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
color_difference::EuclideanDistance, test_colors::TEST_COLORS, testing::assert_approx_eq,
};
#[test]
fn test_to_from_srgba() {
let hwba = Hwba::new(0.0, 0.5, 0.5, 1.0);
let srgba: Srgba = hwba.into();
let hwba2: Hwba = srgba.into();
assert_approx_eq!(hwba.hue, hwba2.hue, 0.001);
assert_approx_eq!(hwba.whiteness, hwba2.whiteness, 0.001);
assert_approx_eq!(hwba.blackness, hwba2.blackness, 0.001);
assert_approx_eq!(hwba.alpha, hwba2.alpha, 0.001);
}
#[test]
fn test_to_from_srgba_2() {
for color in TEST_COLORS.iter() {
let rgb2: Srgba = (color.hwb).into();
let hwb2: Hwba = (color.rgb).into();
assert!(
color.rgb.distance(&rgb2) < 0.00001,
"{}: {:?} != {:?}",
color.name,
color.rgb,
rgb2
);
assert_approx_eq!(color.hwb.hue, hwb2.hue, 0.001);
assert_approx_eq!(color.hwb.whiteness, hwb2.whiteness, 0.001);
assert_approx_eq!(color.hwb.blackness, hwb2.blackness, 0.001);
assert_approx_eq!(color.hwb.alpha, hwb2.alpha, 0.001);
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_color/src/color_ops.rs | crates/bevy_color/src/color_ops.rs | use bevy_math::{ops, Vec3, Vec4};
/// Methods for changing the luminance of a color. Note that these methods are not
/// guaranteed to produce consistent results across color spaces,
/// but will be within a given space.
pub trait Luminance: Sized {
/// Return the luminance of this color (0.0 - 1.0).
fn luminance(&self) -> f32;
/// Return a new version of this color with the given luminance. The resulting color will
/// be clamped to the valid range for the color space; for some color spaces, clamping
/// may cause the hue or chroma to change.
fn with_luminance(&self, value: f32) -> Self;
/// Return a darker version of this color. The `amount` should be between 0.0 and 1.0.
/// The amount represents an absolute decrease in luminance, and is distributive:
/// `color.darker(a).darker(b) == color.darker(a + b)`. Colors are clamped to black
/// if the amount would cause them to go below black.
///
/// For a relative decrease in luminance, you can simply `mix()` with black.
fn darker(&self, amount: f32) -> Self;
/// Return a lighter version of this color. The `amount` should be between 0.0 and 1.0.
/// The amount represents an absolute increase in luminance, and is distributive:
/// `color.lighter(a).lighter(b) == color.lighter(a + b)`. Colors are clamped to white
/// if the amount would cause them to go above white.
///
/// For a relative increase in luminance, you can simply `mix()` with white.
fn lighter(&self, amount: f32) -> Self;
}
/// Linear interpolation of two colors within a given color space.
pub trait Mix: Sized {
/// Linearly interpolate between this and another color, by factor.
/// Factor should be between 0.0 and 1.0.
fn mix(&self, other: &Self, factor: f32) -> Self;
/// Linearly interpolate between this and another color, by factor, storing the result
/// in this color. Factor should be between 0.0 and 1.0.
fn mix_assign(&mut self, other: Self, factor: f32) {
*self = self.mix(&other, factor);
}
}
/// Trait for returning a grayscale color of a provided lightness.
pub trait Gray: Mix + Sized {
/// A pure black color.
const BLACK: Self;
/// A pure white color.
const WHITE: Self;
/// Returns a grey color with the provided lightness from (0.0 - 1.0). 0 is black, 1 is white.
fn gray(lightness: f32) -> Self {
Self::BLACK.mix(&Self::WHITE, lightness)
}
}
/// Methods for manipulating alpha values.
pub trait Alpha: Sized {
/// Return a new version of this color with the given alpha value.
fn with_alpha(&self, alpha: f32) -> Self;
/// Return the alpha component of this color.
fn alpha(&self) -> f32;
/// Sets the alpha component of this color.
fn set_alpha(&mut self, alpha: f32);
/// Is the alpha component of this color less than or equal to 0.0?
fn is_fully_transparent(&self) -> bool {
self.alpha() <= 0.0
}
/// Is the alpha component of this color greater than or equal to 1.0?
fn is_fully_opaque(&self) -> bool {
self.alpha() >= 1.0
}
}
impl Alpha for f32 {
fn with_alpha(&self, alpha: f32) -> Self {
alpha
}
fn alpha(&self) -> f32 {
*self
}
fn set_alpha(&mut self, alpha: f32) {
*self = alpha;
}
}
/// Trait for manipulating the hue of a color.
pub trait Hue: Sized {
/// Return a new version of this color with the hue channel set to the given value.
fn with_hue(&self, hue: f32) -> Self;
/// Return the hue of this color [0.0, 360.0].
fn hue(&self) -> f32;
/// Sets the hue of this color.
fn set_hue(&mut self, hue: f32);
/// Return a new version of this color with the hue channel rotated by the given degrees.
fn rotate_hue(&self, degrees: f32) -> Self {
let rotated_hue = ops::rem_euclid(self.hue() + degrees, 360.);
self.with_hue(rotated_hue)
}
}
/// Trait for manipulating the saturation of a color.
///
/// When working with color spaces that do not have native saturation components
/// the operations are performed in [`Hsla`](`crate::Hsla`).
pub trait Saturation: Sized {
/// Return a new version of this color with the saturation channel set to the given value.
fn with_saturation(&self, saturation: f32) -> Self;
/// Return the saturation of this color [0.0, 1.0].
fn saturation(&self) -> f32;
/// Sets the saturation of this color.
fn set_saturation(&mut self, saturation: f32);
}
/// Trait with methods for converting colors to non-color types
pub trait ColorToComponents {
/// Convert to an f32 array
fn to_f32_array(self) -> [f32; 4];
/// Convert to an f32 array without the alpha value
fn to_f32_array_no_alpha(self) -> [f32; 3];
/// Convert to a Vec4
fn to_vec4(self) -> Vec4;
/// Convert to a Vec3
fn to_vec3(self) -> Vec3;
/// Convert from an f32 array
fn from_f32_array(color: [f32; 4]) -> Self;
/// Convert from an f32 array without the alpha value
fn from_f32_array_no_alpha(color: [f32; 3]) -> Self;
/// Convert from a Vec4
fn from_vec4(color: Vec4) -> Self;
/// Convert from a Vec3
fn from_vec3(color: Vec3) -> Self;
}
/// Trait with methods for converting colors to packed non-color types
pub trait ColorToPacked {
/// Convert to [u8; 4] where that makes sense (Srgba is most relevant)
fn to_u8_array(self) -> [u8; 4];
/// Convert to [u8; 3] where that makes sense (Srgba is most relevant)
fn to_u8_array_no_alpha(self) -> [u8; 3];
/// Convert from [u8; 4] where that makes sense (Srgba is most relevant)
fn from_u8_array(color: [u8; 4]) -> Self;
/// Convert to [u8; 3] where that makes sense (Srgba is most relevant)
fn from_u8_array_no_alpha(color: [u8; 3]) -> Self;
}
/// Utility function for interpolating hue values. This ensures that the interpolation
/// takes the shortest path around the color wheel, and that the result is always between
/// 0 and 360.
pub(crate) fn lerp_hue(a: f32, b: f32, t: f32) -> f32 {
let diff = ops::rem_euclid(b - a + 180.0, 360.) - 180.;
ops::rem_euclid(a + diff * t, 360.)
}
#[cfg(test)]
mod tests {
use core::fmt::Debug;
use super::*;
use crate::{testing::assert_approx_eq, Hsla};
#[test]
fn test_rotate_hue() {
let hsla = Hsla::hsl(180.0, 1.0, 0.5);
assert_eq!(hsla.rotate_hue(90.0), Hsla::hsl(270.0, 1.0, 0.5));
assert_eq!(hsla.rotate_hue(-90.0), Hsla::hsl(90.0, 1.0, 0.5));
assert_eq!(hsla.rotate_hue(180.0), Hsla::hsl(0.0, 1.0, 0.5));
assert_eq!(hsla.rotate_hue(-180.0), Hsla::hsl(0.0, 1.0, 0.5));
assert_eq!(hsla.rotate_hue(0.0), hsla);
assert_eq!(hsla.rotate_hue(360.0), hsla);
assert_eq!(hsla.rotate_hue(-360.0), hsla);
}
#[test]
fn test_hue_wrap() {
assert_approx_eq!(lerp_hue(10., 20., 0.25), 12.5, 0.001);
assert_approx_eq!(lerp_hue(10., 20., 0.5), 15., 0.001);
assert_approx_eq!(lerp_hue(10., 20., 0.75), 17.5, 0.001);
assert_approx_eq!(lerp_hue(20., 10., 0.25), 17.5, 0.001);
assert_approx_eq!(lerp_hue(20., 10., 0.5), 15., 0.001);
assert_approx_eq!(lerp_hue(20., 10., 0.75), 12.5, 0.001);
assert_approx_eq!(lerp_hue(10., 350., 0.25), 5., 0.001);
assert_approx_eq!(lerp_hue(10., 350., 0.5), 0., 0.001);
assert_approx_eq!(lerp_hue(10., 350., 0.75), 355., 0.001);
assert_approx_eq!(lerp_hue(350., 10., 0.25), 355., 0.001);
assert_approx_eq!(lerp_hue(350., 10., 0.5), 0., 0.001);
assert_approx_eq!(lerp_hue(350., 10., 0.75), 5., 0.001);
}
fn verify_gray<Col>()
where
Col: Gray + Debug + PartialEq,
{
assert_eq!(Col::gray(0.), Col::BLACK);
assert_eq!(Col::gray(1.), Col::WHITE);
}
#[test]
fn test_gray() {
verify_gray::<Hsla>();
verify_gray::<crate::Hsva>();
verify_gray::<crate::Hwba>();
verify_gray::<crate::Laba>();
verify_gray::<crate::Lcha>();
verify_gray::<crate::LinearRgba>();
verify_gray::<crate::Oklaba>();
verify_gray::<crate::Oklcha>();
verify_gray::<crate::Xyza>();
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_color/src/hsva.rs | crates/bevy_color/src/hsva.rs | use crate::{
Alpha, ColorToComponents, Gray, Hue, Hwba, Lcha, LinearRgba, Mix, Saturation, Srgba,
StandardColor, Xyza,
};
use bevy_math::{Vec3, Vec4};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::prelude::*;
/// Color in Hue-Saturation-Value (HSV) color space with alpha.
/// Further information on this color model can be found on [Wikipedia](https://en.wikipedia.org/wiki/HSL_and_HSV).
#[doc = include_str!("../docs/conversion.md")]
/// <div>
#[doc = include_str!("../docs/diagrams/model_graph.svg")]
/// </div>
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Clone, PartialEq, Default)
)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Hsva {
/// The hue channel. [0.0, 360.0]
pub hue: f32,
/// The saturation channel. [0.0, 1.0]
pub saturation: f32,
/// The value channel. [0.0, 1.0]
pub value: f32,
/// The alpha channel. [0.0, 1.0]
pub alpha: f32,
}
impl StandardColor for Hsva {}
impl Hsva {
/// Construct a new [`Hsva`] color from components.
///
/// # Arguments
///
/// * `hue` - Hue channel. [0.0, 360.0]
/// * `saturation` - Saturation channel. [0.0, 1.0]
/// * `value` - Value channel. [0.0, 1.0]
/// * `alpha` - Alpha channel. [0.0, 1.0]
pub const fn new(hue: f32, saturation: f32, value: f32, alpha: f32) -> Self {
Self {
hue,
saturation,
value,
alpha,
}
}
/// Construct a new [`Hsva`] color from (h, s, v) components, with the default alpha (1.0).
///
/// # Arguments
///
/// * `hue` - Hue channel. [0.0, 360.0]
/// * `saturation` - Saturation channel. [0.0, 1.0]
/// * `value` - Value channel. [0.0, 1.0]
pub const fn hsv(hue: f32, saturation: f32, value: f32) -> Self {
Self::new(hue, saturation, value, 1.0)
}
/// Return a copy of this color with the saturation channel set to the given value.
pub const fn with_saturation(self, saturation: f32) -> Self {
Self { saturation, ..self }
}
/// Return a copy of this color with the value channel set to the given value.
pub const fn with_value(self, value: f32) -> Self {
Self { value, ..self }
}
}
impl Default for Hsva {
fn default() -> Self {
Self::new(0., 0., 1., 1.)
}
}
impl Mix for Hsva {
#[inline]
fn mix(&self, other: &Self, factor: f32) -> Self {
let n_factor = 1.0 - factor;
Self {
hue: crate::color_ops::lerp_hue(self.hue, other.hue, factor),
saturation: self.saturation * n_factor + other.saturation * factor,
value: self.value * n_factor + other.value * factor,
alpha: self.alpha * n_factor + other.alpha * factor,
}
}
}
impl Gray for Hsva {
const BLACK: Self = Self::new(0., 0., 0., 1.);
const WHITE: Self = Self::new(0., 0., 1., 1.);
}
impl Alpha for Hsva {
#[inline]
fn with_alpha(&self, alpha: f32) -> Self {
Self { alpha, ..*self }
}
#[inline]
fn alpha(&self) -> f32 {
self.alpha
}
#[inline]
fn set_alpha(&mut self, alpha: f32) {
self.alpha = alpha;
}
}
impl Hue for Hsva {
#[inline]
fn with_hue(&self, hue: f32) -> Self {
Self { hue, ..*self }
}
#[inline]
fn hue(&self) -> f32 {
self.hue
}
#[inline]
fn set_hue(&mut self, hue: f32) {
self.hue = hue;
}
}
impl Saturation for Hsva {
#[inline]
fn with_saturation(&self, saturation: f32) -> Self {
Self {
saturation,
..*self
}
}
#[inline]
fn saturation(&self) -> f32 {
self.saturation
}
#[inline]
fn set_saturation(&mut self, saturation: f32) {
self.saturation = saturation;
}
}
impl From<Hsva> for Hwba {
fn from(
Hsva {
hue,
saturation,
value,
alpha,
}: Hsva,
) -> Self {
// Based on https://en.wikipedia.org/wiki/HWB_color_model#Conversion
let whiteness = (1. - saturation) * value;
let blackness = 1. - value;
Hwba::new(hue, whiteness, blackness, alpha)
}
}
impl From<Hwba> for Hsva {
fn from(
Hwba {
hue,
whiteness,
blackness,
alpha,
}: Hwba,
) -> Self {
// Based on https://en.wikipedia.org/wiki/HWB_color_model#Conversion
let value = 1. - blackness;
let saturation = if value != 0. {
1. - (whiteness / value)
} else {
0.
};
Hsva::new(hue, saturation, value, alpha)
}
}
impl ColorToComponents for Hsva {
fn to_f32_array(self) -> [f32; 4] {
[self.hue, self.saturation, self.value, self.alpha]
}
fn to_f32_array_no_alpha(self) -> [f32; 3] {
[self.hue, self.saturation, self.value]
}
fn to_vec4(self) -> Vec4 {
Vec4::new(self.hue, self.saturation, self.value, self.alpha)
}
fn to_vec3(self) -> Vec3 {
Vec3::new(self.hue, self.saturation, self.value)
}
fn from_f32_array(color: [f32; 4]) -> Self {
Self {
hue: color[0],
saturation: color[1],
value: color[2],
alpha: color[3],
}
}
fn from_f32_array_no_alpha(color: [f32; 3]) -> Self {
Self {
hue: color[0],
saturation: color[1],
value: color[2],
alpha: 1.0,
}
}
fn from_vec4(color: Vec4) -> Self {
Self {
hue: color[0],
saturation: color[1],
value: color[2],
alpha: color[3],
}
}
fn from_vec3(color: Vec3) -> Self {
Self {
hue: color[0],
saturation: color[1],
value: color[2],
alpha: 1.0,
}
}
}
// Derived Conversions
impl From<Srgba> for Hsva {
fn from(value: Srgba) -> Self {
Hwba::from(value).into()
}
}
impl From<Hsva> for Srgba {
fn from(value: Hsva) -> Self {
Hwba::from(value).into()
}
}
impl From<LinearRgba> for Hsva {
fn from(value: LinearRgba) -> Self {
Hwba::from(value).into()
}
}
impl From<Hsva> for LinearRgba {
fn from(value: Hsva) -> Self {
Hwba::from(value).into()
}
}
impl From<Lcha> for Hsva {
fn from(value: Lcha) -> Self {
Hwba::from(value).into()
}
}
impl From<Hsva> for Lcha {
fn from(value: Hsva) -> Self {
Hwba::from(value).into()
}
}
impl From<Xyza> for Hsva {
fn from(value: Xyza) -> Self {
Hwba::from(value).into()
}
}
impl From<Hsva> for Xyza {
fn from(value: Hsva) -> Self {
Hwba::from(value).into()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
color_difference::EuclideanDistance, test_colors::TEST_COLORS, testing::assert_approx_eq,
};
#[test]
fn test_to_from_srgba() {
let hsva = Hsva::new(180., 0.5, 0.5, 1.0);
let srgba: Srgba = hsva.into();
let hsva2: Hsva = srgba.into();
assert_approx_eq!(hsva.hue, hsva2.hue, 0.001);
assert_approx_eq!(hsva.saturation, hsva2.saturation, 0.001);
assert_approx_eq!(hsva.value, hsva2.value, 0.001);
assert_approx_eq!(hsva.alpha, hsva2.alpha, 0.001);
}
#[test]
fn test_to_from_srgba_2() {
for color in TEST_COLORS.iter() {
let rgb2: Srgba = (color.hsv).into();
let hsv2: Hsva = (color.rgb).into();
assert!(
color.rgb.distance(&rgb2) < 0.00001,
"{}: {:?} != {:?}",
color.name,
color.rgb,
rgb2
);
assert_approx_eq!(color.hsv.hue, hsv2.hue, 0.001);
assert_approx_eq!(color.hsv.saturation, hsv2.saturation, 0.001);
assert_approx_eq!(color.hsv.value, hsv2.value, 0.001);
assert_approx_eq!(color.hsv.alpha, hsv2.alpha, 0.001);
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_color/src/lcha.rs | crates/bevy_color/src/lcha.rs | use crate::{
Alpha, ColorToComponents, Gray, Hue, Laba, LinearRgba, Luminance, Mix, Srgba, StandardColor,
Xyza,
};
use bevy_math::{ops, Vec3, Vec4};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::prelude::*;
/// Color in LCH color space, with alpha
#[doc = include_str!("../docs/conversion.md")]
/// <div>
#[doc = include_str!("../docs/diagrams/model_graph.svg")]
/// </div>
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Clone, PartialEq, Default)
)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Lcha {
/// The lightness channel. [0.0, 1.5]
pub lightness: f32,
/// The chroma channel. [0.0, 1.5]
pub chroma: f32,
/// The hue channel. [0.0, 360.0]
pub hue: f32,
/// The alpha channel. [0.0, 1.0]
pub alpha: f32,
}
impl StandardColor for Lcha {}
impl Lcha {
/// Construct a new [`Lcha`] color from components.
///
/// # Arguments
///
/// * `lightness` - Lightness channel. [0.0, 1.5]
/// * `chroma` - Chroma channel. [0.0, 1.5]
/// * `hue` - Hue channel. [0.0, 360.0]
/// * `alpha` - Alpha channel. [0.0, 1.0]
pub const fn new(lightness: f32, chroma: f32, hue: f32, alpha: f32) -> Self {
Self {
lightness,
chroma,
hue,
alpha,
}
}
/// Construct a new [`Lcha`] color from (h, s, l) components, with the default alpha (1.0).
///
/// # Arguments
///
/// * `lightness` - Lightness channel. [0.0, 1.5]
/// * `chroma` - Chroma channel. [0.0, 1.5]
/// * `hue` - Hue channel. [0.0, 360.0]
pub const fn lch(lightness: f32, chroma: f32, hue: f32) -> Self {
Self {
lightness,
chroma,
hue,
alpha: 1.0,
}
}
/// Return a copy of this color with the chroma channel set to the given value.
pub const fn with_chroma(self, chroma: f32) -> Self {
Self { chroma, ..self }
}
/// Return a copy of this color with the lightness channel set to the given value.
pub const fn with_lightness(self, lightness: f32) -> Self {
Self { lightness, ..self }
}
/// Generate a deterministic but [quasi-randomly distributed](https://en.wikipedia.org/wiki/Low-discrepancy_sequence)
/// color from a provided `index`.
///
/// This can be helpful for generating debug colors.
///
/// # Examples
///
/// ```rust
/// # use bevy_color::Lcha;
/// // Unique color for an entity
/// # let entity_index = 123;
/// // let entity_index = entity.index();
/// let color = Lcha::sequential_dispersed(entity_index);
///
/// // Palette with 5 distinct hues
/// let palette = (0..5).map(Lcha::sequential_dispersed).collect::<Vec<_>>();
/// ```
pub const fn sequential_dispersed(index: u32) -> Self {
const FRAC_U32MAX_GOLDEN_RATIO: u32 = 2654435769; // (u32::MAX / Φ) rounded up
const RATIO_360: f32 = 360.0 / u32::MAX as f32;
// from https://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/
//
// Map a sequence of integers (eg: 154, 155, 156, 157, 158) into the [0.0..1.0] range,
// so that the closer the numbers are, the larger the difference of their image.
let hue = index.wrapping_mul(FRAC_U32MAX_GOLDEN_RATIO) as f32 * RATIO_360;
Self::lch(0.75, 0.35, hue)
}
}
impl Default for Lcha {
fn default() -> Self {
Self::new(1., 0., 0., 1.)
}
}
impl Mix for Lcha {
#[inline]
fn mix(&self, other: &Self, factor: f32) -> Self {
let n_factor = 1.0 - factor;
Self {
lightness: self.lightness * n_factor + other.lightness * factor,
chroma: self.chroma * n_factor + other.chroma * factor,
hue: crate::color_ops::lerp_hue(self.hue, other.hue, factor),
alpha: self.alpha * n_factor + other.alpha * factor,
}
}
}
impl Gray for Lcha {
const BLACK: Self = Self::new(0.0, 0.0, 0.0000136603785, 1.0);
const WHITE: Self = Self::new(1.0, 0.0, 0.0000136603785, 1.0);
}
impl Alpha for Lcha {
#[inline]
fn with_alpha(&self, alpha: f32) -> Self {
Self { alpha, ..*self }
}
#[inline]
fn alpha(&self) -> f32 {
self.alpha
}
#[inline]
fn set_alpha(&mut self, alpha: f32) {
self.alpha = alpha;
}
}
impl Hue for Lcha {
#[inline]
fn with_hue(&self, hue: f32) -> Self {
Self { hue, ..*self }
}
#[inline]
fn hue(&self) -> f32 {
self.hue
}
#[inline]
fn set_hue(&mut self, hue: f32) {
self.hue = hue;
}
}
impl Luminance for Lcha {
#[inline]
fn with_luminance(&self, lightness: f32) -> Self {
Self { lightness, ..*self }
}
fn luminance(&self) -> f32 {
self.lightness
}
fn darker(&self, amount: f32) -> Self {
Self::new(
(self.lightness - amount).max(0.),
self.chroma,
self.hue,
self.alpha,
)
}
fn lighter(&self, amount: f32) -> Self {
Self::new(
(self.lightness + amount).min(1.),
self.chroma,
self.hue,
self.alpha,
)
}
}
impl ColorToComponents for Lcha {
fn to_f32_array(self) -> [f32; 4] {
[self.lightness, self.chroma, self.hue, self.alpha]
}
fn to_f32_array_no_alpha(self) -> [f32; 3] {
[self.lightness, self.chroma, self.hue]
}
fn to_vec4(self) -> Vec4 {
Vec4::new(self.lightness, self.chroma, self.hue, self.alpha)
}
fn to_vec3(self) -> Vec3 {
Vec3::new(self.lightness, self.chroma, self.hue)
}
fn from_f32_array(color: [f32; 4]) -> Self {
Self {
lightness: color[0],
chroma: color[1],
hue: color[2],
alpha: color[3],
}
}
fn from_f32_array_no_alpha(color: [f32; 3]) -> Self {
Self {
lightness: color[0],
chroma: color[1],
hue: color[2],
alpha: 1.0,
}
}
fn from_vec4(color: Vec4) -> Self {
Self {
lightness: color[0],
chroma: color[1],
hue: color[2],
alpha: color[3],
}
}
fn from_vec3(color: Vec3) -> Self {
Self {
lightness: color[0],
chroma: color[1],
hue: color[2],
alpha: 1.0,
}
}
}
impl From<Lcha> for Laba {
fn from(
Lcha {
lightness,
chroma,
hue,
alpha,
}: Lcha,
) -> Self {
// Based on http://www.brucelindbloom.com/index.html?Eqn_LCH_to_Lab.html
let l = lightness;
let (sin, cos) = ops::sin_cos(hue.to_radians());
let a = chroma * cos;
let b = chroma * sin;
Laba::new(l, a, b, alpha)
}
}
impl From<Laba> for Lcha {
fn from(
Laba {
lightness,
a,
b,
alpha,
}: Laba,
) -> Self {
// Based on http://www.brucelindbloom.com/index.html?Eqn_Lab_to_LCH.html
let c = ops::hypot(a, b);
let h = {
let h = ops::atan2(b.to_radians(), a.to_radians()).to_degrees();
if h < 0.0 {
h + 360.0
} else {
h
}
};
let chroma = c.clamp(0.0, 1.5);
let hue = h;
Lcha::new(lightness, chroma, hue, alpha)
}
}
// Derived Conversions
impl From<Srgba> for Lcha {
fn from(value: Srgba) -> Self {
Laba::from(value).into()
}
}
impl From<Lcha> for Srgba {
fn from(value: Lcha) -> Self {
Laba::from(value).into()
}
}
impl From<LinearRgba> for Lcha {
fn from(value: LinearRgba) -> Self {
Laba::from(value).into()
}
}
impl From<Lcha> for LinearRgba {
fn from(value: Lcha) -> Self {
Laba::from(value).into()
}
}
impl From<Xyza> for Lcha {
fn from(value: Xyza) -> Self {
Laba::from(value).into()
}
}
impl From<Lcha> for Xyza {
fn from(value: Lcha) -> Self {
Laba::from(value).into()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
color_difference::EuclideanDistance, test_colors::TEST_COLORS, testing::assert_approx_eq,
};
#[test]
fn test_to_from_srgba() {
for color in TEST_COLORS.iter() {
let rgb2: Srgba = (color.lch).into();
let lcha: Lcha = (color.rgb).into();
assert!(
color.rgb.distance(&rgb2) < 0.0001,
"{}: {:?} != {:?}",
color.name,
color.rgb,
rgb2
);
assert_approx_eq!(color.lch.lightness, lcha.lightness, 0.001);
if lcha.lightness > 0.01 {
assert_approx_eq!(color.lch.chroma, lcha.chroma, 0.1);
}
if lcha.lightness > 0.01 && lcha.chroma > 0.01 {
assert!(
(color.lch.hue - lcha.hue).abs() < 1.7,
"{:?} != {:?}",
color.lch,
lcha
);
}
assert_approx_eq!(color.lch.alpha, lcha.alpha, 0.001);
}
}
#[test]
fn test_to_from_linear() {
for color in TEST_COLORS.iter() {
let rgb2: LinearRgba = (color.lch).into();
let lcha: Lcha = (color.linear_rgb).into();
assert!(
color.linear_rgb.distance(&rgb2) < 0.0001,
"{}: {:?} != {:?}",
color.name,
color.linear_rgb,
rgb2
);
assert_approx_eq!(color.lch.lightness, lcha.lightness, 0.001);
if lcha.lightness > 0.01 {
assert_approx_eq!(color.lch.chroma, lcha.chroma, 0.1);
}
if lcha.lightness > 0.01 && lcha.chroma > 0.01 {
assert!(
(color.lch.hue - lcha.hue).abs() < 1.7,
"{:?} != {:?}",
color.lch,
lcha
);
}
assert_approx_eq!(color.lch.alpha, lcha.alpha, 0.001);
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_color/src/color_gradient.rs | crates/bevy_color/src/color_gradient.rs | use crate::Mix;
use alloc::vec::Vec;
use bevy_math::curve::{
cores::{EvenCore, EvenCoreError},
Curve, Interval,
};
/// A curve whose samples are defined by a collection of colors.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
pub struct ColorCurve<T> {
core: EvenCore<T>,
}
impl<T> ColorCurve<T>
where
T: Mix + Clone,
{
/// Create a new [`ColorCurve`] from a collection of [mixable] types. The domain of this curve
/// will always be `[0.0, len - 1]` where `len` is the amount of mixable objects in the
/// collection.
///
/// This fails if there's not at least two mixable things in the collection.
///
/// [mixable]: `Mix`
///
/// # Example
///
/// ```
/// # use bevy_color::palettes::basic::*;
/// # use bevy_color::Mix;
/// # use bevy_color::Srgba;
/// # use bevy_color::ColorCurve;
/// # use bevy_math::curve::Interval;
/// # use bevy_math::curve::Curve;
/// let broken = ColorCurve::new([RED]);
/// assert!(broken.is_err());
/// let gradient = ColorCurve::new([RED, GREEN, BLUE]);
/// assert!(gradient.is_ok());
/// assert_eq!(gradient.unwrap().domain(), Interval::new(0.0, 2.0).unwrap());
/// ```
pub fn new(colors: impl IntoIterator<Item = T>) -> Result<Self, EvenCoreError> {
let colors = colors.into_iter().collect::<Vec<_>>();
Interval::new(0.0, colors.len().saturating_sub(1) as f32)
.map_err(|_| EvenCoreError::NotEnoughSamples {
samples: colors.len(),
})
.and_then(|domain| EvenCore::new(domain, colors))
.map(|core| Self { core })
}
}
impl<T> Curve<T> for ColorCurve<T>
where
T: Mix + Clone,
{
#[inline]
fn domain(&self) -> Interval {
self.core.domain()
}
#[inline]
fn sample_clamped(&self, t: f32) -> T {
// `EvenCore::sample_with` clamps the input implicitly.
self.core.sample_with(t, T::mix)
}
#[inline]
fn sample_unchecked(&self, t: f32) -> T {
self.sample_clamped(t)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{palettes::basic, Srgba};
use bevy_math::curve::{Curve, CurveExt};
#[test]
fn test_color_curve() {
let broken = ColorCurve::new([basic::RED]);
assert!(broken.is_err());
let gradient = [basic::RED, basic::LIME, basic::BLUE];
let curve = ColorCurve::new(gradient).unwrap();
assert_eq!(curve.domain(), Interval::new(0.0, 2.0).unwrap());
let brighter_curve = curve.map(|c: Srgba| c.mix(&basic::WHITE, 0.5));
[
(-0.1, None),
(0.0, Some([1.0, 0.5, 0.5, 1.0])),
(0.5, Some([0.75, 0.75, 0.5, 1.0])),
(1.0, Some([0.5, 1.0, 0.5, 1.0])),
(1.5, Some([0.5, 0.75, 0.75, 1.0])),
(2.0, Some([0.5, 0.5, 1.0, 1.0])),
(2.1, None),
]
.map(|(t, maybe_rgba)| {
let maybe_srgba = maybe_rgba.map(|[r, g, b, a]| Srgba::new(r, g, b, a));
(t, maybe_srgba)
})
.into_iter()
.for_each(|(t, maybe_color)| {
assert_eq!(brighter_curve.sample(t), maybe_color);
});
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_color/src/testing.rs | crates/bevy_color/src/testing.rs | #[cfg(test)]
macro_rules! assert_approx_eq {
($x:expr, $y:expr, $d:expr) => {
if ($x - $y).abs() >= $d {
panic!(
"assertion failed: `(left !== right)` \
(left: `{}`, right: `{}`, tolerance: `{}`)",
$x, $y, $d
);
}
};
}
#[cfg(test)]
pub(crate) use assert_approx_eq;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_color/src/xyza.rs | crates/bevy_color/src/xyza.rs | use crate::{
impl_componentwise_vector_space, Alpha, ColorToComponents, Gray, LinearRgba, Luminance, Mix,
StandardColor,
};
use bevy_math::{Vec3, Vec4};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::prelude::*;
/// [CIE 1931](https://en.wikipedia.org/wiki/CIE_1931_color_space) color space, also known as XYZ, with an alpha channel.
#[doc = include_str!("../docs/conversion.md")]
/// <div>
#[doc = include_str!("../docs/diagrams/model_graph.svg")]
/// </div>
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Clone, PartialEq, Default)
)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Xyza {
/// The x-axis. [0.0, 1.0]
pub x: f32,
/// The y-axis, intended to represent luminance. [0.0, 1.0]
pub y: f32,
/// The z-axis. [0.0, 1.0]
pub z: f32,
/// The alpha channel. [0.0, 1.0]
pub alpha: f32,
}
impl StandardColor for Xyza {}
impl_componentwise_vector_space!(Xyza, [x, y, z, alpha]);
impl Xyza {
/// Construct a new [`Xyza`] color from components.
///
/// # Arguments
///
/// * `x` - x-axis. [0.0, 1.0]
/// * `y` - y-axis. [0.0, 1.0]
/// * `z` - z-axis. [0.0, 1.0]
/// * `alpha` - Alpha channel. [0.0, 1.0]
pub const fn new(x: f32, y: f32, z: f32, alpha: f32) -> Self {
Self { x, y, z, alpha }
}
/// Construct a new [`Xyza`] color from (x, y, z) components, with the default alpha (1.0).
///
/// # Arguments
///
/// * `x` - x-axis. [0.0, 1.0]
/// * `y` - y-axis. [0.0, 1.0]
/// * `z` - z-axis. [0.0, 1.0]
pub const fn xyz(x: f32, y: f32, z: f32) -> Self {
Self {
x,
y,
z,
alpha: 1.0,
}
}
/// Return a copy of this color with the 'x' channel set to the given value.
pub const fn with_x(self, x: f32) -> Self {
Self { x, ..self }
}
/// Return a copy of this color with the 'y' channel set to the given value.
pub const fn with_y(self, y: f32) -> Self {
Self { y, ..self }
}
/// Return a copy of this color with the 'z' channel set to the given value.
pub const fn with_z(self, z: f32) -> Self {
Self { z, ..self }
}
/// [D65 White Point](https://en.wikipedia.org/wiki/Illuminant_D65#Definition)
pub const D65_WHITE: Self = Self::xyz(0.95047, 1.0, 1.08883);
}
impl Default for Xyza {
fn default() -> Self {
Self::new(0., 0., 0., 1.)
}
}
impl Alpha for Xyza {
#[inline]
fn with_alpha(&self, alpha: f32) -> Self {
Self { alpha, ..*self }
}
#[inline]
fn alpha(&self) -> f32 {
self.alpha
}
#[inline]
fn set_alpha(&mut self, alpha: f32) {
self.alpha = alpha;
}
}
impl Luminance for Xyza {
#[inline]
fn with_luminance(&self, lightness: f32) -> Self {
Self {
y: lightness,
..*self
}
}
fn luminance(&self) -> f32 {
self.y
}
fn darker(&self, amount: f32) -> Self {
Self {
y: (self.y - amount).clamp(0., 1.),
..*self
}
}
fn lighter(&self, amount: f32) -> Self {
Self {
y: (self.y + amount).min(1.),
..*self
}
}
}
impl Mix for Xyza {
#[inline]
fn mix(&self, other: &Self, factor: f32) -> Self {
let n_factor = 1.0 - factor;
Self {
x: self.x * n_factor + other.x * factor,
y: self.y * n_factor + other.y * factor,
z: self.z * n_factor + other.z * factor,
alpha: self.alpha * n_factor + other.alpha * factor,
}
}
}
impl Gray for Xyza {
const BLACK: Self = Self::new(0., 0., 0., 1.);
const WHITE: Self = Self::new(0.95047, 1.0, 1.08883, 1.0);
}
impl ColorToComponents for Xyza {
fn to_f32_array(self) -> [f32; 4] {
[self.x, self.y, self.z, self.alpha]
}
fn to_f32_array_no_alpha(self) -> [f32; 3] {
[self.x, self.y, self.z]
}
fn to_vec4(self) -> Vec4 {
Vec4::new(self.x, self.y, self.z, self.alpha)
}
fn to_vec3(self) -> Vec3 {
Vec3::new(self.x, self.y, self.z)
}
fn from_f32_array(color: [f32; 4]) -> Self {
Self {
x: color[0],
y: color[1],
z: color[2],
alpha: color[3],
}
}
fn from_f32_array_no_alpha(color: [f32; 3]) -> Self {
Self {
x: color[0],
y: color[1],
z: color[2],
alpha: 1.0,
}
}
fn from_vec4(color: Vec4) -> Self {
Self {
x: color[0],
y: color[1],
z: color[2],
alpha: color[3],
}
}
fn from_vec3(color: Vec3) -> Self {
Self {
x: color[0],
y: color[1],
z: color[2],
alpha: 1.0,
}
}
}
impl From<LinearRgba> for Xyza {
fn from(
LinearRgba {
red,
green,
blue,
alpha,
}: LinearRgba,
) -> Self {
// Linear sRGB to XYZ
// http://www.brucelindbloom.com/index.html?Eqn_XYZ_to_RGB.html
// http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html (sRGB, RGB to XYZ [M])
let r = red;
let g = green;
let b = blue;
let x = r * 0.4124564 + g * 0.3575761 + b * 0.1804375;
let y = r * 0.2126729 + g * 0.7151522 + b * 0.072175;
let z = r * 0.0193339 + g * 0.119192 + b * 0.9503041;
Xyza::new(x, y, z, alpha)
}
}
impl From<Xyza> for LinearRgba {
fn from(Xyza { x, y, z, alpha }: Xyza) -> Self {
// XYZ to Linear sRGB
// http://www.brucelindbloom.com/index.html?Eqn_XYZ_to_RGB.html
// http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html (sRGB, XYZ to RGB [M]-1)
let r = x * 3.2404542 + y * -1.5371385 + z * -0.4985314;
let g = x * -0.969266 + y * 1.8760108 + z * 0.041556;
let b = x * 0.0556434 + y * -0.2040259 + z * 1.0572252;
LinearRgba::new(r, g, b, alpha)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
color_difference::EuclideanDistance, test_colors::TEST_COLORS, testing::assert_approx_eq,
Srgba,
};
#[test]
fn test_to_from_srgba() {
let xyza = Xyza::new(0.5, 0.5, 0.5, 1.0);
let srgba: Srgba = xyza.into();
let xyza2: Xyza = srgba.into();
assert_approx_eq!(xyza.x, xyza2.x, 0.001);
assert_approx_eq!(xyza.y, xyza2.y, 0.001);
assert_approx_eq!(xyza.z, xyza2.z, 0.001);
assert_approx_eq!(xyza.alpha, xyza2.alpha, 0.001);
}
#[test]
fn test_to_from_srgba_2() {
for color in TEST_COLORS.iter() {
let rgb2: Srgba = (color.xyz).into();
let xyz2: Xyza = (color.rgb).into();
assert!(
color.rgb.distance(&rgb2) < 0.00001,
"{}: {:?} != {:?}",
color.name,
color.rgb,
rgb2
);
assert_approx_eq!(color.xyz.x, xyz2.x, 0.001);
assert_approx_eq!(color.xyz.y, xyz2.y, 0.001);
assert_approx_eq!(color.xyz.z, xyz2.z, 0.001);
assert_approx_eq!(color.xyz.alpha, xyz2.alpha, 0.001);
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_color/src/oklcha.rs | crates/bevy_color/src/oklcha.rs | use crate::{
color_difference::EuclideanDistance, Alpha, ColorToComponents, Gray, Hsla, Hsva, Hue, Hwba,
Laba, Lcha, LinearRgba, Luminance, Mix, Oklaba, Srgba, StandardColor, Xyza,
};
use bevy_math::{ops, FloatPow, Vec3, Vec4};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::prelude::*;
/// Color in Oklch color space, with alpha
#[doc = include_str!("../docs/conversion.md")]
/// <div>
#[doc = include_str!("../docs/diagrams/model_graph.svg")]
/// </div>
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Clone, PartialEq, Default)
)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Oklcha {
/// The 'lightness' channel. [0.0, 1.0]
pub lightness: f32,
/// The 'chroma' channel. [0.0, 1.0]
pub chroma: f32,
/// The 'hue' channel. [0.0, 360.0]
pub hue: f32,
/// The alpha channel. [0.0, 1.0]
pub alpha: f32,
}
impl StandardColor for Oklcha {}
impl Oklcha {
/// Construct a new [`Oklcha`] color from components.
///
/// # Arguments
///
/// * `lightness` - Lightness channel. [0.0, 1.0]
/// * `chroma` - Chroma channel. [0.0, 1.0]
/// * `hue` - Hue channel. [0.0, 360.0]
/// * `alpha` - Alpha channel. [0.0, 1.0]
pub const fn new(lightness: f32, chroma: f32, hue: f32, alpha: f32) -> Self {
Self {
lightness,
chroma,
hue,
alpha,
}
}
/// Construct a new [`Oklcha`] color from (l, c, h) components, with the default alpha (1.0).
///
/// # Arguments
///
/// * `lightness` - Lightness channel. [0.0, 1.0]
/// * `chroma` - Chroma channel. [0.0, 1.0]
/// * `hue` - Hue channel. [0.0, 360.0]
pub const fn lch(lightness: f32, chroma: f32, hue: f32) -> Self {
Self::new(lightness, chroma, hue, 1.0)
}
/// Return a copy of this color with the 'lightness' channel set to the given value.
pub const fn with_lightness(self, lightness: f32) -> Self {
Self { lightness, ..self }
}
/// Return a copy of this color with the 'chroma' channel set to the given value.
pub const fn with_chroma(self, chroma: f32) -> Self {
Self { chroma, ..self }
}
/// Generate a deterministic but [quasi-randomly distributed](https://en.wikipedia.org/wiki/Low-discrepancy_sequence)
/// color from a provided `index`.
///
/// This can be helpful for generating debug colors.
///
/// # Examples
///
/// ```rust
/// # use bevy_color::Oklcha;
/// // Unique color for an entity
/// # let entity_index = 123;
/// // let entity_index = entity.index();
/// let color = Oklcha::sequential_dispersed(entity_index);
///
/// // Palette with 5 distinct hues
/// let palette = (0..5).map(Oklcha::sequential_dispersed).collect::<Vec<_>>();
/// ```
pub const fn sequential_dispersed(index: u32) -> Self {
const FRAC_U32MAX_GOLDEN_RATIO: u32 = 2654435769; // (u32::MAX / Φ) rounded up
const RATIO_360: f32 = 360.0 / u32::MAX as f32;
// from https://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/
//
// Map a sequence of integers (eg: 154, 155, 156, 157, 158) into the [0.0..1.0] range,
// so that the closer the numbers are, the larger the difference of their image.
let hue = index.wrapping_mul(FRAC_U32MAX_GOLDEN_RATIO) as f32 * RATIO_360;
Self::lch(0.75, 0.1, hue)
}
}
impl Default for Oklcha {
fn default() -> Self {
Self::new(1., 0., 0., 1.)
}
}
impl Mix for Oklcha {
#[inline]
fn mix(&self, other: &Self, factor: f32) -> Self {
let n_factor = 1.0 - factor;
Self {
lightness: self.lightness * n_factor + other.lightness * factor,
chroma: self.chroma * n_factor + other.chroma * factor,
hue: crate::color_ops::lerp_hue(self.hue, other.hue, factor),
alpha: self.alpha * n_factor + other.alpha * factor,
}
}
}
impl Gray for Oklcha {
const BLACK: Self = Self::new(0., 0., 0., 1.);
const WHITE: Self = Self::new(1.0, 0.000000059604645, 90.0, 1.0);
}
impl Alpha for Oklcha {
#[inline]
fn with_alpha(&self, alpha: f32) -> Self {
Self { alpha, ..*self }
}
#[inline]
fn alpha(&self) -> f32 {
self.alpha
}
#[inline]
fn set_alpha(&mut self, alpha: f32) {
self.alpha = alpha;
}
}
impl Hue for Oklcha {
#[inline]
fn with_hue(&self, hue: f32) -> Self {
Self { hue, ..*self }
}
#[inline]
fn hue(&self) -> f32 {
self.hue
}
#[inline]
fn set_hue(&mut self, hue: f32) {
self.hue = hue;
}
}
impl Luminance for Oklcha {
#[inline]
fn with_luminance(&self, lightness: f32) -> Self {
Self { lightness, ..*self }
}
fn luminance(&self) -> f32 {
self.lightness
}
fn darker(&self, amount: f32) -> Self {
Self::new(
(self.lightness - amount).max(0.),
self.chroma,
self.hue,
self.alpha,
)
}
fn lighter(&self, amount: f32) -> Self {
Self::new(
(self.lightness + amount).min(1.),
self.chroma,
self.hue,
self.alpha,
)
}
}
impl EuclideanDistance for Oklcha {
#[inline]
fn distance_squared(&self, other: &Self) -> f32 {
(self.lightness - other.lightness).squared()
+ (self.chroma - other.chroma).squared()
+ (self.hue - other.hue).squared()
}
}
impl ColorToComponents for Oklcha {
fn to_f32_array(self) -> [f32; 4] {
[self.lightness, self.chroma, self.hue, self.alpha]
}
fn to_f32_array_no_alpha(self) -> [f32; 3] {
[self.lightness, self.chroma, self.hue]
}
fn to_vec4(self) -> Vec4 {
Vec4::new(self.lightness, self.chroma, self.hue, self.alpha)
}
fn to_vec3(self) -> Vec3 {
Vec3::new(self.lightness, self.chroma, self.hue)
}
fn from_f32_array(color: [f32; 4]) -> Self {
Self {
lightness: color[0],
chroma: color[1],
hue: color[2],
alpha: color[3],
}
}
fn from_f32_array_no_alpha(color: [f32; 3]) -> Self {
Self {
lightness: color[0],
chroma: color[1],
hue: color[2],
alpha: 1.0,
}
}
fn from_vec4(color: Vec4) -> Self {
Self {
lightness: color[0],
chroma: color[1],
hue: color[2],
alpha: color[3],
}
}
fn from_vec3(color: Vec3) -> Self {
Self {
lightness: color[0],
chroma: color[1],
hue: color[2],
alpha: 1.0,
}
}
}
impl From<Oklaba> for Oklcha {
fn from(
Oklaba {
lightness,
a,
b,
alpha,
}: Oklaba,
) -> Self {
let chroma = ops::hypot(a, b);
let hue = ops::atan2(b, a).to_degrees();
let hue = if hue < 0.0 { hue + 360.0 } else { hue };
Oklcha::new(lightness, chroma, hue, alpha)
}
}
impl From<Oklcha> for Oklaba {
fn from(
Oklcha {
lightness,
chroma,
hue,
alpha,
}: Oklcha,
) -> Self {
let l = lightness;
let (sin, cos) = ops::sin_cos(hue.to_radians());
let a = chroma * cos;
let b = chroma * sin;
Oklaba::new(l, a, b, alpha)
}
}
// Derived Conversions
impl From<Hsla> for Oklcha {
fn from(value: Hsla) -> Self {
Oklaba::from(value).into()
}
}
impl From<Oklcha> for Hsla {
fn from(value: Oklcha) -> Self {
Oklaba::from(value).into()
}
}
impl From<Hsva> for Oklcha {
fn from(value: Hsva) -> Self {
Oklaba::from(value).into()
}
}
impl From<Oklcha> for Hsva {
fn from(value: Oklcha) -> Self {
Oklaba::from(value).into()
}
}
impl From<Hwba> for Oklcha {
fn from(value: Hwba) -> Self {
Oklaba::from(value).into()
}
}
impl From<Oklcha> for Hwba {
fn from(value: Oklcha) -> Self {
Oklaba::from(value).into()
}
}
impl From<Laba> for Oklcha {
fn from(value: Laba) -> Self {
Oklaba::from(value).into()
}
}
impl From<Oklcha> for Laba {
fn from(value: Oklcha) -> Self {
Oklaba::from(value).into()
}
}
impl From<Lcha> for Oklcha {
fn from(value: Lcha) -> Self {
Oklaba::from(value).into()
}
}
impl From<Oklcha> for Lcha {
fn from(value: Oklcha) -> Self {
Oklaba::from(value).into()
}
}
impl From<LinearRgba> for Oklcha {
fn from(value: LinearRgba) -> Self {
Oklaba::from(value).into()
}
}
impl From<Oklcha> for LinearRgba {
fn from(value: Oklcha) -> Self {
Oklaba::from(value).into()
}
}
impl From<Srgba> for Oklcha {
fn from(value: Srgba) -> Self {
Oklaba::from(value).into()
}
}
impl From<Oklcha> for Srgba {
fn from(value: Oklcha) -> Self {
Oklaba::from(value).into()
}
}
impl From<Xyza> for Oklcha {
fn from(value: Xyza) -> Self {
Oklaba::from(value).into()
}
}
impl From<Oklcha> for Xyza {
fn from(value: Oklcha) -> Self {
Oklaba::from(value).into()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{test_colors::TEST_COLORS, testing::assert_approx_eq};
#[test]
fn test_to_from_srgba() {
let oklcha = Oklcha::new(0.5, 0.5, 180.0, 1.0);
let srgba: Srgba = oklcha.into();
let oklcha2: Oklcha = srgba.into();
assert_approx_eq!(oklcha.lightness, oklcha2.lightness, 0.001);
assert_approx_eq!(oklcha.chroma, oklcha2.chroma, 0.001);
assert_approx_eq!(oklcha.hue, oklcha2.hue, 0.001);
assert_approx_eq!(oklcha.alpha, oklcha2.alpha, 0.001);
}
#[test]
fn test_to_from_srgba_2() {
for color in TEST_COLORS.iter() {
let rgb2: Srgba = (color.oklch).into();
let oklch: Oklcha = (color.rgb).into();
assert!(
color.rgb.distance(&rgb2) < 0.0001,
"{}: {:?} != {:?}",
color.name,
color.rgb,
rgb2
);
assert!(
color.oklch.distance(&oklch) < 0.0001,
"{}: {:?} != {:?}",
color.name,
color.oklch,
oklch
);
}
}
#[test]
fn test_to_from_linear() {
let oklcha = Oklcha::new(0.5, 0.5, 0.5, 1.0);
let linear: LinearRgba = oklcha.into();
let oklcha2: Oklcha = linear.into();
assert_approx_eq!(oklcha.lightness, oklcha2.lightness, 0.001);
assert_approx_eq!(oklcha.chroma, oklcha2.chroma, 0.001);
assert_approx_eq!(oklcha.hue, oklcha2.hue, 0.001);
assert_approx_eq!(oklcha.alpha, oklcha2.alpha, 0.001);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_color/src/laba.rs | crates/bevy_color/src/laba.rs | use crate::{
impl_componentwise_vector_space, Alpha, ColorToComponents, Gray, Hsla, Hsva, Hwba, LinearRgba,
Luminance, Mix, Oklaba, Srgba, StandardColor, Xyza,
};
use bevy_math::{ops, Vec3, Vec4};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::prelude::*;
/// Color in LAB color space, with alpha
#[doc = include_str!("../docs/conversion.md")]
/// <div>
#[doc = include_str!("../docs/diagrams/model_graph.svg")]
/// </div>
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Clone, PartialEq, Default)
)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Laba {
/// The lightness channel. [0.0, 1.5]
pub lightness: f32,
/// The a axis. [-1.5, 1.5]
pub a: f32,
/// The b axis. [-1.5, 1.5]
pub b: f32,
/// The alpha channel. [0.0, 1.0]
pub alpha: f32,
}
impl StandardColor for Laba {}
impl_componentwise_vector_space!(Laba, [lightness, a, b, alpha]);
impl Laba {
/// Construct a new [`Laba`] color from components.
///
/// # Arguments
///
/// * `lightness` - Lightness channel. [0.0, 1.5]
/// * `a` - a axis. [-1.5, 1.5]
/// * `b` - b axis. [-1.5, 1.5]
/// * `alpha` - Alpha channel. [0.0, 1.0]
pub const fn new(lightness: f32, a: f32, b: f32, alpha: f32) -> Self {
Self {
lightness,
a,
b,
alpha,
}
}
/// Construct a new [`Laba`] color from (l, a, b) components, with the default alpha (1.0).
///
/// # Arguments
///
/// * `lightness` - Lightness channel. [0.0, 1.5]
/// * `a` - a axis. [-1.5, 1.5]
/// * `b` - b axis. [-1.5, 1.5]
pub const fn lab(lightness: f32, a: f32, b: f32) -> Self {
Self {
lightness,
a,
b,
alpha: 1.0,
}
}
/// Return a copy of this color with the lightness channel set to the given value.
pub const fn with_lightness(self, lightness: f32) -> Self {
Self { lightness, ..self }
}
/// CIE Epsilon Constant
///
/// See [Continuity (16) (17)](http://brucelindbloom.com/index.html?LContinuity.html)
pub const CIE_EPSILON: f32 = 216.0 / 24389.0;
/// CIE Kappa Constant
///
/// See [Continuity (16) (17)](http://brucelindbloom.com/index.html?LContinuity.html)
pub const CIE_KAPPA: f32 = 24389.0 / 27.0;
}
impl Default for Laba {
fn default() -> Self {
Self::new(1., 0., 0., 1.)
}
}
impl Mix for Laba {
#[inline]
fn mix(&self, other: &Self, factor: f32) -> Self {
let n_factor = 1.0 - factor;
Self {
lightness: self.lightness * n_factor + other.lightness * factor,
a: self.a * n_factor + other.a * factor,
b: self.b * n_factor + other.b * factor,
alpha: self.alpha * n_factor + other.alpha * factor,
}
}
}
impl Gray for Laba {
const BLACK: Self = Self::new(0., 0., 0., 1.);
const WHITE: Self = Self::new(1., 0., 0., 1.);
}
impl Alpha for Laba {
#[inline]
fn with_alpha(&self, alpha: f32) -> Self {
Self { alpha, ..*self }
}
#[inline]
fn alpha(&self) -> f32 {
self.alpha
}
#[inline]
fn set_alpha(&mut self, alpha: f32) {
self.alpha = alpha;
}
}
impl Luminance for Laba {
#[inline]
fn with_luminance(&self, lightness: f32) -> Self {
Self { lightness, ..*self }
}
fn luminance(&self) -> f32 {
self.lightness
}
fn darker(&self, amount: f32) -> Self {
Self::new(
(self.lightness - amount).max(0.),
self.a,
self.b,
self.alpha,
)
}
fn lighter(&self, amount: f32) -> Self {
Self::new(
(self.lightness + amount).min(1.),
self.a,
self.b,
self.alpha,
)
}
}
impl ColorToComponents for Laba {
fn to_f32_array(self) -> [f32; 4] {
[self.lightness, self.a, self.b, self.alpha]
}
fn to_f32_array_no_alpha(self) -> [f32; 3] {
[self.lightness, self.a, self.b]
}
fn to_vec4(self) -> Vec4 {
Vec4::new(self.lightness, self.a, self.b, self.alpha)
}
fn to_vec3(self) -> Vec3 {
Vec3::new(self.lightness, self.a, self.b)
}
fn from_f32_array(color: [f32; 4]) -> Self {
Self {
lightness: color[0],
a: color[1],
b: color[2],
alpha: color[3],
}
}
fn from_f32_array_no_alpha(color: [f32; 3]) -> Self {
Self {
lightness: color[0],
a: color[1],
b: color[2],
alpha: 1.0,
}
}
fn from_vec4(color: Vec4) -> Self {
Self {
lightness: color[0],
a: color[1],
b: color[2],
alpha: color[3],
}
}
fn from_vec3(color: Vec3) -> Self {
Self {
lightness: color[0],
a: color[1],
b: color[2],
alpha: 1.0,
}
}
}
impl From<Laba> for Xyza {
fn from(
Laba {
lightness,
a,
b,
alpha,
}: Laba,
) -> Self {
// Based on http://www.brucelindbloom.com/index.html?Eqn_Lab_to_XYZ.html
let l = 100. * lightness;
let a = 100. * a;
let b = 100. * b;
let fy = (l + 16.0) / 116.0;
let fx = a / 500.0 + fy;
let fz = fy - b / 200.0;
let xr = {
let fx3 = ops::powf(fx, 3.0);
if fx3 > Laba::CIE_EPSILON {
fx3
} else {
(116.0 * fx - 16.0) / Laba::CIE_KAPPA
}
};
let yr = if l > Laba::CIE_EPSILON * Laba::CIE_KAPPA {
ops::powf((l + 16.0) / 116.0, 3.0)
} else {
l / Laba::CIE_KAPPA
};
let zr = {
let fz3 = ops::powf(fz, 3.0);
if fz3 > Laba::CIE_EPSILON {
fz3
} else {
(116.0 * fz - 16.0) / Laba::CIE_KAPPA
}
};
let x = xr * Xyza::D65_WHITE.x;
let y = yr * Xyza::D65_WHITE.y;
let z = zr * Xyza::D65_WHITE.z;
Xyza::new(x, y, z, alpha)
}
}
impl From<Xyza> for Laba {
fn from(Xyza { x, y, z, alpha }: Xyza) -> Self {
// Based on http://www.brucelindbloom.com/index.html?Eqn_XYZ_to_Lab.html
let xr = x / Xyza::D65_WHITE.x;
let yr = y / Xyza::D65_WHITE.y;
let zr = z / Xyza::D65_WHITE.z;
let fx = if xr > Laba::CIE_EPSILON {
ops::cbrt(xr)
} else {
(Laba::CIE_KAPPA * xr + 16.0) / 116.0
};
let fy = if yr > Laba::CIE_EPSILON {
ops::cbrt(yr)
} else {
(Laba::CIE_KAPPA * yr + 16.0) / 116.0
};
let fz = if zr > Laba::CIE_EPSILON {
ops::cbrt(zr)
} else {
(Laba::CIE_KAPPA * zr + 16.0) / 116.0
};
let l = 1.16 * fy - 0.16;
let a = 5.00 * (fx - fy);
let b = 2.00 * (fy - fz);
Laba::new(l, a, b, alpha)
}
}
// Derived Conversions
impl From<Srgba> for Laba {
fn from(value: Srgba) -> Self {
Xyza::from(value).into()
}
}
impl From<Laba> for Srgba {
fn from(value: Laba) -> Self {
Xyza::from(value).into()
}
}
impl From<LinearRgba> for Laba {
fn from(value: LinearRgba) -> Self {
Xyza::from(value).into()
}
}
impl From<Laba> for LinearRgba {
fn from(value: Laba) -> Self {
Xyza::from(value).into()
}
}
impl From<Hsla> for Laba {
fn from(value: Hsla) -> Self {
Xyza::from(value).into()
}
}
impl From<Laba> for Hsla {
fn from(value: Laba) -> Self {
Xyza::from(value).into()
}
}
impl From<Hsva> for Laba {
fn from(value: Hsva) -> Self {
Xyza::from(value).into()
}
}
impl From<Laba> for Hsva {
fn from(value: Laba) -> Self {
Xyza::from(value).into()
}
}
impl From<Hwba> for Laba {
fn from(value: Hwba) -> Self {
Xyza::from(value).into()
}
}
impl From<Laba> for Hwba {
fn from(value: Laba) -> Self {
Xyza::from(value).into()
}
}
impl From<Oklaba> for Laba {
fn from(value: Oklaba) -> Self {
Xyza::from(value).into()
}
}
impl From<Laba> for Oklaba {
fn from(value: Laba) -> Self {
Xyza::from(value).into()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
color_difference::EuclideanDistance, test_colors::TEST_COLORS, testing::assert_approx_eq,
};
#[test]
fn test_to_from_srgba() {
for color in TEST_COLORS.iter() {
let rgb2: Srgba = (color.lab).into();
let laba: Laba = (color.rgb).into();
assert!(
color.rgb.distance(&rgb2) < 0.0001,
"{}: {:?} != {:?}",
color.name,
color.rgb,
rgb2
);
assert_approx_eq!(color.lab.lightness, laba.lightness, 0.001);
if laba.lightness > 0.01 {
assert_approx_eq!(color.lab.a, laba.a, 0.1);
}
if laba.lightness > 0.01 && laba.a > 0.01 {
assert!(
(color.lab.b - laba.b).abs() < 1.7,
"{:?} != {:?}",
color.lab,
laba
);
}
assert_approx_eq!(color.lab.alpha, laba.alpha, 0.001);
}
}
#[test]
fn test_to_from_linear() {
for color in TEST_COLORS.iter() {
let rgb2: LinearRgba = (color.lab).into();
let laba: Laba = (color.linear_rgb).into();
assert!(
color.linear_rgb.distance(&rgb2) < 0.0001,
"{}: {:?} != {:?}",
color.name,
color.linear_rgb,
rgb2
);
assert_approx_eq!(color.lab.lightness, laba.lightness, 0.001);
if laba.lightness > 0.01 {
assert_approx_eq!(color.lab.a, laba.a, 0.1);
}
if laba.lightness > 0.01 && laba.a > 0.01 {
assert!(
(color.lab.b - laba.b).abs() < 1.7,
"{:?} != {:?}",
color.lab,
laba
);
}
assert_approx_eq!(color.lab.alpha, laba.alpha, 0.001);
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_color/src/color.rs | crates/bevy_color/src/color.rs | use crate::{
color_difference::EuclideanDistance, Alpha, Hsla, Hsva, Hue, Hwba, Laba, Lcha, LinearRgba,
Luminance, Mix, Oklaba, Oklcha, Saturation, Srgba, StandardColor, Xyza,
};
use bevy_math::{MismatchedUnitsError, TryStableInterpolate};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::prelude::*;
use derive_more::derive::From;
/// An enumerated type that can represent any of the color types in this crate.
///
/// This is useful when you need to store a color in a data structure that can't be generic over
/// the color type.
#[doc = include_str!("../docs/conversion.md")]
/// <div>
#[doc = include_str!("../docs/diagrams/model_graph.svg")]
/// </div>
///
/// # Operations
///
/// [`Color`] supports all the standard color operations, such as [mixing](Mix),
/// [luminance](Luminance) and [hue](Hue) adjustment,
/// and [diffing](EuclideanDistance). These operations delegate to the concrete color space contained
/// by [`Color`], but will convert to [`Oklch`](Oklcha) for operations which aren't supported in the
/// current space. After performing the operation, if a conversion was required, the result will be
/// converted back into the original color space.
///
/// ```rust
/// # use bevy_color::{Hue, Color};
/// let red_hsv = Color::hsv(0., 1., 1.);
/// let red_srgb = Color::srgb(1., 0., 0.);
///
/// // HSV has a definition of hue, so it will be returned.
/// red_hsv.hue();
///
/// // SRGB doesn't have a native definition for hue.
/// // Converts to Oklch and returns that result.
/// red_srgb.hue();
/// ```
///
/// [`Oklch`](Oklcha) has been chosen as the intermediary space in cases where conversion is required
/// due to its perceptual uniformity and broad support for Bevy's color operations.
/// To avoid the cost of repeated conversion, and ensure consistent results where that is desired,
/// first convert this [`Color`] into your desired color space.
#[derive(Debug, Clone, Copy, PartialEq, From)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Clone, PartialEq, Default)
)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub enum Color {
/// A color in the sRGB color space with alpha.
Srgba(Srgba),
/// A color in the linear sRGB color space with alpha.
LinearRgba(LinearRgba),
/// A color in the HSL color space with alpha.
Hsla(Hsla),
/// A color in the HSV color space with alpha.
Hsva(Hsva),
/// A color in the HWB color space with alpha.
Hwba(Hwba),
/// A color in the LAB color space with alpha.
Laba(Laba),
/// A color in the LCH color space with alpha.
Lcha(Lcha),
/// A color in the Oklab color space with alpha.
Oklaba(Oklaba),
/// A color in the Oklch color space with alpha.
Oklcha(Oklcha),
/// A color in the XYZ color space with alpha.
Xyza(Xyza),
}
impl StandardColor for Color {}
impl Color {
/// Return the color as a linear RGBA color.
pub fn to_linear(&self) -> LinearRgba {
(*self).into()
}
/// Return the color as an SRGBA color.
pub fn to_srgba(&self) -> Srgba {
(*self).into()
}
/// Creates a new [`Color`] object storing a [`Srgba`] color.
///
/// # Arguments
///
/// * `red` - Red channel. [0.0, 1.0]
/// * `green` - Green channel. [0.0, 1.0]
/// * `blue` - Blue channel. [0.0, 1.0]
/// * `alpha` - Alpha channel. [0.0, 1.0]
pub const fn srgba(red: f32, green: f32, blue: f32, alpha: f32) -> Self {
Self::Srgba(Srgba {
red,
green,
blue,
alpha,
})
}
/// Creates a new [`Color`] object storing a [`Srgba`] color with an alpha of 1.0.
///
/// # Arguments
///
/// * `red` - Red channel. [0.0, 1.0]
/// * `green` - Green channel. [0.0, 1.0]
/// * `blue` - Blue channel. [0.0, 1.0]
pub const fn srgb(red: f32, green: f32, blue: f32) -> Self {
Self::Srgba(Srgba {
red,
green,
blue,
alpha: 1.0,
})
}
/// Reads an array of floats to creates a new [`Color`] object storing a [`Srgba`] color with an alpha of 1.0.
///
/// # Arguments
/// * `array` - Red, Green and Blue channels. Each channel is in the range [0.0, 1.0]
pub const fn srgb_from_array(array: [f32; 3]) -> Self {
Self::Srgba(Srgba {
red: array[0],
green: array[1],
blue: array[2],
alpha: 1.0,
})
}
/// Creates a new [`Color`] object storing a [`Srgba`] color from [`u8`] values.
///
/// # Arguments
///
/// * `red` - Red channel. [0, 255]
/// * `green` - Green channel. [0, 255]
/// * `blue` - Blue channel. [0, 255]
/// * `alpha` - Alpha channel. [0, 255]
pub const fn srgba_u8(red: u8, green: u8, blue: u8, alpha: u8) -> Self {
Self::Srgba(Srgba {
red: red as f32 / 255.0,
green: green as f32 / 255.0,
blue: blue as f32 / 255.0,
alpha: alpha as f32 / 255.0,
})
}
/// Creates a new [`Color`] object storing a [`Srgba`] color from [`u8`] values with an alpha of 1.0.
///
/// # Arguments
///
/// * `red` - Red channel. [0, 255]
/// * `green` - Green channel. [0, 255]
/// * `blue` - Blue channel. [0, 255]
pub const fn srgb_u8(red: u8, green: u8, blue: u8) -> Self {
Self::Srgba(Srgba {
red: red as f32 / 255.0,
green: green as f32 / 255.0,
blue: blue as f32 / 255.0,
alpha: 1.0,
})
}
/// Creates a new [`Color`] object storing a [`LinearRgba`] color.
///
/// # Arguments
///
/// * `red` - Red channel. [0.0, 1.0]
/// * `green` - Green channel. [0.0, 1.0]
/// * `blue` - Blue channel. [0.0, 1.0]
/// * `alpha` - Alpha channel. [0.0, 1.0]
pub const fn linear_rgba(red: f32, green: f32, blue: f32, alpha: f32) -> Self {
Self::LinearRgba(LinearRgba {
red,
green,
blue,
alpha,
})
}
/// Creates a new [`Color`] object storing a [`LinearRgba`] color with an alpha of 1.0.
///
/// # Arguments
///
/// * `red` - Red channel. [0.0, 1.0]
/// * `green` - Green channel. [0.0, 1.0]
/// * `blue` - Blue channel. [0.0, 1.0]
pub const fn linear_rgb(red: f32, green: f32, blue: f32) -> Self {
Self::LinearRgba(LinearRgba {
red,
green,
blue,
alpha: 1.0,
})
}
/// Creates a new [`Color`] object storing a [`Hsla`] color.
///
/// # Arguments
///
/// * `hue` - Hue channel. [0.0, 360.0]
/// * `saturation` - Saturation channel. [0.0, 1.0]
/// * `lightness` - Lightness channel. [0.0, 1.0]
/// * `alpha` - Alpha channel. [0.0, 1.0]
pub const fn hsla(hue: f32, saturation: f32, lightness: f32, alpha: f32) -> Self {
Self::Hsla(Hsla {
hue,
saturation,
lightness,
alpha,
})
}
/// Creates a new [`Color`] object storing a [`Hsla`] color with an alpha of 1.0.
///
/// # Arguments
///
/// * `hue` - Hue channel. [0.0, 360.0]
/// * `saturation` - Saturation channel. [0.0, 1.0]
/// * `lightness` - Lightness channel. [0.0, 1.0]
pub const fn hsl(hue: f32, saturation: f32, lightness: f32) -> Self {
Self::Hsla(Hsla {
hue,
saturation,
lightness,
alpha: 1.0,
})
}
/// Creates a new [`Color`] object storing a [`Hsva`] color.
///
/// # Arguments
///
/// * `hue` - Hue channel. [0.0, 360.0]
/// * `saturation` - Saturation channel. [0.0, 1.0]
/// * `value` - Value channel. [0.0, 1.0]
/// * `alpha` - Alpha channel. [0.0, 1.0]
pub const fn hsva(hue: f32, saturation: f32, value: f32, alpha: f32) -> Self {
Self::Hsva(Hsva {
hue,
saturation,
value,
alpha,
})
}
/// Creates a new [`Color`] object storing a [`Hsva`] color with an alpha of 1.0.
///
/// # Arguments
///
/// * `hue` - Hue channel. [0.0, 360.0]
/// * `saturation` - Saturation channel. [0.0, 1.0]
/// * `value` - Value channel. [0.0, 1.0]
pub const fn hsv(hue: f32, saturation: f32, value: f32) -> Self {
Self::Hsva(Hsva {
hue,
saturation,
value,
alpha: 1.0,
})
}
/// Creates a new [`Color`] object storing a [`Hwba`] color.
///
/// # Arguments
///
/// * `hue` - Hue channel. [0.0, 360.0]
/// * `whiteness` - Whiteness channel. [0.0, 1.0]
/// * `blackness` - Blackness channel. [0.0, 1.0]
/// * `alpha` - Alpha channel. [0.0, 1.0]
pub const fn hwba(hue: f32, whiteness: f32, blackness: f32, alpha: f32) -> Self {
Self::Hwba(Hwba {
hue,
whiteness,
blackness,
alpha,
})
}
/// Creates a new [`Color`] object storing a [`Hwba`] color with an alpha of 1.0.
///
/// # Arguments
///
/// * `hue` - Hue channel. [0.0, 360.0]
/// * `whiteness` - Whiteness channel. [0.0, 1.0]
/// * `blackness` - Blackness channel. [0.0, 1.0]
pub const fn hwb(hue: f32, whiteness: f32, blackness: f32) -> Self {
Self::Hwba(Hwba {
hue,
whiteness,
blackness,
alpha: 1.0,
})
}
/// Creates a new [`Color`] object storing a [`Laba`] color.
///
/// # Arguments
///
/// * `lightness` - Lightness channel. [0.0, 1.5]
/// * `a` - a axis. [-1.5, 1.5]
/// * `b` - b axis. [-1.5, 1.5]
/// * `alpha` - Alpha channel. [0.0, 1.0]
pub const fn laba(lightness: f32, a: f32, b: f32, alpha: f32) -> Self {
Self::Laba(Laba {
lightness,
a,
b,
alpha,
})
}
/// Creates a new [`Color`] object storing a [`Laba`] color with an alpha of 1.0.
///
/// # Arguments
///
/// * `lightness` - Lightness channel. [0.0, 1.5]
/// * `a` - a axis. [-1.5, 1.5]
/// * `b` - b axis. [-1.5, 1.5]
pub const fn lab(lightness: f32, a: f32, b: f32) -> Self {
Self::Laba(Laba {
lightness,
a,
b,
alpha: 1.0,
})
}
/// Creates a new [`Color`] object storing a [`Lcha`] color.
///
/// # Arguments
///
/// * `lightness` - Lightness channel. [0.0, 1.5]
/// * `chroma` - Chroma channel. [0.0, 1.5]
/// * `hue` - Hue channel. [0.0, 360.0]
/// * `alpha` - Alpha channel. [0.0, 1.0]
pub const fn lcha(lightness: f32, chroma: f32, hue: f32, alpha: f32) -> Self {
Self::Lcha(Lcha {
lightness,
chroma,
hue,
alpha,
})
}
/// Creates a new [`Color`] object storing a [`Lcha`] color with an alpha of 1.0.
///
/// # Arguments
///
/// * `lightness` - Lightness channel. [0.0, 1.5]
/// * `chroma` - Chroma channel. [0.0, 1.5]
/// * `hue` - Hue channel. [0.0, 360.0]
pub const fn lch(lightness: f32, chroma: f32, hue: f32) -> Self {
Self::Lcha(Lcha {
lightness,
chroma,
hue,
alpha: 1.0,
})
}
/// Creates a new [`Color`] object storing a [`Oklaba`] color.
///
/// # Arguments
///
/// * `lightness` - Lightness channel. [0.0, 1.0]
/// * `a` - Green-red channel. [-1.0, 1.0]
/// * `b` - Blue-yellow channel. [-1.0, 1.0]
/// * `alpha` - Alpha channel. [0.0, 1.0]
pub const fn oklaba(lightness: f32, a: f32, b: f32, alpha: f32) -> Self {
Self::Oklaba(Oklaba {
lightness,
a,
b,
alpha,
})
}
/// Creates a new [`Color`] object storing a [`Oklaba`] color with an alpha of 1.0.
///
/// # Arguments
///
/// * `lightness` - Lightness channel. [0.0, 1.0]
/// * `a` - Green-red channel. [-1.0, 1.0]
/// * `b` - Blue-yellow channel. [-1.0, 1.0]
pub const fn oklab(lightness: f32, a: f32, b: f32) -> Self {
Self::Oklaba(Oklaba {
lightness,
a,
b,
alpha: 1.0,
})
}
/// Creates a new [`Color`] object storing a [`Oklcha`] color.
///
/// # Arguments
///
/// * `lightness` - Lightness channel. [0.0, 1.0]
/// * `chroma` - Chroma channel. [0.0, 1.0]
/// * `hue` - Hue channel. [0.0, 360.0]
/// * `alpha` - Alpha channel. [0.0, 1.0]
pub const fn oklcha(lightness: f32, chroma: f32, hue: f32, alpha: f32) -> Self {
Self::Oklcha(Oklcha {
lightness,
chroma,
hue,
alpha,
})
}
/// Creates a new [`Color`] object storing a [`Oklcha`] color with an alpha of 1.0.
///
/// # Arguments
///
/// * `lightness` - Lightness channel. [0.0, 1.0]
/// * `chroma` - Chroma channel. [0.0, 1.0]
/// * `hue` - Hue channel. [0.0, 360.0]
pub const fn oklch(lightness: f32, chroma: f32, hue: f32) -> Self {
Self::Oklcha(Oklcha {
lightness,
chroma,
hue,
alpha: 1.0,
})
}
/// Creates a new [`Color`] object storing a [`Xyza`] color.
///
/// # Arguments
///
/// * `x` - x-axis. [0.0, 1.0]
/// * `y` - y-axis. [0.0, 1.0]
/// * `z` - z-axis. [0.0, 1.0]
/// * `alpha` - Alpha channel. [0.0, 1.0]
pub const fn xyza(x: f32, y: f32, z: f32, alpha: f32) -> Self {
Self::Xyza(Xyza { x, y, z, alpha })
}
/// Creates a new [`Color`] object storing a [`Xyza`] color with an alpha of 1.0.
///
/// # Arguments
///
/// * `x` - x-axis. [0.0, 1.0]
/// * `y` - y-axis. [0.0, 1.0]
/// * `z` - z-axis. [0.0, 1.0]
pub const fn xyz(x: f32, y: f32, z: f32) -> Self {
Self::Xyza(Xyza {
x,
y,
z,
alpha: 1.0,
})
}
/// A fully white [`Color::LinearRgba`] color with an alpha of 1.0.
pub const WHITE: Self = Self::linear_rgb(1.0, 1.0, 1.0);
/// A fully black [`Color::LinearRgba`] color with an alpha of 1.0.
pub const BLACK: Self = Self::linear_rgb(0., 0., 0.);
/// A fully transparent [`Color::LinearRgba`] color with 0 red, green and blue.
pub const NONE: Self = Self::linear_rgba(0., 0., 0., 0.);
}
impl Default for Color {
/// A fully white [`Color::LinearRgba`] color with an alpha of 1.0.
fn default() -> Self {
Color::WHITE
}
}
impl Alpha for Color {
fn with_alpha(&self, alpha: f32) -> Self {
let mut new = *self;
match &mut new {
Color::Srgba(x) => *x = x.with_alpha(alpha),
Color::LinearRgba(x) => *x = x.with_alpha(alpha),
Color::Hsla(x) => *x = x.with_alpha(alpha),
Color::Hsva(x) => *x = x.with_alpha(alpha),
Color::Hwba(x) => *x = x.with_alpha(alpha),
Color::Laba(x) => *x = x.with_alpha(alpha),
Color::Lcha(x) => *x = x.with_alpha(alpha),
Color::Oklaba(x) => *x = x.with_alpha(alpha),
Color::Oklcha(x) => *x = x.with_alpha(alpha),
Color::Xyza(x) => *x = x.with_alpha(alpha),
}
new
}
fn alpha(&self) -> f32 {
match self {
Color::Srgba(x) => x.alpha(),
Color::LinearRgba(x) => x.alpha(),
Color::Hsla(x) => x.alpha(),
Color::Hsva(x) => x.alpha(),
Color::Hwba(x) => x.alpha(),
Color::Laba(x) => x.alpha(),
Color::Lcha(x) => x.alpha(),
Color::Oklaba(x) => x.alpha(),
Color::Oklcha(x) => x.alpha(),
Color::Xyza(x) => x.alpha(),
}
}
fn set_alpha(&mut self, alpha: f32) {
match self {
Color::Srgba(x) => x.set_alpha(alpha),
Color::LinearRgba(x) => x.set_alpha(alpha),
Color::Hsla(x) => x.set_alpha(alpha),
Color::Hsva(x) => x.set_alpha(alpha),
Color::Hwba(x) => x.set_alpha(alpha),
Color::Laba(x) => x.set_alpha(alpha),
Color::Lcha(x) => x.set_alpha(alpha),
Color::Oklaba(x) => x.set_alpha(alpha),
Color::Oklcha(x) => x.set_alpha(alpha),
Color::Xyza(x) => x.set_alpha(alpha),
}
}
}
impl From<Color> for Srgba {
fn from(value: Color) -> Self {
match value {
Color::Srgba(srgba) => srgba,
Color::LinearRgba(linear) => linear.into(),
Color::Hsla(hsla) => hsla.into(),
Color::Hsva(hsva) => hsva.into(),
Color::Hwba(hwba) => hwba.into(),
Color::Laba(laba) => laba.into(),
Color::Lcha(lcha) => lcha.into(),
Color::Oklaba(oklab) => oklab.into(),
Color::Oklcha(oklch) => oklch.into(),
Color::Xyza(xyza) => xyza.into(),
}
}
}
impl From<Color> for LinearRgba {
fn from(value: Color) -> Self {
match value {
Color::Srgba(srgba) => srgba.into(),
Color::LinearRgba(linear) => linear,
Color::Hsla(hsla) => hsla.into(),
Color::Hsva(hsva) => hsva.into(),
Color::Hwba(hwba) => hwba.into(),
Color::Laba(laba) => laba.into(),
Color::Lcha(lcha) => lcha.into(),
Color::Oklaba(oklab) => oklab.into(),
Color::Oklcha(oklch) => oklch.into(),
Color::Xyza(xyza) => xyza.into(),
}
}
}
impl From<Color> for Hsla {
fn from(value: Color) -> Self {
match value {
Color::Srgba(srgba) => srgba.into(),
Color::LinearRgba(linear) => linear.into(),
Color::Hsla(hsla) => hsla,
Color::Hsva(hsva) => hsva.into(),
Color::Hwba(hwba) => hwba.into(),
Color::Laba(laba) => laba.into(),
Color::Lcha(lcha) => lcha.into(),
Color::Oklaba(oklab) => oklab.into(),
Color::Oklcha(oklch) => oklch.into(),
Color::Xyza(xyza) => xyza.into(),
}
}
}
impl From<Color> for Hsva {
fn from(value: Color) -> Self {
match value {
Color::Srgba(srgba) => srgba.into(),
Color::LinearRgba(linear) => linear.into(),
Color::Hsla(hsla) => hsla.into(),
Color::Hsva(hsva) => hsva,
Color::Hwba(hwba) => hwba.into(),
Color::Laba(laba) => laba.into(),
Color::Lcha(lcha) => lcha.into(),
Color::Oklaba(oklab) => oklab.into(),
Color::Oklcha(oklch) => oklch.into(),
Color::Xyza(xyza) => xyza.into(),
}
}
}
impl From<Color> for Hwba {
fn from(value: Color) -> Self {
match value {
Color::Srgba(srgba) => srgba.into(),
Color::LinearRgba(linear) => linear.into(),
Color::Hsla(hsla) => hsla.into(),
Color::Hsva(hsva) => hsva.into(),
Color::Hwba(hwba) => hwba,
Color::Laba(laba) => laba.into(),
Color::Lcha(lcha) => lcha.into(),
Color::Oklaba(oklab) => oklab.into(),
Color::Oklcha(oklch) => oklch.into(),
Color::Xyza(xyza) => xyza.into(),
}
}
}
impl From<Color> for Laba {
fn from(value: Color) -> Self {
match value {
Color::Srgba(srgba) => srgba.into(),
Color::LinearRgba(linear) => linear.into(),
Color::Hsla(hsla) => hsla.into(),
Color::Hsva(hsva) => hsva.into(),
Color::Hwba(hwba) => hwba.into(),
Color::Laba(laba) => laba,
Color::Lcha(lcha) => lcha.into(),
Color::Oklaba(oklab) => oklab.into(),
Color::Oklcha(oklch) => oklch.into(),
Color::Xyza(xyza) => xyza.into(),
}
}
}
impl From<Color> for Lcha {
fn from(value: Color) -> Self {
match value {
Color::Srgba(srgba) => srgba.into(),
Color::LinearRgba(linear) => linear.into(),
Color::Hsla(hsla) => hsla.into(),
Color::Hsva(hsva) => hsva.into(),
Color::Hwba(hwba) => hwba.into(),
Color::Laba(laba) => laba.into(),
Color::Lcha(lcha) => lcha,
Color::Oklaba(oklab) => oklab.into(),
Color::Oklcha(oklch) => oklch.into(),
Color::Xyza(xyza) => xyza.into(),
}
}
}
impl From<Color> for Oklaba {
fn from(value: Color) -> Self {
match value {
Color::Srgba(srgba) => srgba.into(),
Color::LinearRgba(linear) => linear.into(),
Color::Hsla(hsla) => hsla.into(),
Color::Hsva(hsva) => hsva.into(),
Color::Hwba(hwba) => hwba.into(),
Color::Laba(laba) => laba.into(),
Color::Lcha(lcha) => lcha.into(),
Color::Oklaba(oklab) => oklab,
Color::Oklcha(oklch) => oklch.into(),
Color::Xyza(xyza) => xyza.into(),
}
}
}
impl From<Color> for Oklcha {
fn from(value: Color) -> Self {
match value {
Color::Srgba(srgba) => srgba.into(),
Color::LinearRgba(linear) => linear.into(),
Color::Hsla(hsla) => hsla.into(),
Color::Hsva(hsva) => hsva.into(),
Color::Hwba(hwba) => hwba.into(),
Color::Laba(laba) => laba.into(),
Color::Lcha(lcha) => lcha.into(),
Color::Oklaba(oklab) => oklab.into(),
Color::Oklcha(oklch) => oklch,
Color::Xyza(xyza) => xyza.into(),
}
}
}
impl From<Color> for Xyza {
fn from(value: Color) -> Self {
match value {
Color::Srgba(x) => x.into(),
Color::LinearRgba(x) => x.into(),
Color::Hsla(x) => x.into(),
Color::Hsva(hsva) => hsva.into(),
Color::Hwba(hwba) => hwba.into(),
Color::Laba(laba) => laba.into(),
Color::Lcha(x) => x.into(),
Color::Oklaba(x) => x.into(),
Color::Oklcha(oklch) => oklch.into(),
Color::Xyza(xyza) => xyza,
}
}
}
/// Color space chosen for operations on `Color`.
type ChosenColorSpace = Oklcha;
impl Luminance for Color {
fn luminance(&self) -> f32 {
match self {
Color::Srgba(x) => x.luminance(),
Color::LinearRgba(x) => x.luminance(),
Color::Hsla(x) => x.luminance(),
Color::Hsva(x) => ChosenColorSpace::from(*x).luminance(),
Color::Hwba(x) => ChosenColorSpace::from(*x).luminance(),
Color::Laba(x) => x.luminance(),
Color::Lcha(x) => x.luminance(),
Color::Oklaba(x) => x.luminance(),
Color::Oklcha(x) => x.luminance(),
Color::Xyza(x) => x.luminance(),
}
}
fn with_luminance(&self, value: f32) -> Self {
let mut new = *self;
match &mut new {
Color::Srgba(x) => *x = x.with_luminance(value),
Color::LinearRgba(x) => *x = x.with_luminance(value),
Color::Hsla(x) => *x = x.with_luminance(value),
Color::Hsva(x) => *x = ChosenColorSpace::from(*x).with_luminance(value).into(),
Color::Hwba(x) => *x = ChosenColorSpace::from(*x).with_luminance(value).into(),
Color::Laba(x) => *x = x.with_luminance(value),
Color::Lcha(x) => *x = x.with_luminance(value),
Color::Oklaba(x) => *x = x.with_luminance(value),
Color::Oklcha(x) => *x = x.with_luminance(value),
Color::Xyza(x) => *x = x.with_luminance(value),
}
new
}
fn darker(&self, amount: f32) -> Self {
let mut new = *self;
match &mut new {
Color::Srgba(x) => *x = x.darker(amount),
Color::LinearRgba(x) => *x = x.darker(amount),
Color::Hsla(x) => *x = x.darker(amount),
Color::Hsva(x) => *x = ChosenColorSpace::from(*x).darker(amount).into(),
Color::Hwba(x) => *x = ChosenColorSpace::from(*x).darker(amount).into(),
Color::Laba(x) => *x = x.darker(amount),
Color::Lcha(x) => *x = x.darker(amount),
Color::Oklaba(x) => *x = x.darker(amount),
Color::Oklcha(x) => *x = x.darker(amount),
Color::Xyza(x) => *x = x.darker(amount),
}
new
}
fn lighter(&self, amount: f32) -> Self {
let mut new = *self;
match &mut new {
Color::Srgba(x) => *x = x.lighter(amount),
Color::LinearRgba(x) => *x = x.lighter(amount),
Color::Hsla(x) => *x = x.lighter(amount),
Color::Hsva(x) => *x = ChosenColorSpace::from(*x).lighter(amount).into(),
Color::Hwba(x) => *x = ChosenColorSpace::from(*x).lighter(amount).into(),
Color::Laba(x) => *x = x.lighter(amount),
Color::Lcha(x) => *x = x.lighter(amount),
Color::Oklaba(x) => *x = x.lighter(amount),
Color::Oklcha(x) => *x = x.lighter(amount),
Color::Xyza(x) => *x = x.lighter(amount),
}
new
}
}
impl Hue for Color {
fn with_hue(&self, hue: f32) -> Self {
let mut new = *self;
match &mut new {
Color::Srgba(x) => *x = ChosenColorSpace::from(*x).with_hue(hue).into(),
Color::LinearRgba(x) => *x = ChosenColorSpace::from(*x).with_hue(hue).into(),
Color::Hsla(x) => *x = x.with_hue(hue),
Color::Hsva(x) => *x = x.with_hue(hue),
Color::Hwba(x) => *x = x.with_hue(hue),
Color::Laba(x) => *x = ChosenColorSpace::from(*x).with_hue(hue).into(),
Color::Lcha(x) => *x = x.with_hue(hue),
Color::Oklaba(x) => *x = ChosenColorSpace::from(*x).with_hue(hue).into(),
Color::Oklcha(x) => *x = x.with_hue(hue),
Color::Xyza(x) => *x = ChosenColorSpace::from(*x).with_hue(hue).into(),
}
new
}
fn hue(&self) -> f32 {
match self {
Color::Srgba(x) => ChosenColorSpace::from(*x).hue(),
Color::LinearRgba(x) => ChosenColorSpace::from(*x).hue(),
Color::Hsla(x) => x.hue(),
Color::Hsva(x) => x.hue(),
Color::Hwba(x) => x.hue(),
Color::Laba(x) => ChosenColorSpace::from(*x).hue(),
Color::Lcha(x) => x.hue(),
Color::Oklaba(x) => ChosenColorSpace::from(*x).hue(),
Color::Oklcha(x) => x.hue(),
Color::Xyza(x) => ChosenColorSpace::from(*x).hue(),
}
}
fn set_hue(&mut self, hue: f32) {
*self = self.with_hue(hue);
}
}
impl Saturation for Color {
fn with_saturation(&self, saturation: f32) -> Self {
let mut new = *self;
match &mut new {
Color::Srgba(x) => Hsla::from(*x).with_saturation(saturation).into(),
Color::LinearRgba(x) => Hsla::from(*x).with_saturation(saturation).into(),
Color::Hsla(x) => x.with_saturation(saturation).into(),
Color::Hsva(x) => x.with_saturation(saturation).into(),
Color::Hwba(x) => Hsla::from(*x).with_saturation(saturation).into(),
Color::Laba(x) => Hsla::from(*x).with_saturation(saturation).into(),
Color::Lcha(x) => Hsla::from(*x).with_saturation(saturation).into(),
Color::Oklaba(x) => Hsla::from(*x).with_saturation(saturation).into(),
Color::Oklcha(x) => Hsla::from(*x).with_saturation(saturation).into(),
Color::Xyza(x) => Hsla::from(*x).with_saturation(saturation).into(),
}
}
fn saturation(&self) -> f32 {
match self {
Color::Srgba(x) => Hsla::from(*x).saturation(),
Color::LinearRgba(x) => Hsla::from(*x).saturation(),
Color::Hsla(x) => x.saturation(),
Color::Hsva(x) => x.saturation(),
Color::Hwba(x) => Hsla::from(*x).saturation(),
Color::Laba(x) => Hsla::from(*x).saturation(),
Color::Lcha(x) => Hsla::from(*x).saturation(),
Color::Oklaba(x) => Hsla::from(*x).saturation(),
Color::Oklcha(x) => Hsla::from(*x).saturation(),
Color::Xyza(x) => Hsla::from(*x).saturation(),
}
}
fn set_saturation(&mut self, saturation: f32) {
*self = self.with_saturation(saturation);
}
}
impl Mix for Color {
fn mix(&self, other: &Self, factor: f32) -> Self {
let mut new = *self;
match &mut new {
Color::Srgba(x) => *x = x.mix(&(*other).into(), factor),
Color::LinearRgba(x) => *x = x.mix(&(*other).into(), factor),
Color::Hsla(x) => *x = x.mix(&(*other).into(), factor),
Color::Hsva(x) => *x = x.mix(&(*other).into(), factor),
Color::Hwba(x) => *x = x.mix(&(*other).into(), factor),
Color::Laba(x) => *x = x.mix(&(*other).into(), factor),
Color::Lcha(x) => *x = x.mix(&(*other).into(), factor),
Color::Oklaba(x) => *x = x.mix(&(*other).into(), factor),
Color::Oklcha(x) => *x = x.mix(&(*other).into(), factor),
Color::Xyza(x) => *x = x.mix(&(*other).into(), factor),
}
new
}
}
impl EuclideanDistance for Color {
fn distance_squared(&self, other: &Self) -> f32 {
match self {
Color::Srgba(x) => x.distance_squared(&(*other).into()),
Color::LinearRgba(x) => x.distance_squared(&(*other).into()),
Color::Hsla(x) => ChosenColorSpace::from(*x).distance_squared(&(*other).into()),
Color::Hsva(x) => ChosenColorSpace::from(*x).distance_squared(&(*other).into()),
Color::Hwba(x) => ChosenColorSpace::from(*x).distance_squared(&(*other).into()),
Color::Laba(x) => ChosenColorSpace::from(*x).distance_squared(&(*other).into()),
Color::Lcha(x) => ChosenColorSpace::from(*x).distance_squared(&(*other).into()),
Color::Oklaba(x) => x.distance_squared(&(*other).into()),
Color::Oklcha(x) => x.distance_squared(&(*other).into()),
Color::Xyza(x) => ChosenColorSpace::from(*x).distance_squared(&(*other).into()),
}
}
}
impl TryStableInterpolate for Color {
type Error = MismatchedUnitsError;
fn try_interpolate_stable(&self, other: &Self, t: f32) -> Result<Self, Self::Error> {
match (self, other) {
(Color::Srgba(a), Color::Srgba(b)) => Ok(Color::Srgba(a.mix(b, t))),
(Color::LinearRgba(a), Color::LinearRgba(b)) => Ok(Color::LinearRgba(a.mix(b, t))),
(Color::Hsla(a), Color::Hsla(b)) => Ok(Color::Hsla(a.mix(b, t))),
(Color::Hsva(a), Color::Hsva(b)) => Ok(Color::Hsva(a.mix(b, t))),
(Color::Hwba(a), Color::Hwba(b)) => Ok(Color::Hwba(a.mix(b, t))),
(Color::Laba(a), Color::Laba(b)) => Ok(Color::Laba(a.mix(b, t))),
(Color::Lcha(a), Color::Lcha(b)) => Ok(Color::Lcha(a.mix(b, t))),
(Color::Oklaba(a), Color::Oklaba(b)) => Ok(Color::Oklaba(a.mix(b, t))),
(Color::Oklcha(a), Color::Oklcha(b)) => Ok(Color::Oklcha(a.mix(b, t))),
(Color::Xyza(a), Color::Xyza(b)) => Ok(Color::Xyza(a.mix(b, t))),
_ => Err(MismatchedUnitsError),
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_color/src/test_colors.rs | crates/bevy_color/src/test_colors.rs | // Generated by gen_tests. Do not edit.
#[cfg(test)]
use crate::{Hsla, Hsva, Hwba, Laba, Lcha, LinearRgba, Oklaba, Oklcha, Srgba, Xyza};
#[cfg(test)]
pub struct TestColor {
pub name: &'static str,
pub rgb: Srgba,
pub linear_rgb: LinearRgba,
pub hsl: Hsla,
pub hsv: Hsva,
pub hwb: Hwba,
pub lab: Laba,
pub lch: Lcha,
pub oklab: Oklaba,
pub oklch: Oklcha,
pub xyz: Xyza,
}
// Table of equivalent colors in various color spaces
#[cfg(test)]
pub const TEST_COLORS: &[TestColor] = &[
// black
TestColor {
name: "black",
rgb: Srgba::new(0.0, 0.0, 0.0, 1.0),
linear_rgb: LinearRgba::new(0.0, 0.0, 0.0, 1.0),
hsl: Hsla::new(0.0, 0.0, 0.0, 1.0),
lch: Lcha::new(0.0, 0.0, 0.0000136603785, 1.0),
hsv: Hsva::new(0.0, 0.0, 0.0, 1.0),
hwb: Hwba::new(0.0, 0.0, 1.0, 1.0),
lab: Laba::new(0.0, 0.0, 0.0, 1.0),
oklab: Oklaba::new(0.0, 0.0, 0.0, 1.0),
oklch: Oklcha::new(0.0, 0.0, 0.0, 1.0),
xyz: Xyza::new(0.0, 0.0, 0.0, 1.0),
},
// white
TestColor {
name: "white",
rgb: Srgba::new(1.0, 1.0, 1.0, 1.0),
linear_rgb: LinearRgba::new(1.0, 1.0, 1.0, 1.0),
hsl: Hsla::new(0.0, 0.0, 1.0, 1.0),
lch: Lcha::new(1.0, 0.0, 0.0000136603785, 1.0),
hsv: Hsva::new(0.0, 0.0, 1.0, 1.0),
hwb: Hwba::new(0.0, 1.0, 0.0, 1.0),
lab: Laba::new(1.0, 0.0, 0.0, 1.0),
oklab: Oklaba::new(1.0, 0.0, 0.000000059604645, 1.0),
oklch: Oklcha::new(1.0, 0.000000059604645, 90.0, 1.0),
xyz: Xyza::new(0.95047, 1.0, 1.08883, 1.0),
},
// red
TestColor {
name: "red",
rgb: Srgba::new(1.0, 0.0, 0.0, 1.0),
linear_rgb: LinearRgba::new(1.0, 0.0, 0.0, 1.0),
hsl: Hsla::new(0.0, 1.0, 0.5, 1.0),
lch: Lcha::new(0.53240794, 1.0455177, 39.99901, 1.0),
oklab: Oklaba::new(0.6279554, 0.22486295, 0.1258463, 1.0),
hsv: Hsva::new(0.0, 1.0, 1.0, 1.0),
hwb: Hwba::new(0.0, 0.0, 0.0, 1.0),
lab: Laba::new(0.532408, 0.8009243, 0.6720321, 1.0),
oklch: Oklcha::new(0.6279554, 0.2576833, 29.233892, 1.0),
xyz: Xyza::new(0.4124564, 0.2126729, 0.0193339, 1.0),
},
// green
TestColor {
name: "green",
rgb: Srgba::new(0.0, 1.0, 0.0, 1.0),
linear_rgb: LinearRgba::new(0.0, 1.0, 0.0, 1.0),
hsl: Hsla::new(120.0, 1.0, 0.5, 1.0),
lch: Lcha::new(0.87734723, 1.1977587, 136.01595, 1.0),
hsv: Hsva::new(120.0, 1.0, 1.0, 1.0),
hwb: Hwba::new(120.0, 0.0, 0.0, 1.0),
lab: Laba::new(0.8773472, -0.86182654, 0.8317931, 1.0),
oklab: Oklaba::new(0.8664396, -0.2338874, 0.1794985, 1.0),
oklch: Oklcha::new(0.8664396, 0.2948271, 142.49532, 1.0),
xyz: Xyza::new(0.3575761, 0.7151522, 0.119192, 1.0),
},
// blue
TestColor {
name: "blue",
rgb: Srgba::new(0.0, 0.0, 1.0, 1.0),
linear_rgb: LinearRgba::new(0.0, 0.0, 1.0, 1.0),
hsl: Hsla::new(240.0, 1.0, 0.5, 1.0),
lch: Lcha::new(0.32297012, 1.3380761, 306.28494, 1.0),
oklab: Oklaba::new(0.4520137, -0.032456964, -0.31152815, 1.0),
hsv: Hsva::new(240.0, 1.0, 1.0, 1.0),
hwb: Hwba::new(240.0, 0.0, 0.0, 1.0),
lab: Laba::new(0.32297015, 0.7918751, -1.0786015, 1.0),
oklch: Oklcha::new(0.45201376, 0.31321433, 264.05203, 1.0),
xyz: Xyza::new(0.1804375, 0.072175, 0.9503041, 1.0),
},
// yellow
TestColor {
name: "yellow",
rgb: Srgba::new(1.0, 1.0, 0.0, 1.0),
linear_rgb: LinearRgba::new(1.0, 1.0, 0.0, 1.0),
hsl: Hsla::new(60.0, 1.0, 0.5, 1.0),
lch: Lcha::new(0.9713927, 0.96905375, 102.85126, 1.0),
oklab: Oklaba::new(0.9679827, -0.07136908, 0.19856972, 1.0),
hsv: Hsva::new(60.0, 1.0, 1.0, 1.0),
hwb: Hwba::new(60.0, 0.0, 0.0, 1.0),
lab: Laba::new(0.9713927, -0.21553725, 0.94477975, 1.0),
oklch: Oklcha::new(0.9679827, 0.21100593, 109.76923, 1.0),
xyz: Xyza::new(0.7700325, 0.9278251, 0.1385259, 1.0),
},
// magenta
TestColor {
name: "magenta",
rgb: Srgba::new(1.0, 0.0, 1.0, 1.0),
linear_rgb: LinearRgba::new(1.0, 0.0, 1.0, 1.0),
hsl: Hsla::new(300.0, 1.0, 0.5, 1.0),
hsv: Hsva::new(300.0, 1.0, 1.0, 1.0),
hwb: Hwba::new(300.0, 0.0, 0.0, 1.0),
lab: Laba::new(0.6032421, 0.9823433, -0.60824895, 1.0),
lch: Lcha::new(0.6032421, 1.1554068, 328.23495, 1.0),
oklab: Oklaba::new(0.7016738, 0.27456632, -0.16915613, 1.0),
oklch: Oklcha::new(0.7016738, 0.32249108, 328.36343, 1.0),
xyz: Xyza::new(0.5928939, 0.28484792, 0.969638, 1.0),
},
// cyan
TestColor {
name: "cyan",
rgb: Srgba::new(0.0, 1.0, 1.0, 1.0),
linear_rgb: LinearRgba::new(0.0, 1.0, 1.0, 1.0),
hsl: Hsla::new(180.0, 1.0, 0.5, 1.0),
lch: Lcha::new(0.9111322, 0.50120866, 196.37614, 1.0),
oklab: Oklaba::new(0.90539926, -0.1494439, -0.039398134, 1.0),
hsv: Hsva::new(180.0, 1.0, 1.0, 1.0),
hwb: Hwba::new(180.0, 0.0, 0.0, 1.0),
lab: Laba::new(0.9111321, -0.4808751, -0.14131188, 1.0),
oklch: Oklcha::new(0.9053992, 0.15454963, 194.76901, 1.0),
xyz: Xyza::new(0.5380136, 0.78732723, 1.069496, 1.0),
},
// gray
TestColor {
name: "gray",
rgb: Srgba::new(0.5, 0.5, 0.5, 1.0),
linear_rgb: LinearRgba::new(0.21404114, 0.21404114, 0.21404114, 1.0),
hsl: Hsla::new(0.0, 0.0, 0.5, 1.0),
lch: Lcha::new(0.5338897, 0.00000011920929, 90.0, 1.0),
oklab: Oklaba::new(0.5981807, 0.00000011920929, 0.0, 1.0),
hsv: Hsva::new(0.0, 0.0, 0.5, 1.0),
hwb: Hwba::new(0.0, 0.5, 0.5, 1.0),
lab: Laba::new(0.5338897, 0.0, 0.0, 1.0),
oklch: Oklcha::new(0.5981808, 0.00000023841858, 0.0, 1.0),
xyz: Xyza::new(0.2034397, 0.21404117, 0.23305441, 1.0),
},
// olive
TestColor {
name: "olive",
rgb: Srgba::new(0.5, 0.5, 0.0, 1.0),
linear_rgb: LinearRgba::new(0.21404114, 0.21404114, 0.0, 1.0),
hsl: Hsla::new(60.0, 1.0, 0.25, 1.0),
lch: Lcha::new(0.51677734, 0.57966936, 102.851265, 1.0),
hsv: Hsva::new(60.0, 1.0, 0.5, 1.0),
hwb: Hwba::new(60.0, 0.0, 0.5, 1.0),
lab: Laba::new(0.51677734, -0.1289308, 0.5651491, 1.0),
oklab: Oklaba::new(0.57902855, -0.042691574, 0.11878061, 1.0),
oklch: Oklcha::new(0.57902855, 0.12621966, 109.76922, 1.0),
xyz: Xyza::new(0.16481864, 0.19859275, 0.029650241, 1.0),
},
// purple
TestColor {
name: "purple",
rgb: Srgba::new(0.5, 0.0, 0.5, 1.0),
linear_rgb: LinearRgba::new(0.21404114, 0.0, 0.21404114, 1.0),
hsl: Hsla::new(300.0, 1.0, 0.25, 1.0),
lch: Lcha::new(0.29655674, 0.69114214, 328.23495, 1.0),
hsv: Hsva::new(300.0, 1.0, 0.5, 1.0),
hwb: Hwba::new(300.0, 0.0, 0.5, 1.0),
lab: Laba::new(0.29655674, 0.58761847, -0.3638428, 1.0),
oklab: Oklaba::new(0.41972777, 0.1642403, -0.10118592, 1.0),
oklch: Oklcha::new(0.41972777, 0.19290791, 328.36343, 1.0),
xyz: Xyza::new(0.12690368, 0.060969174, 0.20754242, 1.0),
},
// teal
TestColor {
name: "teal",
rgb: Srgba::new(0.0, 0.5, 0.5, 1.0),
linear_rgb: LinearRgba::new(0.0, 0.21404114, 0.21404114, 1.0),
hsl: Hsla::new(180.0, 1.0, 0.25, 1.0),
lch: Lcha::new(0.48073065, 0.29981336, 196.37614, 1.0),
oklab: Oklaba::new(0.54159236, -0.08939436, -0.02356726, 1.0),
hsv: Hsva::new(180.0, 1.0, 0.5, 1.0),
hwb: Hwba::new(180.0, 0.0, 0.5, 1.0),
lab: Laba::new(0.4807306, -0.28765023, -0.084530115, 1.0),
oklch: Oklcha::new(0.54159236, 0.092448615, 194.76903, 1.0),
xyz: Xyza::new(0.11515705, 0.16852042, 0.22891617, 1.0),
},
// maroon
TestColor {
name: "maroon",
rgb: Srgba::new(0.5, 0.0, 0.0, 1.0),
linear_rgb: LinearRgba::new(0.21404114, 0.0, 0.0, 1.0),
hsl: Hsla::new(0.0, 1.0, 0.25, 1.0),
hsv: Hsva::new(0.0, 1.0, 0.5, 1.0),
hwb: Hwba::new(0.0, 0.0, 0.5, 1.0),
lab: Laba::new(0.2541851, 0.47909766, 0.37905872, 1.0),
lch: Lcha::new(0.2541851, 0.61091745, 38.350803, 1.0),
oklab: Oklaba::new(0.3756308, 0.13450874, 0.07527886, 1.0),
oklch: Oklcha::new(0.3756308, 0.1541412, 29.233906, 1.0),
xyz: Xyza::new(0.08828264, 0.045520753, 0.0041382504, 1.0),
},
// lime
TestColor {
name: "lime",
rgb: Srgba::new(0.0, 0.5, 0.0, 1.0),
linear_rgb: LinearRgba::new(0.0, 0.21404114, 0.0, 1.0),
hsl: Hsla::new(120.0, 1.0, 0.25, 1.0),
hsv: Hsva::new(120.0, 1.0, 0.5, 1.0),
hwb: Hwba::new(120.0, 0.0, 0.5, 1.0),
lab: Laba::new(0.46052113, -0.5155285, 0.4975627, 1.0),
lch: Lcha::new(0.46052113, 0.71647626, 136.01596, 1.0),
oklab: Oklaba::new(0.5182875, -0.13990697, 0.10737252, 1.0),
oklch: Oklcha::new(0.5182875, 0.17635989, 142.49535, 1.0),
xyz: Xyza::new(0.076536, 0.153072, 0.025511991, 1.0),
},
// navy
TestColor {
name: "navy",
rgb: Srgba::new(0.0, 0.0, 0.5, 1.0),
linear_rgb: LinearRgba::new(0.0, 0.0, 0.21404114, 1.0),
hsl: Hsla::new(240.0, 1.0, 0.25, 1.0),
lch: Lcha::new(0.12890343, 0.8004114, 306.28494, 1.0),
hsv: Hsva::new(240.0, 1.0, 0.5, 1.0),
hwb: Hwba::new(240.0, 0.0, 0.5, 1.0),
lab: Laba::new(0.12890343, 0.4736844, -0.64519864, 1.0),
oklab: Oklaba::new(0.27038592, -0.01941514, -0.18635012, 1.0),
oklch: Oklcha::new(0.27038592, 0.18735878, 264.05203, 1.0),
xyz: Xyza::new(0.03862105, 0.01544842, 0.20340417, 1.0),
},
// orange
TestColor {
name: "orange",
rgb: Srgba::new(0.5, 0.5, 0.0, 1.0),
linear_rgb: LinearRgba::new(0.21404114, 0.21404114, 0.0, 1.0),
hsl: Hsla::new(60.0, 1.0, 0.25, 1.0),
lch: Lcha::new(0.51677734, 0.57966936, 102.851265, 1.0),
hsv: Hsva::new(60.0, 1.0, 0.5, 1.0),
hwb: Hwba::new(60.0, 0.0, 0.5, 1.0),
lab: Laba::new(0.51677734, -0.1289308, 0.5651491, 1.0),
oklab: Oklaba::new(0.57902855, -0.042691574, 0.11878061, 1.0),
oklch: Oklcha::new(0.57902855, 0.12621966, 109.76922, 1.0),
xyz: Xyza::new(0.16481864, 0.19859275, 0.029650241, 1.0),
},
// fuchsia
TestColor {
name: "fuchsia",
rgb: Srgba::new(0.5, 0.0, 0.5, 1.0),
linear_rgb: LinearRgba::new(0.21404114, 0.0, 0.21404114, 1.0),
hsl: Hsla::new(300.0, 1.0, 0.25, 1.0),
lch: Lcha::new(0.29655674, 0.69114214, 328.23495, 1.0),
hsv: Hsva::new(300.0, 1.0, 0.5, 1.0),
hwb: Hwba::new(300.0, 0.0, 0.5, 1.0),
lab: Laba::new(0.29655674, 0.58761847, -0.3638428, 1.0),
oklab: Oklaba::new(0.41972777, 0.1642403, -0.10118592, 1.0),
oklch: Oklcha::new(0.41972777, 0.19290791, 328.36343, 1.0),
xyz: Xyza::new(0.12690368, 0.060969174, 0.20754242, 1.0),
},
// aqua
TestColor {
name: "aqua",
rgb: Srgba::new(0.0, 0.5, 0.5, 1.0),
linear_rgb: LinearRgba::new(0.0, 0.21404114, 0.21404114, 1.0),
hsl: Hsla::new(180.0, 1.0, 0.25, 1.0),
lch: Lcha::new(0.48073065, 0.29981336, 196.37614, 1.0),
oklab: Oklaba::new(0.54159236, -0.08939436, -0.02356726, 1.0),
hsv: Hsva::new(180.0, 1.0, 0.5, 1.0),
hwb: Hwba::new(180.0, 0.0, 0.5, 1.0),
lab: Laba::new(0.4807306, -0.28765023, -0.084530115, 1.0),
oklch: Oklcha::new(0.54159236, 0.092448615, 194.76903, 1.0),
xyz: Xyza::new(0.11515705, 0.16852042, 0.22891617, 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_color/src/srgba.rs | crates/bevy_color/src/srgba.rs | use crate::{
color_difference::EuclideanDistance, impl_componentwise_vector_space, Alpha, ColorToComponents,
ColorToPacked, Gray, LinearRgba, Luminance, Mix, StandardColor, Xyza,
};
#[cfg(feature = "alloc")]
use alloc::{format, string::String};
use bevy_math::{ops, Vec3, Vec4};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::prelude::*;
use thiserror::Error;
/// Non-linear standard RGB with alpha.
#[doc = include_str!("../docs/conversion.md")]
/// <div>
#[doc = include_str!("../docs/diagrams/model_graph.svg")]
/// </div>
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Clone, PartialEq, Default)
)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Srgba {
/// The red channel. [0.0, 1.0]
pub red: f32,
/// The green channel. [0.0, 1.0]
pub green: f32,
/// The blue channel. [0.0, 1.0]
pub blue: f32,
/// The alpha channel. [0.0, 1.0]
pub alpha: f32,
}
impl StandardColor for Srgba {}
impl_componentwise_vector_space!(Srgba, [red, green, blue, alpha]);
impl Srgba {
// The standard VGA colors, with alpha set to 1.0.
// https://en.wikipedia.org/wiki/Web_colors#Basic_colors
/// <div style="background-color:rgb(0%, 0%, 0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const BLACK: Srgba = Srgba::new(0.0, 0.0, 0.0, 1.0);
/// <div style="background-color:rgba(0%, 0%, 0%, 0%); width: 10px; padding: 10px; border: 1px solid;"></div>
#[doc(alias = "transparent")]
pub const NONE: Srgba = Srgba::new(0.0, 0.0, 0.0, 0.0);
/// <div style="background-color:rgb(100%, 100%, 100%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const WHITE: Srgba = Srgba::new(1.0, 1.0, 1.0, 1.0);
/// A fully red color with full alpha.
pub const RED: Self = Self {
red: 1.0,
green: 0.0,
blue: 0.0,
alpha: 1.0,
};
/// A fully green color with full alpha.
pub const GREEN: Self = Self {
red: 0.0,
green: 1.0,
blue: 0.0,
alpha: 1.0,
};
/// A fully blue color with full alpha.
pub const BLUE: Self = Self {
red: 0.0,
green: 0.0,
blue: 1.0,
alpha: 1.0,
};
/// Construct a new [`Srgba`] color from components.
///
/// # Arguments
///
/// * `red` - Red channel. [0.0, 1.0]
/// * `green` - Green channel. [0.0, 1.0]
/// * `blue` - Blue channel. [0.0, 1.0]
/// * `alpha` - Alpha channel. [0.0, 1.0]
pub const fn new(red: f32, green: f32, blue: f32, alpha: f32) -> Self {
Self {
red,
green,
blue,
alpha,
}
}
/// Construct a new [`Srgba`] color from (r, g, b) components, with the default alpha (1.0).
///
/// # Arguments
///
/// * `red` - Red channel. [0.0, 1.0]
/// * `green` - Green channel. [0.0, 1.0]
/// * `blue` - Blue channel. [0.0, 1.0]
pub const fn rgb(red: f32, green: f32, blue: f32) -> Self {
Self {
red,
green,
blue,
alpha: 1.0,
}
}
/// Return a copy of this color with the red channel set to the given value.
pub const fn with_red(self, red: f32) -> Self {
Self { red, ..self }
}
/// Return a copy of this color with the green channel set to the given value.
pub const fn with_green(self, green: f32) -> Self {
Self { green, ..self }
}
/// Return a copy of this color with the blue channel set to the given value.
pub const fn with_blue(self, blue: f32) -> Self {
Self { blue, ..self }
}
/// New `Srgba` from a CSS-style hexadecimal string.
///
/// # Examples
///
/// ```
/// # use bevy_color::Srgba;
/// let color = Srgba::hex("FF00FF").unwrap(); // fuchsia
/// let color = Srgba::hex("FF00FF7F").unwrap(); // partially transparent fuchsia
///
/// // A standard hex color notation is also available
/// assert_eq!(Srgba::hex("#FFFFFF").unwrap(), Srgba::new(1.0, 1.0, 1.0, 1.0));
/// ```
pub fn hex<T: AsRef<str>>(hex: T) -> Result<Self, HexColorError> {
let hex = hex.as_ref();
let hex = hex.strip_prefix('#').unwrap_or(hex);
match hex.len() {
// RGB
3 => {
let [l, b] = u16::from_str_radix(hex, 16)?.to_be_bytes();
let (r, g, b) = (l & 0x0F, (b & 0xF0) >> 4, b & 0x0F);
Ok(Self::rgb_u8((r << 4) | r, (g << 4) | g, (b << 4) | b))
}
// RGBA
4 => {
let [l, b] = u16::from_str_radix(hex, 16)?.to_be_bytes();
let (r, g, b, a) = ((l & 0xF0) >> 4, l & 0xF, (b & 0xF0) >> 4, b & 0x0F);
Ok(Self::rgba_u8(
(r << 4) | r,
(g << 4) | g,
(b << 4) | b,
(a << 4) | a,
))
}
// RRGGBB
6 => {
let [_, r, g, b] = u32::from_str_radix(hex, 16)?.to_be_bytes();
Ok(Self::rgb_u8(r, g, b))
}
// RRGGBBAA
8 => {
let [r, g, b, a] = u32::from_str_radix(hex, 16)?.to_be_bytes();
Ok(Self::rgba_u8(r, g, b, a))
}
_ => Err(HexColorError::Length),
}
}
/// Convert this color to CSS-style hexadecimal notation.
#[cfg(feature = "alloc")]
pub fn to_hex(&self) -> String {
let [r, g, b, a] = self.to_u8_array();
match a {
255 => format!("#{r:02X}{g:02X}{b:02X}"),
_ => format!("#{r:02X}{g:02X}{b:02X}{a:02X}"),
}
}
/// New `Srgba` from sRGB colorspace.
///
/// # Arguments
///
/// * `r` - Red channel. [0, 255]
/// * `g` - Green channel. [0, 255]
/// * `b` - Blue channel. [0, 255]
///
/// See also [`Srgba::new`], [`Srgba::rgba_u8`], [`Srgba::hex`].
pub fn rgb_u8(r: u8, g: u8, b: u8) -> Self {
Self::from_u8_array_no_alpha([r, g, b])
}
// Float operations in const fn are not stable yet
// see https://github.com/rust-lang/rust/issues/57241
/// New `Srgba` from sRGB colorspace.
///
/// # Arguments
///
/// * `r` - Red channel. [0, 255]
/// * `g` - Green channel. [0, 255]
/// * `b` - Blue channel. [0, 255]
/// * `a` - Alpha channel. [0, 255]
///
/// See also [`Srgba::new`], [`Srgba::rgb_u8`], [`Srgba::hex`].
pub fn rgba_u8(r: u8, g: u8, b: u8, a: u8) -> Self {
Self::from_u8_array([r, g, b, a])
}
/// Converts a non-linear sRGB value to a linear one via [gamma correction](https://en.wikipedia.org/wiki/Gamma_correction).
pub fn gamma_function(value: f32) -> f32 {
if value <= 0.0 {
return value;
}
if value <= 0.04045 {
value / 12.92 // linear falloff in dark values
} else {
ops::powf((value + 0.055) / 1.055, 2.4) // gamma curve in other area
}
}
/// Converts a linear sRGB value to a non-linear one via [gamma correction](https://en.wikipedia.org/wiki/Gamma_correction).
pub fn gamma_function_inverse(value: f32) -> f32 {
if value <= 0.0 {
return value;
}
if value <= 0.0031308 {
value * 12.92 // linear falloff in dark values
} else {
(1.055 * ops::powf(value, 1.0 / 2.4)) - 0.055 // gamma curve in other area
}
}
}
impl Default for Srgba {
fn default() -> Self {
Self::WHITE
}
}
impl Luminance for Srgba {
#[inline]
fn luminance(&self) -> f32 {
let linear: LinearRgba = (*self).into();
linear.luminance()
}
#[inline]
fn with_luminance(&self, luminance: f32) -> Self {
let linear: LinearRgba = (*self).into();
linear
.with_luminance(Srgba::gamma_function(luminance))
.into()
}
#[inline]
fn darker(&self, amount: f32) -> Self {
let linear: LinearRgba = (*self).into();
linear.darker(amount).into()
}
#[inline]
fn lighter(&self, amount: f32) -> Self {
let linear: LinearRgba = (*self).into();
linear.lighter(amount).into()
}
}
impl Mix for Srgba {
#[inline]
fn mix(&self, other: &Self, factor: f32) -> Self {
let n_factor = 1.0 - factor;
Self {
red: self.red * n_factor + other.red * factor,
green: self.green * n_factor + other.green * factor,
blue: self.blue * n_factor + other.blue * factor,
alpha: self.alpha * n_factor + other.alpha * factor,
}
}
}
impl Alpha for Srgba {
#[inline]
fn with_alpha(&self, alpha: f32) -> Self {
Self { alpha, ..*self }
}
#[inline]
fn alpha(&self) -> f32 {
self.alpha
}
#[inline]
fn set_alpha(&mut self, alpha: f32) {
self.alpha = alpha;
}
}
impl EuclideanDistance for Srgba {
#[inline]
fn distance_squared(&self, other: &Self) -> f32 {
let dr = self.red - other.red;
let dg = self.green - other.green;
let db = self.blue - other.blue;
dr * dr + dg * dg + db * db
}
}
impl Gray for Srgba {
const BLACK: Self = Self::BLACK;
const WHITE: Self = Self::WHITE;
}
impl ColorToComponents for Srgba {
fn to_f32_array(self) -> [f32; 4] {
[self.red, self.green, self.blue, self.alpha]
}
fn to_f32_array_no_alpha(self) -> [f32; 3] {
[self.red, self.green, self.blue]
}
fn to_vec4(self) -> Vec4 {
Vec4::new(self.red, self.green, self.blue, self.alpha)
}
fn to_vec3(self) -> Vec3 {
Vec3::new(self.red, self.green, self.blue)
}
fn from_f32_array(color: [f32; 4]) -> Self {
Self {
red: color[0],
green: color[1],
blue: color[2],
alpha: color[3],
}
}
fn from_f32_array_no_alpha(color: [f32; 3]) -> Self {
Self {
red: color[0],
green: color[1],
blue: color[2],
alpha: 1.0,
}
}
fn from_vec4(color: Vec4) -> Self {
Self {
red: color[0],
green: color[1],
blue: color[2],
alpha: color[3],
}
}
fn from_vec3(color: Vec3) -> Self {
Self {
red: color[0],
green: color[1],
blue: color[2],
alpha: 1.0,
}
}
}
impl ColorToPacked for Srgba {
fn to_u8_array(self) -> [u8; 4] {
[self.red, self.green, self.blue, self.alpha]
.map(|v| ops::round(v.clamp(0.0, 1.0) * 255.0) as u8)
}
fn to_u8_array_no_alpha(self) -> [u8; 3] {
[self.red, self.green, self.blue].map(|v| ops::round(v.clamp(0.0, 1.0) * 255.0) as u8)
}
fn from_u8_array(color: [u8; 4]) -> Self {
Self::from_f32_array(color.map(|u| u as f32 / 255.0))
}
fn from_u8_array_no_alpha(color: [u8; 3]) -> Self {
Self::from_f32_array_no_alpha(color.map(|u| u as f32 / 255.0))
}
}
impl From<LinearRgba> for Srgba {
#[inline]
fn from(value: LinearRgba) -> Self {
Self {
red: Srgba::gamma_function_inverse(value.red),
green: Srgba::gamma_function_inverse(value.green),
blue: Srgba::gamma_function_inverse(value.blue),
alpha: value.alpha,
}
}
}
impl From<Srgba> for LinearRgba {
#[inline]
fn from(value: Srgba) -> Self {
Self {
red: Srgba::gamma_function(value.red),
green: Srgba::gamma_function(value.green),
blue: Srgba::gamma_function(value.blue),
alpha: value.alpha,
}
}
}
// Derived Conversions
impl From<Xyza> for Srgba {
fn from(value: Xyza) -> Self {
LinearRgba::from(value).into()
}
}
impl From<Srgba> for Xyza {
fn from(value: Srgba) -> Self {
LinearRgba::from(value).into()
}
}
/// Error returned if a hex string could not be parsed as a color.
#[derive(Debug, Error, PartialEq, Eq)]
pub enum HexColorError {
/// Parsing error.
#[error("Invalid hex string")]
Parse(#[from] core::num::ParseIntError),
/// Invalid length.
#[error("Unexpected length of hex string")]
Length,
/// Invalid character.
#[error("Invalid hex char")]
Char(char),
}
#[cfg(test)]
mod tests {
use crate::testing::assert_approx_eq;
use super::*;
#[test]
fn test_to_from_linear() {
let srgba = Srgba::new(0.0, 0.5, 1.0, 1.0);
let linear_rgba: LinearRgba = srgba.into();
assert_eq!(linear_rgba.red, 0.0);
assert_approx_eq!(linear_rgba.green, 0.2140, 0.0001);
assert_approx_eq!(linear_rgba.blue, 1.0, 0.0001);
assert_eq!(linear_rgba.alpha, 1.0);
let srgba2: Srgba = linear_rgba.into();
assert_eq!(srgba2.red, 0.0);
assert_approx_eq!(srgba2.green, 0.5, 0.0001);
assert_approx_eq!(srgba2.blue, 1.0, 0.0001);
assert_eq!(srgba2.alpha, 1.0);
}
#[test]
fn euclidean_distance() {
// White to black
let a = Srgba::new(0.0, 0.0, 0.0, 1.0);
let b = Srgba::new(1.0, 1.0, 1.0, 1.0);
assert_eq!(a.distance_squared(&b), 3.0);
// Alpha shouldn't matter
let a = Srgba::new(0.0, 0.0, 0.0, 1.0);
let b = Srgba::new(1.0, 1.0, 1.0, 0.0);
assert_eq!(a.distance_squared(&b), 3.0);
// Red to green
let a = Srgba::new(0.0, 0.0, 0.0, 1.0);
let b = Srgba::new(1.0, 0.0, 0.0, 1.0);
assert_eq!(a.distance_squared(&b), 1.0);
}
#[test]
fn darker_lighter() {
// Darker and lighter should be commutative.
let color = Srgba::new(0.4, 0.5, 0.6, 1.0);
let darker1 = color.darker(0.1);
let darker2 = darker1.darker(0.1);
let twice_as_dark = color.darker(0.2);
assert!(darker2.distance_squared(&twice_as_dark) < 0.0001);
let lighter1 = color.lighter(0.1);
let lighter2 = lighter1.lighter(0.1);
let twice_as_light = color.lighter(0.2);
assert!(lighter2.distance_squared(&twice_as_light) < 0.0001);
}
#[test]
fn hex_color() {
assert_eq!(Srgba::hex("FFF"), Ok(Srgba::WHITE));
assert_eq!(Srgba::hex("FFFF"), Ok(Srgba::WHITE));
assert_eq!(Srgba::hex("FFFFFF"), Ok(Srgba::WHITE));
assert_eq!(Srgba::hex("FFFFFFFF"), Ok(Srgba::WHITE));
assert_eq!(Srgba::hex("000"), Ok(Srgba::BLACK));
assert_eq!(Srgba::hex("000F"), Ok(Srgba::BLACK));
assert_eq!(Srgba::hex("000000"), Ok(Srgba::BLACK));
assert_eq!(Srgba::hex("000000FF"), Ok(Srgba::BLACK));
assert_eq!(Srgba::hex("03a9f4"), Ok(Srgba::rgb_u8(3, 169, 244)));
assert_eq!(Srgba::hex("yy"), Err(HexColorError::Length));
assert_eq!(Srgba::hex("#f2a"), Ok(Srgba::rgb_u8(255, 34, 170)));
assert_eq!(Srgba::hex("#e23030"), Ok(Srgba::rgb_u8(226, 48, 48)));
assert_eq!(Srgba::hex("#ff"), Err(HexColorError::Length));
assert_eq!(Srgba::hex("11223344"), Ok(Srgba::rgba_u8(17, 34, 51, 68)));
assert_eq!(Srgba::hex("1234"), Ok(Srgba::rgba_u8(17, 34, 51, 68)));
assert_eq!(Srgba::hex("12345678"), Ok(Srgba::rgba_u8(18, 52, 86, 120)));
assert_eq!(Srgba::hex("4321"), Ok(Srgba::rgba_u8(68, 51, 34, 17)));
assert!(matches!(Srgba::hex("yyy"), Err(HexColorError::Parse(_))));
assert!(matches!(Srgba::hex("##fff"), Err(HexColorError::Parse(_))));
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_color/src/hsla.rs | crates/bevy_color/src/hsla.rs | use crate::{
Alpha, ColorToComponents, Gray, Hsva, Hue, Hwba, Lcha, LinearRgba, Luminance, Mix, Saturation,
Srgba, StandardColor, Xyza,
};
use bevy_math::{Vec3, Vec4};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::prelude::*;
/// Color in Hue-Saturation-Lightness (HSL) color space with alpha.
/// Further information on this color model can be found on [Wikipedia](https://en.wikipedia.org/wiki/HSL_and_HSV).
#[doc = include_str!("../docs/conversion.md")]
/// <div>
#[doc = include_str!("../docs/diagrams/model_graph.svg")]
/// </div>
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Clone, PartialEq, Default)
)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub struct Hsla {
/// The hue channel. [0.0, 360.0]
pub hue: f32,
/// The saturation channel. [0.0, 1.0]
pub saturation: f32,
/// The lightness channel. [0.0, 1.0]
pub lightness: f32,
/// The alpha channel. [0.0, 1.0]
pub alpha: f32,
}
impl StandardColor for Hsla {}
impl Hsla {
/// Construct a new [`Hsla`] color from components.
///
/// # Arguments
///
/// * `hue` - Hue channel. [0.0, 360.0]
/// * `saturation` - Saturation channel. [0.0, 1.0]
/// * `lightness` - Lightness channel. [0.0, 1.0]
/// * `alpha` - Alpha channel. [0.0, 1.0]
pub const fn new(hue: f32, saturation: f32, lightness: f32, alpha: f32) -> Self {
Self {
hue,
saturation,
lightness,
alpha,
}
}
/// Construct a new [`Hsla`] color from (h, s, l) components, with the default alpha (1.0).
///
/// # Arguments
///
/// * `hue` - Hue channel. [0.0, 360.0]
/// * `saturation` - Saturation channel. [0.0, 1.0]
/// * `lightness` - Lightness channel. [0.0, 1.0]
pub const fn hsl(hue: f32, saturation: f32, lightness: f32) -> Self {
Self::new(hue, saturation, lightness, 1.0)
}
/// Return a copy of this color with the saturation channel set to the given value.
pub const fn with_saturation(self, saturation: f32) -> Self {
Self { saturation, ..self }
}
/// Return a copy of this color with the lightness channel set to the given value.
pub const fn with_lightness(self, lightness: f32) -> Self {
Self { lightness, ..self }
}
/// Generate a deterministic but [quasi-randomly distributed](https://en.wikipedia.org/wiki/Low-discrepancy_sequence)
/// color from a provided `index`.
///
/// This can be helpful for generating debug colors.
///
/// # Examples
///
/// ```rust
/// # use bevy_color::Hsla;
/// // Unique color for an entity
/// # let entity_index = 123;
/// // let entity_index = entity.index();
/// let color = Hsla::sequential_dispersed(entity_index);
///
/// // Palette with 5 distinct hues
/// let palette = (0..5).map(Hsla::sequential_dispersed).collect::<Vec<_>>();
/// ```
pub const fn sequential_dispersed(index: u32) -> Self {
const FRAC_U32MAX_GOLDEN_RATIO: u32 = 2654435769; // (u32::MAX / Φ) rounded up
const RATIO_360: f32 = 360.0 / u32::MAX as f32;
// from https://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/
//
// Map a sequence of integers (eg: 154, 155, 156, 157, 158) into the [0.0..1.0] range,
// so that the closer the numbers are, the larger the difference of their image.
let hue = index.wrapping_mul(FRAC_U32MAX_GOLDEN_RATIO) as f32 * RATIO_360;
Self::hsl(hue, 1., 0.5)
}
}
impl Default for Hsla {
fn default() -> Self {
Self::new(0., 0., 1., 1.)
}
}
impl Mix for Hsla {
#[inline]
fn mix(&self, other: &Self, factor: f32) -> Self {
let n_factor = 1.0 - factor;
Self {
hue: crate::color_ops::lerp_hue(self.hue, other.hue, factor),
saturation: self.saturation * n_factor + other.saturation * factor,
lightness: self.lightness * n_factor + other.lightness * factor,
alpha: self.alpha * n_factor + other.alpha * factor,
}
}
}
impl Gray for Hsla {
const BLACK: Self = Self::new(0., 0., 0., 1.);
const WHITE: Self = Self::new(0., 0., 1., 1.);
}
impl Alpha for Hsla {
#[inline]
fn with_alpha(&self, alpha: f32) -> Self {
Self { alpha, ..*self }
}
#[inline]
fn alpha(&self) -> f32 {
self.alpha
}
#[inline]
fn set_alpha(&mut self, alpha: f32) {
self.alpha = alpha;
}
}
impl Hue for Hsla {
#[inline]
fn with_hue(&self, hue: f32) -> Self {
Self { hue, ..*self }
}
#[inline]
fn hue(&self) -> f32 {
self.hue
}
#[inline]
fn set_hue(&mut self, hue: f32) {
self.hue = hue;
}
}
impl Saturation for Hsla {
#[inline]
fn with_saturation(&self, saturation: f32) -> Self {
Self {
saturation,
..*self
}
}
#[inline]
fn saturation(&self) -> f32 {
self.saturation
}
#[inline]
fn set_saturation(&mut self, saturation: f32) {
self.saturation = saturation;
}
}
impl Luminance for Hsla {
#[inline]
fn with_luminance(&self, lightness: f32) -> Self {
Self { lightness, ..*self }
}
fn luminance(&self) -> f32 {
self.lightness
}
fn darker(&self, amount: f32) -> Self {
Self {
lightness: (self.lightness - amount).clamp(0., 1.),
..*self
}
}
fn lighter(&self, amount: f32) -> Self {
Self {
lightness: (self.lightness + amount).min(1.),
..*self
}
}
}
impl ColorToComponents for Hsla {
fn to_f32_array(self) -> [f32; 4] {
[self.hue, self.saturation, self.lightness, self.alpha]
}
fn to_f32_array_no_alpha(self) -> [f32; 3] {
[self.hue, self.saturation, self.lightness]
}
fn to_vec4(self) -> Vec4 {
Vec4::new(self.hue, self.saturation, self.lightness, self.alpha)
}
fn to_vec3(self) -> Vec3 {
Vec3::new(self.hue, self.saturation, self.lightness)
}
fn from_f32_array(color: [f32; 4]) -> Self {
Self {
hue: color[0],
saturation: color[1],
lightness: color[2],
alpha: color[3],
}
}
fn from_f32_array_no_alpha(color: [f32; 3]) -> Self {
Self {
hue: color[0],
saturation: color[1],
lightness: color[2],
alpha: 1.0,
}
}
fn from_vec4(color: Vec4) -> Self {
Self {
hue: color[0],
saturation: color[1],
lightness: color[2],
alpha: color[3],
}
}
fn from_vec3(color: Vec3) -> Self {
Self {
hue: color[0],
saturation: color[1],
lightness: color[2],
alpha: 1.0,
}
}
}
impl From<Hsla> for Hsva {
fn from(
Hsla {
hue,
saturation,
lightness,
alpha,
}: Hsla,
) -> Self {
// Based on https://en.wikipedia.org/wiki/HSL_and_HSV#HSL_to_HSV
let value = lightness + saturation * lightness.min(1. - lightness);
let saturation = if value == 0. {
0.
} else {
2. * (1. - (lightness / value))
};
Hsva::new(hue, saturation, value, alpha)
}
}
impl From<Hsva> for Hsla {
fn from(
Hsva {
hue,
saturation,
value,
alpha,
}: Hsva,
) -> Self {
// Based on https://en.wikipedia.org/wiki/HSL_and_HSV#HSV_to_HSL
let lightness = value * (1. - saturation / 2.);
let saturation = if lightness == 0. || lightness == 1. {
0.
} else {
(value - lightness) / lightness.min(1. - lightness)
};
Hsla::new(hue, saturation, lightness, alpha)
}
}
// Derived Conversions
impl From<Hwba> for Hsla {
fn from(value: Hwba) -> Self {
Hsva::from(value).into()
}
}
impl From<Hsla> for Hwba {
fn from(value: Hsla) -> Self {
Hsva::from(value).into()
}
}
impl From<Srgba> for Hsla {
fn from(value: Srgba) -> Self {
Hsva::from(value).into()
}
}
impl From<Hsla> for Srgba {
fn from(value: Hsla) -> Self {
Hsva::from(value).into()
}
}
impl From<LinearRgba> for Hsla {
fn from(value: LinearRgba) -> Self {
Hsva::from(value).into()
}
}
impl From<Hsla> for LinearRgba {
fn from(value: Hsla) -> Self {
Hsva::from(value).into()
}
}
impl From<Lcha> for Hsla {
fn from(value: Lcha) -> Self {
Hsva::from(value).into()
}
}
impl From<Hsla> for Lcha {
fn from(value: Hsla) -> Self {
Hsva::from(value).into()
}
}
impl From<Xyza> for Hsla {
fn from(value: Xyza) -> Self {
Hsva::from(value).into()
}
}
impl From<Hsla> for Xyza {
fn from(value: Hsla) -> Self {
Hsva::from(value).into()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
color_difference::EuclideanDistance, test_colors::TEST_COLORS, testing::assert_approx_eq,
};
#[test]
fn test_to_from_srgba() {
let hsla = Hsla::new(0.5, 0.5, 0.5, 1.0);
let srgba: Srgba = hsla.into();
let hsla2: Hsla = srgba.into();
assert_approx_eq!(hsla.hue, hsla2.hue, 0.001);
assert_approx_eq!(hsla.saturation, hsla2.saturation, 0.001);
assert_approx_eq!(hsla.lightness, hsla2.lightness, 0.001);
assert_approx_eq!(hsla.alpha, hsla2.alpha, 0.001);
}
#[test]
fn test_to_from_srgba_2() {
for color in TEST_COLORS.iter() {
let rgb2: Srgba = (color.hsl).into();
let hsl2: Hsla = (color.rgb).into();
assert!(
color.rgb.distance(&rgb2) < 0.000001,
"{}: {:?} != {:?}",
color.name,
color.rgb,
rgb2
);
assert_approx_eq!(color.hsl.hue, hsl2.hue, 0.001);
assert_approx_eq!(color.hsl.saturation, hsl2.saturation, 0.001);
assert_approx_eq!(color.hsl.lightness, hsl2.lightness, 0.001);
assert_approx_eq!(color.hsl.alpha, hsl2.alpha, 0.001);
}
}
#[test]
fn test_to_from_linear() {
let hsla = Hsla::new(0.5, 0.5, 0.5, 1.0);
let linear: LinearRgba = hsla.into();
let hsla2: Hsla = linear.into();
assert_approx_eq!(hsla.hue, hsla2.hue, 0.001);
assert_approx_eq!(hsla.saturation, hsla2.saturation, 0.001);
assert_approx_eq!(hsla.lightness, hsla2.lightness, 0.001);
assert_approx_eq!(hsla.alpha, hsla2.alpha, 0.001);
}
#[test]
fn test_mix_wrap() {
let hsla0 = Hsla::new(10., 0.5, 0.5, 1.0);
let hsla1 = Hsla::new(20., 0.5, 0.5, 1.0);
let hsla2 = Hsla::new(350., 0.5, 0.5, 1.0);
assert_approx_eq!(hsla0.mix(&hsla1, 0.25).hue, 12.5, 0.001);
assert_approx_eq!(hsla0.mix(&hsla1, 0.5).hue, 15., 0.001);
assert_approx_eq!(hsla0.mix(&hsla1, 0.75).hue, 17.5, 0.001);
assert_approx_eq!(hsla1.mix(&hsla0, 0.25).hue, 17.5, 0.001);
assert_approx_eq!(hsla1.mix(&hsla0, 0.5).hue, 15., 0.001);
assert_approx_eq!(hsla1.mix(&hsla0, 0.75).hue, 12.5, 0.001);
assert_approx_eq!(hsla0.mix(&hsla2, 0.25).hue, 5., 0.001);
assert_approx_eq!(hsla0.mix(&hsla2, 0.5).hue, 0., 0.001);
assert_approx_eq!(hsla0.mix(&hsla2, 0.75).hue, 355., 0.001);
assert_approx_eq!(hsla2.mix(&hsla0, 0.25).hue, 355., 0.001);
assert_approx_eq!(hsla2.mix(&hsla0, 0.5).hue, 0., 0.001);
assert_approx_eq!(hsla2.mix(&hsla0, 0.75).hue, 5., 0.001);
}
#[test]
fn test_from_index() {
let references = [
Hsla::hsl(0.0, 1., 0.5),
Hsla::hsl(222.49225, 1., 0.5),
Hsla::hsl(84.984474, 1., 0.5),
Hsla::hsl(307.4767, 1., 0.5),
Hsla::hsl(169.96895, 1., 0.5),
];
for (index, reference) in references.into_iter().enumerate() {
let color = Hsla::sequential_dispersed(index as u32);
assert_approx_eq!(color.hue, reference.hue, 0.001);
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_color/src/linear_rgba.rs | crates/bevy_color/src/linear_rgba.rs | use crate::{
color_difference::EuclideanDistance, impl_componentwise_vector_space, Alpha, ColorToComponents,
ColorToPacked, Gray, Luminance, Mix, StandardColor,
};
use bevy_math::{ops, Vec3, Vec4};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::prelude::*;
use bytemuck::{Pod, Zeroable};
/// Linear RGB color with alpha.
#[doc = include_str!("../docs/conversion.md")]
/// <div>
#[doc = include_str!("../docs/diagrams/model_graph.svg")]
/// </div>
#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Clone, PartialEq, Default)
)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
#[repr(C)]
pub struct LinearRgba {
/// The red channel. [0.0, 1.0]
pub red: f32,
/// The green channel. [0.0, 1.0]
pub green: f32,
/// The blue channel. [0.0, 1.0]
pub blue: f32,
/// The alpha channel. [0.0, 1.0]
pub alpha: f32,
}
impl StandardColor for LinearRgba {}
impl_componentwise_vector_space!(LinearRgba, [red, green, blue, alpha]);
impl LinearRgba {
/// A fully black color with full alpha.
pub const BLACK: Self = Self {
red: 0.0,
green: 0.0,
blue: 0.0,
alpha: 1.0,
};
/// A fully white color with full alpha.
pub const WHITE: Self = Self {
red: 1.0,
green: 1.0,
blue: 1.0,
alpha: 1.0,
};
/// A fully transparent color.
pub const NONE: Self = Self {
red: 0.0,
green: 0.0,
blue: 0.0,
alpha: 0.0,
};
/// A fully red color with full alpha.
pub const RED: Self = Self {
red: 1.0,
green: 0.0,
blue: 0.0,
alpha: 1.0,
};
/// A fully green color with full alpha.
pub const GREEN: Self = Self {
red: 0.0,
green: 1.0,
blue: 0.0,
alpha: 1.0,
};
/// A fully blue color with full alpha.
pub const BLUE: Self = Self {
red: 0.0,
green: 0.0,
blue: 1.0,
alpha: 1.0,
};
/// An invalid color.
///
/// This type can be used to represent an invalid color value;
/// in some rendering applications the color will be ignored,
/// enabling performant hacks like hiding lines by setting their color to `INVALID`.
pub const NAN: Self = Self {
red: f32::NAN,
green: f32::NAN,
blue: f32::NAN,
alpha: f32::NAN,
};
/// Construct a new [`LinearRgba`] color from components.
pub const fn new(red: f32, green: f32, blue: f32, alpha: f32) -> Self {
Self {
red,
green,
blue,
alpha,
}
}
/// Construct a new [`LinearRgba`] color from (r, g, b) components, with the default alpha (1.0).
///
/// # Arguments
///
/// * `red` - Red channel. [0.0, 1.0]
/// * `green` - Green channel. [0.0, 1.0]
/// * `blue` - Blue channel. [0.0, 1.0]
pub const fn rgb(red: f32, green: f32, blue: f32) -> Self {
Self {
red,
green,
blue,
alpha: 1.0,
}
}
/// Return a copy of this color with the red channel set to the given value.
pub const fn with_red(self, red: f32) -> Self {
Self { red, ..self }
}
/// Return a copy of this color with the green channel set to the given value.
pub const fn with_green(self, green: f32) -> Self {
Self { green, ..self }
}
/// Return a copy of this color with the blue channel set to the given value.
pub const fn with_blue(self, blue: f32) -> Self {
Self { blue, ..self }
}
/// Make the color lighter or darker by some amount
fn adjust_lightness(&mut self, amount: f32) {
let luminance = self.luminance();
let target_luminance = (luminance + amount).clamp(0.0, 1.0);
if target_luminance < luminance {
let adjustment = (luminance - target_luminance) / luminance;
self.mix_assign(Self::new(0.0, 0.0, 0.0, self.alpha), adjustment);
} else if target_luminance > luminance {
let adjustment = (target_luminance - luminance) / (1. - luminance);
self.mix_assign(Self::new(1.0, 1.0, 1.0, self.alpha), adjustment);
}
}
/// Converts this color to a u32.
///
/// Maps the RGBA channels in RGBA order to a little-endian byte array (GPUs are little-endian).
/// `A` will be the most significant byte and `R` the least significant.
pub fn as_u32(&self) -> u32 {
u32::from_le_bytes(self.to_u8_array())
}
}
impl Default for LinearRgba {
/// Construct a new [`LinearRgba`] color with the default values (white with full alpha).
fn default() -> Self {
Self::WHITE
}
}
impl Luminance for LinearRgba {
/// Luminance calculated using the [CIE XYZ formula](https://en.wikipedia.org/wiki/Relative_luminance).
#[inline]
fn luminance(&self) -> f32 {
self.red * 0.2126 + self.green * 0.7152 + self.blue * 0.0722
}
#[inline]
fn with_luminance(&self, luminance: f32) -> Self {
let current_luminance = self.luminance();
let adjustment = luminance / current_luminance;
Self {
red: (self.red * adjustment).clamp(0., 1.),
green: (self.green * adjustment).clamp(0., 1.),
blue: (self.blue * adjustment).clamp(0., 1.),
alpha: self.alpha,
}
}
#[inline]
fn darker(&self, amount: f32) -> Self {
let mut result = *self;
result.adjust_lightness(-amount);
result
}
#[inline]
fn lighter(&self, amount: f32) -> Self {
let mut result = *self;
result.adjust_lightness(amount);
result
}
}
impl Mix for LinearRgba {
#[inline]
fn mix(&self, other: &Self, factor: f32) -> Self {
let n_factor = 1.0 - factor;
Self {
red: self.red * n_factor + other.red * factor,
green: self.green * n_factor + other.green * factor,
blue: self.blue * n_factor + other.blue * factor,
alpha: self.alpha * n_factor + other.alpha * factor,
}
}
}
impl Gray for LinearRgba {
const BLACK: Self = Self::BLACK;
const WHITE: Self = Self::WHITE;
}
impl Alpha for LinearRgba {
#[inline]
fn with_alpha(&self, alpha: f32) -> Self {
Self { alpha, ..*self }
}
#[inline]
fn alpha(&self) -> f32 {
self.alpha
}
#[inline]
fn set_alpha(&mut self, alpha: f32) {
self.alpha = alpha;
}
}
impl EuclideanDistance for LinearRgba {
#[inline]
fn distance_squared(&self, other: &Self) -> f32 {
let dr = self.red - other.red;
let dg = self.green - other.green;
let db = self.blue - other.blue;
dr * dr + dg * dg + db * db
}
}
impl ColorToComponents for LinearRgba {
fn to_f32_array(self) -> [f32; 4] {
[self.red, self.green, self.blue, self.alpha]
}
fn to_f32_array_no_alpha(self) -> [f32; 3] {
[self.red, self.green, self.blue]
}
fn to_vec4(self) -> Vec4 {
Vec4::new(self.red, self.green, self.blue, self.alpha)
}
fn to_vec3(self) -> Vec3 {
Vec3::new(self.red, self.green, self.blue)
}
fn from_f32_array(color: [f32; 4]) -> Self {
Self {
red: color[0],
green: color[1],
blue: color[2],
alpha: color[3],
}
}
fn from_f32_array_no_alpha(color: [f32; 3]) -> Self {
Self {
red: color[0],
green: color[1],
blue: color[2],
alpha: 1.0,
}
}
fn from_vec4(color: Vec4) -> Self {
Self {
red: color[0],
green: color[1],
blue: color[2],
alpha: color[3],
}
}
fn from_vec3(color: Vec3) -> Self {
Self {
red: color[0],
green: color[1],
blue: color[2],
alpha: 1.0,
}
}
}
impl ColorToPacked for LinearRgba {
fn to_u8_array(self) -> [u8; 4] {
[self.red, self.green, self.blue, self.alpha]
.map(|v| ops::round(v.clamp(0.0, 1.0) * 255.0) as u8)
}
fn to_u8_array_no_alpha(self) -> [u8; 3] {
[self.red, self.green, self.blue].map(|v| ops::round(v.clamp(0.0, 1.0) * 255.0) as u8)
}
fn from_u8_array(color: [u8; 4]) -> Self {
Self::from_f32_array(color.map(|u| u as f32 / 255.0))
}
fn from_u8_array_no_alpha(color: [u8; 3]) -> Self {
Self::from_f32_array_no_alpha(color.map(|u| u as f32 / 255.0))
}
}
#[cfg(feature = "wgpu-types")]
impl From<LinearRgba> for wgpu_types::Color {
fn from(color: LinearRgba) -> Self {
wgpu_types::Color {
r: color.red as f64,
g: color.green as f64,
b: color.blue as f64,
a: color.alpha as f64,
}
}
}
// [`LinearRgba`] is intended to be used with shaders
// So it's the only color type that implements [`ShaderType`] to make it easier to use inside shaders
#[cfg(feature = "encase")]
impl encase::ShaderType for LinearRgba {
type ExtraMetadata = ();
const METADATA: encase::private::Metadata<Self::ExtraMetadata> = {
let size =
encase::private::SizeValue::from(<f32 as encase::private::ShaderSize>::SHADER_SIZE)
.mul(4);
let alignment = encase::private::AlignmentValue::from_next_power_of_two_size(size);
encase::private::Metadata {
alignment,
has_uniform_min_alignment: false,
is_pod: true,
min_size: size,
extra: (),
}
};
const UNIFORM_COMPAT_ASSERT: fn() = || {};
}
#[cfg(feature = "encase")]
impl encase::private::WriteInto for LinearRgba {
fn write_into<B: encase::private::BufferMut>(&self, writer: &mut encase::private::Writer<B>) {
for el in &[self.red, self.green, self.blue, self.alpha] {
encase::private::WriteInto::write_into(el, writer);
}
}
}
#[cfg(feature = "encase")]
impl encase::private::ReadFrom for LinearRgba {
fn read_from<B: encase::private::BufferRef>(
&mut self,
reader: &mut encase::private::Reader<B>,
) {
let mut buffer = [0.0f32; 4];
for el in &mut buffer {
encase::private::ReadFrom::read_from(el, reader);
}
*self = LinearRgba {
red: buffer[0],
green: buffer[1],
blue: buffer[2],
alpha: buffer[3],
}
}
}
#[cfg(feature = "encase")]
impl encase::private::CreateFrom for LinearRgba {
fn create_from<B>(reader: &mut encase::private::Reader<B>) -> Self
where
B: encase::private::BufferRef,
{
// These are intentionally not inlined in the constructor to make this
// resilient to internal Color refactors / implicit type changes.
let red: f32 = encase::private::CreateFrom::create_from(reader);
let green: f32 = encase::private::CreateFrom::create_from(reader);
let blue: f32 = encase::private::CreateFrom::create_from(reader);
let alpha: f32 = encase::private::CreateFrom::create_from(reader);
LinearRgba {
red,
green,
blue,
alpha,
}
}
}
#[cfg(feature = "encase")]
impl encase::ShaderSize for LinearRgba {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn euclidean_distance() {
// White to black
let a = LinearRgba::new(0.0, 0.0, 0.0, 1.0);
let b = LinearRgba::new(1.0, 1.0, 1.0, 1.0);
assert_eq!(a.distance_squared(&b), 3.0);
// Alpha shouldn't matter
let a = LinearRgba::new(0.0, 0.0, 0.0, 1.0);
let b = LinearRgba::new(1.0, 1.0, 1.0, 0.0);
assert_eq!(a.distance_squared(&b), 3.0);
// Red to green
let a = LinearRgba::new(0.0, 0.0, 0.0, 1.0);
let b = LinearRgba::new(1.0, 0.0, 0.0, 1.0);
assert_eq!(a.distance_squared(&b), 1.0);
}
#[test]
fn to_and_from_u8() {
// from_u8_array
let a = LinearRgba::from_u8_array([255, 0, 0, 255]);
let b = LinearRgba::new(1.0, 0.0, 0.0, 1.0);
assert_eq!(a, b);
// from_u8_array_no_alpha
let a = LinearRgba::from_u8_array_no_alpha([255, 255, 0]);
let b = LinearRgba::rgb(1.0, 1.0, 0.0);
assert_eq!(a, b);
// to_u8_array
let a = LinearRgba::new(0.0, 0.0, 1.0, 1.0).to_u8_array();
let b = [0, 0, 255, 255];
assert_eq!(a, b);
// to_u8_array_no_alpha
let a = LinearRgba::rgb(0.0, 1.0, 1.0).to_u8_array_no_alpha();
let b = [0, 255, 255];
assert_eq!(a, b);
// clamping
let a = LinearRgba::rgb(0.0, 100.0, -100.0).to_u8_array_no_alpha();
let b = [0, 255, 0];
assert_eq!(a, b);
}
#[test]
fn darker_lighter() {
// Darker and lighter should be commutative.
let color = LinearRgba::new(0.4, 0.5, 0.6, 1.0);
let darker1 = color.darker(0.1);
let darker2 = darker1.darker(0.1);
let twice_as_dark = color.darker(0.2);
assert!(darker2.distance_squared(&twice_as_dark) < 0.0001);
let lighter1 = color.lighter(0.1);
let lighter2 = lighter1.lighter(0.1);
let twice_as_light = color.lighter(0.2);
assert!(lighter2.distance_squared(&twice_as_light) < 0.0001);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_color/src/palettes/css.rs | crates/bevy_color/src/palettes/css.rs | //! [Extended colors from the CSS4 specification](https://en.wikipedia.org/wiki/Web_colors#Extended_colors),
//! Also known as X11 colors, which were standardized in HTML 4.0.
use crate::Srgba;
// The CSS4 colors are a superset of the CSS1 colors, so we can just re-export the CSS1 colors.
pub use crate::palettes::basic::*;
/// <div style="background-color:rgb(94.1%, 97.3%, 100.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ALICE_BLUE: Srgba = Srgba::new(0.941, 0.973, 1.0, 1.0);
/// <div style="background-color:rgb(98.0%, 92.2%, 84.3%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ANTIQUE_WHITE: Srgba = Srgba::new(0.98, 0.922, 0.843, 1.0);
/// <div style="background-color:rgb(0.0%, 100.0%, 100.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const AQUA: Srgba = Srgba::new(0.0, 1.0, 1.0, 1.0);
/// <div style="background-color:rgb(49.8%, 100.0%, 83.1%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const AQUAMARINE: Srgba = Srgba::new(0.498, 1.0, 0.831, 1.0);
/// <div style="background-color:rgb(94.1%, 100.0%, 100.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const AZURE: Srgba = Srgba::new(0.941, 1.0, 1.0, 1.0);
/// <div style="background-color:rgb(96.1%, 96.1%, 86.3%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const BEIGE: Srgba = Srgba::new(0.961, 0.961, 0.863, 1.0);
/// <div style="background-color:rgb(100.0%, 89.4%, 76.9%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const BISQUE: Srgba = Srgba::new(1.0, 0.894, 0.769, 1.0);
/// <div style="background-color:rgb(100.0%, 92.2%, 80.4%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const BLANCHED_ALMOND: Srgba = Srgba::new(1.0, 0.922, 0.804, 1.0);
/// <div style="background-color:rgb(54.1%, 16.900000000000002%, 88.6%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const BLUE_VIOLET: Srgba = Srgba::new(0.541, 0.169, 0.886, 1.0);
/// <div style="background-color:rgb(64.7%, 16.5%, 16.5%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const BROWN: Srgba = Srgba::new(0.647, 0.165, 0.165, 1.0);
/// <div style="background-color:rgb(87.1%, 72.2%, 52.900000000000006%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const BURLYWOOD: Srgba = Srgba::new(0.871, 0.722, 0.529, 1.0);
/// <div style="background-color:rgb(37.3%, 62.0%, 62.7%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const CADET_BLUE: Srgba = Srgba::new(0.373, 0.62, 0.627, 1.0);
/// <div style="background-color:rgb(49.8%, 100.0%, 0.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const CHARTREUSE: Srgba = Srgba::new(0.498, 1.0, 0.0, 1.0);
/// <div style="background-color:rgb(82.39999999999999%, 41.199999999999996%, 11.799999999999999%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const CHOCOLATE: Srgba = Srgba::new(0.824, 0.412, 0.118, 1.0);
/// <div style="background-color:rgb(100.0%, 49.8%, 31.4%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const CORAL: Srgba = Srgba::new(1.0, 0.498, 0.314, 1.0);
/// <div style="background-color:rgb(39.2%, 58.4%, 92.9%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const CORNFLOWER_BLUE: Srgba = Srgba::new(0.392, 0.584, 0.929, 1.0);
/// <div style="background-color:rgb(100.0%, 97.3%, 86.3%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const CORNSILK: Srgba = Srgba::new(1.0, 0.973, 0.863, 1.0);
/// <div style="background-color:rgb(86.3%, 7.8%, 23.5%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const CRIMSON: Srgba = Srgba::new(0.863, 0.078, 0.235, 1.0);
/// <div style="background-color:rgb(0.0%, 0.0%, 54.50000000000001%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const DARK_BLUE: Srgba = Srgba::new(0.0, 0.0, 0.545, 1.0);
/// <div style="background-color:rgb(0.0%, 54.50000000000001%, 54.50000000000001%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const DARK_CYAN: Srgba = Srgba::new(0.0, 0.545, 0.545, 1.0);
/// <div style="background-color:rgb(72.2%, 52.5%, 4.3%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const DARK_GOLDENROD: Srgba = Srgba::new(0.722, 0.525, 0.043, 1.0);
/// <div style="background-color:rgb(66.3%, 66.3%, 66.3%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const DARK_GRAY: Srgba = Srgba::new(0.663, 0.663, 0.663, 1.0);
/// <div style="background-color:rgb(0.0%, 39.2%, 0.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const DARK_GREEN: Srgba = Srgba::new(0.0, 0.392, 0.0, 1.0);
/// <div style="background-color:rgb(66.3%, 66.3%, 66.3%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const DARK_GREY: Srgba = Srgba::new(0.663, 0.663, 0.663, 1.0);
/// <div style="background-color:rgb(74.1%, 71.8%, 42.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const DARK_KHAKI: Srgba = Srgba::new(0.741, 0.718, 0.42, 1.0);
/// <div style="background-color:rgb(54.50000000000001%, 0.0%, 54.50000000000001%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const DARK_MAGENTA: Srgba = Srgba::new(0.545, 0.0, 0.545, 1.0);
/// <div style="background-color:rgb(33.300000000000004%, 42.0%, 18.4%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const DARK_OLIVEGREEN: Srgba = Srgba::new(0.333, 0.42, 0.184, 1.0);
/// <div style="background-color:rgb(100.0%, 54.900000000000006%, 0.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const DARK_ORANGE: Srgba = Srgba::new(1.0, 0.549, 0.0, 1.0);
/// <div style="background-color:rgb(60.0%, 19.6%, 80.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const DARK_ORCHID: Srgba = Srgba::new(0.6, 0.196, 0.8, 1.0);
/// <div style="background-color:rgb(54.50000000000001%, 0.0%, 0.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const DARK_RED: Srgba = Srgba::new(0.545, 0.0, 0.0, 1.0);
/// <div style="background-color:rgb(91.4%, 58.8%, 47.8%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const DARK_SALMON: Srgba = Srgba::new(0.914, 0.588, 0.478, 1.0);
/// <div style="background-color:rgb(56.10000000000001%, 73.7%, 56.10000000000001%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const DARK_SEA_GREEN: Srgba = Srgba::new(0.561, 0.737, 0.561, 1.0);
/// <div style="background-color:rgb(28.199999999999996%, 23.9%, 54.50000000000001%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const DARK_SLATE_BLUE: Srgba = Srgba::new(0.282, 0.239, 0.545, 1.0);
/// <div style="background-color:rgb(18.4%, 31.0%, 31.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const DARK_SLATE_GRAY: Srgba = Srgba::new(0.184, 0.31, 0.31, 1.0);
/// <div style="background-color:rgb(18.4%, 31.0%, 31.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const DARK_SLATE_GREY: Srgba = Srgba::new(0.184, 0.31, 0.31, 1.0);
/// <div style="background-color:rgb(0.0%, 80.80000000000001%, 82.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const DARK_TURQUOISE: Srgba = Srgba::new(0.0, 0.808, 0.82, 1.0);
/// <div style="background-color:rgb(57.99999999999999%, 0.0%, 82.69999999999999%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const DARK_VIOLET: Srgba = Srgba::new(0.58, 0.0, 0.827, 1.0);
/// <div style="background-color:rgb(100.0%, 7.8%, 57.599999999999994%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const DEEP_PINK: Srgba = Srgba::new(1.0, 0.078, 0.576, 1.0);
/// <div style="background-color:rgb(0.0%, 74.9%, 100.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const DEEP_SKY_BLUE: Srgba = Srgba::new(0.0, 0.749, 1.0, 1.0);
/// <div style="background-color:rgb(41.199999999999996%, 41.199999999999996%, 41.199999999999996%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const DIM_GRAY: Srgba = Srgba::new(0.412, 0.412, 0.412, 1.0);
/// <div style="background-color:rgb(41.199999999999996%, 41.199999999999996%, 41.199999999999996%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const DIM_GREY: Srgba = Srgba::new(0.412, 0.412, 0.412, 1.0);
/// <div style="background-color:rgb(11.799999999999999%, 56.49999999999999%, 100.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const DODGER_BLUE: Srgba = Srgba::new(0.118, 0.565, 1.0, 1.0);
/// <div style="background-color:rgb(69.8%, 13.3%, 13.3%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const FIRE_BRICK: Srgba = Srgba::new(0.698, 0.133, 0.133, 1.0);
/// <div style="background-color:rgb(100.0%, 98.0%, 94.1%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const FLORAL_WHITE: Srgba = Srgba::new(1.0, 0.98, 0.941, 1.0);
/// <div style="background-color:rgb(13.3%, 54.50000000000001%, 13.3%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const FOREST_GREEN: Srgba = Srgba::new(0.133, 0.545, 0.133, 1.0);
/// <div style="background-color:rgb(86.3%, 86.3%, 86.3%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GAINSBORO: Srgba = Srgba::new(0.863, 0.863, 0.863, 1.0);
/// <div style="background-color:rgb(97.3%, 97.3%, 100.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GHOST_WHITE: Srgba = Srgba::new(0.973, 0.973, 1.0, 1.0);
/// <div style="background-color:rgb(100.0%, 84.3%, 0.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GOLD: Srgba = Srgba::new(1.0, 0.843, 0.0, 1.0);
/// <div style="background-color:rgb(85.5%, 64.7%, 12.5%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GOLDENROD: Srgba = Srgba::new(0.855, 0.647, 0.125, 1.0);
/// <div style="background-color:rgb(0.0%, 50.2%, 0.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GREEN_YELLOW: Srgba = Srgba::new(0.678, 1.0, 0.184, 1.0);
/// <div style="background-color:rgb(50.2%, 50.2%, 50.2%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GREY: Srgba = Srgba::new(0.502, 0.502, 0.502, 1.0);
/// <div style="background-color:rgb(94.1%, 100.0%, 94.1%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const HONEYDEW: Srgba = Srgba::new(0.941, 1.0, 0.941, 1.0);
/// <div style="background-color:rgb(100.0%, 41.199999999999996%, 70.6%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const HOT_PINK: Srgba = Srgba::new(1.0, 0.412, 0.706, 1.0);
/// <div style="background-color:rgb(80.4%, 36.1%, 36.1%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const INDIAN_RED: Srgba = Srgba::new(0.804, 0.361, 0.361, 1.0);
/// <div style="background-color:rgb(29.4%, 0.0%, 51.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const INDIGO: Srgba = Srgba::new(0.294, 0.0, 0.51, 1.0);
/// <div style="background-color:rgb(100.0%, 100.0%, 94.1%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const IVORY: Srgba = Srgba::new(1.0, 1.0, 0.941, 1.0);
/// <div style="background-color:rgb(94.1%, 90.2%, 54.900000000000006%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const KHAKI: Srgba = Srgba::new(0.941, 0.902, 0.549, 1.0);
/// <div style="background-color:rgb(90.2%, 90.2%, 98.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LAVENDER: Srgba = Srgba::new(0.902, 0.902, 0.98, 1.0);
/// <div style="background-color:rgb(100.0%, 94.1%, 96.1%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LAVENDER_BLUSH: Srgba = Srgba::new(1.0, 0.941, 0.961, 1.0);
/// <div style="background-color:rgb(48.6%, 98.8%, 0.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LAWN_GREEN: Srgba = Srgba::new(0.486, 0.988, 0.0, 1.0);
/// <div style="background-color:rgb(100.0%, 98.0%, 80.4%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LEMON_CHIFFON: Srgba = Srgba::new(1.0, 0.98, 0.804, 1.0);
/// <div style="background-color:rgb(67.80000000000001%, 84.7%, 90.2%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIGHT_BLUE: Srgba = Srgba::new(0.678, 0.847, 0.902, 1.0);
/// <div style="background-color:rgb(94.1%, 50.2%, 50.2%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIGHT_CORAL: Srgba = Srgba::new(0.941, 0.502, 0.502, 1.0);
/// <div style="background-color:rgb(87.8%, 100.0%, 100.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIGHT_CYAN: Srgba = Srgba::new(0.878, 1.0, 1.0, 1.0);
/// <div style="background-color:rgb(98.0%, 98.0%, 82.39999999999999%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIGHT_GOLDENROD_YELLOW: Srgba = Srgba::new(0.98, 0.98, 0.824, 1.0);
/// <div style="background-color:rgb(82.69999999999999%, 82.69999999999999%, 82.69999999999999%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIGHT_GRAY: Srgba = Srgba::new(0.827, 0.827, 0.827, 1.0);
/// <div style="background-color:rgb(56.49999999999999%, 93.30000000000001%, 56.49999999999999%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIGHT_GREEN: Srgba = Srgba::new(0.565, 0.933, 0.565, 1.0);
/// <div style="background-color:rgb(82.69999999999999%, 82.69999999999999%, 82.69999999999999%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIGHT_GREY: Srgba = Srgba::new(0.827, 0.827, 0.827, 1.0);
/// <div style="background-color:rgb(100.0%, 71.39999999999999%, 75.7%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIGHT_PINK: Srgba = Srgba::new(1.0, 0.714, 0.757, 1.0);
/// <div style="background-color:rgb(100.0%, 62.7%, 47.8%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIGHT_SALMON: Srgba = Srgba::new(1.0, 0.627, 0.478, 1.0);
/// <div style="background-color:rgb(12.5%, 69.8%, 66.7%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIGHT_SEA_GREEN: Srgba = Srgba::new(0.125, 0.698, 0.667, 1.0);
/// <div style="background-color:rgb(52.900000000000006%, 80.80000000000001%, 98.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIGHT_SKY_BLUE: Srgba = Srgba::new(0.529, 0.808, 0.98, 1.0);
/// <div style="background-color:rgb(46.7%, 53.300000000000004%, 60.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIGHT_SLATE_GRAY: Srgba = Srgba::new(0.467, 0.533, 0.6, 1.0);
/// <div style="background-color:rgb(46.7%, 53.300000000000004%, 60.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIGHT_SLATE_GREY: Srgba = Srgba::new(0.467, 0.533, 0.6, 1.0);
/// <div style="background-color:rgb(69.0%, 76.9%, 87.1%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIGHT_STEEL_BLUE: Srgba = Srgba::new(0.69, 0.769, 0.871, 1.0);
/// <div style="background-color:rgb(100.0%, 100.0%, 87.8%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIGHT_YELLOW: Srgba = Srgba::new(1.0, 1.0, 0.878, 1.0);
/// <div style="background-color:rgb(19.6%, 80.4%, 19.6%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIMEGREEN: Srgba = Srgba::new(0.196, 0.804, 0.196, 1.0);
/// <div style="background-color:rgb(98.0%, 94.1%, 90.2%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LINEN: Srgba = Srgba::new(0.98, 0.941, 0.902, 1.0);
/// <div style="background-color:rgb(100.0%, 0.0%, 100.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const MAGENTA: Srgba = Srgba::new(1.0, 0.0, 1.0, 1.0);
/// <div style="background-color:rgb(40.0%, 80.4%, 66.7%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const MEDIUM_AQUAMARINE: Srgba = Srgba::new(0.4, 0.804, 0.667, 1.0);
/// <div style="background-color:rgb(0.0%, 0.0%, 80.4%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const MEDIUM_BLUE: Srgba = Srgba::new(0.0, 0.0, 0.804, 1.0);
/// <div style="background-color:rgb(72.89999999999999%, 33.300000000000004%, 82.69999999999999%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const MEDIUM_ORCHID: Srgba = Srgba::new(0.729, 0.333, 0.827, 1.0);
/// <div style="background-color:rgb(57.599999999999994%, 43.9%, 85.9%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const MEDIUM_PURPLE: Srgba = Srgba::new(0.576, 0.439, 0.859, 1.0);
/// <div style="background-color:rgb(23.5%, 70.19999999999999%, 44.3%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const MEDIUM_SEA_GREEN: Srgba = Srgba::new(0.235, 0.702, 0.443, 1.0);
/// <div style="background-color:rgb(48.199999999999996%, 40.8%, 93.30000000000001%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const MEDIUM_SLATE_BLUE: Srgba = Srgba::new(0.482, 0.408, 0.933, 1.0);
/// <div style="background-color:rgb(0.0%, 98.0%, 60.4%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const MEDIUM_SPRING_GREEN: Srgba = Srgba::new(0.0, 0.98, 0.604, 1.0);
/// <div style="background-color:rgb(28.199999999999996%, 82.0%, 80.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const MEDIUM_TURQUOISE: Srgba = Srgba::new(0.282, 0.82, 0.8, 1.0);
/// <div style="background-color:rgb(78.0%, 8.200000000000001%, 52.2%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const MEDIUM_VIOLET_RED: Srgba = Srgba::new(0.78, 0.082, 0.522, 1.0);
/// <div style="background-color:rgb(9.8%, 9.8%, 43.9%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const MIDNIGHT_BLUE: Srgba = Srgba::new(0.098, 0.098, 0.439, 1.0);
/// <div style="background-color:rgb(96.1%, 100.0%, 98.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const MINT_CREAM: Srgba = Srgba::new(0.961, 1.0, 0.98, 1.0);
/// <div style="background-color:rgb(100.0%, 89.4%, 88.2%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const MISTY_ROSE: Srgba = Srgba::new(1.0, 0.894, 0.882, 1.0);
/// <div style="background-color:rgb(100.0%, 89.4%, 71.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const MOCCASIN: Srgba = Srgba::new(1.0, 0.894, 0.71, 1.0);
/// <div style="background-color:rgb(100.0%, 87.1%, 67.80000000000001%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const NAVAJO_WHITE: Srgba = Srgba::new(1.0, 0.871, 0.678, 1.0);
/// <div style="background-color:rgb(99.2%, 96.1%, 90.2%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const OLD_LACE: Srgba = Srgba::new(0.992, 0.961, 0.902, 1.0);
/// <div style="background-color:rgb(42.0%, 55.7%, 13.700000000000001%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const OLIVE_DRAB: Srgba = Srgba::new(0.42, 0.557, 0.137, 1.0);
/// <div style="background-color:rgb(100.0%, 64.7%, 0.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ORANGE: Srgba = Srgba::new(1.0, 0.647, 0.0, 1.0);
/// <div style="background-color:rgb(100.0%, 27.1%, 0.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ORANGE_RED: Srgba = Srgba::new(1.0, 0.271, 0.0, 1.0);
/// <div style="background-color:rgb(85.5%, 43.9%, 83.89999999999999%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ORCHID: Srgba = Srgba::new(0.855, 0.439, 0.839, 1.0);
/// <div style="background-color:rgb(93.30000000000001%, 91.0%, 66.7%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PALE_GOLDENROD: Srgba = Srgba::new(0.933, 0.91, 0.667, 1.0);
/// <div style="background-color:rgb(59.599999999999994%, 98.4%, 59.599999999999994%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PALE_GREEN: Srgba = Srgba::new(0.596, 0.984, 0.596, 1.0);
/// <div style="background-color:rgb(68.60000000000001%, 93.30000000000001%, 93.30000000000001%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PALE_TURQUOISE: Srgba = Srgba::new(0.686, 0.933, 0.933, 1.0);
/// <div style="background-color:rgb(85.9%, 43.9%, 57.599999999999994%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PALE_VIOLETRED: Srgba = Srgba::new(0.859, 0.439, 0.576, 1.0);
/// <div style="background-color:rgb(100.0%, 93.7%, 83.5%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PAPAYA_WHIP: Srgba = Srgba::new(1.0, 0.937, 0.835, 1.0);
/// <div style="background-color:rgb(100.0%, 85.5%, 72.5%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PEACHPUFF: Srgba = Srgba::new(1.0, 0.855, 0.725, 1.0);
/// <div style="background-color:rgb(80.4%, 52.2%, 24.7%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PERU: Srgba = Srgba::new(0.804, 0.522, 0.247, 1.0);
/// <div style="background-color:rgb(100.0%, 75.3%, 79.60000000000001%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PINK: Srgba = Srgba::new(1.0, 0.753, 0.796, 1.0);
/// <div style="background-color:rgb(86.7%, 62.7%, 86.7%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PLUM: Srgba = Srgba::new(0.867, 0.627, 0.867, 1.0);
/// <div style="background-color:rgb(69.0%, 87.8%, 90.2%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const POWDER_BLUE: Srgba = Srgba::new(0.69, 0.878, 0.902, 1.0);
/// <div style="background-color:rgb(40.0%, 20.0%, 60.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const REBECCA_PURPLE: Srgba = Srgba::new(0.4, 0.2, 0.6, 1.0);
/// <div style="background-color:rgb(73.7%, 56.10000000000001%, 56.10000000000001%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ROSY_BROWN: Srgba = Srgba::new(0.737, 0.561, 0.561, 1.0);
/// <div style="background-color:rgb(25.5%, 41.199999999999996%, 88.2%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ROYAL_BLUE: Srgba = Srgba::new(0.255, 0.412, 0.882, 1.0);
/// <div style="background-color:rgb(54.50000000000001%, 27.1%, 7.5%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const SADDLE_BROWN: Srgba = Srgba::new(0.545, 0.271, 0.075, 1.0);
/// <div style="background-color:rgb(98.0%, 50.2%, 44.7%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const SALMON: Srgba = Srgba::new(0.98, 0.502, 0.447, 1.0);
/// <div style="background-color:rgb(95.7%, 64.3%, 37.6%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const SANDY_BROWN: Srgba = Srgba::new(0.957, 0.643, 0.376, 1.0);
/// <div style="background-color:rgb(18.0%, 54.50000000000001%, 34.1%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const SEA_GREEN: Srgba = Srgba::new(0.18, 0.545, 0.341, 1.0);
/// <div style="background-color:rgb(100.0%, 96.1%, 93.30000000000001%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const SEASHELL: Srgba = Srgba::new(1.0, 0.961, 0.933, 1.0);
/// <div style="background-color:rgb(62.7%, 32.2%, 17.599999999999998%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const SIENNA: Srgba = Srgba::new(0.627, 0.322, 0.176, 1.0);
/// <div style="background-color:rgb(52.900000000000006%, 80.80000000000001%, 92.2%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const SKY_BLUE: Srgba = Srgba::new(0.529, 0.808, 0.922, 1.0);
/// <div style="background-color:rgb(41.6%, 35.3%, 80.4%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const SLATE_BLUE: Srgba = Srgba::new(0.416, 0.353, 0.804, 1.0);
/// <div style="background-color:rgb(43.9%, 50.2%, 56.49999999999999%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const SLATE_GRAY: Srgba = Srgba::new(0.439, 0.502, 0.565, 1.0);
/// <div style="background-color:rgb(43.9%, 50.2%, 56.49999999999999%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const SLATE_GREY: Srgba = Srgba::new(0.439, 0.502, 0.565, 1.0);
/// <div style="background-color:rgb(100.0%, 98.0%, 98.0%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const SNOW: Srgba = Srgba::new(1.0, 0.98, 0.98, 1.0);
/// <div style="background-color:rgb(0.0%, 100.0%, 49.8%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const SPRING_GREEN: Srgba = Srgba::new(0.0, 1.0, 0.498, 1.0);
/// <div style="background-color:rgb(27.500000000000004%, 51.0%, 70.6%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const STEEL_BLUE: Srgba = Srgba::new(0.275, 0.51, 0.706, 1.0);
/// <div style="background-color:rgb(82.39999999999999%, 70.6%, 54.900000000000006%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const TAN: Srgba = Srgba::new(0.824, 0.706, 0.549, 1.0);
/// <div style="background-color:rgb(84.7%, 74.9%, 84.7%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const THISTLE: Srgba = Srgba::new(0.847, 0.749, 0.847, 1.0);
/// <div style="background-color:rgb(100.0%, 38.800000000000004%, 27.800000000000004%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const TOMATO: Srgba = Srgba::new(1.0, 0.388, 0.278, 1.0);
/// <div style="background-color:rgb(25.1%, 87.8%, 81.6%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const TURQUOISE: Srgba = Srgba::new(0.251, 0.878, 0.816, 1.0);
/// <div style="background-color:rgb(93.30000000000001%, 51.0%, 93.30000000000001%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const VIOLET: Srgba = Srgba::new(0.933, 0.51, 0.933, 1.0);
/// <div style="background-color:rgb(96.1%, 87.1%, 70.19999999999999%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const WHEAT: Srgba = Srgba::new(0.961, 0.871, 0.702, 1.0);
/// <div style="background-color:rgb(96.1%, 96.1%, 96.1%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const WHITE_SMOKE: Srgba = Srgba::new(0.961, 0.961, 0.961, 1.0);
/// <div style="background-color:rgb(60.4%, 80.4%, 19.6%); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const YELLOW_GREEN: Srgba = Srgba::new(0.604, 0.804, 0.196, 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_color/src/palettes/mod.rs | crates/bevy_color/src/palettes/mod.rs | //! Color palettes consisting of collections of const colors.
pub mod basic;
pub mod css;
pub mod tailwind;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_color/src/palettes/basic.rs | crates/bevy_color/src/palettes/basic.rs | //! Named colors from the CSS1 specification, also known as
//! [basic colors](https://en.wikipedia.org/wiki/Web_colors#Basic_colors).
//! This is the same set of colors used in the
//! [VGA graphics standard](https://en.wikipedia.org/wiki/Video_Graphics_Array).
use crate::Srgba;
/// <div style="background-color: #00FFFF; width: 10px; padding: 10px; border: 1px solid;"></div>
pub const AQUA: Srgba = Srgba::rgb(0.0, 1.0, 1.0);
/// <div style="background-color: #000000; width: 10px; padding: 10px; border: 1px solid;"></div>
pub const BLACK: Srgba = Srgba::rgb(0.0, 0.0, 0.0);
/// <div style="background-color: #0000FF; width: 10px; padding: 10px; border: 1px solid;"></div>
pub const BLUE: Srgba = Srgba::rgb(0.0, 0.0, 1.0);
/// <div style="background-color: #FF00FF; width: 10px; padding: 10px; border: 1px solid;"></div>
pub const FUCHSIA: Srgba = Srgba::rgb(1.0, 0.0, 1.0);
/// <div style="background-color: #808080; width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GRAY: Srgba = Srgba::rgb(0.5019608, 0.5019608, 0.5019608);
/// <div style="background-color: #008000; width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GREEN: Srgba = Srgba::rgb(0.0, 0.5019608, 0.0);
/// <div style="background-color: #00FF00; width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIME: Srgba = Srgba::rgb(0.0, 1.0, 0.0);
/// <div style="background-color: #800000; width: 10px; padding: 10px; border: 1px solid;"></div>
pub const MAROON: Srgba = Srgba::rgb(0.5019608, 0.0, 0.0);
/// <div style="background-color: #000080; width: 10px; padding: 10px; border: 1px solid;"></div>
pub const NAVY: Srgba = Srgba::rgb(0.0, 0.0, 0.5019608);
/// <div style="background-color: #808000; width: 10px; padding: 10px; border: 1px solid;"></div>
pub const OLIVE: Srgba = Srgba::rgb(0.5019608, 0.5019608, 0.0);
/// <div style="background-color: #800080; width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PURPLE: Srgba = Srgba::rgb(0.5019608, 0.0, 0.5019608);
/// <div style="background-color: #FF0000; width: 10px; padding: 10px; border: 1px solid;"></div>
pub const RED: Srgba = Srgba::rgb(1.0, 0.0, 0.0);
/// <div style="background-color: #C0C0C0; width: 10px; padding: 10px; border: 1px solid;"></div>
pub const SILVER: Srgba = Srgba::rgb(0.7529412, 0.7529412, 0.7529412);
/// <div style="background-color: #008080; width: 10px; padding: 10px; border: 1px solid;"></div>
pub const TEAL: Srgba = Srgba::rgb(0.0, 0.5019608, 0.5019608);
/// <div style="background-color: #FFFFFF; width: 10px; padding: 10px; border: 1px solid;"></div>
pub const WHITE: Srgba = Srgba::rgb(1.0, 1.0, 1.0);
/// <div style="background-color: #FFFF00; width: 10px; padding: 10px; border: 1px solid;"></div>
pub const YELLOW: Srgba = Srgba::rgb(1.0, 1.0, 0.0);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_color/src/palettes/tailwind.rs | crates/bevy_color/src/palettes/tailwind.rs | //! Colors from [Tailwind CSS](https://tailwindcss.com/docs/customizing-colors) (MIT License).
//! Grouped by hue with numeric lightness scale (50 is light, 950 is dark).
//!
//! Generated from Tailwind 3.4.1.
// MIT License
//
// Copyright (c) Tailwind Labs, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use crate::Srgba;
/// <div style="background-color:rgb(255, 251, 235); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const AMBER_50: Srgba = Srgba::rgb(1.0, 0.9843137, 0.92156863);
/// <div style="background-color:rgb(254, 243, 199); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const AMBER_100: Srgba = Srgba::rgb(0.99607843, 0.9529412, 0.78039217);
/// <div style="background-color:rgb(253, 230, 138); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const AMBER_200: Srgba = Srgba::rgb(0.99215686, 0.9019608, 0.5411765);
/// <div style="background-color:rgb(252, 211, 77); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const AMBER_300: Srgba = Srgba::rgb(0.9882353, 0.827451, 0.3019608);
/// <div style="background-color:rgb(251, 191, 36); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const AMBER_400: Srgba = Srgba::rgb(0.9843137, 0.7490196, 0.14117648);
/// <div style="background-color:rgb(245, 158, 11); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const AMBER_500: Srgba = Srgba::rgb(0.9607843, 0.61960787, 0.043137256);
/// <div style="background-color:rgb(217, 119, 6); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const AMBER_600: Srgba = Srgba::rgb(0.8509804, 0.46666667, 0.023529412);
/// <div style="background-color:rgb(180, 83, 9); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const AMBER_700: Srgba = Srgba::rgb(0.7058824, 0.3254902, 0.03529412);
/// <div style="background-color:rgb(146, 64, 14); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const AMBER_800: Srgba = Srgba::rgb(0.57254905, 0.2509804, 0.05490196);
/// <div style="background-color:rgb(120, 53, 15); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const AMBER_900: Srgba = Srgba::rgb(0.47058824, 0.20784314, 0.05882353);
/// <div style="background-color:rgb(69, 26, 3); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const AMBER_950: Srgba = Srgba::rgb(0.27058825, 0.101960786, 0.011764706);
/// <div style="background-color:rgb(239, 246, 255); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const BLUE_50: Srgba = Srgba::rgb(0.9372549, 0.9647059, 1.0);
/// <div style="background-color:rgb(219, 234, 254); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const BLUE_100: Srgba = Srgba::rgb(0.85882354, 0.91764706, 0.99607843);
/// <div style="background-color:rgb(191, 219, 254); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const BLUE_200: Srgba = Srgba::rgb(0.7490196, 0.85882354, 0.99607843);
/// <div style="background-color:rgb(147, 197, 253); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const BLUE_300: Srgba = Srgba::rgb(0.5764706, 0.77254903, 0.99215686);
/// <div style="background-color:rgb(96, 165, 250); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const BLUE_400: Srgba = Srgba::rgb(0.3764706, 0.64705884, 0.98039216);
/// <div style="background-color:rgb(59, 130, 246); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const BLUE_500: Srgba = Srgba::rgb(0.23137255, 0.50980395, 0.9647059);
/// <div style="background-color:rgb(37, 99, 235); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const BLUE_600: Srgba = Srgba::rgb(0.14509805, 0.3882353, 0.92156863);
/// <div style="background-color:rgb(29, 78, 216); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const BLUE_700: Srgba = Srgba::rgb(0.11372549, 0.30588236, 0.84705883);
/// <div style="background-color:rgb(30, 64, 175); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const BLUE_800: Srgba = Srgba::rgb(0.11764706, 0.2509804, 0.6862745);
/// <div style="background-color:rgb(30, 58, 138); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const BLUE_900: Srgba = Srgba::rgb(0.11764706, 0.22745098, 0.5411765);
/// <div style="background-color:rgb(23, 37, 84); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const BLUE_950: Srgba = Srgba::rgb(0.09019608, 0.14509805, 0.32941177);
/// <div style="background-color:rgb(236, 254, 255); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const CYAN_50: Srgba = Srgba::rgb(0.9254902, 0.99607843, 1.0);
/// <div style="background-color:rgb(207, 250, 254); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const CYAN_100: Srgba = Srgba::rgb(0.8117647, 0.98039216, 0.99607843);
/// <div style="background-color:rgb(165, 243, 252); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const CYAN_200: Srgba = Srgba::rgb(0.64705884, 0.9529412, 0.9882353);
/// <div style="background-color:rgb(103, 232, 249); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const CYAN_300: Srgba = Srgba::rgb(0.40392157, 0.9098039, 0.9764706);
/// <div style="background-color:rgb(34, 211, 238); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const CYAN_400: Srgba = Srgba::rgb(0.13333334, 0.827451, 0.93333334);
/// <div style="background-color:rgb(6, 182, 212); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const CYAN_500: Srgba = Srgba::rgb(0.023529412, 0.7137255, 0.83137256);
/// <div style="background-color:rgb(8, 145, 178); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const CYAN_600: Srgba = Srgba::rgb(0.03137255, 0.5686275, 0.69803923);
/// <div style="background-color:rgb(14, 116, 144); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const CYAN_700: Srgba = Srgba::rgb(0.05490196, 0.45490196, 0.5647059);
/// <div style="background-color:rgb(21, 94, 117); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const CYAN_800: Srgba = Srgba::rgb(0.08235294, 0.36862746, 0.45882353);
/// <div style="background-color:rgb(22, 78, 99); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const CYAN_900: Srgba = Srgba::rgb(0.08627451, 0.30588236, 0.3882353);
/// <div style="background-color:rgb(8, 51, 68); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const CYAN_950: Srgba = Srgba::rgb(0.03137255, 0.2, 0.26666668);
/// <div style="background-color:rgb(236, 253, 245); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const EMERALD_50: Srgba = Srgba::rgb(0.9254902, 0.99215686, 0.9607843);
/// <div style="background-color:rgb(209, 250, 229); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const EMERALD_100: Srgba = Srgba::rgb(0.81960785, 0.98039216, 0.8980392);
/// <div style="background-color:rgb(167, 243, 208); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const EMERALD_200: Srgba = Srgba::rgb(0.654902, 0.9529412, 0.8156863);
/// <div style="background-color:rgb(110, 231, 183); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const EMERALD_300: Srgba = Srgba::rgb(0.43137255, 0.90588236, 0.7176471);
/// <div style="background-color:rgb(52, 211, 153); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const EMERALD_400: Srgba = Srgba::rgb(0.20392157, 0.827451, 0.6);
/// <div style="background-color:rgb(16, 185, 129); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const EMERALD_500: Srgba = Srgba::rgb(0.0627451, 0.7254902, 0.5058824);
/// <div style="background-color:rgb(5, 150, 105); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const EMERALD_600: Srgba = Srgba::rgb(0.019607844, 0.5882353, 0.4117647);
/// <div style="background-color:rgb(4, 120, 87); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const EMERALD_700: Srgba = Srgba::rgb(0.015686275, 0.47058824, 0.34117648);
/// <div style="background-color:rgb(6, 95, 70); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const EMERALD_800: Srgba = Srgba::rgb(0.023529412, 0.37254903, 0.27450982);
/// <div style="background-color:rgb(6, 78, 59); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const EMERALD_900: Srgba = Srgba::rgb(0.023529412, 0.30588236, 0.23137255);
/// <div style="background-color:rgb(2, 44, 34); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const EMERALD_950: Srgba = Srgba::rgb(0.007843138, 0.17254902, 0.13333334);
/// <div style="background-color:rgb(253, 244, 255); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const FUCHSIA_50: Srgba = Srgba::rgb(0.99215686, 0.95686275, 1.0);
/// <div style="background-color:rgb(250, 232, 255); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const FUCHSIA_100: Srgba = Srgba::rgb(0.98039216, 0.9098039, 1.0);
/// <div style="background-color:rgb(245, 208, 254); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const FUCHSIA_200: Srgba = Srgba::rgb(0.9607843, 0.8156863, 0.99607843);
/// <div style="background-color:rgb(240, 171, 252); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const FUCHSIA_300: Srgba = Srgba::rgb(0.9411765, 0.67058825, 0.9882353);
/// <div style="background-color:rgb(232, 121, 249); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const FUCHSIA_400: Srgba = Srgba::rgb(0.9098039, 0.4745098, 0.9764706);
/// <div style="background-color:rgb(217, 70, 239); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const FUCHSIA_500: Srgba = Srgba::rgb(0.8509804, 0.27450982, 0.9372549);
/// <div style="background-color:rgb(192, 38, 211); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const FUCHSIA_600: Srgba = Srgba::rgb(0.7529412, 0.14901961, 0.827451);
/// <div style="background-color:rgb(162, 28, 175); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const FUCHSIA_700: Srgba = Srgba::rgb(0.63529414, 0.10980392, 0.6862745);
/// <div style="background-color:rgb(134, 25, 143); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const FUCHSIA_800: Srgba = Srgba::rgb(0.5254902, 0.09803922, 0.56078434);
/// <div style="background-color:rgb(112, 26, 117); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const FUCHSIA_900: Srgba = Srgba::rgb(0.4392157, 0.101960786, 0.45882353);
/// <div style="background-color:rgb(74, 4, 78); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const FUCHSIA_950: Srgba = Srgba::rgb(0.2901961, 0.015686275, 0.30588236);
/// <div style="background-color:rgb(249, 250, 251); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GRAY_50: Srgba = Srgba::rgb(0.9764706, 0.98039216, 0.9843137);
/// <div style="background-color:rgb(243, 244, 246); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GRAY_100: Srgba = Srgba::rgb(0.9529412, 0.95686275, 0.9647059);
/// <div style="background-color:rgb(229, 231, 235); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GRAY_200: Srgba = Srgba::rgb(0.8980392, 0.90588236, 0.92156863);
/// <div style="background-color:rgb(209, 213, 219); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GRAY_300: Srgba = Srgba::rgb(0.81960785, 0.8352941, 0.85882354);
/// <div style="background-color:rgb(156, 163, 175); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GRAY_400: Srgba = Srgba::rgb(0.6117647, 0.6392157, 0.6862745);
/// <div style="background-color:rgb(107, 114, 128); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GRAY_500: Srgba = Srgba::rgb(0.41960785, 0.44705883, 0.5019608);
/// <div style="background-color:rgb(75, 85, 99); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GRAY_600: Srgba = Srgba::rgb(0.29411766, 0.33333334, 0.3882353);
/// <div style="background-color:rgb(55, 65, 81); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GRAY_700: Srgba = Srgba::rgb(0.21568628, 0.25490198, 0.31764707);
/// <div style="background-color:rgb(31, 41, 55); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GRAY_800: Srgba = Srgba::rgb(0.12156863, 0.16078432, 0.21568628);
/// <div style="background-color:rgb(17, 24, 39); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GRAY_900: Srgba = Srgba::rgb(0.06666667, 0.09411765, 0.15294118);
/// <div style="background-color:rgb(3, 7, 18); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GRAY_950: Srgba = Srgba::rgb(0.011764706, 0.02745098, 0.07058824);
/// <div style="background-color:rgb(240, 253, 244); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GREEN_50: Srgba = Srgba::rgb(0.9411765, 0.99215686, 0.95686275);
/// <div style="background-color:rgb(220, 252, 231); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GREEN_100: Srgba = Srgba::rgb(0.8627451, 0.9882353, 0.90588236);
/// <div style="background-color:rgb(187, 247, 208); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GREEN_200: Srgba = Srgba::rgb(0.73333335, 0.96862745, 0.8156863);
/// <div style="background-color:rgb(134, 239, 172); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GREEN_300: Srgba = Srgba::rgb(0.5254902, 0.9372549, 0.6745098);
/// <div style="background-color:rgb(74, 222, 128); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GREEN_400: Srgba = Srgba::rgb(0.2901961, 0.87058824, 0.5019608);
/// <div style="background-color:rgb(34, 197, 94); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GREEN_500: Srgba = Srgba::rgb(0.13333334, 0.77254903, 0.36862746);
/// <div style="background-color:rgb(22, 163, 74); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GREEN_600: Srgba = Srgba::rgb(0.08627451, 0.6392157, 0.2901961);
/// <div style="background-color:rgb(21, 128, 61); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GREEN_700: Srgba = Srgba::rgb(0.08235294, 0.5019608, 0.23921569);
/// <div style="background-color:rgb(22, 101, 52); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GREEN_800: Srgba = Srgba::rgb(0.08627451, 0.39607844, 0.20392157);
/// <div style="background-color:rgb(20, 83, 45); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GREEN_900: Srgba = Srgba::rgb(0.078431375, 0.3254902, 0.1764706);
/// <div style="background-color:rgb(5, 46, 22); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const GREEN_950: Srgba = Srgba::rgb(0.019607844, 0.18039216, 0.08627451);
/// <div style="background-color:rgb(238, 242, 255); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const INDIGO_50: Srgba = Srgba::rgb(0.93333334, 0.9490196, 1.0);
/// <div style="background-color:rgb(224, 231, 255); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const INDIGO_100: Srgba = Srgba::rgb(0.8784314, 0.90588236, 1.0);
/// <div style="background-color:rgb(199, 210, 254); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const INDIGO_200: Srgba = Srgba::rgb(0.78039217, 0.8235294, 0.99607843);
/// <div style="background-color:rgb(165, 180, 252); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const INDIGO_300: Srgba = Srgba::rgb(0.64705884, 0.7058824, 0.9882353);
/// <div style="background-color:rgb(129, 140, 248); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const INDIGO_400: Srgba = Srgba::rgb(0.5058824, 0.54901963, 0.972549);
/// <div style="background-color:rgb(99, 102, 241); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const INDIGO_500: Srgba = Srgba::rgb(0.3882353, 0.4, 0.94509804);
/// <div style="background-color:rgb(79, 70, 229); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const INDIGO_600: Srgba = Srgba::rgb(0.30980393, 0.27450982, 0.8980392);
/// <div style="background-color:rgb(67, 56, 202); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const INDIGO_700: Srgba = Srgba::rgb(0.2627451, 0.21960784, 0.7921569);
/// <div style="background-color:rgb(55, 48, 163); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const INDIGO_800: Srgba = Srgba::rgb(0.21568628, 0.1882353, 0.6392157);
/// <div style="background-color:rgb(49, 46, 129); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const INDIGO_900: Srgba = Srgba::rgb(0.19215687, 0.18039216, 0.5058824);
/// <div style="background-color:rgb(30, 27, 75); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const INDIGO_950: Srgba = Srgba::rgb(0.11764706, 0.105882354, 0.29411766);
/// <div style="background-color:rgb(247, 254, 231); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIME_50: Srgba = Srgba::rgb(0.96862745, 0.99607843, 0.90588236);
/// <div style="background-color:rgb(236, 252, 203); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIME_100: Srgba = Srgba::rgb(0.9254902, 0.9882353, 0.79607844);
/// <div style="background-color:rgb(217, 249, 157); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIME_200: Srgba = Srgba::rgb(0.8509804, 0.9764706, 0.6156863);
/// <div style="background-color:rgb(190, 242, 100); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIME_300: Srgba = Srgba::rgb(0.74509805, 0.9490196, 0.39215687);
/// <div style="background-color:rgb(163, 230, 53); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIME_400: Srgba = Srgba::rgb(0.6392157, 0.9019608, 0.20784314);
/// <div style="background-color:rgb(132, 204, 22); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIME_500: Srgba = Srgba::rgb(0.5176471, 0.8, 0.08627451);
/// <div style="background-color:rgb(101, 163, 13); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIME_600: Srgba = Srgba::rgb(0.39607844, 0.6392157, 0.050980393);
/// <div style="background-color:rgb(77, 124, 15); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIME_700: Srgba = Srgba::rgb(0.3019608, 0.4862745, 0.05882353);
/// <div style="background-color:rgb(63, 98, 18); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIME_800: Srgba = Srgba::rgb(0.24705882, 0.38431373, 0.07058824);
/// <div style="background-color:rgb(54, 83, 20); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIME_900: Srgba = Srgba::rgb(0.21176471, 0.3254902, 0.078431375);
/// <div style="background-color:rgb(26, 46, 5); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const LIME_950: Srgba = Srgba::rgb(0.101960786, 0.18039216, 0.019607844);
/// <div style="background-color:rgb(250, 250, 250); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const NEUTRAL_50: Srgba = Srgba::rgb(0.98039216, 0.98039216, 0.98039216);
/// <div style="background-color:rgb(245, 245, 245); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const NEUTRAL_100: Srgba = Srgba::rgb(0.9607843, 0.9607843, 0.9607843);
/// <div style="background-color:rgb(229, 229, 229); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const NEUTRAL_200: Srgba = Srgba::rgb(0.8980392, 0.8980392, 0.8980392);
/// <div style="background-color:rgb(212, 212, 212); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const NEUTRAL_300: Srgba = Srgba::rgb(0.83137256, 0.83137256, 0.83137256);
/// <div style="background-color:rgb(163, 163, 163); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const NEUTRAL_400: Srgba = Srgba::rgb(0.6392157, 0.6392157, 0.6392157);
/// <div style="background-color:rgb(115, 115, 115); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const NEUTRAL_500: Srgba = Srgba::rgb(0.4509804, 0.4509804, 0.4509804);
/// <div style="background-color:rgb(82, 82, 82); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const NEUTRAL_600: Srgba = Srgba::rgb(0.32156864, 0.32156864, 0.32156864);
/// <div style="background-color:rgb(64, 64, 64); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const NEUTRAL_700: Srgba = Srgba::rgb(0.2509804, 0.2509804, 0.2509804);
/// <div style="background-color:rgb(38, 38, 38); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const NEUTRAL_800: Srgba = Srgba::rgb(0.14901961, 0.14901961, 0.14901961);
/// <div style="background-color:rgb(23, 23, 23); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const NEUTRAL_900: Srgba = Srgba::rgb(0.09019608, 0.09019608, 0.09019608);
/// <div style="background-color:rgb(10, 10, 10); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const NEUTRAL_950: Srgba = Srgba::rgb(0.039215688, 0.039215688, 0.039215688);
/// <div style="background-color:rgb(255, 247, 237); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ORANGE_50: Srgba = Srgba::rgb(1.0, 0.96862745, 0.92941177);
/// <div style="background-color:rgb(255, 237, 213); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ORANGE_100: Srgba = Srgba::rgb(1.0, 0.92941177, 0.8352941);
/// <div style="background-color:rgb(254, 215, 170); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ORANGE_200: Srgba = Srgba::rgb(0.99607843, 0.84313726, 0.6666667);
/// <div style="background-color:rgb(253, 186, 116); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ORANGE_300: Srgba = Srgba::rgb(0.99215686, 0.7294118, 0.45490196);
/// <div style="background-color:rgb(251, 146, 60); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ORANGE_400: Srgba = Srgba::rgb(0.9843137, 0.57254905, 0.23529412);
/// <div style="background-color:rgb(249, 115, 22); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ORANGE_500: Srgba = Srgba::rgb(0.9764706, 0.4509804, 0.08627451);
/// <div style="background-color:rgb(234, 88, 12); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ORANGE_600: Srgba = Srgba::rgb(0.91764706, 0.34509805, 0.047058824);
/// <div style="background-color:rgb(194, 65, 12); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ORANGE_700: Srgba = Srgba::rgb(0.7607843, 0.25490198, 0.047058824);
/// <div style="background-color:rgb(154, 52, 18); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ORANGE_800: Srgba = Srgba::rgb(0.6039216, 0.20392157, 0.07058824);
/// <div style="background-color:rgb(124, 45, 18); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ORANGE_900: Srgba = Srgba::rgb(0.4862745, 0.1764706, 0.07058824);
/// <div style="background-color:rgb(67, 20, 7); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ORANGE_950: Srgba = Srgba::rgb(0.2627451, 0.078431375, 0.02745098);
/// <div style="background-color:rgb(253, 242, 248); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PINK_50: Srgba = Srgba::rgb(0.99215686, 0.9490196, 0.972549);
/// <div style="background-color:rgb(252, 231, 243); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PINK_100: Srgba = Srgba::rgb(0.9882353, 0.90588236, 0.9529412);
/// <div style="background-color:rgb(251, 207, 232); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PINK_200: Srgba = Srgba::rgb(0.9843137, 0.8117647, 0.9098039);
/// <div style="background-color:rgb(249, 168, 212); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PINK_300: Srgba = Srgba::rgb(0.9764706, 0.65882355, 0.83137256);
/// <div style="background-color:rgb(244, 114, 182); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PINK_400: Srgba = Srgba::rgb(0.95686275, 0.44705883, 0.7137255);
/// <div style="background-color:rgb(236, 72, 153); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PINK_500: Srgba = Srgba::rgb(0.9254902, 0.28235295, 0.6);
/// <div style="background-color:rgb(219, 39, 119); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PINK_600: Srgba = Srgba::rgb(0.85882354, 0.15294118, 0.46666667);
/// <div style="background-color:rgb(190, 24, 93); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PINK_700: Srgba = Srgba::rgb(0.74509805, 0.09411765, 0.3647059);
/// <div style="background-color:rgb(157, 23, 77); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PINK_800: Srgba = Srgba::rgb(0.6156863, 0.09019608, 0.3019608);
/// <div style="background-color:rgb(131, 24, 67); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PINK_900: Srgba = Srgba::rgb(0.5137255, 0.09411765, 0.2627451);
/// <div style="background-color:rgb(80, 7, 36); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PINK_950: Srgba = Srgba::rgb(0.3137255, 0.02745098, 0.14117648);
/// <div style="background-color:rgb(250, 245, 255); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PURPLE_50: Srgba = Srgba::rgb(0.98039216, 0.9607843, 1.0);
/// <div style="background-color:rgb(243, 232, 255); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PURPLE_100: Srgba = Srgba::rgb(0.9529412, 0.9098039, 1.0);
/// <div style="background-color:rgb(233, 213, 255); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PURPLE_200: Srgba = Srgba::rgb(0.9137255, 0.8352941, 1.0);
/// <div style="background-color:rgb(216, 180, 254); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PURPLE_300: Srgba = Srgba::rgb(0.84705883, 0.7058824, 0.99607843);
/// <div style="background-color:rgb(192, 132, 252); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PURPLE_400: Srgba = Srgba::rgb(0.7529412, 0.5176471, 0.9882353);
/// <div style="background-color:rgb(168, 85, 247); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PURPLE_500: Srgba = Srgba::rgb(0.65882355, 0.33333334, 0.96862745);
/// <div style="background-color:rgb(147, 51, 234); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PURPLE_600: Srgba = Srgba::rgb(0.5764706, 0.2, 0.91764706);
/// <div style="background-color:rgb(126, 34, 206); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PURPLE_700: Srgba = Srgba::rgb(0.49411765, 0.13333334, 0.80784315);
/// <div style="background-color:rgb(107, 33, 168); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PURPLE_800: Srgba = Srgba::rgb(0.41960785, 0.12941177, 0.65882355);
/// <div style="background-color:rgb(88, 28, 135); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PURPLE_900: Srgba = Srgba::rgb(0.34509805, 0.10980392, 0.5294118);
/// <div style="background-color:rgb(59, 7, 100); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const PURPLE_950: Srgba = Srgba::rgb(0.23137255, 0.02745098, 0.39215687);
/// <div style="background-color:rgb(254, 242, 242); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const RED_50: Srgba = Srgba::rgb(0.99607843, 0.9490196, 0.9490196);
/// <div style="background-color:rgb(254, 226, 226); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const RED_100: Srgba = Srgba::rgb(0.99607843, 0.8862745, 0.8862745);
/// <div style="background-color:rgb(254, 202, 202); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const RED_200: Srgba = Srgba::rgb(0.99607843, 0.7921569, 0.7921569);
/// <div style="background-color:rgb(252, 165, 165); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const RED_300: Srgba = Srgba::rgb(0.9882353, 0.64705884, 0.64705884);
/// <div style="background-color:rgb(248, 113, 113); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const RED_400: Srgba = Srgba::rgb(0.972549, 0.44313726, 0.44313726);
/// <div style="background-color:rgb(239, 68, 68); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const RED_500: Srgba = Srgba::rgb(0.9372549, 0.26666668, 0.26666668);
/// <div style="background-color:rgb(220, 38, 38); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const RED_600: Srgba = Srgba::rgb(0.8627451, 0.14901961, 0.14901961);
/// <div style="background-color:rgb(185, 28, 28); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const RED_700: Srgba = Srgba::rgb(0.7254902, 0.10980392, 0.10980392);
/// <div style="background-color:rgb(153, 27, 27); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const RED_800: Srgba = Srgba::rgb(0.6, 0.105882354, 0.105882354);
/// <div style="background-color:rgb(127, 29, 29); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const RED_900: Srgba = Srgba::rgb(0.49803922, 0.11372549, 0.11372549);
/// <div style="background-color:rgb(69, 10, 10); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const RED_950: Srgba = Srgba::rgb(0.27058825, 0.039215688, 0.039215688);
/// <div style="background-color:rgb(255, 241, 242); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ROSE_50: Srgba = Srgba::rgb(1.0, 0.94509804, 0.9490196);
/// <div style="background-color:rgb(255, 228, 230); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ROSE_100: Srgba = Srgba::rgb(1.0, 0.89411765, 0.9019608);
/// <div style="background-color:rgb(254, 205, 211); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ROSE_200: Srgba = Srgba::rgb(0.99607843, 0.8039216, 0.827451);
/// <div style="background-color:rgb(253, 164, 175); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ROSE_300: Srgba = Srgba::rgb(0.99215686, 0.6431373, 0.6862745);
/// <div style="background-color:rgb(251, 113, 133); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ROSE_400: Srgba = Srgba::rgb(0.9843137, 0.44313726, 0.52156866);
/// <div style="background-color:rgb(244, 63, 94); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ROSE_500: Srgba = Srgba::rgb(0.95686275, 0.24705882, 0.36862746);
/// <div style="background-color:rgb(225, 29, 72); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ROSE_600: Srgba = Srgba::rgb(0.88235295, 0.11372549, 0.28235295);
/// <div style="background-color:rgb(190, 18, 60); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ROSE_700: Srgba = Srgba::rgb(0.74509805, 0.07058824, 0.23529412);
/// <div style="background-color:rgb(159, 18, 57); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ROSE_800: Srgba = Srgba::rgb(0.62352943, 0.07058824, 0.22352941);
/// <div style="background-color:rgb(136, 19, 55); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ROSE_900: Srgba = Srgba::rgb(0.53333336, 0.07450981, 0.21568628);
/// <div style="background-color:rgb(76, 5, 25); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const ROSE_950: Srgba = Srgba::rgb(0.29803923, 0.019607844, 0.09803922);
/// <div style="background-color:rgb(240, 249, 255); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const SKY_50: Srgba = Srgba::rgb(0.9411765, 0.9764706, 1.0);
/// <div style="background-color:rgb(224, 242, 254); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const SKY_100: Srgba = Srgba::rgb(0.8784314, 0.9490196, 0.99607843);
/// <div style="background-color:rgb(186, 230, 253); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const SKY_200: Srgba = Srgba::rgb(0.7294118, 0.9019608, 0.99215686);
/// <div style="background-color:rgb(125, 211, 252); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const SKY_300: Srgba = Srgba::rgb(0.49019608, 0.827451, 0.9882353);
/// <div style="background-color:rgb(56, 189, 248); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const SKY_400: Srgba = Srgba::rgb(0.21960784, 0.7411765, 0.972549);
/// <div style="background-color:rgb(14, 165, 233); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const SKY_500: Srgba = Srgba::rgb(0.05490196, 0.64705884, 0.9137255);
/// <div style="background-color:rgb(2, 132, 199); width: 10px; padding: 10px; border: 1px solid;"></div>
pub const SKY_600: Srgba = Srgba::rgb(0.007843138, 0.5176471, 0.78039217);
/// <div style="background-color:rgb(3, 105, 161); width: 10px; padding: 10px; border: 1px solid;"></div>
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_color/crates/gen_tests/src/main.rs | crates/bevy_color/crates/gen_tests/src/main.rs | use palette::{Hsl, Hsv, Hwb, IntoColor, Lab, Lch, LinSrgb, Oklab, Oklch, Srgb, Xyz};
const TEST_COLORS: &[(f32, f32, f32, &str)] = &[
(0., 0., 0., "black"),
(1., 1., 1., "white"),
(1., 0., 0., "red"),
(0., 1., 0., "green"),
(0., 0., 1., "blue"),
(1., 1., 0., "yellow"),
(1., 0., 1., "magenta"),
(0., 1., 1., "cyan"),
(0.5, 0.5, 0.5, "gray"),
(0.5, 0.5, 0., "olive"),
(0.5, 0., 0.5, "purple"),
(0., 0.5, 0.5, "teal"),
(0.5, 0., 0., "maroon"),
(0., 0.5, 0., "lime"),
(0., 0., 0.5, "navy"),
(0.5, 0.5, 0., "orange"),
(0.5, 0., 0.5, "fuchsia"),
(0., 0.5, 0.5, "aqua"),
];
fn main() {
println!(
"// Generated by gen_tests. Do not edit.
#[cfg(test)]
use crate::{{Hsla, Hsva, Hwba, Srgba, LinearRgba, Oklaba, Oklcha, Laba, Lcha, Xyza}};
#[cfg(test)]
pub struct TestColor {{
pub name: &'static str,
pub rgb: Srgba,
pub linear_rgb: LinearRgba,
pub hsl: Hsla,
pub hsv: Hsva,
pub hwb: Hwba,
pub lab: Laba,
pub lch: Lcha,
pub oklab: Oklaba,
pub oklch: Oklcha,
pub xyz: Xyza,
}}
"
);
println!("// Table of equivalent colors in various color spaces");
println!("#[cfg(test)]");
println!("pub const TEST_COLORS: &[TestColor] = &[");
for (r, g, b, name) in TEST_COLORS {
let srgb = Srgb::new(*r, *g, *b);
let linear_rgb: LinSrgb = srgb.into_color();
let hsl: Hsl = srgb.into_color();
let hsv: Hsv = srgb.into_color();
let hwb: Hwb = srgb.into_color();
let lab: Lab = srgb.into_color();
let lch: Lch = srgb.into_color();
let oklab: Oklab = srgb.into_color();
let oklch: Oklch = srgb.into_color();
let xyz: Xyz = srgb.into_color();
println!(" // {name}");
println!(
" TestColor {{
name: \"{name}\",
rgb: Srgba::new({}, {}, {}, 1.0),
linear_rgb: LinearRgba::new({}, {}, {}, 1.0),
hsl: Hsla::new({}, {}, {}, 1.0),
hsv: Hsva::new({}, {}, {}, 1.0),
hwb: Hwba::new({}, {}, {}, 1.0),
lab: Laba::new({}, {}, {}, 1.0),
lch: Lcha::new({}, {}, {}, 1.0),
oklab: Oklaba::new({}, {}, {}, 1.0),
oklch: Oklcha::new({}, {}, {}, 1.0),
xyz: Xyza::new({}, {}, {}, 1.0),
}},",
VariablePrecision(srgb.red),
VariablePrecision(srgb.green),
VariablePrecision(srgb.blue),
VariablePrecision(linear_rgb.red),
VariablePrecision(linear_rgb.green),
VariablePrecision(linear_rgb.blue),
VariablePrecision(hsl.hue.into_positive_degrees()),
VariablePrecision(hsl.saturation),
VariablePrecision(hsl.lightness),
VariablePrecision(hsv.hue.into_positive_degrees()),
VariablePrecision(hsv.saturation),
VariablePrecision(hsv.value),
VariablePrecision(hwb.hue.into_positive_degrees()),
VariablePrecision(hwb.whiteness),
VariablePrecision(hwb.blackness),
VariablePrecision(lab.l / 100.0),
VariablePrecision(lab.a / 100.0),
VariablePrecision(lab.b / 100.0),
VariablePrecision(lch.l / 100.0),
VariablePrecision(lch.chroma / 100.0),
VariablePrecision(lch.hue.into_positive_degrees()),
VariablePrecision(oklab.l),
VariablePrecision(oklab.a),
VariablePrecision(oklab.b),
VariablePrecision(oklch.l),
VariablePrecision(oklch.chroma),
VariablePrecision(oklch.hue.into_positive_degrees()),
VariablePrecision(xyz.x),
VariablePrecision(xyz.y),
VariablePrecision(xyz.z),
);
}
println!("];");
}
struct VariablePrecision(f32);
impl core::fmt::Display for VariablePrecision {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
if self.0.fract() == 0.0 {
return write!(f, "{}.0", self.0);
}
write!(f, "{}", self.0)
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_app/src/app.rs | crates/bevy_app/src/app.rs | use crate::{
First, Main, MainSchedulePlugin, PlaceholderPlugin, Plugin, Plugins, PluginsState, SubApp,
SubApps,
};
use alloc::{
boxed::Box,
string::{String, ToString},
vec::Vec,
};
pub use bevy_derive::AppLabel;
use bevy_ecs::{
component::RequiredComponentsError,
error::{DefaultErrorHandler, ErrorHandler},
event::Event,
intern::Interned,
message::{message_update_system, MessageCursor},
prelude::*,
schedule::{
InternedSystemSet, ScheduleBuildSettings, ScheduleCleanupPolicy, ScheduleError,
ScheduleLabel,
},
system::{IntoObserverSystem, ScheduleSystem, SystemId, SystemInput},
};
use bevy_platform::collections::HashMap;
use core::{fmt::Debug, num::NonZero, panic::AssertUnwindSafe};
use log::debug;
#[cfg(feature = "trace")]
use tracing::info_span;
#[cfg(feature = "std")]
use std::{
panic::{catch_unwind, resume_unwind},
process::{ExitCode, Termination},
};
bevy_ecs::define_label!(
/// A strongly-typed class of labels used to identify an [`App`].
#[diagnostic::on_unimplemented(
note = "consider annotating `{Self}` with `#[derive(AppLabel)]`"
)]
AppLabel,
APP_LABEL_INTERNER
);
pub use bevy_ecs::label::DynEq;
/// A shorthand for `Interned<dyn AppLabel>`.
pub type InternedAppLabel = Interned<dyn AppLabel>;
#[derive(Debug, thiserror::Error)]
pub(crate) enum AppError {
#[error("duplicate plugin {plugin_name:?}")]
DuplicatePlugin { plugin_name: String },
}
/// [`App`] is the primary API for writing user applications. It automates the setup of a
/// [standard lifecycle](Main) and provides interface glue for [plugins](`Plugin`).
///
/// A single [`App`] can contain multiple [`SubApp`] instances, but [`App`] methods only affect
/// the "main" one. To access a particular [`SubApp`], use [`get_sub_app`](App::get_sub_app)
/// or [`get_sub_app_mut`](App::get_sub_app_mut).
///
///
/// # Examples
///
/// Here is a simple "Hello World" Bevy app:
///
/// ```
/// # use bevy_app::prelude::*;
/// # use bevy_ecs::prelude::*;
/// #
/// fn main() {
/// App::new()
/// .add_systems(Update, hello_world_system)
/// .run();
/// }
///
/// fn hello_world_system() {
/// println!("hello world");
/// }
/// ```
#[must_use]
pub struct App {
pub(crate) sub_apps: SubApps,
/// The function that will manage the app's lifecycle.
///
/// Bevy provides the [`WinitPlugin`] and [`ScheduleRunnerPlugin`] for windowed and headless
/// applications, respectively.
///
/// [`WinitPlugin`]: https://docs.rs/bevy/latest/bevy/winit/struct.WinitPlugin.html
/// [`ScheduleRunnerPlugin`]: https://docs.rs/bevy/latest/bevy/app/struct.ScheduleRunnerPlugin.html
pub(crate) runner: RunnerFn,
default_error_handler: Option<ErrorHandler>,
}
impl Debug for App {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "App {{ sub_apps: ")?;
f.debug_map()
.entries(self.sub_apps.sub_apps.iter())
.finish()?;
write!(f, "}}")
}
}
impl Default for App {
fn default() -> Self {
let mut app = App::empty();
app.sub_apps.main.update_schedule = Some(Main.intern());
#[cfg(feature = "bevy_reflect")]
{
#[cfg(not(feature = "reflect_auto_register"))]
app.init_resource::<AppTypeRegistry>();
#[cfg(feature = "reflect_auto_register")]
app.insert_resource(AppTypeRegistry::new_with_derived_types());
}
#[cfg(feature = "reflect_functions")]
app.init_resource::<AppFunctionRegistry>();
app.add_plugins(MainSchedulePlugin);
app.add_systems(
First,
message_update_system
.in_set(bevy_ecs::message::MessageUpdateSystems)
.run_if(bevy_ecs::message::message_update_condition),
);
app.add_message::<AppExit>();
app
}
}
impl App {
/// Creates a new [`App`] with some default structure to enable core engine features.
/// This is the preferred constructor for most use cases.
pub fn new() -> App {
App::default()
}
/// Creates a new empty [`App`] with minimal default configuration.
///
/// Use this constructor if you want to customize scheduling, exit handling, cleanup, etc.
pub fn empty() -> App {
Self {
sub_apps: SubApps {
main: SubApp::new(),
sub_apps: HashMap::default(),
},
runner: Box::new(run_once),
default_error_handler: None,
}
}
/// Runs the default schedules of all sub-apps (starting with the "main" app) once.
pub fn update(&mut self) {
if self.is_building_plugins() {
panic!("App::update() was called while a plugin was building.");
}
self.sub_apps.update();
}
/// Runs the [`App`] by calling its [runner](Self::set_runner).
///
/// This will (re)build the [`App`] first. For general usage, see the example on the item
/// level documentation.
///
/// # Caveats
///
/// Calls to [`App::run()`] will never return on iOS and Web.
///
/// Headless apps can generally expect this method to return control to the caller when
/// it completes, but that is not the case for windowed apps. Windowed apps are typically
/// driven by an event loop and some platforms expect the program to terminate when the
/// event loop ends.
///
/// By default, *Bevy* uses the `winit` crate for window creation.
///
/// # Panics
///
/// Panics if not all plugins have been built.
pub fn run(&mut self) -> AppExit {
#[cfg(feature = "trace")]
let _bevy_app_run_span = info_span!("bevy_app").entered();
if self.is_building_plugins() {
panic!("App::run() was called while a plugin was building.");
}
let runner = core::mem::replace(&mut self.runner, Box::new(run_once));
let app = core::mem::replace(self, App::empty());
(runner)(app)
}
/// Sets the function that will be called when the app is run.
///
/// The runner function `f` is called only once by [`App::run`]. If the
/// presence of a main loop in the app is desired, it is the responsibility of the runner
/// function to provide it.
///
/// The runner function is usually not set manually, but by Bevy integrated plugins
/// (e.g. `WinitPlugin`).
///
/// # Examples
///
/// ```
/// # use bevy_app::prelude::*;
/// #
/// fn my_runner(mut app: App) -> AppExit {
/// loop {
/// println!("In main loop");
/// app.update();
/// if let Some(exit) = app.should_exit() {
/// return exit;
/// }
/// }
/// }
///
/// App::new()
/// .set_runner(my_runner);
/// ```
pub fn set_runner(&mut self, f: impl FnOnce(App) -> AppExit + 'static) -> &mut Self {
self.runner = Box::new(f);
self
}
/// Returns the state of all plugins. This is usually called by the event loop, but can be
/// useful for situations where you want to use [`App::update`].
// TODO: &mut self -> &self
#[inline]
pub fn plugins_state(&mut self) -> PluginsState {
let mut overall_plugins_state = match self.main_mut().plugins_state {
PluginsState::Adding => {
let mut state = PluginsState::Ready;
let plugins = core::mem::take(&mut self.main_mut().plugin_registry);
for plugin in &plugins {
// plugins installed to main need to see all sub-apps
if !plugin.ready(self) {
state = PluginsState::Adding;
break;
}
}
self.main_mut().plugin_registry = plugins;
state
}
state => state,
};
// overall state is the earliest state of any sub-app
self.sub_apps.iter_mut().skip(1).for_each(|s| {
overall_plugins_state = overall_plugins_state.min(s.plugins_state());
});
overall_plugins_state
}
/// Runs [`Plugin::finish`] for each plugin. This is usually called by the event loop once all
/// plugins are ready, but can be useful for situations where you want to use [`App::update`].
pub fn finish(&mut self) {
#[cfg(feature = "trace")]
let _finish_span = info_span!("plugin finish").entered();
// plugins installed to main should see all sub-apps
// do hokey pokey with a boxed zst plugin (doesn't allocate)
let mut hokeypokey: Box<dyn Plugin> = Box::new(HokeyPokey);
for i in 0..self.main().plugin_registry.len() {
core::mem::swap(&mut self.main_mut().plugin_registry[i], &mut hokeypokey);
#[cfg(feature = "trace")]
let _plugin_finish_span =
info_span!("plugin finish", plugin = hokeypokey.name()).entered();
hokeypokey.finish(self);
core::mem::swap(&mut self.main_mut().plugin_registry[i], &mut hokeypokey);
}
self.main_mut().plugins_state = PluginsState::Finished;
self.sub_apps.iter_mut().skip(1).for_each(SubApp::finish);
}
/// Runs [`Plugin::cleanup`] for each plugin. This is usually called by the event loop after
/// [`App::finish`], but can be useful for situations where you want to use [`App::update`].
pub fn cleanup(&mut self) {
#[cfg(feature = "trace")]
let _cleanup_span = info_span!("plugin cleanup").entered();
// plugins installed to main should see all sub-apps
// do hokey pokey with a boxed zst plugin (doesn't allocate)
let mut hokeypokey: Box<dyn Plugin> = Box::new(HokeyPokey);
for i in 0..self.main().plugin_registry.len() {
core::mem::swap(&mut self.main_mut().plugin_registry[i], &mut hokeypokey);
#[cfg(feature = "trace")]
let _plugin_cleanup_span =
info_span!("plugin cleanup", plugin = hokeypokey.name()).entered();
hokeypokey.cleanup(self);
core::mem::swap(&mut self.main_mut().plugin_registry[i], &mut hokeypokey);
}
self.main_mut().plugins_state = PluginsState::Cleaned;
self.sub_apps.iter_mut().skip(1).for_each(SubApp::cleanup);
}
/// Returns `true` if any of the sub-apps are building plugins.
pub(crate) fn is_building_plugins(&self) -> bool {
self.sub_apps.iter().any(SubApp::is_building_plugins)
}
/// Adds one or more systems to the given schedule in this app's [`Schedules`].
///
/// # Examples
///
/// ```
/// # use bevy_app::prelude::*;
/// # use bevy_ecs::prelude::*;
/// #
/// # let mut app = App::new();
/// # fn system_a() {}
/// # fn system_b() {}
/// # fn system_c() {}
/// # fn should_run() -> bool { true }
/// #
/// app.add_systems(Update, (system_a, system_b, system_c));
/// app.add_systems(Update, (system_a, system_b).run_if(should_run));
/// ```
pub fn add_systems<M>(
&mut self,
schedule: impl ScheduleLabel,
systems: impl IntoScheduleConfigs<ScheduleSystem, M>,
) -> &mut Self {
self.main_mut().add_systems(schedule, systems);
self
}
/// Removes all systems in a [`SystemSet`]. This will cause the schedule to be rebuilt when
/// the schedule is run again and can be slow. A [`ScheduleError`] is returned if the schedule needs to be
/// [`Schedule::initialize`]'d or the `set` is not found.
///
/// Note that this can remove all systems of a type if you pass
/// the system to this function as systems implicitly create a set based
/// on the system type.
///
/// ## Example
/// ```
/// # use bevy_app::prelude::*;
/// # use bevy_ecs::schedule::ScheduleCleanupPolicy;
/// #
/// # let mut app = App::new();
/// # fn system_a() {}
/// # fn system_b() {}
/// #
/// // add the system
/// app.add_systems(Update, system_a);
///
/// // remove the system
/// app.remove_systems_in_set(Update, system_a, ScheduleCleanupPolicy::RemoveSystemsOnly);
/// ```
pub fn remove_systems_in_set<M>(
&mut self,
schedule: impl ScheduleLabel,
set: impl IntoSystemSet<M>,
policy: ScheduleCleanupPolicy,
) -> Result<usize, ScheduleError> {
self.main_mut().remove_systems_in_set(schedule, set, policy)
}
/// Registers a system and returns a [`SystemId`] so it can later be called by [`World::run_system`].
///
/// It's possible to register the same systems more than once, they'll be stored separately.
///
/// This is different from adding systems to a [`Schedule`] with [`App::add_systems`],
/// because the [`SystemId`] that is returned can be used anywhere in the [`World`] to run the associated system.
/// This allows for running systems in a push-based fashion.
/// Using a [`Schedule`] is still preferred for most cases
/// due to its better performance and ability to run non-conflicting systems simultaneously.
pub fn register_system<I, O, M>(
&mut self,
system: impl IntoSystem<I, O, M> + 'static,
) -> SystemId<I, O>
where
I: SystemInput + 'static,
O: 'static,
{
self.main_mut().register_system(system)
}
/// Configures a collection of system sets in the provided schedule, adding any sets that do not exist.
#[track_caller]
pub fn configure_sets<M>(
&mut self,
schedule: impl ScheduleLabel,
sets: impl IntoScheduleConfigs<InternedSystemSet, M>,
) -> &mut Self {
self.main_mut().configure_sets(schedule, sets);
self
}
/// Initializes [`Message`] handling for `T` by inserting a message queue resource ([`Messages::<T>`])
/// and scheduling an [`message_update_system`] in [`First`].
///
/// See [`Messages`] for information on how to define messages.
///
/// # Examples
///
/// ```
/// # use bevy_app::prelude::*;
/// # use bevy_ecs::prelude::*;
/// #
/// # #[derive(Message)]
/// # struct MyMessage;
/// # let mut app = App::new();
/// #
/// app.add_message::<MyMessage>();
/// ```
pub fn add_message<M: Message>(&mut self) -> &mut Self {
self.main_mut().add_message::<M>();
self
}
/// Inserts the [`Resource`] into the app, overwriting any existing resource of the same type.
///
/// There is also an [`init_resource`](Self::init_resource) for resources that have
/// [`Default`] or [`FromWorld`] implementations.
///
/// # Examples
///
/// ```
/// # use bevy_app::prelude::*;
/// # use bevy_ecs::prelude::*;
/// #
/// #[derive(Resource)]
/// struct MyCounter {
/// counter: usize,
/// }
///
/// App::new()
/// .insert_resource(MyCounter { counter: 0 });
/// ```
pub fn insert_resource<R: Resource>(&mut self, resource: R) -> &mut Self {
self.main_mut().insert_resource(resource);
self
}
/// Inserts the [`Resource`], initialized with its default value, into the app,
/// if there is no existing instance of `R`.
///
/// `R` must implement [`FromWorld`].
/// If `R` implements [`Default`], [`FromWorld`] will be automatically implemented and
/// initialize the [`Resource`] with [`Default::default`].
///
/// # Examples
///
/// ```
/// # use bevy_app::prelude::*;
/// # use bevy_ecs::prelude::*;
/// #
/// #[derive(Resource)]
/// struct MyCounter {
/// counter: usize,
/// }
///
/// impl Default for MyCounter {
/// fn default() -> MyCounter {
/// MyCounter {
/// counter: 100
/// }
/// }
/// }
///
/// App::new()
/// .init_resource::<MyCounter>();
/// ```
pub fn init_resource<R: Resource + FromWorld>(&mut self) -> &mut Self {
self.main_mut().init_resource::<R>();
self
}
/// Inserts the [`!Send`](Send) resource into the app, overwriting any existing resource
/// of the same type.
///
/// There is also an [`init_non_send_resource`](Self::init_non_send_resource) for
/// resources that implement [`Default`]
///
/// # Examples
///
/// ```
/// # use bevy_app::prelude::*;
/// # use bevy_ecs::prelude::*;
/// #
/// struct MyCounter {
/// counter: usize,
/// }
///
/// App::new()
/// .insert_non_send_resource(MyCounter { counter: 0 });
/// ```
pub fn insert_non_send_resource<R: 'static>(&mut self, resource: R) -> &mut Self {
self.world_mut().insert_non_send_resource(resource);
self
}
/// Inserts the [`!Send`](Send) resource into the app if there is no existing instance of `R`.
///
/// `R` must implement [`FromWorld`].
/// If `R` implements [`Default`], [`FromWorld`] will be automatically implemented and
/// initialize the [`Resource`] with [`Default::default`].
pub fn init_non_send_resource<R: 'static + FromWorld>(&mut self) -> &mut Self {
self.world_mut().init_non_send_resource::<R>();
self
}
pub(crate) fn add_boxed_plugin(
&mut self,
plugin: Box<dyn Plugin>,
) -> Result<&mut Self, AppError> {
debug!("added plugin: {}", plugin.name());
if plugin.is_unique() && self.main_mut().plugin_names.contains(plugin.name()) {
Err(AppError::DuplicatePlugin {
plugin_name: plugin.name().to_string(),
})?;
}
// Reserve position in the plugin registry. If the plugin adds more plugins,
// they'll all end up in insertion order.
let index = self.main().plugin_registry.len();
self.main_mut()
.plugin_registry
.push(Box::new(PlaceholderPlugin));
self.main_mut().plugin_build_depth += 1;
#[cfg(feature = "trace")]
let _plugin_build_span = info_span!("plugin build", plugin = plugin.name()).entered();
let f = AssertUnwindSafe(|| plugin.build(self));
#[cfg(feature = "std")]
let result = catch_unwind(f);
#[cfg(not(feature = "std"))]
f();
self.main_mut()
.plugin_names
.insert(plugin.name().to_string());
self.main_mut().plugin_build_depth -= 1;
#[cfg(feature = "std")]
if let Err(payload) = result {
resume_unwind(payload);
}
self.main_mut().plugin_registry[index] = plugin;
Ok(self)
}
/// Returns `true` if the [`Plugin`] has already been added.
pub fn is_plugin_added<T>(&self) -> bool
where
T: Plugin,
{
self.main().is_plugin_added::<T>()
}
/// Returns a vector of references to all plugins of type `T` that have been added.
///
/// This can be used to read the settings of any existing plugins.
/// This vector will be empty if no plugins of that type have been added.
/// If multiple copies of the same plugin are added to the [`App`], they will be listed in insertion order in this vector.
///
/// ```
/// # use bevy_app::prelude::*;
/// # #[derive(Default)]
/// # struct ImagePlugin {
/// # default_sampler: bool,
/// # }
/// # impl Plugin for ImagePlugin {
/// # fn build(&self, app: &mut App) {}
/// # }
/// # let mut app = App::new();
/// # app.add_plugins(ImagePlugin::default());
/// let default_sampler = app.get_added_plugins::<ImagePlugin>()[0].default_sampler;
/// ```
pub fn get_added_plugins<T>(&self) -> Vec<&T>
where
T: Plugin,
{
self.main().get_added_plugins::<T>()
}
/// Installs a [`Plugin`] collection.
///
/// Bevy prioritizes modularity as a core principle. **All** engine features are implemented
/// as plugins, even the complex ones like rendering.
///
/// [`Plugin`]s can be grouped into a set by using a [`PluginGroup`].
///
/// There are built-in [`PluginGroup`]s that provide core engine functionality.
/// The [`PluginGroup`]s available by default are `DefaultPlugins` and `MinimalPlugins`.
///
/// To customize the plugins in the group (reorder, disable a plugin, add a new plugin
/// before / after another plugin), call [`build()`](super::PluginGroup::build) on the group,
/// which will convert it to a [`PluginGroupBuilder`](crate::PluginGroupBuilder).
///
/// You can also specify a group of [`Plugin`]s by using a tuple over [`Plugin`]s and
/// [`PluginGroup`]s. See [`Plugins`] for more details.
///
/// ## Examples
/// ```
/// # use bevy_app::{prelude::*, PluginGroupBuilder, NoopPluginGroup as MinimalPlugins};
/// #
/// # // Dummies created to avoid using `bevy_log`,
/// # // which pulls in too many dependencies and breaks rust-analyzer
/// # pub struct LogPlugin;
/// # impl Plugin for LogPlugin {
/// # fn build(&self, app: &mut App) {}
/// # }
/// App::new()
/// .add_plugins(MinimalPlugins);
/// App::new()
/// .add_plugins((MinimalPlugins, LogPlugin));
/// ```
///
/// # Panics
///
/// Panics if one of the plugins had already been added to the application.
///
/// [`PluginGroup`]:super::PluginGroup
#[track_caller]
pub fn add_plugins<M>(&mut self, plugins: impl Plugins<M>) -> &mut Self {
if matches!(
self.plugins_state(),
PluginsState::Cleaned | PluginsState::Finished
) {
panic!(
"Plugins cannot be added after App::cleanup() or App::finish() has been called."
);
}
plugins.add_to_app(self);
self
}
/// Registers the type `T` in the [`AppTypeRegistry`] resource,
/// adding reflect data as specified in the [`Reflect`](bevy_reflect::Reflect) derive:
/// ```ignore (No serde "derive" feature)
/// #[derive(Component, Serialize, Deserialize, Reflect)]
/// #[reflect(Component, Serialize, Deserialize)] // will register ReflectComponent, ReflectSerialize, ReflectDeserialize
/// ```
///
/// See [`bevy_reflect::TypeRegistry::register`] for more information.
#[cfg(feature = "bevy_reflect")]
pub fn register_type<T: bevy_reflect::GetTypeRegistration>(&mut self) -> &mut Self {
self.main_mut().register_type::<T>();
self
}
/// Associates type data `D` with type `T` in the [`AppTypeRegistry`] resource.
///
/// Most of the time [`register_type`](Self::register_type) can be used instead to register a
/// type you derived [`Reflect`](bevy_reflect::Reflect) for. However, in cases where you want to
/// add a piece of type data that was not included in the list of `#[reflect(...)]` type data in
/// the derive, or where the type is generic and cannot register e.g. `ReflectSerialize`
/// unconditionally without knowing the specific type parameters, this method can be used to
/// insert additional type data.
///
/// # Example
/// ```
/// use bevy_app::App;
/// use bevy_reflect::{ReflectSerialize, ReflectDeserialize};
///
/// App::new()
/// .register_type::<Option<String>>()
/// .register_type_data::<Option<String>, ReflectSerialize>()
/// .register_type_data::<Option<String>, ReflectDeserialize>();
/// ```
///
/// See [`bevy_reflect::TypeRegistry::register_type_data`].
#[cfg(feature = "bevy_reflect")]
pub fn register_type_data<
T: bevy_reflect::Reflect + bevy_reflect::TypePath,
D: bevy_reflect::TypeData + bevy_reflect::FromType<T>,
>(
&mut self,
) -> &mut Self {
self.main_mut().register_type_data::<T, D>();
self
}
/// Registers the given function into the [`AppFunctionRegistry`] resource.
///
/// The given function will internally be stored as a [`DynamicFunction`]
/// and mapped according to its [name].
///
/// Because the function must have a name,
/// anonymous functions (e.g. `|a: i32, b: i32| { a + b }`) and closures must instead
/// be registered using [`register_function_with_name`] or converted to a [`DynamicFunction`]
/// and named using [`DynamicFunction::with_name`].
/// Failure to do so will result in a panic.
///
/// Only types that implement [`IntoFunction`] may be registered via this method.
///
/// See [`FunctionRegistry::register`] for more information.
///
/// # Panics
///
/// Panics if a function has already been registered with the given name
/// or if the function is missing a name (such as when it is an anonymous function).
///
/// # Examples
///
/// ```
/// use bevy_app::App;
///
/// fn add(a: i32, b: i32) -> i32 {
/// a + b
/// }
///
/// App::new().register_function(add);
/// ```
///
/// Functions cannot be registered more than once.
///
/// ```should_panic
/// use bevy_app::App;
///
/// fn add(a: i32, b: i32) -> i32 {
/// a + b
/// }
///
/// App::new()
/// .register_function(add)
/// // Panic! A function has already been registered with the name "my_function"
/// .register_function(add);
/// ```
///
/// Anonymous functions and closures should be registered using [`register_function_with_name`] or given a name using [`DynamicFunction::with_name`].
///
/// ```should_panic
/// use bevy_app::App;
///
/// // Panic! Anonymous functions cannot be registered using `register_function`
/// App::new().register_function(|a: i32, b: i32| a + b);
/// ```
///
/// [`register_function_with_name`]: Self::register_function_with_name
/// [`DynamicFunction`]: bevy_reflect::func::DynamicFunction
/// [name]: bevy_reflect::func::FunctionInfo::name
/// [`DynamicFunction::with_name`]: bevy_reflect::func::DynamicFunction::with_name
/// [`IntoFunction`]: bevy_reflect::func::IntoFunction
/// [`FunctionRegistry::register`]: bevy_reflect::func::FunctionRegistry::register
#[cfg(feature = "reflect_functions")]
pub fn register_function<F, Marker>(&mut self, function: F) -> &mut Self
where
F: bevy_reflect::func::IntoFunction<'static, Marker> + 'static,
{
self.main_mut().register_function(function);
self
}
/// Registers the given function or closure into the [`AppFunctionRegistry`] resource using the given name.
///
/// To avoid conflicts, it's recommended to use a unique name for the function.
/// This can be achieved by "namespacing" the function with a unique identifier,
/// such as the name of your crate.
///
/// For example, to register a function, `add`, from a crate, `my_crate`,
/// you could use the name, `"my_crate::add"`.
///
/// Another approach could be to use the [type name] of the function,
/// however, it should be noted that anonymous functions do _not_ have unique type names.
///
/// For named functions (e.g. `fn add(a: i32, b: i32) -> i32 { a + b }`) where a custom name is not needed,
/// it's recommended to use [`register_function`] instead as the generated name is guaranteed to be unique.
///
/// Only types that implement [`IntoFunction`] may be registered via this method.
///
/// See [`FunctionRegistry::register_with_name`] for more information.
///
/// # Panics
///
/// Panics if a function has already been registered with the given name.
///
/// # Examples
///
/// ```
/// use bevy_app::App;
///
/// fn mul(a: i32, b: i32) -> i32 {
/// a * b
/// }
///
/// let div = |a: i32, b: i32| a / b;
///
/// App::new()
/// // Registering an anonymous function with a unique name
/// .register_function_with_name("my_crate::add", |a: i32, b: i32| {
/// a + b
/// })
/// // Registering an existing function with its type name
/// .register_function_with_name(std::any::type_name_of_val(&mul), mul)
/// // Registering an existing function with a custom name
/// .register_function_with_name("my_crate::mul", mul)
/// // Be careful not to register anonymous functions with their type name.
/// // This code works but registers the function with a non-unique name like `foo::bar::{{closure}}`
/// .register_function_with_name(std::any::type_name_of_val(&div), div);
/// ```
///
/// Names must be unique.
///
/// ```should_panic
/// use bevy_app::App;
///
/// fn one() {}
/// fn two() {}
///
/// App::new()
/// .register_function_with_name("my_function", one)
/// // Panic! A function has already been registered with the name "my_function"
/// .register_function_with_name("my_function", two);
/// ```
///
/// [type name]: std::any::type_name
/// [`register_function`]: Self::register_function
/// [`IntoFunction`]: bevy_reflect::func::IntoFunction
/// [`FunctionRegistry::register_with_name`]: bevy_reflect::func::FunctionRegistry::register_with_name
#[cfg(feature = "reflect_functions")]
pub fn register_function_with_name<F, Marker>(
&mut self,
name: impl Into<alloc::borrow::Cow<'static, str>>,
function: F,
) -> &mut Self
where
F: bevy_reflect::func::IntoFunction<'static, Marker> + 'static,
{
self.main_mut().register_function_with_name(name, function);
self
}
/// Registers the given component `R` as a [required component] for `T`.
///
/// When `T` is added to an entity, `R` and its own required components will also be added
/// if `R` was not already provided. The [`Default`] `constructor` will be used for the creation of `R`.
/// If a custom constructor is desired, use [`App::register_required_components_with`] instead.
///
/// For the non-panicking version, see [`App::try_register_required_components`].
///
/// Note that requirements must currently be registered before `T` is inserted into the world
/// for the first time. Commonly, this is done in plugins. This limitation may be fixed in the future.
///
/// [required component]: Component#required-components
///
/// # Panics
///
/// Panics if `R` is already a directly required component for `T`, or if `T` has ever been added
/// on an entity before the registration.
///
/// Indirect requirements through other components are allowed. In those cases, any existing requirements
/// will only be overwritten if the new requirement is more specific.
///
/// # Example
///
/// ```
/// # use bevy_app::{App, NoopPluginGroup as MinimalPlugins, Startup};
/// # use bevy_ecs::prelude::*;
/// #[derive(Component)]
/// struct A;
///
/// #[derive(Component, Default, PartialEq, Eq, Debug)]
/// struct B(usize);
///
/// #[derive(Component, Default, PartialEq, Eq, Debug)]
/// struct C(u32);
///
/// # let mut app = App::new();
/// # app.add_plugins(MinimalPlugins).add_systems(Startup, setup);
/// // Register B as required by A and C as required by B.
/// app.register_required_components::<A, B>();
/// app.register_required_components::<B, C>();
///
/// fn setup(mut commands: Commands) {
/// // This will implicitly also insert B and C with their Default constructors.
/// commands.spawn(A);
/// }
///
/// fn validate(query: Option<Single<(&A, &B, &C)>>) {
/// let (a, b, c) = query.unwrap().into_inner();
/// assert_eq!(b, &B(0));
/// assert_eq!(c, &C(0));
/// }
/// # app.update();
/// ```
pub fn register_required_components<T: Component, R: Component + Default>(
&mut self,
) -> &mut Self {
self.world_mut().register_required_components::<T, R>();
self
}
/// Registers the given component `R` as a [required component] for `T`.
///
/// When `T` is added to an entity, `R` and its own required components will also be added
/// if `R` was not already provided. The given `constructor` will be used for the creation of `R`.
/// If a [`Default`] constructor is desired, use [`App::register_required_components`] instead.
///
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_app/src/sub_app.rs | crates/bevy_app/src/sub_app.rs | use crate::{App, AppLabel, InternedAppLabel, Plugin, Plugins, PluginsState};
use alloc::{boxed::Box, string::String, vec::Vec};
use bevy_ecs::{
message::MessageRegistry,
prelude::*,
schedule::{
InternedScheduleLabel, InternedSystemSet, ScheduleBuildSettings, ScheduleCleanupPolicy,
ScheduleError, ScheduleLabel,
},
system::{ScheduleSystem, SystemId, SystemInput},
};
use bevy_platform::collections::{HashMap, HashSet};
use core::fmt::Debug;
#[cfg(feature = "trace")]
use tracing::info_span;
type ExtractFn = Box<dyn FnMut(&mut World, &mut World) + Send>;
/// A secondary application with its own [`World`]. These can run independently of each other.
///
/// These are useful for situations where certain processes (e.g. a render thread) need to be kept
/// separate from the main application.
///
/// # Example
///
/// ```
/// # use bevy_app::{App, AppLabel, SubApp, Main};
/// # use bevy_ecs::prelude::*;
/// # use bevy_ecs::schedule::ScheduleLabel;
///
/// #[derive(Resource, Default)]
/// struct Val(pub i32);
///
/// #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, AppLabel)]
/// struct ExampleApp;
///
/// // Create an app with a certain resource.
/// let mut app = App::new();
/// app.insert_resource(Val(10));
///
/// // Create a sub-app with the same resource and a single schedule.
/// let mut sub_app = SubApp::new();
/// sub_app.update_schedule = Some(Main.intern());
/// sub_app.insert_resource(Val(100));
///
/// // Setup an extract function to copy the resource's value in the main world.
/// sub_app.set_extract(|main_world, sub_world| {
/// sub_world.resource_mut::<Val>().0 = main_world.resource::<Val>().0;
/// });
///
/// // Schedule a system that will verify extraction is working.
/// sub_app.add_systems(Main, |counter: Res<Val>| {
/// // The value will be copied during extraction, so we should see 10 instead of 100.
/// assert_eq!(counter.0, 10);
/// });
///
/// // Add the sub-app to the main app.
/// app.insert_sub_app(ExampleApp, sub_app);
///
/// // Update the application once (using the default runner).
/// app.run();
/// ```
pub struct SubApp {
/// The data of this application.
world: World,
/// List of plugins that have been added.
pub(crate) plugin_registry: Vec<Box<dyn Plugin>>,
/// The names of plugins that have been added to this app. (used to track duplicates and
/// already-registered plugins)
pub(crate) plugin_names: HashSet<String>,
/// Panics if an update is attempted while plugins are building.
pub(crate) plugin_build_depth: usize,
pub(crate) plugins_state: PluginsState,
/// The schedule that will be run by [`update`](Self::update).
pub update_schedule: Option<InternedScheduleLabel>,
/// A function that gives mutable access to two app worlds. This is primarily
/// intended for copying data from the main world to secondary worlds.
extract: Option<ExtractFn>,
}
impl Debug for SubApp {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "SubApp")
}
}
impl Default for SubApp {
fn default() -> Self {
let mut world = World::new();
world.init_resource::<Schedules>();
Self {
world,
plugin_registry: Vec::default(),
plugin_names: HashSet::default(),
plugin_build_depth: 0,
plugins_state: PluginsState::Adding,
update_schedule: None,
extract: None,
}
}
}
impl SubApp {
/// Returns a default, empty [`SubApp`].
pub fn new() -> Self {
Self::default()
}
/// This method is a workaround. Each [`SubApp`] can have its own plugins, but [`Plugin`]
/// works on an [`App`] as a whole.
fn run_as_app<F>(&mut self, f: F)
where
F: FnOnce(&mut App),
{
let mut app = App::empty();
core::mem::swap(self, &mut app.sub_apps.main);
f(&mut app);
core::mem::swap(self, &mut app.sub_apps.main);
}
/// Returns a reference to the [`World`].
pub fn world(&self) -> &World {
&self.world
}
/// Returns a mutable reference to the [`World`].
pub fn world_mut(&mut self) -> &mut World {
&mut self.world
}
/// Runs the default schedule.
///
/// Does not clear internal trackers used for change detection.
pub fn run_default_schedule(&mut self) {
if self.is_building_plugins() {
panic!("SubApp::update() was called while a plugin was building.");
}
if let Some(label) = self.update_schedule {
self.world.run_schedule(label);
}
}
/// Runs the default schedule and updates internal component trackers.
pub fn update(&mut self) {
self.run_default_schedule();
self.world.clear_trackers();
}
/// Extracts data from `world` into the app's world using the registered extract method.
///
/// **Note:** There is no default extract method. Calling `extract` does nothing if
/// [`set_extract`](Self::set_extract) has not been called.
pub fn extract(&mut self, world: &mut World) {
if let Some(f) = self.extract.as_mut() {
f(world, &mut self.world);
}
}
/// Sets the method that will be called by [`extract`](Self::extract).
///
/// The first argument is the `World` to extract data from, the second argument is the app `World`.
pub fn set_extract<F>(&mut self, extract: F) -> &mut Self
where
F: FnMut(&mut World, &mut World) + Send + 'static,
{
self.extract = Some(Box::new(extract));
self
}
/// Take the function that will be called by [`extract`](Self::extract) out of the app, if any was set,
/// and replace it with `None`.
///
/// If you use Bevy, `bevy_render` will set a default extract function used to extract data from
/// the main world into the render world as part of the Extract phase. In that case, you cannot replace
/// it with your own function. Instead, take the Bevy default function with this, and install your own
/// instead which calls the Bevy default.
///
/// ```
/// # use bevy_app::SubApp;
/// # let mut app = SubApp::new();
/// let mut default_fn = app.take_extract();
/// app.set_extract(move |main, render| {
/// // Do pre-extract custom logic
/// // [...]
///
/// // Call Bevy's default, which executes the Extract phase
/// if let Some(f) = default_fn.as_mut() {
/// f(main, render);
/// }
///
/// // Do post-extract custom logic
/// // [...]
/// });
/// ```
pub fn take_extract(&mut self) -> Option<ExtractFn> {
self.extract.take()
}
/// See [`App::insert_resource`].
pub fn insert_resource<R: Resource>(&mut self, resource: R) -> &mut Self {
self.world.insert_resource(resource);
self
}
/// See [`App::init_resource`].
pub fn init_resource<R: Resource + FromWorld>(&mut self) -> &mut Self {
self.world.init_resource::<R>();
self
}
/// See [`App::add_systems`].
pub fn add_systems<M>(
&mut self,
schedule: impl ScheduleLabel,
systems: impl IntoScheduleConfigs<ScheduleSystem, M>,
) -> &mut Self {
let mut schedules = self.world.resource_mut::<Schedules>();
schedules.add_systems(schedule, systems);
self
}
/// See [`App::remove_systems_in_set`]
pub fn remove_systems_in_set<M>(
&mut self,
schedule: impl ScheduleLabel,
set: impl IntoSystemSet<M>,
policy: ScheduleCleanupPolicy,
) -> Result<usize, ScheduleError> {
self.world.schedule_scope(schedule, |world, schedule| {
schedule.remove_systems_in_set(set, world, policy)
})
}
/// See [`App::register_system`].
pub fn register_system<I, O, M>(
&mut self,
system: impl IntoSystem<I, O, M> + 'static,
) -> SystemId<I, O>
where
I: SystemInput + 'static,
O: 'static,
{
self.world.register_system(system)
}
/// See [`App::configure_sets`].
#[track_caller]
pub fn configure_sets<M>(
&mut self,
schedule: impl ScheduleLabel,
sets: impl IntoScheduleConfigs<InternedSystemSet, M>,
) -> &mut Self {
let mut schedules = self.world.resource_mut::<Schedules>();
schedules.configure_sets(schedule, sets);
self
}
/// See [`App::add_schedule`].
pub fn add_schedule(&mut self, schedule: Schedule) -> &mut Self {
let mut schedules = self.world.resource_mut::<Schedules>();
schedules.insert(schedule);
self
}
/// See [`App::init_schedule`].
pub fn init_schedule(&mut self, label: impl ScheduleLabel) -> &mut Self {
let label = label.intern();
let mut schedules = self.world.resource_mut::<Schedules>();
if !schedules.contains(label) {
schedules.insert(Schedule::new(label));
}
self
}
/// See [`App::get_schedule`].
pub fn get_schedule(&self, label: impl ScheduleLabel) -> Option<&Schedule> {
let schedules = self.world.get_resource::<Schedules>()?;
schedules.get(label)
}
/// See [`App::get_schedule_mut`].
pub fn get_schedule_mut(&mut self, label: impl ScheduleLabel) -> Option<&mut Schedule> {
let schedules = self.world.get_resource_mut::<Schedules>()?;
// We must call `.into_inner` here because the borrow checker only understands reborrows
// using ordinary references, not our `Mut` smart pointers.
schedules.into_inner().get_mut(label)
}
/// See [`App::edit_schedule`].
pub fn edit_schedule(
&mut self,
label: impl ScheduleLabel,
mut f: impl FnMut(&mut Schedule),
) -> &mut Self {
let label = label.intern();
let mut schedules = self.world.resource_mut::<Schedules>();
if !schedules.contains(label) {
schedules.insert(Schedule::new(label));
}
let schedule = schedules.get_mut(label).unwrap();
f(schedule);
self
}
/// See [`App::configure_schedules`].
pub fn configure_schedules(
&mut self,
schedule_build_settings: ScheduleBuildSettings,
) -> &mut Self {
self.world_mut()
.resource_mut::<Schedules>()
.configure_schedules(schedule_build_settings);
self
}
/// See [`App::allow_ambiguous_component`].
pub fn allow_ambiguous_component<T: Component>(&mut self) -> &mut Self {
self.world_mut().allow_ambiguous_component::<T>();
self
}
/// See [`App::allow_ambiguous_resource`].
pub fn allow_ambiguous_resource<T: Resource>(&mut self) -> &mut Self {
self.world_mut().allow_ambiguous_resource::<T>();
self
}
/// See [`App::ignore_ambiguity`].
#[track_caller]
pub fn ignore_ambiguity<M1, M2, S1, S2>(
&mut self,
schedule: impl ScheduleLabel,
a: S1,
b: S2,
) -> &mut Self
where
S1: IntoSystemSet<M1>,
S2: IntoSystemSet<M2>,
{
let schedule = schedule.intern();
let mut schedules = self.world.resource_mut::<Schedules>();
schedules.ignore_ambiguity(schedule, a, b);
self
}
/// See [`App::add_message`].
pub fn add_message<T>(&mut self) -> &mut Self
where
T: Message,
{
if !self.world.contains_resource::<Messages<T>>() {
MessageRegistry::register_message::<T>(self.world_mut());
}
self
}
/// See [`App::add_plugins`].
pub fn add_plugins<M>(&mut self, plugins: impl Plugins<M>) -> &mut Self {
self.run_as_app(|app| plugins.add_to_app(app));
self
}
/// See [`App::is_plugin_added`].
pub fn is_plugin_added<T>(&self) -> bool
where
T: Plugin,
{
self.plugin_names.contains(core::any::type_name::<T>())
}
/// See [`App::get_added_plugins`].
pub fn get_added_plugins<T>(&self) -> Vec<&T>
where
T: Plugin,
{
self.plugin_registry
.iter()
.filter_map(|p| p.downcast_ref())
.collect()
}
/// Returns `true` if there is no plugin in the middle of being built.
pub(crate) fn is_building_plugins(&self) -> bool {
self.plugin_build_depth > 0
}
/// Return the state of plugins.
#[inline]
pub fn plugins_state(&mut self) -> PluginsState {
match self.plugins_state {
PluginsState::Adding => {
let mut state = PluginsState::Ready;
let plugins = core::mem::take(&mut self.plugin_registry);
self.run_as_app(|app| {
for plugin in &plugins {
if !plugin.ready(app) {
state = PluginsState::Adding;
return;
}
}
});
self.plugin_registry = plugins;
state
}
state => state,
}
}
/// Runs [`Plugin::finish`] for each plugin.
pub fn finish(&mut self) {
// do hokey pokey with a boxed zst plugin (doesn't allocate)
let mut hokeypokey: Box<dyn Plugin> = Box::new(crate::HokeyPokey);
for i in 0..self.plugin_registry.len() {
core::mem::swap(&mut self.plugin_registry[i], &mut hokeypokey);
#[cfg(feature = "trace")]
let _plugin_finish_span =
info_span!("plugin finish", plugin = hokeypokey.name()).entered();
self.run_as_app(|app| {
hokeypokey.finish(app);
});
core::mem::swap(&mut self.plugin_registry[i], &mut hokeypokey);
}
self.plugins_state = PluginsState::Finished;
}
/// Runs [`Plugin::cleanup`] for each plugin.
pub fn cleanup(&mut self) {
// do hokey pokey with a boxed zst plugin (doesn't allocate)
let mut hokeypokey: Box<dyn Plugin> = Box::new(crate::HokeyPokey);
for i in 0..self.plugin_registry.len() {
core::mem::swap(&mut self.plugin_registry[i], &mut hokeypokey);
#[cfg(feature = "trace")]
let _plugin_cleanup_span =
info_span!("plugin cleanup", plugin = hokeypokey.name()).entered();
self.run_as_app(|app| {
hokeypokey.cleanup(app);
});
core::mem::swap(&mut self.plugin_registry[i], &mut hokeypokey);
}
self.plugins_state = PluginsState::Cleaned;
}
/// See [`App::register_type`].
#[cfg(feature = "bevy_reflect")]
pub fn register_type<T: bevy_reflect::GetTypeRegistration>(&mut self) -> &mut Self {
let registry = self.world.resource_mut::<AppTypeRegistry>();
registry.write().register::<T>();
self
}
/// See [`App::register_type_data`].
#[cfg(feature = "bevy_reflect")]
pub fn register_type_data<
T: bevy_reflect::Reflect + bevy_reflect::TypePath,
D: bevy_reflect::TypeData + bevy_reflect::FromType<T>,
>(
&mut self,
) -> &mut Self {
let registry = self.world.resource_mut::<AppTypeRegistry>();
registry.write().register_type_data::<T, D>();
self
}
/// See [`App::register_function`].
#[cfg(feature = "reflect_functions")]
pub fn register_function<F, Marker>(&mut self, function: F) -> &mut Self
where
F: bevy_reflect::func::IntoFunction<'static, Marker> + 'static,
{
let registry = self.world.resource_mut::<AppFunctionRegistry>();
registry.write().register(function).unwrap();
self
}
/// See [`App::register_function_with_name`].
#[cfg(feature = "reflect_functions")]
pub fn register_function_with_name<F, Marker>(
&mut self,
name: impl Into<alloc::borrow::Cow<'static, str>>,
function: F,
) -> &mut Self
where
F: bevy_reflect::func::IntoFunction<'static, Marker> + 'static,
{
let registry = self.world.resource_mut::<AppFunctionRegistry>();
registry.write().register_with_name(name, function).unwrap();
self
}
}
/// The collection of sub-apps that belong to an [`App`].
#[derive(Default)]
pub struct SubApps {
/// The primary sub-app that contains the "main" world.
pub main: SubApp,
/// Other, labeled sub-apps.
pub sub_apps: HashMap<InternedAppLabel, SubApp>,
}
impl SubApps {
/// Calls [`update`](SubApp::update) for the main sub-app, and then calls
/// [`extract`](SubApp::extract) and [`update`](SubApp::update) for the rest.
pub fn update(&mut self) {
#[cfg(feature = "trace")]
let _bevy_update_span = info_span!("update").entered();
{
#[cfg(feature = "trace")]
let _bevy_frame_update_span = info_span!("main app").entered();
self.main.run_default_schedule();
}
for (_label, sub_app) in self.sub_apps.iter_mut() {
#[cfg(feature = "trace")]
let _sub_app_span = info_span!("sub app", name = ?_label).entered();
sub_app.extract(&mut self.main.world);
sub_app.update();
}
self.main.world.clear_trackers();
}
/// Returns an iterator over the sub-apps (starting with the main one).
pub fn iter(&self) -> impl Iterator<Item = &SubApp> + '_ {
core::iter::once(&self.main).chain(self.sub_apps.values())
}
/// Returns a mutable iterator over the sub-apps (starting with the main one).
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut SubApp> + '_ {
core::iter::once(&mut self.main).chain(self.sub_apps.values_mut())
}
/// Extract data from the main world into the [`SubApp`] with the given label and perform an update if it exists.
pub fn update_subapp_by_label(&mut self, label: impl AppLabel) {
if let Some(sub_app) = self.sub_apps.get_mut(&label.intern()) {
sub_app.extract(&mut self.main.world);
sub_app.update();
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_app/src/lib.rs | crates/bevy_app/src/lib.rs | #![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))]
#![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 is about everything concerning the highest-level, application layer of a Bevy app.
#[cfg(feature = "std")]
extern crate std;
extern crate alloc;
// Required to make proc macros work in bevy itself.
extern crate self as bevy_app;
mod app;
mod main_schedule;
mod panic_handler;
mod plugin;
mod plugin_group;
mod propagate;
mod schedule_runner;
mod sub_app;
mod task_pool_plugin;
#[cfg(all(any(all(unix, not(target_os = "horizon")), windows), feature = "std"))]
mod terminal_ctrl_c_handler;
#[cfg(feature = "hotpatching")]
pub mod hotpatch;
pub use app::*;
pub use main_schedule::*;
pub use panic_handler::*;
pub use plugin::*;
pub use plugin_group::*;
pub use propagate::*;
pub use schedule_runner::*;
pub use sub_app::*;
pub use task_pool_plugin::*;
#[cfg(all(any(all(unix, not(target_os = "horizon")), windows), feature = "std"))]
pub use terminal_ctrl_c_handler::*;
/// The app prelude.
///
/// This includes the most common types in this crate, re-exported for your convenience.
pub mod prelude {
#[doc(hidden)]
pub use crate::{
app::{App, AppExit},
main_schedule::{
First, FixedFirst, FixedLast, FixedPostUpdate, FixedPreUpdate, FixedUpdate, Last, Main,
PostStartup, PostUpdate, PreStartup, PreUpdate, RunFixedMainLoop,
RunFixedMainLoopSystems, SpawnScene, Startup, Update,
},
sub_app::SubApp,
Plugin, PluginGroup, TaskPoolOptions, TaskPoolPlugin,
};
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_app/src/plugin_group.rs | crates/bevy_app/src/plugin_group.rs | use crate::{App, AppError, Plugin};
use alloc::{
boxed::Box,
string::{String, ToString},
vec::Vec,
};
use bevy_platform::collections::hash_map::Entry;
use bevy_utils::TypeIdMap;
use core::any::TypeId;
use log::{debug, warn};
/// A macro for generating a well-documented [`PluginGroup`] from a list of [`Plugin`] paths.
///
/// Every plugin must implement the [`Default`] trait.
///
/// # Example
///
/// ```
/// # use bevy_app::*;
/// #
/// # mod velocity {
/// # use bevy_app::*;
/// # #[derive(Default)]
/// # pub struct VelocityPlugin;
/// # impl Plugin for VelocityPlugin { fn build(&self, _: &mut App) {} }
/// # }
/// #
/// # mod collision {
/// # pub mod capsule {
/// # use bevy_app::*;
/// # #[derive(Default)]
/// # pub struct CapsuleCollisionPlugin;
/// # impl Plugin for CapsuleCollisionPlugin { fn build(&self, _: &mut App) {} }
/// # }
/// # }
/// #
/// # #[derive(Default)]
/// # pub struct TickratePlugin;
/// # impl Plugin for TickratePlugin { fn build(&self, _: &mut App) {} }
/// #
/// # mod features {
/// # use bevy_app::*;
/// # #[derive(Default)]
/// # pub struct ForcePlugin;
/// # impl Plugin for ForcePlugin { fn build(&self, _: &mut App) {} }
/// # }
/// #
/// # mod web {
/// # use bevy_app::*;
/// # #[derive(Default)]
/// # pub struct WebCompatibilityPlugin;
/// # impl Plugin for WebCompatibilityPlugin { fn build(&self, _: &mut App) {} }
/// # }
/// #
/// # mod audio {
/// # use bevy_app::*;
/// # #[derive(Default)]
/// # pub struct AudioPlugins;
/// # impl PluginGroup for AudioPlugins {
/// # fn build(self) -> PluginGroupBuilder {
/// # PluginGroupBuilder::start::<Self>()
/// # }
/// # }
/// # }
/// #
/// # mod internal {
/// # use bevy_app::*;
/// # #[derive(Default)]
/// # pub struct InternalPlugin;
/// # impl Plugin for InternalPlugin { fn build(&self, _: &mut App) {} }
/// # }
/// #
/// plugin_group! {
/// /// Doc comments and annotations are supported: they will be added to the generated plugin
/// /// group.
/// #[derive(Debug)]
/// pub struct PhysicsPlugins {
/// // If referencing a plugin within the same module, you must prefix it with a colon `:`.
/// :TickratePlugin,
/// // If referencing a plugin within a different module, there must be three colons `:::`
/// // between the final module and the plugin name.
/// collision::capsule:::CapsuleCollisionPlugin,
/// velocity:::VelocityPlugin,
/// // If you feature-flag a plugin, it will be automatically documented. There can only be
/// // one automatically documented feature flag, and it must be first. All other
/// // `#[cfg()]` attributes must be wrapped by `#[custom()]`.
/// #[cfg(feature = "external_forces")]
/// features:::ForcePlugin,
/// // More complicated `#[cfg()]`s and annotations are not supported by automatic doc
/// // generation, in which case you must wrap it in `#[custom()]`.
/// #[custom(cfg(target_arch = "wasm32"))]
/// web:::WebCompatibilityPlugin,
/// // You can nest `PluginGroup`s within other `PluginGroup`s, you just need the
/// // `#[plugin_group]` attribute.
/// #[plugin_group]
/// audio:::AudioPlugins,
/// // You can hide plugins from documentation. Due to macro limitations, hidden plugins
/// // must be last.
/// #[doc(hidden)]
/// internal:::InternalPlugin
/// }
/// /// You may add doc comments after the plugin group as well. They will be appended after
/// /// the documented list of plugins.
/// }
/// ```
#[macro_export]
macro_rules! plugin_group {
{
$(#[$group_meta:meta])*
$vis:vis struct $group:ident {
$(
$(#[cfg(feature = $plugin_feature:literal)])?
$(#[custom($plugin_meta:meta)])*
$($plugin_path:ident::)* : $plugin_name:ident
),*
$(
$(,)?$(
#[plugin_group]
$(#[cfg(feature = $plugin_group_feature:literal)])?
$(#[custom($plugin_group_meta:meta)])*
$($plugin_group_path:ident::)* : $plugin_group_name:ident
),+
)?
$(
$(,)?$(
#[doc(hidden)]
$(#[cfg(feature = $hidden_plugin_feature:literal)])?
$(#[custom($hidden_plugin_meta:meta)])*
$($hidden_plugin_path:ident::)* : $hidden_plugin_name:ident
),+
)?
$(,)?
}
$($(#[doc = $post_doc:literal])+)?
} => {
$(#[$group_meta])*
///
$(#[doc = concat!(
" - [`", stringify!($plugin_name), "`](" $(, stringify!($plugin_path), "::")*, stringify!($plugin_name), ")"
$(, " - with feature `", $plugin_feature, "`")?
)])*
$($(#[doc = concat!(
" - [`", stringify!($plugin_group_name), "`](" $(, stringify!($plugin_group_path), "::")*, stringify!($plugin_group_name), ")"
$(, " - with feature `", $plugin_group_feature, "`")?
)])+)?
$(
///
$(#[doc = $post_doc])+
)?
$vis struct $group;
impl $crate::PluginGroup for $group {
fn build(self) -> $crate::PluginGroupBuilder {
let mut group = $crate::PluginGroupBuilder::start::<Self>();
$(
$(#[cfg(feature = $plugin_feature)])?
$(#[$plugin_meta])*
{
const _: () = {
const fn check_default<T: Default>() {}
check_default::<$($plugin_path::)*$plugin_name>();
};
group = group.add(<$($plugin_path::)*$plugin_name>::default());
}
)*
$($(
$(#[cfg(feature = $plugin_group_feature)])?
$(#[$plugin_group_meta])*
{
const _: () = {
const fn check_default<T: Default>() {}
check_default::<$($plugin_group_path::)*$plugin_group_name>();
};
group = group.add_group(<$($plugin_group_path::)*$plugin_group_name>::default());
}
)+)?
$($(
$(#[cfg(feature = $hidden_plugin_feature)])?
$(#[$hidden_plugin_meta])*
{
const _: () = {
const fn check_default<T: Default>() {}
check_default::<$($hidden_plugin_path::)*$hidden_plugin_name>();
};
group = group.add(<$($hidden_plugin_path::)*$hidden_plugin_name>::default());
}
)+)?
group
}
}
};
}
/// Combines multiple [`Plugin`]s into a single unit.
///
/// If you want an easier, but slightly more restrictive, method of implementing this trait, you
/// may be interested in the [`plugin_group!`] macro.
pub trait PluginGroup: Sized {
/// Configures the [`Plugin`]s that are to be added.
fn build(self) -> PluginGroupBuilder;
/// Configures a name for the [`PluginGroup`] which is primarily used for debugging.
fn name() -> String {
core::any::type_name::<Self>().to_string()
}
/// Sets the value of the given [`Plugin`], if it exists
fn set<T: Plugin>(self, plugin: T) -> PluginGroupBuilder {
self.build().set(plugin)
}
}
struct PluginEntry {
plugin: Box<dyn Plugin>,
enabled: bool,
}
impl PluginGroup for PluginGroupBuilder {
fn build(self) -> PluginGroupBuilder {
self
}
}
/// Facilitates the creation and configuration of a [`PluginGroup`].
///
/// Provides a build ordering to ensure that [`Plugin`]s which produce/require a [`Resource`](bevy_ecs::resource::Resource)
/// are built before/after dependent/depending [`Plugin`]s. [`Plugin`]s inside the group
/// can be disabled, enabled or reordered.
pub struct PluginGroupBuilder {
group_name: String,
plugins: TypeIdMap<PluginEntry>,
order: Vec<TypeId>,
}
impl PluginGroupBuilder {
/// Start a new builder for the [`PluginGroup`].
pub fn start<PG: PluginGroup>() -> Self {
Self {
group_name: PG::name(),
plugins: Default::default(),
order: Default::default(),
}
}
/// Checks if the [`PluginGroupBuilder`] contains the given [`Plugin`].
pub fn contains<T: Plugin>(&self) -> bool {
self.plugins.contains_key(&TypeId::of::<T>())
}
/// Returns `true` if the [`PluginGroupBuilder`] contains the given [`Plugin`] and it's enabled.
pub fn enabled<T: Plugin>(&self) -> bool {
self.plugins
.get(&TypeId::of::<T>())
.is_some_and(|e| e.enabled)
}
/// Finds the index of a target [`Plugin`].
fn index_of<Target: Plugin>(&self) -> Option<usize> {
self.order
.iter()
.position(|&ty| ty == TypeId::of::<Target>())
}
// Insert the new plugin as enabled, and removes its previous ordering if it was
// already present
fn upsert_plugin_state<T: Plugin>(&mut self, plugin: T, added_at_index: usize) {
self.upsert_plugin_entry_state(
TypeId::of::<T>(),
PluginEntry {
plugin: Box::new(plugin),
enabled: true,
},
added_at_index,
);
}
// Insert the new plugin entry as enabled, and removes its previous ordering if it was
// already present
fn upsert_plugin_entry_state(
&mut self,
key: TypeId,
plugin: PluginEntry,
added_at_index: usize,
) {
if let Some(entry) = self.plugins.insert(key, plugin) {
if entry.enabled {
warn!(
"You are replacing plugin '{}' that was not disabled.",
entry.plugin.name()
);
}
if let Some(to_remove) = self
.order
.iter()
.enumerate()
.find(|(i, ty)| *i != added_at_index && **ty == key)
.map(|(i, _)| i)
{
self.order.remove(to_remove);
}
}
}
/// Sets the value of the given [`Plugin`], if it exists.
///
/// # Panics
///
/// Panics if the [`Plugin`] does not exist.
pub fn set<T: Plugin>(self, plugin: T) -> Self {
self.try_set(plugin).unwrap_or_else(|_| {
panic!(
"{} does not exist in this PluginGroup",
core::any::type_name::<T>(),
)
})
}
/// Tries to set the value of the given [`Plugin`], if it exists.
///
/// If the given plugin doesn't exist returns self and the passed in [`Plugin`].
pub fn try_set<T: Plugin>(mut self, plugin: T) -> Result<Self, (Self, T)> {
match self.plugins.entry(TypeId::of::<T>()) {
Entry::Occupied(mut entry) => {
entry.get_mut().plugin = Box::new(plugin);
Ok(self)
}
Entry::Vacant(_) => Err((self, plugin)),
}
}
/// Adds the plugin [`Plugin`] at the end of this [`PluginGroupBuilder`]. If the plugin was
/// already in the group, it is removed from its previous place.
// This is not confusing, clippy!
#[expect(
clippy::should_implement_trait,
reason = "This does not emulate the `+` operator, but is more akin to pushing to a stack."
)]
pub fn add<T: Plugin>(mut self, plugin: T) -> Self {
let target_index = self.order.len();
self.order.push(TypeId::of::<T>());
self.upsert_plugin_state(plugin, target_index);
self
}
/// Attempts to add the plugin [`Plugin`] at the end of this [`PluginGroupBuilder`].
///
/// If the plugin was already in the group the addition fails.
pub fn try_add<T: Plugin>(self, plugin: T) -> Result<Self, (Self, T)> {
if self.contains::<T>() {
return Err((self, plugin));
}
Ok(self.add(plugin))
}
/// Adds a [`PluginGroup`] at the end of this [`PluginGroupBuilder`]. If the plugin was
/// already in the group, it is removed from its previous place.
pub fn add_group(mut self, group: impl PluginGroup) -> Self {
let Self {
mut plugins, order, ..
} = group.build();
for plugin_id in order {
self.upsert_plugin_entry_state(
plugin_id,
plugins.remove(&plugin_id).unwrap(),
self.order.len(),
);
self.order.push(plugin_id);
}
self
}
/// Adds a [`Plugin`] in this [`PluginGroupBuilder`] before the plugin of type `Target`.
///
/// If the plugin was already the group, it is removed from its previous place.
///
/// # Panics
///
/// Panics if `Target` is not already in this [`PluginGroupBuilder`].
pub fn add_before<Target: Plugin>(self, plugin: impl Plugin) -> Self {
self.try_add_before_overwrite::<Target, _>(plugin)
.unwrap_or_else(|_| {
panic!(
"Plugin does not exist in group: {}.",
core::any::type_name::<Target>()
)
})
}
/// Adds a [`Plugin`] in this [`PluginGroupBuilder`] before the plugin of type `Target`.
///
/// If the plugin was already in the group the add fails. If there isn't a plugin
/// of type `Target` in the group the plugin we're trying to insert is returned.
pub fn try_add_before<Target: Plugin, Insert: Plugin>(
self,
plugin: Insert,
) -> Result<Self, (Self, Insert)> {
if self.contains::<Insert>() {
return Err((self, plugin));
}
self.try_add_before_overwrite::<Target, _>(plugin)
}
/// Adds a [`Plugin`] in this [`PluginGroupBuilder`] before the plugin of type `Target`.
///
/// If the plugin was already in the group, it is removed from its previous places.
/// If there isn't a plugin of type `Target` in the group the plugin we're trying to insert
/// is returned.
pub fn try_add_before_overwrite<Target: Plugin, Insert: Plugin>(
mut self,
plugin: Insert,
) -> Result<Self, (Self, Insert)> {
let Some(target_index) = self.index_of::<Target>() else {
return Err((self, plugin));
};
self.order.insert(target_index, TypeId::of::<Insert>());
self.upsert_plugin_state(plugin, target_index);
Ok(self)
}
/// Adds a [`Plugin`] in this [`PluginGroupBuilder`] after the plugin of type `Target`.
///
/// If the plugin was already the group, it is removed from its previous place.
///
/// # Panics
///
/// Panics if `Target` is not already in this [`PluginGroupBuilder`].
pub fn add_after<Target: Plugin>(self, plugin: impl Plugin) -> Self {
self.try_add_after_overwrite::<Target, _>(plugin)
.unwrap_or_else(|_| {
panic!(
"Plugin does not exist in group: {}.",
core::any::type_name::<Target>()
)
})
}
/// Adds a [`Plugin`] in this [`PluginGroupBuilder`] after the plugin of type `Target`.
///
/// If the plugin was already in the group the add fails. If there isn't a plugin
/// of type `Target` in the group the plugin we're trying to insert is returned.
pub fn try_add_after<Target: Plugin, Insert: Plugin>(
self,
plugin: Insert,
) -> Result<Self, (Self, Insert)> {
if self.contains::<Insert>() {
return Err((self, plugin));
}
self.try_add_after_overwrite::<Target, _>(plugin)
}
/// Adds a [`Plugin`] in this [`PluginGroupBuilder`] after the plugin of type `Target`.
///
/// If the plugin was already in the group, it is removed from its previous places.
/// If there isn't a plugin of type `Target` in the group the plugin we're trying to insert
/// is returned.
pub fn try_add_after_overwrite<Target: Plugin, Insert: Plugin>(
mut self,
plugin: Insert,
) -> Result<Self, (Self, Insert)> {
let Some(target_index) = self.index_of::<Target>() else {
return Err((self, plugin));
};
let target_index = target_index + 1;
self.order.insert(target_index, TypeId::of::<Insert>());
self.upsert_plugin_state(plugin, target_index);
Ok(self)
}
/// Enables a [`Plugin`].
///
/// [`Plugin`]s within a [`PluginGroup`] are enabled by default. This function is used to
/// opt back in to a [`Plugin`] after [disabling](Self::disable) it. If there are no plugins
/// of type `T` in this group, it will panic.
pub fn enable<T: Plugin>(mut self) -> Self {
let plugin_entry = self
.plugins
.get_mut(&TypeId::of::<T>())
.expect("Cannot enable a plugin that does not exist.");
plugin_entry.enabled = true;
self
}
/// Disables a [`Plugin`], preventing it from being added to the [`App`] with the rest of the
/// [`PluginGroup`]. The disabled [`Plugin`] keeps its place in the [`PluginGroup`], so it can
/// still be used for ordering with [`add_before`](Self::add_before) or
/// [`add_after`](Self::add_after), or it can be [re-enabled](Self::enable). If there are no
/// plugins of type `T` in this group, it will panic.
pub fn disable<T: Plugin>(mut self) -> Self {
let plugin_entry = self
.plugins
.get_mut(&TypeId::of::<T>())
.expect("Cannot disable a plugin that does not exist.");
plugin_entry.enabled = false;
self
}
/// Consumes the [`PluginGroupBuilder`] and [builds](Plugin::build) the contained [`Plugin`]s
/// in the order specified.
///
/// # Panics
///
/// Panics if one of the plugin in the group was already added to the application.
#[track_caller]
pub fn finish(mut self, app: &mut App) {
for ty in &self.order {
if let Some(entry) = self.plugins.remove(ty)
&& entry.enabled
{
debug!("added plugin: {}", entry.plugin.name());
if let Err(AppError::DuplicatePlugin { plugin_name }) =
app.add_boxed_plugin(entry.plugin)
{
panic!(
"Error adding plugin {} in group {}: plugin was already added in application",
plugin_name,
self.group_name
);
}
}
}
}
}
/// A plugin group which doesn't do anything. Useful for examples:
/// ```
/// # use bevy_app::prelude::*;
/// use bevy_app::NoopPluginGroup as MinimalPlugins;
///
/// fn main(){
/// App::new().add_plugins(MinimalPlugins).run();
/// }
/// ```
#[doc(hidden)]
pub struct NoopPluginGroup;
impl PluginGroup for NoopPluginGroup {
fn build(self) -> PluginGroupBuilder {
PluginGroupBuilder::start::<Self>()
}
}
#[cfg(test)]
mod tests {
use alloc::vec;
use core::{any::TypeId, fmt::Debug};
use super::PluginGroupBuilder;
use crate::{App, NoopPluginGroup, Plugin, PluginGroup};
#[derive(Default)]
struct PluginA;
impl Plugin for PluginA {
fn build(&self, _: &mut App) {}
}
#[derive(Default)]
struct PluginB;
impl Plugin for PluginB {
fn build(&self, _: &mut App) {}
}
#[derive(Default)]
struct PluginC;
impl Plugin for PluginC {
fn build(&self, _: &mut App) {}
}
#[derive(PartialEq, Debug)]
struct PluginWithData(u32);
impl Plugin for PluginWithData {
fn build(&self, _: &mut App) {}
}
fn get_plugin<T: Debug + 'static>(group: &PluginGroupBuilder, id: TypeId) -> &T {
group.plugins[&id]
.plugin
.as_any()
.downcast_ref::<T>()
.unwrap()
}
#[test]
fn contains() {
let group = PluginGroupBuilder::start::<NoopPluginGroup>()
.add(PluginA)
.add(PluginB);
assert!(group.contains::<PluginA>());
assert!(!group.contains::<PluginC>());
let group = group.disable::<PluginA>();
assert!(group.enabled::<PluginB>());
assert!(!group.enabled::<PluginA>());
}
#[test]
fn basic_ordering() {
let group = PluginGroupBuilder::start::<NoopPluginGroup>()
.add(PluginA)
.add(PluginB)
.add(PluginC);
assert_eq!(
group.order,
vec![
TypeId::of::<PluginA>(),
TypeId::of::<PluginB>(),
TypeId::of::<PluginC>(),
]
);
}
#[test]
fn add_before() {
let group = PluginGroupBuilder::start::<NoopPluginGroup>()
.add(PluginA)
.add(PluginB)
.add_before::<PluginB>(PluginC);
assert_eq!(
group.order,
vec![
TypeId::of::<PluginA>(),
TypeId::of::<PluginC>(),
TypeId::of::<PluginB>(),
]
);
}
#[test]
fn try_add_before() {
let group = PluginGroupBuilder::start::<NoopPluginGroup>().add(PluginA);
let Ok(group) = group.try_add_before::<PluginA, _>(PluginC) else {
panic!("PluginA wasn't in group");
};
assert_eq!(
group.order,
vec![TypeId::of::<PluginC>(), TypeId::of::<PluginA>(),]
);
assert!(group.try_add_before::<PluginA, _>(PluginC).is_err());
}
#[test]
#[should_panic(
expected = "Plugin does not exist in group: bevy_app::plugin_group::tests::PluginB."
)]
fn add_before_nonexistent() {
PluginGroupBuilder::start::<NoopPluginGroup>()
.add(PluginA)
.add_before::<PluginB>(PluginC);
}
#[test]
fn add_after() {
let group = PluginGroupBuilder::start::<NoopPluginGroup>()
.add(PluginA)
.add(PluginB)
.add_after::<PluginA>(PluginC);
assert_eq!(
group.order,
vec![
TypeId::of::<PluginA>(),
TypeId::of::<PluginC>(),
TypeId::of::<PluginB>(),
]
);
}
#[test]
fn try_add_after() {
let group = PluginGroupBuilder::start::<NoopPluginGroup>()
.add(PluginA)
.add(PluginB);
let Ok(group) = group.try_add_after::<PluginA, _>(PluginC) else {
panic!("PluginA wasn't in group");
};
assert_eq!(
group.order,
vec![
TypeId::of::<PluginA>(),
TypeId::of::<PluginC>(),
TypeId::of::<PluginB>(),
]
);
assert!(group.try_add_after::<PluginA, _>(PluginC).is_err());
}
#[test]
#[should_panic(
expected = "Plugin does not exist in group: bevy_app::plugin_group::tests::PluginB."
)]
fn add_after_nonexistent() {
PluginGroupBuilder::start::<NoopPluginGroup>()
.add(PluginA)
.add_after::<PluginB>(PluginC);
}
#[test]
fn add_overwrite() {
let group = PluginGroupBuilder::start::<NoopPluginGroup>()
.add(PluginA)
.add(PluginWithData(0x0F))
.add(PluginC);
let id = TypeId::of::<PluginWithData>();
assert_eq!(
get_plugin::<PluginWithData>(&group, id),
&PluginWithData(0x0F)
);
let group = group.add(PluginWithData(0xA0));
assert_eq!(
get_plugin::<PluginWithData>(&group, id),
&PluginWithData(0xA0)
);
assert_eq!(
group.order,
vec![
TypeId::of::<PluginA>(),
TypeId::of::<PluginC>(),
TypeId::of::<PluginWithData>(),
]
);
let Ok(group) = group.try_add_before_overwrite::<PluginA, _>(PluginWithData(0x01)) else {
panic!("PluginA wasn't in group");
};
assert_eq!(
get_plugin::<PluginWithData>(&group, id),
&PluginWithData(0x01)
);
assert_eq!(
group.order,
vec![
TypeId::of::<PluginWithData>(),
TypeId::of::<PluginA>(),
TypeId::of::<PluginC>(),
]
);
let Ok(group) = group.try_add_after_overwrite::<PluginA, _>(PluginWithData(0xdeadbeef))
else {
panic!("PluginA wasn't in group");
};
assert_eq!(
get_plugin::<PluginWithData>(&group, id),
&PluginWithData(0xdeadbeef)
);
assert_eq!(
group.order,
vec![
TypeId::of::<PluginA>(),
TypeId::of::<PluginWithData>(),
TypeId::of::<PluginC>(),
]
);
}
#[test]
fn readd() {
let group = PluginGroupBuilder::start::<NoopPluginGroup>()
.add(PluginA)
.add(PluginB)
.add(PluginC)
.add(PluginB);
assert_eq!(
group.order,
vec![
TypeId::of::<PluginA>(),
TypeId::of::<PluginC>(),
TypeId::of::<PluginB>(),
]
);
}
#[test]
fn readd_before() {
let group = PluginGroupBuilder::start::<NoopPluginGroup>()
.add(PluginA)
.add(PluginB)
.add(PluginC)
.add_before::<PluginB>(PluginC);
assert_eq!(
group.order,
vec![
TypeId::of::<PluginA>(),
TypeId::of::<PluginC>(),
TypeId::of::<PluginB>(),
]
);
}
#[test]
fn readd_after() {
let group = PluginGroupBuilder::start::<NoopPluginGroup>()
.add(PluginA)
.add(PluginB)
.add(PluginC)
.add_after::<PluginA>(PluginC);
assert_eq!(
group.order,
vec![
TypeId::of::<PluginA>(),
TypeId::of::<PluginC>(),
TypeId::of::<PluginB>(),
]
);
}
#[test]
fn add_basic_subgroup() {
let group_a = PluginGroupBuilder::start::<NoopPluginGroup>()
.add(PluginA)
.add(PluginB);
let group_b = PluginGroupBuilder::start::<NoopPluginGroup>()
.add_group(group_a)
.add(PluginC);
assert_eq!(
group_b.order,
vec![
TypeId::of::<PluginA>(),
TypeId::of::<PluginB>(),
TypeId::of::<PluginC>(),
]
);
}
#[test]
fn add_conflicting_subgroup() {
let group_a = PluginGroupBuilder::start::<NoopPluginGroup>()
.add(PluginA)
.add(PluginC);
let group_b = PluginGroupBuilder::start::<NoopPluginGroup>()
.add(PluginB)
.add(PluginC);
let group = PluginGroupBuilder::start::<NoopPluginGroup>()
.add_group(group_a)
.add_group(group_b);
assert_eq!(
group.order,
vec![
TypeId::of::<PluginA>(),
TypeId::of::<PluginB>(),
TypeId::of::<PluginC>(),
]
);
}
plugin_group! {
#[derive(Default)]
struct PluginGroupA {
:PluginA
}
}
plugin_group! {
#[derive(Default)]
struct PluginGroupB {
:PluginB
}
}
plugin_group! {
struct PluginGroupC {
:PluginC
#[plugin_group]
:PluginGroupA,
#[plugin_group]
:PluginGroupB,
}
}
#[test]
fn construct_nested_plugin_groups() {
PluginGroupC {}.build();
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_app/src/schedule_runner.rs | crates/bevy_app/src/schedule_runner.rs | use crate::{
app::{App, AppExit},
plugin::Plugin,
PluginsState,
};
use bevy_platform::time::Instant;
use core::time::Duration;
#[cfg(all(target_arch = "wasm32", feature = "web"))]
use {
alloc::{boxed::Box, rc::Rc},
core::cell::RefCell,
wasm_bindgen::{prelude::*, JsCast},
};
/// Determines the method used to run an [`App`]'s [`Schedule`](bevy_ecs::schedule::Schedule).
///
/// It is used in the [`ScheduleRunnerPlugin`].
#[derive(Copy, Clone, Debug)]
pub enum RunMode {
/// Indicates that the [`App`]'s schedule should run repeatedly.
Loop {
/// The minimum [`Duration`] to wait after a [`Schedule`](bevy_ecs::schedule::Schedule)
/// has completed before repeating. A value of [`None`] will not wait.
wait: Option<Duration>,
},
/// Indicates that the [`App`]'s schedule should run only once.
Once,
}
impl Default for RunMode {
fn default() -> Self {
RunMode::Loop { wait: None }
}
}
/// Configures an [`App`] to run its [`Schedule`](bevy_ecs::schedule::Schedule) according to a given
/// [`RunMode`].
///
/// [`ScheduleRunnerPlugin`] is included in the
/// [`MinimalPlugins`](https://docs.rs/bevy/latest/bevy/struct.MinimalPlugins.html) plugin group.
///
/// [`ScheduleRunnerPlugin`] is *not* included in the
/// [`DefaultPlugins`](https://docs.rs/bevy/latest/bevy/struct.DefaultPlugins.html) plugin group
/// which assumes that the [`Schedule`](bevy_ecs::schedule::Schedule) will be executed by other means:
/// typically, the `winit` event loop
/// (see [`WinitPlugin`](https://docs.rs/bevy/latest/bevy/winit/struct.WinitPlugin.html))
/// executes the schedule making [`ScheduleRunnerPlugin`] unnecessary.
#[derive(Default)]
pub struct ScheduleRunnerPlugin {
/// Determines whether the [`Schedule`](bevy_ecs::schedule::Schedule) is run once or repeatedly.
pub run_mode: RunMode,
}
impl ScheduleRunnerPlugin {
/// See [`RunMode::Once`].
pub fn run_once() -> Self {
ScheduleRunnerPlugin {
run_mode: RunMode::Once,
}
}
/// See [`RunMode::Loop`].
pub fn run_loop(wait_duration: Duration) -> Self {
ScheduleRunnerPlugin {
run_mode: RunMode::Loop {
wait: Some(wait_duration),
},
}
}
}
impl Plugin for ScheduleRunnerPlugin {
fn build(&self, app: &mut App) {
let run_mode = self.run_mode;
app.set_runner(move |mut app: App| {
let plugins_state = app.plugins_state();
if plugins_state != PluginsState::Cleaned {
while app.plugins_state() == PluginsState::Adding {
#[cfg(not(all(target_arch = "wasm32", feature = "web")))]
bevy_tasks::tick_global_task_pools_on_main_thread();
}
app.finish();
app.cleanup();
}
match run_mode {
RunMode::Once => {
app.update();
if let Some(exit) = app.should_exit() {
return exit;
}
AppExit::Success
}
RunMode::Loop { wait } => {
let tick = move |app: &mut App,
_wait: Option<Duration>|
-> Result<Option<Duration>, AppExit> {
let start_time = Instant::now();
app.update();
if let Some(exit) = app.should_exit() {
return Err(exit);
};
let end_time = Instant::now();
if let Some(wait) = _wait {
let exe_time = end_time - start_time;
if exe_time < wait {
return Ok(Some(wait - exe_time));
}
}
Ok(None)
};
cfg_if::cfg_if! {
if #[cfg(all(target_arch = "wasm32", feature = "web"))] {
fn set_timeout(callback: &Closure<dyn FnMut()>, dur: Duration) {
web_sys::window()
.unwrap()
.set_timeout_with_callback_and_timeout_and_arguments_0(
callback.as_ref().unchecked_ref(),
dur.as_millis() as i32,
)
.expect("Should register `setTimeout`.");
}
let asap = Duration::from_millis(1);
let exit = Rc::new(RefCell::new(AppExit::Success));
let closure_exit = exit.clone();
let mut app = Rc::new(app);
let moved_tick_closure = Rc::new(RefCell::new(None));
let base_tick_closure = moved_tick_closure.clone();
let tick_app = move || {
let app = Rc::get_mut(&mut app).unwrap();
let delay = tick(app, wait);
match delay {
Ok(delay) => set_timeout(
moved_tick_closure.borrow().as_ref().unwrap(),
delay.unwrap_or(asap),
),
Err(code) => {
closure_exit.replace(code);
}
}
};
*base_tick_closure.borrow_mut() =
Some(Closure::wrap(Box::new(tick_app) as Box<dyn FnMut()>));
set_timeout(base_tick_closure.borrow().as_ref().unwrap(), asap);
exit.take()
} else {
loop {
match tick(&mut app, wait) {
Ok(Some(delay)) => {
bevy_platform::thread::sleep(delay);
}
Ok(None) => continue,
Err(exit) => return exit,
}
}
}
}
}
}
});
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_app/src/main_schedule.rs | crates/bevy_app/src/main_schedule.rs | use crate::{App, Plugin};
use alloc::{vec, vec::Vec};
use bevy_ecs::{
resource::Resource,
schedule::{
ExecutorKind, InternedScheduleLabel, IntoScheduleConfigs, Schedule, ScheduleLabel,
SystemSet,
},
system::Local,
world::{Mut, World},
};
/// The schedule that contains the app logic that is evaluated each tick of [`App::update()`].
///
/// By default, it will run the following schedules in the given order:
///
/// On the first run of the schedule (and only on the first run), it will run:
/// * [`StateTransition`] [^1]
/// * This means that [`OnEnter(MyState::Foo)`] will be called *before* [`PreStartup`]
/// if `MyState` was added to the app with `MyState::Foo` as the initial state,
/// as well as [`OnEnter(MyComputedState)`] if it `compute`s to `Some(Self)` in `MyState::Foo`.
/// * If you want to run systems before any state transitions, regardless of which state is the starting state,
/// for example, for registering required components, you can add your own custom startup schedule
/// before [`StateTransition`]. See [`MainScheduleOrder::insert_startup_before`] for more details.
/// * [`PreStartup`]
/// * [`Startup`]
/// * [`PostStartup`]
///
/// Then it will run:
/// * [`First`]
/// * [`PreUpdate`]
/// * [`StateTransition`] [^1]
/// * [`RunFixedMainLoop`]
/// * This will run [`FixedMain`] zero to many times, based on how much time has elapsed.
/// * [`Update`]
/// * [`SpawnScene`]
/// * [`PostUpdate`]
/// * [`Last`]
///
/// # Rendering
///
/// Note rendering is not executed in the main schedule by default.
/// Instead, rendering is performed in a separate [`SubApp`]
/// which exchanges data with the main app in between the main schedule runs.
///
/// See [`RenderPlugin`] and [`PipelinedRenderingPlugin`] for more details.
///
/// [^1]: [`StateTransition`] is inserted only if you have `bevy_state` feature enabled. It is enabled in `default` features.
///
/// [`StateTransition`]: https://docs.rs/bevy/latest/bevy/prelude/struct.StateTransition.html
/// [`OnEnter(MyState::Foo)`]: https://docs.rs/bevy/latest/bevy/prelude/struct.OnEnter.html
/// [`OnEnter(MyComputedState)`]: https://docs.rs/bevy/latest/bevy/prelude/struct.OnEnter.html
/// [`RenderPlugin`]: https://docs.rs/bevy/latest/bevy/render/struct.RenderPlugin.html
/// [`PipelinedRenderingPlugin`]: https://docs.rs/bevy/latest/bevy/render/pipelined_rendering/struct.PipelinedRenderingPlugin.html
/// [`SubApp`]: crate::SubApp
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct Main;
/// The schedule that runs before [`Startup`].
///
/// See the [`Main`] schedule for some details about how schedules are run.
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct PreStartup;
/// The schedule that runs once when the app starts.
///
/// See the [`Main`] schedule for some details about how schedules are run.
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct Startup;
/// The schedule that runs once after [`Startup`].
///
/// See the [`Main`] schedule for some details about how schedules are run.
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct PostStartup;
/// Runs first in the schedule.
///
/// See the [`Main`] schedule for some details about how schedules are run.
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct First;
/// The schedule that contains logic that must run before [`Update`]. For example, a system that reads raw keyboard
/// input OS events into a `Messages` resource. This enables systems in [`Update`] to consume the messages from the `Messages`
/// resource without actually knowing about (or taking a direct scheduler dependency on) the "os-level keyboard event system".
///
/// [`PreUpdate`] exists to do "engine/plugin preparation work" that ensures the APIs consumed in [`Update`] are "ready".
/// [`PreUpdate`] abstracts out "pre work implementation details".
///
/// See the [`Main`] schedule for some details about how schedules are run.
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct PreUpdate;
/// Runs the [`FixedMain`] schedule in a loop according until all relevant elapsed time has been "consumed".
///
/// If you need to order your variable timestep systems before or after
/// the fixed update logic, use the [`RunFixedMainLoopSystems`] system set.
///
/// Note that in contrast to most other Bevy schedules, systems added directly to
/// [`RunFixedMainLoop`] will *not* be parallelized between each other.
///
/// See the [`Main`] schedule for some details about how schedules are run.
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct RunFixedMainLoop;
/// Runs first in the [`FixedMain`] schedule.
///
/// See the [`FixedMain`] schedule for details on how fixed updates work.
/// See the [`Main`] schedule for some details about how schedules are run.
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct FixedFirst;
/// The schedule that contains logic that must run before [`FixedUpdate`].
///
/// See the [`FixedMain`] schedule for details on how fixed updates work.
/// See the [`Main`] schedule for some details about how schedules are run.
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct FixedPreUpdate;
/// The schedule that contains most gameplay logic, which runs at a fixed rate rather than every render frame.
/// For logic that should run once per render frame, use the [`Update`] schedule instead.
///
/// Examples of systems that should run at a fixed rate include (but are not limited to):
/// - Physics
/// - AI
/// - Networking
/// - Game rules
///
/// See the [`Update`] schedule for examples of systems that *should not* use this schedule.
/// See the [`FixedMain`] schedule for details on how fixed updates work.
/// See the [`Main`] schedule for some details about how schedules are run.
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct FixedUpdate;
/// The schedule that runs after the [`FixedUpdate`] schedule, for reacting
/// to changes made in the main update logic.
///
/// See the [`FixedMain`] schedule for details on how fixed updates work.
/// See the [`Main`] schedule for some details about how schedules are run.
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct FixedPostUpdate;
/// The schedule that runs last in [`FixedMain`]
///
/// See the [`FixedMain`] schedule for details on how fixed updates work.
/// See the [`Main`] schedule for some details about how schedules are run.
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct FixedLast;
/// The schedule that contains systems which only run after a fixed period of time has elapsed.
///
/// This is run by the [`RunFixedMainLoop`] schedule. If you need to order your variable timestep systems
/// before or after the fixed update logic, use the [`RunFixedMainLoopSystems`] system set.
///
/// Frequency of execution is configured by inserting `Time<Fixed>` resource, 64 Hz by default.
/// See [this example](https://github.com/bevyengine/bevy/blob/latest/examples/time/time.rs).
///
/// See the [`Main`] schedule for some details about how schedules are run.
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct FixedMain;
/// The schedule that contains any app logic that must run once per render frame.
/// For most gameplay logic, consider using [`FixedUpdate`] instead.
///
/// Examples of systems that should run once per render frame include (but are not limited to):
/// - UI
/// - Input handling
/// - Audio control
///
/// See the [`FixedUpdate`] schedule for examples of systems that *should not* use this schedule.
/// See the [`Main`] schedule for some details about how schedules are run.
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct Update;
/// The schedule that contains scene spawning.
///
/// This runs after [`Update`] and before [`PostUpdate`]. See the [`Main`] schedule for more details about how schedules are run.
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct SpawnScene;
/// The schedule that contains logic that must run after [`Update`]. For example, synchronizing "local transforms" in a hierarchy
/// to "global" absolute transforms. This enables the [`PostUpdate`] transform-sync system to react to "local transform" changes in
/// [`Update`] without the [`Update`] systems needing to know about (or add scheduler dependencies for) the "global transform sync system".
///
/// [`PostUpdate`] exists to do "engine/plugin response work" to things that happened in [`Update`].
/// [`PostUpdate`] abstracts out "implementation details" from users defining systems in [`Update`].
///
/// See the [`Main`] schedule for some details about how schedules are run.
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct PostUpdate;
/// Runs last in the schedule.
///
/// See the [`Main`] schedule for some details about how schedules are run.
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct Last;
/// Animation system set. This exists in [`PostUpdate`].
#[derive(SystemSet, Debug, Hash, PartialEq, Eq, Clone)]
pub struct AnimationSystems;
/// Defines the schedules to be run for the [`Main`] schedule, including
/// their order.
#[derive(Resource, Debug)]
pub struct MainScheduleOrder {
/// The labels to run for the main phase of the [`Main`] schedule (in the order they will be run).
pub labels: Vec<InternedScheduleLabel>,
/// The labels to run for the startup phase of the [`Main`] schedule (in the order they will be run).
pub startup_labels: Vec<InternedScheduleLabel>,
}
impl Default for MainScheduleOrder {
fn default() -> Self {
Self {
labels: vec![
First.intern(),
PreUpdate.intern(),
RunFixedMainLoop.intern(),
Update.intern(),
SpawnScene.intern(),
PostUpdate.intern(),
Last.intern(),
],
startup_labels: vec![PreStartup.intern(), Startup.intern(), PostStartup.intern()],
}
}
}
impl MainScheduleOrder {
/// Adds the given `schedule` after the `after` schedule in the main list of schedules.
pub fn insert_after(&mut self, after: impl ScheduleLabel, schedule: impl ScheduleLabel) {
let index = self
.labels
.iter()
.position(|current| (**current).eq(&after))
.unwrap_or_else(|| panic!("Expected {after:?} to exist"));
self.labels.insert(index + 1, schedule.intern());
}
/// Adds the given `schedule` before the `before` schedule in the main list of schedules.
pub fn insert_before(&mut self, before: impl ScheduleLabel, schedule: impl ScheduleLabel) {
let index = self
.labels
.iter()
.position(|current| (**current).eq(&before))
.unwrap_or_else(|| panic!("Expected {before:?} to exist"));
self.labels.insert(index, schedule.intern());
}
/// Adds the given `schedule` after the `after` schedule in the list of startup schedules.
pub fn insert_startup_after(
&mut self,
after: impl ScheduleLabel,
schedule: impl ScheduleLabel,
) {
let index = self
.startup_labels
.iter()
.position(|current| (**current).eq(&after))
.unwrap_or_else(|| panic!("Expected {after:?} to exist"));
self.startup_labels.insert(index + 1, schedule.intern());
}
/// Adds the given `schedule` before the `before` schedule in the list of startup schedules.
pub fn insert_startup_before(
&mut self,
before: impl ScheduleLabel,
schedule: impl ScheduleLabel,
) {
let index = self
.startup_labels
.iter()
.position(|current| (**current).eq(&before))
.unwrap_or_else(|| panic!("Expected {before:?} to exist"));
self.startup_labels.insert(index, schedule.intern());
}
}
impl Main {
/// A system that runs the "main schedule"
pub fn run_main(world: &mut World, mut run_at_least_once: Local<bool>) {
if !*run_at_least_once {
world.resource_scope(|world, order: Mut<MainScheduleOrder>| {
for &label in &order.startup_labels {
let _ = world.try_run_schedule(label);
}
});
*run_at_least_once = true;
}
world.resource_scope(|world, order: Mut<MainScheduleOrder>| {
for &label in &order.labels {
let _ = world.try_run_schedule(label);
}
});
}
}
/// Initializes the [`Main`] schedule, sub schedules, and resources for a given [`App`].
pub struct MainSchedulePlugin;
impl Plugin for MainSchedulePlugin {
fn build(&self, app: &mut App) {
// simple "facilitator" schedules benefit from simpler single threaded scheduling
let mut main_schedule = Schedule::new(Main);
main_schedule.set_executor_kind(ExecutorKind::SingleThreaded);
let mut fixed_main_schedule = Schedule::new(FixedMain);
fixed_main_schedule.set_executor_kind(ExecutorKind::SingleThreaded);
let mut fixed_main_loop_schedule = Schedule::new(RunFixedMainLoop);
fixed_main_loop_schedule.set_executor_kind(ExecutorKind::SingleThreaded);
app.add_schedule(main_schedule)
.add_schedule(fixed_main_schedule)
.add_schedule(fixed_main_loop_schedule)
.init_resource::<MainScheduleOrder>()
.init_resource::<FixedMainScheduleOrder>()
.add_systems(Main, Main::run_main)
.add_systems(FixedMain, FixedMain::run_fixed_main)
.configure_sets(
RunFixedMainLoop,
(
RunFixedMainLoopSystems::BeforeFixedMainLoop,
RunFixedMainLoopSystems::FixedMainLoop,
RunFixedMainLoopSystems::AfterFixedMainLoop,
)
.chain(),
);
#[cfg(feature = "bevy_debug_stepping")]
{
use bevy_ecs::schedule::{IntoScheduleConfigs, Stepping};
app.add_systems(Main, Stepping::begin_frame.before(Main::run_main));
}
}
}
/// Defines the schedules to be run for the [`FixedMain`] schedule, including
/// their order.
#[derive(Resource, Debug)]
pub struct FixedMainScheduleOrder {
/// The labels to run for the [`FixedMain`] schedule (in the order they will be run).
pub labels: Vec<InternedScheduleLabel>,
}
impl Default for FixedMainScheduleOrder {
fn default() -> Self {
Self {
labels: vec![
FixedFirst.intern(),
FixedPreUpdate.intern(),
FixedUpdate.intern(),
FixedPostUpdate.intern(),
FixedLast.intern(),
],
}
}
}
impl FixedMainScheduleOrder {
/// Adds the given `schedule` after the `after` schedule
pub fn insert_after(&mut self, after: impl ScheduleLabel, schedule: impl ScheduleLabel) {
let index = self
.labels
.iter()
.position(|current| (**current).eq(&after))
.unwrap_or_else(|| panic!("Expected {after:?} to exist"));
self.labels.insert(index + 1, schedule.intern());
}
/// Adds the given `schedule` before the `before` schedule
pub fn insert_before(&mut self, before: impl ScheduleLabel, schedule: impl ScheduleLabel) {
let index = self
.labels
.iter()
.position(|current| (**current).eq(&before))
.unwrap_or_else(|| panic!("Expected {before:?} to exist"));
self.labels.insert(index, schedule.intern());
}
}
impl FixedMain {
/// A system that runs the fixed timestep's "main schedule"
pub fn run_fixed_main(world: &mut World) {
world.resource_scope(|world, order: Mut<FixedMainScheduleOrder>| {
for &label in &order.labels {
let _ = world.try_run_schedule(label);
}
});
}
}
/// Set enum for the systems that want to run inside [`RunFixedMainLoop`],
/// but before or after the fixed update logic. Systems in this set
/// will run exactly once per frame, regardless of the number of fixed updates.
/// They will also run under a variable timestep.
///
/// This is useful for handling things that need to run every frame, but
/// also need to be read by the fixed update logic. See the individual variants
/// for examples of what kind of systems should be placed in each.
///
/// Note that in contrast to most other Bevy schedules, systems added directly to
/// [`RunFixedMainLoop`] will *not* be parallelized between each other.
#[derive(Debug, Hash, PartialEq, Eq, Copy, Clone, SystemSet)]
pub enum RunFixedMainLoopSystems {
/// Runs before the fixed update logic.
///
/// A good example of a system that fits here
/// is camera movement, which needs to be updated in a variable timestep,
/// as you want the camera to move with as much precision and updates as
/// the frame rate allows. A physics system that needs to read the camera
/// position and orientation, however, should run in the fixed update logic,
/// as it needs to be deterministic and run at a fixed rate for better stability.
/// Note that we are not placing the camera movement system in `Update`, as that
/// would mean that the physics system already ran at that point.
///
/// # Example
/// ```
/// # use bevy_app::prelude::*;
/// # use bevy_ecs::prelude::*;
/// App::new()
/// .add_systems(
/// RunFixedMainLoop,
/// update_camera_rotation.in_set(RunFixedMainLoopSystems::BeforeFixedMainLoop))
/// .add_systems(FixedUpdate, update_physics);
///
/// # fn update_camera_rotation() {}
/// # fn update_physics() {}
/// ```
BeforeFixedMainLoop,
/// Contains the fixed update logic.
/// Runs [`FixedMain`] zero or more times based on delta of
/// [`Time<Virtual>`] and [`Time::overstep`].
///
/// Don't place systems here, use [`FixedUpdate`] and friends instead.
/// Use this system instead to order your systems to run specifically inbetween the fixed update logic and all
/// other systems that run in [`RunFixedMainLoopSystems::BeforeFixedMainLoop`] or [`RunFixedMainLoopSystems::AfterFixedMainLoop`].
///
/// [`Time<Virtual>`]: https://docs.rs/bevy/latest/bevy/prelude/struct.Virtual.html
/// [`Time::overstep`]: https://docs.rs/bevy/latest/bevy/time/struct.Time.html#method.overstep
/// # Example
/// ```
/// # use bevy_app::prelude::*;
/// # use bevy_ecs::prelude::*;
/// App::new()
/// .add_systems(FixedUpdate, update_physics)
/// .add_systems(
/// RunFixedMainLoop,
/// (
/// // This system will be called before all interpolation systems
/// // that third-party plugins might add.
/// prepare_for_interpolation
/// .after(RunFixedMainLoopSystems::FixedMainLoop)
/// .before(RunFixedMainLoopSystems::AfterFixedMainLoop),
/// )
/// );
///
/// # fn prepare_for_interpolation() {}
/// # fn update_physics() {}
/// ```
FixedMainLoop,
/// Runs after the fixed update logic.
///
/// A good example of a system that fits here
/// is a system that interpolates the transform of an entity between the last and current fixed update.
/// See the [fixed timestep example] for more details.
///
/// [fixed timestep example]: https://github.com/bevyengine/bevy/blob/main/examples/movement/physics_in_fixed_timestep.rs
///
/// # Example
/// ```
/// # use bevy_app::prelude::*;
/// # use bevy_ecs::prelude::*;
/// App::new()
/// .add_systems(FixedUpdate, update_physics)
/// .add_systems(
/// RunFixedMainLoop,
/// interpolate_transforms.in_set(RunFixedMainLoopSystems::AfterFixedMainLoop));
///
/// # fn interpolate_transforms() {}
/// # fn update_physics() {}
/// ```
AfterFixedMainLoop,
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_app/src/terminal_ctrl_c_handler.rs | crates/bevy_app/src/terminal_ctrl_c_handler.rs | use core::sync::atomic::{AtomicBool, Ordering};
use bevy_ecs::message::MessageWriter;
use crate::{App, AppExit, Plugin, Update};
pub use ctrlc;
/// Indicates that all [`App`]'s should exit.
static SHOULD_EXIT: AtomicBool = AtomicBool::new(false);
/// Gracefully handles `Ctrl+C` by emitting a [`AppExit`] event. This plugin is part of the `DefaultPlugins`.
///
/// ```no_run
/// # use bevy_app::{App, NoopPluginGroup as MinimalPlugins, PluginGroup, TerminalCtrlCHandlerPlugin};
/// fn main() {
/// App::new()
/// .add_plugins(MinimalPlugins)
/// .add_plugins(TerminalCtrlCHandlerPlugin)
/// .run();
/// }
/// ```
///
/// If you want to setup your own `Ctrl+C` handler, you should call the
/// [`TerminalCtrlCHandlerPlugin::gracefully_exit`] function in your handler if you want bevy to gracefully exit.
/// ```no_run
/// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup, TerminalCtrlCHandlerPlugin, ctrlc};
/// fn main() {
/// // Your own `Ctrl+C` handler
/// ctrlc::set_handler(move || {
/// // Other clean up code ...
///
/// TerminalCtrlCHandlerPlugin::gracefully_exit();
/// });
///
/// App::new()
/// .add_plugins(DefaultPlugins)
/// .run();
/// }
/// ```
#[derive(Default)]
pub struct TerminalCtrlCHandlerPlugin;
impl TerminalCtrlCHandlerPlugin {
/// Sends the [`AppExit`] event to all apps using this plugin to make them gracefully exit.
pub fn gracefully_exit() {
SHOULD_EXIT.store(true, Ordering::Relaxed);
}
/// Sends a [`AppExit`] event when the user presses `Ctrl+C` on the terminal.
pub fn exit_on_flag(mut app_exit_writer: MessageWriter<AppExit>) {
if SHOULD_EXIT.load(Ordering::Relaxed) {
app_exit_writer.write(AppExit::from_code(130));
}
}
}
impl Plugin for TerminalCtrlCHandlerPlugin {
fn build(&self, app: &mut App) {
let result = ctrlc::try_set_handler(move || {
Self::gracefully_exit();
});
match result {
Ok(()) => {}
Err(ctrlc::Error::MultipleHandlers) => {
log::info!("Skipping installing `Ctrl+C` handler as one was already installed. Please call `TerminalCtrlCHandlerPlugin::gracefully_exit` in your own `Ctrl+C` handler if you want Bevy to gracefully exit on `Ctrl+C`.");
}
Err(err) => log::warn!("Failed to set `Ctrl+C` handler: {err}"),
}
app.add_systems(Update, TerminalCtrlCHandlerPlugin::exit_on_flag);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_app/src/task_pool_plugin.rs | crates/bevy_app/src/task_pool_plugin.rs | use crate::{App, Plugin};
use alloc::string::ToString;
use bevy_platform::sync::Arc;
use bevy_tasks::{AsyncComputeTaskPool, ComputeTaskPool, IoTaskPool, TaskPoolBuilder};
use core::fmt::Debug;
use log::trace;
cfg_if::cfg_if! {
if #[cfg(not(all(target_arch = "wasm32", feature = "web")))] {
use {crate::Last, bevy_tasks::tick_global_task_pools_on_main_thread};
use bevy_ecs::system::NonSendMarker;
/// A system used to check and advanced our task pools.
///
/// Calls [`tick_global_task_pools_on_main_thread`],
/// and uses [`NonSendMarker`] to ensure that this system runs on the main thread
fn tick_global_task_pools(_main_thread_marker: NonSendMarker) {
tick_global_task_pools_on_main_thread();
}
}
}
/// Setup of default task pools: [`AsyncComputeTaskPool`], [`ComputeTaskPool`], [`IoTaskPool`].
#[derive(Default)]
pub struct TaskPoolPlugin {
/// Options for the [`TaskPool`](bevy_tasks::TaskPool) created at application start.
pub task_pool_options: TaskPoolOptions,
}
impl Plugin for TaskPoolPlugin {
fn build(&self, _app: &mut App) {
// Setup the default bevy task pools
self.task_pool_options.create_default_pools();
#[cfg(not(all(target_arch = "wasm32", feature = "web")))]
_app.add_systems(Last, tick_global_task_pools);
}
}
/// Defines a simple way to determine how many threads to use given the number of remaining cores
/// and number of total cores
#[derive(Clone)]
pub struct TaskPoolThreadAssignmentPolicy {
/// Force using at least this many threads
pub min_threads: usize,
/// Under no circumstance use more than this many threads for this pool
pub max_threads: usize,
/// Target using this percentage of total cores, clamped by `min_threads` and `max_threads`. It is
/// permitted to use 1.0 to try to use all remaining threads
pub percent: f32,
/// Callback that is invoked once for every created thread as it starts.
/// This configuration will be ignored under wasm platform.
pub on_thread_spawn: Option<Arc<dyn Fn() + Send + Sync + 'static>>,
/// Callback that is invoked once for every created thread as it terminates
/// This configuration will be ignored under wasm platform.
pub on_thread_destroy: Option<Arc<dyn Fn() + Send + Sync + 'static>>,
}
impl Debug for TaskPoolThreadAssignmentPolicy {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("TaskPoolThreadAssignmentPolicy")
.field("min_threads", &self.min_threads)
.field("max_threads", &self.max_threads)
.field("percent", &self.percent)
.finish()
}
}
impl TaskPoolThreadAssignmentPolicy {
/// Determine the number of threads to use for this task pool
fn get_number_of_threads(&self, remaining_threads: usize, total_threads: usize) -> usize {
assert!(self.percent >= 0.0);
let proportion = total_threads as f32 * self.percent;
let mut desired = proportion as usize;
// Equivalent to round() for positive floats without libm requirement for
// no_std compatibility
if proportion - desired as f32 >= 0.5 {
desired += 1;
}
// Limit ourselves to the number of cores available
desired = desired.min(remaining_threads);
// Clamp by min_threads, max_threads. (This may result in us using more threads than are
// available, this is intended. An example case where this might happen is a device with
// <= 2 threads.
desired.clamp(self.min_threads, self.max_threads)
}
}
/// Helper for configuring and creating the default task pools. For end-users who want full control,
/// set up [`TaskPoolPlugin`]
#[derive(Clone, Debug)]
pub struct TaskPoolOptions {
/// If the number of physical cores is less than `min_total_threads`, force using
/// `min_total_threads`
pub min_total_threads: usize,
/// If the number of physical cores is greater than `max_total_threads`, force using
/// `max_total_threads`
pub max_total_threads: usize,
/// Used to determine number of IO threads to allocate
pub io: TaskPoolThreadAssignmentPolicy,
/// Used to determine number of async compute threads to allocate
pub async_compute: TaskPoolThreadAssignmentPolicy,
/// Used to determine number of compute threads to allocate
pub compute: TaskPoolThreadAssignmentPolicy,
}
impl Default for TaskPoolOptions {
fn default() -> Self {
TaskPoolOptions {
// By default, use however many cores are available on the system
min_total_threads: 1,
max_total_threads: usize::MAX,
// Use 25% of cores for IO, at least 1, no more than 4
io: TaskPoolThreadAssignmentPolicy {
min_threads: 1,
max_threads: 4,
percent: 0.25,
on_thread_spawn: None,
on_thread_destroy: None,
},
// Use 25% of cores for async compute, at least 1, no more than 4
async_compute: TaskPoolThreadAssignmentPolicy {
min_threads: 1,
max_threads: 4,
percent: 0.25,
on_thread_spawn: None,
on_thread_destroy: None,
},
// Use all remaining cores for compute (at least 1)
compute: TaskPoolThreadAssignmentPolicy {
min_threads: 1,
max_threads: usize::MAX,
percent: 1.0, // This 1.0 here means "whatever is left over"
on_thread_spawn: None,
on_thread_destroy: None,
},
}
}
}
impl TaskPoolOptions {
/// Create a configuration that forces using the given number of threads.
pub fn with_num_threads(thread_count: usize) -> Self {
TaskPoolOptions {
min_total_threads: thread_count,
max_total_threads: thread_count,
..Default::default()
}
}
/// Inserts the default thread pools into the given resource map based on the configured values
pub fn create_default_pools(&self) {
let total_threads = bevy_tasks::available_parallelism()
.clamp(self.min_total_threads, self.max_total_threads);
trace!("Assigning {total_threads} cores to default task pools");
let mut remaining_threads = total_threads;
{
// Determine the number of IO threads we will use
let io_threads = self
.io
.get_number_of_threads(remaining_threads, total_threads);
trace!("IO Threads: {io_threads}");
remaining_threads = remaining_threads.saturating_sub(io_threads);
IoTaskPool::get_or_init(|| {
let builder = TaskPoolBuilder::default()
.num_threads(io_threads)
.thread_name("IO Task Pool".to_string());
#[cfg(not(all(target_arch = "wasm32", feature = "web")))]
let builder = {
let mut builder = builder;
if let Some(f) = self.io.on_thread_spawn.clone() {
builder = builder.on_thread_spawn(move || f());
}
if let Some(f) = self.io.on_thread_destroy.clone() {
builder = builder.on_thread_destroy(move || f());
}
builder
};
builder.build()
});
}
{
// Determine the number of async compute threads we will use
let async_compute_threads = self
.async_compute
.get_number_of_threads(remaining_threads, total_threads);
trace!("Async Compute Threads: {async_compute_threads}");
remaining_threads = remaining_threads.saturating_sub(async_compute_threads);
AsyncComputeTaskPool::get_or_init(|| {
let builder = TaskPoolBuilder::default()
.num_threads(async_compute_threads)
.thread_name("Async Compute Task Pool".to_string());
#[cfg(not(all(target_arch = "wasm32", feature = "web")))]
let builder = {
let mut builder = builder;
if let Some(f) = self.async_compute.on_thread_spawn.clone() {
builder = builder.on_thread_spawn(move || f());
}
if let Some(f) = self.async_compute.on_thread_destroy.clone() {
builder = builder.on_thread_destroy(move || f());
}
builder
};
builder.build()
});
}
{
// Determine the number of compute threads we will use
// This is intentionally last so that an end user can specify 1.0 as the percent
let compute_threads = self
.compute
.get_number_of_threads(remaining_threads, total_threads);
trace!("Compute Threads: {compute_threads}");
ComputeTaskPool::get_or_init(|| {
let builder = TaskPoolBuilder::default()
.num_threads(compute_threads)
.thread_name("Compute Task Pool".to_string());
#[cfg(not(all(target_arch = "wasm32", feature = "web")))]
let builder = {
let mut builder = builder;
if let Some(f) = self.compute.on_thread_spawn.clone() {
builder = builder.on_thread_spawn(move || f());
}
if let Some(f) = self.compute.on_thread_destroy.clone() {
builder = builder.on_thread_destroy(move || f());
}
builder
};
builder.build()
});
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use bevy_tasks::prelude::{AsyncComputeTaskPool, ComputeTaskPool, IoTaskPool};
#[test]
fn runs_spawn_local_tasks() {
let mut app = App::new();
app.add_plugins(TaskPoolPlugin::default());
let (async_tx, async_rx) = crossbeam_channel::unbounded();
AsyncComputeTaskPool::get()
.spawn_local(async move {
async_tx.send(()).unwrap();
})
.detach();
let (compute_tx, compute_rx) = crossbeam_channel::unbounded();
ComputeTaskPool::get()
.spawn_local(async move {
compute_tx.send(()).unwrap();
})
.detach();
let (io_tx, io_rx) = crossbeam_channel::unbounded();
IoTaskPool::get()
.spawn_local(async move {
io_tx.send(()).unwrap();
})
.detach();
app.run();
async_rx.try_recv().unwrap();
compute_rx.try_recv().unwrap();
io_rx.try_recv().unwrap();
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_app/src/panic_handler.rs | crates/bevy_app/src/panic_handler.rs | //! This module provides panic handlers for [Bevy](https://bevy.org)
//! apps, and automatically configures platform specifics (i.e. Wasm or Android).
//!
//! By default, the [`PanicHandlerPlugin`] from this crate is included in Bevy's `DefaultPlugins`.
//!
//! For more fine-tuned control over panic behavior, disable the [`PanicHandlerPlugin`] or
//! `DefaultPlugins` during app initialization.
use crate::{App, Plugin};
/// Adds sensible panic handlers to Apps. This plugin is part of the `DefaultPlugins`. Adding
/// this plugin will setup a panic hook appropriate to your target platform:
/// * On Wasm, uses [`console_error_panic_hook`](https://crates.io/crates/console_error_panic_hook), logging
/// to the browser console.
/// * Other platforms are currently not setup.
///
/// ```no_run
/// # use bevy_app::{App, NoopPluginGroup as MinimalPlugins, PluginGroup, PanicHandlerPlugin};
/// fn main() {
/// App::new()
/// .add_plugins(MinimalPlugins)
/// .add_plugins(PanicHandlerPlugin)
/// .run();
/// }
/// ```
///
/// If you want to setup your own panic handler, you should disable this
/// plugin from `DefaultPlugins`:
/// ```no_run
/// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup, PanicHandlerPlugin};
/// fn main() {
/// App::new()
/// .add_plugins(DefaultPlugins.build().disable::<PanicHandlerPlugin>())
/// .run();
/// }
/// ```
#[derive(Default)]
pub struct PanicHandlerPlugin;
impl Plugin for PanicHandlerPlugin {
fn build(&self, _app: &mut App) {
#[cfg(feature = "std")]
{
static SET_HOOK: std::sync::Once = std::sync::Once::new();
SET_HOOK.call_once(|| {
cfg_if::cfg_if! {
if #[cfg(all(target_arch = "wasm32", feature = "web"))] {
// This provides better panic handling in JS engines (displays the panic message and improves the backtrace).
std::panic::set_hook(alloc::boxed::Box::new(console_error_panic_hook::hook));
} else if #[cfg(feature = "error_panic_hook")] {
let current_hook = std::panic::take_hook();
std::panic::set_hook(alloc::boxed::Box::new(
bevy_ecs::error::bevy_error_panic_hook(current_hook),
));
}
// Otherwise use the default target panic hook - Do nothing.
}
});
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_app/src/hotpatch.rs | crates/bevy_app/src/hotpatch.rs | //! Utilities for hotpatching code.
extern crate alloc;
use alloc::sync::Arc;
#[cfg(feature = "reflect_auto_register")]
use bevy_ecs::schedule::IntoScheduleConfigs;
use bevy_ecs::{
change_detection::DetectChangesMut, message::MessageWriter, system::ResMut, HotPatchChanges,
HotPatched,
};
#[cfg(not(target_family = "wasm"))]
use dioxus_devtools::connect_subsecond;
use dioxus_devtools::subsecond;
pub use dioxus_devtools::subsecond::{call, HotFunction};
use crate::{Last, Plugin};
/// Plugin connecting to Dioxus CLI to enable hot patching.
#[derive(Default)]
pub struct HotPatchPlugin;
impl Plugin for HotPatchPlugin {
fn build(&self, app: &mut crate::App) {
let (sender, receiver) = crossbeam_channel::bounded::<HotPatched>(1);
// Connects to the dioxus CLI that will handle rebuilds
// This will open a connection to the dioxus CLI to receive updated jump tables
// Sends a `HotPatched` message through the channel when the jump table is updated
#[cfg(not(target_family = "wasm"))]
connect_subsecond();
subsecond::register_handler(Arc::new(move || {
sender.send(HotPatched).unwrap();
}));
// Adds a system that will read the channel for new `HotPatched` messages, send the message, and update change detection.
app.init_resource::<HotPatchChanges>()
.add_message::<HotPatched>()
.add_systems(
Last,
move |mut hot_patched_writer: MessageWriter<HotPatched>,
mut res: ResMut<HotPatchChanges>| {
if receiver.try_recv().is_ok() {
hot_patched_writer.write_default();
res.set_changed();
}
},
);
#[cfg(feature = "reflect_auto_register")]
app.add_systems(
crate::First,
(move |registry: bevy_ecs::system::Res<bevy_ecs::reflect::AppTypeRegistry>| {
registry.write().register_derived_types();
})
.run_if(bevy_ecs::schedule::common_conditions::on_message::<HotPatched>),
);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_app/src/propagate.rs | crates/bevy_app/src/propagate.rs | use alloc::vec::Vec;
use core::marker::PhantomData;
use crate::{App, Plugin};
#[cfg(feature = "bevy_reflect")]
use bevy_ecs::reflect::ReflectComponent;
use bevy_ecs::{
change_detection::DetectChangesMut,
component::Component,
entity::Entity,
hierarchy::ChildOf,
intern::Interned,
lifecycle::RemovedComponents,
query::{Changed, Or, QueryFilter, With, Without},
relationship::{Relationship, RelationshipTarget},
schedule::{IntoScheduleConfigs, ScheduleLabel, SystemSet},
system::{Commands, Local, Query},
};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
/// Plugin to automatically propagate a component value to all direct and transient relationship
/// targets (e.g. [`bevy_ecs::hierarchy::Children`]) of entities with a [`Propagate`] component.
///
/// The plugin Will maintain the target component over hierarchy changes, adding or removing
/// `C` when a relationship `R` (e.g. [`ChildOf`]) is added to or removed from a
/// relationship tree with a [`Propagate<C>`] source, or if the [`Propagate<C>`] component
/// is added, changed or removed.
///
/// Optionally you can include a query filter `F` to restrict the entities that are updated.
/// Note that the filter is not rechecked dynamically: changes to the filter state will not be
/// picked up until the [`Propagate`] component is touched, or the hierarchy is changed.
/// All members of the tree between source and target must match the filter for propagation
/// to reach a given target.
/// Individual entities can be skipped or terminate the propagation with the [`PropagateOver`]
/// and [`PropagateStop`] components.
///
/// The schedule can be configured via [`HierarchyPropagatePlugin::new`].
/// You should be sure to schedule your logic relative to this set: making changes
/// that modify component values before this logic, and reading the propagated
/// values after it.
pub struct HierarchyPropagatePlugin<
C: Component + Clone + PartialEq,
F: QueryFilter = (),
R: Relationship = ChildOf,
> {
schedule: Interned<dyn ScheduleLabel>,
_marker: PhantomData<fn() -> (C, F, R)>,
}
impl<C: Component + Clone + PartialEq, F: QueryFilter, R: Relationship>
HierarchyPropagatePlugin<C, F, R>
{
/// Construct the plugin. The propagation systems will be placed in the specified schedule.
pub fn new(schedule: impl ScheduleLabel) -> Self {
Self {
schedule: schedule.intern(),
_marker: PhantomData,
}
}
}
/// Causes the inner component to be added to this entity and all direct and transient relationship
/// targets. A target with a [`Propagate<C>`] component of its own will override propagation from
/// that point in the tree.
#[derive(Component, Clone, PartialEq)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Component, Clone, PartialEq)
)]
pub struct Propagate<C: Component + Clone + PartialEq>(pub C);
/// Stops the output component being added to this entity.
/// Relationship targets will still inherit the component from this entity or its parents.
#[derive(Component)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Component))]
pub struct PropagateOver<C>(PhantomData<fn() -> C>);
/// Stops the propagation at this entity. Children will not inherit the component.
#[derive(Component)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Component))]
pub struct PropagateStop<C>(PhantomData<fn() -> C>);
/// The set in which propagation systems are added. You can schedule your logic relative to this set.
#[derive(SystemSet, Clone, PartialEq, PartialOrd, Ord)]
pub struct PropagateSet<C: Component + Clone + PartialEq> {
_p: PhantomData<fn() -> C>,
}
/// Internal struct for managing propagation
#[derive(Component, Clone, PartialEq, Debug)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Component, Clone, PartialEq)
)]
pub struct Inherited<C: Component + Clone + PartialEq>(pub C);
impl<C> Default for PropagateOver<C> {
fn default() -> Self {
Self(Default::default())
}
}
impl<C> Default for PropagateStop<C> {
fn default() -> Self {
Self(Default::default())
}
}
impl<C: Component + Clone + PartialEq> core::fmt::Debug for PropagateSet<C> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("PropagateSet")
.field("_p", &self._p)
.finish()
}
}
impl<C: Component + Clone + PartialEq> Eq for PropagateSet<C> {}
impl<C: Component + Clone + PartialEq> core::hash::Hash for PropagateSet<C> {
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self._p.hash(state);
}
}
impl<C: Component + Clone + PartialEq> Default for PropagateSet<C> {
fn default() -> Self {
Self {
_p: Default::default(),
}
}
}
impl<C: Component + Clone + PartialEq, F: QueryFilter + 'static, R: Relationship> Plugin
for HierarchyPropagatePlugin<C, F, R>
{
fn build(&self, app: &mut App) {
app.add_systems(
self.schedule,
(
update_source::<C, F, R>,
update_reparented::<C, F, R>,
update_removed_limit::<C, F, R>,
propagate_inherited::<C, F, R>,
propagate_output::<C, F>,
)
.chain()
.in_set(PropagateSet::<C>::default()),
);
}
}
/// add/remove `Inherited::<C>` for entities with a direct `Propagate::<C>`
pub fn update_source<C: Component + Clone + PartialEq, F: QueryFilter, R: Relationship>(
mut commands: Commands,
changed: Query<(Entity, &Propagate<C>), (Or<(Changed<Propagate<C>>, Without<Inherited<C>>)>,)>,
mut removed: RemovedComponents<Propagate<C>>,
relationship: Query<&R>,
relations: Query<&Inherited<C>, Without<PropagateStop<C>>>,
) {
for (entity, source) in &changed {
commands
.entity(entity)
.try_insert(Inherited(source.0.clone()));
}
// set `Inherited::<C>` based on ancestry when `Propagate::<C>` is removed
for removed in removed.read() {
if let Ok(mut commands) = commands.get_entity(removed) {
if let Some(inherited) = relationship
.get(removed)
.ok()
.and_then(|r| relations.get(r.get()).ok())
{
commands.insert(inherited.clone());
} else {
commands.try_remove::<Inherited<C>>();
}
}
}
}
/// add/remove `Inherited::<C>` for entities which have changed relationship
pub fn update_reparented<C: Component + Clone + PartialEq, F: QueryFilter, R: Relationship>(
mut commands: Commands,
moved: Query<(Entity, &R, Option<&Inherited<C>>), (Changed<R>, Without<Propagate<C>>, F)>,
relations: Query<&Inherited<C>, Without<PropagateStop<C>>>,
orphaned: Query<Entity, (With<Inherited<C>>, Without<Propagate<C>>, Without<R>, F)>,
) {
for (entity, relation, maybe_inherited) in &moved {
if let Ok(inherited) = relations.get(relation.get()) {
commands.entity(entity).try_insert(inherited.clone());
} else if maybe_inherited.is_some() {
commands.entity(entity).try_remove::<Inherited<C>>();
}
}
for orphan in &orphaned {
commands.entity(orphan).try_remove::<Inherited<C>>();
}
}
/// When `PropagateOver` or `PropagateStop` is removed, update the `Inherited::<C>` to trigger propagation
pub fn update_removed_limit<C: Component + Clone + PartialEq, F: QueryFilter, R: Relationship>(
mut inherited: Query<&mut Inherited<C>>,
mut removed_skip: RemovedComponents<PropagateOver<C>>,
mut removed_stop: RemovedComponents<PropagateStop<C>>,
) {
for entity in removed_skip.read() {
if let Ok(mut inherited) = inherited.get_mut(entity) {
inherited.set_changed();
}
}
for entity in removed_stop.read() {
if let Ok(mut inherited) = inherited.get_mut(entity) {
inherited.set_changed();
}
}
}
/// add/remove `Inherited::<C>` for targets of entities with modified `Inherited::<C>`
pub fn propagate_inherited<C: Component + Clone + PartialEq, F: QueryFilter, R: Relationship>(
mut commands: Commands,
changed: Query<
(&Inherited<C>, &R::RelationshipTarget),
(Changed<Inherited<C>>, Without<PropagateStop<C>>, F),
>,
recurse: Query<
(
Option<&R::RelationshipTarget>,
Option<&Inherited<C>>,
Option<&PropagateStop<C>>,
),
(Without<Propagate<C>>, F),
>,
mut removed: RemovedComponents<Inherited<C>>,
mut to_process: Local<Vec<(Entity, Option<Inherited<C>>)>>,
) {
// gather changed
for (inherited, targets) in &changed {
to_process.extend(
targets
.iter()
.map(|target| (target, Some(inherited.clone()))),
);
}
// and removed
for entity in removed.read() {
if let Ok((Some(targets), _, _)) = recurse.get(entity) {
to_process.extend(targets.iter().map(|target| (target, None)));
}
}
// propagate
while let Some((entity, maybe_inherited)) = (*to_process).pop() {
let Ok((maybe_targets, maybe_current, maybe_stop)) = recurse.get(entity) else {
continue;
};
if maybe_current == maybe_inherited.as_ref() {
continue;
}
// update children if required
if maybe_stop.is_none()
&& let Some(targets) = maybe_targets
{
to_process.extend(
targets
.iter()
.map(|target| (target, maybe_inherited.clone())),
);
}
// update this node's `Inherited<C>`
if let Some(inherited) = maybe_inherited {
commands.entity(entity).try_insert(inherited);
} else {
commands.entity(entity).try_remove::<Inherited<C>>();
}
}
}
/// add/remove `C` on entities with `Inherited::<C>`
pub fn propagate_output<C: Component + Clone + PartialEq, F: QueryFilter>(
mut commands: Commands,
changed: Query<
(Entity, &Inherited<C>, Option<&C>),
(Changed<Inherited<C>>, Without<PropagateOver<C>>, F),
>,
mut removed: RemovedComponents<Inherited<C>>,
skip: Query<(), With<PropagateOver<C>>>,
) {
for (entity, inherited, maybe_current) in &changed {
if maybe_current.is_some_and(|c| &inherited.0 == c) {
continue;
}
commands.entity(entity).try_insert(inherited.0.clone());
}
for removed in removed.read() {
if skip.get(removed).is_err() {
commands.entity(removed).try_remove::<C>();
}
}
}
#[cfg(test)]
mod tests {
use bevy_ecs::schedule::Schedule;
use crate::{App, Update};
use super::*;
#[derive(Component, Clone, PartialEq, Debug)]
struct TestValue(u32);
#[test]
fn test_simple_propagate() {
let mut app = App::new();
app.add_schedule(Schedule::new(Update));
app.add_plugins(HierarchyPropagatePlugin::<TestValue>::new(Update));
let mut query = app.world_mut().query::<&TestValue>();
let propagator = app.world_mut().spawn(Propagate(TestValue(1))).id();
let intermediate = app
.world_mut()
.spawn_empty()
.insert(ChildOf(propagator))
.id();
let propagatee = app
.world_mut()
.spawn_empty()
.insert(ChildOf(intermediate))
.id();
app.update();
assert_eq!(
query.get_many(app.world(), [propagator, intermediate, propagatee]),
Ok([&TestValue(1), &TestValue(1), &TestValue(1)])
);
}
#[test]
fn test_remove_propagate() {
let mut app = App::new();
app.add_schedule(Schedule::new(Update));
app.add_plugins(HierarchyPropagatePlugin::<TestValue>::new(Update));
let mut query = app.world_mut().query::<&TestValue>();
let propagator = app.world_mut().spawn(Propagate(TestValue(1))).id();
let propagatee = app
.world_mut()
.spawn_empty()
.insert(ChildOf(propagator))
.id();
app.update();
assert_eq!(query.get(app.world(), propagatee), Ok(&TestValue(1)));
app.world_mut()
.commands()
.entity(propagator)
.remove::<Propagate<TestValue>>();
app.update();
assert!(query.get(app.world(), propagator).is_err());
assert!(query.get(app.world(), propagatee).is_err());
}
#[test]
fn test_remove_orphan() {
let mut app = App::new();
app.add_schedule(Schedule::new(Update));
app.add_plugins(HierarchyPropagatePlugin::<TestValue>::new(Update));
let mut query = app.world_mut().query::<&TestValue>();
let propagator = app.world_mut().spawn(Propagate(TestValue(1))).id();
let propagatee = app
.world_mut()
.spawn_empty()
.insert(ChildOf(propagator))
.id();
app.update();
assert_eq!(query.get(app.world(), propagatee), Ok(&TestValue(1)));
app.world_mut()
.commands()
.entity(propagatee)
.remove::<ChildOf>();
app.update();
assert!(query.get(app.world(), propagatee).is_err());
}
#[test]
fn test_reparented() {
let mut app = App::new();
app.add_schedule(Schedule::new(Update));
app.add_plugins(HierarchyPropagatePlugin::<TestValue>::new(Update));
let mut query = app.world_mut().query::<&TestValue>();
let propagator_one = app.world_mut().spawn(Propagate(TestValue(1))).id();
let other_parent = app.world_mut().spawn_empty().id();
let propagatee = app
.world_mut()
.spawn_empty()
.insert(ChildOf(propagator_one))
.id();
app.update();
assert_eq!(query.get(app.world(), propagatee), Ok(&TestValue(1)));
app.world_mut()
.commands()
.entity(propagatee)
.insert(ChildOf(other_parent));
app.update();
assert!(query.get(app.world(), propagatee).is_err());
}
#[test]
fn test_reparented_with_prior() {
let mut app = App::new();
app.add_schedule(Schedule::new(Update));
app.add_plugins(HierarchyPropagatePlugin::<TestValue>::new(Update));
let mut query = app.world_mut().query::<&TestValue>();
let propagator_a = app.world_mut().spawn(Propagate(TestValue(1))).id();
let propagator_b = app.world_mut().spawn(Propagate(TestValue(2))).id();
let propagatee = app
.world_mut()
.spawn_empty()
.insert(ChildOf(propagator_a))
.id();
app.update();
assert_eq!(query.get(app.world(), propagatee), Ok(&TestValue(1)));
app.world_mut()
.commands()
.entity(propagatee)
.insert(ChildOf(propagator_b));
app.update();
assert_eq!(query.get(app.world(), propagatee), Ok(&TestValue(2)));
}
#[test]
fn test_propagate_over() {
let mut app = App::new();
app.add_schedule(Schedule::new(Update));
app.add_plugins(HierarchyPropagatePlugin::<TestValue>::new(Update));
let mut query = app.world_mut().query::<&TestValue>();
let propagator = app.world_mut().spawn(Propagate(TestValue(1))).id();
let propagate_over = app
.world_mut()
.spawn(TestValue(2))
.insert((PropagateOver::<TestValue>::default(), ChildOf(propagator)))
.id();
let propagatee = app
.world_mut()
.spawn_empty()
.insert(ChildOf(propagate_over))
.id();
app.update();
assert_eq!(query.get(app.world(), propagate_over), Ok(&TestValue(2)));
assert_eq!(query.get(app.world(), propagatee), Ok(&TestValue(1)));
}
#[test]
fn test_remove_propagate_over() {
let mut app = App::new();
app.add_schedule(Schedule::new(Update));
app.add_plugins(HierarchyPropagatePlugin::<TestValue>::new(Update));
let mut query = app.world_mut().query::<&TestValue>();
let propagator = app.world_mut().spawn(Propagate(TestValue(1))).id();
let propagate_over = app
.world_mut()
.spawn(TestValue(2))
.insert((PropagateOver::<TestValue>::default(), ChildOf(propagator)))
.id();
let propagatee = app
.world_mut()
.spawn_empty()
.insert(ChildOf(propagate_over))
.id();
app.update();
assert_eq!(
app.world_mut()
.query::<&Inherited<TestValue>>()
.get(app.world(), propagate_over),
Ok(&Inherited(TestValue(1)))
);
assert_eq!(
app.world_mut()
.query::<&Inherited<TestValue>>()
.get(app.world(), propagatee),
Ok(&Inherited(TestValue(1)))
);
assert_eq!(
query.get_many(app.world(), [propagate_over, propagatee]),
Ok([&TestValue(2), &TestValue(1)])
);
app.world_mut()
.commands()
.entity(propagate_over)
.remove::<PropagateOver<TestValue>>();
app.update();
assert_eq!(
query.get_many(app.world(), [propagate_over, propagatee]),
Ok([&TestValue(1), &TestValue(1)])
);
}
#[test]
fn test_propagate_over_parent_removed() {
let mut app = App::new();
app.add_schedule(Schedule::new(Update));
app.add_plugins(HierarchyPropagatePlugin::<TestValue>::new(Update));
let mut query = app.world_mut().query::<&TestValue>();
let propagator = app.world_mut().spawn(Propagate(TestValue(1))).id();
let propagate_over = app
.world_mut()
.spawn(TestValue(2))
.insert((PropagateOver::<TestValue>::default(), ChildOf(propagator)))
.id();
app.update();
assert_eq!(
query.get_many(app.world(), [propagator, propagate_over]),
Ok([&TestValue(1), &TestValue(2)])
);
app.world_mut()
.commands()
.entity(propagator)
.remove::<Propagate<TestValue>>();
app.update();
assert!(query.get(app.world(), propagator).is_err(),);
assert_eq!(query.get(app.world(), propagate_over), Ok(&TestValue(2)));
}
#[test]
fn test_orphaned_propagate_over() {
let mut app = App::new();
app.add_schedule(Schedule::new(Update));
app.add_plugins(HierarchyPropagatePlugin::<TestValue>::new(Update));
let mut query = app.world_mut().query::<&TestValue>();
let propagator = app.world_mut().spawn(Propagate(TestValue(1))).id();
let propagate_over = app
.world_mut()
.spawn(TestValue(2))
.insert((PropagateOver::<TestValue>::default(), ChildOf(propagator)))
.id();
let propagatee = app
.world_mut()
.spawn_empty()
.insert(ChildOf(propagate_over))
.id();
app.update();
assert_eq!(
query.get_many(app.world(), [propagate_over, propagatee]),
Ok([&TestValue(2), &TestValue(1)])
);
app.world_mut()
.commands()
.entity(propagate_over)
.remove::<ChildOf>();
app.update();
assert_eq!(query.get(app.world(), propagate_over), Ok(&TestValue(2)));
assert!(query.get(app.world(), propagatee).is_err());
}
#[test]
fn test_propagate_stop() {
let mut app = App::new();
app.add_schedule(Schedule::new(Update));
app.add_plugins(HierarchyPropagatePlugin::<TestValue>::new(Update));
let mut query = app.world_mut().query::<&TestValue>();
let propagator = app.world_mut().spawn(Propagate(TestValue(1))).id();
let propagate_stop = app
.world_mut()
.spawn(PropagateStop::<TestValue>::default())
.insert(ChildOf(propagator))
.id();
let no_propagatee = app
.world_mut()
.spawn_empty()
.insert(ChildOf(propagate_stop))
.id();
app.update();
assert_eq!(query.get(app.world(), propagate_stop), Ok(&TestValue(1)));
assert!(query.get(app.world(), no_propagatee).is_err());
}
#[test]
fn test_remove_propagate_stop() {
let mut app = App::new();
app.add_schedule(Schedule::new(Update));
app.add_plugins(HierarchyPropagatePlugin::<TestValue>::new(Update));
let mut query = app.world_mut().query::<&TestValue>();
let propagator = app.world_mut().spawn(Propagate(TestValue(1))).id();
let propagate_stop = app
.world_mut()
.spawn(PropagateStop::<TestValue>::default())
.insert(ChildOf(propagator))
.id();
let no_propagatee = app
.world_mut()
.spawn_empty()
.insert(ChildOf(propagate_stop))
.id();
app.update();
assert_eq!(query.get(app.world(), propagate_stop), Ok(&TestValue(1)));
assert!(query.get(app.world(), no_propagatee).is_err());
app.world_mut()
.commands()
.entity(propagate_stop)
.remove::<PropagateStop<TestValue>>();
app.update();
assert_eq!(
query.get_many(app.world(), [propagate_stop, no_propagatee]),
Ok([&TestValue(1), &TestValue(1)])
);
}
#[test]
fn test_intermediate_override() {
let mut app = App::new();
app.add_schedule(Schedule::new(Update));
app.add_plugins(HierarchyPropagatePlugin::<TestValue>::new(Update));
let mut query = app.world_mut().query::<&TestValue>();
let propagator = app.world_mut().spawn(Propagate(TestValue(1))).id();
let intermediate = app
.world_mut()
.spawn_empty()
.insert(ChildOf(propagator))
.id();
let propagatee = app
.world_mut()
.spawn_empty()
.insert(ChildOf(intermediate))
.id();
app.update();
assert_eq!(
query.get_many(app.world(), [propagator, intermediate, propagatee]),
Ok([&TestValue(1), &TestValue(1), &TestValue(1)])
);
app.world_mut()
.entity_mut(intermediate)
.insert(Propagate(TestValue(2)));
app.update();
assert_eq!(
app.world_mut()
.query::<&TestValue>()
.get_many(app.world(), [propagator, intermediate, propagatee]),
Ok([&TestValue(1), &TestValue(2), &TestValue(2)])
);
}
#[test]
fn test_filter() {
#[derive(Component)]
struct Marker;
let mut app = App::new();
app.add_schedule(Schedule::new(Update));
app.add_plugins(HierarchyPropagatePlugin::<TestValue, With<Marker>>::new(
Update,
));
let mut query = app.world_mut().query::<&TestValue>();
let propagator = app.world_mut().spawn(Propagate(TestValue(1))).id();
let propagatee = app
.world_mut()
.spawn_empty()
.insert(ChildOf(propagator))
.id();
app.update();
assert!(query.get(app.world(), propagator).is_err());
assert!(query.get(app.world(), propagatee).is_err());
// NOTE: changes to the filter condition are not rechecked
app.world_mut().entity_mut(propagator).insert(Marker);
app.update();
assert!(query.get(app.world(), propagator).is_err());
assert!(query.get(app.world(), propagatee).is_err());
app.world_mut()
.entity_mut(propagator)
.insert(Propagate(TestValue(1)));
app.update();
assert_eq!(query.get(app.world(), propagator), Ok(&TestValue(1)));
assert!(query.get(app.world(), propagatee).is_err());
app.world_mut().entity_mut(propagatee).insert(Marker);
app.update();
assert_eq!(query.get(app.world(), propagator), Ok(&TestValue(1)));
assert!(query.get(app.world(), propagatee).is_err());
app.world_mut()
.entity_mut(propagator)
.insert(Propagate(TestValue(1)));
app.update();
assert_eq!(
app.world_mut()
.query::<&TestValue>()
.get_many(app.world(), [propagator, propagatee]),
Ok([&TestValue(1), &TestValue(1)])
);
}
#[test]
fn test_removed_propagate_still_inherits() {
let mut app = App::new();
app.add_schedule(Schedule::new(Update));
app.add_plugins(HierarchyPropagatePlugin::<TestValue>::new(Update));
let mut query = app.world_mut().query::<&TestValue>();
let propagator = app.world_mut().spawn(Propagate(TestValue(1))).id();
let propagatee = app
.world_mut()
.spawn(Propagate(TestValue(2)))
.insert(ChildOf(propagator))
.id();
app.update();
assert_eq!(
query.get_many(app.world(), [propagator, propagatee]),
Ok([&TestValue(1), &TestValue(2)])
);
app.world_mut()
.commands()
.entity(propagatee)
.remove::<Propagate<TestValue>>();
app.update();
assert_eq!(
query.get_many(app.world(), [propagator, propagatee]),
Ok([&TestValue(1), &TestValue(1)])
);
}
#[test]
fn test_reparent_respects_stop() {
let mut app = App::new();
app.add_schedule(Schedule::new(Update));
app.add_plugins(HierarchyPropagatePlugin::<TestValue>::new(Update));
let mut query = app.world_mut().query::<&TestValue>();
let propagator = app
.world_mut()
.spawn((
Propagate(TestValue(1)),
PropagateStop::<TestValue>::default(),
))
.id();
let propagatee = app.world_mut().spawn(TestValue(2)).id();
app.update();
assert_eq!(
query.get_many(app.world(), [propagator, propagatee]),
Ok([&TestValue(1), &TestValue(2)])
);
app.world_mut()
.commands()
.entity(propagatee)
.insert(ChildOf(propagator));
app.update();
assert_eq!(
query.get_many(app.world(), [propagator, propagatee]),
Ok([&TestValue(1), &TestValue(2)])
);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_app/src/plugin.rs | crates/bevy_app/src/plugin.rs | use crate::App;
use core::any::Any;
use downcast_rs::{impl_downcast, Downcast};
/// A collection of Bevy app logic and configuration.
///
/// Plugins configure an [`App`]. When an [`App`] registers a plugin,
/// the plugin's [`Plugin::build`] function is run. By default, a plugin
/// can only be added once to an [`App`].
///
/// If the plugin may need to be added twice or more, the function [`is_unique()`](Self::is_unique)
/// should be overridden to return `false`. Plugins are considered duplicate if they have the same
/// [`name()`](Self::name). The default `name()` implementation returns the type name, which means
/// generic plugins with different type parameters will not be considered duplicates.
///
/// ## Lifecycle of a plugin
///
/// When adding a plugin to an [`App`]:
/// * the app calls [`Plugin::build`] immediately, and register the plugin
/// * once the app started, it will wait for all registered [`Plugin::ready`] to return `true`
/// * it will then call all registered [`Plugin::finish`]
/// * and call all registered [`Plugin::cleanup`]
///
/// ## Defining a plugin.
///
/// Most plugins are simply functions that add configuration to an [`App`].
///
/// ```
/// # use bevy_app::{App, Update};
/// App::new().add_plugins(my_plugin).run();
///
/// // This function implements `Plugin`, along with every other `fn(&mut App)`.
/// pub fn my_plugin(app: &mut App) {
/// app.add_systems(Update, hello_world);
/// }
/// # fn hello_world() {}
/// ```
///
/// For more advanced use cases, the `Plugin` trait can be implemented manually for a type.
///
/// ```
/// # use bevy_app::*;
/// pub struct AccessibilityPlugin {
/// pub flicker_damping: bool,
/// // ...
/// }
///
/// impl Plugin for AccessibilityPlugin {
/// fn build(&self, app: &mut App) {
/// if self.flicker_damping {
/// app.add_systems(PostUpdate, damp_flickering);
/// }
/// }
/// }
/// # fn damp_flickering() {}
/// ```
pub trait Plugin: Downcast + Any + Send + Sync {
/// Configures the [`App`] to which this plugin is added.
fn build(&self, app: &mut App);
/// Has the plugin finished its setup? This can be useful for plugins that need something
/// asynchronous to happen before they can finish their setup, like the initialization of a renderer.
/// Once the plugin is ready, [`finish`](Plugin::finish) should be called.
fn ready(&self, _app: &App) -> bool {
true
}
/// Finish adding this plugin to the [`App`], once all plugins registered are ready. This can
/// be useful for plugins that depends on another plugin asynchronous setup, like the renderer.
fn finish(&self, _app: &mut App) {
// do nothing
}
/// Runs after all plugins are built and finished, but before the app schedule is executed.
/// This can be useful if you have some resource that other plugins need during their build step,
/// but after build you want to remove it and send it to another thread.
fn cleanup(&self, _app: &mut App) {
// do nothing
}
/// Configures a name for the [`Plugin`] which is primarily used for checking plugin
/// uniqueness and debugging.
fn name(&self) -> &str {
core::any::type_name::<Self>()
}
/// If the plugin can be meaningfully instantiated several times in an [`App`],
/// override this method to return `false`.
fn is_unique(&self) -> bool {
true
}
}
impl_downcast!(Plugin);
impl<T: Fn(&mut App) + Send + Sync + 'static> Plugin for T {
fn build(&self, app: &mut App) {
self(app);
}
}
/// Plugins state in the application
#[derive(PartialEq, Eq, Debug, Clone, Copy, PartialOrd, Ord)]
pub enum PluginsState {
/// Plugins are being added.
Adding,
/// All plugins already added are ready.
Ready,
/// Finish has been executed for all plugins added.
Finished,
/// Cleanup has been executed for all plugins added.
Cleaned,
}
/// A dummy plugin that's to temporarily occupy an entry in an app's plugin registry.
pub(crate) struct PlaceholderPlugin;
impl Plugin for PlaceholderPlugin {
fn build(&self, _app: &mut App) {}
}
/// Types that represent a set of [`Plugin`]s.
///
/// This is implemented for all types which implement [`Plugin`],
/// [`PluginGroup`](super::PluginGroup), and tuples over [`Plugins`].
pub trait Plugins<Marker>: sealed::Plugins<Marker> {}
impl<Marker, T> Plugins<Marker> for T where T: sealed::Plugins<Marker> {}
mod sealed {
use alloc::boxed::Box;
use variadics_please::all_tuples;
use crate::{App, AppError, Plugin, PluginGroup};
pub trait Plugins<Marker> {
fn add_to_app(self, app: &mut App);
}
pub struct PluginMarker;
pub struct PluginGroupMarker;
pub struct PluginsTupleMarker;
impl<P: Plugin> Plugins<PluginMarker> for P {
#[track_caller]
fn add_to_app(self, app: &mut App) {
if let Err(AppError::DuplicatePlugin { plugin_name }) =
app.add_boxed_plugin(Box::new(self))
{
panic!(
"Error adding plugin {plugin_name}: : plugin was already added in application"
)
}
}
}
impl<P: PluginGroup> Plugins<PluginGroupMarker> for P {
#[track_caller]
fn add_to_app(self, app: &mut App) {
self.build().finish(app);
}
}
macro_rules! impl_plugins_tuples {
($(#[$meta:meta])* $(($param: ident, $plugins: ident)),*) => {
$(#[$meta])*
impl<$($param, $plugins),*> Plugins<(PluginsTupleMarker, $($param,)*)> for ($($plugins,)*)
where
$($plugins: Plugins<$param>),*
{
#[expect(
clippy::allow_attributes,
reason = "This is inside a macro, and as such, may not trigger in all cases."
)]
#[allow(non_snake_case, reason = "`all_tuples!()` generates non-snake-case variable names.")]
#[allow(unused_variables, reason = "`app` is unused when implemented for the unit type `()`.")]
#[track_caller]
fn add_to_app(self, app: &mut App) {
let ($($plugins,)*) = self;
$($plugins.add_to_app(app);)*
}
}
}
}
all_tuples!(
#[doc(fake_variadic)]
impl_plugins_tuples,
0,
15,
P,
S
);
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_audio/src/lib.rs | crates/bevy_audio/src/lib.rs | #![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"
)]
//! Audio support for the game engine Bevy
//!
//! ```no_run
//! # use bevy_ecs::prelude::*;
//! # use bevy_audio::{AudioPlayer, AudioPlugin, AudioSource, PlaybackSettings};
//! # use bevy_asset::{AssetPlugin, AssetServer};
//! # use bevy_app::{App, AppExit, NoopPluginGroup as MinimalPlugins, Startup};
//! fn main() {
//! App::new()
//! .add_plugins((MinimalPlugins, AssetPlugin::default(), AudioPlugin::default()))
//! .add_systems(Startup, play_background_audio)
//! .run();
//! }
//!
//! fn play_background_audio(asset_server: Res<AssetServer>, mut commands: Commands) {
//! commands.spawn((
//! AudioPlayer::new(asset_server.load("background_audio.ogg")),
//! PlaybackSettings::LOOP,
//! ));
//! }
//! ```
extern crate alloc;
mod audio;
mod audio_output;
mod audio_source;
mod pitch;
mod sinks;
mod volume;
/// The audio prelude.
///
/// This includes the most common types in this crate, re-exported for your convenience.
pub mod prelude {
#[doc(hidden)]
pub use crate::{
AudioPlayer, AudioSink, AudioSinkPlayback, AudioSource, Decodable, GlobalVolume, Pitch,
PlaybackSettings, SpatialAudioSink, SpatialListener,
};
}
pub use audio::*;
pub use audio_source::*;
pub use pitch::*;
pub use volume::*;
pub use rodio::{cpal::Sample as CpalSample, source::Source, Sample};
pub use sinks::*;
use bevy_app::prelude::*;
use bevy_asset::{Asset, AssetApp};
use bevy_ecs::prelude::*;
use bevy_transform::TransformSystems;
use audio_output::*;
/// Set for the audio playback systems, so they can share a run condition
#[derive(SystemSet, Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
struct AudioPlaybackSystems;
/// Adds support for audio playback to a Bevy Application
///
/// Insert an [`AudioPlayer`] onto your entities to play audio.
#[derive(Default)]
pub struct AudioPlugin {
/// The global volume for all audio entities.
pub global_volume: GlobalVolume,
/// The scale factor applied to the positions of audio sources and listeners for
/// spatial audio.
pub default_spatial_scale: SpatialScale,
}
impl Plugin for AudioPlugin {
fn build(&self, app: &mut App) {
app.insert_resource(self.global_volume)
.insert_resource(DefaultSpatialScale(self.default_spatial_scale))
.configure_sets(
PostUpdate,
AudioPlaybackSystems
.run_if(audio_output_available)
.after(TransformSystems::Propagate), // For spatial audio transforms
)
.add_systems(
PostUpdate,
(update_emitter_positions, update_listener_positions).in_set(AudioPlaybackSystems),
)
.init_resource::<AudioOutput>();
#[cfg(any(feature = "mp3", feature = "flac", feature = "wav", feature = "vorbis"))]
{
app.add_audio_source::<AudioSource>();
app.init_asset_loader::<AudioLoader>();
}
app.add_audio_source::<Pitch>();
}
}
impl AddAudioSource for App {
fn add_audio_source<T>(&mut self) -> &mut Self
where
T: Decodable + Asset,
f32: rodio::cpal::FromSample<T::DecoderItem>,
{
self.init_asset::<T>().add_systems(
PostUpdate,
(play_queued_audio_system::<T>, cleanup_finished_audio::<T>)
.in_set(AudioPlaybackSystems),
);
self
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_audio/src/pitch.rs | crates/bevy_audio/src/pitch.rs | use crate::Decodable;
use bevy_asset::Asset;
use bevy_reflect::TypePath;
use rodio::{
source::{SineWave, TakeDuration},
Source,
};
/// A source of sine wave sound
#[derive(Asset, Debug, Clone, TypePath)]
pub struct Pitch {
/// Frequency at which sound will be played
pub frequency: f32,
/// Duration for which sound will be played
pub duration: core::time::Duration,
}
impl Pitch {
/// Creates a new note
pub fn new(frequency: f32, duration: core::time::Duration) -> Self {
Pitch {
frequency,
duration,
}
}
}
impl Decodable for Pitch {
type DecoderItem = <SineWave as Iterator>::Item;
type Decoder = TakeDuration<SineWave>;
fn decoder(&self) -> Self::Decoder {
SineWave::new(self.frequency).take_duration(self.duration)
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_audio/src/volume.rs | crates/bevy_audio/src/volume.rs | use bevy_ecs::prelude::*;
use bevy_math::ops;
use bevy_reflect::prelude::*;
/// Use this [`Resource`] to control the global volume of all audio.
///
/// Note: Changing [`GlobalVolume`] does not affect already playing audio.
#[derive(Resource, Debug, Default, Clone, Copy, Reflect)]
#[reflect(Resource, Debug, Default, Clone)]
pub struct GlobalVolume {
/// The global volume of all audio.
pub volume: Volume,
}
impl From<Volume> for GlobalVolume {
fn from(volume: Volume) -> Self {
Self { volume }
}
}
impl GlobalVolume {
/// Create a new [`GlobalVolume`] with the given volume.
pub fn new(volume: Volume) -> Self {
Self { volume }
}
}
/// A [`Volume`] represents an audio source's volume level.
///
/// To create a new [`Volume`] from a linear scale value, use
/// [`Volume::Linear`].
///
/// To create a new [`Volume`] from decibels, use [`Volume::Decibels`].
#[derive(Clone, Copy, Debug, Reflect)]
#[reflect(Clone, Debug, PartialEq)]
pub enum Volume {
/// Create a new [`Volume`] from the given volume in the linear scale.
///
/// In a linear scale, the value `1.0` represents the "normal" volume,
/// meaning the audio is played at its original level. Values greater than
/// `1.0` increase the volume, while values between `0.0` and `1.0` decrease
/// the volume. A value of `0.0` effectively mutes the audio.
///
/// # Examples
///
/// ```
/// # use bevy_audio::Volume;
/// # use bevy_math::ops;
/// #
/// # const EPSILON: f32 = 0.01;
///
/// let volume = Volume::Linear(0.5);
/// assert_eq!(volume.to_linear(), 0.5);
/// assert!(ops::abs(volume.to_decibels() - -6.0206) < EPSILON);
///
/// let volume = Volume::Linear(0.0);
/// assert_eq!(volume.to_linear(), 0.0);
/// assert_eq!(volume.to_decibels(), f32::NEG_INFINITY);
///
/// let volume = Volume::Linear(1.0);
/// assert_eq!(volume.to_linear(), 1.0);
/// assert!(ops::abs(volume.to_decibels() - 0.0) < EPSILON);
/// ```
Linear(f32),
/// Create a new [`Volume`] from the given volume in decibels.
///
/// In a decibel scale, the value `0.0` represents the "normal" volume,
/// meaning the audio is played at its original level. Values greater than
/// `0.0` increase the volume, while values less than `0.0` decrease the
/// volume. A value of [`f32::NEG_INFINITY`] decibels effectively mutes the
/// audio.
///
/// # Examples
///
/// ```
/// # use bevy_audio::Volume;
/// # use bevy_math::ops;
/// #
/// # const EPSILON: f32 = 0.01;
///
/// let volume = Volume::Decibels(-5.998);
/// assert!(ops::abs(volume.to_linear() - 0.5) < EPSILON);
///
/// let volume = Volume::Decibels(f32::NEG_INFINITY);
/// assert_eq!(volume.to_linear(), 0.0);
///
/// let volume = Volume::Decibels(0.0);
/// assert_eq!(volume.to_linear(), 1.0);
///
/// let volume = Volume::Decibels(20.0);
/// assert_eq!(volume.to_linear(), 10.0);
/// ```
Decibels(f32),
}
impl Default for Volume {
fn default() -> Self {
Self::Linear(1.0)
}
}
impl PartialEq for Volume {
fn eq(&self, other: &Self) -> bool {
use Volume::{Decibels, Linear};
match (self, other) {
(Linear(a), Linear(b)) => a.abs() == b.abs(),
(Decibels(a), Decibels(b)) => a == b,
(a, b) => a.to_decibels() == b.to_decibels(),
}
}
}
impl PartialOrd for Volume {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
use Volume::{Decibels, Linear};
Some(match (self, other) {
(Linear(a), Linear(b)) => a.abs().total_cmp(&b.abs()),
(Decibels(a), Decibels(b)) => a.total_cmp(b),
(a, b) => a.to_decibels().total_cmp(&b.to_decibels()),
})
}
}
#[inline]
fn decibels_to_linear(decibels: f32) -> f32 {
ops::powf(10.0f32, decibels / 20.0)
}
#[inline]
fn linear_to_decibels(linear: f32) -> f32 {
20.0 * ops::log10(linear.abs())
}
impl Volume {
/// Returns the volume in linear scale as a float.
pub fn to_linear(&self) -> f32 {
match self {
Self::Linear(v) => v.abs(),
Self::Decibels(v) => decibels_to_linear(*v),
}
}
/// Returns the volume in decibels as a float.
///
/// If the volume is silent / off / muted, i.e., its underlying linear scale
/// is `0.0`, this method returns negative infinity.
pub fn to_decibels(&self) -> f32 {
match self {
Self::Linear(v) => linear_to_decibels(*v),
Self::Decibels(v) => *v,
}
}
/// The silent volume. Also known as "off" or "muted".
pub const SILENT: Self = Volume::Linear(0.0);
/// Increases the volume by the specified percentage.
///
/// This method works in the linear domain, where a 100% increase
/// means doubling the volume (equivalent to +6.02dB).
///
/// # Arguments
/// * `percentage` - The percentage to increase (50.0 means 50% increase)
///
/// # Examples
/// ```
/// use bevy_audio::Volume;
///
/// let volume = Volume::Linear(1.0);
/// let increased = volume.increase_by_percentage(100.0);
/// assert_eq!(increased.to_linear(), 2.0);
/// ```
pub fn increase_by_percentage(&self, percentage: f32) -> Self {
let factor = 1.0 + (percentage / 100.0);
Volume::Linear(self.to_linear() * factor)
}
/// Decreases the volume by the specified percentage.
///
/// This method works in the linear domain, where a 50% decrease
/// means halving the volume (equivalent to -6.02dB).
///
/// # Arguments
/// * `percentage` - The percentage to decrease (50.0 means 50% decrease)
///
/// # Examples
/// ```
/// use bevy_audio::Volume;
///
/// let volume = Volume::Linear(1.0);
/// let decreased = volume.decrease_by_percentage(50.0);
/// assert_eq!(decreased.to_linear(), 0.5);
/// ```
pub fn decrease_by_percentage(&self, percentage: f32) -> Self {
let factor = 1.0 - (percentage / 100.0).clamp(0.0, 1.0);
Volume::Linear(self.to_linear() * factor)
}
/// Scales the volume to a specific linear factor relative to the current volume.
///
/// This is different from `adjust_by_linear` as it sets the volume to be
/// exactly the factor times the original volume, rather than applying
/// the factor to the current volume.
///
/// # Arguments
/// * `factor` - The scaling factor (2.0 = twice as loud, 0.5 = half as loud)
///
/// # Examples
/// ```
/// use bevy_audio::Volume;
///
/// let volume = Volume::Linear(0.8);
/// let scaled = volume.scale_to_factor(1.25);
/// assert_eq!(scaled.to_linear(), 1.0);
/// ```
pub fn scale_to_factor(&self, factor: f32) -> Self {
Volume::Linear(self.to_linear() * factor)
}
/// Creates a fade effect by interpolating between current volume and target volume.
///
/// This method performs linear interpolation in the linear domain, which
/// provides a more natural-sounding fade effect.
///
/// # Arguments
/// * `target` - The target volume to fade towards
/// * `factor` - The interpolation factor (0.0 = current volume, 1.0 = target volume)
///
/// # Examples
/// ```
/// use bevy_audio::Volume;
///
/// let current = Volume::Linear(1.0);
/// let target = Volume::Linear(0.0);
/// let faded = current.fade_towards(target, 0.5);
/// assert_eq!(faded.to_linear(), 0.5);
/// ```
pub fn fade_towards(&self, target: Volume, factor: f32) -> Self {
let current_linear = self.to_linear();
let target_linear = target.to_linear();
let factor_clamped = factor.clamp(0.0, 1.0);
let interpolated = current_linear + (target_linear - current_linear) * factor_clamped;
Volume::Linear(interpolated)
}
}
impl core::ops::Mul<Self> for Volume {
type Output = Self;
fn mul(self, rhs: Self) -> Self {
use Volume::{Decibels, Linear};
match (self, rhs) {
(Linear(a), Linear(b)) => Linear(a * b),
(Decibels(a), Decibels(b)) => Decibels(a + b),
// {Linear, Decibels} favors the left hand side of the operation by
// first converting the right hand side to the same type as the left
// hand side and then performing the operation.
(Linear(..), Decibels(db)) => self * Linear(decibels_to_linear(db)),
(Decibels(..), Linear(l)) => self * Decibels(linear_to_decibels(l)),
}
}
}
impl core::ops::MulAssign<Self> for Volume {
fn mul_assign(&mut self, rhs: Self) {
*self = *self * rhs;
}
}
impl core::ops::Div<Self> for Volume {
type Output = Self;
fn div(self, rhs: Self) -> Self {
use Volume::{Decibels, Linear};
match (self, rhs) {
(Linear(a), Linear(b)) => Linear(a / b),
(Decibels(a), Decibels(b)) => Decibels(a - b),
// {Linear, Decibels} favors the left hand side of the operation by
// first converting the right hand side to the same type as the left
// hand side and then performing the operation.
(Linear(..), Decibels(db)) => self / Linear(decibels_to_linear(db)),
(Decibels(..), Linear(l)) => self / Decibels(linear_to_decibels(l)),
}
}
}
impl core::ops::DivAssign<Self> for Volume {
fn div_assign(&mut self, rhs: Self) {
*self = *self / rhs;
}
}
#[cfg(test)]
mod tests {
use super::Volume::{self, Decibels, Linear};
/// Based on [Wikipedia's Decibel article].
///
/// [Wikipedia's Decibel article]: https://web.archive.org/web/20230810185300/https://en.wikipedia.org/wiki/Decibel
const DECIBELS_LINEAR_TABLE: [(f32, f32); 27] = [
(100., 100000.),
(90., 31623.),
(80., 10000.),
(70., 3162.),
(60., 1000.),
(50., 316.2),
(40., 100.),
(30., 31.62),
(20., 10.),
(10., 3.162),
(5.998, 1.995),
(3.003, 1.413),
(1.002, 1.122),
(0., 1.),
(-1.002, 0.891),
(-3.003, 0.708),
(-5.998, 0.501),
(-10., 0.3162),
(-20., 0.1),
(-30., 0.03162),
(-40., 0.01),
(-50., 0.003162),
(-60., 0.001),
(-70., 0.0003162),
(-80., 0.0001),
(-90., 0.00003162),
(-100., 0.00001),
];
#[test]
fn volume_conversion() {
for (db, linear) in DECIBELS_LINEAR_TABLE {
for volume in [Linear(linear), Decibels(db), Linear(-linear)] {
let db_test = volume.to_decibels();
let linear_test = volume.to_linear();
let db_delta = db_test - db;
let linear_relative_delta = (linear_test - linear) / linear;
assert!(
db_delta.abs() < 1e-2,
"Expected ~{db}dB, got {db_test}dB (delta {db_delta})",
);
assert!(
linear_relative_delta.abs() < 1e-3,
"Expected ~{linear}, got {linear_test} (relative delta {linear_relative_delta})",
);
}
}
}
#[test]
fn volume_conversion_special() {
assert!(
Decibels(f32::INFINITY).to_linear().is_infinite(),
"Infinite decibels is equivalent to infinite linear scale"
);
assert!(
Linear(f32::INFINITY).to_decibels().is_infinite(),
"Infinite linear scale is equivalent to infinite decibels"
);
assert!(
Linear(f32::NEG_INFINITY).to_decibels().is_infinite(),
"Negative infinite linear scale is equivalent to infinite decibels"
);
assert_eq!(
Decibels(f32::NEG_INFINITY).to_linear().abs(),
0.0,
"Negative infinity decibels is equivalent to zero linear scale"
);
assert!(
Linear(0.0).to_decibels().is_infinite(),
"Zero linear scale is equivalent to negative infinity decibels"
);
assert!(
Linear(-0.0).to_decibels().is_infinite(),
"Negative zero linear scale is equivalent to negative infinity decibels"
);
assert!(
Decibels(f32::NAN).to_linear().is_nan(),
"NaN decibels is equivalent to NaN linear scale"
);
assert!(
Linear(f32::NAN).to_decibels().is_nan(),
"NaN linear scale is equivalent to NaN decibels"
);
}
#[test]
fn test_increase_by_percentage() {
let volume = Linear(1.0);
// 100% increase should double the volume
let increased = volume.increase_by_percentage(100.0);
assert_eq!(increased.to_linear(), 2.0);
// 50% increase
let increased = volume.increase_by_percentage(50.0);
assert_eq!(increased.to_linear(), 1.5);
}
#[test]
fn test_decrease_by_percentage() {
let volume = Linear(1.0);
// 50% decrease should halve the volume
let decreased = volume.decrease_by_percentage(50.0);
assert_eq!(decreased.to_linear(), 0.5);
// 25% decrease
let decreased = volume.decrease_by_percentage(25.0);
assert_eq!(decreased.to_linear(), 0.75);
// 100% decrease should result in silence
let decreased = volume.decrease_by_percentage(100.0);
assert_eq!(decreased.to_linear(), 0.0);
}
#[test]
fn test_scale_to_factor() {
let volume = Linear(0.8);
let scaled = volume.scale_to_factor(1.25);
assert_eq!(scaled.to_linear(), 1.0);
}
#[test]
fn test_fade_towards() {
let current = Linear(1.0);
let target = Linear(0.0);
// 50% fade should result in 0.5 linear volume
let faded = current.fade_towards(target, 0.5);
assert_eq!(faded.to_linear(), 0.5);
// 0% fade should keep current volume
let faded = current.fade_towards(target, 0.0);
assert_eq!(faded.to_linear(), 1.0);
// 100% fade should reach target volume
let faded = current.fade_towards(target, 1.0);
assert_eq!(faded.to_linear(), 0.0);
}
#[test]
fn test_decibel_math_properties() {
let volume = Linear(1.0);
// Adding 20dB should multiply linear volume by 10
let adjusted = volume * Decibels(20.0);
assert_approx_eq(adjusted, Linear(10.0));
// Subtracting 20dB should divide linear volume by 10
let adjusted = volume / Decibels(20.0);
assert_approx_eq(adjusted, Linear(0.1));
}
fn assert_approx_eq(a: Volume, b: Volume) {
const EPSILON: f32 = 0.0001;
match (a, b) {
(Decibels(a), Decibels(b)) | (Linear(a), Linear(b)) => assert!(
(a - b).abs() < EPSILON,
"Expected {a:?} to be approximately equal to {b:?}",
),
(a, b) => assert!(
(a.to_decibels() - b.to_decibels()).abs() < EPSILON,
"Expected {a:?} to be approximately equal to {b:?}",
),
}
}
#[test]
fn volume_ops_mul() {
// Linear to Linear.
assert_approx_eq(Linear(0.5) * Linear(0.5), Linear(0.25));
assert_approx_eq(Linear(0.5) * Linear(0.1), Linear(0.05));
assert_approx_eq(Linear(0.5) * Linear(-0.5), Linear(-0.25));
// Decibels to Decibels.
assert_approx_eq(Decibels(0.0) * Decibels(0.0), Decibels(0.0));
assert_approx_eq(Decibels(6.0) * Decibels(6.0), Decibels(12.0));
assert_approx_eq(Decibels(-6.0) * Decibels(-6.0), Decibels(-12.0));
// {Linear, Decibels} favors the left hand side of the operation.
assert_approx_eq(Linear(0.5) * Decibels(0.0), Linear(0.5));
assert_approx_eq(Decibels(0.0) * Linear(0.501), Decibels(-6.003246));
}
#[test]
fn volume_ops_mul_assign() {
// Linear to Linear.
let mut volume = Linear(0.5);
volume *= Linear(0.5);
assert_approx_eq(volume, Linear(0.25));
// Decibels to Decibels.
let mut volume = Decibels(6.0);
volume *= Decibels(6.0);
assert_approx_eq(volume, Decibels(12.0));
// {Linear, Decibels} favors the left hand side of the operation.
let mut volume = Linear(0.5);
volume *= Decibels(0.0);
assert_approx_eq(volume, Linear(0.5));
let mut volume = Decibels(0.0);
volume *= Linear(0.501);
assert_approx_eq(volume, Decibels(-6.003246));
}
#[test]
fn volume_ops_div() {
// Linear to Linear.
assert_approx_eq(Linear(0.5) / Linear(0.5), Linear(1.0));
assert_approx_eq(Linear(0.5) / Linear(0.1), Linear(5.0));
assert_approx_eq(Linear(0.5) / Linear(-0.5), Linear(-1.0));
// Decibels to Decibels.
assert_approx_eq(Decibels(0.0) / Decibels(0.0), Decibels(0.0));
assert_approx_eq(Decibels(6.0) / Decibels(6.0), Decibels(0.0));
assert_approx_eq(Decibels(-6.0) / Decibels(-6.0), Decibels(0.0));
// {Linear, Decibels} favors the left hand side of the operation.
assert_approx_eq(Linear(0.5) / Decibels(0.0), Linear(0.5));
assert_approx_eq(Decibels(0.0) / Linear(0.501), Decibels(6.003246));
}
#[test]
fn volume_ops_div_assign() {
// Linear to Linear.
let mut volume = Linear(0.5);
volume /= Linear(0.5);
assert_approx_eq(volume, Linear(1.0));
// Decibels to Decibels.
let mut volume = Decibels(6.0);
volume /= Decibels(6.0);
assert_approx_eq(volume, Decibels(0.0));
// {Linear, Decibels} favors the left hand side of the operation.
let mut volume = Linear(0.5);
volume /= Decibels(0.0);
assert_approx_eq(volume, Linear(0.5));
let mut volume = Decibels(0.0);
volume /= Linear(0.501);
assert_approx_eq(volume, Decibels(6.003246));
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_audio/src/audio_output.rs | crates/bevy_audio/src/audio_output.rs | use crate::{
AudioPlayer, Decodable, DefaultSpatialScale, GlobalVolume, PlaybackMode, PlaybackSettings,
SpatialAudioSink, SpatialListener,
};
use bevy_asset::{Asset, Assets};
use bevy_ecs::{prelude::*, system::SystemParam};
use bevy_math::Vec3;
use bevy_transform::prelude::GlobalTransform;
use rodio::{OutputStream, OutputStreamHandle, Sink, Source, SpatialSink};
use tracing::warn;
use crate::{AudioSink, AudioSinkPlayback};
/// Used internally to play audio on the current "audio device"
///
/// ## Note
///
/// Initializing this resource will leak [`OutputStream`]
/// using [`std::mem::forget`].
/// This is done to avoid storing this in the struct (and making this `!Send`)
/// while preventing it from dropping (to avoid halting of audio).
///
/// This is fine when initializing this once (as is default when adding this plugin),
/// since the memory cost will be the same.
/// However, repeatedly inserting this resource into the app will **leak more memory**.
#[derive(Resource)]
pub(crate) struct AudioOutput {
stream_handle: Option<OutputStreamHandle>,
}
impl Default for AudioOutput {
fn default() -> Self {
if let Ok((stream, stream_handle)) = OutputStream::try_default() {
// We leak `OutputStream` to prevent the audio from stopping.
core::mem::forget(stream);
Self {
stream_handle: Some(stream_handle),
}
} else {
warn!("No audio device found.");
Self {
stream_handle: None,
}
}
}
}
/// Marker for internal use, to despawn entities when playback finishes.
#[derive(Component, Default)]
pub struct PlaybackDespawnMarker;
/// Marker for internal use, to remove audio components when playback finishes.
#[derive(Component, Default)]
pub struct PlaybackRemoveMarker;
#[derive(SystemParam)]
pub(crate) struct EarPositions<'w, 's> {
pub(crate) query: Query<'w, 's, (Entity, &'static GlobalTransform, &'static SpatialListener)>,
}
impl<'w, 's> EarPositions<'w, 's> {
/// Gets a set of transformed ear positions.
///
/// If there are no listeners, use the default values. If a user has added multiple
/// listeners for whatever reason, we will return the first value.
pub(crate) fn get(&self) -> (Vec3, Vec3) {
let (left_ear, right_ear) = self
.query
.iter()
.next()
.map(|(_, transform, settings)| {
(
transform.transform_point(settings.left_ear_offset),
transform.transform_point(settings.right_ear_offset),
)
})
.unwrap_or_else(|| {
let settings = SpatialListener::default();
(settings.left_ear_offset, settings.right_ear_offset)
});
(left_ear, right_ear)
}
pub(crate) fn multiple_listeners(&self) -> bool {
self.query.iter().len() > 1
}
}
/// Plays "queued" audio through the [`AudioOutput`] resource.
///
/// "Queued" audio is any audio entity (with an [`AudioPlayer`] component) that does not have an
/// [`AudioSink`]/[`SpatialAudioSink`] component.
///
/// This system detects such entities, checks if their source asset
/// data is available, and creates/inserts the sink.
pub(crate) fn play_queued_audio_system<Source: Asset + Decodable>(
audio_output: Res<AudioOutput>,
audio_sources: Res<Assets<Source>>,
global_volume: Res<GlobalVolume>,
query_nonplaying: Query<
(
Entity,
&AudioPlayer<Source>,
&PlaybackSettings,
Option<&GlobalTransform>,
),
(Without<AudioSink>, Without<SpatialAudioSink>),
>,
ear_positions: EarPositions,
default_spatial_scale: Res<DefaultSpatialScale>,
mut commands: Commands,
) where
f32: rodio::cpal::FromSample<Source::DecoderItem>,
{
let Some(stream_handle) = audio_output.stream_handle.as_ref() else {
// audio output unavailable; cannot play sound
return;
};
for (entity, source_handle, settings, maybe_emitter_transform) in &query_nonplaying {
let Some(audio_source) = audio_sources.get(&source_handle.0) else {
continue;
};
// audio data is available (has loaded), begin playback and insert sink component
if settings.spatial {
let (left_ear, right_ear) = ear_positions.get();
// We can only use one `SpatialListener`. If there are more than that, then
// the user may have made a mistake.
if ear_positions.multiple_listeners() {
warn!(
"Multiple SpatialListeners found. Using {}.",
ear_positions.query.iter().next().unwrap().0
);
}
let scale = settings.spatial_scale.unwrap_or(default_spatial_scale.0).0;
let emitter_translation = if let Some(emitter_transform) = maybe_emitter_transform {
(emitter_transform.translation() * scale).into()
} else {
warn!("Spatial AudioPlayer with no GlobalTransform component. Using zero.");
Vec3::ZERO.into()
};
let sink = match SpatialSink::try_new(
stream_handle,
emitter_translation,
(left_ear * scale).into(),
(right_ear * scale).into(),
) {
Ok(sink) => sink,
Err(err) => {
warn!("Error creating spatial sink: {err:?}");
continue;
}
};
let decoder = audio_source.decoder();
match settings.mode {
PlaybackMode::Loop => match (settings.start_position, settings.duration) {
// custom start position and duration
(Some(start_position), Some(duration)) => sink.append(
decoder
.skip_duration(start_position)
.take_duration(duration)
.repeat_infinite(),
),
// custom start position
(Some(start_position), None) => {
sink.append(decoder.skip_duration(start_position).repeat_infinite());
}
// custom duration
(None, Some(duration)) => {
sink.append(decoder.take_duration(duration).repeat_infinite());
}
// full clip
(None, None) => sink.append(decoder.repeat_infinite()),
},
PlaybackMode::Once | PlaybackMode::Despawn | PlaybackMode::Remove => {
match (settings.start_position, settings.duration) {
(Some(start_position), Some(duration)) => sink.append(
decoder
.skip_duration(start_position)
.take_duration(duration),
),
(Some(start_position), None) => {
sink.append(decoder.skip_duration(start_position));
}
(None, Some(duration)) => sink.append(decoder.take_duration(duration)),
(None, None) => sink.append(decoder),
}
}
}
let mut sink = SpatialAudioSink::new(sink);
if settings.muted {
sink.mute();
}
sink.set_speed(settings.speed);
sink.set_volume(settings.volume * global_volume.volume);
if settings.paused {
sink.pause();
}
match settings.mode {
PlaybackMode::Loop | PlaybackMode::Once => commands.entity(entity).insert(sink),
PlaybackMode::Despawn => commands
.entity(entity)
// PERF: insert as bundle to reduce archetype moves
.insert((sink, PlaybackDespawnMarker)),
PlaybackMode::Remove => commands
.entity(entity)
// PERF: insert as bundle to reduce archetype moves
.insert((sink, PlaybackRemoveMarker)),
};
} else {
let sink = match Sink::try_new(stream_handle) {
Ok(sink) => sink,
Err(err) => {
warn!("Error creating sink: {err:?}");
continue;
}
};
let decoder = audio_source.decoder();
match settings.mode {
PlaybackMode::Loop => match (settings.start_position, settings.duration) {
// custom start position and duration
(Some(start_position), Some(duration)) => sink.append(
decoder
.skip_duration(start_position)
.take_duration(duration)
.repeat_infinite(),
),
// custom start position
(Some(start_position), None) => {
sink.append(decoder.skip_duration(start_position).repeat_infinite());
}
// custom duration
(None, Some(duration)) => {
sink.append(decoder.take_duration(duration).repeat_infinite());
}
// full clip
(None, None) => sink.append(decoder.repeat_infinite()),
},
PlaybackMode::Once | PlaybackMode::Despawn | PlaybackMode::Remove => {
match (settings.start_position, settings.duration) {
(Some(start_position), Some(duration)) => sink.append(
decoder
.skip_duration(start_position)
.take_duration(duration),
),
(Some(start_position), None) => {
sink.append(decoder.skip_duration(start_position));
}
(None, Some(duration)) => sink.append(decoder.take_duration(duration)),
(None, None) => sink.append(decoder),
}
}
}
let mut sink = AudioSink::new(sink);
if settings.muted {
sink.mute();
}
sink.set_speed(settings.speed);
sink.set_volume(settings.volume * global_volume.volume);
if settings.paused {
sink.pause();
}
match settings.mode {
PlaybackMode::Loop | PlaybackMode::Once => commands.entity(entity).insert(sink),
PlaybackMode::Despawn => commands
.entity(entity)
// PERF: insert as bundle to reduce archetype moves
.insert((sink, PlaybackDespawnMarker)),
PlaybackMode::Remove => commands
.entity(entity)
// PERF: insert as bundle to reduce archetype moves
.insert((sink, PlaybackRemoveMarker)),
};
}
}
}
pub(crate) fn cleanup_finished_audio<T: Decodable + Asset>(
mut commands: Commands,
query_nonspatial_despawn: Query<
(Entity, &AudioSink),
(With<PlaybackDespawnMarker>, With<AudioPlayer<T>>),
>,
query_spatial_despawn: Query<
(Entity, &SpatialAudioSink),
(With<PlaybackDespawnMarker>, With<AudioPlayer<T>>),
>,
query_nonspatial_remove: Query<
(Entity, &AudioSink),
(With<PlaybackRemoveMarker>, With<AudioPlayer<T>>),
>,
query_spatial_remove: Query<
(Entity, &SpatialAudioSink),
(With<PlaybackRemoveMarker>, With<AudioPlayer<T>>),
>,
) {
for (entity, sink) in &query_nonspatial_despawn {
if sink.sink.empty() {
commands.entity(entity).despawn();
}
}
for (entity, sink) in &query_spatial_despawn {
if sink.sink.empty() {
commands.entity(entity).despawn();
}
}
for (entity, sink) in &query_nonspatial_remove {
if sink.sink.empty() {
commands.entity(entity).remove::<(
AudioPlayer<T>,
AudioSink,
PlaybackSettings,
PlaybackRemoveMarker,
)>();
}
}
for (entity, sink) in &query_spatial_remove {
if sink.sink.empty() {
commands.entity(entity).remove::<(
AudioPlayer<T>,
SpatialAudioSink,
PlaybackSettings,
PlaybackRemoveMarker,
)>();
}
}
}
/// Run Condition to only play audio if the audio output is available
pub(crate) fn audio_output_available(audio_output: Res<AudioOutput>) -> bool {
audio_output.stream_handle.is_some()
}
/// Updates spatial audio sinks when emitter positions change.
pub(crate) fn update_emitter_positions(
mut emitters: Query<
(&GlobalTransform, &SpatialAudioSink, &PlaybackSettings),
Or<(Changed<GlobalTransform>, Changed<PlaybackSettings>)>,
>,
default_spatial_scale: Res<DefaultSpatialScale>,
) {
for (transform, sink, settings) in emitters.iter_mut() {
let scale = settings.spatial_scale.unwrap_or(default_spatial_scale.0).0;
let translation = transform.translation() * scale;
sink.set_emitter_position(translation);
}
}
/// Updates spatial audio sink ear positions when spatial listeners change.
pub(crate) fn update_listener_positions(
mut emitters: Query<(&SpatialAudioSink, &PlaybackSettings)>,
changed_listener: Query<
(),
(
Or<(
Changed<SpatialListener>,
Changed<GlobalTransform>,
Changed<PlaybackSettings>,
)>,
With<SpatialListener>,
),
>,
ear_positions: EarPositions,
default_spatial_scale: Res<DefaultSpatialScale>,
) {
if !default_spatial_scale.is_changed() && changed_listener.is_empty() {
return;
}
let (left_ear, right_ear) = ear_positions.get();
for (sink, settings) in emitters.iter_mut() {
let scale = settings.spatial_scale.unwrap_or(default_spatial_scale.0).0;
sink.set_ears_position(left_ear * scale, right_ear * scale);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_audio/src/audio_source.rs | crates/bevy_audio/src/audio_source.rs | use alloc::sync::Arc;
use bevy_asset::{io::Reader, Asset, AssetLoader, LoadContext};
use bevy_reflect::TypePath;
use std::io::Cursor;
/// A source of audio data
#[derive(Asset, Debug, Clone, TypePath)]
pub struct AudioSource {
/// Raw data of the audio source.
///
/// The data must be one of the file formats supported by Bevy (`wav`, `ogg`, `flac`, or `mp3`).
/// However, support for these file formats is not part of Bevy's [`default feature set`](https://docs.rs/bevy/latest/bevy/index.html#default-features).
/// In order to be able to use these file formats, you will have to enable the appropriate [`optional features`](https://docs.rs/bevy/latest/bevy/index.html#optional-features).
///
/// It is decoded using [`rodio::decoder::Decoder`](https://docs.rs/rodio/latest/rodio/decoder/struct.Decoder.html).
/// The decoder has conditionally compiled methods
/// depending on the features enabled.
/// If the format used is not enabled,
/// then this will panic with an `UnrecognizedFormat` error.
pub bytes: Arc<[u8]>,
}
impl AsRef<[u8]> for AudioSource {
fn as_ref(&self) -> &[u8] {
&self.bytes
}
}
/// Loads files as [`AudioSource`] [`Assets`](bevy_asset::Assets)
///
/// This asset loader supports different audio formats based on the enable Bevy features.
/// The feature `bevy/vorbis` enables loading from `.ogg` files and is enabled by default.
/// Other file endings can be loaded from with additional features:
/// `.mp3` with `bevy/mp3`
/// `.flac` with `bevy/flac`
/// `.wav` with `bevy/wav`
#[derive(Default, TypePath)]
pub struct AudioLoader;
impl AssetLoader for AudioLoader {
type Asset = AudioSource;
type Settings = ();
type Error = std::io::Error;
async fn load(
&self,
reader: &mut dyn Reader,
_settings: &Self::Settings,
_load_context: &mut LoadContext<'_>,
) -> Result<AudioSource, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
Ok(AudioSource {
bytes: bytes.into(),
})
}
fn extensions(&self) -> &[&str] {
&[
#[cfg(feature = "mp3")]
"mp3",
#[cfg(feature = "flac")]
"flac",
#[cfg(feature = "wav")]
"wav",
#[cfg(feature = "vorbis")]
"oga",
#[cfg(feature = "vorbis")]
"ogg",
#[cfg(feature = "vorbis")]
"spx",
]
}
}
/// A type implementing this trait can be converted to a [`rodio::Source`] type.
///
/// It must be [`Send`] and [`Sync`] in order to be registered.
/// Types that implement this trait usually contain raw sound data that can be converted into an iterator of samples.
/// This trait is implemented for [`AudioSource`].
/// Check the example [`decodable`](https://github.com/bevyengine/bevy/blob/latest/examples/audio/decodable.rs) for how to implement this trait on a custom type.
pub trait Decodable: Send + Sync + 'static {
/// The type of the audio samples.
/// Usually a [`u16`], [`i16`] or [`f32`], as those implement [`rodio::Sample`].
/// Other types can implement the [`rodio::Sample`] trait as well.
type DecoderItem: rodio::Sample + Send + Sync;
/// The type of the iterator of the audio samples,
/// which iterates over samples of type [`Self::DecoderItem`].
/// Must be a [`rodio::Source`] so that it can provide information on the audio it is iterating over.
type Decoder: rodio::Source + Send + Iterator<Item = Self::DecoderItem>;
/// Build and return a [`Self::Decoder`] of the implementing type
fn decoder(&self) -> Self::Decoder;
}
impl Decodable for AudioSource {
type DecoderItem = <rodio::Decoder<Cursor<AudioSource>> as Iterator>::Item;
type Decoder = rodio::Decoder<Cursor<AudioSource>>;
fn decoder(&self) -> Self::Decoder {
rodio::Decoder::new(Cursor::new(self.clone())).unwrap()
}
}
/// A trait that allows adding a custom audio source to the object.
/// This is implemented for [`App`][bevy_app::App] to allow registering custom [`Decodable`] types.
pub trait AddAudioSource {
/// Registers an audio source.
/// The type must implement [`Decodable`],
/// so that it can be converted to a [`rodio::Source`] type,
/// and [`Asset`], so that it can be registered as an asset.
/// To use this method on [`App`][bevy_app::App],
/// the [audio][super::AudioPlugin] and [asset][bevy_asset::AssetPlugin] plugins must be added first.
fn add_audio_source<T>(&mut self) -> &mut Self
where
T: Decodable + Asset,
f32: rodio::cpal::FromSample<T::DecoderItem>;
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_audio/src/audio.rs | crates/bevy_audio/src/audio.rs | use crate::{AudioSource, Decodable, Volume};
use bevy_asset::{Asset, Handle};
use bevy_ecs::prelude::*;
use bevy_math::Vec3;
use bevy_reflect::prelude::*;
use bevy_transform::components::Transform;
/// The way Bevy manages the sound playback.
#[derive(Debug, Clone, Copy, Reflect)]
#[reflect(Clone)]
pub enum PlaybackMode {
/// Play the sound once. Do nothing when it ends.
///
/// Note: It is not possible to reuse an [`AudioPlayer`] after it has finished playing and
/// the underlying [`AudioSink`](crate::AudioSink) or [`SpatialAudioSink`](crate::SpatialAudioSink) has been drained.
///
/// To replay a sound, the audio components provided by [`AudioPlayer`] must be removed and
/// added again.
Once,
/// Repeat the sound forever.
Loop,
/// Despawn the entity and its children when the sound finishes playing.
Despawn,
/// Remove the audio components from the entity, when the sound finishes playing.
Remove,
}
/// Initial settings to be used when audio starts playing.
///
/// If you would like to control the audio while it is playing, query for the
/// [`AudioSink`](crate::AudioSink) or [`SpatialAudioSink`](crate::SpatialAudioSink)
/// components. Changes to this component will *not* be applied to already-playing audio.
#[derive(Component, Clone, Copy, Debug, Reflect)]
#[reflect(Clone, Default, Component, Debug)]
pub struct PlaybackSettings {
/// The desired playback behavior.
pub mode: PlaybackMode,
/// Volume to play at.
pub volume: Volume,
/// Speed to play at.
pub speed: f32,
/// Create the sink in paused state.
/// Useful for "deferred playback", if you want to prepare
/// the entity, but hear the sound later.
pub paused: bool,
/// Whether to create the sink in muted state or not.
///
/// This is useful for audio that should be initially muted. You can still
/// set the initial volume and it is applied when the audio is unmuted.
pub muted: bool,
/// Enables spatial audio for this source.
///
/// See also: [`SpatialListener`].
///
/// Note: Bevy does not currently support HRTF or any other high-quality 3D sound rendering
/// features. Spatial audio is implemented via simple left-right stereo panning.
pub spatial: bool,
/// Optional scale factor applied to the positions of this audio source and the listener,
/// overriding the default value configured on [`AudioPlugin::default_spatial_scale`](crate::AudioPlugin::default_spatial_scale).
pub spatial_scale: Option<SpatialScale>,
/// The point in time in the audio clip where playback should start. If set to `None`, it will
/// play from the beginning of the clip.
///
/// If the playback mode is set to `Loop`, each loop will start from this position.
pub start_position: Option<core::time::Duration>,
/// How long the audio should play before stopping. If set, the clip will play for at most
/// the specified duration. If set to `None`, it will play for as long as it can.
///
/// If the playback mode is set to `Loop`, each loop will last for this duration.
pub duration: Option<core::time::Duration>,
}
impl Default for PlaybackSettings {
fn default() -> Self {
Self::ONCE
}
}
impl PlaybackSettings {
/// Will play the associated audio source once.
///
/// Note: It is not possible to reuse an [`AudioPlayer`] after it has finished playing and
/// the underlying [`AudioSink`](crate::AudioSink) or [`SpatialAudioSink`](crate::SpatialAudioSink) has been drained.
///
/// To replay a sound, the audio components provided by [`AudioPlayer`] must be removed and
/// added again.
pub const ONCE: PlaybackSettings = PlaybackSettings {
mode: PlaybackMode::Once,
volume: Volume::Linear(1.0),
speed: 1.0,
paused: false,
muted: false,
spatial: false,
spatial_scale: None,
start_position: None,
duration: None,
};
/// Will play the associated audio source in a loop.
pub const LOOP: PlaybackSettings = PlaybackSettings {
mode: PlaybackMode::Loop,
..PlaybackSettings::ONCE
};
/// Will play the associated audio source once and despawn the entity afterwards.
pub const DESPAWN: PlaybackSettings = PlaybackSettings {
mode: PlaybackMode::Despawn,
..PlaybackSettings::ONCE
};
/// Will play the associated audio source once and remove the audio components afterwards.
pub const REMOVE: PlaybackSettings = PlaybackSettings {
mode: PlaybackMode::Remove,
..PlaybackSettings::ONCE
};
/// Helper to start in a paused state.
pub const fn paused(mut self) -> Self {
self.paused = true;
self
}
/// Helper to start muted.
pub const fn muted(mut self) -> Self {
self.muted = true;
self
}
/// Helper to set the volume from start of playback.
pub const fn with_volume(mut self, volume: Volume) -> Self {
self.volume = volume;
self
}
/// Helper to set the speed from start of playback.
pub const fn with_speed(mut self, speed: f32) -> Self {
self.speed = speed;
self
}
/// Helper to enable or disable spatial audio.
pub const fn with_spatial(mut self, spatial: bool) -> Self {
self.spatial = spatial;
self
}
/// Helper to use a custom spatial scale.
pub const fn with_spatial_scale(mut self, spatial_scale: SpatialScale) -> Self {
self.spatial_scale = Some(spatial_scale);
self
}
/// Helper to use a custom playback start position.
pub const fn with_start_position(mut self, start_position: core::time::Duration) -> Self {
self.start_position = Some(start_position);
self
}
/// Helper to use a custom playback duration.
pub const fn with_duration(mut self, duration: core::time::Duration) -> Self {
self.duration = Some(duration);
self
}
}
/// Settings for the listener for spatial audio sources.
///
/// This is accompanied by [`Transform`] and [`GlobalTransform`](bevy_transform::prelude::GlobalTransform).
/// Only one entity with a [`SpatialListener`] should be present at any given time.
#[derive(Component, Clone, Debug, Reflect)]
#[require(Transform)]
#[reflect(Clone, Default, Component, Debug)]
pub struct SpatialListener {
/// Left ear position relative to the [`GlobalTransform`](bevy_transform::prelude::GlobalTransform).
pub left_ear_offset: Vec3,
/// Right ear position relative to the [`GlobalTransform`](bevy_transform::prelude::GlobalTransform).
pub right_ear_offset: Vec3,
}
impl Default for SpatialListener {
fn default() -> Self {
Self::new(4.)
}
}
impl SpatialListener {
/// Creates a new [`SpatialListener`] component.
///
/// `gap` is the distance between the left and right "ears" of the listener. Ears are
/// positioned on the x axis.
pub fn new(gap: f32) -> Self {
SpatialListener {
left_ear_offset: Vec3::X * gap / -2.0,
right_ear_offset: Vec3::X * gap / 2.0,
}
}
}
/// A scale factor applied to the positions of audio sources and listeners for
/// spatial audio.
///
/// Default is `Vec3::ONE`.
#[derive(Clone, Copy, Debug, Reflect)]
#[reflect(Clone, Default)]
pub struct SpatialScale(pub Vec3);
impl SpatialScale {
/// Create a new [`SpatialScale`] with the same value for all 3 dimensions.
pub const fn new(scale: f32) -> Self {
Self(Vec3::splat(scale))
}
/// Create a new [`SpatialScale`] with the same value for `x` and `y`, and `0.0`
/// for `z`.
pub const fn new_2d(scale: f32) -> Self {
Self(Vec3::new(scale, scale, 0.0))
}
}
impl Default for SpatialScale {
fn default() -> Self {
Self(Vec3::ONE)
}
}
/// The default scale factor applied to the positions of audio sources and listeners for
/// spatial audio. Can be overridden for individual sounds in [`PlaybackSettings`].
///
/// You may need to adjust this scale to fit your world's units.
///
/// Default is `Vec3::ONE`.
#[derive(Resource, Default, Clone, Copy, Reflect)]
#[reflect(Resource, Default, Clone)]
pub struct DefaultSpatialScale(pub SpatialScale);
/// A component for playing a sound.
///
/// Insert this component onto an entity to trigger an audio source to begin playing.
///
/// If the handle refers to an unavailable asset (such as if it has not finished loading yet),
/// the audio will not begin playing immediately. The audio will play when the asset is ready.
///
/// When Bevy begins the audio playback, an [`AudioSink`](crate::AudioSink) component will be
/// added to the entity. You can use that component to control the audio settings during playback.
///
/// Playback can be configured using the [`PlaybackSettings`] component. Note that changes to the
/// [`PlaybackSettings`] component will *not* affect already-playing audio.
#[derive(Component, Reflect)]
#[reflect(Component, Clone)]
#[require(PlaybackSettings)]
pub struct AudioPlayer<Source = AudioSource>(pub Handle<Source>)
where
Source: Asset + Decodable;
impl<Source> Clone for AudioPlayer<Source>
where
Source: Asset + Decodable,
{
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl AudioPlayer<AudioSource> {
/// Creates a new [`AudioPlayer`] with the given [`Handle<AudioSource>`].
///
/// For convenience reasons, this hard-codes the [`AudioSource`] type. If you want to
/// initialize an [`AudioPlayer`] with a different type, just initialize it directly using normal
/// tuple struct syntax.
pub fn new(source: Handle<AudioSource>) -> Self {
Self(source)
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_audio/src/sinks.rs | crates/bevy_audio/src/sinks.rs | use crate::Volume;
use bevy_ecs::component::Component;
use bevy_math::Vec3;
use bevy_transform::prelude::Transform;
use core::time::Duration;
pub use rodio::source::SeekError;
use rodio::{Sink, SpatialSink};
/// Common interactions with an audio sink.
pub trait AudioSinkPlayback {
/// Gets the volume of the sound as a [`Volume`].
///
/// If the sink is muted, this returns the managed volume rather than the
/// sink's actual volume. This allows you to use the returned volume as if
/// the sink were not muted, because a muted sink has a physical volume of
/// 0.
fn volume(&self) -> Volume;
/// Changes the volume of the sound to the given [`Volume`].
///
/// If the sink is muted, changing the volume won't unmute it, i.e. the
/// sink's volume will remain "off" / "muted". However, the sink will
/// remember the volume change and it will be used when
/// [`unmute`](Self::unmute) is called. This allows you to control the
/// volume even when the sink is muted.
fn set_volume(&mut self, volume: Volume);
/// Gets the speed of the sound.
///
/// The value `1.0` is the "normal" speed (unfiltered input). Any value other than `1.0`
/// will change the play speed of the sound.
fn speed(&self) -> f32;
/// Changes the speed of the sound.
///
/// The value `1.0` is the "normal" speed (unfiltered input). Any value other than `1.0`
/// will change the play speed of the sound.
fn set_speed(&self, speed: f32);
/// Resumes playback of a paused sink.
///
/// No effect if not paused.
fn play(&self);
/// Returns the position of the sound that's being played.
///
/// This takes into account any speedup or delay applied.
///
/// Example: if you [`set_speed(2.0)`](Self::set_speed) and [`position()`](Self::position) returns *5s*,
/// then the position in the recording is *10s* from its start.
fn position(&self) -> Duration;
/// Attempts to seek to a given position in the current source.
///
/// This blocks between 0 and ~5 milliseconds.
///
/// As long as the duration of the source is known, seek is guaranteed to saturate
/// at the end of the source. For example given a source that reports a total duration
/// of 42 seconds calling `try_seek()` with 60 seconds as argument will seek to
/// 42 seconds.
///
/// # Errors
/// This function will return [`SeekError::NotSupported`] if one of the underlying
/// sources does not support seeking.
///
/// It will return an error if an implementation ran
/// into one during the seek.
///
/// When seeking beyond the end of a source, this
/// function might return an error if the duration of the source is not known.
fn try_seek(&self, pos: Duration) -> Result<(), SeekError>;
/// Pauses playback of this sink.
///
/// No effect if already paused.
/// A paused sink can be resumed with [`play`](Self::play).
fn pause(&self);
/// Toggles playback of the sink.
///
/// If the sink is paused, toggling playback resumes it. If the sink is
/// playing, toggling playback pauses it.
fn toggle_playback(&self) {
if self.is_paused() {
self.play();
} else {
self.pause();
}
}
/// Returns true if the sink is paused.
///
/// Sinks can be paused and resumed using [`pause`](Self::pause) and [`play`](Self::play).
fn is_paused(&self) -> bool;
/// Stops the sink.
///
/// It won't be possible to restart it afterwards.
fn stop(&self);
/// Returns true if this sink has no more sounds to play.
fn empty(&self) -> bool;
/// Returns true if the sink is muted.
fn is_muted(&self) -> bool;
/// Mutes the sink.
///
/// Muting a sink sets the volume to 0. Use [`unmute`](Self::unmute) to
/// unmute the sink and restore the original volume.
fn mute(&mut self);
/// Unmutes the sink.
///
/// Restores the volume to the value it was before it was muted.
fn unmute(&mut self);
/// Toggles whether the sink is muted or not.
fn toggle_mute(&mut self) {
if self.is_muted() {
self.unmute();
} else {
self.mute();
}
}
}
/// Used to control audio during playback.
///
/// Bevy inserts this component onto your entities when it begins playing an audio source.
/// Use [`AudioPlayer`][crate::AudioPlayer] to trigger that to happen.
///
/// You can use this component to modify the playback settings while the audio is playing.
///
/// If this component is removed from an entity, and an [`AudioSource`][crate::AudioSource] is
/// attached to that entity, that [`AudioSource`][crate::AudioSource] will start playing. If
/// that source is unchanged, that translates to the audio restarting.
#[derive(Component)]
pub struct AudioSink {
pub(crate) sink: Sink,
/// Managed volume allows the sink to be muted without losing the user's
/// intended volume setting.
///
/// This is used to restore the volume when [`unmute`](Self::unmute) is
/// called.
///
/// If the sink is not muted, this is `None`.
///
/// If the sink is muted, this is `Some(volume)` where `volume` is the
/// user's intended volume setting, even if the underlying sink's volume is
/// 0.
pub(crate) managed_volume: Option<Volume>,
}
impl AudioSink {
/// Create a new audio sink.
pub fn new(sink: Sink) -> Self {
Self {
sink,
managed_volume: None,
}
}
}
impl AudioSinkPlayback for AudioSink {
fn volume(&self) -> Volume {
self.managed_volume
.unwrap_or_else(|| Volume::Linear(self.sink.volume()))
}
fn set_volume(&mut self, volume: Volume) {
if self.is_muted() {
self.managed_volume = Some(volume);
} else {
self.sink.set_volume(volume.to_linear());
}
}
fn speed(&self) -> f32 {
self.sink.speed()
}
fn set_speed(&self, speed: f32) {
self.sink.set_speed(speed);
}
fn play(&self) {
self.sink.play();
}
fn position(&self) -> Duration {
self.sink.get_pos()
}
fn try_seek(&self, pos: Duration) -> Result<(), SeekError> {
self.sink.try_seek(pos)
}
fn pause(&self) {
self.sink.pause();
}
fn is_paused(&self) -> bool {
self.sink.is_paused()
}
fn stop(&self) {
self.sink.stop();
}
fn empty(&self) -> bool {
self.sink.empty()
}
fn is_muted(&self) -> bool {
self.managed_volume.is_some()
}
fn mute(&mut self) {
self.managed_volume = Some(self.volume());
self.sink.set_volume(0.0);
}
fn unmute(&mut self) {
if let Some(volume) = self.managed_volume.take() {
self.sink.set_volume(volume.to_linear());
}
}
}
/// Used to control spatial audio during playback.
///
/// Bevy inserts this component onto your entities when it begins playing an audio source
/// that's configured to use spatial audio.
///
/// You can use this component to modify the playback settings while the audio is playing.
///
/// If this component is removed from an entity, and a [`AudioSource`][crate::AudioSource] is
/// attached to that entity, that [`AudioSource`][crate::AudioSource] will start playing. If
/// that source is unchanged, that translates to the audio restarting.
#[derive(Component)]
pub struct SpatialAudioSink {
pub(crate) sink: SpatialSink,
/// Managed volume allows the sink to be muted without losing the user's
/// intended volume setting.
///
/// This is used to restore the volume when [`unmute`](Self::unmute) is
/// called.
///
/// If the sink is not muted, this is `None`.
///
/// If the sink is muted, this is `Some(volume)` where `volume` is the
/// user's intended volume setting, even if the underlying sink's volume is
/// 0.
pub(crate) managed_volume: Option<Volume>,
}
impl SpatialAudioSink {
/// Create a new spatial audio sink.
pub fn new(sink: SpatialSink) -> Self {
Self {
sink,
managed_volume: None,
}
}
}
impl AudioSinkPlayback for SpatialAudioSink {
fn volume(&self) -> Volume {
self.managed_volume
.unwrap_or_else(|| Volume::Linear(self.sink.volume()))
}
fn set_volume(&mut self, volume: Volume) {
if self.is_muted() {
self.managed_volume = Some(volume);
} else {
self.sink.set_volume(volume.to_linear());
}
}
fn speed(&self) -> f32 {
self.sink.speed()
}
fn set_speed(&self, speed: f32) {
self.sink.set_speed(speed);
}
fn play(&self) {
self.sink.play();
}
fn position(&self) -> Duration {
self.sink.get_pos()
}
fn try_seek(&self, pos: Duration) -> Result<(), SeekError> {
self.sink.try_seek(pos)
}
fn pause(&self) {
self.sink.pause();
}
fn is_paused(&self) -> bool {
self.sink.is_paused()
}
fn stop(&self) {
self.sink.stop();
}
fn empty(&self) -> bool {
self.sink.empty()
}
fn is_muted(&self) -> bool {
self.managed_volume.is_some()
}
fn mute(&mut self) {
self.managed_volume = Some(self.volume());
self.sink.set_volume(0.0);
}
fn unmute(&mut self) {
if let Some(volume) = self.managed_volume.take() {
self.sink.set_volume(volume.to_linear());
}
}
}
impl SpatialAudioSink {
/// Set the two ears position.
pub fn set_ears_position(&self, left_position: Vec3, right_position: Vec3) {
self.sink.set_left_ear_position(left_position.to_array());
self.sink.set_right_ear_position(right_position.to_array());
}
/// Set the listener position, with an ear on each side separated by `gap`.
pub fn set_listener_position(&self, position: Transform, gap: f32) {
self.set_ears_position(
position.translation + position.left() * gap / 2.0,
position.translation + position.right() * gap / 2.0,
);
}
/// Set the emitter position.
pub fn set_emitter_position(&self, position: Vec3) {
self.sink.set_emitter_position(position.to_array());
}
}
#[cfg(test)]
mod tests {
use rodio::Sink;
use super::*;
fn test_audio_sink_playback<T: AudioSinkPlayback>(mut audio_sink: T) {
// Test volume
assert_eq!(audio_sink.volume(), Volume::Linear(1.0)); // default volume
audio_sink.set_volume(Volume::Linear(0.5));
assert_eq!(audio_sink.volume(), Volume::Linear(0.5));
audio_sink.set_volume(Volume::Linear(1.0));
assert_eq!(audio_sink.volume(), Volume::Linear(1.0));
// Test speed
assert_eq!(audio_sink.speed(), 1.0); // default speed
audio_sink.set_speed(0.5);
assert_eq!(audio_sink.speed(), 0.5);
audio_sink.set_speed(1.0);
assert_eq!(audio_sink.speed(), 1.0);
// Test playback
assert!(!audio_sink.is_paused()); // default pause state
audio_sink.pause();
assert!(audio_sink.is_paused());
audio_sink.play();
assert!(!audio_sink.is_paused());
// Test toggle playback
audio_sink.pause(); // start paused
audio_sink.toggle_playback();
assert!(!audio_sink.is_paused());
audio_sink.toggle_playback();
assert!(audio_sink.is_paused());
// Test mute
assert!(!audio_sink.is_muted()); // default mute state
audio_sink.mute();
assert!(audio_sink.is_muted());
audio_sink.unmute();
assert!(!audio_sink.is_muted());
// Test volume with mute
audio_sink.set_volume(Volume::Linear(0.5));
audio_sink.mute();
assert_eq!(audio_sink.volume(), Volume::Linear(0.5)); // returns managed volume even though sink volume is 0
audio_sink.unmute();
assert_eq!(audio_sink.volume(), Volume::Linear(0.5)); // managed volume is restored
// Test toggle mute
audio_sink.toggle_mute();
assert!(audio_sink.is_muted());
audio_sink.toggle_mute();
assert!(!audio_sink.is_muted());
}
#[test]
fn test_audio_sink() {
let (sink, _queue_rx) = Sink::new_idle();
let audio_sink = AudioSink::new(sink);
test_audio_sink_playback(audio_sink);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_dev_tools/src/picking_debug.rs | crates/bevy_dev_tools/src/picking_debug.rs | //! Text and on-screen debugging tools
use bevy_app::prelude::*;
use bevy_camera::visibility::Visibility;
use bevy_camera::{Camera, RenderTarget};
use bevy_color::prelude::*;
use bevy_ecs::prelude::*;
use bevy_picking::backend::HitData;
use bevy_picking::hover::HoverMap;
use bevy_picking::pointer::{Location, PointerId, PointerInput, PointerLocation, PointerPress};
use bevy_picking::prelude::*;
use bevy_picking::PickingSystems;
use bevy_reflect::prelude::*;
use bevy_text::prelude::*;
use bevy_ui::prelude::*;
use core::cmp::Ordering;
use core::fmt::{Debug, Display, Formatter, Result};
use tracing::{debug, trace};
/// This resource determines the runtime behavior of the debug plugin.
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, Resource)]
pub enum DebugPickingMode {
/// Only log non-noisy events, show the debug overlay.
Normal,
/// Log all events, including noisy events like `Move` and `Drag`, show the debug overlay.
Noisy,
/// Do not show the debug overlay or log any messages.
#[default]
Disabled,
}
impl DebugPickingMode {
/// A condition indicating the plugin is enabled
pub fn is_enabled(this: Res<Self>) -> bool {
matches!(*this, Self::Normal | Self::Noisy)
}
/// A condition indicating the plugin is disabled
pub fn is_disabled(this: Res<Self>) -> bool {
matches!(*this, Self::Disabled)
}
/// A condition indicating the plugin is enabled and in noisy mode
pub fn is_noisy(this: Res<Self>) -> bool {
matches!(*this, Self::Noisy)
}
}
/// Logs events for debugging
///
/// "Normal" events are logged at the `debug` level. "Noisy" events are logged at the `trace` level.
/// See [Bevy's LogPlugin](https://docs.rs/bevy/latest/bevy/log/struct.LogPlugin.html) and [Bevy
/// Cheatbook: Logging, Console Messages](https://bevy-cheatbook.github.io/features/log.html) for
/// details.
///
/// Usually, the default level printed is `info`, so debug and trace messages will not be displayed
/// even when this plugin is active. You can set `RUST_LOG` to change this.
///
/// You can also change the log filter at runtime in your code. The [LogPlugin
/// docs](https://docs.rs/bevy/latest/bevy/log/struct.LogPlugin.html) give an example.
///
/// Use the [`DebugPickingMode`] state resource to control this plugin. Example:
///
/// ```ignore
/// use DebugPickingMode::{Normal, Disabled};
/// app.insert_resource(DebugPickingMode::Normal)
/// .add_systems(
/// PreUpdate,
/// (|mut mode: ResMut<DebugPickingMode>| {
/// *mode = match *mode {
/// DebugPickingMode::Disabled => DebugPickingMode::Normal,
/// _ => DebugPickingMode::Disabled,
/// };
/// })
/// .distributive_run_if(bevy::input::common_conditions::input_just_pressed(
/// KeyCode::F3,
/// )),
/// )
/// ```
/// This sets the starting mode of the plugin to [`DebugPickingMode::Disabled`] and binds the F3 key
/// to toggle it.
#[derive(Debug, Default, Clone)]
pub struct DebugPickingPlugin;
impl Plugin for DebugPickingPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<DebugPickingMode>()
.add_systems(
PreUpdate,
pointer_debug_visibility.in_set(PickingSystems::PostHover),
)
.add_systems(
PreUpdate,
(
// This leaves room to easily change the log-level associated
// with different events, should that be desired.
log_message_debug::<PointerInput>.run_if(DebugPickingMode::is_noisy),
log_pointer_message_debug::<Over>,
log_pointer_message_debug::<Out>,
log_pointer_message_debug::<Press>,
log_pointer_message_debug::<Release>,
log_pointer_message_debug::<Click>,
log_pointer_event_trace::<Move>.run_if(DebugPickingMode::is_noisy),
log_pointer_message_debug::<DragStart>,
log_pointer_event_trace::<Drag>.run_if(DebugPickingMode::is_noisy),
log_pointer_message_debug::<DragEnd>,
log_pointer_message_debug::<DragEnter>,
log_pointer_event_trace::<DragOver>.run_if(DebugPickingMode::is_noisy),
log_pointer_message_debug::<DragLeave>,
log_pointer_message_debug::<DragDrop>,
)
.distributive_run_if(DebugPickingMode::is_enabled)
.in_set(PickingSystems::Last),
);
app.add_systems(
PreUpdate,
(add_pointer_debug, update_debug_data, debug_draw)
.chain()
.distributive_run_if(DebugPickingMode::is_enabled)
.in_set(PickingSystems::Last),
);
}
}
/// Listen for any message and logs it at the debug level
pub fn log_message_debug<M: Message + Debug>(mut events: MessageReader<PointerInput>) {
for event in events.read() {
debug!("{event:?}");
}
}
/// Listens for pointer events of type `E` and logs them at "debug" level
pub fn log_pointer_message_debug<E: Debug + Clone + Reflect>(
mut pointer_reader: MessageReader<Pointer<E>>,
) {
for pointer in pointer_reader.read() {
debug!("{pointer}");
}
}
/// Listens for pointer events of type `E` and logs them at "trace" level
pub fn log_pointer_event_trace<E: Debug + Clone + Reflect>(
mut pointer_reader: MessageReader<Pointer<E>>,
) {
for pointer in pointer_reader.read() {
trace!("{pointer}");
}
}
/// Adds [`PointerDebug`] to pointers automatically.
pub fn add_pointer_debug(
mut commands: Commands,
pointers: Query<Entity, (With<PointerId>, Without<PointerDebug>)>,
) {
for entity in &pointers {
commands.entity(entity).insert(PointerDebug::default());
}
}
/// Hide text from pointers.
pub fn pointer_debug_visibility(
debug: Res<DebugPickingMode>,
mut pointers: Query<&mut Visibility, With<PointerId>>,
) {
let visible = match *debug {
DebugPickingMode::Disabled => Visibility::Hidden,
_ => Visibility::Visible,
};
for mut vis in &mut pointers {
*vis = visible;
}
}
/// Storage for per-pointer debug information.
#[derive(Debug, Component, Clone, Default)]
pub struct PointerDebug {
/// The pointer location.
pub location: Option<Location>,
/// Representation of the different pointer button states.
pub press: PointerPress,
/// List of hit elements to be displayed.
pub hits: Vec<(String, HitData)>,
}
fn bool_to_icon(f: &mut Formatter, prefix: &str, input: bool) -> Result {
write!(f, "{prefix}{}", if input { "[X]" } else { "[ ]" })
}
impl Display for PointerDebug {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
if let Some(location) = &self.location {
writeln!(f, "Location: {:.2?}", location.position)?;
}
bool_to_icon(f, "Pressed: ", self.press.is_primary_pressed())?;
bool_to_icon(f, " ", self.press.is_middle_pressed())?;
bool_to_icon(f, " ", self.press.is_secondary_pressed())?;
let mut sorted_hits = self.hits.clone();
sorted_hits.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(Ordering::Equal));
for (entity, hit) in sorted_hits.iter() {
write!(f, "\nEntity: {entity:?}")?;
if let Some((position, normal)) = hit.position.zip(hit.normal) {
write!(f, ", Position: {position:.2?}, Normal: {normal:.2?}")?;
}
write!(f, ", Depth: {:.2?}", hit.depth)?;
}
Ok(())
}
}
/// Update typed debug data used to draw overlays
pub fn update_debug_data(
hover_map: Res<HoverMap>,
entity_names: Query<NameOrEntity>,
mut pointers: Query<(
&PointerId,
&PointerLocation,
&PointerPress,
&mut PointerDebug,
)>,
) {
for (id, location, press, mut debug) in &mut pointers {
*debug = PointerDebug {
location: location.location().cloned(),
press: press.to_owned(),
hits: hover_map
.get(id)
.iter()
.flat_map(|h| h.iter())
.filter_map(|(e, h)| {
if let Ok(entity_name) = entity_names.get(*e) {
Some((entity_name.to_string(), h.to_owned()))
} else {
None
}
})
.collect(),
};
}
}
/// Draw text on each cursor with debug info
pub fn debug_draw(
mut commands: Commands,
camera_query: Query<(Entity, &Camera, &RenderTarget)>,
primary_window: Query<Entity, With<bevy_window::PrimaryWindow>>,
pointers: Query<(Entity, &PointerId, &PointerDebug)>,
scale: Res<UiScale>,
) {
for (entity, id, debug) in &pointers {
let Some(pointer_location) = &debug.location else {
continue;
};
let text = format!("{id:?}\n{debug}");
for (camera, _, _) in camera_query.iter().filter(|(_, _, render_target)| {
render_target
.normalize(primary_window.single().ok())
.is_some_and(|target| target == pointer_location.target)
}) {
let mut pointer_pos = pointer_location.position;
if let Some(viewport) = camera_query
.get(camera)
.ok()
.and_then(|(_, camera, _)| camera.logical_viewport_rect())
{
pointer_pos -= viewport.min;
}
commands
.entity(entity)
.despawn_related::<Children>()
.insert((
Node {
position_type: PositionType::Absolute,
left: Val::Px(pointer_pos.x + 5.0) / scale.0,
top: Val::Px(pointer_pos.y + 5.0) / scale.0,
padding: UiRect::px(10.0, 10.0, 8.0, 6.0),
..Default::default()
},
BackgroundColor(Color::BLACK.with_alpha(0.75)),
GlobalZIndex(i32::MAX),
Pickable::IGNORE,
UiTargetCamera(camera),
children![(Text::new(text.clone()), TextFont::from_font_size(12.0))],
));
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_dev_tools/src/easy_screenshot.rs | crates/bevy_dev_tools/src/easy_screenshot.rs | #[cfg(feature = "screenrecording")]
use core::time::Duration;
use std::time::{SystemTime, UNIX_EPOCH};
use bevy_app::{App, Plugin, PostUpdate, Update};
use bevy_camera::Camera;
use bevy_ecs::prelude::*;
use bevy_input::{common_conditions::input_just_pressed, keyboard::KeyCode};
use bevy_math::{Quat, StableInterpolate, Vec3};
use bevy_render::view::screenshot::{save_to_disk, Screenshot};
use bevy_time::Time;
use bevy_transform::{components::Transform, TransformSystems};
use bevy_window::{PrimaryWindow, Window};
#[cfg(all(not(target_os = "windows"), feature = "screenrecording"))]
pub use x264::{Preset, Tune};
/// File format the screenshot will be saved in
#[derive(Clone, Copy)]
pub enum ScreenshotFormat {
/// JPEG format
Jpeg,
/// PNG format
Png,
/// BMP format
Bmp,
}
/// Add this plugin to your app to enable easy screenshotting.
///
/// Add this plugin, press the key, and you have a screenshot 🎉
pub struct EasyScreenshotPlugin {
/// Key that will trigger a screenshot
pub trigger: KeyCode,
/// Format of the screenshot
///
/// The corresponding image format must be supported by bevy renderer
pub format: ScreenshotFormat,
}
impl Default for EasyScreenshotPlugin {
fn default() -> Self {
EasyScreenshotPlugin {
trigger: KeyCode::PrintScreen,
format: ScreenshotFormat::Png,
}
}
}
impl Plugin for EasyScreenshotPlugin {
fn build(&self, app: &mut App) {
let format = self.format;
app.add_systems(
Update,
(move |mut commands: Commands, window: Single<&Window, With<PrimaryWindow>>| {
let since_the_epoch = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("time should go forward");
commands
.spawn(Screenshot::primary_window())
.observe(save_to_disk(format!(
"{}-{}.{}",
window.title,
since_the_epoch.as_millis(),
match format {
ScreenshotFormat::Jpeg => "jpg",
ScreenshotFormat::Png => "png",
ScreenshotFormat::Bmp => "bmp",
}
)));
})
.run_if(input_just_pressed(self.trigger)),
);
}
}
/// Placeholder
#[cfg(all(target_os = "windows", feature = "screenrecording"))]
pub enum Preset {
/// Placeholder
Ultrafast,
/// Placeholder
Superfast,
/// Placeholder
Veryfast,
/// Placeholder
Faster,
/// Placeholder
Fast,
/// Placeholder
Medium,
/// Placeholder
Slow,
/// Placeholder
Slower,
/// Placeholder
Veryslow,
/// Placeholder
Placebo,
}
/// Placeholder
#[cfg(all(target_os = "windows", feature = "screenrecording"))]
pub enum Tune {
/// Placeholder
None,
/// Placeholder
Film,
/// Placeholder
Animation,
/// Placeholder
Grain,
/// Placeholder
StillImage,
/// Placeholder
Psnr,
/// Placeholder
Ssim,
}
#[cfg(feature = "screenrecording")]
/// Add this plugin to your app to enable easy screen recording.
pub struct EasyScreenRecordPlugin {
/// The key to toggle recording.
pub toggle: KeyCode,
/// h264 encoder preset
pub preset: Preset,
/// h264 encoder tune
pub tune: Tune,
/// target frame time
pub frame_time: Duration,
}
#[cfg(feature = "screenrecording")]
impl Default for EasyScreenRecordPlugin {
fn default() -> Self {
EasyScreenRecordPlugin {
toggle: KeyCode::Space,
preset: Preset::Medium,
tune: Tune::Animation,
frame_time: Duration::from_millis(33),
}
}
}
#[cfg(feature = "screenrecording")]
/// Controls screen recording
#[derive(Message)]
pub enum RecordScreen {
/// Starts screen recording
Start,
/// Stops screen recording
Stop,
}
#[cfg(feature = "screenrecording")]
impl Plugin for EasyScreenRecordPlugin {
#[cfg_attr(
target_os = "windows",
expect(unused_variables, reason = "not working on windows")
)]
fn build(&self, app: &mut App) {
#[cfg(target_os = "windows")]
{
tracing::warn!("Screen recording is not currently supported on Windows: see https://github.com/bevyengine/bevy/issues/22132");
}
#[cfg(not(target_os = "windows"))]
{
use bevy_image::Image;
use bevy_render::view::screenshot::ScreenshotCaptured;
use bevy_time::Time;
use std::{fs::File, io::Write, sync::mpsc::channel};
use tracing::info;
use x264::{Colorspace, Encoder, Setup};
enum RecordCommand {
Start(String, Preset, Tune),
Stop,
Frame(Image),
}
let (tx, rx) = channel::<RecordCommand>();
let frame_time = self.frame_time;
std::thread::spawn(move || {
let mut encoder: Option<Encoder> = None;
let mut setup = None;
let mut file: Option<File> = None;
let mut frame = 0;
loop {
let Ok(next) = rx.recv() else {
break;
};
match next {
RecordCommand::Start(name, preset, tune) => {
info!("starting recording at {}", name);
file = Some(File::create(name).unwrap());
setup = Some(Setup::preset(preset, tune, false, true).high());
}
RecordCommand::Stop => {
info!("stopping recording");
if let Some(encoder) = encoder.take() {
let mut flush = encoder.flush();
let mut file = file.take().unwrap();
while let Some(result) = flush.next() {
let (data, _) = result.unwrap();
file.write_all(data.entirety()).unwrap();
}
}
}
RecordCommand::Frame(image) => {
if let Some(setup) = setup.take() {
let mut new_encoder = setup
.fps((1000 / frame_time.as_millis()) as u32, 1)
.build(
Colorspace::RGB,
image.width() as i32,
image.height() as i32,
)
.unwrap();
let headers = new_encoder.headers().unwrap();
file.as_mut()
.unwrap()
.write_all(headers.entirety())
.unwrap();
encoder = Some(new_encoder);
}
if let Some(encoder) = encoder.as_mut() {
let pts = (frame_time.as_millis() * frame) as i64;
frame += 1;
let (data, _) = encoder
.encode(
pts,
x264::Image::rgb(
image.width() as i32,
image.height() as i32,
&image.try_into_dynamic().unwrap().to_rgb8(),
),
)
.unwrap();
file.as_mut().unwrap().write_all(data.entirety()).unwrap();
}
}
}
}
});
let frame_time = self.frame_time;
app.add_message::<RecordScreen>().add_systems(
Update,
(
(move |mut messages: MessageWriter<RecordScreen>,
mut recording: Local<bool>| {
*recording = !*recording;
if *recording {
messages.write(RecordScreen::Start);
} else {
messages.write(RecordScreen::Stop);
}
})
.run_if(input_just_pressed(self.toggle)),
{
let tx = tx.clone();
let preset = self.preset;
let tune = self.tune;
move |mut commands: Commands,
mut recording: Local<bool>,
mut messages: MessageReader<RecordScreen>,
window: Single<&Window, With<PrimaryWindow>>,
current_screenshot: Query<(), With<Screenshot>>,
mut virtual_time: ResMut<Time<bevy_time::Virtual>>| {
match messages.read().last() {
Some(RecordScreen::Start) => {
let since_the_epoch = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("time should go forward");
let filename = format!(
"{}-{}.h264",
window.title,
since_the_epoch.as_millis(),
);
tx.send(RecordCommand::Start(filename, preset, tune))
.unwrap();
*recording = true;
virtual_time.pause();
}
Some(RecordScreen::Stop) => {
tx.send(RecordCommand::Stop).unwrap();
*recording = false;
virtual_time.unpause();
}
_ => {}
}
if *recording && current_screenshot.single().is_err() {
let tx = tx.clone();
commands.spawn(Screenshot::primary_window()).observe(
move |screenshot_captured: On<ScreenshotCaptured>,
mut virtual_time: ResMut<Time<bevy_time::Virtual>>,
mut time: ResMut<Time<()>>| {
let img = screenshot_captured.image.clone();
tx.send(RecordCommand::Frame(img)).unwrap();
virtual_time.advance_by(frame_time);
*time = virtual_time.as_generic();
},
);
}
}
},
)
.chain(),
);
}
}
}
/// Plugin to move the camera smoothly according to the current time
pub struct EasyCameraMovementPlugin {
/// Decay rate for the camera movement
pub decay_rate: f32,
}
impl Default for EasyCameraMovementPlugin {
fn default() -> Self {
Self { decay_rate: 1.0 }
}
}
/// Move the camera to the given position
#[derive(Component)]
pub struct CameraMovement {
/// Target position for the camera movement
pub translation: Vec3,
/// Target rotation for the camera movement
pub rotation: Quat,
}
impl Plugin for EasyCameraMovementPlugin {
fn build(&self, app: &mut App) {
let decay_rate = self.decay_rate;
app.add_systems(
PostUpdate,
(move |mut query: Single<(&mut Transform, &CameraMovement), With<Camera>>,
time: Res<Time>| {
{
{
let target = query.1;
query.0.translation.smooth_nudge(
&target.translation,
decay_rate,
time.delta_secs(),
);
query.0.rotation.smooth_nudge(
&target.rotation,
decay_rate,
time.delta_secs(),
);
}
}
})
.before(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_dev_tools/src/fps_overlay.rs | crates/bevy_dev_tools/src/fps_overlay.rs | //! Module containing logic for FPS overlay.
use bevy_app::{Plugin, Startup, Update};
use bevy_asset::Assets;
use bevy_color::Color;
use bevy_diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin};
use bevy_ecs::{
component::Component,
entity::Entity,
query::{With, Without},
reflect::ReflectResource,
resource::Resource,
schedule::{common_conditions::resource_changed, IntoScheduleConfigs},
system::{Commands, Query, Res, ResMut, Single},
};
use bevy_picking::Pickable;
use bevy_reflect::Reflect;
use bevy_render::storage::ShaderStorageBuffer;
use bevy_text::{TextColor, TextFont, TextSpan};
use bevy_time::common_conditions::on_timer;
use bevy_ui::{
widget::{Text, TextUiWriter},
FlexDirection, GlobalZIndex, Node, PositionType, Val,
};
#[cfg(not(all(target_arch = "wasm32", not(feature = "webgpu"))))]
use bevy_ui_render::prelude::MaterialNode;
use core::time::Duration;
use tracing::warn;
#[cfg(not(all(target_arch = "wasm32", not(feature = "webgpu"))))]
use crate::frame_time_graph::FrameTimeGraphConfigUniform;
use crate::frame_time_graph::{FrameTimeGraphPlugin, FrametimeGraphMaterial};
/// [`GlobalZIndex`] used to render the fps overlay.
///
/// We use a number slightly under `i32::MAX` so you can render on top of it if you really need to.
pub const FPS_OVERLAY_ZINDEX: i32 = i32::MAX - 32;
// Warn the user if the interval is below this threshold.
const MIN_SAFE_INTERVAL: Duration = Duration::from_millis(50);
// Used to scale the frame time graph based on the fps text size
const FRAME_TIME_GRAPH_WIDTH_SCALE: f32 = 6.0;
const FRAME_TIME_GRAPH_HEIGHT_SCALE: f32 = 2.0;
/// A plugin that adds an FPS overlay to the Bevy application.
///
/// This plugin will add the [`FrameTimeDiagnosticsPlugin`] if it wasn't added before.
///
/// Note: It is recommended to use native overlay of rendering statistics when possible for lower overhead and more accurate results.
/// The correct way to do this will vary by platform:
/// - **Metal**: setting env variable `MTL_HUD_ENABLED=1`
#[derive(Default)]
pub struct FpsOverlayPlugin {
/// Starting configuration of overlay, this can be later be changed through [`FpsOverlayConfig`] resource.
pub config: FpsOverlayConfig,
}
impl Plugin for FpsOverlayPlugin {
fn build(&self, app: &mut bevy_app::App) {
// TODO: Use plugin dependencies, see https://github.com/bevyengine/bevy/issues/69
if !app.is_plugin_added::<FrameTimeDiagnosticsPlugin>() {
app.add_plugins(FrameTimeDiagnosticsPlugin::default());
}
if !app.is_plugin_added::<FrameTimeGraphPlugin>() {
app.add_plugins(FrameTimeGraphPlugin);
}
if self.config.refresh_interval < MIN_SAFE_INTERVAL {
warn!(
"Low refresh interval ({:?}) may degrade performance. \
Min recommended: {:?}.",
self.config.refresh_interval, MIN_SAFE_INTERVAL
);
}
app.insert_resource(self.config.clone())
.add_systems(Startup, setup)
.add_systems(
Update,
(
(toggle_display, customize_overlay)
.run_if(resource_changed::<FpsOverlayConfig>),
update_text.run_if(on_timer(self.config.refresh_interval)),
),
);
}
}
/// Configuration options for the FPS overlay.
#[derive(Resource, Clone, Reflect)]
#[reflect(Resource)]
pub struct FpsOverlayConfig {
/// Configuration of text in the overlay.
pub text_config: TextFont,
/// Color of text in the overlay.
pub text_color: Color,
/// Displays the FPS overlay if true.
pub enabled: bool,
/// The period after which the FPS overlay re-renders.
///
/// Defaults to once every 100 ms.
pub refresh_interval: Duration,
/// Configuration of the frame time graph
pub frame_time_graph_config: FrameTimeGraphConfig,
}
impl Default for FpsOverlayConfig {
fn default() -> Self {
FpsOverlayConfig {
text_config: TextFont::from_font_size(32.),
text_color: Color::WHITE,
enabled: true,
refresh_interval: Duration::from_millis(100),
// TODO set this to display refresh rate if possible
frame_time_graph_config: FrameTimeGraphConfig::target_fps(60.0),
}
}
}
/// Configuration of the frame time graph
#[derive(Clone, Copy, Reflect)]
pub struct FrameTimeGraphConfig {
/// Is the graph visible
pub enabled: bool,
/// The minimum acceptable FPS
///
/// Anything below this will show a red bar
pub min_fps: f32,
/// The target FPS
///
/// Anything above this will show a green bar
pub target_fps: f32,
}
impl FrameTimeGraphConfig {
/// Constructs a default config for a given target fps
pub fn target_fps(target_fps: f32) -> Self {
Self {
target_fps,
..Self::default()
}
}
}
impl Default for FrameTimeGraphConfig {
fn default() -> Self {
Self {
enabled: true,
min_fps: 30.0,
target_fps: 60.0,
}
}
}
#[derive(Component)]
struct FpsText;
#[derive(Component)]
struct FrameTimeGraph;
fn setup(
mut commands: Commands,
overlay_config: Res<FpsOverlayConfig>,
#[cfg_attr(
all(target_arch = "wasm32", not(feature = "webgpu")),
expect(unused, reason = "Unused variables in wasm32 without webgpu feature")
)]
(mut frame_time_graph_materials, mut buffers): (
ResMut<Assets<FrametimeGraphMaterial>>,
ResMut<Assets<ShaderStorageBuffer>>,
),
) {
commands
.spawn((
Node {
// We need to make sure the overlay doesn't affect the position of other UI nodes
position_type: PositionType::Absolute,
flex_direction: FlexDirection::Column,
..Default::default()
},
// Render overlay on top of everything
GlobalZIndex(FPS_OVERLAY_ZINDEX),
Pickable::IGNORE,
))
.with_children(|p| {
p.spawn((
Text::new("FPS: "),
overlay_config.text_config.clone(),
TextColor(overlay_config.text_color),
FpsText,
Pickable::IGNORE,
))
.with_child((TextSpan::default(), overlay_config.text_config.clone()));
#[cfg(all(target_arch = "wasm32", not(feature = "webgpu")))]
{
if overlay_config.frame_time_graph_config.enabled {
use tracing::warn;
warn!("Frame time graph is not supported with WebGL. Consider if WebGPU is viable for your usecase.");
}
}
#[cfg(not(all(target_arch = "wasm32", not(feature = "webgpu"))))]
{
let font_size = overlay_config.text_config.font_size;
p.spawn((
Node {
width: Val::Px(font_size * FRAME_TIME_GRAPH_WIDTH_SCALE),
height: Val::Px(font_size * FRAME_TIME_GRAPH_HEIGHT_SCALE),
display: if overlay_config.frame_time_graph_config.enabled {
bevy_ui::Display::DEFAULT
} else {
bevy_ui::Display::None
},
..Default::default()
},
Pickable::IGNORE,
MaterialNode::from(frame_time_graph_materials.add(FrametimeGraphMaterial {
values: buffers.add(ShaderStorageBuffer {
// Initialize with dummy data because the default (`data: None`) will
// cause a panic in the shader if the frame time graph is constructed
// with `enabled: false`.
data: Some(vec![0, 0, 0, 0]),
..Default::default()
}),
config: FrameTimeGraphConfigUniform::new(
overlay_config.frame_time_graph_config.target_fps,
overlay_config.frame_time_graph_config.min_fps,
true,
),
})),
FrameTimeGraph,
));
}
});
}
fn update_text(
diagnostic: Res<DiagnosticsStore>,
query: Query<Entity, With<FpsText>>,
mut writer: TextUiWriter,
) {
if let Ok(entity) = query.single()
&& let Some(fps) = diagnostic.get(&FrameTimeDiagnosticsPlugin::FPS)
&& let Some(value) = fps.smoothed()
{
*writer.text(entity, 1) = format!("{value:.2}");
}
}
fn customize_overlay(
overlay_config: Res<FpsOverlayConfig>,
query: Query<Entity, With<FpsText>>,
mut writer: TextUiWriter,
) {
for entity in &query {
writer.for_each_font(entity, |mut font| {
*font = overlay_config.text_config.clone();
});
writer.for_each_color(entity, |mut color| color.0 = overlay_config.text_color);
}
}
fn toggle_display(
overlay_config: Res<FpsOverlayConfig>,
mut text_node: Single<&mut Node, (With<FpsText>, Without<FrameTimeGraph>)>,
mut graph_node: Single<&mut Node, (With<FrameTimeGraph>, Without<FpsText>)>,
) {
if overlay_config.enabled {
text_node.display = bevy_ui::Display::DEFAULT;
} else {
text_node.display = bevy_ui::Display::None;
}
if overlay_config.frame_time_graph_config.enabled {
// Scale the frame time graph based on the font size of the overlay
let font_size = overlay_config.text_config.font_size;
graph_node.width = Val::Px(font_size * FRAME_TIME_GRAPH_WIDTH_SCALE);
graph_node.height = Val::Px(font_size * FRAME_TIME_GRAPH_HEIGHT_SCALE);
graph_node.display = bevy_ui::Display::DEFAULT;
} else {
graph_node.display = bevy_ui::Display::None;
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_dev_tools/src/lib.rs | crates/bevy_dev_tools/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"
)]
//! This crate provides additional utilities for the [Bevy game engine](https://bevy.org),
//! focused on improving developer experience.
#[cfg(feature = "bevy_ci_testing")]
pub mod ci_testing;
mod easy_screenshot;
pub mod fps_overlay;
pub mod frame_time_graph;
pub mod picking_debug;
pub mod states;
pub use easy_screenshot::*;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_dev_tools/src/states.rs | crates/bevy_dev_tools/src/states.rs | //! Tools for debugging states.
use bevy_ecs::message::MessageReader;
use bevy_state::state::{StateTransitionEvent, States};
use tracing::info;
/// Logs state transitions into console.
///
/// This system is provided to make debugging easier by tracking state changes.
pub fn log_transitions<S: States>(mut transitions: MessageReader<StateTransitionEvent<S>>) {
// State internals can generate at most one event (of type) per frame.
let Some(transition) = transitions.read().last() else {
return;
};
let name = core::any::type_name::<S>();
let StateTransitionEvent {
exited,
entered,
allow_same_state_transitions,
} = transition;
let skip_text = if exited == entered && !*allow_same_state_transitions {
" (disallowing same-state transitions)"
} else {
""
};
info!("{name} transition: {exited:?} => {entered:?}{skip_text}");
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_dev_tools/src/ci_testing/config.rs | crates/bevy_dev_tools/src/ci_testing/config.rs | use bevy_ecs::prelude::*;
use bevy_math::{Quat, Vec3};
use serde::Deserialize;
/// A configuration struct for automated CI testing.
///
/// It gets used when the `bevy_ci_testing` feature is enabled to automatically
/// exit a Bevy app when run through the CI. This is needed because otherwise
/// Bevy apps would be stuck in the game loop and wouldn't allow the CI to progress.
#[derive(Deserialize, Resource, PartialEq, Debug, Default, Clone)]
pub struct CiTestingConfig {
/// The setup for this test.
#[serde(default)]
pub setup: CiTestingSetup,
/// Events to send, with their associated frame.
#[serde(default)]
pub events: Vec<CiTestingEventOnFrame>,
}
/// Setup for a test.
#[derive(Deserialize, Default, PartialEq, Debug, Clone)]
pub struct CiTestingSetup {
/// The amount of time in seconds between frame updates.
///
/// This is set through the [`TimeUpdateStrategy::ManualDuration`] resource.
///
/// [`TimeUpdateStrategy::ManualDuration`]: bevy_time::TimeUpdateStrategy::ManualDuration
pub fixed_frame_time: Option<f32>,
}
/// An event to send at a given frame, used for CI testing.
#[derive(Deserialize, PartialEq, Debug, Clone)]
pub struct CiTestingEventOnFrame(pub u32, pub CiTestingEvent);
/// An event to send, used for CI testing.
#[derive(Deserialize, PartialEq, Debug, Clone)]
pub enum CiTestingEvent {
/// Takes a screenshot of the entire screen, and saves the results to
/// `screenshot-{current_frame}.png`.
Screenshot,
/// Takes a screenshot of the entire screen, saves the results to
/// `screenshot-{current_frame}.png`, and exits once the screenshot is taken.
ScreenshotAndExit,
/// Takes a screenshot of the entire screen, and saves the results to
/// `screenshot-{name}.png`.
NamedScreenshot(String),
/// Stops the program by sending [`AppExit::Success`].
///
/// [`AppExit::Success`]: bevy_app::AppExit::Success
AppExit,
/// Starts recording the screen.
StartScreenRecording,
/// Stops recording the screen.
StopScreenRecording,
/// Smoothly moves the camera to the given position.
MoveCamera {
/// Position to move the camera to.
translation: Vec3,
/// Rotation to move the camera to.
rotation: Quat,
},
/// Sends a [`CiTestingCustomEvent`] using the given [`String`].
Custom(String),
}
/// A custom event that can be configured from a configuration file for CI testing.
#[derive(Message)]
pub struct CiTestingCustomEvent(pub String);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deserialize() {
const INPUT: &str = r#"
(
setup: (
fixed_frame_time: Some(0.03),
),
events: [
(100, Custom("Hello, world!")),
(200, Screenshot),
(300, AppExit),
],
)"#;
let expected = CiTestingConfig {
setup: CiTestingSetup {
fixed_frame_time: Some(0.03),
},
events: vec![
CiTestingEventOnFrame(100, CiTestingEvent::Custom("Hello, world!".into())),
CiTestingEventOnFrame(200, CiTestingEvent::Screenshot),
CiTestingEventOnFrame(300, CiTestingEvent::AppExit),
],
};
let config: CiTestingConfig = ron::from_str(INPUT).unwrap();
assert_eq!(config, expected);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_dev_tools/src/ci_testing/systems.rs | crates/bevy_dev_tools/src/ci_testing/systems.rs | use crate::CameraMovement;
use super::config::*;
use bevy_app::AppExit;
use bevy_camera::Camera;
use bevy_ecs::prelude::*;
use bevy_render::view::screenshot::{save_to_disk, Screenshot};
use tracing::{debug, info};
pub(crate) fn send_events(world: &mut World, mut current_frame: Local<u32>) {
let mut config = world.resource_mut::<CiTestingConfig>();
// Take all events for the current frame, leaving all the remaining alone.
let events = core::mem::take(&mut config.events);
let (to_run, remaining): (Vec<_>, _) = events
.into_iter()
.partition(|event| event.0 == *current_frame);
config.events = remaining;
for CiTestingEventOnFrame(_, event) in to_run {
debug!("Handling event: {:?}", event);
match event {
CiTestingEvent::AppExit => {
world.write_message(AppExit::Success);
info!("Exiting after {} frames. Test successful!", *current_frame);
}
CiTestingEvent::ScreenshotAndExit => {
let this_frame = *current_frame;
world.spawn(Screenshot::primary_window()).observe(
move |captured: On<bevy_render::view::screenshot::ScreenshotCaptured>,
mut app_exit_writer: MessageWriter<AppExit>| {
let path = format!("./screenshot-{this_frame}.png");
save_to_disk(path)(captured);
info!("Exiting. Test successful!");
app_exit_writer.write(AppExit::Success);
},
);
info!("Took a screenshot at frame {}.", *current_frame);
}
CiTestingEvent::Screenshot => {
let path = format!("./screenshot-{}.png", *current_frame);
world
.spawn(Screenshot::primary_window())
.observe(save_to_disk(path));
info!("Took a screenshot at frame {}.", *current_frame);
}
CiTestingEvent::NamedScreenshot(name) => {
let path = format!("./screenshot-{name}.png");
world
.spawn(Screenshot::primary_window())
.observe(save_to_disk(path));
info!(
"Took a screenshot at frame {} for {}.",
*current_frame, name
);
}
CiTestingEvent::StartScreenRecording => {
info!("Started recording screen at frame {}.", *current_frame);
#[cfg(feature = "screenrecording")]
world.write_message(crate::RecordScreen::Start);
}
CiTestingEvent::StopScreenRecording => {
info!("Stopped recording screen at frame {}.", *current_frame);
#[cfg(feature = "screenrecording")]
world.write_message(crate::RecordScreen::Stop);
}
CiTestingEvent::MoveCamera {
translation,
rotation,
} => {
info!("Moved camera at frame {}.", *current_frame);
if let Ok(camera) = world.query_filtered::<Entity, With<Camera>>().single(world) {
world.entity_mut(camera).insert(CameraMovement {
translation,
rotation,
});
}
}
// Custom events are forwarded to the world.
CiTestingEvent::Custom(event_string) => {
world.write_message(CiTestingCustomEvent(event_string));
}
}
}
*current_frame += 1;
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_dev_tools/src/ci_testing/mod.rs | crates/bevy_dev_tools/src/ci_testing/mod.rs | //! Utilities for testing in CI environments.
mod config;
mod systems;
use crate::EasyCameraMovementPlugin;
#[cfg(feature = "screenrecording")]
use crate::EasyScreenRecordPlugin;
pub use self::config::*;
use bevy_app::prelude::*;
use bevy_ecs::prelude::*;
use bevy_render::view::screenshot::trigger_screenshots;
use bevy_time::TimeUpdateStrategy;
use core::time::Duration;
/// A plugin that instruments continuous integration testing by automatically executing user-defined actions.
///
/// This plugin reads a [`ron`] file specified with the `CI_TESTING_CONFIG` environmental variable
/// (`ci_testing_config.ron` by default) and executes its specified actions. For a reference of the
/// allowed configuration, see [`CiTestingConfig`].
///
/// This plugin is included within `DefaultPlugins` and `MinimalPlugins`
/// when the `bevy_ci_testing` feature is enabled.
/// It is recommended to only used this plugin during testing (manual or
/// automatic), and disable it during regular development and for production builds.
#[derive(Default)]
pub struct CiTestingPlugin;
impl Plugin for CiTestingPlugin {
fn build(&self, app: &mut App) {
let config = if !app.world().is_resource_added::<CiTestingConfig>() {
// Load configuration from file if not already setup
#[cfg(not(target_arch = "wasm32"))]
let config: CiTestingConfig = {
let filename = std::env::var("CI_TESTING_CONFIG")
.unwrap_or_else(|_| "ci_testing_config.ron".to_string());
std::fs::read_to_string(filename)
.map(|content| {
ron::from_str(&content)
.expect("error deserializing CI testing configuration file")
})
.unwrap_or_default()
};
#[cfg(target_arch = "wasm32")]
let config: CiTestingConfig = {
let config = include_str!("../../../../ci_testing_config.ron");
ron::from_str(config).expect("error deserializing CI testing configuration file")
};
config
} else {
app.world().resource::<CiTestingConfig>().clone()
};
// Add the `EasyCameraMovementPlugin` to the app if it's not already added.
// To configure the movement speed, add the plugin first.
if !app.is_plugin_added::<EasyCameraMovementPlugin>() {
app.add_plugins(EasyCameraMovementPlugin::default());
}
// Add the `EasyScreenRecordPlugin` to the app if it's not already added and one of the event is starting screenrecording.
// To configure the recording quality, add the plugin first.
#[cfg(feature = "screenrecording")]
if !app.is_plugin_added::<EasyScreenRecordPlugin>()
&& config
.events
.iter()
.any(|e| matches!(e.1, CiTestingEvent::StartScreenRecording))
{
app.add_plugins(EasyScreenRecordPlugin::default());
}
// Configure a fixed frame time if specified.
if let Some(fixed_frame_time) = config.setup.fixed_frame_time {
app.insert_resource(TimeUpdateStrategy::ManualDuration(Duration::from_secs_f32(
fixed_frame_time,
)));
}
app.add_message::<CiTestingCustomEvent>()
.insert_resource(config)
.add_systems(
Update,
systems::send_events
.before(trigger_screenshots)
.before(bevy_window::close_when_requested)
.in_set(EventSenderSystems)
.ambiguous_with_all(),
);
// The offending system does not exist in the wasm32 target.
// As a result, we must conditionally order the two systems using a system set.
#[cfg(any(unix, windows))]
app.configure_sets(
Update,
EventSenderSystems.before(bevy_app::TerminalCtrlCHandlerPlugin::exit_on_flag),
);
}
}
#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
struct EventSenderSystems;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_dev_tools/src/frame_time_graph/mod.rs | crates/bevy_dev_tools/src/frame_time_graph/mod.rs | //! Module containing logic for the frame time graph
use bevy_app::{Plugin, Update};
use bevy_asset::{load_internal_asset, uuid_handle, Asset, Assets, Handle};
use bevy_diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin};
use bevy_ecs::system::{Res, ResMut};
use bevy_math::ops::log2;
use bevy_reflect::TypePath;
use bevy_render::{
render_resource::{AsBindGroup, ShaderType},
storage::ShaderStorageBuffer,
};
use bevy_shader::{Shader, ShaderRef};
use bevy_ui_render::prelude::{UiMaterial, UiMaterialPlugin};
use crate::fps_overlay::FpsOverlayConfig;
const FRAME_TIME_GRAPH_SHADER_HANDLE: Handle<Shader> =
uuid_handle!("4e38163a-5782-47a5-af52-d9161472ab59");
/// Plugin that sets up everything to render the frame time graph material
pub struct FrameTimeGraphPlugin;
impl Plugin for FrameTimeGraphPlugin {
fn build(&self, app: &mut bevy_app::App) {
load_internal_asset!(
app,
FRAME_TIME_GRAPH_SHADER_HANDLE,
"frame_time_graph.wgsl",
Shader::from_wgsl
);
// TODO: Use plugin dependencies, see https://github.com/bevyengine/bevy/issues/69
if !app.is_plugin_added::<FrameTimeDiagnosticsPlugin>() {
panic!("Requires FrameTimeDiagnosticsPlugin");
// app.add_plugins(FrameTimeDiagnosticsPlugin);
}
app.add_plugins(UiMaterialPlugin::<FrametimeGraphMaterial>::default())
.add_systems(Update, update_frame_time_values);
}
}
/// The config values sent to the frame time graph shader
#[derive(Debug, Clone, Copy, ShaderType)]
pub struct FrameTimeGraphConfigUniform {
// minimum expected delta time
dt_min: f32,
// maximum expected delta time
dt_max: f32,
dt_min_log2: f32,
dt_max_log2: f32,
// controls whether or not the bars width are proportional to their delta time
proportional_width: u32,
}
impl FrameTimeGraphConfigUniform {
/// `proportional_width`: controls whether or not the bars width are proportional to their delta time
pub fn new(target_fps: f32, min_fps: f32, proportional_width: bool) -> Self {
// we want an upper limit that is above the target otherwise the bars will disappear
let dt_min = 1. / (target_fps * 1.2);
let dt_max = 1. / min_fps;
Self {
dt_min,
dt_max,
dt_min_log2: log2(dt_min),
dt_max_log2: log2(dt_max),
proportional_width: u32::from(proportional_width),
}
}
}
/// The material used to render the frame time graph ui node
#[derive(AsBindGroup, Asset, TypePath, Debug, Clone)]
pub struct FrametimeGraphMaterial {
/// The history of the previous frame times value.
///
/// This should be updated every frame to match the frame time history from the [`DiagnosticsStore`]
#[storage(0, read_only)]
pub values: Handle<ShaderStorageBuffer>, // Vec<f32>,
/// The configuration values used by the shader to control how the graph is rendered
#[uniform(1)]
pub config: FrameTimeGraphConfigUniform,
}
impl UiMaterial for FrametimeGraphMaterial {
fn fragment_shader() -> ShaderRef {
FRAME_TIME_GRAPH_SHADER_HANDLE.into()
}
}
/// A system that updates the frame time values sent to the frame time graph
fn update_frame_time_values(
mut frame_time_graph_materials: ResMut<Assets<FrametimeGraphMaterial>>,
mut buffers: ResMut<Assets<ShaderStorageBuffer>>,
diagnostics_store: Res<DiagnosticsStore>,
config: Option<Res<FpsOverlayConfig>>,
) {
if !config.is_none_or(|c| c.frame_time_graph_config.enabled) {
return;
}
let Some(frame_time) = diagnostics_store.get(&FrameTimeDiagnosticsPlugin::FRAME_TIME) else {
return;
};
let frame_times = frame_time
.values()
// convert to millis
.map(|x| *x as f32 / 1000.0)
.collect::<Vec<_>>();
for (_, material) in frame_time_graph_materials.iter_mut() {
let buffer = buffers.get_mut(&material.values).unwrap();
buffer.set_data(frame_times.clone());
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_image/src/ktx2.rs | crates/bevy_image/src/ktx2.rs | #[cfg(any(feature = "flate2", feature = "zstd_rust"))]
use std::io::Read;
#[cfg(feature = "basis-universal")]
use basis_universal::{
DecodeFlags, LowLevelUastcTranscoder, SliceParametersUastc, TranscoderBlockFormat,
};
use bevy_color::Srgba;
use bevy_utils::default;
#[cfg(any(feature = "flate2", feature = "zstd_rust", feature = "zstd_c"))]
use ktx2::SupercompressionScheme;
use ktx2::{
ChannelTypeQualifiers, ColorModel, DfdBlockBasic, DfdBlockHeaderBasic, DfdHeader, Header,
SampleInformation,
};
use wgpu_types::{
AstcBlock, AstcChannel, Extent3d, TextureDimension, TextureFormat, TextureViewDescriptor,
TextureViewDimension,
};
use super::{CompressedImageFormats, DataFormat, Image, TextureError, TranscodeFormat};
#[cfg(feature = "ktx2")]
pub fn ktx2_buffer_to_image(
buffer: &[u8],
supported_compressed_formats: CompressedImageFormats,
is_srgb: bool,
) -> Result<Image, TextureError> {
let ktx2 = ktx2::Reader::new(buffer)
.map_err(|err| TextureError::InvalidData(format!("Failed to parse ktx2 file: {err:?}")))?;
let Header {
pixel_width: width,
pixel_height: height,
pixel_depth: depth,
layer_count,
face_count,
level_count,
supercompression_scheme,
..
} = ktx2.header();
let layer_count = layer_count.max(1);
let face_count = face_count.max(1);
let depth = depth.max(1);
// Handle supercompression
let mut levels: Vec<Vec<u8>>;
if let Some(supercompression_scheme) = supercompression_scheme {
match supercompression_scheme {
#[cfg(feature = "flate2")]
SupercompressionScheme::ZLIB => {
levels = Vec::with_capacity(ktx2.levels().len());
for (level_index, level) in ktx2.levels().enumerate() {
let mut decoder = flate2::bufread::ZlibDecoder::new(level.data);
let mut decompressed = Vec::new();
decoder.read_to_end(&mut decompressed).map_err(|err| {
TextureError::SuperDecompressionError(format!(
"Failed to decompress {supercompression_scheme:?} for mip {level_index}: {err:?}",
))
})?;
levels.push(decompressed);
}
}
#[cfg(all(feature = "zstd_rust", not(feature = "zstd_c")))]
SupercompressionScheme::Zstandard => {
levels = Vec::with_capacity(ktx2.levels().len());
for (level_index, level) in ktx2.levels().enumerate() {
let mut cursor = std::io::Cursor::new(level.data);
let mut decoder = ruzstd::decoding::StreamingDecoder::new(&mut cursor)
.map_err(|err| TextureError::SuperDecompressionError(err.to_string()))?;
let mut decompressed = Vec::new();
decoder.read_to_end(&mut decompressed).map_err(|err| {
TextureError::SuperDecompressionError(format!(
"Failed to decompress {supercompression_scheme:?} for mip {level_index}: {err:?}",
))
})?;
levels.push(decompressed);
}
}
#[cfg(feature = "zstd_c")]
SupercompressionScheme::Zstandard => {
levels = Vec::with_capacity(ktx2.levels().len());
for (level_index, level) in ktx2.levels().enumerate() {
levels.push(zstd::decode_all(level.data).map_err(|err| {
TextureError::SuperDecompressionError(format!(
"Failed to decompress {supercompression_scheme:?} for mip {level_index}: {err:?}",
))
})?);
}
}
_ => {
return Err(TextureError::SuperDecompressionError(format!(
"Unsupported supercompression scheme: {supercompression_scheme:?}",
)));
}
}
} else {
levels = ktx2.levels().map(|level| level.data.to_vec()).collect();
}
// Identify the format
let texture_format = ktx2_get_texture_format(&ktx2, is_srgb).or_else(|error| match error {
// Transcode if needed and supported
TextureError::FormatRequiresTranscodingError(transcode_format) => {
let mut transcoded = vec![Vec::default(); levels.len()];
let texture_format = match transcode_format {
TranscodeFormat::R8UnormSrgb => {
let (mut original_width, mut original_height) = (width, height);
for (level, level_data) in levels.iter().enumerate() {
transcoded[level] = level_data
.iter()
.copied()
.map(|v| (Srgba::gamma_function(v as f32 / 255.) * 255.).floor() as u8)
.collect::<Vec<u8>>();
// Next mip dimensions are half the current, minimum 1x1
original_width = (original_width / 2).max(1);
original_height = (original_height / 2).max(1);
}
TextureFormat::R8Unorm
}
TranscodeFormat::Rg8UnormSrgb => {
let (mut original_width, mut original_height) = (width, height);
for (level, level_data) in levels.iter().enumerate() {
transcoded[level] = level_data
.iter()
.copied()
.map(|v| (Srgba::gamma_function(v as f32 / 255.) * 255.).floor() as u8)
.collect::<Vec<u8>>();
// Next mip dimensions are half the current, minimum 1x1
original_width = (original_width / 2).max(1);
original_height = (original_height / 2).max(1);
}
TextureFormat::Rg8Unorm
}
TranscodeFormat::Rgb8 => {
let mut rgba = vec![255u8; width as usize * height as usize * 4];
for (level, level_data) in levels.iter().enumerate() {
let n_pixels = (width as usize >> level).max(1) * (height as usize >> level).max(1);
let mut offset = 0;
for _layer in 0..layer_count {
for _face in 0..face_count {
for i in 0..n_pixels {
rgba[i * 4] = level_data[offset];
rgba[i * 4 + 1] = level_data[offset + 1];
rgba[i * 4 + 2] = level_data[offset + 2];
offset += 3;
}
transcoded[level].extend_from_slice(&rgba[0..n_pixels * 4]);
}
}
}
if is_srgb {
TextureFormat::Rgba8UnormSrgb
} else {
TextureFormat::Rgba8Unorm
}
}
#[cfg(feature = "basis-universal")]
TranscodeFormat::Uastc(data_format) => {
let (transcode_block_format, texture_format) =
get_transcoded_formats(supported_compressed_formats, data_format, is_srgb);
let texture_format_info = texture_format;
let (block_width_pixels, block_height_pixels) = (
texture_format_info.block_dimensions().0,
texture_format_info.block_dimensions().1,
);
// Texture is not a depth or stencil format, it is possible to pass `None` and unwrap
let block_bytes = texture_format_info.block_copy_size(None).unwrap();
let transcoder = LowLevelUastcTranscoder::new();
for (level, level_data) in levels.iter().enumerate() {
let (level_width, level_height) = (
(width >> level as u32).max(1),
(height >> level as u32).max(1),
);
let (num_blocks_x, num_blocks_y) = (
level_width.div_ceil(block_width_pixels) .max(1),
level_height.div_ceil(block_height_pixels) .max(1),
);
let level_bytes = (num_blocks_x * num_blocks_y * block_bytes) as usize;
let mut offset = 0;
for _layer in 0..layer_count {
for _face in 0..face_count {
// NOTE: SliceParametersUastc does not implement Clone nor Copy so
// it has to be created per use
let slice_parameters = SliceParametersUastc {
num_blocks_x,
num_blocks_y,
has_alpha: false,
original_width: level_width,
original_height: level_height,
};
transcoder
.transcode_slice(
&level_data[offset..(offset + level_bytes)],
slice_parameters,
DecodeFlags::HIGH_QUALITY,
transcode_block_format,
)
.map(|mut transcoded_level| transcoded[level].append(&mut transcoded_level))
.map_err(|error| {
TextureError::SuperDecompressionError(format!(
"Failed to transcode mip level {level} from UASTC to {transcode_block_format:?}: {error:?}",
))
})?;
offset += level_bytes;
}
}
}
texture_format
}
// ETC1S is a subset of ETC1 which is a subset of ETC2
// TODO: Implement transcoding
TranscodeFormat::Etc1s => {
let texture_format = if is_srgb {
TextureFormat::Etc2Rgb8UnormSrgb
} else {
TextureFormat::Etc2Rgb8Unorm
};
if !supported_compressed_formats.supports(texture_format) {
return Err(error);
}
transcoded = levels.to_vec();
texture_format
}
#[cfg(not(feature = "basis-universal"))]
_ => return Err(error),
};
levels = transcoded;
Ok(texture_format)
}
_ => Err(error),
})?;
if !supported_compressed_formats.supports(texture_format) {
return Err(TextureError::UnsupportedTextureFormat(format!(
"Format not supported by this GPU: {texture_format:?}",
)));
}
// Collect all level data into a contiguous buffer
let mut image_data = Vec::new();
image_data.reserve_exact(levels.iter().map(Vec::len).sum());
levels.iter().for_each(|level| image_data.extend(level));
// Assign the data and fill in the rest of the metadata now the possible
// error cases have been handled
let mut image = Image::default();
image.texture_descriptor.format = texture_format;
image.data = Some(image_data);
image.data_order = wgpu_types::TextureDataOrder::MipMajor;
// Note: we must give wgpu the logical texture dimensions, so it can correctly compute mip sizes.
// However this currently causes wgpu to panic if the dimensions arent a multiple of blocksize.
// See https://github.com/gfx-rs/wgpu/issues/7677 for more context.
image.texture_descriptor.size = Extent3d {
width,
height,
depth_or_array_layers: if layer_count > 1 || face_count > 1 {
layer_count * face_count
} else {
depth
}
.max(1),
};
image.texture_descriptor.mip_level_count = level_count;
image.texture_descriptor.dimension = if depth > 1 {
TextureDimension::D3
} else if image.is_compressed() || height > 1 {
TextureDimension::D2
} else {
TextureDimension::D1
};
let mut dimension = None;
if face_count == 6 {
dimension = Some(if layer_count > 1 {
TextureViewDimension::CubeArray
} else {
TextureViewDimension::Cube
});
} else if layer_count > 1 {
dimension = Some(TextureViewDimension::D2Array);
} else if depth > 1 {
dimension = Some(TextureViewDimension::D3);
}
if dimension.is_some() {
image.texture_view_descriptor = Some(TextureViewDescriptor {
dimension,
..default()
});
}
Ok(image)
}
#[cfg(feature = "basis-universal")]
pub fn get_transcoded_formats(
supported_compressed_formats: CompressedImageFormats,
data_format: DataFormat,
is_srgb: bool,
) -> (TranscoderBlockFormat, TextureFormat) {
match data_format {
DataFormat::Rrr => {
if supported_compressed_formats.contains(CompressedImageFormats::BC) {
(TranscoderBlockFormat::BC4, TextureFormat::Bc4RUnorm)
} else if supported_compressed_formats.contains(CompressedImageFormats::ETC2) {
(
TranscoderBlockFormat::ETC2_EAC_R11,
TextureFormat::EacR11Unorm,
)
} else {
(TranscoderBlockFormat::RGBA32, TextureFormat::R8Unorm)
}
}
DataFormat::Rrrg | DataFormat::Rg => {
if supported_compressed_formats.contains(CompressedImageFormats::BC) {
(TranscoderBlockFormat::BC5, TextureFormat::Bc5RgUnorm)
} else if supported_compressed_formats.contains(CompressedImageFormats::ETC2) {
(
TranscoderBlockFormat::ETC2_EAC_RG11,
TextureFormat::EacRg11Unorm,
)
} else {
(TranscoderBlockFormat::RGBA32, TextureFormat::Rg8Unorm)
}
}
// NOTE: Rgba16Float should be transcoded to BC6H/ASTC_HDR. Neither are supported by
// basis-universal, nor is ASTC_HDR supported by wgpu
DataFormat::Rgb | DataFormat::Rgba => {
// NOTE: UASTC can be losslessly transcoded to ASTC4x4 and ASTC uses the same
// space as BC7 (128-bits per 4x4 texel block) so prefer ASTC over BC for
// transcoding speed and quality.
if supported_compressed_formats.contains(CompressedImageFormats::ASTC_LDR) {
(
TranscoderBlockFormat::ASTC_4x4,
TextureFormat::Astc {
block: AstcBlock::B4x4,
channel: if is_srgb {
AstcChannel::UnormSrgb
} else {
AstcChannel::Unorm
},
},
)
} else if supported_compressed_formats.contains(CompressedImageFormats::BC) {
(
TranscoderBlockFormat::BC7,
if is_srgb {
TextureFormat::Bc7RgbaUnormSrgb
} else {
TextureFormat::Bc7RgbaUnorm
},
)
} else if supported_compressed_formats.contains(CompressedImageFormats::ETC2) {
(
TranscoderBlockFormat::ETC2_RGBA,
if is_srgb {
TextureFormat::Etc2Rgba8UnormSrgb
} else {
TextureFormat::Etc2Rgba8Unorm
},
)
} else {
(
TranscoderBlockFormat::RGBA32,
if is_srgb {
TextureFormat::Rgba8UnormSrgb
} else {
TextureFormat::Rgba8Unorm
},
)
}
}
}
}
#[cfg(feature = "ktx2")]
pub fn ktx2_get_texture_format<Data: AsRef<[u8]>>(
ktx2: &ktx2::Reader<Data>,
is_srgb: bool,
) -> Result<TextureFormat, TextureError> {
if let Some(format) = ktx2.header().format {
return ktx2_format_to_texture_format(format, is_srgb);
}
for data_format_descriptor in ktx2.dfd_blocks() {
if data_format_descriptor.header == DfdHeader::BASIC {
let basic_data_format_descriptor = DfdBlockBasic::parse(data_format_descriptor.data)
.map_err(|err| TextureError::InvalidData(format!("KTX2: {err:?}")))?;
let sample_information = basic_data_format_descriptor
.sample_information()
.collect::<Vec<_>>();
return ktx2_dfd_header_to_texture_format(
&basic_data_format_descriptor.header,
&sample_information,
is_srgb,
);
}
}
Err(TextureError::UnsupportedTextureFormat(
"Unknown".to_string(),
))
}
enum DataType {
Unorm,
UnormSrgb,
Snorm,
Float,
Uint,
Sint,
}
// This can be obtained from core::mem::transmute::<f32, u32>(1.0f32). It is used for identifying
// normalized sample types as in Unorm or Snorm.
const F32_1_AS_U32: u32 = 1065353216;
fn sample_information_to_data_type(
sample: &SampleInformation,
is_srgb: bool,
) -> Result<DataType, TextureError> {
// Exponent flag not supported
if sample
.channel_type_qualifiers
.contains(ChannelTypeQualifiers::EXPONENT)
{
return Err(TextureError::UnsupportedTextureFormat(
"Unsupported KTX2 channel type qualifier: exponent".to_string(),
));
}
Ok(
if sample
.channel_type_qualifiers
.contains(ChannelTypeQualifiers::FLOAT)
{
// If lower bound of range is 0 then unorm, else if upper bound is 1.0f32 as u32
if sample
.channel_type_qualifiers
.contains(ChannelTypeQualifiers::SIGNED)
{
if sample.upper == F32_1_AS_U32 {
DataType::Snorm
} else {
DataType::Float
}
} else if is_srgb {
DataType::UnormSrgb
} else {
DataType::Unorm
}
} else if sample
.channel_type_qualifiers
.contains(ChannelTypeQualifiers::SIGNED)
{
DataType::Sint
} else {
DataType::Uint
},
)
}
#[cfg(feature = "ktx2")]
pub fn ktx2_dfd_header_to_texture_format(
data_format_descriptor: &DfdBlockHeaderBasic,
sample_information: &[SampleInformation],
is_srgb: bool,
) -> Result<TextureFormat, TextureError> {
Ok(match data_format_descriptor.color_model {
Some(ColorModel::RGBSDA) => {
match sample_information.len() {
1 => {
// Only red channel allowed
if sample_information[0].channel_type != 0 {
return Err(TextureError::UnsupportedTextureFormat(
"Only red-component single-component KTX2 RGBSDA formats supported"
.to_string(),
));
}
let sample = &sample_information[0];
let data_type = sample_information_to_data_type(sample, false)?;
match sample.bit_length.get() {
8 => match data_type {
DataType::Unorm => TextureFormat::R8Unorm,
DataType::UnormSrgb => {
return Err(TextureError::UnsupportedTextureFormat(
"UnormSrgb not supported for R8".to_string(),
));
}
DataType::Snorm => TextureFormat::R8Snorm,
DataType::Float => {
return Err(TextureError::UnsupportedTextureFormat(
"Float not supported for R8".to_string(),
));
}
DataType::Uint => TextureFormat::R8Uint,
DataType::Sint => TextureFormat::R8Sint,
},
16 => match data_type {
DataType::Unorm => TextureFormat::R16Unorm,
DataType::UnormSrgb => {
return Err(TextureError::UnsupportedTextureFormat(
"UnormSrgb not supported for R16".to_string(),
));
}
DataType::Snorm => TextureFormat::R16Snorm,
DataType::Float => TextureFormat::R16Float,
DataType::Uint => TextureFormat::R16Uint,
DataType::Sint => TextureFormat::R16Sint,
},
32 => match data_type {
DataType::Unorm => {
return Err(TextureError::UnsupportedTextureFormat(
"Unorm not supported for R32".to_string(),
));
}
DataType::UnormSrgb => {
return Err(TextureError::UnsupportedTextureFormat(
"UnormSrgb not supported for R32".to_string(),
));
}
DataType::Snorm => {
return Err(TextureError::UnsupportedTextureFormat(
"Snorm not supported for R32".to_string(),
));
}
DataType::Float => TextureFormat::R32Float,
DataType::Uint => TextureFormat::R32Uint,
DataType::Sint => TextureFormat::R32Sint,
},
v => {
return Err(TextureError::UnsupportedTextureFormat(format!(
"Unsupported sample bit length for RGBSDA 1-channel format: {v}",
)));
}
}
}
2 => {
// Only red and green channels allowed
if sample_information[0].channel_type != 0
|| sample_information[1].channel_type != 1
{
return Err(TextureError::UnsupportedTextureFormat(
"Only red-green-component two-component KTX2 RGBSDA formats supported"
.to_string(),
));
}
// Only same bit length for all channels
assert_eq!(
sample_information[0].bit_length,
sample_information[1].bit_length
);
// Only same channel type qualifiers for all channels
assert_eq!(
sample_information[0].channel_type_qualifiers,
sample_information[1].channel_type_qualifiers
);
// Only same sample range for all channels
assert_eq!(sample_information[0].lower, sample_information[1].lower);
assert_eq!(sample_information[0].upper, sample_information[1].upper);
let sample = &sample_information[0];
let data_type = sample_information_to_data_type(sample, false)?;
match sample.bit_length.get() {
8 => match data_type {
DataType::Unorm => TextureFormat::Rg8Unorm,
DataType::UnormSrgb => {
return Err(TextureError::UnsupportedTextureFormat(
"UnormSrgb not supported for Rg8".to_string(),
));
}
DataType::Snorm => TextureFormat::Rg8Snorm,
DataType::Float => {
return Err(TextureError::UnsupportedTextureFormat(
"Float not supported for Rg8".to_string(),
));
}
DataType::Uint => TextureFormat::Rg8Uint,
DataType::Sint => TextureFormat::Rg8Sint,
},
16 => match data_type {
DataType::Unorm => TextureFormat::Rg16Unorm,
DataType::UnormSrgb => {
return Err(TextureError::UnsupportedTextureFormat(
"UnormSrgb not supported for Rg16".to_string(),
));
}
DataType::Snorm => TextureFormat::Rg16Snorm,
DataType::Float => TextureFormat::Rg16Float,
DataType::Uint => TextureFormat::Rg16Uint,
DataType::Sint => TextureFormat::Rg16Sint,
},
32 => match data_type {
DataType::Unorm => {
return Err(TextureError::UnsupportedTextureFormat(
"Unorm not supported for Rg32".to_string(),
));
}
DataType::UnormSrgb => {
return Err(TextureError::UnsupportedTextureFormat(
"UnormSrgb not supported for Rg32".to_string(),
));
}
DataType::Snorm => {
return Err(TextureError::UnsupportedTextureFormat(
"Snorm not supported for Rg32".to_string(),
));
}
DataType::Float => TextureFormat::Rg32Float,
DataType::Uint => TextureFormat::Rg32Uint,
DataType::Sint => TextureFormat::Rg32Sint,
},
v => {
return Err(TextureError::UnsupportedTextureFormat(format!(
"Unsupported sample bit length for RGBSDA 2-channel format: {v}",
)));
}
}
}
3 => {
if sample_information[0].channel_type == 0
&& sample_information[0].bit_length.get() == 11
&& sample_information[1].channel_type == 1
&& sample_information[1].bit_length.get() == 11
&& sample_information[2].channel_type == 2
&& sample_information[2].bit_length.get() == 10
{
TextureFormat::Rg11b10Ufloat
} else if sample_information[0].channel_type == 0
&& sample_information[0].bit_length.get() == 9
&& sample_information[1].channel_type == 1
&& sample_information[1].bit_length.get() == 9
&& sample_information[2].channel_type == 2
&& sample_information[2].bit_length.get() == 9
{
TextureFormat::Rgb9e5Ufloat
} else if sample_information[0].channel_type == 0
&& sample_information[0].bit_length.get() == 8
&& sample_information[1].channel_type == 1
&& sample_information[1].bit_length.get() == 8
&& sample_information[2].channel_type == 2
&& sample_information[2].bit_length.get() == 8
{
return Err(TextureError::FormatRequiresTranscodingError(
TranscodeFormat::Rgb8,
));
} else {
return Err(TextureError::UnsupportedTextureFormat(
"3-component formats not supported".to_string(),
));
}
}
4 => {
// Only RGBA or BGRA channels allowed
let is_rgba = sample_information[0].channel_type == 0;
assert!(
sample_information[0].channel_type == 0
|| sample_information[0].channel_type == 2
);
assert_eq!(sample_information[1].channel_type, 1);
assert_eq!(
sample_information[2].channel_type,
if is_rgba { 2 } else { 0 }
);
assert_eq!(sample_information[3].channel_type, 15);
// Handle one special packed format
if sample_information[0].bit_length.get() == 10
&& sample_information[1].bit_length.get() == 10
&& sample_information[2].bit_length.get() == 10
&& sample_information[3].bit_length.get() == 2
{
return Ok(TextureFormat::Rgb10a2Unorm);
}
// Only same bit length for all channels
assert!(
sample_information[0].bit_length == sample_information[1].bit_length
&& sample_information[0].bit_length == sample_information[2].bit_length
&& sample_information[0].bit_length == sample_information[3].bit_length
);
assert!(
sample_information[0].lower == sample_information[1].lower
&& sample_information[0].lower == sample_information[2].lower
&& sample_information[0].lower == sample_information[3].lower
);
assert!(
sample_information[0].upper == sample_information[1].upper
&& sample_information[0].upper == sample_information[2].upper
&& sample_information[0].upper == sample_information[3].upper
);
let sample = &sample_information[0];
let data_type = sample_information_to_data_type(sample, is_srgb)?;
match sample.bit_length.get() {
8 => match data_type {
DataType::Unorm => {
if is_rgba {
TextureFormat::Rgba8Unorm
} else {
TextureFormat::Bgra8Unorm
}
}
DataType::UnormSrgb => {
if is_rgba {
TextureFormat::Rgba8UnormSrgb
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_image/src/image_loader.rs | crates/bevy_image/src/image_loader.rs | use crate::{
image::{Image, ImageFormat, ImageType, TextureError},
TextureReinterpretationError,
};
use bevy_asset::{io::Reader, AssetLoader, LoadContext, RenderAssetUsages};
use bevy_reflect::TypePath;
use thiserror::Error;
use super::{CompressedImageFormats, ImageSampler};
use serde::{Deserialize, Serialize};
/// Loader for images that can be read by the `image` crate.
#[derive(Clone, TypePath)]
pub struct ImageLoader {
supported_compressed_formats: CompressedImageFormats,
}
impl ImageLoader {
/// Full list of supported formats.
pub const SUPPORTED_FORMATS: &'static [ImageFormat] = &[
#[cfg(feature = "basis-universal")]
ImageFormat::Basis,
#[cfg(feature = "bmp")]
ImageFormat::Bmp,
#[cfg(feature = "dds")]
ImageFormat::Dds,
#[cfg(feature = "ff")]
ImageFormat::Farbfeld,
#[cfg(feature = "gif")]
ImageFormat::Gif,
#[cfg(feature = "ico")]
ImageFormat::Ico,
#[cfg(feature = "jpeg")]
ImageFormat::Jpeg,
#[cfg(feature = "ktx2")]
ImageFormat::Ktx2,
#[cfg(feature = "png")]
ImageFormat::Png,
#[cfg(feature = "pnm")]
ImageFormat::Pnm,
#[cfg(feature = "qoi")]
ImageFormat::Qoi,
#[cfg(feature = "tga")]
ImageFormat::Tga,
#[cfg(feature = "tiff")]
ImageFormat::Tiff,
#[cfg(feature = "webp")]
ImageFormat::WebP,
];
/// Total count of file extensions, for computing supported file extensions list.
const COUNT_FILE_EXTENSIONS: usize = {
let mut count = 0;
let mut idx = 0;
while idx < Self::SUPPORTED_FORMATS.len() {
count += Self::SUPPORTED_FORMATS[idx].to_file_extensions().len();
idx += 1;
}
count
};
/// Gets the list of file extensions for all formats.
pub const SUPPORTED_FILE_EXTENSIONS: &'static [&'static str] = &{
let mut exts = [""; Self::COUNT_FILE_EXTENSIONS];
let mut ext_idx = 0;
let mut fmt_idx = 0;
while fmt_idx < Self::SUPPORTED_FORMATS.len() {
let mut off = 0;
let fmt_exts = Self::SUPPORTED_FORMATS[fmt_idx].to_file_extensions();
while off < fmt_exts.len() {
exts[ext_idx] = fmt_exts[off];
off += 1;
ext_idx += 1;
}
fmt_idx += 1;
}
exts
};
/// Creates a new image loader that supports the provided formats.
pub fn new(supported_compressed_formats: CompressedImageFormats) -> Self {
Self {
supported_compressed_formats,
}
}
}
/// How to determine an image's format when loading.
#[derive(Serialize, Deserialize, Default, Debug, Clone)]
pub enum ImageFormatSetting {
/// Determine the image format from its file extension.
///
/// This is the default.
#[default]
FromExtension,
/// Declare the image format explicitly.
Format(ImageFormat),
/// Guess the image format by looking for magic bytes at the
/// beginning of its data.
Guess,
}
/// How to interpret the image as an array of textures.
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub enum ImageArrayLayout {
/// Interpret the image as a vertical stack of *n* images.
RowCount { rows: u32 },
/// Interpret the image as a vertical stack of images, each *n* pixels tall.
RowHeight { pixels: u32 },
}
/// Settings for loading an [`Image`] using an [`ImageLoader`].
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ImageLoaderSettings {
/// How to determine the image's container format.
pub format: ImageFormatSetting,
/// Forcibly use a specific [`wgpu_types::TextureFormat`].
/// Useful to control how data is handled when used
/// in a shader.
/// Ex: data that would be `R16Uint` that needs to
/// be sampled as a float using `R16Snorm`.
#[serde(skip)]
pub texture_format: Option<wgpu_types::TextureFormat>,
/// Specifies whether image data is linear
/// or in sRGB space when this is not determined by
/// the image format.
pub is_srgb: bool,
/// [`ImageSampler`] to use when rendering - this does
/// not affect the loading of the image data.
pub sampler: ImageSampler,
/// Where the asset will be used - see the docs on
/// [`RenderAssetUsages`] for details.
pub asset_usage: RenderAssetUsages,
/// Interpret the image as an array of images. This is
/// primarily for use with the `texture2DArray` shader
/// uniform type.
#[serde(default)]
pub array_layout: Option<ImageArrayLayout>,
}
impl Default for ImageLoaderSettings {
fn default() -> Self {
Self {
format: ImageFormatSetting::default(),
texture_format: None,
is_srgb: true,
sampler: ImageSampler::Default,
asset_usage: RenderAssetUsages::default(),
array_layout: None,
}
}
}
/// An error when loading an image using [`ImageLoader`].
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum ImageLoaderError {
/// An error occurred while trying to load the image bytes.
#[error("Failed to load image bytes: {0}")]
Io(#[from] std::io::Error),
/// An error occurred while trying to decode the image bytes.
#[error("Could not load texture file: {0}")]
FileTexture(#[from] FileTextureError),
/// An error occurred while trying to interpret the image bytes as an array texture.
#[error("Invalid array layout: {0}")]
ArrayLayout(#[from] TextureReinterpretationError),
}
impl AssetLoader for ImageLoader {
type Asset = Image;
type Settings = ImageLoaderSettings;
type Error = ImageLoaderError;
async fn load(
&self,
reader: &mut dyn Reader,
settings: &ImageLoaderSettings,
load_context: &mut LoadContext<'_>,
) -> Result<Image, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let image_type = match settings.format {
ImageFormatSetting::FromExtension => {
// use the file extension for the image type
let ext = load_context
.path()
.path()
.extension()
.unwrap()
.to_str()
.unwrap();
ImageType::Extension(ext)
}
ImageFormatSetting::Format(format) => ImageType::Format(format),
ImageFormatSetting::Guess => {
let format = image::guess_format(&bytes).map_err(|err| FileTextureError {
error: err.into(),
path: format!("{}", load_context.path().path().display()),
})?;
ImageType::Format(ImageFormat::from_image_crate_format(format).ok_or_else(
|| FileTextureError {
error: TextureError::UnsupportedTextureFormat(format!("{format:?}")),
path: format!("{}", load_context.path().path().display()),
},
)?)
}
};
let mut image = Image::from_buffer(
&bytes,
image_type,
self.supported_compressed_formats,
settings.is_srgb,
settings.sampler.clone(),
settings.asset_usage,
)
.map_err(|err| FileTextureError {
error: err,
path: format!("{}", load_context.path().path().display()),
})?;
if let Some(format) = settings.texture_format {
image.texture_descriptor.format = format;
}
if let Some(array_layout) = settings.array_layout {
let layers = match array_layout {
ImageArrayLayout::RowCount { rows } => rows,
ImageArrayLayout::RowHeight { pixels } => image.height() / pixels,
};
image.reinterpret_stacked_2d_as_array(layers)?;
}
Ok(image)
}
fn extensions(&self) -> &[&str] {
Self::SUPPORTED_FILE_EXTENSIONS
}
}
/// An error that occurs when loading a texture from a file.
#[derive(Error, Debug)]
#[error("Error reading image file {path}: {error}.")]
pub struct FileTextureError {
error: TextureError,
path: String,
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_image/src/lib.rs | crates/bevy_image/src/lib.rs | #![expect(missing_docs, reason = "Not all docs are written yet, see #3492.")]
extern crate alloc;
pub mod prelude {
pub use crate::{
dynamic_texture_atlas_builder::DynamicTextureAtlasBuilder,
texture_atlas::{TextureAtlas, TextureAtlasLayout, TextureAtlasSources},
BevyDefault as _, Image, ImageFormat, ImagePlugin, TextureAtlasBuilder, TextureError,
};
}
#[cfg(all(feature = "zstd", not(feature = "zstd_rust"), not(feature = "zstd_c")))]
compile_error!(
"Choosing a zstd backend is required for zstd support. Please enable either the \"zstd_rust\" or the \"zstd_c\" feature."
);
mod image;
pub use self::image::*;
#[cfg(feature = "serialize")]
mod serialized_image;
#[cfg(feature = "serialize")]
pub use self::serialized_image::*;
#[cfg(feature = "basis-universal")]
mod basis;
#[cfg(feature = "compressed_image_saver")]
mod compressed_image_saver;
#[cfg(feature = "dds")]
mod dds;
mod dynamic_texture_atlas_builder;
#[cfg(feature = "exr")]
mod exr_texture_loader;
#[cfg(feature = "hdr")]
mod hdr_texture_loader;
mod image_loader;
#[cfg(feature = "ktx2")]
mod ktx2;
mod texture_atlas;
mod texture_atlas_builder;
#[cfg(feature = "compressed_image_saver")]
pub use compressed_image_saver::*;
#[cfg(feature = "dds")]
pub use dds::*;
pub use dynamic_texture_atlas_builder::*;
#[cfg(feature = "exr")]
pub use exr_texture_loader::*;
#[cfg(feature = "hdr")]
pub use hdr_texture_loader::*;
pub use image_loader::*;
#[cfg(feature = "ktx2")]
pub use ktx2::*;
pub use texture_atlas::*;
pub use texture_atlas_builder::*;
pub(crate) mod image_texture_conversion;
pub use image_texture_conversion::IntoDynamicImageError;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_image/src/image.rs | crates/bevy_image/src/image.rs | use crate::ImageLoader;
#[cfg(feature = "basis-universal")]
use super::basis::*;
#[cfg(feature = "dds")]
use super::dds::*;
#[cfg(feature = "ktx2")]
use super::ktx2::*;
use bevy_app::{App, Plugin};
#[cfg(not(feature = "bevy_reflect"))]
use bevy_reflect::TypePath;
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
use bevy_asset::{uuid_handle, Asset, AssetApp, Assets, Handle, RenderAssetUsages};
use bevy_color::{Color, ColorToComponents, Gray, LinearRgba, Srgba, Xyza};
use bevy_ecs::resource::Resource;
use bevy_math::{AspectRatio, UVec2, UVec3, Vec2};
use core::hash::Hash;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use wgpu_types::{
AddressMode, CompareFunction, Extent3d, Features, FilterMode, SamplerBorderColor,
SamplerDescriptor, TextureDataOrder, TextureDescriptor, TextureDimension, TextureFormat,
TextureUsages, TextureViewDescriptor,
};
/// Trait used to provide default values for Bevy-external types that
/// do not implement [`Default`].
pub trait BevyDefault {
/// Returns the default value for a type.
fn bevy_default() -> Self;
}
impl BevyDefault for TextureFormat {
fn bevy_default() -> Self {
TextureFormat::Rgba8UnormSrgb
}
}
/// Trait used to provide texture srgb view formats with static lifetime for `TextureDescriptor.view_formats`.
pub trait TextureSrgbViewFormats {
/// Returns the srgb view formats for a type.
fn srgb_view_formats(&self) -> &'static [TextureFormat];
}
impl TextureSrgbViewFormats for TextureFormat {
/// Returns the srgb view formats if the format has an srgb variant, otherwise returns an empty slice.
///
/// The return result covers all the results of [`TextureFormat::add_srgb_suffix`](wgpu_types::TextureFormat::add_srgb_suffix).
fn srgb_view_formats(&self) -> &'static [TextureFormat] {
match self {
TextureFormat::Rgba8Unorm => &[TextureFormat::Rgba8UnormSrgb],
TextureFormat::Bgra8Unorm => &[TextureFormat::Bgra8UnormSrgb],
TextureFormat::Bc1RgbaUnorm => &[TextureFormat::Bc1RgbaUnormSrgb],
TextureFormat::Bc2RgbaUnorm => &[TextureFormat::Bc2RgbaUnormSrgb],
TextureFormat::Bc3RgbaUnorm => &[TextureFormat::Bc3RgbaUnormSrgb],
TextureFormat::Bc7RgbaUnorm => &[TextureFormat::Bc7RgbaUnormSrgb],
TextureFormat::Etc2Rgb8Unorm => &[TextureFormat::Etc2Rgb8UnormSrgb],
TextureFormat::Etc2Rgb8A1Unorm => &[TextureFormat::Etc2Rgb8A1UnormSrgb],
TextureFormat::Etc2Rgba8Unorm => &[TextureFormat::Etc2Rgba8UnormSrgb],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B4x4,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B4x4,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B5x4,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B5x4,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B5x5,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B5x5,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B6x5,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B6x5,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B6x6,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B6x6,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B8x5,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B8x5,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B8x6,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B8x6,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B8x8,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B8x8,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B10x5,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B10x5,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B10x6,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B10x6,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B10x8,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B10x8,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B10x10,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B10x10,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B12x10,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B12x10,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
TextureFormat::Astc {
block: wgpu_types::AstcBlock::B12x12,
channel: wgpu_types::AstcChannel::Unorm,
} => &[TextureFormat::Astc {
block: wgpu_types::AstcBlock::B12x12,
channel: wgpu_types::AstcChannel::UnormSrgb,
}],
_ => &[],
}
}
}
/// A handle to a 1 x 1 transparent white image.
///
/// Like [`Handle<Image>::default`], this is a handle to a fallback image asset.
/// While that handle points to an opaque white 1 x 1 image, this handle points to a transparent 1 x 1 white image.
// Number randomly selected by fair WolframAlpha query. Totally arbitrary.
pub const TRANSPARENT_IMAGE_HANDLE: Handle<Image> =
uuid_handle!("d18ad97e-a322-4981-9505-44c59a4b5e46");
/// Adds the [`Image`] as an asset and makes sure that they are extracted and prepared for the GPU.
pub struct ImagePlugin {
/// The default image sampler to use when [`ImageSampler`] is set to `Default`.
pub default_sampler: ImageSamplerDescriptor,
}
impl Default for ImagePlugin {
fn default() -> Self {
ImagePlugin::default_linear()
}
}
impl ImagePlugin {
/// Creates image settings with linear sampling by default.
pub fn default_linear() -> ImagePlugin {
ImagePlugin {
default_sampler: ImageSamplerDescriptor::linear(),
}
}
/// Creates image settings with nearest sampling by default.
pub fn default_nearest() -> ImagePlugin {
ImagePlugin {
default_sampler: ImageSamplerDescriptor::nearest(),
}
}
}
impl Plugin for ImagePlugin {
fn build(&self, app: &mut App) {
#[cfg(feature = "exr")]
app.init_asset_loader::<crate::ExrTextureLoader>();
#[cfg(feature = "hdr")]
app.init_asset_loader::<crate::HdrTextureLoader>();
app.init_asset::<Image>();
#[cfg(feature = "bevy_reflect")]
app.register_asset_reflect::<Image>();
let mut image_assets = app.world_mut().resource_mut::<Assets<Image>>();
image_assets
.insert(&Handle::default(), Image::default())
.unwrap();
image_assets
.insert(&TRANSPARENT_IMAGE_HANDLE, Image::transparent())
.unwrap();
#[cfg(feature = "compressed_image_saver")]
if let Some(processor) = app
.world()
.get_resource::<bevy_asset::processor::AssetProcessor>()
{
processor.register_processor::<bevy_asset::processor::LoadTransformAndSave<
ImageLoader,
bevy_asset::transformer::IdentityAssetTransformer<Image>,
crate::CompressedImageSaver,
>>(crate::CompressedImageSaver.into());
processor.set_default_processor::<bevy_asset::processor::LoadTransformAndSave<
ImageLoader,
bevy_asset::transformer::IdentityAssetTransformer<Image>,
crate::CompressedImageSaver,
>>("png");
}
app.preregister_asset_loader::<ImageLoader>(ImageLoader::SUPPORTED_FILE_EXTENSIONS);
}
}
pub const TEXTURE_ASSET_INDEX: u64 = 0;
pub const SAMPLER_ASSET_INDEX: u64 = 1;
#[derive(Debug, Serialize, Deserialize, Copy, Clone)]
pub enum ImageFormat {
#[cfg(feature = "basis-universal")]
Basis,
#[cfg(feature = "bmp")]
Bmp,
#[cfg(feature = "dds")]
Dds,
#[cfg(feature = "ff")]
Farbfeld,
#[cfg(feature = "gif")]
Gif,
#[cfg(feature = "exr")]
OpenExr,
#[cfg(feature = "hdr")]
Hdr,
#[cfg(feature = "ico")]
Ico,
#[cfg(feature = "jpeg")]
Jpeg,
#[cfg(feature = "ktx2")]
Ktx2,
#[cfg(feature = "png")]
Png,
#[cfg(feature = "pnm")]
Pnm,
#[cfg(feature = "qoi")]
Qoi,
#[cfg(feature = "tga")]
Tga,
#[cfg(feature = "tiff")]
Tiff,
#[cfg(feature = "webp")]
WebP,
}
macro_rules! feature_gate {
($feature: tt, $value: ident) => {{
#[cfg(not(feature = $feature))]
{
tracing::warn!("feature \"{}\" is not enabled", $feature);
return None;
}
#[cfg(feature = $feature)]
ImageFormat::$value
}};
}
impl ImageFormat {
/// Gets the file extensions for a given format.
pub const fn to_file_extensions(&self) -> &'static [&'static str] {
match self {
#[cfg(feature = "basis-universal")]
ImageFormat::Basis => &["basis"],
#[cfg(feature = "bmp")]
ImageFormat::Bmp => &["bmp"],
#[cfg(feature = "dds")]
ImageFormat::Dds => &["dds"],
#[cfg(feature = "ff")]
ImageFormat::Farbfeld => &["ff", "farbfeld"],
#[cfg(feature = "gif")]
ImageFormat::Gif => &["gif"],
#[cfg(feature = "exr")]
ImageFormat::OpenExr => &["exr"],
#[cfg(feature = "hdr")]
ImageFormat::Hdr => &["hdr"],
#[cfg(feature = "ico")]
ImageFormat::Ico => &["ico"],
#[cfg(feature = "jpeg")]
ImageFormat::Jpeg => &["jpg", "jpeg"],
#[cfg(feature = "ktx2")]
ImageFormat::Ktx2 => &["ktx2"],
#[cfg(feature = "pnm")]
ImageFormat::Pnm => &["pam", "pbm", "pgm", "ppm"],
#[cfg(feature = "png")]
ImageFormat::Png => &["png"],
#[cfg(feature = "qoi")]
ImageFormat::Qoi => &["qoi"],
#[cfg(feature = "tga")]
ImageFormat::Tga => &["tga"],
#[cfg(feature = "tiff")]
ImageFormat::Tiff => &["tif", "tiff"],
#[cfg(feature = "webp")]
ImageFormat::WebP => &["webp"],
// FIXME: https://github.com/rust-lang/rust/issues/129031
#[expect(
clippy::allow_attributes,
reason = "`unreachable_patterns` may not always lint"
)]
#[allow(
unreachable_patterns,
reason = "The wildcard pattern will be unreachable if all formats are enabled; otherwise, it will be reachable"
)]
_ => &[],
}
}
/// Gets the MIME types for a given format.
///
/// If a format doesn't have any dedicated MIME types, this list will be empty.
pub const fn to_mime_types(&self) -> &'static [&'static str] {
match self {
#[cfg(feature = "basis-universal")]
ImageFormat::Basis => &["image/basis", "image/x-basis"],
#[cfg(feature = "bmp")]
ImageFormat::Bmp => &["image/bmp", "image/x-bmp"],
#[cfg(feature = "dds")]
ImageFormat::Dds => &["image/vnd-ms.dds"],
#[cfg(feature = "hdr")]
ImageFormat::Hdr => &["image/vnd.radiance"],
#[cfg(feature = "gif")]
ImageFormat::Gif => &["image/gif"],
#[cfg(feature = "ff")]
ImageFormat::Farbfeld => &[],
#[cfg(feature = "ico")]
ImageFormat::Ico => &["image/x-icon"],
#[cfg(feature = "jpeg")]
ImageFormat::Jpeg => &["image/jpeg"],
#[cfg(feature = "ktx2")]
ImageFormat::Ktx2 => &["image/ktx2"],
#[cfg(feature = "png")]
ImageFormat::Png => &["image/png"],
#[cfg(feature = "qoi")]
ImageFormat::Qoi => &["image/qoi", "image/x-qoi"],
#[cfg(feature = "exr")]
ImageFormat::OpenExr => &["image/x-exr"],
#[cfg(feature = "pnm")]
ImageFormat::Pnm => &[
"image/x-portable-bitmap",
"image/x-portable-graymap",
"image/x-portable-pixmap",
"image/x-portable-anymap",
],
#[cfg(feature = "tga")]
ImageFormat::Tga => &["image/x-targa", "image/x-tga"],
#[cfg(feature = "tiff")]
ImageFormat::Tiff => &["image/tiff"],
#[cfg(feature = "webp")]
ImageFormat::WebP => &["image/webp"],
// FIXME: https://github.com/rust-lang/rust/issues/129031
#[expect(
clippy::allow_attributes,
reason = "`unreachable_patterns` may not always lint"
)]
#[allow(
unreachable_patterns,
reason = "The wildcard pattern will be unreachable if all formats are enabled; otherwise, it will be reachable"
)]
_ => &[],
}
}
pub fn from_mime_type(mime_type: &str) -> Option<Self> {
#[expect(
clippy::allow_attributes,
reason = "`unreachable_code` may not always lint"
)]
#[allow(
unreachable_code,
reason = "If all features listed below are disabled, then all arms will have a `return None`, keeping the surrounding `Some()` from being constructed."
)]
Some(match mime_type.to_ascii_lowercase().as_str() {
// note: farbfeld does not have a MIME type
"image/basis" | "image/x-basis" => feature_gate!("basis-universal", Basis),
"image/bmp" | "image/x-bmp" => feature_gate!("bmp", Bmp),
"image/vnd-ms.dds" => feature_gate!("dds", Dds),
"image/vnd.radiance" => feature_gate!("hdr", Hdr),
"image/gif" => feature_gate!("gif", Gif),
"image/x-icon" => feature_gate!("ico", Ico),
"image/jpeg" => feature_gate!("jpeg", Jpeg),
"image/ktx2" => feature_gate!("ktx2", Ktx2),
"image/png" => feature_gate!("png", Png),
"image/qoi" | "image/x-qoi" => feature_gate!("qoi", Qoi),
"image/x-exr" => feature_gate!("exr", OpenExr),
"image/x-portable-bitmap"
| "image/x-portable-graymap"
| "image/x-portable-pixmap"
| "image/x-portable-anymap" => feature_gate!("pnm", Pnm),
"image/x-targa" | "image/x-tga" => feature_gate!("tga", Tga),
"image/tiff" => feature_gate!("tiff", Tiff),
"image/webp" => feature_gate!("webp", WebP),
_ => return None,
})
}
pub fn from_extension(extension: &str) -> Option<Self> {
#[expect(
clippy::allow_attributes,
reason = "`unreachable_code` may not always lint"
)]
#[allow(
unreachable_code,
reason = "If all features listed below are disabled, then all arms will have a `return None`, keeping the surrounding `Some()` from being constructed."
)]
Some(match extension.to_ascii_lowercase().as_str() {
"basis" => feature_gate!("basis-universal", Basis),
"bmp" => feature_gate!("bmp", Bmp),
"dds" => feature_gate!("dds", Dds),
"ff" | "farbfeld" => feature_gate!("ff", Farbfeld),
"gif" => feature_gate!("gif", Gif),
"exr" => feature_gate!("exr", OpenExr),
"hdr" => feature_gate!("hdr", Hdr),
"ico" => feature_gate!("ico", Ico),
"jpg" | "jpeg" => feature_gate!("jpeg", Jpeg),
"ktx2" => feature_gate!("ktx2", Ktx2),
"pam" | "pbm" | "pgm" | "ppm" => feature_gate!("pnm", Pnm),
"png" => feature_gate!("png", Png),
"qoi" => feature_gate!("qoi", Qoi),
"tga" => feature_gate!("tga", Tga),
"tif" | "tiff" => feature_gate!("tiff", Tiff),
"webp" => feature_gate!("webp", WebP),
_ => return None,
})
}
pub fn as_image_crate_format(&self) -> Option<image::ImageFormat> {
#[expect(
clippy::allow_attributes,
reason = "`unreachable_code` may not always lint"
)]
#[allow(
unreachable_code,
reason = "If all features listed below are disabled, then all arms will have a `return None`, keeping the surrounding `Some()` from being constructed."
)]
Some(match self {
#[cfg(feature = "bmp")]
ImageFormat::Bmp => image::ImageFormat::Bmp,
#[cfg(feature = "dds")]
ImageFormat::Dds => image::ImageFormat::Dds,
#[cfg(feature = "ff")]
ImageFormat::Farbfeld => image::ImageFormat::Farbfeld,
#[cfg(feature = "gif")]
ImageFormat::Gif => image::ImageFormat::Gif,
#[cfg(feature = "exr")]
ImageFormat::OpenExr => image::ImageFormat::OpenExr,
#[cfg(feature = "hdr")]
ImageFormat::Hdr => image::ImageFormat::Hdr,
#[cfg(feature = "ico")]
ImageFormat::Ico => image::ImageFormat::Ico,
#[cfg(feature = "jpeg")]
ImageFormat::Jpeg => image::ImageFormat::Jpeg,
#[cfg(feature = "png")]
ImageFormat::Png => image::ImageFormat::Png,
#[cfg(feature = "pnm")]
ImageFormat::Pnm => image::ImageFormat::Pnm,
#[cfg(feature = "qoi")]
ImageFormat::Qoi => image::ImageFormat::Qoi,
#[cfg(feature = "tga")]
ImageFormat::Tga => image::ImageFormat::Tga,
#[cfg(feature = "tiff")]
ImageFormat::Tiff => image::ImageFormat::Tiff,
#[cfg(feature = "webp")]
ImageFormat::WebP => image::ImageFormat::WebP,
#[cfg(feature = "basis-universal")]
ImageFormat::Basis => return None,
#[cfg(feature = "ktx2")]
ImageFormat::Ktx2 => return None,
// FIXME: https://github.com/rust-lang/rust/issues/129031
#[expect(
clippy::allow_attributes,
reason = "`unreachable_patterns` may not always lint"
)]
#[allow(
unreachable_patterns,
reason = "The wildcard pattern will be unreachable if all formats are enabled; otherwise, it will be reachable"
)]
_ => return None,
})
}
pub fn from_image_crate_format(format: image::ImageFormat) -> Option<ImageFormat> {
#[expect(
clippy::allow_attributes,
reason = "`unreachable_code` may not always lint"
)]
#[allow(
unreachable_code,
reason = "If all features listed below are disabled, then all arms will have a `return None`, keeping the surrounding `Some()` from being constructed."
)]
Some(match format {
image::ImageFormat::Bmp => feature_gate!("bmp", Bmp),
image::ImageFormat::Dds => feature_gate!("dds", Dds),
image::ImageFormat::Farbfeld => feature_gate!("ff", Farbfeld),
image::ImageFormat::Gif => feature_gate!("gif", Gif),
image::ImageFormat::OpenExr => feature_gate!("exr", OpenExr),
image::ImageFormat::Hdr => feature_gate!("hdr", Hdr),
image::ImageFormat::Ico => feature_gate!("ico", Ico),
image::ImageFormat::Jpeg => feature_gate!("jpeg", Jpeg),
image::ImageFormat::Png => feature_gate!("png", Png),
image::ImageFormat::Pnm => feature_gate!("pnm", Pnm),
image::ImageFormat::Qoi => feature_gate!("qoi", Qoi),
image::ImageFormat::Tga => feature_gate!("tga", Tga),
image::ImageFormat::Tiff => feature_gate!("tiff", Tiff),
image::ImageFormat::WebP => feature_gate!("webp", WebP),
_ => return None,
})
}
}
pub trait ToExtents {
fn to_extents(self) -> Extent3d;
}
impl ToExtents for UVec2 {
fn to_extents(self) -> Extent3d {
Extent3d {
width: self.x,
height: self.y,
depth_or_array_layers: 1,
}
}
}
impl ToExtents for UVec3 {
fn to_extents(self) -> Extent3d {
Extent3d {
width: self.x,
height: self.y,
depth_or_array_layers: self.z,
}
}
}
/// An image, optimized for usage in rendering.
///
/// ## Remote Inspection
///
/// To transmit an [`Image`] between two running Bevy apps, e.g. through BRP, use [`SerializedImage`](crate::SerializedImage).
/// This type is only meant for short-term transmission between same versions and should not be stored anywhere.
#[derive(Asset, Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(opaque, Default, Debug, Clone)
)]
#[cfg_attr(not(feature = "bevy_reflect"), derive(TypePath))]
pub struct Image {
/// Raw pixel data.
/// If the image is being used as a storage texture which doesn't need to be initialized by the
/// CPU, then this should be `None`.
/// Otherwise, it should always be `Some`.
pub data: Option<Vec<u8>>,
/// For texture data with layers and mips, this field controls how wgpu interprets the buffer layout.
///
/// Use [`TextureDataOrder::default()`] for all other cases.
pub data_order: TextureDataOrder,
// TODO: this nesting makes accessing Image metadata verbose. Either flatten out descriptor or add accessors.
/// Describes the data layout of the GPU texture.\
/// For example, whether a texture contains 1D/2D/3D data, and what the format of the texture data is.
///
/// ## Field Usage Notes
/// - [`TextureDescriptor::label`] is used for caching purposes when not using `Asset<Image>`.\
/// If you use assets, the label is purely a debugging aid.
/// - [`TextureDescriptor::view_formats`] is currently unused by Bevy.
pub texture_descriptor: TextureDescriptor<Option<&'static str>, &'static [TextureFormat]>,
/// The [`ImageSampler`] to use during rendering.
pub sampler: ImageSampler,
/// Describes how the GPU texture should be interpreted.\
/// For example, 2D image data could be read as plain 2D, an array texture of layers of 2D with the same dimensions (and the number of layers in that case),
/// a cube map, an array of cube maps, etc.
///
/// ## Field Usage Notes
/// - [`TextureViewDescriptor::label`] is used for caching purposes when not using `Asset<Image>`.\
/// If you use assets, the label is purely a debugging aid.
pub texture_view_descriptor: Option<TextureViewDescriptor<Option<&'static str>>>,
pub asset_usage: RenderAssetUsages,
/// Whether this image should be copied on the GPU when resized.
pub copy_on_resize: bool,
}
/// Used in [`Image`], this determines what image sampler to use when rendering. The default setting,
/// [`ImageSampler::Default`], will read the sampler from the `ImagePlugin` at setup.
/// Setting this to [`ImageSampler::Descriptor`] will override the global default descriptor for this [`Image`].
#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
pub enum ImageSampler {
/// Default image sampler, derived from the `ImagePlugin` setup.
#[default]
Default,
/// Custom sampler for this image which will override global default.
Descriptor(ImageSamplerDescriptor),
}
impl ImageSampler {
/// Returns an image sampler with [`ImageFilterMode::Linear`] min and mag filters
#[inline]
pub fn linear() -> ImageSampler {
ImageSampler::Descriptor(ImageSamplerDescriptor::linear())
}
/// Returns an image sampler with [`ImageFilterMode::Nearest`] min and mag filters
#[inline]
pub fn nearest() -> ImageSampler {
ImageSampler::Descriptor(ImageSamplerDescriptor::nearest())
}
/// Initialize the descriptor if it is not already initialized.
///
/// Descriptor is typically initialized by Bevy when the image is loaded,
/// so this is convenient shortcut for updating the descriptor.
pub fn get_or_init_descriptor(&mut self) -> &mut ImageSamplerDescriptor {
match self {
ImageSampler::Default => {
*self = ImageSampler::Descriptor(ImageSamplerDescriptor::default());
match self {
ImageSampler::Descriptor(descriptor) => descriptor,
_ => unreachable!(),
}
}
ImageSampler::Descriptor(descriptor) => descriptor,
}
}
}
/// How edges should be handled in texture addressing.
///
/// See [`ImageSamplerDescriptor`] for information how to configure this.
///
/// This type mirrors [`AddressMode`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
pub enum ImageAddressMode {
/// Clamp the value to the edge of the texture.
///
/// -0.25 -> 0.0
/// 1.25 -> 1.0
#[default]
ClampToEdge,
/// Repeat the texture in a tiling fashion.
///
/// -0.25 -> 0.75
/// 1.25 -> 0.25
Repeat,
/// Repeat the texture, mirroring it every repeat.
///
/// -0.25 -> 0.25
/// 1.25 -> 0.75
MirrorRepeat,
/// Clamp the value to the border of the texture
/// Requires the wgpu feature [`Features::ADDRESS_MODE_CLAMP_TO_BORDER`].
///
/// -0.25 -> border
/// 1.25 -> border
ClampToBorder,
}
/// Texel mixing mode when sampling between texels.
///
/// This type mirrors [`FilterMode`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
pub enum ImageFilterMode {
/// Nearest neighbor sampling.
///
/// This creates a pixelated effect when used as a mag filter.
#[default]
Nearest,
/// Linear Interpolation.
///
/// This makes textures smooth but blurry when used as a mag filter.
Linear,
}
/// Comparison function used for depth and stencil operations.
///
/// This type mirrors [`CompareFunction`].
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub enum ImageCompareFunction {
/// Function never passes
Never,
/// Function passes if new value less than existing value
Less,
/// Function passes if new value is equal to existing value. When using
/// this compare function, make sure to mark your Vertex Shader's `@builtin(position)`
/// output as `@invariant` to prevent artifacting.
Equal,
/// Function passes if new value is less than or equal to existing value
LessEqual,
/// Function passes if new value is greater than existing value
Greater,
/// Function passes if new value is not equal to existing value. When using
/// this compare function, make sure to mark your Vertex Shader's `@builtin(position)`
/// output as `@invariant` to prevent artifacting.
NotEqual,
/// Function passes if new value is greater than or equal to existing value
GreaterEqual,
/// Function always passes
Always,
}
/// Color variation to use when the sampler addressing mode is [`ImageAddressMode::ClampToBorder`].
///
/// This type mirrors [`SamplerBorderColor`].
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub enum ImageSamplerBorderColor {
/// RGBA color `[0, 0, 0, 0]`.
TransparentBlack,
/// RGBA color `[0, 0, 0, 1]`.
OpaqueBlack,
/// RGBA color `[1, 1, 1, 1]`.
OpaqueWhite,
/// On the Metal wgpu backend, this is equivalent to [`Self::TransparentBlack`] for
/// textures that have an alpha component, and equivalent to [`Self::OpaqueBlack`]
/// for textures that do not have an alpha component. On other backends,
/// this is equivalent to [`Self::TransparentBlack`]. Requires
/// [`Features::ADDRESS_MODE_CLAMP_TO_ZERO`]. Not supported on the web.
Zero,
}
/// Indicates to an `ImageLoader` how an [`Image`] should be sampled.
///
/// As this type is part of the `ImageLoaderSettings`,
/// it will be serialized to an image asset `.meta` file which might require a migration in case of
/// a breaking change.
///
/// This types mirrors [`SamplerDescriptor`], but that might change in future versions.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ImageSamplerDescriptor {
pub label: Option<String>,
/// How to deal with out of bounds accesses in the u (i.e. x) direction.
pub address_mode_u: ImageAddressMode,
/// How to deal with out of bounds accesses in the v (i.e. y) direction.
pub address_mode_v: ImageAddressMode,
/// How to deal with out of bounds accesses in the w (i.e. z) direction.
pub address_mode_w: ImageAddressMode,
/// How to filter the texture when it needs to be magnified (made larger).
pub mag_filter: ImageFilterMode,
/// How to filter the texture when it needs to be minified (made smaller).
pub min_filter: ImageFilterMode,
/// How to filter between mip map levels
pub mipmap_filter: ImageFilterMode,
/// Minimum level of detail (i.e. mip level) to use.
pub lod_min_clamp: f32,
/// Maximum level of detail (i.e. mip level) to use.
pub lod_max_clamp: f32,
/// If this is enabled, this is a comparison sampler using the given comparison function.
pub compare: Option<ImageCompareFunction>,
/// Must be at least 1. If this is not 1, all filter modes must be linear.
pub anisotropy_clamp: u16,
/// Border color to use when `address_mode` is [`ImageAddressMode::ClampToBorder`].
pub border_color: Option<ImageSamplerBorderColor>,
}
impl Default for ImageSamplerDescriptor {
fn default() -> Self {
Self {
address_mode_u: Default::default(),
address_mode_v: Default::default(),
address_mode_w: Default::default(),
mag_filter: Default::default(),
min_filter: Default::default(),
mipmap_filter: Default::default(),
lod_min_clamp: 0.0,
lod_max_clamp: 32.0,
compare: None,
anisotropy_clamp: 1,
border_color: None,
label: None,
}
}
}
impl ImageSamplerDescriptor {
/// Returns a sampler descriptor with [`Linear`](ImageFilterMode::Linear) min and mag filters
#[inline]
pub fn linear() -> ImageSamplerDescriptor {
ImageSamplerDescriptor {
mag_filter: ImageFilterMode::Linear,
min_filter: ImageFilterMode::Linear,
mipmap_filter: ImageFilterMode::Linear,
..Default::default()
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_image/src/serialized_image.rs | crates/bevy_image/src/serialized_image.rs | use crate::{Image, ImageSampler};
use bevy_asset::RenderAssetUsages;
use core::fmt::Debug;
use serde::{Deserialize, Serialize};
use wgpu_types::{
TextureAspect, TextureDataOrder, TextureDescriptor, TextureFormat, TextureUsages,
TextureViewDescriptor, TextureViewDimension,
};
/// A version of [`Image`] suitable for serializing for short-term transfer.
///
/// [`Image`] does not implement [`Serialize`] / [`Deserialize`] because it is made with the renderer in mind.
/// It is not a general-purpose image implementation, and its internals are subject to frequent change.
/// As such, storing an [`Image`] on disk is highly discouraged.
/// Use an existing image asset format such as `.png` instead!
///
/// But there are still some valid use cases for serializing an [`Image`], namely transferring images between processes.
/// To support this, you can create a [`SerializedImage`] from an [`Image`] with [`SerializedImage::from_image`],
/// and then deserialize it with [`SerializedImage::into_image`].
///
/// The caveats are:
/// - The image representation is not valid across different versions of Bevy.
/// - This conversion is lossy. The following information is not preserved:
/// - texture descriptor and texture view descriptor labels
/// - texture descriptor view formats
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SerializedImage {
data: Option<Vec<u8>>,
data_order: SerializedTextureDataOrder,
texture_descriptor: TextureDescriptor<(), ()>,
sampler: ImageSampler,
texture_view_descriptor: Option<SerializedTextureViewDescriptor>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct SerializedTextureViewDescriptor {
format: Option<TextureFormat>,
dimension: Option<TextureViewDimension>,
usage: Option<TextureUsages>,
aspect: TextureAspect,
base_mip_level: u32,
mip_level_count: Option<u32>,
base_array_layer: u32,
array_layer_count: Option<u32>,
}
impl SerializedTextureViewDescriptor {
fn from_texture_view_descriptor(
descriptor: TextureViewDescriptor<Option<&'static str>>,
) -> Self {
Self {
format: descriptor.format,
dimension: descriptor.dimension,
usage: descriptor.usage,
aspect: descriptor.aspect,
base_mip_level: descriptor.base_mip_level,
mip_level_count: descriptor.mip_level_count,
base_array_layer: descriptor.base_array_layer,
array_layer_count: descriptor.array_layer_count,
}
}
fn into_texture_view_descriptor(self) -> TextureViewDescriptor<Option<&'static str>> {
TextureViewDescriptor {
// Not used for asset-based images other than debugging
label: None,
format: self.format,
dimension: self.dimension,
usage: self.usage,
aspect: self.aspect,
base_mip_level: self.base_mip_level,
mip_level_count: self.mip_level_count,
base_array_layer: self.base_array_layer,
array_layer_count: self.array_layer_count,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
enum SerializedTextureDataOrder {
LayerMajor,
MipMajor,
}
impl SerializedTextureDataOrder {
fn from_texture_data_order(order: TextureDataOrder) -> Self {
match order {
TextureDataOrder::LayerMajor => SerializedTextureDataOrder::LayerMajor,
TextureDataOrder::MipMajor => SerializedTextureDataOrder::MipMajor,
}
}
fn into_texture_data_order(self) -> TextureDataOrder {
match self {
SerializedTextureDataOrder::LayerMajor => TextureDataOrder::LayerMajor,
SerializedTextureDataOrder::MipMajor => TextureDataOrder::MipMajor,
}
}
}
impl SerializedImage {
/// Creates a new [`SerializedImage`] from an [`Image`].
pub fn from_image(image: Image) -> Self {
Self {
data: image.data,
data_order: SerializedTextureDataOrder::from_texture_data_order(image.data_order),
texture_descriptor: TextureDescriptor {
label: (),
size: image.texture_descriptor.size,
mip_level_count: image.texture_descriptor.mip_level_count,
sample_count: image.texture_descriptor.sample_count,
dimension: image.texture_descriptor.dimension,
format: image.texture_descriptor.format,
usage: image.texture_descriptor.usage,
view_formats: (),
},
sampler: image.sampler,
texture_view_descriptor: image.texture_view_descriptor.map(|descriptor| {
SerializedTextureViewDescriptor::from_texture_view_descriptor(descriptor)
}),
}
}
/// Create an [`Image`] from a [`SerializedImage`].
pub fn into_image(self) -> Image {
Image {
data: self.data,
data_order: self.data_order.into_texture_data_order(),
texture_descriptor: TextureDescriptor {
// Not used for asset-based images other than debugging
label: None,
size: self.texture_descriptor.size,
mip_level_count: self.texture_descriptor.mip_level_count,
sample_count: self.texture_descriptor.sample_count,
dimension: self.texture_descriptor.dimension,
format: self.texture_descriptor.format,
usage: self.texture_descriptor.usage,
// Not used for asset-based images
view_formats: &[],
},
sampler: self.sampler,
texture_view_descriptor: self
.texture_view_descriptor
.map(SerializedTextureViewDescriptor::into_texture_view_descriptor),
asset_usage: RenderAssetUsages::RENDER_WORLD,
copy_on_resize: false,
}
}
}
#[cfg(test)]
mod tests {
use wgpu_types::{Extent3d, TextureDimension};
use super::*;
#[test]
fn serialize_deserialize_image() {
let image = Image::new(
Extent3d {
width: 3,
height: 1,
depth_or_array_layers: 1,
},
TextureDimension::D2,
vec![255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255],
TextureFormat::Rgba8UnormSrgb,
RenderAssetUsages::RENDER_WORLD,
);
let serialized_image = SerializedImage::from_image(image.clone());
let serialized_string = serde_json::to_string(&serialized_image).unwrap();
let serialized_image_from_string: SerializedImage =
serde_json::from_str(&serialized_string).unwrap();
let deserialized_image = serialized_image_from_string.into_image();
assert_eq!(image, deserialized_image);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_image/src/hdr_texture_loader.rs | crates/bevy_image/src/hdr_texture_loader.rs | use crate::{Image, TextureAccessError, TextureFormatPixelInfo};
use bevy_asset::RenderAssetUsages;
use bevy_asset::{io::Reader, AssetLoader, LoadContext};
use bevy_reflect::TypePath;
use image::DynamicImage;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use wgpu_types::{Extent3d, TextureDimension, TextureFormat};
/// Loads HDR textures as Texture assets
#[derive(Clone, Default, TypePath)]
pub struct HdrTextureLoader;
#[derive(Serialize, Deserialize, Default, Debug)]
pub struct HdrTextureLoaderSettings {
pub asset_usage: RenderAssetUsages,
}
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum HdrTextureLoaderError {
#[error("Could load texture: {0}")]
Io(#[from] std::io::Error),
#[error("Could not extract image: {0}")]
Image(#[from] image::ImageError),
#[error("Texture access error: {0}")]
TextureAccess(#[from] TextureAccessError),
}
impl AssetLoader for HdrTextureLoader {
type Asset = Image;
type Settings = HdrTextureLoaderSettings;
type Error = HdrTextureLoaderError;
async fn load(
&self,
reader: &mut dyn Reader,
settings: &Self::Settings,
_load_context: &mut LoadContext<'_>,
) -> Result<Image, Self::Error> {
let format = TextureFormat::Rgba32Float;
let pixel_size = format.pixel_size()?;
debug_assert_eq!(pixel_size, 4 * 4, "Format should have 32bit x 4 size");
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let decoder = image::codecs::hdr::HdrDecoder::new(bytes.as_slice())?;
let info = decoder.metadata();
let dynamic_image = DynamicImage::from_decoder(decoder)?;
let image_buffer = dynamic_image
.as_rgb32f()
.expect("HDR Image format should be Rgb32F");
let mut rgba_data = Vec::with_capacity(image_buffer.pixels().len() * pixel_size);
for rgb in image_buffer.pixels() {
let alpha = 1.0f32;
rgba_data.extend_from_slice(&rgb.0[0].to_le_bytes());
rgba_data.extend_from_slice(&rgb.0[1].to_le_bytes());
rgba_data.extend_from_slice(&rgb.0[2].to_le_bytes());
rgba_data.extend_from_slice(&alpha.to_le_bytes());
}
Ok(Image::new(
Extent3d {
width: info.width,
height: info.height,
depth_or_array_layers: 1,
},
TextureDimension::D2,
rgba_data,
format,
settings.asset_usage,
))
}
fn extensions(&self) -> &[&str] {
&["hdr"]
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_image/src/basis.rs | crates/bevy_image/src/basis.rs | use basis_universal::{
BasisTextureType, DecodeFlags, TranscodeParameters, Transcoder, TranscoderTextureFormat,
};
use wgpu_types::{AstcBlock, AstcChannel, Extent3d, TextureDimension, TextureFormat};
use super::{CompressedImageFormats, Image, TextureError};
pub fn basis_buffer_to_image(
buffer: &[u8],
supported_compressed_formats: CompressedImageFormats,
is_srgb: bool,
) -> Result<Image, TextureError> {
let mut transcoder = Transcoder::new();
#[cfg(debug_assertions)]
if !transcoder.validate_file_checksums(buffer, true) {
return Err(TextureError::InvalidData("Invalid checksum".to_string()));
}
if !transcoder.validate_header(buffer) {
return Err(TextureError::InvalidData("Invalid header".to_string()));
}
let Some(image0_info) = transcoder.image_info(buffer, 0) else {
return Err(TextureError::InvalidData(
"Failed to get image info".to_string(),
));
};
// First deal with transcoding to the desired format
// FIXME: Use external metadata to transcode to more appropriate formats for 1- or 2-component sources
let (transcode_format, texture_format) =
get_transcoded_formats(supported_compressed_formats, is_srgb);
let basis_texture_format = transcoder.basis_texture_format(buffer);
if !basis_texture_format.can_transcode_to_format(transcode_format) {
return Err(TextureError::UnsupportedTextureFormat(format!(
"{basis_texture_format:?} cannot be transcoded to {transcode_format:?}",
)));
}
transcoder.prepare_transcoding(buffer).map_err(|_| {
TextureError::TranscodeError(format!(
"Failed to prepare for transcoding from {basis_texture_format:?}",
))
})?;
let mut transcoded = Vec::new();
let image_count = transcoder.image_count(buffer);
let texture_type = transcoder.basis_texture_type(buffer);
if texture_type == BasisTextureType::TextureTypeCubemapArray && !image_count.is_multiple_of(6) {
return Err(TextureError::InvalidData(format!(
"Basis file with cube map array texture with non-modulo 6 number of images: {image_count}",
)));
}
let image0_mip_level_count = transcoder.image_level_count(buffer, 0);
for image_index in 0..image_count {
if let Some(image_info) = transcoder.image_info(buffer, image_index)
&& texture_type == BasisTextureType::TextureType2D
&& (image_info.m_orig_width != image0_info.m_orig_width
|| image_info.m_orig_height != image0_info.m_orig_height)
{
return Err(TextureError::UnsupportedTextureFormat(format!(
"Basis file with multiple 2D textures with different sizes not supported. Image {} {}x{}, image 0 {}x{}",
image_index,
image_info.m_orig_width,
image_info.m_orig_height,
image0_info.m_orig_width,
image0_info.m_orig_height,
)));
}
let mip_level_count = transcoder.image_level_count(buffer, image_index);
if mip_level_count != image0_mip_level_count {
return Err(TextureError::InvalidData(format!(
"Array or volume texture has inconsistent number of mip levels. Image {image_index} has {mip_level_count} but image 0 has {image0_mip_level_count}",
)));
}
for level_index in 0..mip_level_count {
let mut data = transcoder
.transcode_image_level(
buffer,
transcode_format,
TranscodeParameters {
image_index,
level_index,
decode_flags: Some(DecodeFlags::HIGH_QUALITY),
..Default::default()
},
)
.map_err(|error| {
TextureError::TranscodeError(format!(
"Failed to transcode mip level {level_index} from {basis_texture_format:?} to {transcode_format:?}: {error:?}",
))
})?;
transcoded.append(&mut data);
}
}
// Then prepare the Image
let mut image = Image::default();
image.texture_descriptor.size = Extent3d {
width: image0_info.m_orig_width,
height: image0_info.m_orig_height,
depth_or_array_layers: image_count,
}
.physical_size(texture_format);
image.texture_descriptor.mip_level_count = image0_mip_level_count;
image.texture_descriptor.format = texture_format;
image.texture_descriptor.dimension = match texture_type {
BasisTextureType::TextureType2D
| BasisTextureType::TextureType2DArray
| BasisTextureType::TextureTypeCubemapArray => TextureDimension::D2,
BasisTextureType::TextureTypeVolume => TextureDimension::D3,
basis_texture_type => {
return Err(TextureError::UnsupportedTextureFormat(format!(
"{basis_texture_type:?}",
)))
}
};
image.data = Some(transcoded);
Ok(image)
}
pub fn get_transcoded_formats(
supported_compressed_formats: CompressedImageFormats,
is_srgb: bool,
) -> (TranscoderTextureFormat, TextureFormat) {
// NOTE: UASTC can be losslessly transcoded to ASTC4x4 and ASTC uses the same
// space as BC7 (128-bits per 4x4 texel block) so prefer ASTC over BC for
// transcoding speed and quality.
if supported_compressed_formats.contains(CompressedImageFormats::ASTC_LDR) {
(
TranscoderTextureFormat::ASTC_4x4_RGBA,
TextureFormat::Astc {
block: AstcBlock::B4x4,
channel: if is_srgb {
AstcChannel::UnormSrgb
} else {
AstcChannel::Unorm
},
},
)
} else if supported_compressed_formats.contains(CompressedImageFormats::BC) {
(
TranscoderTextureFormat::BC7_RGBA,
if is_srgb {
TextureFormat::Bc7RgbaUnormSrgb
} else {
TextureFormat::Bc7RgbaUnorm
},
)
} else if supported_compressed_formats.contains(CompressedImageFormats::ETC2) {
(
TranscoderTextureFormat::ETC2_RGBA,
if is_srgb {
TextureFormat::Etc2Rgba8UnormSrgb
} else {
TextureFormat::Etc2Rgba8Unorm
},
)
} else {
(
TranscoderTextureFormat::RGBA32,
if is_srgb {
TextureFormat::Rgba8UnormSrgb
} else {
TextureFormat::Rgba8Unorm
},
)
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_image/src/compressed_image_saver.rs | crates/bevy_image/src/compressed_image_saver.rs | use crate::{Image, ImageFormat, ImageFormatSetting, ImageLoader, ImageLoaderSettings};
use bevy_asset::saver::{AssetSaver, SavedAsset};
use bevy_reflect::TypePath;
use futures_lite::AsyncWriteExt;
use thiserror::Error;
#[derive(TypePath)]
pub struct CompressedImageSaver;
#[non_exhaustive]
#[derive(Debug, Error, TypePath)]
pub enum CompressedImageSaverError {
#[error(transparent)]
Io(#[from] std::io::Error),
#[error("Cannot compress an uninitialized image")]
UninitializedImage,
}
impl AssetSaver for CompressedImageSaver {
type Asset = Image;
type Settings = ();
type OutputLoader = ImageLoader;
type Error = CompressedImageSaverError;
async fn save(
&self,
writer: &mut bevy_asset::io::Writer,
image: SavedAsset<'_, Self::Asset>,
_settings: &Self::Settings,
) -> Result<ImageLoaderSettings, Self::Error> {
let is_srgb = image.texture_descriptor.format.is_srgb();
let compressed_basis_data = {
let mut compressor_params = basis_universal::CompressorParams::new();
compressor_params.set_basis_format(basis_universal::BasisTextureFormat::UASTC4x4);
compressor_params.set_generate_mipmaps(true);
let color_space = if is_srgb {
basis_universal::ColorSpace::Srgb
} else {
basis_universal::ColorSpace::Linear
};
compressor_params.set_color_space(color_space);
compressor_params.set_uastc_quality_level(basis_universal::UASTC_QUALITY_DEFAULT);
let mut source_image = compressor_params.source_image_mut(0);
let size = image.size();
let Some(ref data) = image.data else {
return Err(CompressedImageSaverError::UninitializedImage);
};
source_image.init(data, size.x, size.y, 4);
let mut compressor = basis_universal::Compressor::new(4);
#[expect(
unsafe_code,
reason = "The basis-universal compressor cannot be interacted with except through unsafe functions"
)]
// SAFETY: the CompressorParams are "valid" to the best of our knowledge. The basis-universal
// library bindings note that invalid params might produce undefined behavior.
unsafe {
compressor.init(&compressor_params);
compressor.process().unwrap();
}
compressor.basis_file().to_vec()
};
writer.write_all(&compressed_basis_data).await?;
Ok(ImageLoaderSettings {
format: ImageFormatSetting::Format(ImageFormat::Basis),
is_srgb,
sampler: image.sampler.clone(),
asset_usage: image.asset_usage,
texture_format: None,
array_layout: None,
})
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_image/src/image_texture_conversion.rs | crates/bevy_image/src/image_texture_conversion.rs | use crate::{Image, TextureFormatPixelInfo};
use bevy_asset::RenderAssetUsages;
use image::{DynamicImage, ImageBuffer};
use thiserror::Error;
use wgpu_types::{Extent3d, TextureDimension, TextureFormat};
impl Image {
/// Converts a [`DynamicImage`] to an [`Image`].
pub fn from_dynamic(
dyn_img: DynamicImage,
is_srgb: bool,
asset_usage: RenderAssetUsages,
) -> Image {
use bytemuck::cast_slice;
let width;
let height;
let data: Vec<u8>;
let format: TextureFormat;
match dyn_img {
DynamicImage::ImageLuma8(image) => {
let i = DynamicImage::ImageLuma8(image).into_rgba8();
width = i.width();
height = i.height();
format = if is_srgb {
TextureFormat::Rgba8UnormSrgb
} else {
TextureFormat::Rgba8Unorm
};
data = i.into_raw();
}
DynamicImage::ImageLumaA8(image) => {
let i = DynamicImage::ImageLumaA8(image).into_rgba8();
width = i.width();
height = i.height();
format = if is_srgb {
TextureFormat::Rgba8UnormSrgb
} else {
TextureFormat::Rgba8Unorm
};
data = i.into_raw();
}
DynamicImage::ImageRgb8(image) => {
let i = DynamicImage::ImageRgb8(image).into_rgba8();
width = i.width();
height = i.height();
format = if is_srgb {
TextureFormat::Rgba8UnormSrgb
} else {
TextureFormat::Rgba8Unorm
};
data = i.into_raw();
}
DynamicImage::ImageRgba8(image) => {
width = image.width();
height = image.height();
format = if is_srgb {
TextureFormat::Rgba8UnormSrgb
} else {
TextureFormat::Rgba8Unorm
};
data = image.into_raw();
}
DynamicImage::ImageLuma16(image) => {
width = image.width();
height = image.height();
format = TextureFormat::R16Uint;
let raw_data = image.into_raw();
data = cast_slice(&raw_data).to_owned();
}
DynamicImage::ImageLumaA16(image) => {
width = image.width();
height = image.height();
format = TextureFormat::Rg16Uint;
let raw_data = image.into_raw();
data = cast_slice(&raw_data).to_owned();
}
DynamicImage::ImageRgb16(image) => {
let i = DynamicImage::ImageRgb16(image).into_rgba16();
width = i.width();
height = i.height();
format = TextureFormat::Rgba16Unorm;
let raw_data = i.into_raw();
data = cast_slice(&raw_data).to_owned();
}
DynamicImage::ImageRgba16(image) => {
width = image.width();
height = image.height();
format = TextureFormat::Rgba16Unorm;
let raw_data = image.into_raw();
data = cast_slice(&raw_data).to_owned();
}
DynamicImage::ImageRgb32F(image) => {
width = image.width();
height = image.height();
format = TextureFormat::Rgba32Float;
let mut local_data = Vec::with_capacity(
width as usize * height as usize * format.pixel_size().unwrap_or(0),
);
for pixel in image.into_raw().chunks_exact(3) {
// TODO: use the array_chunks method once stabilized
// https://github.com/rust-lang/rust/issues/74985
let r = pixel[0];
let g = pixel[1];
let b = pixel[2];
let a = 1f32;
local_data.extend_from_slice(&r.to_le_bytes());
local_data.extend_from_slice(&g.to_le_bytes());
local_data.extend_from_slice(&b.to_le_bytes());
local_data.extend_from_slice(&a.to_le_bytes());
}
data = local_data;
}
DynamicImage::ImageRgba32F(image) => {
width = image.width();
height = image.height();
format = TextureFormat::Rgba32Float;
let raw_data = image.into_raw();
data = cast_slice(&raw_data).to_owned();
}
// DynamicImage is now non exhaustive, catch future variants and convert them
_ => {
let image = dyn_img.into_rgba8();
width = image.width();
height = image.height();
format = TextureFormat::Rgba8UnormSrgb;
data = image.into_raw();
}
}
Image::new(
Extent3d {
width,
height,
depth_or_array_layers: 1,
},
TextureDimension::D2,
data,
format,
asset_usage,
)
}
/// Convert a [`Image`] to a [`DynamicImage`]. Useful for editing image
/// data. Not all [`TextureFormat`] are covered, therefore it will return an
/// error if the format is unsupported. Supported formats are:
/// - `TextureFormat::R8Unorm`
/// - `TextureFormat::Rg8Unorm`
/// - `TextureFormat::Rgba8UnormSrgb`
/// - `TextureFormat::Bgra8UnormSrgb`
///
/// To convert [`Image`] to a different format see: [`Image::convert`].
pub fn try_into_dynamic(self) -> Result<DynamicImage, IntoDynamicImageError> {
let width = self.width();
let height = self.height();
let Some(data) = self.data else {
return Err(IntoDynamicImageError::UninitializedImage);
};
match self.texture_descriptor.format {
TextureFormat::R8Unorm => {
ImageBuffer::from_raw(width, height, data).map(DynamicImage::ImageLuma8)
}
TextureFormat::Rg8Unorm => {
ImageBuffer::from_raw(width, height, data).map(DynamicImage::ImageLumaA8)
}
TextureFormat::Rgba8UnormSrgb => {
ImageBuffer::from_raw(width, height, data).map(DynamicImage::ImageRgba8)
}
// This format is commonly used as the format for the swapchain texture
// This conversion is added here to support screenshots
TextureFormat::Bgra8UnormSrgb | TextureFormat::Bgra8Unorm => {
ImageBuffer::from_raw(width, height, {
let mut data = data;
for bgra in data.chunks_exact_mut(4) {
bgra.swap(0, 2);
}
data
})
.map(DynamicImage::ImageRgba8)
}
// Throw and error if conversion isn't supported
texture_format => return Err(IntoDynamicImageError::UnsupportedFormat(texture_format)),
}
.ok_or(IntoDynamicImageError::UnknownConversionError(
self.texture_descriptor.format,
))
}
}
/// Errors that occur while converting an [`Image`] into a [`DynamicImage`]
#[non_exhaustive]
#[derive(Error, Debug)]
pub enum IntoDynamicImageError {
/// Conversion into dynamic image not supported for source format.
#[error("Conversion into dynamic image not supported for {0:?}.")]
UnsupportedFormat(TextureFormat),
/// Encountered an unknown error during conversion.
#[error("Failed to convert into {0:?}.")]
UnknownConversionError(TextureFormat),
/// Tried to convert an image that has no texture data
#[error("Image has no texture data")]
UninitializedImage,
}
#[cfg(test)]
mod test {
use image::{GenericImage, Rgba};
use super::*;
#[test]
fn two_way_conversion() {
// Check to see if color is preserved through an rgba8 conversion and back.
let mut initial = DynamicImage::new_rgba8(1, 1);
initial.put_pixel(0, 0, Rgba::from([132, 3, 7, 200]));
let image = Image::from_dynamic(initial.clone(), true, RenderAssetUsages::RENDER_WORLD);
// NOTE: Fails if `is_srgb = false` or the dynamic image is of the type rgb8.
assert_eq!(initial, image.try_into_dynamic().unwrap());
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_image/src/dds.rs | crates/bevy_image/src/dds.rs | //! [DirectDraw Surface](https://en.wikipedia.org/wiki/DirectDraw_Surface) functionality.
use ddsfile::{Caps2, D3DFormat, Dds, DxgiFormat};
use std::io::Cursor;
use wgpu_types::{
Extent3d, TextureDimension, TextureFormat, TextureViewDescriptor, TextureViewDimension,
};
#[cfg(debug_assertions)]
use {bevy_utils::once, tracing::warn};
use super::{CompressedImageFormats, Image, TextureError, TranscodeFormat};
#[cfg(feature = "dds")]
pub fn dds_buffer_to_image(
buffer: &[u8],
supported_compressed_formats: CompressedImageFormats,
is_srgb: bool,
) -> Result<Image, TextureError> {
let mut cursor = Cursor::new(buffer);
let dds = Dds::read(&mut cursor)
.map_err(|error| TextureError::InvalidData(format!("Failed to parse DDS file: {error}")))?;
let (texture_format, transcode_format) = match dds_format_to_texture_format(&dds, is_srgb) {
Ok(format) => (format, None),
Err(TextureError::FormatRequiresTranscodingError(TranscodeFormat::Rgb8)) => {
let format = if is_srgb {
TextureFormat::Rgba8UnormSrgb
} else {
TextureFormat::Rgba8Unorm
};
(format, Some(TranscodeFormat::Rgb8))
}
Err(error) => return Err(error),
};
if !supported_compressed_formats.supports(texture_format) {
return Err(TextureError::UnsupportedTextureFormat(format!(
"Format not supported by this GPU: {texture_format:?}",
)));
}
let mut image = Image::default();
let is_cubemap = dds.header.caps2.contains(Caps2::CUBEMAP);
let depth_or_array_layers = if dds.get_num_array_layers() > 1 {
dds.get_num_array_layers()
} else {
dds.get_depth()
};
if is_cubemap
&& !dds.header.caps2.contains(
Caps2::CUBEMAP_NEGATIVEX
| Caps2::CUBEMAP_NEGATIVEY
| Caps2::CUBEMAP_NEGATIVEZ
| Caps2::CUBEMAP_POSITIVEX
| Caps2::CUBEMAP_POSITIVEY
| Caps2::CUBEMAP_POSITIVEZ,
)
{
return Err(TextureError::IncompleteCubemap);
}
image.texture_descriptor.size = Extent3d {
width: dds.get_width(),
height: dds.get_height(),
depth_or_array_layers,
}
.physical_size(texture_format);
let mip_map_level = match dds.get_num_mipmap_levels() {
0 => {
#[cfg(debug_assertions)]
once!(warn!("Mipmap levels for texture are 0, bumping them to 1",));
1
}
t => t,
};
image.texture_descriptor.mip_level_count = mip_map_level;
image.texture_descriptor.format = texture_format;
image.texture_descriptor.dimension = if dds.get_depth() > 1 {
TextureDimension::D3
// 1x1 textures should generally be interpreted as solid 2D
} else if ((dds.get_width() > 1 || dds.get_height() > 1)
&& !(dds.get_width() > 1 && dds.get_height() > 1))
&& !image.is_compressed()
{
TextureDimension::D1
} else {
TextureDimension::D2
};
if is_cubemap {
let dimension = if image.texture_descriptor.size.depth_or_array_layers > 6 {
TextureViewDimension::CubeArray
} else {
TextureViewDimension::Cube
};
image.texture_view_descriptor = Some(TextureViewDescriptor {
dimension: Some(dimension),
..Default::default()
});
}
// DDS mipmap layout is directly compatible with wgpu's layout (Slice -> Face -> Mip):
// https://learn.microsoft.com/fr-fr/windows/win32/direct3ddds/dx-graphics-dds-reference
image.data = if let Some(transcode_format) = transcode_format {
match transcode_format {
TranscodeFormat::Rgb8 => {
let data = dds
.data
.chunks_exact(3)
.flat_map(|pixel| [pixel[0], pixel[1], pixel[2], u8::MAX])
.collect();
Some(data)
}
_ => {
return Err(TextureError::TranscodeError(format!(
"unsupported transcode from {transcode_format:?} to {texture_format:?}"
)))
}
}
} else {
Some(dds.data)
};
Ok(image)
}
#[cfg(feature = "dds")]
pub fn dds_format_to_texture_format(
dds: &Dds,
is_srgb: bool,
) -> Result<TextureFormat, TextureError> {
Ok(if let Some(d3d_format) = dds.get_d3d_format() {
match d3d_format {
D3DFormat::A8B8G8R8 => {
if is_srgb {
TextureFormat::Rgba8UnormSrgb
} else {
TextureFormat::Rgba8Unorm
}
}
D3DFormat::A8 => TextureFormat::R8Unorm,
D3DFormat::A8R8G8B8 => {
if is_srgb {
TextureFormat::Bgra8UnormSrgb
} else {
TextureFormat::Bgra8Unorm
}
}
D3DFormat::R8G8B8 => {
return Err(TextureError::FormatRequiresTranscodingError(TranscodeFormat::Rgb8));
},
D3DFormat::G16R16 => TextureFormat::Rg16Uint,
D3DFormat::A2B10G10R10 => TextureFormat::Rgb10a2Unorm,
D3DFormat::A8L8 => TextureFormat::Rg8Uint,
D3DFormat::L16 => TextureFormat::R16Uint,
D3DFormat::L8 => TextureFormat::R8Uint,
D3DFormat::DXT1 => {
if is_srgb {
TextureFormat::Bc1RgbaUnormSrgb
} else {
TextureFormat::Bc1RgbaUnorm
}
}
D3DFormat::DXT3 | D3DFormat::DXT2 => {
if is_srgb {
TextureFormat::Bc2RgbaUnormSrgb
} else {
TextureFormat::Bc2RgbaUnorm
}
}
D3DFormat::DXT5 | D3DFormat::DXT4 => {
if is_srgb {
TextureFormat::Bc3RgbaUnormSrgb
} else {
TextureFormat::Bc3RgbaUnorm
}
}
D3DFormat::A16B16G16R16 => TextureFormat::Rgba16Unorm,
D3DFormat::Q16W16V16U16 => TextureFormat::Rgba16Sint,
D3DFormat::R16F => TextureFormat::R16Float,
D3DFormat::G16R16F => TextureFormat::Rg16Float,
D3DFormat::A16B16G16R16F => TextureFormat::Rgba16Float,
D3DFormat::R32F => TextureFormat::R32Float,
D3DFormat::G32R32F => TextureFormat::Rg32Float,
D3DFormat::A32B32G32R32F => TextureFormat::Rgba32Float,
D3DFormat::A1R5G5B5
| D3DFormat::R5G6B5
// FIXME: Map to argb format and user has to know to ignore the alpha channel?
| D3DFormat::X8R8G8B8
// FIXME: Map to argb format and user has to know to ignore the alpha channel?
| D3DFormat::X8B8G8R8
| D3DFormat::A2R10G10B10
| D3DFormat::X1R5G5B5
| D3DFormat::A4R4G4B4
| D3DFormat::X4R4G4B4
| D3DFormat::A8R3G3B2
| D3DFormat::A4L4
| D3DFormat::R8G8_B8G8
| D3DFormat::G8R8_G8B8
| D3DFormat::UYVY
| D3DFormat::YUY2
| D3DFormat::CXV8U8 => {
return Err(TextureError::UnsupportedTextureFormat(format!(
"{d3d_format:?}",
)))
}
}
} else if let Some(dxgi_format) = dds.get_dxgi_format() {
match dxgi_format {
DxgiFormat::R32G32B32A32_Typeless | DxgiFormat::R32G32B32A32_Float => {
TextureFormat::Rgba32Float
}
DxgiFormat::R32G32B32A32_UInt => TextureFormat::Rgba32Uint,
DxgiFormat::R32G32B32A32_SInt => TextureFormat::Rgba32Sint,
DxgiFormat::R16G16B16A16_Typeless | DxgiFormat::R16G16B16A16_Float => {
TextureFormat::Rgba16Float
}
DxgiFormat::R16G16B16A16_UNorm => TextureFormat::Rgba16Unorm,
DxgiFormat::R16G16B16A16_UInt => TextureFormat::Rgba16Uint,
DxgiFormat::R16G16B16A16_SNorm => TextureFormat::Rgba16Snorm,
DxgiFormat::R16G16B16A16_SInt => TextureFormat::Rgba16Sint,
DxgiFormat::R32G32_Typeless | DxgiFormat::R32G32_Float => TextureFormat::Rg32Float,
DxgiFormat::R32G32_UInt => TextureFormat::Rg32Uint,
DxgiFormat::R32G32_SInt => TextureFormat::Rg32Sint,
DxgiFormat::R10G10B10A2_Typeless | DxgiFormat::R10G10B10A2_UNorm => {
TextureFormat::Rgb10a2Unorm
}
DxgiFormat::R11G11B10_Float => TextureFormat::Rg11b10Ufloat,
DxgiFormat::R8G8B8A8_Typeless
| DxgiFormat::R8G8B8A8_UNorm
| DxgiFormat::R8G8B8A8_UNorm_sRGB => {
if is_srgb {
TextureFormat::Rgba8UnormSrgb
} else {
TextureFormat::Rgba8Unorm
}
}
DxgiFormat::R8G8B8A8_UInt => TextureFormat::Rgba8Uint,
DxgiFormat::R8G8B8A8_SNorm => TextureFormat::Rgba8Snorm,
DxgiFormat::R8G8B8A8_SInt => TextureFormat::Rgba8Sint,
DxgiFormat::R16G16_Typeless | DxgiFormat::R16G16_Float => TextureFormat::Rg16Float,
DxgiFormat::R16G16_UNorm => TextureFormat::Rg16Unorm,
DxgiFormat::R16G16_UInt => TextureFormat::Rg16Uint,
DxgiFormat::R16G16_SNorm => TextureFormat::Rg16Snorm,
DxgiFormat::R16G16_SInt => TextureFormat::Rg16Sint,
DxgiFormat::R32_Typeless | DxgiFormat::R32_Float => TextureFormat::R32Float,
DxgiFormat::D32_Float => TextureFormat::Depth32Float,
DxgiFormat::R32_UInt => TextureFormat::R32Uint,
DxgiFormat::R32_SInt => TextureFormat::R32Sint,
DxgiFormat::R24G8_Typeless | DxgiFormat::D24_UNorm_S8_UInt => {
TextureFormat::Depth24PlusStencil8
}
DxgiFormat::R24_UNorm_X8_Typeless => TextureFormat::Depth24Plus,
DxgiFormat::R8G8_Typeless | DxgiFormat::R8G8_UNorm => TextureFormat::Rg8Unorm,
DxgiFormat::R8G8_UInt => TextureFormat::Rg8Uint,
DxgiFormat::R8G8_SNorm => TextureFormat::Rg8Snorm,
DxgiFormat::R8G8_SInt => TextureFormat::Rg8Sint,
DxgiFormat::R16_Typeless | DxgiFormat::R16_Float => TextureFormat::R16Float,
DxgiFormat::R16_UNorm => TextureFormat::R16Unorm,
DxgiFormat::R16_UInt => TextureFormat::R16Uint,
DxgiFormat::R16_SNorm => TextureFormat::R16Snorm,
DxgiFormat::R16_SInt => TextureFormat::R16Sint,
DxgiFormat::R8_Typeless | DxgiFormat::R8_UNorm => TextureFormat::R8Unorm,
DxgiFormat::R8_UInt => TextureFormat::R8Uint,
DxgiFormat::R8_SNorm => TextureFormat::R8Snorm,
DxgiFormat::R8_SInt => TextureFormat::R8Sint,
DxgiFormat::R9G9B9E5_SharedExp => TextureFormat::Rgb9e5Ufloat,
DxgiFormat::BC1_Typeless | DxgiFormat::BC1_UNorm | DxgiFormat::BC1_UNorm_sRGB => {
if is_srgb {
TextureFormat::Bc1RgbaUnormSrgb
} else {
TextureFormat::Bc1RgbaUnorm
}
}
DxgiFormat::BC2_Typeless | DxgiFormat::BC2_UNorm | DxgiFormat::BC2_UNorm_sRGB => {
if is_srgb {
TextureFormat::Bc2RgbaUnormSrgb
} else {
TextureFormat::Bc2RgbaUnorm
}
}
DxgiFormat::BC3_Typeless | DxgiFormat::BC3_UNorm | DxgiFormat::BC3_UNorm_sRGB => {
if is_srgb {
TextureFormat::Bc3RgbaUnormSrgb
} else {
TextureFormat::Bc3RgbaUnorm
}
}
DxgiFormat::BC4_Typeless | DxgiFormat::BC4_UNorm => TextureFormat::Bc4RUnorm,
DxgiFormat::BC4_SNorm => TextureFormat::Bc4RSnorm,
DxgiFormat::BC5_Typeless | DxgiFormat::BC5_UNorm => TextureFormat::Bc5RgUnorm,
DxgiFormat::BC5_SNorm => TextureFormat::Bc5RgSnorm,
DxgiFormat::B8G8R8A8_UNorm
| DxgiFormat::B8G8R8A8_Typeless
| DxgiFormat::B8G8R8A8_UNorm_sRGB => {
if is_srgb {
TextureFormat::Bgra8UnormSrgb
} else {
TextureFormat::Bgra8Unorm
}
}
DxgiFormat::BC6H_Typeless | DxgiFormat::BC6H_UF16 => TextureFormat::Bc6hRgbUfloat,
DxgiFormat::BC6H_SF16 => TextureFormat::Bc6hRgbFloat,
DxgiFormat::BC7_Typeless | DxgiFormat::BC7_UNorm | DxgiFormat::BC7_UNorm_sRGB => {
if is_srgb {
TextureFormat::Bc7RgbaUnormSrgb
} else {
TextureFormat::Bc7RgbaUnorm
}
}
_ => {
return Err(TextureError::UnsupportedTextureFormat(format!(
"{dxgi_format:?}",
)))
}
}
} else {
return Err(TextureError::UnsupportedTextureFormat(
"unspecified".to_string(),
));
})
}
#[cfg(test)]
mod test {
use wgpu_types::{TextureDataOrder, TextureDescriptor, TextureDimension, TextureFormat};
use crate::CompressedImageFormats;
use super::dds_buffer_to_image;
/// `wgpu::create_texture_with_data` that reads from data structure but doesn't actually talk to your GPU
fn fake_wgpu_create_texture_with_data(
desc: &TextureDescriptor<Option<&'_ str>, &'_ [TextureFormat]>,
data: &[u8],
) {
// Will return None only if it's a combined depth-stencil format
// If so, default to 4, validation will fail later anyway since the depth or stencil
// aspect needs to be written to individually
let block_size = desc.format.block_copy_size(None).unwrap_or(4);
let (block_width, block_height) = desc.format.block_dimensions();
let layer_iterations = desc.array_layer_count();
let outer_iteration;
let inner_iteration;
match TextureDataOrder::default() {
TextureDataOrder::LayerMajor => {
outer_iteration = layer_iterations;
inner_iteration = desc.mip_level_count;
}
TextureDataOrder::MipMajor => {
outer_iteration = desc.mip_level_count;
inner_iteration = layer_iterations;
}
}
let mut binary_offset = 0;
for outer in 0..outer_iteration {
for inner in 0..inner_iteration {
let (_layer, mip) = match TextureDataOrder::default() {
TextureDataOrder::LayerMajor => (outer, inner),
TextureDataOrder::MipMajor => (inner, outer),
};
let mut mip_size = desc.mip_level_size(mip).unwrap();
// copying layers separately
if desc.dimension != TextureDimension::D3 {
mip_size.depth_or_array_layers = 1;
}
// When uploading mips of compressed textures and the mip is supposed to be
// a size that isn't a multiple of the block size, the mip needs to be uploaded
// as its "physical size" which is the size rounded up to the nearest block size.
let mip_physical = mip_size.physical_size(desc.format);
// All these calculations are performed on the physical size as that's the
// data that exists in the buffer.
let width_blocks = mip_physical.width / block_width;
let height_blocks = mip_physical.height / block_height;
let bytes_per_row = width_blocks * block_size;
let data_size = bytes_per_row * height_blocks * mip_size.depth_or_array_layers;
let end_offset = binary_offset + data_size as usize;
assert!(binary_offset < data.len());
assert!(end_offset <= data.len());
// those asserts match how the data will be accessed by wgpu:
// data[binary_offset..end_offset])
binary_offset = end_offset;
}
}
}
#[test]
fn dds_skybox() {
let buffer: [u8; 224] = [
0x44, 0x44, 0x53, 0x20, 0x7c, 0, 0, 0, 7, 0x10, 0x08, 0, 4, 0, 0, 0, 4, 0, 0, 0, 0x10,
0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0x47, 0x49, 0x4d, 0x50, 0x2d, 0x44, 0x44, 0x53, 0x5c,
0x09, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0x20, 0, 0, 0, 4, 0, 0, 0, 0x44, 0x58, 0x54, 0x35, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x08, 0x10, 0, 0, 0, 0xfe, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0x49, 0x92, 0x24, 0x49, 0x92, 0x24, 0xda, 0xd6,
0x2f, 0x5b, 0x8a, 0, 0xff, 0x55, 0xff, 0xff, 0x49, 0x92, 0x24, 0x49, 0x92, 0x24, 0xd5,
0x84, 0x8e, 0x3a, 0xb7, 0, 0xaa, 0x55, 0xff, 0xff, 0x49, 0x92, 0x24, 0x49, 0x92, 0x24,
0xf5, 0x94, 0x6f, 0x32, 0x57, 0xb7, 0x8b, 0, 0xff, 0xff, 0x49, 0x92, 0x24, 0x49, 0x92,
0x24, 0x2c, 0x3a, 0x49, 0x19, 0x28, 0xf7, 0xd7, 0xbe, 0xff, 0xff, 0x49, 0x92, 0x24,
0x49, 0x92, 0x24, 0x16, 0x95, 0xae, 0x42, 0xfc, 0, 0xaa, 0x55, 0xff, 0xff, 0x49, 0x92,
0x24, 0x49, 0x92, 0x24, 0xd8, 0xad, 0xae, 0x42, 0xaf, 0x0a, 0xaa, 0x55,
];
let r = dds_buffer_to_image(&buffer, CompressedImageFormats::BC, true);
assert!(r.is_ok());
if let Ok(r) = r {
fake_wgpu_create_texture_with_data(&r.texture_descriptor, r.data.as_ref().unwrap());
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_image/src/texture_atlas.rs | crates/bevy_image/src/texture_atlas.rs | use bevy_app::prelude::*;
use bevy_asset::{Asset, AssetApp as _, AssetId, Assets, Handle};
use bevy_math::{Rect, URect, UVec2};
use bevy_platform::collections::HashMap;
#[cfg(not(feature = "bevy_reflect"))]
use bevy_reflect::TypePath;
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
#[cfg(feature = "serialize")]
use bevy_reflect::{ReflectDeserialize, ReflectSerialize};
use crate::Image;
/// Adds support for texture atlases.
pub struct TextureAtlasPlugin;
impl Plugin for TextureAtlasPlugin {
fn build(&self, app: &mut App) {
app.init_asset::<TextureAtlasLayout>();
#[cfg(feature = "bevy_reflect")]
app.register_asset_reflect::<TextureAtlasLayout>();
}
}
/// Stores a mapping from sub texture handles to the related area index.
///
/// Generated by [`TextureAtlasBuilder`].
///
/// [`TextureAtlasBuilder`]: crate::TextureAtlasBuilder
#[derive(Debug)]
pub struct TextureAtlasSources {
/// Maps from a specific image handle to the index in `textures` where they can be found.
pub texture_ids: HashMap<AssetId<Image>, usize>,
}
impl TextureAtlasSources {
/// Retrieves the texture *section* index of the given `texture` handle.
pub fn texture_index(&self, texture: impl Into<AssetId<Image>>) -> Option<usize> {
let id = texture.into();
self.texture_ids.get(&id).cloned()
}
/// Creates a [`TextureAtlas`] handle for the given `texture` handle.
pub fn handle(
&self,
layout: Handle<TextureAtlasLayout>,
texture: impl Into<AssetId<Image>>,
) -> Option<TextureAtlas> {
Some(TextureAtlas {
layout,
index: self.texture_index(texture)?,
})
}
/// Retrieves the texture *section* rectangle of the given `texture` handle in pixels.
pub fn texture_rect(
&self,
layout: &TextureAtlasLayout,
texture: impl Into<AssetId<Image>>,
) -> Option<URect> {
layout.textures.get(self.texture_index(texture)?).cloned()
}
/// Retrieves the texture *section* rectangle of the given `texture` handle in UV coordinates.
/// These are within the range [0..1], as a fraction of the entire texture atlas' size.
pub fn uv_rect(
&self,
layout: &TextureAtlasLayout,
texture: impl Into<AssetId<Image>>,
) -> Option<Rect> {
self.texture_rect(layout, texture).map(|rect| {
let rect = rect.as_rect();
let size = layout.size.as_vec2();
Rect::from_corners(rect.min / size, rect.max / size)
})
}
}
/// Stores a map used to lookup the position of a texture in a [`TextureAtlas`].
/// This can be used to either use and look up a specific section of a texture, or animate frame-by-frame as a sprite sheet.
///
/// Optionally it can store a mapping from sub texture handles to the related area index (see
/// [`TextureAtlasBuilder`]).
///
/// [Example usage animating sprite.](https://github.com/bevyengine/bevy/blob/latest/examples/2d/sprite_sheet.rs)
/// [Example usage animating sprite in response to an event.](https://github.com/bevyengine/bevy/blob/latest/examples/2d/sprite_animation.rs)
/// [Example usage loading sprite sheet.](https://github.com/bevyengine/bevy/blob/latest/examples/2d/texture_atlas.rs)
///
/// [`TextureAtlasBuilder`]: crate::TextureAtlasBuilder
#[derive(Asset, PartialEq, Eq, Debug, Clone)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, PartialEq, Clone)
)]
#[cfg_attr(
feature = "serialize",
derive(serde::Serialize, serde::Deserialize),
reflect(Serialize, Deserialize)
)]
#[cfg_attr(not(feature = "bevy_reflect"), derive(TypePath))]
pub struct TextureAtlasLayout {
/// Total size of texture atlas.
pub size: UVec2,
/// The specific areas of the atlas where each texture can be found
pub textures: Vec<URect>,
}
impl TextureAtlasLayout {
/// Create a new empty layout with custom `dimensions`
pub fn new_empty(dimensions: UVec2) -> Self {
Self {
size: dimensions,
textures: Vec::new(),
}
}
/// Generate a [`TextureAtlasLayout`] as a grid where each
/// `tile_size` by `tile_size` grid-cell is one of the *section* in the
/// atlas. Grid cells are separated by some `padding`, and the grid starts
/// at `offset` pixels from the top left corner. Resulting layout is
/// indexed left to right, top to bottom.
///
/// # Arguments
///
/// * `tile_size` - Each layout grid cell size
/// * `columns` - Grid column count
/// * `rows` - Grid row count
/// * `padding` - Optional padding between cells
/// * `offset` - Optional global grid offset
pub fn from_grid(
tile_size: UVec2,
columns: u32,
rows: u32,
padding: Option<UVec2>,
offset: Option<UVec2>,
) -> Self {
let padding = padding.unwrap_or_default();
let offset = offset.unwrap_or_default();
let mut sprites = Vec::new();
let mut current_padding = UVec2::ZERO;
for y in 0..rows {
if y > 0 {
current_padding.y = padding.y;
}
for x in 0..columns {
if x > 0 {
current_padding.x = padding.x;
}
let cell = UVec2::new(x, y);
let rect_min = (tile_size + current_padding) * cell + offset;
sprites.push(URect {
min: rect_min,
max: rect_min + tile_size,
});
}
}
let grid_size = UVec2::new(columns, rows);
Self {
size: ((tile_size + current_padding) * grid_size) - current_padding,
textures: sprites,
}
}
/// Add a *section* to the list in the layout and returns its index
/// which can be used with [`TextureAtlas`]
///
/// # Arguments
///
/// * `rect` - The section of the texture to be added
///
/// [`TextureAtlas`]: crate::TextureAtlas
pub fn add_texture(&mut self, rect: URect) -> usize {
self.textures.push(rect);
self.textures.len() - 1
}
/// The number of textures in the [`TextureAtlasLayout`]
pub fn len(&self) -> usize {
self.textures.len()
}
pub fn is_empty(&self) -> bool {
self.textures.is_empty()
}
}
/// An index into a [`TextureAtlasLayout`], which corresponds to a specific section of a texture.
///
/// It stores a handle to [`TextureAtlasLayout`] and the index of the current section of the atlas.
/// The texture atlas contains various *sections* of a given texture, allowing users to have a single
/// image file for either sprite animation or global mapping.
/// You can change the texture [`index`](Self::index) of the atlas to animate the sprite or display only a *section* of the texture
/// for efficient rendering of related game objects.
///
/// Check the following examples for usage:
/// - [`animated sprite sheet example`](https://github.com/bevyengine/bevy/blob/latest/examples/2d/sprite_sheet.rs)
/// - [`sprite animation event example`](https://github.com/bevyengine/bevy/blob/latest/examples/2d/sprite_animation.rs)
/// - [`texture atlas example`](https://github.com/bevyengine/bevy/blob/latest/examples/2d/texture_atlas.rs)
#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Debug, PartialEq, Hash, Clone)
)]
pub struct TextureAtlas {
/// Texture atlas layout handle
pub layout: Handle<TextureAtlasLayout>,
/// Texture atlas section index
pub index: usize,
}
impl TextureAtlas {
/// Retrieves the current texture [`URect`] of the sprite sheet according to the section `index`
pub fn texture_rect(&self, texture_atlases: &Assets<TextureAtlasLayout>) -> Option<URect> {
let atlas = texture_atlases.get(&self.layout)?;
atlas.textures.get(self.index).copied()
}
/// Returns this [`TextureAtlas`] with the specified index.
pub fn with_index(mut self, index: usize) -> Self {
self.index = index;
self
}
/// Returns this [`TextureAtlas`] with the specified [`TextureAtlasLayout`] handle.
pub fn with_layout(mut self, layout: Handle<TextureAtlasLayout>) -> Self {
self.layout = layout;
self
}
}
impl From<Handle<TextureAtlasLayout>> for TextureAtlas {
fn from(texture_atlas: Handle<TextureAtlasLayout>) -> Self {
Self {
layout: texture_atlas,
index: 0,
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_image/src/dynamic_texture_atlas_builder.rs | crates/bevy_image/src/dynamic_texture_atlas_builder.rs | use crate::{Image, TextureAccessError, TextureAtlasLayout, TextureFormatPixelInfo as _};
use bevy_asset::RenderAssetUsages;
use bevy_math::{URect, UVec2};
use guillotiere::{size2, Allocation, AtlasAllocator};
use thiserror::Error;
/// An error produced by [`DynamicTextureAtlasBuilder`] when trying to add a new
/// texture to a [`TextureAtlasLayout`].
#[derive(Debug, Error)]
pub enum DynamicTextureAtlasBuilderError {
/// Unable to allocate space within the atlas for the new texture
#[error("Couldn't allocate space to add the image requested")]
FailedToAllocateSpace,
/// Attempted to add a texture to an uninitialized atlas
#[error("cannot add texture to uninitialized atlas texture")]
UninitializedAtlas,
/// Attempted to add an uninitialized texture to an atlas
#[error("cannot add uninitialized texture to atlas")]
UninitializedSourceTexture,
/// A texture access error occurred
#[error("texture access error: {0}")]
TextureAccess(#[from] TextureAccessError),
}
/// Helper utility to update [`TextureAtlasLayout`] on the fly.
///
/// Helpful in cases when texture is created procedurally,
/// e.g: in a font glyph [`TextureAtlasLayout`], only add the [`Image`] texture for letters to be rendered.
pub struct DynamicTextureAtlasBuilder {
atlas_allocator: AtlasAllocator,
padding: u32,
}
impl DynamicTextureAtlasBuilder {
/// Create a new [`DynamicTextureAtlasBuilder`]
///
/// # Arguments
///
/// * `size` - total size for the atlas
/// * `padding` - gap added between textures in the atlas, both in x axis and y axis
pub fn new(size: UVec2, padding: u32) -> Self {
Self {
atlas_allocator: AtlasAllocator::new(to_size2(size)),
padding,
}
}
/// Add a new texture to `atlas_layout`.
///
/// It is the user's responsibility to pass in the correct [`TextureAtlasLayout`].
/// Also, the asset that `atlas_texture_handle` points to must have a usage matching
/// [`RenderAssetUsages::MAIN_WORLD`].
///
/// # Arguments
///
/// * `atlas_layout` - The atlas layout to add the texture to.
/// * `texture` - The source texture to add to the atlas.
/// * `atlas_texture` - The destination atlas texture to copy the source texture to.
pub fn add_texture(
&mut self,
atlas_layout: &mut TextureAtlasLayout,
texture: &Image,
atlas_texture: &mut Image,
) -> Result<usize, DynamicTextureAtlasBuilderError> {
let allocation = self.atlas_allocator.allocate(size2(
(texture.width() + self.padding).try_into().unwrap(),
(texture.height() + self.padding).try_into().unwrap(),
));
if let Some(allocation) = allocation {
assert!(
atlas_texture.asset_usage.contains(RenderAssetUsages::MAIN_WORLD),
"The atlas_texture image must have the RenderAssetUsages::MAIN_WORLD usage flag set"
);
self.place_texture(atlas_texture, allocation, texture)?;
let mut rect: URect = to_rect(allocation.rectangle);
rect.max = rect.max.saturating_sub(UVec2::splat(self.padding));
Ok(atlas_layout.add_texture(rect))
} else {
Err(DynamicTextureAtlasBuilderError::FailedToAllocateSpace)
}
}
fn place_texture(
&mut self,
atlas_texture: &mut Image,
allocation: Allocation,
texture: &Image,
) -> Result<(), DynamicTextureAtlasBuilderError> {
let mut rect = allocation.rectangle;
rect.max.x -= self.padding as i32;
rect.max.y -= self.padding as i32;
let atlas_width = atlas_texture.width() as usize;
let rect_width = rect.width() as usize;
let format_size = atlas_texture.texture_descriptor.format.pixel_size()?;
let Some(ref mut atlas_data) = atlas_texture.data else {
return Err(DynamicTextureAtlasBuilderError::UninitializedAtlas);
};
let Some(ref data) = texture.data else {
return Err(DynamicTextureAtlasBuilderError::UninitializedSourceTexture);
};
for (texture_y, bound_y) in (rect.min.y..rect.max.y).map(|i| i as usize).enumerate() {
let begin = (bound_y * atlas_width + rect.min.x as usize) * format_size;
let end = begin + rect_width * format_size;
let texture_begin = texture_y * rect_width * format_size;
let texture_end = texture_begin + rect_width * format_size;
atlas_data[begin..end].copy_from_slice(&data[texture_begin..texture_end]);
}
Ok(())
}
}
fn to_rect(rectangle: guillotiere::Rectangle) -> URect {
URect {
min: UVec2::new(
rectangle.min.x.try_into().unwrap(),
rectangle.min.y.try_into().unwrap(),
),
max: UVec2::new(
rectangle.max.x.try_into().unwrap(),
rectangle.max.y.try_into().unwrap(),
),
}
}
fn to_size2(vec2: UVec2) -> guillotiere::Size {
guillotiere::Size::new(vec2.x as i32, vec2.y as i32)
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_image/src/texture_atlas_builder.rs | crates/bevy_image/src/texture_atlas_builder.rs | use bevy_asset::{AssetId, RenderAssetUsages};
use bevy_math::{URect, UVec2};
use bevy_platform::collections::HashMap;
use rectangle_pack::{
contains_smallest_box, pack_rects, volume_heuristic, GroupedRectsToPlace, PackedLocation,
RectToInsert, TargetBin,
};
use thiserror::Error;
use tracing::{debug, error, warn};
use wgpu_types::{Extent3d, TextureDimension, TextureFormat};
use crate::{Image, TextureAccessError, TextureFormatPixelInfo};
use crate::{TextureAtlasLayout, TextureAtlasSources};
#[derive(Debug, Error)]
pub enum TextureAtlasBuilderError {
#[error("could not pack textures into an atlas within the given bounds")]
NotEnoughSpace,
#[error("added a texture with the wrong format in an atlas")]
WrongFormat,
/// Attempted to add a texture to an uninitialized atlas
#[error("cannot add texture to uninitialized atlas texture")]
UninitializedAtlas,
/// Attempted to add an uninitialized texture to an atlas
#[error("cannot add uninitialized texture to atlas")]
UninitializedSourceTexture,
/// A texture access error occurred
#[error("texture access error: {0}")]
TextureAccess(#[from] TextureAccessError),
}
#[derive(Debug)]
#[must_use]
/// A builder which is used to create a texture atlas from many individual
/// sprites.
pub struct TextureAtlasBuilder<'a> {
/// Collection of texture's asset id (optional) and image data to be packed into an atlas
textures_to_place: Vec<(Option<AssetId<Image>>, &'a Image)>,
/// The initial atlas size in pixels.
initial_size: UVec2,
/// The absolute maximum size of the texture atlas in pixels.
max_size: UVec2,
/// The texture format for the textures that will be loaded in the atlas.
format: TextureFormat,
/// Enable automatic format conversion for textures if they are not in the atlas format.
auto_format_conversion: bool,
/// The amount of padding in pixels to add along the right and bottom edges of the texture rects.
padding: UVec2,
}
impl Default for TextureAtlasBuilder<'_> {
fn default() -> Self {
Self {
textures_to_place: Vec::new(),
initial_size: UVec2::splat(256),
max_size: UVec2::splat(2048),
format: TextureFormat::Rgba8UnormSrgb,
auto_format_conversion: true,
padding: UVec2::ZERO,
}
}
}
pub type TextureAtlasBuilderResult<T> = Result<T, TextureAtlasBuilderError>;
impl<'a> TextureAtlasBuilder<'a> {
/// Sets the initial size of the atlas in pixels.
pub fn initial_size(&mut self, size: UVec2) -> &mut Self {
self.initial_size = size;
self
}
/// Sets the max size of the atlas in pixels.
pub fn max_size(&mut self, size: UVec2) -> &mut Self {
self.max_size = size;
self
}
/// Sets the texture format for textures in the atlas.
pub fn format(&mut self, format: TextureFormat) -> &mut Self {
self.format = format;
self
}
/// Control whether the added texture should be converted to the atlas format, if different.
pub fn auto_format_conversion(&mut self, auto_format_conversion: bool) -> &mut Self {
self.auto_format_conversion = auto_format_conversion;
self
}
/// Adds a texture to be copied to the texture atlas.
///
/// Optionally an asset id can be passed that can later be used with the texture layout to retrieve the index of this texture.
/// The insertion order will reflect the index of the added texture in the finished texture atlas.
pub fn add_texture(
&mut self,
image_id: Option<AssetId<Image>>,
texture: &'a Image,
) -> &mut Self {
self.textures_to_place.push((image_id, texture));
self
}
/// Sets the amount of padding in pixels to add between the textures in the texture atlas.
///
/// The `x` value provide will be added to the right edge, while the `y` value will be added to the bottom edge.
pub fn padding(&mut self, padding: UVec2) -> &mut Self {
self.padding = padding;
self
}
fn copy_texture_to_atlas(
atlas_texture: &mut Image,
texture: &Image,
packed_location: &PackedLocation,
padding: UVec2,
) -> TextureAtlasBuilderResult<()> {
let rect_width = (packed_location.width() - padding.x) as usize;
let rect_height = (packed_location.height() - padding.y) as usize;
let rect_x = packed_location.x() as usize;
let rect_y = packed_location.y() as usize;
let atlas_width = atlas_texture.width() as usize;
let format_size = atlas_texture.texture_descriptor.format.pixel_size()?;
let Some(ref mut atlas_data) = atlas_texture.data else {
return Err(TextureAtlasBuilderError::UninitializedAtlas);
};
let Some(ref data) = texture.data else {
return Err(TextureAtlasBuilderError::UninitializedSourceTexture);
};
for (texture_y, bound_y) in (rect_y..rect_y + rect_height).enumerate() {
let begin = (bound_y * atlas_width + rect_x) * format_size;
let end = begin + rect_width * format_size;
let texture_begin = texture_y * rect_width * format_size;
let texture_end = texture_begin + rect_width * format_size;
atlas_data[begin..end].copy_from_slice(&data[texture_begin..texture_end]);
}
Ok(())
}
fn copy_converted_texture(
&self,
atlas_texture: &mut Image,
texture: &Image,
packed_location: &PackedLocation,
) -> TextureAtlasBuilderResult<()> {
if self.format == texture.texture_descriptor.format {
Self::copy_texture_to_atlas(atlas_texture, texture, packed_location, self.padding)?;
} else if let Some(converted_texture) = texture.convert(self.format) {
debug!(
"Converting texture from '{:?}' to '{:?}'",
texture.texture_descriptor.format, self.format
);
Self::copy_texture_to_atlas(
atlas_texture,
&converted_texture,
packed_location,
self.padding,
)?;
} else {
error!(
"Error converting texture from '{:?}' to '{:?}', ignoring",
texture.texture_descriptor.format, self.format
);
}
Ok(())
}
/// Consumes the builder, and returns the newly created texture atlas and
/// the associated atlas layout.
///
/// Assigns indices to the textures based on the insertion order.
/// Internally it copies all rectangles from the textures and copies them
/// into a new texture.
///
/// # Usage
///
/// ```rust
/// # use bevy_ecs::prelude::*;
/// # use bevy_asset::*;
/// # use bevy_image::prelude::*;
///
/// fn my_system(mut textures: ResMut<Assets<Image>>, mut layouts: ResMut<Assets<TextureAtlasLayout>>) {
/// // Declare your builder
/// let mut builder = TextureAtlasBuilder::default();
/// // Customize it
/// // ...
/// // Build your texture and the atlas layout
/// let (atlas_layout, atlas_sources, texture) = builder.build().unwrap();
/// let texture = textures.add(texture);
/// let layout = layouts.add(atlas_layout);
/// }
/// ```
///
/// # Errors
///
/// If there is not enough space in the atlas texture, an error will
/// be returned. It is then recommended to make a larger sprite sheet.
pub fn build(
&mut self,
) -> Result<(TextureAtlasLayout, TextureAtlasSources, Image), TextureAtlasBuilderError> {
let max_width = self.max_size.x;
let max_height = self.max_size.y;
let mut current_width = self.initial_size.x;
let mut current_height = self.initial_size.y;
let mut rect_placements = None;
let mut atlas_texture = Image::default();
let mut rects_to_place = GroupedRectsToPlace::<usize>::new();
// Adds textures to rectangle group packer
for (index, (_, texture)) in self.textures_to_place.iter().enumerate() {
rects_to_place.push_rect(
index,
None,
RectToInsert::new(
texture.width() + self.padding.x,
texture.height() + self.padding.y,
1,
),
);
}
while rect_placements.is_none() {
if current_width > max_width || current_height > max_height {
break;
}
let last_attempt = current_height == max_height && current_width == max_width;
let mut target_bins = alloc::collections::BTreeMap::new();
target_bins.insert(0, TargetBin::new(current_width, current_height, 1));
rect_placements = match pack_rects(
&rects_to_place,
&mut target_bins,
&volume_heuristic,
&contains_smallest_box,
) {
Ok(rect_placements) => {
atlas_texture = Image::new(
Extent3d {
width: current_width,
height: current_height,
depth_or_array_layers: 1,
},
TextureDimension::D2,
vec![
0;
self.format.pixel_size()? * (current_width * current_height) as usize
],
self.format,
RenderAssetUsages::MAIN_WORLD | RenderAssetUsages::RENDER_WORLD,
);
Some(rect_placements)
}
Err(rectangle_pack::RectanglePackError::NotEnoughBinSpace) => {
current_height = (current_height * 2).clamp(0, max_height);
current_width = (current_width * 2).clamp(0, max_width);
None
}
};
if last_attempt {
break;
}
}
let rect_placements = rect_placements.ok_or(TextureAtlasBuilderError::NotEnoughSpace)?;
let mut texture_rects = Vec::with_capacity(rect_placements.packed_locations().len());
let mut texture_ids = <HashMap<_, _>>::default();
// We iterate through the textures to place to respect the insertion order for the texture indices
for (index, (image_id, texture)) in self.textures_to_place.iter().enumerate() {
let (_, packed_location) = rect_placements.packed_locations().get(&index).unwrap();
let min = UVec2::new(packed_location.x(), packed_location.y());
let max =
min + UVec2::new(packed_location.width(), packed_location.height()) - self.padding;
if let Some(image_id) = image_id {
texture_ids.insert(*image_id, index);
}
texture_rects.push(URect { min, max });
if texture.texture_descriptor.format != self.format && !self.auto_format_conversion {
warn!(
"Loading a texture of format '{:?}' in an atlas with format '{:?}'",
texture.texture_descriptor.format, self.format
);
return Err(TextureAtlasBuilderError::WrongFormat);
}
self.copy_converted_texture(&mut atlas_texture, texture, packed_location)?;
}
Ok((
TextureAtlasLayout {
size: atlas_texture.size(),
textures: texture_rects,
},
TextureAtlasSources { texture_ids },
atlas_texture,
))
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_image/src/exr_texture_loader.rs | crates/bevy_image/src/exr_texture_loader.rs | use crate::{Image, TextureAccessError, TextureFormatPixelInfo};
use bevy_asset::{io::Reader, AssetLoader, LoadContext, RenderAssetUsages};
use bevy_reflect::TypePath;
use image::ImageDecoder;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use wgpu_types::{Extent3d, TextureDimension, TextureFormat};
/// Loads EXR textures as Texture assets
#[derive(Clone, Default, TypePath)]
#[cfg(feature = "exr")]
pub struct ExrTextureLoader;
#[derive(Serialize, Deserialize, Default, Debug)]
#[cfg(feature = "exr")]
pub struct ExrTextureLoaderSettings {
pub asset_usage: RenderAssetUsages,
}
/// Possible errors that can be produced by [`ExrTextureLoader`]
#[non_exhaustive]
#[derive(Debug, Error, TypePath)]
#[cfg(feature = "exr")]
pub enum ExrTextureLoaderError {
#[error(transparent)]
Io(#[from] std::io::Error),
#[error(transparent)]
ImageError(#[from] image::ImageError),
#[error("Texture access error: {0}")]
TextureAccess(#[from] TextureAccessError),
}
impl AssetLoader for ExrTextureLoader {
type Asset = Image;
type Settings = ExrTextureLoaderSettings;
type Error = ExrTextureLoaderError;
async fn load(
&self,
reader: &mut dyn Reader,
settings: &Self::Settings,
_load_context: &mut LoadContext<'_>,
) -> Result<Image, Self::Error> {
let format = TextureFormat::Rgba32Float;
debug_assert_eq!(
format.pixel_size()?,
4 * 4,
"Format should have 32bit x 4 size"
);
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let decoder = image::codecs::openexr::OpenExrDecoder::with_alpha_preference(
std::io::Cursor::new(bytes),
Some(true),
)?;
let (width, height) = decoder.dimensions();
let total_bytes = decoder.total_bytes() as usize;
let mut buf = vec![0u8; total_bytes];
decoder.read_image(buf.as_mut_slice())?;
Ok(Image::new(
Extent3d {
width,
height,
depth_or_array_layers: 1,
},
TextureDimension::D2,
buf,
format,
settings.asset_usage,
))
}
fn extensions(&self) -> &[&str] {
&["exr"]
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_anti_alias/src/lib.rs | crates/bevy_anti_alias/src/lib.rs | #![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"
)]
use bevy_app::Plugin;
use contrast_adaptive_sharpening::CasPlugin;
use fxaa::FxaaPlugin;
use smaa::SmaaPlugin;
use taa::TemporalAntiAliasPlugin;
pub mod contrast_adaptive_sharpening;
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
pub mod dlss;
pub mod fxaa;
pub mod smaa;
pub mod taa;
/// Adds fxaa, smaa, taa, contrast aware sharpening, and optional dlss support.
#[derive(Default)]
pub struct AntiAliasPlugin;
impl Plugin for AntiAliasPlugin {
fn build(&self, app: &mut bevy_app::App) {
app.add_plugins((
FxaaPlugin,
SmaaPlugin,
TemporalAntiAliasPlugin,
CasPlugin,
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
dlss::DlssPlugin,
));
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_anti_alias/src/fxaa/node.rs | crates/bevy_anti_alias/src/fxaa/node.rs | use std::sync::Mutex;
use crate::fxaa::{CameraFxaaPipeline, Fxaa, FxaaPipeline};
use bevy_ecs::{prelude::*, query::QueryItem};
use bevy_render::{
diagnostic::RecordDiagnostics,
render_graph::{NodeRunError, RenderGraphContext, ViewNode},
render_resource::{
BindGroup, BindGroupEntries, Operations, PipelineCache, RenderPassColorAttachment,
RenderPassDescriptor, TextureViewId,
},
renderer::RenderContext,
view::ViewTarget,
};
#[derive(Default)]
pub struct FxaaNode {
cached_texture_bind_group: Mutex<Option<(TextureViewId, BindGroup)>>,
}
impl ViewNode for FxaaNode {
type ViewQuery = (
&'static ViewTarget,
&'static CameraFxaaPipeline,
&'static Fxaa,
);
fn run(
&self,
_graph: &mut RenderGraphContext,
render_context: &mut RenderContext,
(target, pipeline, fxaa): QueryItem<Self::ViewQuery>,
world: &World,
) -> Result<(), NodeRunError> {
let pipeline_cache = world.resource::<PipelineCache>();
let fxaa_pipeline = world.resource::<FxaaPipeline>();
if !fxaa.enabled {
return Ok(());
};
let Some(pipeline) = pipeline_cache.get_render_pipeline(pipeline.pipeline_id) else {
return Ok(());
};
let diagnostics = render_context.diagnostic_recorder();
let post_process = target.post_process_write();
let source = post_process.source;
let destination = post_process.destination;
let mut cached_bind_group = self.cached_texture_bind_group.lock().unwrap();
let bind_group = match &mut *cached_bind_group {
Some((id, bind_group)) if source.id() == *id => bind_group,
cached_bind_group => {
let bind_group = render_context.render_device().create_bind_group(
None,
&pipeline_cache.get_bind_group_layout(&fxaa_pipeline.texture_bind_group),
&BindGroupEntries::sequential((source, &fxaa_pipeline.sampler)),
);
let (_, bind_group) = cached_bind_group.insert((source.id(), bind_group));
bind_group
}
};
let pass_descriptor = RenderPassDescriptor {
label: Some("fxaa"),
color_attachments: &[Some(RenderPassColorAttachment {
view: destination,
depth_slice: None,
resolve_target: None,
ops: Operations::default(),
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
};
let mut render_pass = render_context
.command_encoder()
.begin_render_pass(&pass_descriptor);
let pass_span = diagnostics.pass_span(&mut render_pass, "fxaa");
render_pass.set_pipeline(pipeline);
render_pass.set_bind_group(0, bind_group, &[]);
render_pass.draw(0..3, 0..1);
pass_span.end(&mut render_pass);
Ok(())
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_anti_alias/src/fxaa/mod.rs | crates/bevy_anti_alias/src/fxaa/mod.rs | use bevy_app::prelude::*;
use bevy_asset::{embedded_asset, load_embedded_asset, AssetServer, Handle};
use bevy_camera::Camera;
use bevy_core_pipeline::{
core_2d::graph::{Core2d, Node2d},
core_3d::graph::{Core3d, Node3d},
FullscreenShader,
};
use bevy_ecs::prelude::*;
use bevy_image::BevyDefault as _;
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
use bevy_render::{
extract_component::{ExtractComponent, ExtractComponentPlugin},
render_graph::{RenderGraphExt, ViewNodeRunner},
render_resource::{
binding_types::{sampler, texture_2d},
*,
},
renderer::RenderDevice,
view::{ExtractedView, ViewTarget},
Render, RenderApp, RenderStartup, RenderSystems,
};
use bevy_shader::Shader;
use bevy_utils::default;
mod node;
pub use node::FxaaNode;
#[derive(Debug, Reflect, Eq, PartialEq, Hash, Clone, Copy)]
#[reflect(PartialEq, Hash, Clone)]
pub enum Sensitivity {
Low,
Medium,
High,
Ultra,
Extreme,
}
impl Sensitivity {
pub fn get_str(&self) -> &str {
match self {
Sensitivity::Low => "LOW",
Sensitivity::Medium => "MEDIUM",
Sensitivity::High => "HIGH",
Sensitivity::Ultra => "ULTRA",
Sensitivity::Extreme => "EXTREME",
}
}
}
/// A component for enabling Fast Approximate Anti-Aliasing (FXAA)
/// for a [`bevy_camera::Camera`].
#[derive(Reflect, Component, Clone, ExtractComponent)]
#[reflect(Component, Default, Clone)]
#[extract_component_filter(With<Camera>)]
#[doc(alias = "FastApproximateAntiAliasing")]
pub struct Fxaa {
/// Enable render passes for FXAA.
pub enabled: bool,
/// Use lower sensitivity for a sharper, faster, result.
/// Use higher sensitivity for a slower, smoother, result.
/// [`Ultra`](`Sensitivity::Ultra`) and [`Extreme`](`Sensitivity::Extreme`)
/// settings can result in significant smearing and loss of detail.
///
/// The minimum amount of local contrast required to apply algorithm.
pub edge_threshold: Sensitivity,
/// Trims the algorithm from processing darks.
pub edge_threshold_min: Sensitivity,
}
impl Default for Fxaa {
fn default() -> Self {
Fxaa {
enabled: true,
edge_threshold: Sensitivity::High,
edge_threshold_min: Sensitivity::High,
}
}
}
/// Adds support for Fast Approximate Anti-Aliasing (FXAA)
#[derive(Default)]
pub struct FxaaPlugin;
impl Plugin for FxaaPlugin {
fn build(&self, app: &mut App) {
embedded_asset!(app, "fxaa.wgsl");
app.add_plugins(ExtractComponentPlugin::<Fxaa>::default());
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
return;
};
render_app
.init_resource::<SpecializedRenderPipelines<FxaaPipeline>>()
.add_systems(RenderStartup, init_fxaa_pipeline)
.add_systems(
Render,
prepare_fxaa_pipelines.in_set(RenderSystems::Prepare),
)
.add_render_graph_node::<ViewNodeRunner<FxaaNode>>(Core3d, Node3d::Fxaa)
.add_render_graph_edges(
Core3d,
(
Node3d::Tonemapping,
Node3d::Fxaa,
Node3d::EndMainPassPostProcessing,
),
)
.add_render_graph_node::<ViewNodeRunner<FxaaNode>>(Core2d, Node2d::Fxaa)
.add_render_graph_edges(
Core2d,
(
Node2d::Tonemapping,
Node2d::Fxaa,
Node2d::EndMainPassPostProcessing,
),
);
}
}
#[derive(Resource)]
pub struct FxaaPipeline {
texture_bind_group: BindGroupLayoutDescriptor,
sampler: Sampler,
fullscreen_shader: FullscreenShader,
fragment_shader: Handle<Shader>,
}
pub fn init_fxaa_pipeline(
mut commands: Commands,
render_device: Res<RenderDevice>,
fullscreen_shader: Res<FullscreenShader>,
asset_server: Res<AssetServer>,
) {
let texture_bind_group = BindGroupLayoutDescriptor::new(
"fxaa_texture_bind_group_layout",
&BindGroupLayoutEntries::sequential(
ShaderStages::FRAGMENT,
(
texture_2d(TextureSampleType::Float { filterable: true }),
sampler(SamplerBindingType::Filtering),
),
),
);
let sampler = render_device.create_sampler(&SamplerDescriptor {
mipmap_filter: FilterMode::Linear,
mag_filter: FilterMode::Linear,
min_filter: FilterMode::Linear,
..default()
});
commands.insert_resource(FxaaPipeline {
texture_bind_group,
sampler,
fullscreen_shader: fullscreen_shader.clone(),
fragment_shader: load_embedded_asset!(asset_server.as_ref(), "fxaa.wgsl"),
});
}
#[derive(Component)]
pub struct CameraFxaaPipeline {
pub pipeline_id: CachedRenderPipelineId,
}
#[derive(PartialEq, Eq, Hash, Clone, Copy)]
pub struct FxaaPipelineKey {
edge_threshold: Sensitivity,
edge_threshold_min: Sensitivity,
texture_format: TextureFormat,
}
impl SpecializedRenderPipeline for FxaaPipeline {
type Key = FxaaPipelineKey;
fn specialize(&self, key: Self::Key) -> RenderPipelineDescriptor {
RenderPipelineDescriptor {
label: Some("fxaa".into()),
layout: vec![self.texture_bind_group.clone()],
vertex: self.fullscreen_shader.to_vertex_state(),
fragment: Some(FragmentState {
shader: self.fragment_shader.clone(),
shader_defs: vec![
format!("EDGE_THRESH_{}", key.edge_threshold.get_str()).into(),
format!("EDGE_THRESH_MIN_{}", key.edge_threshold_min.get_str()).into(),
],
targets: vec![Some(ColorTargetState {
format: key.texture_format,
blend: None,
write_mask: ColorWrites::ALL,
})],
..default()
}),
..default()
}
}
}
pub fn prepare_fxaa_pipelines(
mut commands: Commands,
pipeline_cache: Res<PipelineCache>,
mut pipelines: ResMut<SpecializedRenderPipelines<FxaaPipeline>>,
fxaa_pipeline: Res<FxaaPipeline>,
views: Query<(Entity, &ExtractedView, &Fxaa)>,
) {
for (entity, view, fxaa) in &views {
if !fxaa.enabled {
continue;
}
let pipeline_id = pipelines.specialize(
&pipeline_cache,
&fxaa_pipeline,
FxaaPipelineKey {
edge_threshold: fxaa.edge_threshold,
edge_threshold_min: fxaa.edge_threshold_min,
texture_format: if view.hdr {
ViewTarget::TEXTURE_FORMAT_HDR
} else {
TextureFormat::bevy_default()
},
},
);
commands
.entity(entity)
.insert(CameraFxaaPipeline { pipeline_id });
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_anti_alias/src/contrast_adaptive_sharpening/node.rs | crates/bevy_anti_alias/src/contrast_adaptive_sharpening/node.rs | use std::sync::Mutex;
use crate::contrast_adaptive_sharpening::ViewCasPipeline;
use bevy_ecs::prelude::*;
use bevy_render::{
diagnostic::RecordDiagnostics,
extract_component::{ComponentUniforms, DynamicUniformIndex},
render_graph::{Node, NodeRunError, RenderGraphContext},
render_resource::{
BindGroup, BindGroupEntries, BufferId, Operations, PipelineCache,
RenderPassColorAttachment, RenderPassDescriptor, TextureViewId,
},
renderer::RenderContext,
view::{ExtractedView, ViewTarget},
};
use super::{CasPipeline, CasUniform};
pub struct CasNode {
query: QueryState<
(
&'static ViewTarget,
&'static ViewCasPipeline,
&'static DynamicUniformIndex<CasUniform>,
),
With<ExtractedView>,
>,
cached_bind_group: Mutex<Option<(BufferId, TextureViewId, BindGroup)>>,
}
impl FromWorld for CasNode {
fn from_world(world: &mut World) -> Self {
Self {
query: QueryState::new(world),
cached_bind_group: Mutex::new(None),
}
}
}
impl Node for CasNode {
fn update(&mut self, world: &mut World) {
self.query.update_archetypes(world);
}
fn run(
&self,
graph: &mut RenderGraphContext,
render_context: &mut RenderContext,
world: &World,
) -> Result<(), NodeRunError> {
let view_entity = graph.view_entity();
let pipeline_cache = world.resource::<PipelineCache>();
let sharpening_pipeline = world.resource::<CasPipeline>();
let uniforms = world.resource::<ComponentUniforms<CasUniform>>();
let Ok((target, pipeline, uniform_index)) = self.query.get_manual(world, view_entity)
else {
return Ok(());
};
let uniforms_id = uniforms.buffer().unwrap().id();
let Some(uniforms) = uniforms.binding() else {
return Ok(());
};
let Some(pipeline) = pipeline_cache.get_render_pipeline(pipeline.0) else {
return Ok(());
};
let diagnostics = render_context.diagnostic_recorder();
let view_target = target.post_process_write();
let source = view_target.source;
let destination = view_target.destination;
let mut cached_bind_group = self.cached_bind_group.lock().unwrap();
let bind_group = match &mut *cached_bind_group {
Some((buffer_id, texture_id, bind_group))
if source.id() == *texture_id && uniforms_id == *buffer_id =>
{
bind_group
}
cached_bind_group => {
let bind_group = render_context.render_device().create_bind_group(
"cas_bind_group",
&pipeline_cache.get_bind_group_layout(&sharpening_pipeline.layout),
&BindGroupEntries::sequential((
view_target.source,
&sharpening_pipeline.sampler,
uniforms,
)),
);
let (_, _, bind_group) =
cached_bind_group.insert((uniforms_id, source.id(), bind_group));
bind_group
}
};
let pass_descriptor = RenderPassDescriptor {
label: Some("contrast_adaptive_sharpening"),
color_attachments: &[Some(RenderPassColorAttachment {
view: destination,
depth_slice: None,
resolve_target: None,
ops: Operations::default(),
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
};
let mut render_pass = render_context
.command_encoder()
.begin_render_pass(&pass_descriptor);
let pass_span = diagnostics.pass_span(&mut render_pass, "contrast_adaptive_sharpening");
render_pass.set_pipeline(pipeline);
render_pass.set_bind_group(0, bind_group, &[uniform_index.index()]);
render_pass.draw(0..3, 0..1);
pass_span.end(&mut render_pass);
Ok(())
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_anti_alias/src/contrast_adaptive_sharpening/mod.rs | crates/bevy_anti_alias/src/contrast_adaptive_sharpening/mod.rs | use bevy_app::prelude::*;
use bevy_asset::{embedded_asset, load_embedded_asset, AssetServer};
use bevy_camera::Camera;
use bevy_core_pipeline::{
core_2d::graph::{Core2d, Node2d},
core_3d::graph::{Core3d, Node3d},
FullscreenShader,
};
use bevy_ecs::{prelude::*, query::QueryItem};
use bevy_image::BevyDefault as _;
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
use bevy_render::{
extract_component::{ExtractComponent, ExtractComponentPlugin, UniformComponentPlugin},
render_graph::RenderGraphExt,
render_resource::{
binding_types::{sampler, texture_2d, uniform_buffer},
*,
},
renderer::RenderDevice,
view::{ExtractedView, ViewTarget},
Render, RenderApp, RenderStartup, RenderSystems,
};
mod node;
pub use node::CasNode;
/// Applies a contrast adaptive sharpening (CAS) filter to the camera.
///
/// CAS is usually used in combination with shader based anti-aliasing methods
/// such as FXAA or TAA to regain some of the lost detail from the blurring that they introduce.
///
/// CAS is designed to adjust the amount of sharpening applied to different areas of an image
/// based on the local contrast. This can help avoid over-sharpening areas with high contrast
/// and under-sharpening areas with low contrast.
///
/// To use this, add the [`ContrastAdaptiveSharpening`] component to a 2D or 3D camera.
#[derive(Component, Reflect, Clone)]
#[reflect(Component, Default, Clone)]
pub struct ContrastAdaptiveSharpening {
/// Enable or disable sharpening.
pub enabled: bool,
/// Adjusts sharpening strength. Higher values increase the amount of sharpening.
///
/// Clamped between 0.0 and 1.0.
///
/// The default value is 0.6.
pub sharpening_strength: f32,
/// Whether to try and avoid sharpening areas that are already noisy.
///
/// You probably shouldn't use this, and just leave it set to false.
/// You should generally apply any sort of film grain or similar effects after CAS
/// and upscaling to avoid artifacts.
pub denoise: bool,
}
impl Default for ContrastAdaptiveSharpening {
fn default() -> Self {
ContrastAdaptiveSharpening {
enabled: true,
sharpening_strength: 0.6,
denoise: false,
}
}
}
#[derive(Component, Default, Reflect, Clone)]
#[reflect(Component, Default, Clone)]
pub struct DenoiseCas(bool);
/// The uniform struct extracted from [`ContrastAdaptiveSharpening`] attached to a [`Camera`].
/// Will be available for use in the CAS shader.
#[doc(hidden)]
#[derive(Component, ShaderType, Clone)]
pub struct CasUniform {
sharpness: f32,
}
impl ExtractComponent for ContrastAdaptiveSharpening {
type QueryData = &'static Self;
type QueryFilter = With<Camera>;
type Out = (DenoiseCas, CasUniform);
fn extract_component(item: QueryItem<Self::QueryData>) -> Option<Self::Out> {
if !item.enabled || item.sharpening_strength == 0.0 {
return None;
}
Some((
DenoiseCas(item.denoise),
CasUniform {
// above 1.0 causes extreme artifacts and fireflies
sharpness: item.sharpening_strength.clamp(0.0, 1.0),
},
))
}
}
/// Adds Support for Contrast Adaptive Sharpening (CAS).
#[derive(Default)]
pub struct CasPlugin;
impl Plugin for CasPlugin {
fn build(&self, app: &mut App) {
embedded_asset!(app, "robust_contrast_adaptive_sharpening.wgsl");
app.add_plugins((
ExtractComponentPlugin::<ContrastAdaptiveSharpening>::default(),
UniformComponentPlugin::<CasUniform>::default(),
));
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
return;
};
render_app
.add_systems(RenderStartup, init_cas_pipeline)
.add_systems(Render, prepare_cas_pipelines.in_set(RenderSystems::Prepare));
{
render_app
.add_render_graph_node::<CasNode>(Core3d, Node3d::ContrastAdaptiveSharpening)
.add_render_graph_edge(
Core3d,
Node3d::Tonemapping,
Node3d::ContrastAdaptiveSharpening,
)
.add_render_graph_edges(
Core3d,
(
Node3d::Fxaa,
Node3d::ContrastAdaptiveSharpening,
Node3d::EndMainPassPostProcessing,
),
);
}
{
render_app
.add_render_graph_node::<CasNode>(Core2d, Node2d::ContrastAdaptiveSharpening)
.add_render_graph_edge(
Core2d,
Node2d::Tonemapping,
Node2d::ContrastAdaptiveSharpening,
)
.add_render_graph_edges(
Core2d,
(
Node2d::Fxaa,
Node2d::ContrastAdaptiveSharpening,
Node2d::EndMainPassPostProcessing,
),
);
}
}
}
#[derive(Resource)]
pub struct CasPipeline {
layout: BindGroupLayoutDescriptor,
sampler: Sampler,
variants: Variants<RenderPipeline, CasPipelineSpecializer>,
}
pub fn init_cas_pipeline(
mut commands: Commands,
render_device: Res<RenderDevice>,
fullscreen_shader: Res<FullscreenShader>,
asset_server: Res<AssetServer>,
) {
let layout = BindGroupLayoutDescriptor::new(
"sharpening_texture_bind_group_layout",
&BindGroupLayoutEntries::sequential(
ShaderStages::FRAGMENT,
(
texture_2d(TextureSampleType::Float { filterable: true }),
sampler(SamplerBindingType::Filtering),
// CAS Settings
uniform_buffer::<CasUniform>(true),
),
),
);
let sampler = render_device.create_sampler(&SamplerDescriptor::default());
let fragment_shader = load_embedded_asset!(
asset_server.as_ref(),
"robust_contrast_adaptive_sharpening.wgsl"
);
let variants = Variants::new(
CasPipelineSpecializer,
RenderPipelineDescriptor {
label: Some("contrast_adaptive_sharpening".into()),
layout: vec![layout.clone()],
vertex: fullscreen_shader.to_vertex_state(),
fragment: Some(FragmentState {
shader: fragment_shader,
..Default::default()
}),
..Default::default()
},
);
commands.insert_resource(CasPipeline {
layout,
sampler,
variants,
});
}
#[derive(PartialEq, Eq, Hash, Clone, Copy, SpecializerKey)]
pub struct CasPipelineKey {
texture_format: TextureFormat,
denoise: bool,
}
pub struct CasPipelineSpecializer;
impl Specializer<RenderPipeline> for CasPipelineSpecializer {
type Key = CasPipelineKey;
fn specialize(
&self,
key: Self::Key,
descriptor: &mut <RenderPipeline as Specializable>::Descriptor,
) -> Result<Canonical<Self::Key>, BevyError> {
let fragment = descriptor.fragment_mut()?;
if key.denoise {
fragment.shader_defs.push("RCAS_DENOISE".into());
}
fragment.set_target(
0,
ColorTargetState {
format: key.texture_format,
blend: None,
write_mask: ColorWrites::ALL,
},
);
Ok(key)
}
}
fn prepare_cas_pipelines(
mut commands: Commands,
pipeline_cache: Res<PipelineCache>,
mut sharpening_pipeline: ResMut<CasPipeline>,
views: Query<
(Entity, &ExtractedView, &DenoiseCas),
Or<(Added<CasUniform>, Changed<DenoiseCas>)>,
>,
mut removals: RemovedComponents<CasUniform>,
) -> Result<(), BevyError> {
for entity in removals.read() {
commands.entity(entity).remove::<ViewCasPipeline>();
}
for (entity, view, denoise_cas) in &views {
let pipeline_id = sharpening_pipeline.variants.specialize(
&pipeline_cache,
CasPipelineKey {
denoise: denoise_cas.0,
texture_format: if view.hdr {
ViewTarget::TEXTURE_FORMAT_HDR
} else {
TextureFormat::bevy_default()
},
},
)?;
commands.entity(entity).insert(ViewCasPipeline(pipeline_id));
}
Ok(())
}
#[derive(Component)]
pub struct ViewCasPipeline(CachedRenderPipelineId);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_anti_alias/src/taa/mod.rs | crates/bevy_anti_alias/src/taa/mod.rs | use bevy_app::{App, Plugin};
use bevy_asset::{embedded_asset, load_embedded_asset, AssetServer};
use bevy_camera::{Camera, Camera3d};
use bevy_core_pipeline::{
core_3d::graph::{Core3d, Node3d},
prepass::{DepthPrepass, MotionVectorPrepass, ViewPrepassTextures},
FullscreenShader,
};
use bevy_diagnostic::FrameCount;
use bevy_ecs::{
error::BevyError,
prelude::{Component, Entity, ReflectComponent},
query::{QueryItem, With},
resource::Resource,
schedule::IntoScheduleConfigs,
system::{Commands, Query, Res, ResMut},
world::World,
};
use bevy_image::{BevyDefault as _, ToExtents};
use bevy_math::vec2;
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
use bevy_render::{
camera::{ExtractedCamera, MipBias, TemporalJitter},
diagnostic::RecordDiagnostics,
render_graph::{NodeRunError, RenderGraphContext, RenderGraphExt, ViewNode, ViewNodeRunner},
render_resource::{
binding_types::{sampler, texture_2d, texture_depth_2d},
BindGroupEntries, BindGroupLayoutDescriptor, BindGroupLayoutEntries,
CachedRenderPipelineId, Canonical, ColorTargetState, ColorWrites, FilterMode,
FragmentState, Operations, PipelineCache, RenderPassColorAttachment, RenderPassDescriptor,
RenderPipeline, RenderPipelineDescriptor, Sampler, SamplerBindingType, SamplerDescriptor,
ShaderStages, Specializer, SpecializerKey, TextureDescriptor, TextureDimension,
TextureFormat, TextureSampleType, TextureUsages, Variants,
},
renderer::{RenderContext, RenderDevice},
sync_component::SyncComponentPlugin,
sync_world::RenderEntity,
texture::{CachedTexture, TextureCache},
view::{ExtractedView, Msaa, ViewTarget},
ExtractSchedule, MainWorld, Render, RenderApp, RenderStartup, RenderSystems,
};
use bevy_utils::default;
use tracing::warn;
/// Plugin for temporal anti-aliasing.
///
/// See [`TemporalAntiAliasing`] for more details.
#[derive(Default)]
pub struct TemporalAntiAliasPlugin;
impl Plugin for TemporalAntiAliasPlugin {
fn build(&self, app: &mut App) {
embedded_asset!(app, "taa.wgsl");
app.add_plugins(SyncComponentPlugin::<TemporalAntiAliasing>::default());
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
return;
};
render_app
.add_systems(RenderStartup, init_taa_pipeline)
.add_systems(ExtractSchedule, extract_taa_settings)
.add_systems(
Render,
(
prepare_taa_jitter.in_set(RenderSystems::ManageViews),
prepare_taa_pipelines.in_set(RenderSystems::Prepare),
prepare_taa_history_textures.in_set(RenderSystems::PrepareResources),
),
)
.add_render_graph_node::<ViewNodeRunner<TemporalAntiAliasNode>>(Core3d, Node3d::Taa)
.add_render_graph_edges(
Core3d,
(
Node3d::StartMainPassPostProcessing,
Node3d::MotionBlur, // Running before TAA reduces edge artifacts and noise
Node3d::Taa,
Node3d::Bloom,
Node3d::Tonemapping,
),
);
}
}
/// Component to apply temporal anti-aliasing to a 3D camera.
///
/// Temporal anti-aliasing (TAA) is a form of image smoothing/filtering, like
/// multisample anti-aliasing (MSAA), or fast approximate anti-aliasing (FXAA).
/// TAA works by blending (averaging) each frame with the past few frames.
///
/// # Tradeoffs
///
/// Pros:
/// * Filters more types of aliasing than MSAA, such as textures and singular bright pixels (specular aliasing)
/// * Cost scales with screen/view resolution, unlike MSAA which scales with number of triangles
/// * Greatly increases the quality of stochastic rendering techniques such as SSAO, certain shadow map sampling methods, etc
///
/// Cons:
/// * Chance of "ghosting" - ghostly trails left behind moving objects
/// * Thin geometry, lighting detail, or texture lines may flicker noisily or disappear
///
/// Because TAA blends past frames with the current frame, when the frames differ too much
/// (such as with fast moving objects or camera cuts), ghosting artifacts may occur.
///
/// Artifacts tend to be reduced at higher framerates and rendering resolution.
///
/// # Usage Notes
///
/// Any camera with this component must also disable [`Msaa`] by setting it to [`Msaa::Off`].
///
/// TAA also does not work well with alpha-blended meshes, as it requires depth writing to determine motion.
///
/// It is very important that correct motion vectors are written for everything on screen.
/// Failure to do so will lead to ghosting artifacts. For instance, if particle effects
/// are added using a third party library, the library must either:
///
/// 1. Write particle motion vectors to the motion vectors prepass texture
/// 2. Render particles after TAA
#[derive(Component, Reflect, Clone)]
#[reflect(Component, Default, Clone)]
#[require(TemporalJitter, MipBias, DepthPrepass, MotionVectorPrepass)]
#[doc(alias = "Taa")]
pub struct TemporalAntiAliasing {
/// Set to true to delete the saved temporal history (past frames).
///
/// Useful for preventing ghosting when the history is no longer
/// representative of the current frame, such as in sudden camera cuts.
///
/// After setting this to true, it will automatically be toggled
/// back to false at the end of the frame.
pub reset: bool,
}
impl Default for TemporalAntiAliasing {
fn default() -> Self {
Self { reset: true }
}
}
/// Render [`bevy_render::render_graph::Node`] used by temporal anti-aliasing.
#[derive(Default)]
pub struct TemporalAntiAliasNode;
impl ViewNode for TemporalAntiAliasNode {
type ViewQuery = (
&'static ExtractedCamera,
&'static ViewTarget,
&'static TemporalAntiAliasHistoryTextures,
&'static ViewPrepassTextures,
&'static TemporalAntiAliasPipelineId,
&'static Msaa,
);
fn run(
&self,
_graph: &mut RenderGraphContext,
render_context: &mut RenderContext,
(camera, view_target, taa_history_textures, prepass_textures, taa_pipeline_id, msaa): QueryItem<
Self::ViewQuery,
>,
world: &World,
) -> Result<(), NodeRunError> {
if *msaa != Msaa::Off {
warn!("Temporal anti-aliasing requires MSAA to be disabled");
return Ok(());
}
let (Some(pipelines), Some(pipeline_cache)) = (
world.get_resource::<TaaPipeline>(),
world.get_resource::<PipelineCache>(),
) else {
return Ok(());
};
let (Some(taa_pipeline), Some(prepass_motion_vectors_texture), Some(prepass_depth_texture)) = (
pipeline_cache.get_render_pipeline(taa_pipeline_id.0),
&prepass_textures.motion_vectors,
&prepass_textures.depth,
) else {
return Ok(());
};
let diagnostics = render_context.diagnostic_recorder();
let view_target = view_target.post_process_write();
let taa_bind_group = render_context.render_device().create_bind_group(
"taa_bind_group",
&pipeline_cache.get_bind_group_layout(&pipelines.taa_bind_group_layout),
&BindGroupEntries::sequential((
view_target.source,
&taa_history_textures.read.default_view,
&prepass_motion_vectors_texture.texture.default_view,
&prepass_depth_texture.texture.default_view,
&pipelines.nearest_sampler,
&pipelines.linear_sampler,
)),
);
{
let mut taa_pass = render_context.begin_tracked_render_pass(RenderPassDescriptor {
label: Some("taa"),
color_attachments: &[
Some(RenderPassColorAttachment {
view: view_target.destination,
depth_slice: None,
resolve_target: None,
ops: Operations::default(),
}),
Some(RenderPassColorAttachment {
view: &taa_history_textures.write.default_view,
depth_slice: None,
resolve_target: None,
ops: Operations::default(),
}),
],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
});
let pass_span = diagnostics.pass_span(&mut taa_pass, "taa");
taa_pass.set_render_pipeline(taa_pipeline);
taa_pass.set_bind_group(0, &taa_bind_group, &[]);
if let Some(viewport) = camera.viewport.as_ref() {
taa_pass.set_camera_viewport(viewport);
}
taa_pass.draw(0..3, 0..1);
pass_span.end(&mut taa_pass);
}
Ok(())
}
}
#[derive(Resource)]
struct TaaPipeline {
taa_bind_group_layout: BindGroupLayoutDescriptor,
nearest_sampler: Sampler,
linear_sampler: Sampler,
variants: Variants<RenderPipeline, TaaPipelineSpecializer>,
}
fn init_taa_pipeline(
mut commands: Commands,
render_device: Res<RenderDevice>,
fullscreen_shader: Res<FullscreenShader>,
asset_server: Res<AssetServer>,
) {
let nearest_sampler = render_device.create_sampler(&SamplerDescriptor {
label: Some("taa_nearest_sampler"),
mag_filter: FilterMode::Nearest,
min_filter: FilterMode::Nearest,
..SamplerDescriptor::default()
});
let linear_sampler = render_device.create_sampler(&SamplerDescriptor {
label: Some("taa_linear_sampler"),
mag_filter: FilterMode::Linear,
min_filter: FilterMode::Linear,
..SamplerDescriptor::default()
});
let taa_bind_group_layout = BindGroupLayoutDescriptor::new(
"taa_bind_group_layout",
&BindGroupLayoutEntries::sequential(
ShaderStages::FRAGMENT,
(
// View target (read)
texture_2d(TextureSampleType::Float { filterable: true }),
// TAA History (read)
texture_2d(TextureSampleType::Float { filterable: true }),
// Motion Vectors
texture_2d(TextureSampleType::Float { filterable: true }),
// Depth
texture_depth_2d(),
// Nearest sampler
sampler(SamplerBindingType::NonFiltering),
// Linear sampler
sampler(SamplerBindingType::Filtering),
),
),
);
let fragment_shader = load_embedded_asset!(asset_server.as_ref(), "taa.wgsl");
let variants = Variants::new(
TaaPipelineSpecializer,
RenderPipelineDescriptor {
label: Some("taa_pipeline".into()),
layout: vec![taa_bind_group_layout.clone()],
vertex: fullscreen_shader.to_vertex_state(),
fragment: Some(FragmentState {
shader: fragment_shader,
..default()
}),
..default()
},
);
commands.insert_resource(TaaPipeline {
taa_bind_group_layout,
nearest_sampler,
linear_sampler,
variants,
});
}
struct TaaPipelineSpecializer;
#[derive(PartialEq, Eq, Hash, Clone, SpecializerKey)]
struct TaaPipelineKey {
hdr: bool,
reset: bool,
}
impl Specializer<RenderPipeline> for TaaPipelineSpecializer {
type Key = TaaPipelineKey;
fn specialize(
&self,
key: Self::Key,
descriptor: &mut RenderPipelineDescriptor,
) -> Result<Canonical<Self::Key>, BevyError> {
let fragment = descriptor.fragment_mut()?;
let format = if key.hdr {
fragment.shader_defs.push("TONEMAP".into());
ViewTarget::TEXTURE_FORMAT_HDR
} else {
TextureFormat::bevy_default()
};
if key.reset {
fragment.shader_defs.push("RESET".into());
}
let color_target_state = ColorTargetState {
format,
blend: None,
write_mask: ColorWrites::ALL,
};
fragment.set_target(0, color_target_state.clone());
fragment.set_target(1, color_target_state);
Ok(key)
}
}
fn extract_taa_settings(mut commands: Commands, mut main_world: ResMut<MainWorld>) {
let mut cameras_3d =
main_world.query::<(RenderEntity, &Camera, Option<&mut TemporalAntiAliasing>)>();
for (entity, camera, taa_settings) in cameras_3d.iter_mut(&mut main_world) {
let mut entity_commands = commands
.get_entity(entity)
.expect("Camera entity wasn't synced.");
if let Some(mut taa_settings) = taa_settings
&& camera.is_active
{
entity_commands.insert(taa_settings.clone());
taa_settings.reset = false;
} else {
entity_commands.remove::<(
TemporalAntiAliasing,
TemporalAntiAliasHistoryTextures,
TemporalAntiAliasPipelineId,
)>();
}
}
}
fn prepare_taa_jitter(
frame_count: Res<FrameCount>,
mut query: Query<
&mut TemporalJitter,
(
With<TemporalAntiAliasing>,
With<Camera3d>,
With<TemporalJitter>,
With<DepthPrepass>,
With<MotionVectorPrepass>,
),
>,
) {
// Halton sequence (2, 3) - 0.5
let halton_sequence = [
vec2(0.0, 0.0),
vec2(0.0, -0.16666666),
vec2(-0.25, 0.16666669),
vec2(0.25, -0.3888889),
vec2(-0.375, -0.055555552),
vec2(0.125, 0.2777778),
vec2(-0.125, -0.2777778),
vec2(0.375, 0.055555582),
];
let offset = halton_sequence[frame_count.0 as usize % halton_sequence.len()];
for mut jitter in &mut query {
jitter.offset = offset;
}
}
#[derive(Component)]
pub struct TemporalAntiAliasHistoryTextures {
write: CachedTexture,
read: CachedTexture,
}
fn prepare_taa_history_textures(
mut commands: Commands,
mut texture_cache: ResMut<TextureCache>,
render_device: Res<RenderDevice>,
frame_count: Res<FrameCount>,
views: Query<(Entity, &ExtractedCamera, &ExtractedView), With<TemporalAntiAliasing>>,
) {
for (entity, camera, view) in &views {
if let Some(physical_target_size) = camera.physical_target_size {
let mut texture_descriptor = TextureDescriptor {
label: None,
size: physical_target_size.to_extents(),
mip_level_count: 1,
sample_count: 1,
dimension: TextureDimension::D2,
format: if view.hdr {
ViewTarget::TEXTURE_FORMAT_HDR
} else {
TextureFormat::bevy_default()
},
usage: TextureUsages::TEXTURE_BINDING | TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
};
texture_descriptor.label = Some("taa_history_1_texture");
let history_1_texture = texture_cache.get(&render_device, texture_descriptor.clone());
texture_descriptor.label = Some("taa_history_2_texture");
let history_2_texture = texture_cache.get(&render_device, texture_descriptor);
let textures = if frame_count.0.is_multiple_of(2) {
TemporalAntiAliasHistoryTextures {
write: history_1_texture,
read: history_2_texture,
}
} else {
TemporalAntiAliasHistoryTextures {
write: history_2_texture,
read: history_1_texture,
}
};
commands.entity(entity).insert(textures);
}
}
}
#[derive(Component)]
pub struct TemporalAntiAliasPipelineId(CachedRenderPipelineId);
fn prepare_taa_pipelines(
mut commands: Commands,
pipeline_cache: Res<PipelineCache>,
mut pipeline: ResMut<TaaPipeline>,
views: Query<(Entity, &ExtractedView, &TemporalAntiAliasing)>,
) -> Result<(), BevyError> {
for (entity, view, taa_settings) in &views {
let mut pipeline_key = TaaPipelineKey {
hdr: view.hdr,
reset: taa_settings.reset,
};
let pipeline_id = pipeline
.variants
.specialize(&pipeline_cache, pipeline_key.clone())?;
// Prepare non-reset pipeline anyways - it will be necessary next frame
if pipeline_key.reset {
pipeline_key.reset = false;
pipeline
.variants
.specialize(&pipeline_cache, pipeline_key)?;
}
commands
.entity(entity)
.insert(TemporalAntiAliasPipelineId(pipeline_id));
}
Ok(())
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_anti_alias/src/dlss/node.rs | crates/bevy_anti_alias/src/dlss/node.rs | use super::{
prepare::DlssRenderContext, Dlss, DlssFeature, DlssRayReconstructionFeature,
DlssSuperResolutionFeature, ViewDlssRayReconstructionTextures,
};
use bevy_camera::MainPassResolutionOverride;
use bevy_core_pipeline::prepass::ViewPrepassTextures;
use bevy_ecs::{query::QueryItem, world::World};
use bevy_render::{
camera::TemporalJitter,
diagnostic::RecordDiagnostics,
render_graph::{NodeRunError, RenderGraphContext, ViewNode},
renderer::{RenderAdapter, RenderContext},
view::ViewTarget,
};
use dlss_wgpu::{
ray_reconstruction::{
DlssRayReconstructionRenderParameters, DlssRayReconstructionSpecularGuide,
},
super_resolution::{DlssSuperResolutionExposure, DlssSuperResolutionRenderParameters},
};
use std::marker::PhantomData;
#[derive(Default)]
pub struct DlssNode<F: DlssFeature>(PhantomData<F>);
impl ViewNode for DlssNode<DlssSuperResolutionFeature> {
type ViewQuery = (
&'static Dlss<DlssSuperResolutionFeature>,
&'static DlssRenderContext<DlssSuperResolutionFeature>,
&'static MainPassResolutionOverride,
&'static TemporalJitter,
&'static ViewTarget,
&'static ViewPrepassTextures,
);
fn run(
&self,
_graph: &mut RenderGraphContext,
render_context: &mut RenderContext,
(
dlss,
dlss_context,
resolution_override,
temporal_jitter,
view_target,
prepass_textures,
): QueryItem<Self::ViewQuery>,
world: &World,
) -> Result<(), NodeRunError> {
let adapter = world.resource::<RenderAdapter>();
let (Some(prepass_depth_texture), Some(prepass_motion_vectors_texture)) =
(&prepass_textures.depth, &prepass_textures.motion_vectors)
else {
return Ok(());
};
let view_target = view_target.post_process_write();
let render_resolution = resolution_override.0;
let render_parameters = DlssSuperResolutionRenderParameters {
color: &view_target.source,
depth: &prepass_depth_texture.texture.default_view,
motion_vectors: &prepass_motion_vectors_texture.texture.default_view,
exposure: DlssSuperResolutionExposure::Automatic, // TODO
bias: None, // TODO
dlss_output: &view_target.destination,
reset: dlss.reset,
jitter_offset: -temporal_jitter.offset,
partial_texture_size: Some(render_resolution),
motion_vector_scale: Some(-render_resolution.as_vec2()),
};
let diagnostics = render_context.diagnostic_recorder();
let command_encoder = render_context.command_encoder();
let mut dlss_context = dlss_context.context.lock().unwrap();
command_encoder.push_debug_group("dlss_super_resolution");
let time_span = diagnostics.time_span(command_encoder, "dlss_super_resolution");
dlss_context
.render(render_parameters, command_encoder, &adapter)
.expect("Failed to render DLSS Super Resolution");
time_span.end(command_encoder);
command_encoder.pop_debug_group();
Ok(())
}
}
impl ViewNode for DlssNode<DlssRayReconstructionFeature> {
type ViewQuery = (
&'static Dlss<DlssRayReconstructionFeature>,
&'static DlssRenderContext<DlssRayReconstructionFeature>,
&'static MainPassResolutionOverride,
&'static TemporalJitter,
&'static ViewTarget,
&'static ViewPrepassTextures,
&'static ViewDlssRayReconstructionTextures,
);
fn run(
&self,
_graph: &mut RenderGraphContext,
render_context: &mut RenderContext,
(
dlss,
dlss_context,
resolution_override,
temporal_jitter,
view_target,
prepass_textures,
ray_reconstruction_textures,
): QueryItem<Self::ViewQuery>,
world: &World,
) -> Result<(), NodeRunError> {
let adapter = world.resource::<RenderAdapter>();
let (Some(prepass_depth_texture), Some(prepass_motion_vectors_texture)) =
(&prepass_textures.depth, &prepass_textures.motion_vectors)
else {
return Ok(());
};
let view_target = view_target.post_process_write();
let render_resolution = resolution_override.0;
let render_parameters = DlssRayReconstructionRenderParameters {
diffuse_albedo: &ray_reconstruction_textures.diffuse_albedo.default_view,
specular_albedo: &ray_reconstruction_textures.specular_albedo.default_view,
normals: &ray_reconstruction_textures.normal_roughness.default_view,
roughness: None,
color: &view_target.source,
depth: &prepass_depth_texture.texture.default_view,
motion_vectors: &prepass_motion_vectors_texture.texture.default_view,
specular_guide: DlssRayReconstructionSpecularGuide::SpecularMotionVectors(
&ray_reconstruction_textures
.specular_motion_vectors
.default_view,
),
screen_space_subsurface_scattering_guide: None, // TODO
bias: None, // TODO
dlss_output: &view_target.destination,
reset: dlss.reset,
jitter_offset: -temporal_jitter.offset,
partial_texture_size: Some(render_resolution),
motion_vector_scale: Some(-render_resolution.as_vec2()),
};
let diagnostics = render_context.diagnostic_recorder();
let command_encoder = render_context.command_encoder();
let mut dlss_context = dlss_context.context.lock().unwrap();
command_encoder.push_debug_group("dlss_ray_reconstruction");
let time_span = diagnostics.time_span(command_encoder, "dlss_ray_reconstruction");
dlss_context
.render(render_parameters, command_encoder, &adapter)
.expect("Failed to render DLSS Ray Reconstruction");
time_span.end(command_encoder);
command_encoder.pop_debug_group();
Ok(())
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_anti_alias/src/dlss/mod.rs | crates/bevy_anti_alias/src/dlss/mod.rs | //! NVIDIA Deep Learning Super Sampling (DLSS).
//!
//! DLSS uses machine learning models to upscale and anti-alias images.
//!
//! Requires a NVIDIA RTX GPU, and the Windows/Linux Vulkan rendering backend. Does not work on other platforms.
//!
//! See https://github.com/bevyengine/dlss_wgpu for licensing requirements and setup instructions.
//!
//! # Usage
//! 1. Enable Bevy's `dlss` feature
//! 2. During app setup, insert the `DlssProjectId` resource before `DefaultPlugins`
//! 3. Check for the presence of `Option<Res<DlssSuperResolutionSupported>>` at runtime to see if DLSS is supported on the current machine
//! 4. Add the `Dlss` component to your camera entity, optionally setting a specific `DlssPerfQualityMode` (defaults to `Auto`)
//! 5. Optionally add sharpening via `ContrastAdaptiveSharpening`
//! 6. Custom rendering code, including third party crates, should account for the optional `MainPassResolutionOverride` to work with DLSS (see the `custom_render_phase` example)
mod extract;
mod node;
mod prepare;
pub use dlss_wgpu::DlssPerfQualityMode;
use bevy_app::{App, Plugin};
use bevy_core_pipeline::{
core_3d::graph::{Core3d, Node3d},
prepass::{DepthPrepass, MotionVectorPrepass},
};
use bevy_ecs::prelude::*;
use bevy_math::{UVec2, Vec2};
use bevy_reflect::{reflect_remote, Reflect};
use bevy_render::{
camera::{MipBias, TemporalJitter},
render_graph::{RenderGraphExt, ViewNodeRunner},
renderer::{
raw_vulkan_init::{AdditionalVulkanFeatures, RawVulkanInitSettings},
RenderDevice, RenderQueue,
},
texture::CachedTexture,
view::{prepare_view_targets, Hdr},
ExtractSchedule, Render, RenderApp, RenderSystems,
};
use dlss_wgpu::{
ray_reconstruction::{
DlssRayReconstruction, DlssRayReconstructionDepthMode, DlssRayReconstructionRoughnessMode,
},
super_resolution::DlssSuperResolution,
FeatureSupport,
};
use std::{
marker::PhantomData,
ops::Deref,
sync::{Arc, Mutex},
};
use tracing::info;
use uuid::Uuid;
/// Initializes DLSS support in the renderer. This must be registered before [`RenderPlugin`](bevy_render::RenderPlugin) because
/// it configures render init code.
#[derive(Default)]
pub struct DlssInitPlugin;
impl Plugin for DlssInitPlugin {
#[allow(unsafe_code)]
fn build(&self, app: &mut App) {
let dlss_project_id = app.world().get_resource::<DlssProjectId>()
.expect("The `dlss` feature is enabled, but DlssProjectId was not added to the App before DlssInitPlugin.").0;
let mut raw_vulkan_settings = app
.world_mut()
.get_resource_or_init::<RawVulkanInitSettings>();
// SAFETY: this does not remove any instance features and only enables features that are supported
unsafe {
raw_vulkan_settings.add_create_instance_callback(
move |mut args, additional_vulkan_features| {
let mut feature_support = FeatureSupport::default();
match dlss_wgpu::register_instance_extensions(
dlss_project_id,
&mut args,
&mut feature_support,
) {
Ok(_) => {
if feature_support.super_resolution_supported {
additional_vulkan_features.insert::<DlssSuperResolutionSupported>();
}
if feature_support.ray_reconstruction_supported {
additional_vulkan_features
.insert::<DlssRayReconstructionSupported>();
}
}
Err(_) => {}
}
},
);
}
// SAFETY: this does not remove any device features and only enables features that are supported
unsafe {
raw_vulkan_settings.add_create_device_callback(
move |mut args, adapter, additional_vulkan_features| {
let mut feature_support = FeatureSupport::default();
match dlss_wgpu::register_device_extensions(
dlss_project_id,
&mut args,
adapter,
&mut feature_support,
) {
Ok(_) => {
if feature_support.super_resolution_supported {
additional_vulkan_features.insert::<DlssSuperResolutionSupported>();
} else {
additional_vulkan_features.remove::<DlssSuperResolutionSupported>();
}
if feature_support.ray_reconstruction_supported {
additional_vulkan_features
.insert::<DlssRayReconstructionSupported>();
} else {
additional_vulkan_features
.remove::<DlssRayReconstructionSupported>();
}
}
Err(_) => {}
}
},
)
};
}
}
/// Enables DLSS support. This requires [`DlssInitPlugin`] to function, which must be manually registered in the correct order
/// prior to registering this plugin.
#[derive(Default)]
pub struct DlssPlugin;
impl Plugin for DlssPlugin {
fn build(&self, app: &mut App) {
app.register_type::<Dlss<DlssSuperResolutionFeature>>()
.register_type::<Dlss<DlssRayReconstructionFeature>>();
}
fn finish(&self, app: &mut App) {
let (super_resolution_supported, ray_reconstruction_supported) = {
let features = app
.sub_app_mut(RenderApp)
.world()
.resource::<AdditionalVulkanFeatures>();
(
features.has::<DlssSuperResolutionSupported>(),
features.has::<DlssRayReconstructionSupported>(),
)
};
if !super_resolution_supported {
return;
}
let wgpu_device = {
let render_world = app.sub_app(RenderApp).world();
let render_device = render_world.resource::<RenderDevice>().wgpu_device();
render_device.clone()
};
let project_id = app.world().get_resource::<DlssProjectId>()
.expect("The `dlss` feature is enabled, but DlssProjectId was not added to the App before DlssPlugin.");
let dlss_sdk = dlss_wgpu::DlssSdk::new(project_id.0, wgpu_device);
if dlss_sdk.is_err() {
info!("DLSS is not supported on this system");
return;
}
app.insert_resource(DlssSuperResolutionSupported);
if ray_reconstruction_supported {
app.insert_resource(DlssRayReconstructionSupported);
}
app.sub_app_mut(RenderApp)
.insert_resource(DlssSdk(dlss_sdk.unwrap()))
.add_systems(
ExtractSchedule,
(
extract::extract_dlss::<DlssSuperResolutionFeature>,
extract::extract_dlss::<DlssRayReconstructionFeature>,
),
)
.add_systems(
Render,
(
prepare::prepare_dlss::<DlssSuperResolutionFeature>,
prepare::prepare_dlss::<DlssRayReconstructionFeature>,
)
.in_set(RenderSystems::ManageViews)
.before(prepare_view_targets),
)
.add_render_graph_node::<ViewNodeRunner<node::DlssNode<DlssSuperResolutionFeature>>>(
Core3d,
Node3d::DlssSuperResolution,
)
.add_render_graph_node::<ViewNodeRunner<node::DlssNode<DlssRayReconstructionFeature>>>(
Core3d,
Node3d::DlssRayReconstruction,
)
.add_render_graph_edges(
Core3d,
(
Node3d::EndMainPass,
Node3d::MotionBlur, // Running before DLSS reduces edge artifacts and noise
Node3d::DlssSuperResolution,
Node3d::DlssRayReconstruction,
Node3d::Bloom,
Node3d::Tonemapping,
),
);
}
}
/// Camera component to enable DLSS.
#[derive(Component, Reflect, Clone)]
#[reflect(Component)]
#[require(TemporalJitter, MipBias, DepthPrepass, MotionVectorPrepass, Hdr)]
pub struct Dlss<F: DlssFeature = DlssSuperResolutionFeature> {
/// How much upscaling should be applied.
#[reflect(remote = DlssPerfQualityModeRemoteReflect)]
pub perf_quality_mode: DlssPerfQualityMode,
/// Set to true to delete the saved temporal history (past frames).
///
/// Useful for preventing ghosting when the history is no longer
/// representative of the current frame, such as in sudden camera cuts.
///
/// After setting this to true, it will automatically be toggled
/// back to false at the end of the frame.
pub reset: bool,
#[reflect(ignore)]
pub _phantom_data: PhantomData<F>,
}
impl Default for Dlss<DlssSuperResolutionFeature> {
fn default() -> Self {
Self {
perf_quality_mode: Default::default(),
reset: Default::default(),
_phantom_data: Default::default(),
}
}
}
pub trait DlssFeature: Reflect + Clone + Default {
type Context: Send;
fn upscaled_resolution(context: &Self::Context) -> UVec2;
fn render_resolution(context: &Self::Context) -> UVec2;
fn suggested_jitter(
context: &Self::Context,
frame_number: u32,
render_resolution: UVec2,
) -> Vec2;
fn suggested_mip_bias(context: &Self::Context, render_resolution: UVec2) -> f32;
fn new_context(
upscaled_resolution: UVec2,
perf_quality_mode: DlssPerfQualityMode,
feature_flags: dlss_wgpu::DlssFeatureFlags,
sdk: Arc<Mutex<dlss_wgpu::DlssSdk>>,
device: &RenderDevice,
queue: &RenderQueue,
) -> Result<Self::Context, dlss_wgpu::DlssError>;
}
/// DLSS Super Resolution.
///
/// Only available when the [`DlssSuperResolutionSupported`] resource exists.
#[derive(Reflect, Clone, Default)]
pub struct DlssSuperResolutionFeature;
impl DlssFeature for DlssSuperResolutionFeature {
type Context = DlssSuperResolution;
fn upscaled_resolution(context: &Self::Context) -> UVec2 {
context.upscaled_resolution()
}
fn render_resolution(context: &Self::Context) -> UVec2 {
context.render_resolution()
}
fn suggested_jitter(
context: &Self::Context,
frame_number: u32,
render_resolution: UVec2,
) -> Vec2 {
context.suggested_jitter(frame_number, render_resolution)
}
fn suggested_mip_bias(context: &Self::Context, render_resolution: UVec2) -> f32 {
context.suggested_mip_bias(render_resolution)
}
fn new_context(
upscaled_resolution: UVec2,
perf_quality_mode: DlssPerfQualityMode,
feature_flags: dlss_wgpu::DlssFeatureFlags,
sdk: Arc<Mutex<dlss_wgpu::DlssSdk>>,
device: &RenderDevice,
queue: &RenderQueue,
) -> Result<Self::Context, dlss_wgpu::DlssError> {
DlssSuperResolution::new(
upscaled_resolution,
perf_quality_mode,
feature_flags,
sdk,
device.wgpu_device(),
queue.deref(),
)
}
}
/// DLSS Ray Reconstruction.
///
/// Only available when the [`DlssRayReconstructionSupported`] resource exists.
#[derive(Reflect, Clone, Default)]
pub struct DlssRayReconstructionFeature;
impl DlssFeature for DlssRayReconstructionFeature {
type Context = DlssRayReconstruction;
fn upscaled_resolution(context: &Self::Context) -> UVec2 {
context.upscaled_resolution()
}
fn render_resolution(context: &Self::Context) -> UVec2 {
context.render_resolution()
}
fn suggested_jitter(
context: &Self::Context,
frame_number: u32,
render_resolution: UVec2,
) -> Vec2 {
context.suggested_jitter(frame_number, render_resolution)
}
fn suggested_mip_bias(context: &Self::Context, render_resolution: UVec2) -> f32 {
context.suggested_mip_bias(render_resolution)
}
fn new_context(
upscaled_resolution: UVec2,
perf_quality_mode: DlssPerfQualityMode,
feature_flags: dlss_wgpu::DlssFeatureFlags,
sdk: Arc<Mutex<dlss_wgpu::DlssSdk>>,
device: &RenderDevice,
queue: &RenderQueue,
) -> Result<Self::Context, dlss_wgpu::DlssError> {
DlssRayReconstruction::new(
upscaled_resolution,
perf_quality_mode,
feature_flags,
DlssRayReconstructionRoughnessMode::Packed,
DlssRayReconstructionDepthMode::Hardware,
sdk,
device.wgpu_device(),
queue.deref(),
)
}
}
/// Additional textures needed as inputs for [`DlssRayReconstructionFeature`].
#[derive(Component)]
pub struct ViewDlssRayReconstructionTextures {
pub diffuse_albedo: CachedTexture,
pub specular_albedo: CachedTexture,
pub normal_roughness: CachedTexture,
pub specular_motion_vectors: CachedTexture,
}
#[reflect_remote(DlssPerfQualityMode)]
#[derive(Default)]
enum DlssPerfQualityModeRemoteReflect {
#[default]
Auto,
Dlaa,
Quality,
Balanced,
Performance,
UltraPerformance,
}
#[derive(Resource)]
struct DlssSdk(Arc<Mutex<dlss_wgpu::DlssSdk>>);
/// Application-specific ID for DLSS.
///
/// See the DLSS programming guide for more info.
#[derive(Resource, Clone)]
pub struct DlssProjectId(pub Uuid);
/// When DLSS Super Resolution is supported by the current system, this resource will exist in the main world.
/// Otherwise this resource will be absent.
#[derive(Resource, Clone, Copy)]
pub struct DlssSuperResolutionSupported;
/// When DLSS Ray Reconstruction is supported by the current system, this resource will exist in the main world.
/// Otherwise this resource will be absent.
#[derive(Resource, Clone, Copy)]
pub struct DlssRayReconstructionSupported;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_anti_alias/src/dlss/extract.rs | crates/bevy_anti_alias/src/dlss/extract.rs | use super::{prepare::DlssRenderContext, Dlss, DlssFeature};
use bevy_camera::{Camera, MainPassResolutionOverride, Projection};
use bevy_ecs::{
query::{Has, With},
system::{Commands, Query, ResMut},
};
use bevy_render::{sync_world::RenderEntity, view::Hdr, MainWorld};
pub fn extract_dlss<F: DlssFeature>(
mut commands: Commands,
mut main_world: ResMut<MainWorld>,
cleanup_query: Query<Has<Dlss<F>>>,
) {
let mut cameras_3d = main_world
.query_filtered::<(RenderEntity, &Camera, &Projection, Option<&mut Dlss<F>>), With<Hdr>>();
for (entity, camera, camera_projection, mut dlss) in cameras_3d.iter_mut(&mut main_world) {
let mut entity_commands = commands
.get_entity(entity)
.expect("Camera entity wasn't synced.");
if dlss.is_some() && camera.is_active && camera_projection.is_perspective() {
entity_commands.insert(dlss.as_deref().unwrap().clone());
dlss.as_mut().unwrap().reset = false;
} else if cleanup_query.get(entity) == Ok(true) {
entity_commands.remove::<(Dlss<F>, DlssRenderContext<F>, MainPassResolutionOverride)>();
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_anti_alias/src/dlss/prepare.rs | crates/bevy_anti_alias/src/dlss/prepare.rs | use super::{Dlss, DlssFeature, DlssSdk};
use bevy_camera::{Camera3d, CameraMainTextureUsages, MainPassResolutionOverride};
use bevy_core_pipeline::prepass::{DepthPrepass, MotionVectorPrepass};
use bevy_diagnostic::FrameCount;
use bevy_ecs::{
component::Component,
entity::Entity,
query::With,
system::{Commands, Query, Res},
};
use bevy_math::Vec4Swizzles;
use bevy_render::{
camera::{MipBias, TemporalJitter},
render_resource::TextureUsages,
renderer::{RenderDevice, RenderQueue},
view::ExtractedView,
};
use dlss_wgpu::{DlssFeatureFlags, DlssPerfQualityMode};
use std::sync::{Arc, Mutex};
#[derive(Component)]
pub struct DlssRenderContext<F: DlssFeature> {
pub context: Mutex<F::Context>,
pub perf_quality_mode: DlssPerfQualityMode,
pub feature_flags: DlssFeatureFlags,
}
pub fn prepare_dlss<F: DlssFeature>(
mut query: Query<
(
Entity,
&ExtractedView,
&Dlss<F>,
&mut Camera3d,
&mut CameraMainTextureUsages,
&mut TemporalJitter,
&mut MipBias,
Option<&mut DlssRenderContext<F>>,
),
(
With<Camera3d>,
With<TemporalJitter>,
With<DepthPrepass>,
With<MotionVectorPrepass>,
),
>,
dlss_sdk: Res<DlssSdk>,
render_device: Res<RenderDevice>,
render_queue: Res<RenderQueue>,
frame_count: Res<FrameCount>,
mut commands: Commands,
) {
for (
entity,
view,
dlss,
mut camera_3d,
mut camera_main_texture_usages,
mut temporal_jitter,
mut mip_bias,
mut dlss_context,
) in &mut query
{
camera_main_texture_usages.0 |= TextureUsages::STORAGE_BINDING;
let mut depth_texture_usages = TextureUsages::from(camera_3d.depth_texture_usages);
depth_texture_usages |= TextureUsages::TEXTURE_BINDING;
camera_3d.depth_texture_usages = depth_texture_usages.into();
let upscaled_resolution = view.viewport.zw();
let dlss_feature_flags = DlssFeatureFlags::LowResolutionMotionVectors
| DlssFeatureFlags::InvertedDepth
| DlssFeatureFlags::HighDynamicRange
| DlssFeatureFlags::AutoExposure; // TODO
match dlss_context.as_deref_mut() {
Some(dlss_context)
if upscaled_resolution
== F::upscaled_resolution(&dlss_context.context.lock().unwrap())
&& dlss.perf_quality_mode == dlss_context.perf_quality_mode
&& dlss_feature_flags == dlss_context.feature_flags =>
{
let dlss_context = dlss_context.context.lock().unwrap();
let render_resolution = F::render_resolution(&dlss_context);
temporal_jitter.offset =
F::suggested_jitter(&dlss_context, frame_count.0, render_resolution);
}
_ => {
let dlss_context = F::new_context(
upscaled_resolution,
dlss.perf_quality_mode,
dlss_feature_flags,
Arc::clone(&dlss_sdk.0),
&render_device,
&render_queue,
)
.expect("Failed to create DlssRenderContext");
let render_resolution = F::render_resolution(&dlss_context);
temporal_jitter.offset =
F::suggested_jitter(&dlss_context, frame_count.0, render_resolution);
mip_bias.0 = F::suggested_mip_bias(&dlss_context, render_resolution);
commands.entity(entity).insert((
DlssRenderContext::<F> {
context: Mutex::new(dlss_context),
perf_quality_mode: dlss.perf_quality_mode,
feature_flags: dlss_feature_flags,
},
MainPassResolutionOverride(render_resolution),
));
}
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_anti_alias/src/smaa/mod.rs | crates/bevy_anti_alias/src/smaa/mod.rs | //! Subpixel morphological antialiasing (SMAA).
//!
//! [SMAA] is a 2011 antialiasing technique that takes an aliased image and
//! smooths out the *jaggies*, making edges smoother. It's been used in numerous
//! games and has become a staple postprocessing technique. Compared to MSAA,
//! SMAA has the advantage of compatibility with deferred rendering and
//! reduction of GPU memory bandwidth. Compared to FXAA, SMAA has the advantage
//! of improved quality, but the disadvantage of reduced performance. Compared
//! to TAA, SMAA has the advantage of stability and lack of *ghosting*
//! artifacts, but has the disadvantage of not supporting temporal accumulation,
//! which have made SMAA less popular when advanced photorealistic rendering
//! features are used in recent years.
//!
//! To use SMAA, add [`Smaa`] to a [`bevy_camera::Camera`]. In a
//! pinch, you can simply use the default settings (via the [`Default`] trait)
//! for a high-quality, high-performance appearance. When using SMAA, you will
//! likely want set [`bevy_render::view::Msaa`] to [`bevy_render::view::Msaa::Off`]
//! for every camera using SMAA.
//!
//! Those who have used SMAA in other engines should be aware that Bevy doesn't
//! yet support the following more advanced features of SMAA:
//!
//! * The temporal variant.
//!
//! * Depth- and chroma-based edge detection.
//!
//! * Predicated thresholding.
//!
//! * Compatibility with SSAA and MSAA.
//!
//! [SMAA]: https://www.iryoku.com/smaa/
use bevy_app::{App, Plugin};
use bevy_asset::{embedded_asset, load_embedded_asset, AssetServer, Handle};
#[cfg(not(feature = "smaa_luts"))]
use bevy_core_pipeline::tonemapping::lut_placeholder;
use bevy_core_pipeline::{
core_2d::graph::{Core2d, Node2d},
core_3d::graph::{Core3d, Node3d},
};
use bevy_derive::{Deref, DerefMut};
use bevy_ecs::{
component::Component,
entity::Entity,
query::{QueryItem, With},
reflect::ReflectComponent,
resource::Resource,
schedule::IntoScheduleConfigs as _,
system::{lifetimeless::Read, Commands, Query, Res, ResMut},
world::World,
};
use bevy_image::{BevyDefault, Image, ToExtents};
use bevy_math::{vec4, Vec4};
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
use bevy_render::{
camera::ExtractedCamera,
diagnostic::RecordDiagnostics,
extract_component::{ExtractComponent, ExtractComponentPlugin},
render_asset::RenderAssets,
render_graph::{
NodeRunError, RenderGraphContext, RenderGraphExt as _, ViewNode, ViewNodeRunner,
},
render_resource::{
binding_types::{sampler, texture_2d, uniform_buffer},
AddressMode, BindGroup, BindGroupEntries, BindGroupLayoutDescriptor,
BindGroupLayoutEntries, CachedRenderPipelineId, ColorTargetState, ColorWrites,
CompareFunction, DepthStencilState, DynamicUniformBuffer, FilterMode, FragmentState,
LoadOp, Operations, PipelineCache, RenderPassColorAttachment,
RenderPassDepthStencilAttachment, RenderPassDescriptor, RenderPipeline,
RenderPipelineDescriptor, SamplerBindingType, SamplerDescriptor, ShaderStages, ShaderType,
SpecializedRenderPipeline, SpecializedRenderPipelines, StencilFaceState, StencilOperation,
StencilState, StoreOp, TextureDescriptor, TextureDimension, TextureFormat,
TextureSampleType, TextureUsages, TextureView, VertexState,
},
renderer::{RenderContext, RenderDevice, RenderQueue},
texture::{CachedTexture, GpuImage, TextureCache},
view::{ExtractedView, ViewTarget},
Render, RenderApp, RenderStartup, RenderSystems,
};
use bevy_shader::{Shader, ShaderDefVal};
use bevy_utils::prelude::default;
/// Adds support for subpixel morphological antialiasing, or SMAA.
#[derive(Default)]
pub struct SmaaPlugin;
/// A component for enabling Subpixel Morphological Anti-Aliasing (SMAA)
/// for a [`bevy_camera::Camera`].
#[derive(Clone, Copy, Default, Component, Reflect, ExtractComponent)]
#[reflect(Component, Default, Clone)]
#[doc(alias = "SubpixelMorphologicalAntiAliasing")]
pub struct Smaa {
/// A predefined set of SMAA parameters: i.e. a quality level.
///
/// Generally, you can leave this at its default level.
pub preset: SmaaPreset,
}
/// A preset quality level for SMAA.
///
/// Higher values are slower but result in a higher-quality image.
///
/// The default value is *high*.
#[derive(Clone, Copy, Reflect, Default, PartialEq, Eq, Hash)]
#[reflect(Default, Clone, PartialEq, Hash)]
pub enum SmaaPreset {
/// Four search steps; no diagonal or corner detection.
Low,
/// Eight search steps; no diagonal or corner detection.
Medium,
/// Sixteen search steps, 8 diagonal search steps, and corner detection.
///
/// This is the default.
#[default]
High,
/// Thirty-two search steps, 8 diagonal search steps, and corner detection.
Ultra,
}
#[derive(Resource)]
struct SmaaLuts {
/// The handle of the area LUT, a KTX2 format texture that SMAA uses internally.
area_lut: Handle<Image>,
/// The handle of the search LUT, a KTX2 format texture that SMAA uses internally.
search_lut: Handle<Image>,
}
/// A render world resource that holds all render pipeline data needed for SMAA.
///
/// There are three separate passes, so we need three separate pipelines.
#[derive(Resource)]
pub struct SmaaPipelines {
/// Pass 1: Edge detection.
edge_detection: SmaaEdgeDetectionPipeline,
/// Pass 2: Blending weight calculation.
blending_weight_calculation: SmaaBlendingWeightCalculationPipeline,
/// Pass 3: Neighborhood blending.
neighborhood_blending: SmaaNeighborhoodBlendingPipeline,
}
/// The pipeline data for phase 1 of SMAA: edge detection.
struct SmaaEdgeDetectionPipeline {
/// The bind group layout common to all passes.
postprocess_bind_group_layout: BindGroupLayoutDescriptor,
/// The bind group layout for data specific to this pass.
edge_detection_bind_group_layout: BindGroupLayoutDescriptor,
/// The shader asset handle.
shader: Handle<Shader>,
}
/// The pipeline data for phase 2 of SMAA: blending weight calculation.
struct SmaaBlendingWeightCalculationPipeline {
/// The bind group layout common to all passes.
postprocess_bind_group_layout: BindGroupLayoutDescriptor,
/// The bind group layout for data specific to this pass.
blending_weight_calculation_bind_group_layout: BindGroupLayoutDescriptor,
/// The shader asset handle.
shader: Handle<Shader>,
}
/// The pipeline data for phase 3 of SMAA: neighborhood blending.
struct SmaaNeighborhoodBlendingPipeline {
/// The bind group layout common to all passes.
postprocess_bind_group_layout: BindGroupLayoutDescriptor,
/// The bind group layout for data specific to this pass.
neighborhood_blending_bind_group_layout: BindGroupLayoutDescriptor,
/// The shader asset handle.
shader: Handle<Shader>,
}
/// A unique identifier for a set of SMAA pipelines.
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct SmaaNeighborhoodBlendingPipelineKey {
/// The format of the framebuffer.
texture_format: TextureFormat,
/// The quality preset.
preset: SmaaPreset,
}
/// A render world component that holds the pipeline IDs for the SMAA passes.
///
/// There are three separate SMAA passes, each with a different shader and bind
/// group layout, so we need three pipeline IDs.
#[derive(Component)]
pub struct ViewSmaaPipelines {
/// The pipeline ID for edge detection (phase 1).
edge_detection_pipeline_id: CachedRenderPipelineId,
/// The pipeline ID for blending weight calculation (phase 2).
blending_weight_calculation_pipeline_id: CachedRenderPipelineId,
/// The pipeline ID for neighborhood blending (phase 3).
neighborhood_blending_pipeline_id: CachedRenderPipelineId,
}
/// The render graph node that performs subpixel morphological antialiasing
/// (SMAA).
#[derive(Default)]
pub struct SmaaNode;
/// Values supplied to the GPU for SMAA.
///
/// Currently, this just contains the render target metrics and values derived
/// from them. These could be computed by the shader itself, but the original
/// SMAA HLSL code supplied them in a uniform, so we do the same for
/// consistency.
#[derive(Clone, Copy, ShaderType)]
pub struct SmaaInfoUniform {
/// Information about the width and height of the framebuffer.
///
/// * *x*: The reciprocal pixel width of the framebuffer.
///
/// * *y*: The reciprocal pixel height of the framebuffer.
///
/// * *z*: The pixel width of the framebuffer.
///
/// * *w*: The pixel height of the framebuffer.
pub rt_metrics: Vec4,
}
/// A render world component that stores the offset of each [`SmaaInfoUniform`]
/// within the [`SmaaInfoUniformBuffer`] for each view.
#[derive(Clone, Copy, Deref, DerefMut, Component)]
pub struct SmaaInfoUniformOffset(pub u32);
/// The GPU buffer that holds all [`SmaaInfoUniform`]s for all views.
///
/// This is a resource stored in the render world.
#[derive(Resource, Default, Deref, DerefMut)]
pub struct SmaaInfoUniformBuffer(pub DynamicUniformBuffer<SmaaInfoUniform>);
/// A render world component that holds the intermediate textures necessary to
/// perform SMAA.
///
/// This is stored on each view that has enabled SMAA.
#[derive(Component)]
pub struct SmaaTextures {
/// The two-channel texture that stores the output from the first pass (edge
/// detection).
///
/// The second pass (blending weight calculation) reads this texture to do
/// its work.
pub edge_detection_color_texture: CachedTexture,
/// The 8-bit stencil texture that records which pixels the first pass
/// touched, so that the second pass doesn't have to examine other pixels.
///
/// Each texel will contain a 0 if the first pass didn't touch the
/// corresponding pixel or a 1 if the first pass did touch that pixel.
pub edge_detection_stencil_texture: CachedTexture,
/// A four-channel RGBA texture that stores the output from the second pass
/// (blending weight calculation).
///
/// The final pass (neighborhood blending) reads this texture to do its
/// work.
pub blend_texture: CachedTexture,
}
/// A render world component that stores the bind groups necessary to perform
/// SMAA.
///
/// This is stored on each view.
#[derive(Component)]
pub struct SmaaBindGroups {
/// The bind group for the first pass (edge detection).
pub edge_detection_bind_group: BindGroup,
/// The bind group for the second pass (blending weight calculation).
pub blending_weight_calculation_bind_group: BindGroup,
/// The bind group for the final pass (neighborhood blending).
pub neighborhood_blending_bind_group: BindGroup,
}
/// Stores the specialized render pipelines for SMAA.
///
/// Because SMAA uses three passes, we need three separate render pipeline
/// stores.
#[derive(Resource, Default)]
pub struct SmaaSpecializedRenderPipelines {
/// Specialized render pipelines for the first phase (edge detection).
edge_detection: SpecializedRenderPipelines<SmaaEdgeDetectionPipeline>,
/// Specialized render pipelines for the second phase (blending weight
/// calculation).
blending_weight_calculation: SpecializedRenderPipelines<SmaaBlendingWeightCalculationPipeline>,
/// Specialized render pipelines for the third phase (neighborhood
/// blending).
neighborhood_blending: SpecializedRenderPipelines<SmaaNeighborhoodBlendingPipeline>,
}
impl Plugin for SmaaPlugin {
fn build(&self, app: &mut App) {
// Load the shader.
embedded_asset!(app, "smaa.wgsl");
#[cfg(feature = "smaa_luts")]
let smaa_luts = {
use bevy_asset::RenderAssetUsages;
use bevy_image::ImageLoaderSettings;
// Load the two lookup textures. These are compressed textures in KTX2 format.
embedded_asset!(app, "SMAAAreaLUT.ktx2");
embedded_asset!(app, "SMAASearchLUT.ktx2");
SmaaLuts {
area_lut: load_embedded_asset!(
app,
"SMAAAreaLUT.ktx2",
|settings: &mut ImageLoaderSettings| {
settings.is_srgb = false;
settings.asset_usage = RenderAssetUsages::RENDER_WORLD;
}
),
search_lut: load_embedded_asset!(
app,
"SMAASearchLUT.ktx2",
|settings: &mut ImageLoaderSettings| {
settings.is_srgb = false;
settings.asset_usage = RenderAssetUsages::RENDER_WORLD;
}
),
}
};
#[cfg(not(feature = "smaa_luts"))]
let smaa_luts = {
let mut images = app.world_mut().resource_mut::<bevy_asset::Assets<Image>>();
let handle = images.add(lut_placeholder());
SmaaLuts {
area_lut: handle.clone(),
search_lut: handle.clone(),
}
};
app.add_plugins(ExtractComponentPlugin::<Smaa>::default());
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
return;
};
render_app
.insert_resource(smaa_luts)
.init_resource::<SmaaSpecializedRenderPipelines>()
.init_resource::<SmaaInfoUniformBuffer>()
.add_systems(RenderStartup, init_smaa_pipelines)
.add_systems(
Render,
(
prepare_smaa_pipelines.in_set(RenderSystems::Prepare),
prepare_smaa_uniforms.in_set(RenderSystems::PrepareResources),
prepare_smaa_textures.in_set(RenderSystems::PrepareResources),
prepare_smaa_bind_groups.in_set(RenderSystems::PrepareBindGroups),
),
)
.add_render_graph_node::<ViewNodeRunner<SmaaNode>>(Core3d, Node3d::Smaa)
.add_render_graph_edges(
Core3d,
(
Node3d::Tonemapping,
Node3d::Smaa,
Node3d::EndMainPassPostProcessing,
),
)
.add_render_graph_node::<ViewNodeRunner<SmaaNode>>(Core2d, Node2d::Smaa)
.add_render_graph_edges(
Core2d,
(
Node2d::Tonemapping,
Node2d::Smaa,
Node2d::EndMainPassPostProcessing,
),
);
}
}
pub fn init_smaa_pipelines(mut commands: Commands, asset_server: Res<AssetServer>) {
// Create the postprocess bind group layout (all passes, bind group 0).
let postprocess_bind_group_layout = BindGroupLayoutDescriptor::new(
"SMAA postprocess bind group layout",
&BindGroupLayoutEntries::sequential(
ShaderStages::FRAGMENT,
(
texture_2d(TextureSampleType::Float { filterable: true }),
uniform_buffer::<SmaaInfoUniform>(true).visibility(ShaderStages::VERTEX_FRAGMENT),
),
),
);
// Create the edge detection bind group layout (pass 1, bind group 1).
let edge_detection_bind_group_layout = BindGroupLayoutDescriptor::new(
"SMAA edge detection bind group layout",
&BindGroupLayoutEntries::sequential(
ShaderStages::FRAGMENT,
(sampler(SamplerBindingType::Filtering),),
),
);
// Create the blending weight calculation bind group layout (pass 2, bind group 1).
let blending_weight_calculation_bind_group_layout = BindGroupLayoutDescriptor::new(
"SMAA blending weight calculation bind group layout",
&BindGroupLayoutEntries::sequential(
ShaderStages::FRAGMENT,
(
texture_2d(TextureSampleType::Float { filterable: true }), // edges texture
sampler(SamplerBindingType::Filtering), // edges sampler
texture_2d(TextureSampleType::Float { filterable: true }), // search texture
texture_2d(TextureSampleType::Float { filterable: true }), // area texture
),
),
);
// Create the neighborhood blending bind group layout (pass 3, bind group 1).
let neighborhood_blending_bind_group_layout = BindGroupLayoutDescriptor::new(
"SMAA neighborhood blending bind group layout",
&BindGroupLayoutEntries::sequential(
ShaderStages::FRAGMENT,
(
texture_2d(TextureSampleType::Float { filterable: true }),
sampler(SamplerBindingType::Filtering),
),
),
);
let shader = load_embedded_asset!(asset_server.as_ref(), "smaa.wgsl");
commands.insert_resource(SmaaPipelines {
edge_detection: SmaaEdgeDetectionPipeline {
postprocess_bind_group_layout: postprocess_bind_group_layout.clone(),
edge_detection_bind_group_layout,
shader: shader.clone(),
},
blending_weight_calculation: SmaaBlendingWeightCalculationPipeline {
postprocess_bind_group_layout: postprocess_bind_group_layout.clone(),
blending_weight_calculation_bind_group_layout,
shader: shader.clone(),
},
neighborhood_blending: SmaaNeighborhoodBlendingPipeline {
postprocess_bind_group_layout,
neighborhood_blending_bind_group_layout,
shader,
},
});
}
// Phase 1: edge detection.
impl SpecializedRenderPipeline for SmaaEdgeDetectionPipeline {
type Key = SmaaPreset;
fn specialize(&self, preset: Self::Key) -> RenderPipelineDescriptor {
let shader_defs = vec!["SMAA_EDGE_DETECTION".into(), preset.shader_def()];
// We mark the pixels that we touched with a 1 so that the blending
// weight calculation (phase 2) will only consider those. This reduces
// the overhead of phase 2 considerably.
let stencil_face_state = StencilFaceState {
compare: CompareFunction::Always,
fail_op: StencilOperation::Replace,
depth_fail_op: StencilOperation::Replace,
pass_op: StencilOperation::Replace,
};
RenderPipelineDescriptor {
label: Some("SMAA edge detection".into()),
layout: vec![
self.postprocess_bind_group_layout.clone(),
self.edge_detection_bind_group_layout.clone(),
],
vertex: VertexState {
shader: self.shader.clone(),
shader_defs: shader_defs.clone(),
entry_point: Some("edge_detection_vertex_main".into()),
buffers: vec![],
},
fragment: Some(FragmentState {
shader: self.shader.clone(),
shader_defs,
entry_point: Some("luma_edge_detection_fragment_main".into()),
targets: vec![Some(ColorTargetState {
format: TextureFormat::Rg8Unorm,
blend: None,
write_mask: ColorWrites::ALL,
})],
}),
depth_stencil: Some(DepthStencilState {
format: TextureFormat::Stencil8,
depth_write_enabled: false,
depth_compare: CompareFunction::Always,
stencil: StencilState {
front: stencil_face_state,
back: stencil_face_state,
read_mask: 1,
write_mask: 1,
},
bias: default(),
}),
..default()
}
}
}
// Phase 2: blending weight calculation.
impl SpecializedRenderPipeline for SmaaBlendingWeightCalculationPipeline {
type Key = SmaaPreset;
fn specialize(&self, preset: Self::Key) -> RenderPipelineDescriptor {
let shader_defs = vec![
"SMAA_BLENDING_WEIGHT_CALCULATION".into(),
preset.shader_def(),
];
// Only consider the pixels that were touched in phase 1.
let stencil_face_state = StencilFaceState {
compare: CompareFunction::Equal,
fail_op: StencilOperation::Keep,
depth_fail_op: StencilOperation::Keep,
pass_op: StencilOperation::Keep,
};
RenderPipelineDescriptor {
label: Some("SMAA blending weight calculation".into()),
layout: vec![
self.postprocess_bind_group_layout.clone(),
self.blending_weight_calculation_bind_group_layout.clone(),
],
vertex: VertexState {
shader: self.shader.clone(),
shader_defs: shader_defs.clone(),
entry_point: Some("blending_weight_calculation_vertex_main".into()),
buffers: vec![],
},
fragment: Some(FragmentState {
shader: self.shader.clone(),
shader_defs,
entry_point: Some("blending_weight_calculation_fragment_main".into()),
targets: vec![Some(ColorTargetState {
format: TextureFormat::Rgba8Unorm,
blend: None,
write_mask: ColorWrites::ALL,
})],
}),
depth_stencil: Some(DepthStencilState {
format: TextureFormat::Stencil8,
depth_write_enabled: false,
depth_compare: CompareFunction::Always,
stencil: StencilState {
front: stencil_face_state,
back: stencil_face_state,
read_mask: 1,
write_mask: 1,
},
bias: default(),
}),
..default()
}
}
}
impl SpecializedRenderPipeline for SmaaNeighborhoodBlendingPipeline {
type Key = SmaaNeighborhoodBlendingPipelineKey;
fn specialize(&self, key: Self::Key) -> RenderPipelineDescriptor {
let shader_defs = vec!["SMAA_NEIGHBORHOOD_BLENDING".into(), key.preset.shader_def()];
RenderPipelineDescriptor {
label: Some("SMAA neighborhood blending".into()),
layout: vec![
self.postprocess_bind_group_layout.clone(),
self.neighborhood_blending_bind_group_layout.clone(),
],
vertex: VertexState {
shader: self.shader.clone(),
shader_defs: shader_defs.clone(),
entry_point: Some("neighborhood_blending_vertex_main".into()),
buffers: vec![],
},
fragment: Some(FragmentState {
shader: self.shader.clone(),
shader_defs,
entry_point: Some("neighborhood_blending_fragment_main".into()),
targets: vec![Some(ColorTargetState {
format: key.texture_format,
blend: None,
write_mask: ColorWrites::ALL,
})],
}),
..default()
}
}
}
/// A system, part of the render app, that specializes the three pipelines
/// needed for SMAA according to each view's SMAA settings.
fn prepare_smaa_pipelines(
mut commands: Commands,
pipeline_cache: Res<PipelineCache>,
mut specialized_render_pipelines: ResMut<SmaaSpecializedRenderPipelines>,
smaa_pipelines: Res<SmaaPipelines>,
view_targets: Query<(Entity, &ExtractedView, &Smaa)>,
) {
for (entity, view, smaa) in &view_targets {
let edge_detection_pipeline_id = specialized_render_pipelines.edge_detection.specialize(
&pipeline_cache,
&smaa_pipelines.edge_detection,
smaa.preset,
);
let blending_weight_calculation_pipeline_id = specialized_render_pipelines
.blending_weight_calculation
.specialize(
&pipeline_cache,
&smaa_pipelines.blending_weight_calculation,
smaa.preset,
);
let neighborhood_blending_pipeline_id = specialized_render_pipelines
.neighborhood_blending
.specialize(
&pipeline_cache,
&smaa_pipelines.neighborhood_blending,
SmaaNeighborhoodBlendingPipelineKey {
texture_format: if view.hdr {
ViewTarget::TEXTURE_FORMAT_HDR
} else {
TextureFormat::bevy_default()
},
preset: smaa.preset,
},
);
commands.entity(entity).insert(ViewSmaaPipelines {
edge_detection_pipeline_id,
blending_weight_calculation_pipeline_id,
neighborhood_blending_pipeline_id,
});
}
}
/// A system, part of the render app, that builds the [`SmaaInfoUniform`] data
/// for each view with SMAA enabled and writes the resulting data to GPU memory.
fn prepare_smaa_uniforms(
mut commands: Commands,
render_device: Res<RenderDevice>,
render_queue: Res<RenderQueue>,
view_targets: Query<(Entity, &ExtractedView), With<Smaa>>,
mut smaa_info_buffer: ResMut<SmaaInfoUniformBuffer>,
) {
smaa_info_buffer.clear();
for (entity, view) in &view_targets {
let offset = smaa_info_buffer.push(&SmaaInfoUniform {
rt_metrics: vec4(
1.0 / view.viewport.z as f32,
1.0 / view.viewport.w as f32,
view.viewport.z as f32,
view.viewport.w as f32,
),
});
commands
.entity(entity)
.insert(SmaaInfoUniformOffset(offset));
}
smaa_info_buffer.write_buffer(&render_device, &render_queue);
}
/// A system, part of the render app, that builds the intermediate textures for
/// each view with SMAA enabled.
///
/// Phase 1 (edge detection) needs a two-channel RG texture and an 8-bit stencil
/// texture; phase 2 (blend weight calculation) needs a four-channel RGBA
/// texture.
fn prepare_smaa_textures(
mut commands: Commands,
render_device: Res<RenderDevice>,
mut texture_cache: ResMut<TextureCache>,
view_targets: Query<(Entity, &ExtractedCamera), (With<ExtractedView>, With<Smaa>)>,
) {
for (entity, camera) in &view_targets {
let Some(texture_size) = camera.physical_target_size else {
continue;
};
// Create the two-channel RG texture for phase 1 (edge detection).
let edge_detection_color_texture = texture_cache.get(
&render_device,
TextureDescriptor {
label: Some("SMAA edge detection color texture"),
size: texture_size.to_extents(),
mip_level_count: 1,
sample_count: 1,
dimension: TextureDimension::D2,
format: TextureFormat::Rg8Unorm,
usage: TextureUsages::TEXTURE_BINDING | TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
},
);
// Create the stencil texture for phase 1 (edge detection).
let edge_detection_stencil_texture = texture_cache.get(
&render_device,
TextureDescriptor {
label: Some("SMAA edge detection stencil texture"),
size: texture_size.to_extents(),
mip_level_count: 1,
sample_count: 1,
dimension: TextureDimension::D2,
format: TextureFormat::Stencil8,
usage: TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
},
);
// Create the four-channel RGBA texture for phase 2 (blending weight
// calculation).
let blend_texture = texture_cache.get(
&render_device,
TextureDescriptor {
label: Some("SMAA blend texture"),
size: texture_size.to_extents(),
mip_level_count: 1,
sample_count: 1,
dimension: TextureDimension::D2,
format: TextureFormat::Rgba8Unorm,
usage: TextureUsages::TEXTURE_BINDING | TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
},
);
commands.entity(entity).insert(SmaaTextures {
edge_detection_color_texture,
edge_detection_stencil_texture,
blend_texture,
});
}
}
/// A system, part of the render app, that builds the SMAA bind groups for each
/// view with SMAA enabled.
fn prepare_smaa_bind_groups(
mut commands: Commands,
render_device: Res<RenderDevice>,
smaa_pipelines: Res<SmaaPipelines>,
smaa_luts: Res<SmaaLuts>,
images: Res<RenderAssets<GpuImage>>,
pipeline_cache: Res<PipelineCache>,
view_targets: Query<(Entity, &SmaaTextures), (With<ExtractedView>, With<Smaa>)>,
) {
// Fetch the two lookup textures. These are bundled in this library.
let (Some(search_texture), Some(area_texture)) = (
images.get(&smaa_luts.search_lut),
images.get(&smaa_luts.area_lut),
) else {
return;
};
for (entity, smaa_textures) in &view_targets {
// We use the same sampler settings for all textures, so we can build
// only one and reuse it.
let sampler = render_device.create_sampler(&SamplerDescriptor {
label: Some("SMAA sampler"),
address_mode_u: AddressMode::ClampToEdge,
address_mode_v: AddressMode::ClampToEdge,
address_mode_w: AddressMode::ClampToEdge,
mag_filter: FilterMode::Linear,
min_filter: FilterMode::Linear,
..default()
});
commands.entity(entity).insert(SmaaBindGroups {
edge_detection_bind_group: render_device.create_bind_group(
Some("SMAA edge detection bind group"),
&pipeline_cache.get_bind_group_layout(
&smaa_pipelines
.edge_detection
.edge_detection_bind_group_layout,
),
&BindGroupEntries::sequential((&sampler,)),
),
blending_weight_calculation_bind_group: render_device.create_bind_group(
Some("SMAA blending weight calculation bind group"),
&pipeline_cache.get_bind_group_layout(
&smaa_pipelines
.blending_weight_calculation
.blending_weight_calculation_bind_group_layout,
),
&BindGroupEntries::sequential((
&smaa_textures.edge_detection_color_texture.default_view,
&sampler,
&search_texture.texture_view,
&area_texture.texture_view,
)),
),
neighborhood_blending_bind_group: render_device.create_bind_group(
Some("SMAA neighborhood blending bind group"),
&pipeline_cache.get_bind_group_layout(
&smaa_pipelines
.neighborhood_blending
.neighborhood_blending_bind_group_layout,
),
&BindGroupEntries::sequential((
&smaa_textures.blend_texture.default_view,
&sampler,
)),
),
});
}
}
impl ViewNode for SmaaNode {
type ViewQuery = (
Read<ViewTarget>,
Read<ViewSmaaPipelines>,
Read<SmaaInfoUniformOffset>,
Read<SmaaTextures>,
Read<SmaaBindGroups>,
);
fn run<'w>(
&self,
_: &mut RenderGraphContext,
render_context: &mut RenderContext<'w>,
(
view_target,
view_pipelines,
view_smaa_uniform_offset,
smaa_textures,
view_smaa_bind_groups,
): QueryItem<'w, '_, Self::ViewQuery>,
world: &'w World,
) -> Result<(), NodeRunError> {
let pipeline_cache = world.resource::<PipelineCache>();
let smaa_pipelines = world.resource::<SmaaPipelines>();
let smaa_info_uniform_buffer = world.resource::<SmaaInfoUniformBuffer>();
// Fetch the render pipelines.
let (
Some(edge_detection_pipeline),
Some(blending_weight_calculation_pipeline),
Some(neighborhood_blending_pipeline),
) = (
pipeline_cache.get_render_pipeline(view_pipelines.edge_detection_pipeline_id),
pipeline_cache
.get_render_pipeline(view_pipelines.blending_weight_calculation_pipeline_id),
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | true |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_time/src/virt.rs | crates/bevy_time/src/virt.rs | #[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
use core::time::Duration;
use log::debug;
use crate::{real::Real, time::Time};
/// The virtual game clock representing game time.
///
/// A specialization of the [`Time`] structure. **For method documentation, see
/// [`Time<Virtual>#impl-Time<Virtual>`].**
///
/// Normally used as `Time<Virtual>`. It is automatically inserted as a resource
/// by [`TimePlugin`](crate::TimePlugin) and updated based on
/// [`Time<Real>`](Real). The virtual clock is automatically set as the default
/// generic [`Time`] resource for the update.
///
/// The virtual clock differs from real time clock in that it can be paused, sped up
/// and slowed down. It also limits how much it can advance in a single update
/// in order to prevent unexpected behavior in cases where updates do not happen
/// at regular intervals (e.g. coming back after the program was suspended a long time).
///
/// The virtual clock can be paused by calling [`pause()`](Time::pause),
/// unpaused by calling [`unpause()`](Time::unpause), or toggled by calling
/// [`toggle()`](Time::toggle). When the game clock is
/// paused [`delta()`](Time::delta) will be zero on each update, and
/// [`elapsed()`](Time::elapsed) will not grow.
/// [`effective_speed()`](Time::effective_speed) will return `0.0`. Calling
/// [`pause()`](Time::pause) will not affect value the [`delta()`](Time::delta)
/// value for the update currently being processed.
///
/// The speed of the virtual clock can be changed by calling
/// [`set_relative_speed()`](Time::set_relative_speed). A value of `2.0` means
/// that virtual clock should advance twice as fast as real time, meaning that
/// [`delta()`](Time::delta) values will be double of what
/// [`Time<Real>::delta()`](Time::delta) reports and
/// [`elapsed()`](Time::elapsed) will go twice as fast as
/// [`Time<Real>::elapsed()`](Time::elapsed). Calling
/// [`set_relative_speed()`](Time::set_relative_speed) will not affect the
/// [`delta()`](Time::delta) value for the update currently being processed.
///
/// The maximum amount of delta time that can be added by a single update can be
/// set by [`set_max_delta()`](Time::set_max_delta). This value serves a dual
/// purpose in the virtual clock.
///
/// If the game temporarily freezes due to any reason, such as disk access, a
/// blocking system call, or operating system level suspend, reporting the full
/// elapsed delta time is likely to cause bugs in game logic. Usually if a
/// laptop is suspended for an hour, it doesn't make sense to try to simulate
/// the game logic for the elapsed hour when resuming. Instead it is better to
/// lose the extra time and pretend a shorter duration of time passed. Setting
/// [`max_delta()`](Time::max_delta) to a relatively short time means that the
/// impact on game logic will be minimal.
///
/// If the game lags for some reason, meaning that it will take a longer time to
/// compute a frame than the real time that passes during the computation, then
/// we would fall behind in processing virtual time. If this situation persists,
/// and computing a frame takes longer depending on how much virtual time has
/// passed, the game would enter a "death spiral" where computing each frame
/// takes longer and longer and the game will appear to freeze. By limiting the
/// maximum time that can be added at once, we also limit the amount of virtual
/// time the game needs to compute for each frame. This means that the game will
/// run slow, and it will run slower than real time, but it will not freeze and
/// it will recover as soon as computation becomes fast again.
///
/// You should set [`max_delta()`](Time::max_delta) to a value that is
/// approximately the minimum FPS your game should have even if heavily lagged
/// for a moment. The actual FPS when lagged will be somewhat lower than this,
/// depending on how much more time it takes to compute a frame compared to real
/// time. You should also consider how stable your FPS is, as the limit will
/// also dictate how big of an FPS drop you can accept without losing time and
/// falling behind real time.
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Clone))]
pub struct Virtual {
max_delta: Duration,
paused: bool,
relative_speed: f64,
effective_speed: f64,
}
impl Time<Virtual> {
/// The default amount of time that can added in a single update.
///
/// Equal to 250 milliseconds.
const DEFAULT_MAX_DELTA: Duration = Duration::from_millis(250);
/// Create new virtual clock with given maximum delta step [`Duration`]
///
/// # Panics
///
/// Panics if `max_delta` is zero.
pub fn from_max_delta(max_delta: Duration) -> Self {
let mut ret = Self::default();
ret.set_max_delta(max_delta);
ret
}
/// Returns the maximum amount of time that can be added to this clock by a
/// single update, as [`Duration`].
///
/// This is the maximum value [`Self::delta()`] will return and also to
/// maximum time [`Self::elapsed()`] will be increased by in a single
/// update.
///
/// This ensures that even if no updates happen for an extended amount of time,
/// the clock will not have a sudden, huge advance all at once. This also indirectly
/// limits the maximum number of fixed update steps that can run in a single update.
///
/// The default value is 250 milliseconds.
#[inline]
pub fn max_delta(&self) -> Duration {
self.context().max_delta
}
/// Sets the maximum amount of time that can be added to this clock by a
/// single update, as [`Duration`].
///
/// This is the maximum value [`Self::delta()`] will return and also to
/// maximum time [`Self::elapsed()`] will be increased by in a single
/// update.
///
/// This is used to ensure that even if the game freezes for a few seconds,
/// or is suspended for hours or even days, the virtual clock doesn't
/// suddenly jump forward for that full amount, which would likely cause
/// gameplay bugs or having to suddenly simulate all the intervening time.
///
/// If no updates happen for an extended amount of time, this limit prevents
/// having a sudden, huge advance all at once. This also indirectly limits
/// the maximum number of fixed update steps that can run in a single
/// update.
///
/// The default value is 250 milliseconds. If you want to disable this
/// feature, set the value to [`Duration::MAX`].
///
/// # Panics
///
/// Panics if `max_delta` is zero.
#[inline]
pub fn set_max_delta(&mut self, max_delta: Duration) {
assert_ne!(max_delta, Duration::ZERO, "tried to set max delta to zero");
self.context_mut().max_delta = max_delta;
}
/// Returns the speed the clock advances relative to your system clock, as [`f32`].
/// This is known as "time scaling" or "time dilation" in other engines.
#[inline]
pub fn relative_speed(&self) -> f32 {
self.relative_speed_f64() as f32
}
/// Returns the speed the clock advances relative to your system clock, as [`f64`].
/// This is known as "time scaling" or "time dilation" in other engines.
#[inline]
pub fn relative_speed_f64(&self) -> f64 {
self.context().relative_speed
}
/// Returns the speed the clock advanced relative to your system clock in
/// this update, as [`f32`].
///
/// Returns `0.0` if the game was paused or what the `relative_speed` value
/// was at the start of this update.
#[inline]
pub fn effective_speed(&self) -> f32 {
self.context().effective_speed as f32
}
/// Returns the speed the clock advanced relative to your system clock in
/// this update, as [`f64`].
///
/// Returns `0.0` if the game was paused or what the `relative_speed` value
/// was at the start of this update.
#[inline]
pub fn effective_speed_f64(&self) -> f64 {
self.context().effective_speed
}
/// Sets the speed the clock advances relative to your system clock, given as an [`f32`].
///
/// For example, setting this to `2.0` will make the clock advance twice as fast as your system
/// clock.
///
/// # Panics
///
/// Panics if `ratio` is negative or not finite.
#[inline]
pub fn set_relative_speed(&mut self, ratio: f32) {
self.set_relative_speed_f64(ratio as f64);
}
/// Sets the speed the clock advances relative to your system clock, given as an [`f64`].
///
/// For example, setting this to `2.0` will make the clock advance twice as fast as your system
/// clock.
///
/// # Panics
///
/// Panics if `ratio` is negative or not finite.
#[inline]
pub fn set_relative_speed_f64(&mut self, ratio: f64) {
assert!(ratio.is_finite(), "tried to go infinitely fast");
assert!(ratio >= 0.0, "tried to go back in time");
self.context_mut().relative_speed = ratio;
}
/// Stops the clock if it is running, otherwise resumes the clock.
#[inline]
pub fn toggle(&mut self) {
self.context_mut().paused ^= true;
}
/// Stops the clock, preventing it from advancing until resumed.
#[inline]
pub fn pause(&mut self) {
self.context_mut().paused = true;
}
/// Resumes the clock.
#[inline]
pub fn unpause(&mut self) {
self.context_mut().paused = false;
}
/// Returns `true` if the clock is currently paused.
#[inline]
pub fn is_paused(&self) -> bool {
self.context().paused
}
/// Returns `true` if the clock was paused at the start of this update.
#[inline]
pub fn was_paused(&self) -> bool {
self.context().effective_speed == 0.0
}
/// Updates the elapsed duration of `self` by `raw_delta`, up to the `max_delta`.
fn advance_with_raw_delta(&mut self, raw_delta: Duration) {
let max_delta = self.context().max_delta;
let clamped_delta = if raw_delta > max_delta {
debug!(
"delta time larger than maximum delta, clamping delta to {:?} and skipping {:?}",
max_delta,
raw_delta - max_delta
);
max_delta
} else {
raw_delta
};
let effective_speed = if self.context().paused {
0.0
} else {
self.context().relative_speed
};
let delta = if effective_speed != 1.0 {
clamped_delta.mul_f64(effective_speed)
} else {
// avoid rounding when at normal speed
clamped_delta
};
self.context_mut().effective_speed = effective_speed;
self.advance_by(delta);
}
}
impl Default for Virtual {
fn default() -> Self {
Self {
max_delta: Time::<Virtual>::DEFAULT_MAX_DELTA,
paused: false,
relative_speed: 1.0,
effective_speed: 1.0,
}
}
}
/// Advances [`Time<Virtual>`] and [`Time`] based on the elapsed [`Time<Real>`].
///
/// The virtual time will be advanced up to the provided [`Time::max_delta`].
pub fn update_virtual_time(current: &mut Time, virt: &mut Time<Virtual>, real: &Time<Real>) {
let raw_delta = real.delta();
virt.advance_with_raw_delta(raw_delta);
*current = virt.as_generic();
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_default() {
let time = Time::<Virtual>::default();
assert!(!time.is_paused()); // false
assert_eq!(time.relative_speed(), 1.0);
assert_eq!(time.max_delta(), Time::<Virtual>::DEFAULT_MAX_DELTA);
assert_eq!(time.delta(), Duration::ZERO);
assert_eq!(time.elapsed(), Duration::ZERO);
}
#[test]
fn test_advance() {
let mut time = Time::<Virtual>::default();
time.advance_with_raw_delta(Duration::from_millis(125));
assert_eq!(time.delta(), Duration::from_millis(125));
assert_eq!(time.elapsed(), Duration::from_millis(125));
time.advance_with_raw_delta(Duration::from_millis(125));
assert_eq!(time.delta(), Duration::from_millis(125));
assert_eq!(time.elapsed(), Duration::from_millis(250));
time.advance_with_raw_delta(Duration::from_millis(125));
assert_eq!(time.delta(), Duration::from_millis(125));
assert_eq!(time.elapsed(), Duration::from_millis(375));
time.advance_with_raw_delta(Duration::from_millis(125));
assert_eq!(time.delta(), Duration::from_millis(125));
assert_eq!(time.elapsed(), Duration::from_millis(500));
}
#[test]
fn test_relative_speed() {
let mut time = Time::<Virtual>::default();
time.advance_with_raw_delta(Duration::from_millis(250));
assert_eq!(time.relative_speed(), 1.0);
assert_eq!(time.effective_speed(), 1.0);
assert_eq!(time.delta(), Duration::from_millis(250));
assert_eq!(time.elapsed(), Duration::from_millis(250));
time.set_relative_speed_f64(2.0);
assert_eq!(time.relative_speed(), 2.0);
assert_eq!(time.effective_speed(), 1.0);
time.advance_with_raw_delta(Duration::from_millis(250));
assert_eq!(time.relative_speed(), 2.0);
assert_eq!(time.effective_speed(), 2.0);
assert_eq!(time.delta(), Duration::from_millis(500));
assert_eq!(time.elapsed(), Duration::from_millis(750));
time.set_relative_speed_f64(0.5);
assert_eq!(time.relative_speed(), 0.5);
assert_eq!(time.effective_speed(), 2.0);
time.advance_with_raw_delta(Duration::from_millis(250));
assert_eq!(time.relative_speed(), 0.5);
assert_eq!(time.effective_speed(), 0.5);
assert_eq!(time.delta(), Duration::from_millis(125));
assert_eq!(time.elapsed(), Duration::from_millis(875));
}
#[test]
fn test_pause() {
let mut time = Time::<Virtual>::default();
time.advance_with_raw_delta(Duration::from_millis(250));
assert!(!time.is_paused()); // false
assert!(!time.was_paused()); // false
assert_eq!(time.relative_speed(), 1.0);
assert_eq!(time.effective_speed(), 1.0);
assert_eq!(time.delta(), Duration::from_millis(250));
assert_eq!(time.elapsed(), Duration::from_millis(250));
time.pause();
assert!(time.is_paused()); // true
assert!(!time.was_paused()); // false
assert_eq!(time.relative_speed(), 1.0);
assert_eq!(time.effective_speed(), 1.0);
time.advance_with_raw_delta(Duration::from_millis(250));
assert!(time.is_paused()); // true
assert!(time.was_paused()); // true
assert_eq!(time.relative_speed(), 1.0);
assert_eq!(time.effective_speed(), 0.0);
assert_eq!(time.delta(), Duration::ZERO);
assert_eq!(time.elapsed(), Duration::from_millis(250));
time.unpause();
assert!(!time.is_paused()); // false
assert!(time.was_paused()); // true
assert_eq!(time.relative_speed(), 1.0);
assert_eq!(time.effective_speed(), 0.0);
time.advance_with_raw_delta(Duration::from_millis(250));
assert!(!time.is_paused()); // false
assert!(!time.was_paused()); // false
assert_eq!(time.relative_speed(), 1.0);
assert_eq!(time.effective_speed(), 1.0);
assert_eq!(time.delta(), Duration::from_millis(250));
assert_eq!(time.elapsed(), Duration::from_millis(500));
}
#[test]
fn test_max_delta() {
let mut time = Time::<Virtual>::default();
time.set_max_delta(Duration::from_millis(500));
time.advance_with_raw_delta(Duration::from_millis(250));
assert_eq!(time.delta(), Duration::from_millis(250));
assert_eq!(time.elapsed(), Duration::from_millis(250));
time.advance_with_raw_delta(Duration::from_millis(500));
assert_eq!(time.delta(), Duration::from_millis(500));
assert_eq!(time.elapsed(), Duration::from_millis(750));
time.advance_with_raw_delta(Duration::from_millis(750));
assert_eq!(time.delta(), Duration::from_millis(500));
assert_eq!(time.elapsed(), Duration::from_millis(1250));
time.set_max_delta(Duration::from_secs(1));
assert_eq!(time.max_delta(), Duration::from_secs(1));
time.advance_with_raw_delta(Duration::from_millis(750));
assert_eq!(time.delta(), Duration::from_millis(750));
assert_eq!(time.elapsed(), Duration::from_millis(2000));
time.advance_with_raw_delta(Duration::from_millis(1250));
assert_eq!(time.delta(), Duration::from_millis(1000));
assert_eq!(time.elapsed(), Duration::from_millis(3000));
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_time/src/lib.rs | crates/bevy_time/src/lib.rs | #![doc = include_str!("../README.md")]
#![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]
#[cfg(feature = "std")]
extern crate std;
extern crate alloc;
/// Common run conditions
pub mod common_conditions;
mod fixed;
mod real;
mod stopwatch;
mod time;
mod timer;
mod virt;
pub use fixed::*;
pub use real::*;
pub use stopwatch::*;
pub use time::*;
pub use timer::*;
pub use virt::*;
/// The time prelude.
///
/// This includes the most common types in this crate, re-exported for your convenience.
pub mod prelude {
#[doc(hidden)]
pub use crate::{Fixed, Real, Time, Timer, TimerMode, Virtual};
}
use bevy_app::{prelude::*, RunFixedMainLoop};
use bevy_ecs::{
message::{
message_update_system, signal_message_update_system, MessageRegistry, ShouldUpdateMessages,
},
prelude::*,
};
use bevy_platform::time::Instant;
use core::time::Duration;
#[cfg(feature = "std")]
pub use crossbeam_channel::TrySendError;
#[cfg(feature = "std")]
use crossbeam_channel::{Receiver, Sender};
/// Adds time functionality to Apps.
#[derive(Default)]
pub struct TimePlugin;
/// Updates the elapsed time. Any system that interacts with [`Time`] component should run after
/// this.
#[derive(Debug, PartialEq, Eq, Clone, Hash, SystemSet)]
pub struct TimeSystems;
impl Plugin for TimePlugin {
fn build(&self, app: &mut App) {
app.init_resource::<Time>()
.init_resource::<Time<Real>>()
.init_resource::<Time<Virtual>>()
.init_resource::<Time<Fixed>>()
.init_resource::<TimeUpdateStrategy>();
#[cfg(feature = "bevy_reflect")]
{
app.register_type::<Time>()
.register_type::<Time<Real>>()
.register_type::<Time<Virtual>>()
.register_type::<Time<Fixed>>();
}
app.add_systems(
First,
time_system
.in_set(TimeSystems)
.ambiguous_with(message_update_system),
)
.add_systems(
RunFixedMainLoop,
run_fixed_main_schedule.in_set(RunFixedMainLoopSystems::FixedMainLoop),
);
// Ensure the messages are not dropped until `FixedMain` systems can observe them
app.add_systems(FixedPostUpdate, signal_message_update_system);
let mut message_registry = app.world_mut().resource_mut::<MessageRegistry>();
// We need to start in a waiting state so that the messages are not updated until the first fixed update
message_registry.should_update = ShouldUpdateMessages::Waiting;
}
}
/// Configuration resource used to determine how the time system should run.
///
/// For most cases, [`TimeUpdateStrategy::Automatic`] is fine. When writing tests, dealing with
/// networking or similar, you may prefer to set the next [`Time`] value manually.
#[derive(Resource, Default)]
pub enum TimeUpdateStrategy {
/// [`Time`] will be automatically updated each frame using an [`Instant`] sent from the render world.
/// If nothing is sent, the system clock will be used instead.
#[cfg_attr(feature = "std", doc = "See [`TimeSender`] for more details.")]
#[default]
Automatic,
/// [`Time`] will be updated to the specified [`Instant`] value each frame.
/// In order for time to progress, this value must be manually updated each frame.
///
/// Note that the `Time` resource will not be updated until [`TimeSystems`] runs.
ManualInstant(Instant),
/// [`Time`] will be incremented by the specified [`Duration`] each frame.
ManualDuration(Duration),
/// [`Time`] will be incremented by the fixed timestep each frame, multiplied by the specified factor `n`.
/// This means that a call to [`App::update`] will always run the fixed loop exactly n times.
FixedTimesteps(u32),
}
/// Channel resource used to receive time from the render world.
#[cfg(feature = "std")]
#[derive(Resource)]
pub struct TimeReceiver(pub Receiver<Instant>);
/// Channel resource used to send time from the render world.
#[cfg(feature = "std")]
#[derive(Resource)]
pub struct TimeSender(pub Sender<Instant>);
/// Creates channels used for sending time between the render world and the main world.
#[cfg(feature = "std")]
pub fn create_time_channels() -> (TimeSender, TimeReceiver) {
// bound the channel to 2 since when pipelined the render phase can finish before
// the time system runs.
let (s, r) = crossbeam_channel::bounded::<Instant>(2);
(TimeSender(s), TimeReceiver(r))
}
/// The system used to update the [`Time`] used by app logic. If there is a render world the time is
/// sent from there to this system through channels. Otherwise the time is updated in this system.
pub fn time_system(
mut real_time: ResMut<Time<Real>>,
mut virtual_time: ResMut<Time<Virtual>>,
fixed_time: Res<Time<Fixed>>,
mut time: ResMut<Time>,
update_strategy: Res<TimeUpdateStrategy>,
#[cfg(feature = "std")] time_recv: Option<Res<TimeReceiver>>,
#[cfg(feature = "std")] mut has_received_time: Local<bool>,
) {
#[cfg(feature = "std")]
// TODO: Figure out how to handle this when using pipelined rendering.
let sent_time = match time_recv.map(|res| res.0.try_recv()) {
Some(Ok(new_time)) => {
*has_received_time = true;
Some(new_time)
}
Some(Err(_)) => {
if *has_received_time {
log::warn!("time_system did not receive the time from the render world! Calculations depending on the time may be incorrect.");
}
None
}
None => None,
};
match update_strategy.as_ref() {
TimeUpdateStrategy::Automatic => {
#[cfg(feature = "std")]
real_time.update_with_instant(sent_time.unwrap_or_else(Instant::now));
#[cfg(not(feature = "std"))]
real_time.update_with_instant(Instant::now());
}
TimeUpdateStrategy::ManualInstant(instant) => real_time.update_with_instant(*instant),
TimeUpdateStrategy::ManualDuration(duration) => real_time.update_with_duration(*duration),
TimeUpdateStrategy::FixedTimesteps(factor) => {
real_time.update_with_duration(fixed_time.timestep() * *factor);
}
}
update_virtual_time(&mut time, &mut virtual_time, &real_time);
}
#[cfg(test)]
#[expect(clippy::print_stdout, reason = "Allowed in tests.")]
mod tests {
use crate::{Fixed, Time, TimePlugin, TimeUpdateStrategy, Virtual};
use bevy_app::{App, FixedUpdate, Startup, Update};
use bevy_ecs::{
message::{
Message, MessageReader, MessageRegistry, MessageWriter, Messages, ShouldUpdateMessages,
},
resource::Resource,
system::{Local, Res, ResMut},
};
use core::error::Error;
use core::time::Duration;
use std::println;
#[derive(Message)]
struct TestMessage<T: Default> {
sender: std::sync::mpsc::Sender<T>,
}
impl<T: Default> Drop for TestMessage<T> {
fn drop(&mut self) {
self.sender
.send(T::default())
.expect("Failed to send drop signal");
}
}
#[derive(Message)]
struct DummyMessage;
#[derive(Resource, Default)]
struct FixedUpdateCounter(u8);
fn count_fixed_updates(mut counter: ResMut<FixedUpdateCounter>) {
counter.0 += 1;
}
fn report_time(
mut frame_count: Local<u64>,
virtual_time: Res<Time<Virtual>>,
fixed_time: Res<Time<Fixed>>,
) {
println!(
"Virtual time on frame {}: {:?}",
*frame_count,
virtual_time.elapsed()
);
println!(
"Fixed time on frame {}: {:?}",
*frame_count,
fixed_time.elapsed()
);
*frame_count += 1;
}
#[test]
fn fixed_main_schedule_should_run_with_time_plugin_enabled() {
// Set the time step to just over half the fixed update timestep
// This way, it will have not accumulated enough time to run the fixed update after one update
// But will definitely have enough time after two updates
let fixed_update_timestep = Time::<Fixed>::default().timestep();
let time_step = fixed_update_timestep / 2 + Duration::from_millis(1);
let mut app = App::new();
app.add_plugins(TimePlugin)
.add_systems(FixedUpdate, count_fixed_updates)
.add_systems(Update, report_time)
.init_resource::<FixedUpdateCounter>()
.insert_resource(TimeUpdateStrategy::ManualDuration(time_step));
// Frame 0
// Fixed update should not have run yet
app.update();
assert!(Duration::ZERO < fixed_update_timestep);
let counter = app.world().resource::<FixedUpdateCounter>();
assert_eq!(counter.0, 0, "Fixed update should not have run yet");
// Frame 1
// Fixed update should not have run yet
app.update();
assert!(time_step < fixed_update_timestep);
let counter = app.world().resource::<FixedUpdateCounter>();
assert_eq!(counter.0, 0, "Fixed update should not have run yet");
// Frame 2
// Fixed update should have run now
app.update();
assert!(2 * time_step > fixed_update_timestep);
let counter = app.world().resource::<FixedUpdateCounter>();
assert_eq!(counter.0, 1, "Fixed update should have run once");
// Frame 3
// Fixed update should have run exactly once still
app.update();
assert!(3 * time_step < 2 * fixed_update_timestep);
let counter = app.world().resource::<FixedUpdateCounter>();
assert_eq!(counter.0, 1, "Fixed update should have run once");
// Frame 4
// Fixed update should have run twice now
app.update();
assert!(4 * time_step > 2 * fixed_update_timestep);
let counter = app.world().resource::<FixedUpdateCounter>();
assert_eq!(counter.0, 2, "Fixed update should have run twice");
}
#[test]
fn events_get_dropped_regression_test_11528() -> Result<(), impl Error> {
let (tx1, rx1) = std::sync::mpsc::channel();
let (tx2, rx2) = std::sync::mpsc::channel();
let mut app = App::new();
app.add_plugins(TimePlugin)
.add_message::<TestMessage<i32>>()
.add_message::<TestMessage<()>>()
.add_systems(Startup, move |mut ev2: MessageWriter<TestMessage<()>>| {
ev2.write(TestMessage {
sender: tx2.clone(),
});
})
.add_systems(Update, move |mut ev1: MessageWriter<TestMessage<i32>>| {
// Keep adding events so this event type is processed every update
ev1.write(TestMessage {
sender: tx1.clone(),
});
})
.add_systems(
Update,
|mut m1: MessageReader<TestMessage<i32>>,
mut m2: MessageReader<TestMessage<()>>| {
// Read events so they can be dropped
for _ in m1.read() {}
for _ in m2.read() {}
},
)
.insert_resource(TimeUpdateStrategy::ManualDuration(
Time::<Fixed>::default().timestep(),
));
for _ in 0..10 {
app.update();
}
// Check event type 1 as been dropped at least once
let _drop_signal = rx1.try_recv()?;
// Check event type 2 has been dropped
rx2.try_recv()
}
#[test]
fn event_update_should_wait_for_fixed_main() {
// Set the time step to just over half the fixed update timestep
// This way, it will have not accumulated enough time to run the fixed update after one update
// But will definitely have enough time after two updates
let fixed_update_timestep = Time::<Fixed>::default().timestep();
let time_step = fixed_update_timestep / 2 + Duration::from_millis(1);
fn write_message(mut messages: ResMut<Messages<DummyMessage>>) {
messages.write(DummyMessage);
}
let mut app = App::new();
app.add_plugins(TimePlugin)
.add_message::<DummyMessage>()
.init_resource::<FixedUpdateCounter>()
.add_systems(Startup, write_message)
.add_systems(FixedUpdate, count_fixed_updates)
.insert_resource(TimeUpdateStrategy::ManualDuration(time_step));
for frame in 0..10 {
app.update();
let fixed_updates_seen = app.world().resource::<FixedUpdateCounter>().0;
let messages = app.world().resource::<Messages<DummyMessage>>();
let n_total_messages = messages.len();
let n_current_messages = messages.iter_current_update_messages().count();
let message_registry = app.world().resource::<MessageRegistry>();
let should_update = message_registry.should_update;
println!("Frame {frame}, {fixed_updates_seen} fixed updates seen. Should update: {should_update:?}");
println!("Total messages: {n_total_messages} | Current messages: {n_current_messages}",);
match frame {
0 | 1 => {
assert_eq!(fixed_updates_seen, 0);
assert_eq!(n_total_messages, 1);
assert_eq!(n_current_messages, 1);
assert_eq!(should_update, ShouldUpdateMessages::Waiting);
}
2 => {
assert_eq!(fixed_updates_seen, 1); // Time to trigger event updates
assert_eq!(n_total_messages, 1);
assert_eq!(n_current_messages, 1);
assert_eq!(should_update, ShouldUpdateMessages::Ready); // Prepping first update
}
3 => {
assert_eq!(fixed_updates_seen, 1);
assert_eq!(n_total_messages, 1);
assert_eq!(n_current_messages, 0); // First update has occurred
assert_eq!(should_update, ShouldUpdateMessages::Waiting);
}
4 => {
assert_eq!(fixed_updates_seen, 2); // Time to trigger the second update
assert_eq!(n_total_messages, 1);
assert_eq!(n_current_messages, 0);
assert_eq!(should_update, ShouldUpdateMessages::Ready); // Prepping second update
}
5 => {
assert_eq!(fixed_updates_seen, 2);
assert_eq!(n_total_messages, 0); // Second update has occurred
assert_eq!(n_current_messages, 0);
assert_eq!(should_update, ShouldUpdateMessages::Waiting);
}
_ => {
assert_eq!(n_total_messages, 0); // No more events are sent
assert_eq!(n_current_messages, 0);
}
}
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_time/src/fixed.rs | crates/bevy_time/src/fixed.rs | use bevy_app::FixedMain;
use bevy_ecs::world::World;
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
use core::time::Duration;
use crate::{time::Time, virt::Virtual};
/// The fixed timestep game clock following virtual time.
///
/// A specialization of the [`Time`] structure. **For method documentation, see
/// [`Time<Fixed>#impl-Time<Fixed>`].**
///
/// It is automatically inserted as a resource by
/// [`TimePlugin`](crate::TimePlugin) and updated based on
/// [`Time<Virtual>`](Virtual). The fixed clock is automatically set as the
/// generic [`Time`] resource during [`FixedUpdate`](bevy_app::FixedUpdate)
/// schedule processing.
///
/// The fixed timestep clock advances in fixed-size increments, which is
/// extremely useful for writing logic (like physics) that should have
/// consistent behavior, regardless of framerate.
///
/// The default [`timestep()`](Time::timestep) is 64 hertz, or 15625
/// microseconds. This value was chosen because using 60 hertz has the potential
/// for a pathological interaction with the monitor refresh rate where the game
/// alternates between running two fixed timesteps and zero fixed timesteps per
/// frame (for example when running two fixed timesteps takes longer than a
/// frame). Additionally, the value is a power of two which losslessly converts
/// into [`f32`] and [`f64`].
///
/// To run a system on a fixed timestep, add it to one of the [`FixedMain`]
/// schedules, most commonly [`FixedUpdate`](bevy_app::FixedUpdate).
///
/// This schedule is run a number of times between
/// [`PreUpdate`](bevy_app::PreUpdate) and [`Update`](bevy_app::Update)
/// according to the accumulated [`overstep()`](Time::overstep) time divided by
/// the [`timestep()`](Time::timestep). This means the schedule may run 0, 1 or
/// more times during a single update (which typically corresponds to a rendered
/// frame).
///
/// `Time<Fixed>` and the generic [`Time`] resource will report a
/// [`delta()`](Time::delta) equal to [`timestep()`](Time::timestep) and always
/// grow [`elapsed()`](Time::elapsed) by one [`timestep()`](Time::timestep) per
/// iteration.
///
/// The fixed timestep clock follows the [`Time<Virtual>`](Virtual) clock, which
/// means it is affected by [`pause()`](Time::pause),
/// [`set_relative_speed()`](Time::set_relative_speed) and
/// [`set_max_delta()`](Time::set_max_delta) from virtual time. If the virtual
/// clock is paused, the [`FixedUpdate`](bevy_app::FixedUpdate) schedule will
/// not run. It is guaranteed that the [`elapsed()`](Time::elapsed) time in
/// `Time<Fixed>` is always between the previous `elapsed()` and the current
/// `elapsed()` value in `Time<Virtual>`, so the values are compatible.
///
/// Changing the timestep size while the game is running should not normally be
/// done, as having a regular interval is the point of this schedule, but it may
/// be necessary for effects like "bullet-time" if the normal granularity of the
/// fixed timestep is too big for the slowed down time. In this case,
/// [`set_timestep()`](Time::set_timestep) and be called to set a new value. The
/// new value will be used immediately for the next run of the
/// [`FixedUpdate`](bevy_app::FixedUpdate) schedule, meaning that it will affect
/// the [`delta()`](Time::delta) value for the very next
/// [`FixedUpdate`](bevy_app::FixedUpdate), even if it is still during the same
/// frame. Any [`overstep()`](Time::overstep) present in the accumulator will be
/// processed according to the new [`timestep()`](Time::timestep) value.
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Clone))]
pub struct Fixed {
timestep: Duration,
overstep: Duration,
}
impl Time<Fixed> {
/// Corresponds to 64 Hz.
const DEFAULT_TIMESTEP: Duration = Duration::from_micros(15625);
/// Return new fixed time clock with given timestep as [`Duration`]
///
/// # Panics
///
/// Panics if `timestep` is zero.
pub fn from_duration(timestep: Duration) -> Self {
let mut ret = Self::default();
ret.set_timestep(timestep);
ret
}
/// Return new fixed time clock with given timestep seconds as `f64`
///
/// # Panics
///
/// Panics if `seconds` is zero, negative or not finite.
pub fn from_seconds(seconds: f64) -> Self {
let mut ret = Self::default();
ret.set_timestep_seconds(seconds);
ret
}
/// Return new fixed time clock with given timestep frequency in Hertz (1/seconds)
///
/// # Panics
///
/// Panics if `hz` is zero, negative or not finite.
pub fn from_hz(hz: f64) -> Self {
let mut ret = Self::default();
ret.set_timestep_hz(hz);
ret
}
/// Returns the amount of virtual time that must pass before the fixed
/// timestep schedule is run again.
#[inline]
pub fn timestep(&self) -> Duration {
self.context().timestep
}
/// Sets the amount of virtual time that must pass before the fixed timestep
/// schedule is run again, as [`Duration`].
///
/// Takes effect immediately on the next run of the schedule, respecting
/// what is currently in [`Self::overstep`].
///
/// # Panics
///
/// Panics if `timestep` is zero.
#[inline]
pub fn set_timestep(&mut self, timestep: Duration) {
assert_ne!(
timestep,
Duration::ZERO,
"attempted to set fixed timestep to zero"
);
self.context_mut().timestep = timestep;
}
/// Sets the amount of virtual time that must pass before the fixed timestep
/// schedule is run again, as seconds.
///
/// Timestep is stored as a [`Duration`], which has fixed nanosecond
/// resolution and will be converted from the floating point number.
///
/// Takes effect immediately on the next run of the schedule, respecting
/// what is currently in [`Self::overstep`].
///
/// # Panics
///
/// Panics if `seconds` is zero, negative or not finite.
#[inline]
pub fn set_timestep_seconds(&mut self, seconds: f64) {
assert!(
seconds.is_sign_positive(),
"seconds less than or equal to zero"
);
assert!(seconds.is_finite(), "seconds is infinite");
self.set_timestep(Duration::from_secs_f64(seconds));
}
/// Sets the amount of virtual time that must pass before the fixed timestep
/// schedule is run again, as frequency.
///
/// The timestep value is set to `1 / hz`, converted to a [`Duration`] which
/// has fixed nanosecond resolution.
///
/// Takes effect immediately on the next run of the schedule, respecting
/// what is currently in [`Self::overstep`].
///
/// # Panics
///
/// Panics if `hz` is zero, negative or not finite.
#[inline]
pub fn set_timestep_hz(&mut self, hz: f64) {
assert!(hz.is_sign_positive(), "Hz less than or equal to zero");
assert!(hz.is_finite(), "Hz is infinite");
self.set_timestep_seconds(1.0 / hz);
}
/// Returns the amount of overstep time accumulated toward new steps, as
/// [`Duration`].
#[inline]
pub fn overstep(&self) -> Duration {
self.context().overstep
}
/// Increase the overstep time accumulated towards new steps.
///
/// This method is provided for use in tests. Ordinarily, the [`run_fixed_main_schedule`] system is responsible for calculating the overstep.
#[inline]
pub fn accumulate_overstep(&mut self, delta: Duration) {
self.context_mut().overstep += delta;
}
/// Discard a part of the overstep amount.
///
/// If `discard` is higher than overstep, the overstep becomes zero.
#[inline]
pub fn discard_overstep(&mut self, discard: Duration) {
let context = self.context_mut();
context.overstep = context.overstep.saturating_sub(discard);
}
/// Returns the amount of overstep time accumulated toward new steps, as an
/// [`f32`] fraction of the timestep.
#[inline]
pub fn overstep_fraction(&self) -> f32 {
self.context().overstep.as_secs_f32() / self.context().timestep.as_secs_f32()
}
/// Returns the amount of overstep time accumulated toward new steps, as an
/// [`f64`] fraction of the timestep.
#[inline]
pub fn overstep_fraction_f64(&self) -> f64 {
self.context().overstep.as_secs_f64() / self.context().timestep.as_secs_f64()
}
fn expend(&mut self) -> bool {
let timestep = self.timestep();
if let Some(new_value) = self.context_mut().overstep.checked_sub(timestep) {
// reduce accumulated and increase elapsed by period
self.context_mut().overstep = new_value;
self.advance_by(timestep);
true
} else {
// no more periods left in accumulated
false
}
}
}
impl Default for Fixed {
fn default() -> Self {
Self {
timestep: Time::<Fixed>::DEFAULT_TIMESTEP,
overstep: Duration::ZERO,
}
}
}
/// Runs [`FixedMain`] zero or more times based on delta of
/// [`Time<Virtual>`](Virtual) and [`Time::overstep`].
/// You can order your systems relative to this by using
/// [`RunFixedMainLoopSystems`](bevy_app::prelude::RunFixedMainLoopSystems).
pub fn run_fixed_main_schedule(world: &mut World) {
let delta = world.resource::<Time<Virtual>>().delta();
world
.resource_mut::<Time<Fixed>>()
.accumulate_overstep(delta);
// Run the schedule until we run out of accumulated time
let _ = world.try_schedule_scope(FixedMain, |world, schedule| {
while world.resource_mut::<Time<Fixed>>().expend() {
*world.resource_mut::<Time>() = world.resource::<Time<Fixed>>().as_generic();
schedule.run(world);
}
});
*world.resource_mut::<Time>() = world.resource::<Time<Virtual>>().as_generic();
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_set_timestep() {
let mut time = Time::<Fixed>::default();
assert_eq!(time.timestep(), Time::<Fixed>::DEFAULT_TIMESTEP);
time.set_timestep(Duration::from_millis(500));
assert_eq!(time.timestep(), Duration::from_millis(500));
time.set_timestep_seconds(0.25);
assert_eq!(time.timestep(), Duration::from_millis(250));
time.set_timestep_hz(8.0);
assert_eq!(time.timestep(), Duration::from_millis(125));
}
#[test]
fn test_expend() {
let mut time = Time::<Fixed>::from_seconds(2.0);
assert_eq!(time.delta(), Duration::ZERO);
assert_eq!(time.elapsed(), Duration::ZERO);
time.accumulate_overstep(Duration::from_secs(1));
assert_eq!(time.delta(), Duration::ZERO);
assert_eq!(time.elapsed(), Duration::ZERO);
assert_eq!(time.overstep(), Duration::from_secs(1));
assert_eq!(time.overstep_fraction(), 0.5);
assert_eq!(time.overstep_fraction_f64(), 0.5);
assert!(!time.expend()); // false
assert_eq!(time.delta(), Duration::ZERO);
assert_eq!(time.elapsed(), Duration::ZERO);
assert_eq!(time.overstep(), Duration::from_secs(1));
assert_eq!(time.overstep_fraction(), 0.5);
assert_eq!(time.overstep_fraction_f64(), 0.5);
time.accumulate_overstep(Duration::from_secs(1));
assert_eq!(time.delta(), Duration::ZERO);
assert_eq!(time.elapsed(), Duration::ZERO);
assert_eq!(time.overstep(), Duration::from_secs(2));
assert_eq!(time.overstep_fraction(), 1.0);
assert_eq!(time.overstep_fraction_f64(), 1.0);
assert!(time.expend()); // true
assert_eq!(time.delta(), Duration::from_secs(2));
assert_eq!(time.elapsed(), Duration::from_secs(2));
assert_eq!(time.overstep(), Duration::ZERO);
assert_eq!(time.overstep_fraction(), 0.0);
assert_eq!(time.overstep_fraction_f64(), 0.0);
assert!(!time.expend()); // false
assert_eq!(time.delta(), Duration::from_secs(2));
assert_eq!(time.elapsed(), Duration::from_secs(2));
assert_eq!(time.overstep(), Duration::ZERO);
assert_eq!(time.overstep_fraction(), 0.0);
assert_eq!(time.overstep_fraction_f64(), 0.0);
time.accumulate_overstep(Duration::from_secs(1));
assert_eq!(time.delta(), Duration::from_secs(2));
assert_eq!(time.elapsed(), Duration::from_secs(2));
assert_eq!(time.overstep(), Duration::from_secs(1));
assert_eq!(time.overstep_fraction(), 0.5);
assert_eq!(time.overstep_fraction_f64(), 0.5);
assert!(!time.expend()); // false
assert_eq!(time.delta(), Duration::from_secs(2));
assert_eq!(time.elapsed(), Duration::from_secs(2));
assert_eq!(time.overstep(), Duration::from_secs(1));
assert_eq!(time.overstep_fraction(), 0.5);
assert_eq!(time.overstep_fraction_f64(), 0.5);
}
#[test]
fn test_expend_multiple() {
let mut time = Time::<Fixed>::from_seconds(2.0);
time.accumulate_overstep(Duration::from_secs(7));
assert_eq!(time.overstep(), Duration::from_secs(7));
assert!(time.expend()); // true
assert_eq!(time.elapsed(), Duration::from_secs(2));
assert_eq!(time.overstep(), Duration::from_secs(5));
assert!(time.expend()); // true
assert_eq!(time.elapsed(), Duration::from_secs(4));
assert_eq!(time.overstep(), Duration::from_secs(3));
assert!(time.expend()); // true
assert_eq!(time.elapsed(), Duration::from_secs(6));
assert_eq!(time.overstep(), Duration::from_secs(1));
assert!(!time.expend()); // false
assert_eq!(time.elapsed(), Duration::from_secs(6));
assert_eq!(time.overstep(), Duration::from_secs(1));
}
}
| 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.