Enum Color

Source
pub enum Color {
    Srgba(Srgba),
    LinearRgba(LinearRgba),
    Hsla(Hsla),
    Hsva(Hsva),
    Hwba(Hwba),
    Laba(Laba),
    Lcha(Lcha),
    Oklaba(Oklaba),
    Oklcha(Oklcha),
    Xyza(Xyza),
}
Expand description

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.

§Conversion

Conversion between the various color spaces is achieved using Rust’s native From trait. Because certain color spaces are defined by their transformation to and from another space, these From implementations reflect that set of definitions.

let color = Srgba::rgb(0.5, 0.5, 0.5);

// Using From explicitly
let linear_color = LinearRgba::from(color);

// Using Into
let linear_color: LinearRgba = color.into();

For example, the sRGB space is defined by its relationship with Linear RGB, and HWB by its with sRGB. As such, it is the responsibility of sRGB to provide From implementations for Linear RGB, and HWB for sRGB. To then provide conversion between Linear RGB and HWB directly, HWB is responsible for implementing these conversions, delegating to sRGB as an intermediatory. This ensures that all conversions take the shortest path between any two spaces, and limit the proliferation of domain specific knowledge for each color space to their respective definitions.

GPU

§Operations

Color supports all the standard color operations, such as mixing, luminance and hue adjustment, and diffing. These operations delegate to the concrete color space contained by Color, but will convert to Oklch 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.

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 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.

Variants§

§

Srgba(Srgba)

A color in the sRGB color space with alpha.

§

LinearRgba(LinearRgba)

A color in the linear sRGB color space with alpha.

§

Hsla(Hsla)

A color in the HSL color space with alpha.

§

Hsva(Hsva)

A color in the HSV color space with alpha.

§

Hwba(Hwba)

A color in the HWB color space with alpha.

§

Laba(Laba)

A color in the LAB color space with alpha.

§

Lcha(Lcha)

A color in the LCH color space with alpha.

§

Oklaba(Oklaba)

A color in the Oklab color space with alpha.

§

Oklcha(Oklcha)

A color in the Oklch color space with alpha.

§

Xyza(Xyza)

A color in the XYZ color space with alpha.

Implementations§

Source§

impl Color

Source

pub const WHITE: Color

A fully white Color::LinearRgba color with an alpha of 1.0.

Source

pub const BLACK: Color

A fully black Color::LinearRgba color with an alpha of 1.0.

Source

pub const NONE: Color

A fully transparent Color::LinearRgba color with 0 red, green and blue.

Source

pub fn to_linear(&self) -> LinearRgba

Return the color as a linear RGBA color.

Examples found in repository?
examples/ui/ui_material.rs (line 90)
79fn animate(
80    mut materials: ResMut<Assets<CustomUiMaterial>>,
81    q: Query<&MaterialNode<CustomUiMaterial>>,
82    time: Res<Time>,
83) {
84    let duration = 2.0;
85    for handle in &q {
86        if let Some(material) = materials.get_mut(handle) {
87            // rainbow color effect
88            let new_color = Color::hsl((time.elapsed_secs() * 60.0) % 360.0, 1., 0.5);
89            let border_color = Color::hsl((time.elapsed_secs() * 60.0) % 360.0, 0.75, 0.75);
90            material.color = new_color.to_linear().to_vec4();
91            material.slider =
92                ((time.elapsed_secs() % (duration * 2.0)) - duration).abs() / duration;
93            material.border_color = border_color.to_linear().to_vec4();
94        }
95    }
96}
Source

pub fn to_srgba(&self) -> Srgba

Return the color as an SRGBA color.

Examples found in repository?
examples/2d/wireframe_2d.rs (line 121)
103fn update_colors(
104    keyboard_input: Res<ButtonInput<KeyCode>>,
105    mut config: ResMut<Wireframe2dConfig>,
106    mut wireframe_colors: Query<&mut Wireframe2dColor>,
107    mut text: Single<&mut Text>,
108) {
109    text.0 = format!(
110        "Controls
111---------------
112Z - Toggle global
113X - Change global color
114C - Change color of the circle wireframe
115
116Wireframe2dConfig
117-------------
118Global: {}
119Color: {:?}",
120        config.global,
121        config.default_color.to_srgba(),
122    );
123
124    // Toggle showing a wireframe on all meshes
125    if keyboard_input.just_pressed(KeyCode::KeyZ) {
126        config.global = !config.global;
127    }
128
129    // Toggle the global wireframe color
130    if keyboard_input.just_pressed(KeyCode::KeyX) {
131        config.default_color = if config.default_color == WHITE.into() {
132            RED.into()
133        } else {
134            WHITE.into()
135        };
136    }
137
138    // Toggle the color of a wireframe using `Wireframe2dColor` and not the global color
139    if keyboard_input.just_pressed(KeyCode::KeyC) {
140        for mut color in &mut wireframe_colors {
141            color.color = if color.color == GREEN.into() {
142                RED.into()
143            } else {
144                GREEN.into()
145            };
146        }
147    }
148}
Source

pub const fn rgba(red: f32, green: f32, blue: f32, alpha: f32) -> Color

👎Deprecated: Use Color::srgba instead

Creates a new Color object storing a Srgba color.

Source

pub const fn srgba(red: f32, green: f32, blue: f32, alpha: f32) -> Color

Creates a new Color object storing a Srgba color.

Examples found in repository?
examples/3d/clearcoat.rs (line 132)
119fn spawn_coated_glass_bubble_sphere(
120    commands: &mut Commands,
121    materials: &mut Assets<StandardMaterial>,
122    sphere: &Handle<Mesh>,
123) {
124    commands
125        .spawn((
126            Mesh3d(sphere.clone()),
127            MeshMaterial3d(materials.add(StandardMaterial {
128                clearcoat: 1.0,
129                clearcoat_perceptual_roughness: 0.1,
130                metallic: 0.5,
131                perceptual_roughness: 0.1,
132                base_color: Color::srgba(0.9, 0.9, 0.9, 0.3),
133                alpha_mode: AlphaMode::Blend,
134                ..default()
135            })),
136            Transform::from_xyz(-1.0, -1.0, 0.0).with_scale(Vec3::splat(SPHERE_SCALE)),
137        ))
138        .insert(ExampleSphere);
139}
More examples
Hide additional examples
examples/2d/transparency_2d.rs (line 23)
13fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
14    commands.spawn(Camera2d);
15
16    let sprite_handle = asset_server.load("branding/icon.png");
17
18    commands.spawn(Sprite::from_image(sprite_handle.clone()));
19    commands.spawn((
20        Sprite {
21            image: sprite_handle.clone(),
22            // Alpha channel of the color controls transparency.
23            color: Color::srgba(0.0, 0.0, 1.0, 0.7),
24            ..default()
25        },
26        Transform::from_xyz(100.0, 0.0, 0.0),
27    ));
28    commands.spawn((
29        Sprite {
30            image: sprite_handle,
31            color: Color::srgba(0.0, 1.0, 0.0, 0.3),
32            ..default()
33        },
34        Transform::from_xyz(200.0, 0.0, 0.0),
35    ));
36}
examples/3d/atmospheric_fog.rs (line 31)
26fn setup_camera_fog(mut commands: Commands) {
27    commands.spawn((
28        Camera3d::default(),
29        Transform::from_xyz(-1.0, 0.1, 1.0).looking_at(Vec3::new(0.0, 0.0, 0.0), Vec3::Y),
30        DistanceFog {
31            color: Color::srgba(0.35, 0.48, 0.66, 1.0),
32            directional_light_color: Color::srgba(1.0, 0.95, 0.85, 0.5),
33            directional_light_exponent: 30.0,
34            falloff: FogFalloff::from_visibility_colors(
35                15.0, // distance in world units up to which objects retain visibility (>= 5% contrast)
36                Color::srgb(0.35, 0.5, 0.66), // atmospheric extinction color (after light is lost due to absorption by atmospheric particles)
37                Color::srgb(0.8, 0.844, 1.0), // atmospheric inscattering color (light gained due to scattering from the sun)
38            ),
39        },
40    ));
41}
examples/3d/texture.rs (line 39)
15fn setup(
16    mut commands: Commands,
17    asset_server: Res<AssetServer>,
18    mut meshes: ResMut<Assets<Mesh>>,
19    mut materials: ResMut<Assets<StandardMaterial>>,
20) {
21    // load a texture and retrieve its aspect ratio
22    let texture_handle = asset_server.load("branding/bevy_logo_dark_big.png");
23    let aspect = 0.25;
24
25    // create a new quad mesh. this is what we will apply the texture to
26    let quad_width = 8.0;
27    let quad_handle = meshes.add(Rectangle::new(quad_width, quad_width * aspect));
28
29    // this material renders the texture normally
30    let material_handle = materials.add(StandardMaterial {
31        base_color_texture: Some(texture_handle.clone()),
32        alpha_mode: AlphaMode::Blend,
33        unlit: true,
34        ..default()
35    });
36
37    // this material modulates the texture to make it red (and slightly transparent)
38    let red_material_handle = materials.add(StandardMaterial {
39        base_color: Color::srgba(1.0, 0.0, 0.0, 0.5),
40        base_color_texture: Some(texture_handle.clone()),
41        alpha_mode: AlphaMode::Blend,
42        unlit: true,
43        ..default()
44    });
45
46    // and lets make this one blue! (and also slightly transparent)
47    let blue_material_handle = materials.add(StandardMaterial {
48        base_color: Color::srgba(0.0, 0.0, 1.0, 0.5),
49        base_color_texture: Some(texture_handle),
50        alpha_mode: AlphaMode::Blend,
51        unlit: true,
52        ..default()
53    });
54
55    // textured quad - normal
56    commands.spawn((
57        Mesh3d(quad_handle.clone()),
58        MeshMaterial3d(material_handle),
59        Transform::from_xyz(0.0, 0.0, 1.5).with_rotation(Quat::from_rotation_x(-PI / 5.0)),
60    ));
61    // textured quad - modulated
62    commands.spawn((
63        Mesh3d(quad_handle.clone()),
64        MeshMaterial3d(red_material_handle),
65        Transform::from_rotation(Quat::from_rotation_x(-PI / 5.0)),
66    ));
67    // textured quad - modulated
68    commands.spawn((
69        Mesh3d(quad_handle),
70        MeshMaterial3d(blue_material_handle),
71        Transform::from_xyz(0.0, 0.0, -1.5).with_rotation(Quat::from_rotation_x(-PI / 5.0)),
72    ));
73    // camera
74    commands.spawn((
75        Camera3d::default(),
76        Transform::from_xyz(3.0, 5.0, 8.0).looking_at(Vec3::ZERO, Vec3::Y),
77    ));
78}
examples/ui/transparency_ui.rs (line 49)
14fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
15    commands.spawn(Camera2d);
16
17    let font_handle = asset_server.load("fonts/FiraSans-Bold.ttf");
18
19    commands
20        .spawn(Node {
21            width: Val::Percent(100.0),
22            height: Val::Percent(100.0),
23            align_items: AlignItems::Center,
24            justify_content: JustifyContent::SpaceAround,
25            ..default()
26        })
27        .with_children(|parent| {
28            parent
29                .spawn((
30                    Button,
31                    Node {
32                        width: Val::Px(150.0),
33                        height: Val::Px(65.0),
34                        justify_content: JustifyContent::Center,
35                        align_items: AlignItems::Center,
36                        ..default()
37                    },
38                    BackgroundColor(Color::srgb(0.1, 0.5, 0.1)),
39                ))
40                .with_children(|parent| {
41                    parent.spawn((
42                        Text::new("Button 1"),
43                        TextFont {
44                            font: font_handle.clone(),
45                            font_size: 33.0,
46                            ..default()
47                        },
48                        // Alpha channel of the color controls transparency.
49                        TextColor(Color::srgba(1.0, 1.0, 1.0, 0.2)),
50                    ));
51                });
52
53            // Button with a different color,
54            // to demonstrate the text looks different due to its transparency.
55            parent
56                .spawn((
57                    Button,
58                    Node {
59                        width: Val::Px(150.0),
60                        height: Val::Px(65.0),
61                        justify_content: JustifyContent::Center,
62                        align_items: AlignItems::Center,
63                        ..default()
64                    },
65                    BackgroundColor(Color::srgb(0.5, 0.1, 0.5)),
66                ))
67                .with_children(|parent| {
68                    parent.spawn((
69                        Text::new("Button 2"),
70                        TextFont {
71                            font: font_handle.clone(),
72                            font_size: 33.0,
73                            ..default()
74                        },
75                        // Alpha channel of the color controls transparency.
76                        TextColor(Color::srgba(1.0, 1.0, 1.0, 0.2)),
77                    ));
78                });
79        });
80}
examples/math/random_sampling.rs (line 75)
51fn setup(
52    mut commands: Commands,
53    mut meshes: ResMut<Assets<Mesh>>,
54    mut materials: ResMut<Assets<StandardMaterial>>,
55) {
56    // Use seeded rng and store it in a resource; this makes the random output reproducible.
57    let seeded_rng = ChaCha8Rng::seed_from_u64(19878367467712);
58    commands.insert_resource(RandomSource(seeded_rng));
59
60    // Make a plane for establishing space.
61    commands.spawn((
62        Mesh3d(meshes.add(Plane3d::default().mesh().size(12.0, 12.0))),
63        MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))),
64        Transform::from_xyz(0.0, -2.5, 0.0),
65    ));
66
67    // Store the shape we sample from in a resource:
68    let shape = Cuboid::from_length(2.9);
69    commands.insert_resource(SampledShape(shape));
70
71    // The sampled shape shown transparently:
72    commands.spawn((
73        Mesh3d(meshes.add(shape)),
74        MeshMaterial3d(materials.add(StandardMaterial {
75            base_color: Color::srgba(0.2, 0.1, 0.6, 0.3),
76            alpha_mode: AlphaMode::Blend,
77            cull_mode: None,
78            ..default()
79        })),
80    ));
81
82    // A light:
83    commands.spawn((
84        PointLight {
85            shadows_enabled: true,
86            ..default()
87        },
88        Transform::from_xyz(4.0, 8.0, 4.0),
89    ));
90
91    // A camera:
92    commands.spawn((
93        Camera3d::default(),
94        Transform::from_xyz(-2.0, 3.0, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
95    ));
96
97    // Store the mesh and material for sample points in resources:
98    commands.insert_resource(PointMesh(
99        meshes.add(
100            Sphere::new(0.03)
101                .mesh()
102                .kind(SphereKind::Ico { subdivisions: 3 }),
103        ),
104    ));
105    commands.insert_resource(PointMaterial(materials.add(StandardMaterial {
106        base_color: Color::srgb(1.0, 0.8, 0.8),
107        metallic: 0.8,
108        ..default()
109    })));
110
111    // Instructions for the example:
112    commands.spawn((
113        Text::new(
114            "Controls:\n\
115            M: Toggle between sampling boundary and interior.\n\
116            R: Restart (erase all samples).\n\
117            S: Add one random sample.\n\
118            D: Add 100 random samples.\n\
119            Rotate camera by holding left mouse and panning left/right.",
120        ),
121        Node {
122            position_type: PositionType::Absolute,
123            top: Val::Px(12.0),
124            left: Val::Px(12.0),
125            ..default()
126        },
127    ));
128
129    // The mode starts with interior points.
130    commands.insert_resource(Mode::Interior);
131
132    // Starting mouse-pressed state is false.
133    commands.insert_resource(MousePressed(false));
134}
Source

pub const fn rgb(red: f32, green: f32, blue: f32) -> Color

👎Deprecated: Use Color::srgb instead

Creates a new Color object storing a Srgba color with an alpha of 1.0.

Source

pub const fn srgb(red: f32, green: f32, blue: f32) -> Color

Creates a new Color object storing a Srgba color with an alpha of 1.0.

Examples found in repository?
examples/dev_tools/fps_overlay.rs (line 12)
12    const RED: Color = Color::srgb(1.0, 0.0, 0.0);
13    const GREEN: Color = Color::srgb(0.0, 1.0, 0.0);
More examples
Hide additional examples
examples/games/game_menu.rs (line 7)
7const TEXT_COLOR: Color = Color::srgb(0.9, 0.9, 0.9);
8
9// Enum that will be used as a global state for the game
10#[derive(Clone, Copy, Default, Eq, PartialEq, Debug, Hash, States)]
11enum GameState {
12    #[default]
13    Splash,
14    Menu,
15    Game,
16}
17
18// One of the two settings that can be set through the menu. It will be a resource in the app
19#[derive(Resource, Debug, Component, PartialEq, Eq, Clone, Copy)]
20enum DisplayQuality {
21    Low,
22    Medium,
23    High,
24}
25
26// One of the two settings that can be set through the menu. It will be a resource in the app
27#[derive(Resource, Debug, Component, PartialEq, Eq, Clone, Copy)]
28struct Volume(u32);
29
30fn main() {
31    App::new()
32        .add_plugins(DefaultPlugins)
33        // Insert as resource the initial value for the settings resources
34        .insert_resource(DisplayQuality::Medium)
35        .insert_resource(Volume(7))
36        // Declare the game state, whose starting value is determined by the `Default` trait
37        .init_state::<GameState>()
38        .add_systems(Startup, setup)
39        // Adds the plugins for each state
40        .add_plugins((splash::splash_plugin, menu::menu_plugin, game::game_plugin))
41        .run();
42}
43
44fn setup(mut commands: Commands) {
45    commands.spawn(Camera2d);
46}
47
48mod splash {
49    use bevy::prelude::*;
50
51    use super::{despawn_screen, GameState};
52
53    // This plugin will display a splash screen with Bevy logo for 1 second before switching to the menu
54    pub fn splash_plugin(app: &mut App) {
55        // As this plugin is managing the splash screen, it will focus on the state `GameState::Splash`
56        app
57            // When entering the state, spawn everything needed for this screen
58            .add_systems(OnEnter(GameState::Splash), splash_setup)
59            // While in this state, run the `countdown` system
60            .add_systems(Update, countdown.run_if(in_state(GameState::Splash)))
61            // When exiting the state, despawn everything that was spawned for this screen
62            .add_systems(OnExit(GameState::Splash), despawn_screen::<OnSplashScreen>);
63    }
64
65    // Tag component used to tag entities added on the splash screen
66    #[derive(Component)]
67    struct OnSplashScreen;
68
69    // Newtype to use a `Timer` for this screen as a resource
70    #[derive(Resource, Deref, DerefMut)]
71    struct SplashTimer(Timer);
72
73    fn splash_setup(mut commands: Commands, asset_server: Res<AssetServer>) {
74        let icon = asset_server.load("branding/icon.png");
75        // Display the logo
76        commands
77            .spawn((
78                Node {
79                    align_items: AlignItems::Center,
80                    justify_content: JustifyContent::Center,
81                    width: Val::Percent(100.0),
82                    height: Val::Percent(100.0),
83                    ..default()
84                },
85                OnSplashScreen,
86            ))
87            .with_children(|parent| {
88                parent.spawn((
89                    ImageNode::new(icon),
90                    Node {
91                        // This will set the logo to be 200px wide, and auto adjust its height
92                        width: Val::Px(200.0),
93                        ..default()
94                    },
95                ));
96            });
97        // Insert the timer as a resource
98        commands.insert_resource(SplashTimer(Timer::from_seconds(1.0, TimerMode::Once)));
99    }
100
101    // Tick the timer, and change state when finished
102    fn countdown(
103        mut game_state: ResMut<NextState<GameState>>,
104        time: Res<Time>,
105        mut timer: ResMut<SplashTimer>,
106    ) {
107        if timer.tick(time.delta()).finished() {
108            game_state.set(GameState::Menu);
109        }
110    }
111}
112
113mod game {
114    use bevy::{
115        color::palettes::basic::{BLUE, LIME},
116        prelude::*,
117    };
118
119    use super::{despawn_screen, DisplayQuality, GameState, Volume, TEXT_COLOR};
120
121    // This plugin will contain the game. In this case, it's just be a screen that will
122    // display the current settings for 5 seconds before returning to the menu
123    pub fn game_plugin(app: &mut App) {
124        app.add_systems(OnEnter(GameState::Game), game_setup)
125            .add_systems(Update, game.run_if(in_state(GameState::Game)))
126            .add_systems(OnExit(GameState::Game), despawn_screen::<OnGameScreen>);
127    }
128
129    // Tag component used to tag entities added on the game screen
130    #[derive(Component)]
131    struct OnGameScreen;
132
133    #[derive(Resource, Deref, DerefMut)]
134    struct GameTimer(Timer);
135
136    fn game_setup(
137        mut commands: Commands,
138        display_quality: Res<DisplayQuality>,
139        volume: Res<Volume>,
140    ) {
141        commands
142            .spawn((
143                Node {
144                    width: Val::Percent(100.0),
145                    height: Val::Percent(100.0),
146                    // center children
147                    align_items: AlignItems::Center,
148                    justify_content: JustifyContent::Center,
149                    ..default()
150                },
151                OnGameScreen,
152            ))
153            .with_children(|parent| {
154                // First create a `Node` for centering what we want to display
155                parent
156                    .spawn((
157                        Node {
158                            // This will display its children in a column, from top to bottom
159                            flex_direction: FlexDirection::Column,
160                            // `align_items` will align children on the cross axis. Here the main axis is
161                            // vertical (column), so the cross axis is horizontal. This will center the
162                            // children
163                            align_items: AlignItems::Center,
164                            ..default()
165                        },
166                        BackgroundColor(Color::BLACK),
167                    ))
168                    .with_children(|p| {
169                        p.spawn((
170                            Text::new("Will be back to the menu shortly..."),
171                            TextFont {
172                                font_size: 67.0,
173                                ..default()
174                            },
175                            TextColor(TEXT_COLOR),
176                            Node {
177                                margin: UiRect::all(Val::Px(50.0)),
178                                ..default()
179                            },
180                        ));
181                        p.spawn((
182                            Text::default(),
183                            Node {
184                                margin: UiRect::all(Val::Px(50.0)),
185                                ..default()
186                            },
187                        ))
188                        .with_children(|p| {
189                            p.spawn((
190                                TextSpan(format!("quality: {:?}", *display_quality)),
191                                TextFont {
192                                    font_size: 50.0,
193                                    ..default()
194                                },
195                                TextColor(BLUE.into()),
196                            ));
197                            p.spawn((
198                                TextSpan::new(" - "),
199                                TextFont {
200                                    font_size: 50.0,
201                                    ..default()
202                                },
203                                TextColor(TEXT_COLOR),
204                            ));
205                            p.spawn((
206                                TextSpan(format!("volume: {:?}", *volume)),
207                                TextFont {
208                                    font_size: 50.0,
209                                    ..default()
210                                },
211                                TextColor(LIME.into()),
212                            ));
213                        });
214                    });
215            });
216        // Spawn a 5 seconds timer to trigger going back to the menu
217        commands.insert_resource(GameTimer(Timer::from_seconds(5.0, TimerMode::Once)));
218    }
219
220    // Tick the timer, and change state when finished
221    fn game(
222        time: Res<Time>,
223        mut game_state: ResMut<NextState<GameState>>,
224        mut timer: ResMut<GameTimer>,
225    ) {
226        if timer.tick(time.delta()).finished() {
227            game_state.set(GameState::Menu);
228        }
229    }
230}
231
232mod menu {
233    use bevy::{app::AppExit, color::palettes::css::CRIMSON, prelude::*};
234
235    use super::{despawn_screen, DisplayQuality, GameState, Volume, TEXT_COLOR};
236
237    // This plugin manages the menu, with 5 different screens:
238    // - a main menu with "New Game", "Settings", "Quit"
239    // - a settings menu with two submenus and a back button
240    // - two settings screen with a setting that can be set and a back button
241    pub fn menu_plugin(app: &mut App) {
242        app
243            // At start, the menu is not enabled. This will be changed in `menu_setup` when
244            // entering the `GameState::Menu` state.
245            // Current screen in the menu is handled by an independent state from `GameState`
246            .init_state::<MenuState>()
247            .add_systems(OnEnter(GameState::Menu), menu_setup)
248            // Systems to handle the main menu screen
249            .add_systems(OnEnter(MenuState::Main), main_menu_setup)
250            .add_systems(OnExit(MenuState::Main), despawn_screen::<OnMainMenuScreen>)
251            // Systems to handle the settings menu screen
252            .add_systems(OnEnter(MenuState::Settings), settings_menu_setup)
253            .add_systems(
254                OnExit(MenuState::Settings),
255                despawn_screen::<OnSettingsMenuScreen>,
256            )
257            // Systems to handle the display settings screen
258            .add_systems(
259                OnEnter(MenuState::SettingsDisplay),
260                display_settings_menu_setup,
261            )
262            .add_systems(
263                Update,
264                (setting_button::<DisplayQuality>.run_if(in_state(MenuState::SettingsDisplay)),),
265            )
266            .add_systems(
267                OnExit(MenuState::SettingsDisplay),
268                despawn_screen::<OnDisplaySettingsMenuScreen>,
269            )
270            // Systems to handle the sound settings screen
271            .add_systems(OnEnter(MenuState::SettingsSound), sound_settings_menu_setup)
272            .add_systems(
273                Update,
274                setting_button::<Volume>.run_if(in_state(MenuState::SettingsSound)),
275            )
276            .add_systems(
277                OnExit(MenuState::SettingsSound),
278                despawn_screen::<OnSoundSettingsMenuScreen>,
279            )
280            // Common systems to all screens that handles buttons behavior
281            .add_systems(
282                Update,
283                (menu_action, button_system).run_if(in_state(GameState::Menu)),
284            );
285    }
286
287    // State used for the current menu screen
288    #[derive(Clone, Copy, Default, Eq, PartialEq, Debug, Hash, States)]
289    enum MenuState {
290        Main,
291        Settings,
292        SettingsDisplay,
293        SettingsSound,
294        #[default]
295        Disabled,
296    }
297
298    // Tag component used to tag entities added on the main menu screen
299    #[derive(Component)]
300    struct OnMainMenuScreen;
301
302    // Tag component used to tag entities added on the settings menu screen
303    #[derive(Component)]
304    struct OnSettingsMenuScreen;
305
306    // Tag component used to tag entities added on the display settings menu screen
307    #[derive(Component)]
308    struct OnDisplaySettingsMenuScreen;
309
310    // Tag component used to tag entities added on the sound settings menu screen
311    #[derive(Component)]
312    struct OnSoundSettingsMenuScreen;
313
314    const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15);
315    const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25);
316    const HOVERED_PRESSED_BUTTON: Color = Color::srgb(0.25, 0.65, 0.25);
317    const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35);
examples/games/stepping.rs (line 88)
88const FONT_COLOR: Color = Color::srgb(0.2, 0.2, 0.2);
examples/math/sampling_primitives.rs (line 64)
64const SKY_COLOR: Color = Color::srgb(0.02, 0.06, 0.15);
65
66const SMALL_3D: f32 = 0.5;
67const BIG_3D: f32 = 1.0;
68
69// primitives
70
71const CUBOID: Cuboid = Cuboid {
72    half_size: Vec3::new(SMALL_3D, BIG_3D, SMALL_3D),
73};
74
75const SPHERE: Sphere = Sphere {
76    radius: 1.5 * SMALL_3D,
77};
78
79const TRIANGLE_3D: Triangle3d = Triangle3d {
80    vertices: [
81        Vec3::new(BIG_3D, -BIG_3D * 0.5, 0.0),
82        Vec3::new(0.0, BIG_3D, 0.0),
83        Vec3::new(-BIG_3D, -BIG_3D * 0.5, 0.0),
84    ],
85};
86
87const CAPSULE_3D: Capsule3d = Capsule3d {
88    radius: SMALL_3D,
89    half_length: SMALL_3D,
90};
91
92const CYLINDER: Cylinder = Cylinder {
93    radius: SMALL_3D,
94    half_height: SMALL_3D,
95};
96
97const TETRAHEDRON: Tetrahedron = Tetrahedron {
98    vertices: [
99        Vec3::new(-BIG_3D, -BIG_3D * 0.67, BIG_3D * 0.5),
100        Vec3::new(BIG_3D, -BIG_3D * 0.67, BIG_3D * 0.5),
101        Vec3::new(0.0, -BIG_3D * 0.67, -BIG_3D * 1.17),
102        Vec3::new(0.0, BIG_3D, 0.0),
103    ],
104};
105
106// Components, Resources
107
108/// Resource for the random sampling mode, telling whether to sample the interior or the boundary.
109#[derive(Resource)]
110enum SamplingMode {
111    Interior,
112    Boundary,
113}
114
115/// Resource for storing whether points should spawn by themselves
116#[derive(Resource)]
117enum SpawningMode {
118    Manual,
119    Automatic,
120}
121
122/// Resource for tracking how many points should be spawned
123#[derive(Resource)]
124struct SpawnQueue(usize);
125
126#[derive(Resource)]
127struct PointCounter(usize);
128
129/// Resource storing the shapes being sampled and their translations.
130#[derive(Resource)]
131struct SampledShapes(Vec<(Shape, Vec3)>);
132
133impl SampledShapes {
134    fn new() -> Self {
135        let shapes = Shape::list_all_shapes();
136
137        let n_shapes = shapes.len();
138
139        let translations =
140            (0..n_shapes).map(|i| (i as f32 - n_shapes as f32 / 2.0) * DISTANCE_BETWEEN_SHAPES);
141
142        SampledShapes(shapes.into_iter().zip(translations).collect())
143    }
144}
145
146/// Enum listing the shapes that can be sampled
147#[derive(Clone, Copy)]
148enum Shape {
149    Cuboid,
150    Sphere,
151    Capsule,
152    Cylinder,
153    Tetrahedron,
154    Triangle,
155}
156struct ShapeMeshBuilder {
157    shape: Shape,
158}
159
160impl Shape {
161    /// Return a vector containing all implemented shapes
162    fn list_all_shapes() -> Vec<Shape> {
163        vec![
164            Shape::Cuboid,
165            Shape::Sphere,
166            Shape::Capsule,
167            Shape::Cylinder,
168            Shape::Tetrahedron,
169            Shape::Triangle,
170        ]
171    }
172}
173
174impl ShapeSample for Shape {
175    type Output = Vec3;
176    fn sample_interior<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec3 {
177        match self {
178            Shape::Cuboid => CUBOID.sample_interior(rng),
179            Shape::Sphere => SPHERE.sample_interior(rng),
180            Shape::Capsule => CAPSULE_3D.sample_interior(rng),
181            Shape::Cylinder => CYLINDER.sample_interior(rng),
182            Shape::Tetrahedron => TETRAHEDRON.sample_interior(rng),
183            Shape::Triangle => TRIANGLE_3D.sample_interior(rng),
184        }
185    }
186
187    fn sample_boundary<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::Output {
188        match self {
189            Shape::Cuboid => CUBOID.sample_boundary(rng),
190            Shape::Sphere => SPHERE.sample_boundary(rng),
191            Shape::Capsule => CAPSULE_3D.sample_boundary(rng),
192            Shape::Cylinder => CYLINDER.sample_boundary(rng),
193            Shape::Tetrahedron => TETRAHEDRON.sample_boundary(rng),
194            Shape::Triangle => TRIANGLE_3D.sample_boundary(rng),
195        }
196    }
197}
198
199impl Meshable for Shape {
200    type Output = ShapeMeshBuilder;
201
202    fn mesh(&self) -> Self::Output {
203        ShapeMeshBuilder { shape: *self }
204    }
205}
206
207impl MeshBuilder for ShapeMeshBuilder {
208    fn build(&self) -> Mesh {
209        match self.shape {
210            Shape::Cuboid => CUBOID.mesh().into(),
211            Shape::Sphere => SPHERE.mesh().into(),
212            Shape::Capsule => CAPSULE_3D.mesh().into(),
213            Shape::Cylinder => CYLINDER.mesh().into(),
214            Shape::Tetrahedron => TETRAHEDRON.mesh().into(),
215            Shape::Triangle => TRIANGLE_3D.mesh().into(),
216        }
217    }
218}
219
220/// The source of randomness used by this example.
221#[derive(Resource)]
222struct RandomSource(ChaCha8Rng);
223
224/// A container for the handle storing the mesh used to display sampled points as spheres.
225#[derive(Resource)]
226struct PointMesh(Handle<Mesh>);
227
228/// A container for the handle storing the material used to display sampled points.
229#[derive(Resource)]
230struct PointMaterial {
231    interior: Handle<StandardMaterial>,
232    boundary: Handle<StandardMaterial>,
233}
234
235/// Marker component for sampled points.
236#[derive(Component)]
237struct SamplePoint;
238
239/// Component for animating the spawn animation of lights.
240#[derive(Component)]
241struct SpawningPoint {
242    progress: f32,
243}
244
245/// Marker component for lights which should change intensity.
246#[derive(Component)]
247struct DespawningPoint {
248    progress: f32,
249}
250
251/// Marker component for lights which should change intensity.
252#[derive(Component)]
253struct FireflyLights;
254
255/// The pressed state of the mouse, used for camera motion.
256#[derive(Resource)]
257struct MousePressed(bool);
258
259/// Camera movement component.
260#[derive(Component)]
261struct CameraRig {
262    /// Rotation around the vertical axis of the camera (radians).
263    /// Positive changes makes the camera look more from the right.
264    pub yaw: f32,
265    /// Rotation around the horizontal axis of the camera (radians) (-pi/2; pi/2).
266    /// Positive looks down from above.
267    pub pitch: f32,
268    /// Distance from the center, smaller distance causes more zoom.
269    pub distance: f32,
270    /// Location in 3D space at which the camera is looking and around which it is orbiting.
271    pub target: Vec3,
272}
273
274fn setup(
275    mut commands: Commands,
276    mut meshes: ResMut<Assets<Mesh>>,
277    mut materials: ResMut<Assets<StandardMaterial>>,
278    shapes: Res<SampledShapes>,
279) {
280    // Use seeded rng and store it in a resource; this makes the random output reproducible.
281    let seeded_rng = ChaCha8Rng::seed_from_u64(4); // Chosen by a fair die roll, guaranteed to be random.
282    commands.insert_resource(RandomSource(seeded_rng));
283
284    // Make a plane for establishing space.
285    commands.spawn((
286        Mesh3d(meshes.add(Plane3d::default().mesh().size(20.0, 20.0))),
287        MeshMaterial3d(materials.add(StandardMaterial {
288            base_color: Color::srgb(0.3, 0.5, 0.3),
289            perceptual_roughness: 0.95,
290            metallic: 0.0,
291            ..default()
292        })),
293        Transform::from_xyz(0.0, -2.5, 0.0),
294    ));
295
296    let shape_material = materials.add(StandardMaterial {
297        base_color: Color::srgba(0.2, 0.1, 0.6, 0.3),
298        reflectance: 0.0,
299        alpha_mode: AlphaMode::Blend,
300        cull_mode: None,
301        ..default()
302    });
303
304    // Spawn shapes to be sampled
305    for (shape, translation) in shapes.0.iter() {
306        // The sampled shape shown transparently:
307        commands.spawn((
308            Mesh3d(meshes.add(shape.mesh())),
309            MeshMaterial3d(shape_material.clone()),
310            Transform::from_translation(*translation),
311        ));
312
313        // Lights which work as the bulk lighting of the fireflies:
314        commands.spawn((
315            PointLight {
316                range: 4.0,
317                radius: 0.6,
318                intensity: 1.0,
319                shadows_enabled: false,
320                color: Color::LinearRgba(INSIDE_POINT_COLOR),
321                ..default()
322            },
323            Transform::from_translation(*translation),
324            FireflyLights,
325        ));
326    }
327
328    // Global light:
329    commands.spawn((
330        PointLight {
331            color: SKY_COLOR,
332            intensity: 2_000.0,
333            shadows_enabled: false,
334            ..default()
335        },
336        Transform::from_xyz(4.0, 8.0, 4.0),
337    ));
338
339    // A camera:
340    commands.spawn((
341        Camera3d::default(),
342        Camera {
343            hdr: true, // HDR is required for bloom
344            clear_color: ClearColorConfig::Custom(SKY_COLOR),
345            ..default()
346        },
347        Tonemapping::TonyMcMapface,
348        Transform::from_xyz(-2.0, 3.0, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
349        Bloom::NATURAL,
350        CameraRig {
351            yaw: 0.56,
352            pitch: 0.45,
353            distance: 8.0,
354            target: Vec3::ZERO,
355        },
356    ));
357
358    // Store the mesh and material for sample points in resources:
359    commands.insert_resource(PointMesh(
360        meshes.add(Sphere::new(0.03).mesh().ico(1).unwrap()),
361    ));
362    commands.insert_resource(PointMaterial {
363        interior: materials.add(StandardMaterial {
364            base_color: Color::BLACK,
365            reflectance: 0.05,
366            emissive: 2.5 * INSIDE_POINT_COLOR,
367            ..default()
368        }),
369        boundary: materials.add(StandardMaterial {
370            base_color: Color::BLACK,
371            reflectance: 0.05,
372            emissive: 1.5 * BOUNDARY_POINT_COLOR,
373            ..default()
374        }),
375    });
376
377    // Instructions for the example:
378    commands.spawn((
379        Text::new(
380            "Controls:\n\
381            M: Toggle between sampling boundary and interior.\n\
382            A: Toggle automatic spawning & despawning of points.\n\
383            R: Restart (erase all samples).\n\
384            S: Add one random sample.\n\
385            D: Add 100 random samples.\n\
386            Rotate camera by holding left mouse and panning.\n\
387            Zoom camera by scrolling via mouse or +/-.\n\
388            Move camera by L/R arrow keys.\n\
389            Tab: Toggle this text",
390        ),
391        Node {
392            position_type: PositionType::Absolute,
393            top: Val::Px(12.0),
394            left: Val::Px(12.0),
395            ..default()
396        },
397    ));
398
399    // No points are scheduled to spawn initially.
400    commands.insert_resource(SpawnQueue(0));
401
402    // No points have been spawned initially.
403    commands.insert_resource(PointCounter(0));
404
405    // The mode starts with interior points.
406    commands.insert_resource(SamplingMode::Interior);
407
408    // Points spawn automatically by default.
409    commands.insert_resource(SpawningMode::Automatic);
410
411    // Starting mouse-pressed state is false.
412    commands.insert_resource(MousePressed(false));
413}
examples/ui/display_and_visibility.rs (line 10)
10const HIDDEN_COLOR: Color = Color::srgb(1.0, 0.7, 0.7);
11
12fn main() {
13    App::new()
14        .add_plugins(DefaultPlugins)
15        // Only run the app when there is user input. This will significantly reduce CPU/GPU use.
16        .insert_resource(WinitSettings::desktop_app())
17        .add_systems(Startup, setup)
18        .add_systems(
19            Update,
20            (
21                buttons_handler::<Display>,
22                buttons_handler::<Visibility>,
23                text_hover,
24            ),
25        )
26        .run();
27}
28
29#[derive(Component)]
30struct Target<T> {
31    id: Entity,
32    phantom: std::marker::PhantomData<T>,
33}
34
35impl<T> Target<T> {
36    fn new(id: Entity) -> Self {
37        Self {
38            id,
39            phantom: std::marker::PhantomData,
40        }
41    }
42}
43
44trait TargetUpdate {
45    type TargetComponent: Component;
46    const NAME: &'static str;
47    fn update_target(&self, target: &mut Self::TargetComponent) -> String;
48}
49
50impl TargetUpdate for Target<Display> {
51    type TargetComponent = Node;
52    const NAME: &'static str = "Display";
53    fn update_target(&self, node: &mut Self::TargetComponent) -> String {
54        node.display = match node.display {
55            Display::Flex => Display::None,
56            Display::None => Display::Flex,
57            Display::Block | Display::Grid => unreachable!(),
58        };
59        format!("{}::{:?} ", Self::NAME, node.display)
60    }
61}
62
63impl TargetUpdate for Target<Visibility> {
64    type TargetComponent = Visibility;
65    const NAME: &'static str = "Visibility";
66    fn update_target(&self, visibility: &mut Self::TargetComponent) -> String {
67        *visibility = match *visibility {
68            Visibility::Inherited => Visibility::Visible,
69            Visibility::Visible => Visibility::Hidden,
70            Visibility::Hidden => Visibility::Inherited,
71        };
72        format!("{}::{visibility:?}", Self::NAME)
73    }
74}
75
76fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
77    let palette: [Color; 4] = PALETTE.map(|hex| Srgba::hex(hex).unwrap().into());
78
79    let text_font = TextFont {
80        font: asset_server.load("fonts/FiraSans-Bold.ttf"),
81        ..default()
82    };
83
84    commands.spawn(Camera2d);
85    commands
86        .spawn((
87            Node {
88                width: Val::Percent(100.),
89                height: Val::Percent(100.),
90                flex_direction: FlexDirection::Column,
91                align_items: AlignItems::Center,
92                justify_content: JustifyContent::SpaceEvenly,
93                ..Default::default()
94            },
95            BackgroundColor(Color::BLACK),
96        ))
97        .with_children(|parent| {
98            parent.spawn((
99                Text::new("Use the panel on the right to change the Display and Visibility properties for the respective nodes of the panel on the left"),
100                text_font.clone(),
101                TextLayout::new_with_justify(JustifyText::Center),
102                Node {
103                    margin: UiRect::bottom(Val::Px(10.)),
104                    ..Default::default()
105                },
106            ));
107
108            parent
109                .spawn(Node {
110                    width: Val::Percent(100.),
111                    ..default()
112                })
113                .with_children(|parent| {
114                    let mut target_ids = vec![];
115                    parent
116                        .spawn(Node {
117                            width: Val::Percent(50.),
118                            height: Val::Px(520.),
119                            justify_content: JustifyContent::Center,
120                            ..default()
121                        })
122                        .with_children(|parent| {
123                            target_ids = spawn_left_panel(parent, &palette);
124                        });
125
126                    parent
127                        .spawn(Node {
128                            width: Val::Percent(50.),
129                            justify_content: JustifyContent::Center,
130                            ..default()
131                        })
132                        .with_children(|parent| {
133                            spawn_right_panel(parent, text_font, &palette, target_ids);
134                        });
135                });
136
137            parent
138                .spawn(Node {
139                    flex_direction: FlexDirection::Row,
140                    align_items: AlignItems::Start,
141                    justify_content: JustifyContent::Start,
142                    column_gap: Val::Px(10.),
143                    ..default()
144                })
145                .with_children(|builder| {
146                    let text_font = TextFont {
147                        font: asset_server.load("fonts/FiraSans-Bold.ttf"),
148                        ..default()
149                    };
150
151                    builder.spawn((
152                        Text::new("Display::None\nVisibility::Hidden\nVisibility::Inherited"),
153                        text_font.clone(),
154                        TextColor(HIDDEN_COLOR),
155                        TextLayout::new_with_justify(JustifyText::Center),
156                    ));
157                    builder.spawn((
158                        Text::new("-\n-\n-"),
159                        text_font.clone(),
160                        TextColor(DARK_GRAY.into()),
161                        TextLayout::new_with_justify(JustifyText::Center),
162                    ));
163                    builder.spawn((Text::new("The UI Node and its descendants will not be visible and will not be allotted any space in the UI layout.\nThe UI Node will not be visible but will still occupy space in the UI layout.\nThe UI node will inherit the visibility property of its parent. If it has no parent it will be visible."), text_font));
164                });
165        });
166}
167
168fn spawn_left_panel(builder: &mut ChildBuilder, palette: &[Color; 4]) -> Vec<Entity> {
169    let mut target_ids = vec![];
170    builder
171        .spawn((
172            Node {
173                padding: UiRect::all(Val::Px(10.)),
174                ..default()
175            },
176            BackgroundColor(Color::WHITE),
177        ))
178        .with_children(|parent| {
179            parent
180                .spawn((Node::default(), BackgroundColor(Color::BLACK)))
181                .with_children(|parent| {
182                    let id = parent
183                        .spawn((
184                            Node {
185                                align_items: AlignItems::FlexEnd,
186                                justify_content: JustifyContent::FlexEnd,
187                                ..default()
188                            },
189                            BackgroundColor(palette[0]),
190                            Outline {
191                                width: Val::Px(4.),
192                                color: DARK_CYAN.into(),
193                                offset: Val::Px(10.),
194                            },
195                        ))
196                        .with_children(|parent| {
197                            parent.spawn(Node {
198                                width: Val::Px(100.),
199                                height: Val::Px(500.),
200                                ..default()
201                            });
202
203                            let id = parent
204                                .spawn((
205                                    Node {
206                                        height: Val::Px(400.),
207                                        align_items: AlignItems::FlexEnd,
208                                        justify_content: JustifyContent::FlexEnd,
209                                        ..default()
210                                    },
211                                    BackgroundColor(palette[1]),
212                                ))
213                                .with_children(|parent| {
214                                    parent.spawn(Node {
215                                        width: Val::Px(100.),
216                                        height: Val::Px(400.),
217                                        ..default()
218                                    });
219
220                                    let id = parent
221                                        .spawn((
222                                            Node {
223                                                height: Val::Px(300.),
224                                                align_items: AlignItems::FlexEnd,
225                                                justify_content: JustifyContent::FlexEnd,
226                                                ..default()
227                                            },
228                                            BackgroundColor(palette[2]),
229                                        ))
230                                        .with_children(|parent| {
231                                            parent.spawn(Node {
232                                                width: Val::Px(100.),
233                                                height: Val::Px(300.),
234                                                ..default()
235                                            });
236
237                                            let id = parent
238                                                .spawn((
239                                                    Node {
240                                                        width: Val::Px(200.),
241                                                        height: Val::Px(200.),
242                                                        ..default()
243                                                    },
244                                                    BackgroundColor(palette[3]),
245                                                ))
246                                                .id();
247                                            target_ids.push(id);
248                                        })
249                                        .id();
250                                    target_ids.push(id);
251                                })
252                                .id();
253                            target_ids.push(id);
254                        })
255                        .id();
256                    target_ids.push(id);
257                });
258        });
259    target_ids
260}
261
262fn spawn_right_panel(
263    parent: &mut ChildBuilder,
264    text_font: TextFont,
265    palette: &[Color; 4],
266    mut target_ids: Vec<Entity>,
267) {
268    let spawn_buttons = |parent: &mut ChildBuilder, target_id| {
269        spawn_button::<Display>(parent, text_font.clone(), target_id);
270        spawn_button::<Visibility>(parent, text_font.clone(), target_id);
271    };
272    parent
273        .spawn((
274            Node {
275                padding: UiRect::all(Val::Px(10.)),
276                ..default()
277            },
278            BackgroundColor(Color::WHITE),
279        ))
280        .with_children(|parent| {
281            parent
282                .spawn((
283                    Node {
284                        width: Val::Px(500.),
285                        height: Val::Px(500.),
286                        flex_direction: FlexDirection::Column,
287                        align_items: AlignItems::FlexEnd,
288                        justify_content: JustifyContent::SpaceBetween,
289                        padding: UiRect {
290                            left: Val::Px(5.),
291                            top: Val::Px(5.),
292                            ..default()
293                        },
294                        ..default()
295                    },
296                    BackgroundColor(palette[0]),
297                    Outline {
298                        width: Val::Px(4.),
299                        color: DARK_CYAN.into(),
300                        offset: Val::Px(10.),
301                    },
302                ))
303                .with_children(|parent| {
304                    spawn_buttons(parent, target_ids.pop().unwrap());
305
306                    parent
307                        .spawn((
308                            Node {
309                                width: Val::Px(400.),
310                                height: Val::Px(400.),
311                                flex_direction: FlexDirection::Column,
312                                align_items: AlignItems::FlexEnd,
313                                justify_content: JustifyContent::SpaceBetween,
314                                padding: UiRect {
315                                    left: Val::Px(5.),
316                                    top: Val::Px(5.),
317                                    ..default()
318                                },
319                                ..default()
320                            },
321                            BackgroundColor(palette[1]),
322                        ))
323                        .with_children(|parent| {
324                            spawn_buttons(parent, target_ids.pop().unwrap());
325
326                            parent
327                                .spawn((
328                                    Node {
329                                        width: Val::Px(300.),
330                                        height: Val::Px(300.),
331                                        flex_direction: FlexDirection::Column,
332                                        align_items: AlignItems::FlexEnd,
333                                        justify_content: JustifyContent::SpaceBetween,
334                                        padding: UiRect {
335                                            left: Val::Px(5.),
336                                            top: Val::Px(5.),
337                                            ..default()
338                                        },
339                                        ..default()
340                                    },
341                                    BackgroundColor(palette[2]),
342                                ))
343                                .with_children(|parent| {
344                                    spawn_buttons(parent, target_ids.pop().unwrap());
345
346                                    parent
347                                        .spawn((
348                                            Node {
349                                                width: Val::Px(200.),
350                                                height: Val::Px(200.),
351                                                align_items: AlignItems::FlexStart,
352                                                justify_content: JustifyContent::SpaceBetween,
353                                                flex_direction: FlexDirection::Column,
354                                                padding: UiRect {
355                                                    left: Val::Px(5.),
356                                                    top: Val::Px(5.),
357                                                    ..default()
358                                                },
359                                                ..default()
360                                            },
361                                            BackgroundColor(palette[3]),
362                                        ))
363                                        .with_children(|parent| {
364                                            spawn_buttons(parent, target_ids.pop().unwrap());
365
366                                            parent.spawn(Node {
367                                                width: Val::Px(100.),
368                                                height: Val::Px(100.),
369                                                ..default()
370                                            });
371                                        });
372                                });
373                        });
374                });
375        });
376}
377
378fn spawn_button<T>(parent: &mut ChildBuilder, text_font: TextFont, target: Entity)
379where
380    T: Default + std::fmt::Debug + Send + Sync + 'static,
381    Target<T>: TargetUpdate,
382{
383    parent
384        .spawn((
385            Button,
386            Node {
387                align_self: AlignSelf::FlexStart,
388                padding: UiRect::axes(Val::Px(5.), Val::Px(1.)),
389                ..default()
390            },
391            BackgroundColor(Color::BLACK.with_alpha(0.5)),
392            Target::<T>::new(target),
393        ))
394        .with_children(|builder| {
395            builder.spawn((
396                Text(format!("{}::{:?}", Target::<T>::NAME, T::default())),
397                text_font,
398                TextLayout::new_with_justify(JustifyText::Center),
399            ));
400        });
401}
402
403fn buttons_handler<T>(
404    mut left_panel_query: Query<&mut <Target<T> as TargetUpdate>::TargetComponent>,
405    mut visibility_button_query: Query<(&Target<T>, &Interaction, &Children), Changed<Interaction>>,
406    mut text_query: Query<(&mut Text, &mut TextColor)>,
407) where
408    T: Send + Sync,
409    Target<T>: TargetUpdate + Component,
410{
411    for (target, interaction, children) in visibility_button_query.iter_mut() {
412        if matches!(interaction, Interaction::Pressed) {
413            let mut target_value = left_panel_query.get_mut(target.id).unwrap();
414            for &child in children {
415                if let Ok((mut text, mut text_color)) = text_query.get_mut(child) {
416                    **text = target.update_target(target_value.as_mut());
417                    text_color.0 = if text.contains("None") || text.contains("Hidden") {
418                        Color::srgb(1.0, 0.7, 0.7)
419                    } else {
420                        Color::WHITE
421                    };
422                }
423            }
424        }
425    }
426}
examples/games/breakout.rs (line 45)
45const BACKGROUND_COLOR: Color = Color::srgb(0.9, 0.9, 0.9);
46const PADDLE_COLOR: Color = Color::srgb(0.3, 0.3, 0.7);
47const BALL_COLOR: Color = Color::srgb(1.0, 0.5, 0.5);
48const BRICK_COLOR: Color = Color::srgb(0.5, 0.5, 1.0);
49const WALL_COLOR: Color = Color::srgb(0.8, 0.8, 0.8);
50const TEXT_COLOR: Color = Color::srgb(0.5, 0.5, 1.0);
51const SCORE_COLOR: Color = Color::srgb(1.0, 0.5, 0.5);
Source

pub fn rgb_from_array(_: [f32; 3]) -> Color

👎Deprecated: Use Color::srgb_from_array instead

Reads an array of floats to creates a new Color object storing a Srgba color with an alpha of 1.0.

Source

pub fn srgb_from_array(array: [f32; 3]) -> Color

Reads an array of floats to creates a new Color object storing a Srgba color with an alpha of 1.0.

Source

pub fn rgba_u8(red: u8, green: u8, blue: u8, alpha: u8) -> Color

👎Deprecated: Use Color::srgba_u8 instead

Creates a new Color object storing a Srgba color from u8 values.

A value of 0 is interpreted as 0.0, and a value of 255 is interpreted as 1.0.

Source

pub fn srgba_u8(red: u8, green: u8, blue: u8, alpha: u8) -> Color

Creates a new Color object storing a Srgba color from u8 values.

A value of 0 is interpreted as 0.0, and a value of 255 is interpreted as 1.0.

Examples found in repository?
examples/3d/anti_aliasing.rs (line 319)
252fn setup(
253    mut commands: Commands,
254    mut meshes: ResMut<Assets<Mesh>>,
255    mut materials: ResMut<Assets<StandardMaterial>>,
256    mut images: ResMut<Assets<Image>>,
257    asset_server: Res<AssetServer>,
258) {
259    // Plane
260    commands.spawn((
261        Mesh3d(meshes.add(Plane3d::default().mesh().size(50.0, 50.0))),
262        MeshMaterial3d(materials.add(Color::srgb(0.1, 0.2, 0.1))),
263    ));
264
265    let cube_material = materials.add(StandardMaterial {
266        base_color_texture: Some(images.add(uv_debug_texture())),
267        ..default()
268    });
269
270    // Cubes
271    for i in 0..5 {
272        commands.spawn((
273            Mesh3d(meshes.add(Cuboid::new(0.25, 0.25, 0.25))),
274            MeshMaterial3d(cube_material.clone()),
275            Transform::from_xyz(i as f32 * 0.25 - 1.0, 0.125, -i as f32 * 0.5),
276        ));
277    }
278
279    // Flight Helmet
280    commands.spawn(SceneRoot(asset_server.load(
281        GltfAssetLabel::Scene(0).from_asset("models/FlightHelmet/FlightHelmet.gltf"),
282    )));
283
284    // Light
285    commands.spawn((
286        DirectionalLight {
287            illuminance: light_consts::lux::FULL_DAYLIGHT,
288            shadows_enabled: true,
289            ..default()
290        },
291        Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, PI * -0.15, PI * -0.15)),
292        CascadeShadowConfigBuilder {
293            maximum_distance: 3.0,
294            first_cascade_far_bound: 0.9,
295            ..default()
296        }
297        .build(),
298    ));
299
300    // Camera
301    commands.spawn((
302        Camera3d::default(),
303        Camera {
304            hdr: true,
305            ..default()
306        },
307        Transform::from_xyz(0.7, 0.7, 1.0).looking_at(Vec3::new(0.0, 0.3, 0.0), Vec3::Y),
308        ContrastAdaptiveSharpening {
309            enabled: false,
310            ..default()
311        },
312        EnvironmentMapLight {
313            diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"),
314            specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
315            intensity: 150.0,
316            ..default()
317        },
318        DistanceFog {
319            color: Color::srgba_u8(43, 44, 47, 255),
320            falloff: FogFalloff::Linear {
321                start: 1.0,
322                end: 4.0,
323            },
324            ..default()
325        },
326    ));
327
328    // example instructions
329    commands.spawn((
330        Text::default(),
331        Node {
332            position_type: PositionType::Absolute,
333            top: Val::Px(12.0),
334            left: Val::Px(12.0),
335            ..default()
336        },
337    ));
338}
Source

pub fn rgb_u8(red: u8, green: u8, blue: u8) -> Color

👎Deprecated: Use Color::srgb_u8 instead

Creates a new Color object storing a Srgba color from u8 values with an alpha of 1.0.

A value of 0 is interpreted as 0.0, and a value of 255 is interpreted as 1.0.

Source

pub fn srgb_u8(red: u8, green: u8, blue: u8) -> Color

Creates a new Color object storing a Srgba color from u8 values with an alpha of 1.0.

A value of 0 is interpreted as 0.0, and a value of 255 is interpreted as 1.0.

Examples found in repository?
examples/picking/simple_picking.rs (line 75)
65fn on_click_spawn_cube(
66    _click: Trigger<Pointer<Click>>,
67    mut commands: Commands,
68    mut meshes: ResMut<Assets<Mesh>>,
69    mut materials: ResMut<Assets<StandardMaterial>>,
70    mut num: Local<usize>,
71) {
72    commands
73        .spawn((
74            Mesh3d(meshes.add(Cuboid::new(0.5, 0.5, 0.5))),
75            MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))),
76            Transform::from_xyz(0.0, 0.25 + 0.55 * *num as f32, 0.0),
77        ))
78        // With the MeshPickingPlugin added, you can add pointer event observers to meshes:
79        .observe(on_drag_rotate);
80    *num += 1;
81}
More examples
Hide additional examples
examples/3d/color_grading.rs (line 344)
334fn add_camera(commands: &mut Commands, asset_server: &AssetServer, color_grading: ColorGrading) {
335    commands.spawn((
336        Camera3d::default(),
337        Camera {
338            hdr: true,
339            ..default()
340        },
341        Transform::from_xyz(0.7, 0.7, 1.0).looking_at(Vec3::new(0.0, 0.3, 0.0), Vec3::Y),
342        color_grading,
343        DistanceFog {
344            color: Color::srgb_u8(43, 44, 47),
345            falloff: FogFalloff::Linear {
346                start: 1.0,
347                end: 8.0,
348            },
349            ..default()
350        },
351        EnvironmentMapLight {
352            diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"),
353            specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
354            intensity: 2000.0,
355            ..default()
356        },
357    ));
358}
examples/3d/motion_blur.rs (line 182)
174fn spawn_barriers(
175    meshes: &mut Assets<Mesh>,
176    materials: &mut Assets<StandardMaterial>,
177    commands: &mut Commands,
178) {
179    const N_CONES: usize = 100;
180    let capsule = meshes.add(Capsule3d::default());
181    let matl = materials.add(StandardMaterial {
182        base_color: Color::srgb_u8(255, 87, 51),
183        reflectance: 1.0,
184        ..default()
185    });
186    let mut spawn_with_offset = |offset: f32| {
187        for i in 0..N_CONES {
188            let pos = race_track_pos(
189                offset,
190                (i as f32) / (N_CONES as f32) * std::f32::consts::PI * 2.0,
191            );
192            commands.spawn((
193                Mesh3d(capsule.clone()),
194                MeshMaterial3d(matl.clone()),
195                Transform::from_xyz(pos.x, -0.65, pos.y).with_scale(Vec3::splat(0.07)),
196            ));
197        }
198    };
199    spawn_with_offset(0.04);
200    spawn_with_offset(-0.04);
201}
examples/3d/post_processing.rs (line 69)
60fn spawn_camera(commands: &mut Commands, asset_server: &AssetServer) {
61    commands.spawn((
62        Camera3d::default(),
63        Camera {
64            hdr: true,
65            ..default()
66        },
67        Transform::from_xyz(0.7, 0.7, 1.0).looking_at(Vec3::new(0.0, 0.3, 0.0), Vec3::Y),
68        DistanceFog {
69            color: Color::srgb_u8(43, 44, 47),
70            falloff: FogFalloff::Linear {
71                start: 1.0,
72                end: 8.0,
73            },
74            ..default()
75        },
76        EnvironmentMapLight {
77            diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"),
78            specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
79            intensity: 2000.0,
80            ..default()
81        },
82        // Include the `ChromaticAberration` component.
83        ChromaticAberration::default(),
84    ));
85}
examples/3d/3d_scene.rs (line 27)
13fn setup(
14    mut commands: Commands,
15    mut meshes: ResMut<Assets<Mesh>>,
16    mut materials: ResMut<Assets<StandardMaterial>>,
17) {
18    // circular base
19    commands.spawn((
20        Mesh3d(meshes.add(Circle::new(4.0))),
21        MeshMaterial3d(materials.add(Color::WHITE)),
22        Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
23    ));
24    // cube
25    commands.spawn((
26        Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
27        MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))),
28        Transform::from_xyz(0.0, 0.5, 0.0),
29    ));
30    // light
31    commands.spawn((
32        PointLight {
33            shadows_enabled: true,
34            ..default()
35        },
36        Transform::from_xyz(4.0, 8.0, 4.0),
37    ));
38    // camera
39    commands.spawn((
40        Camera3d::default(),
41        Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y),
42    ));
43}
examples/remote/server.rs (line 38)
23fn setup(
24    mut commands: Commands,
25    mut meshes: ResMut<Assets<Mesh>>,
26    mut materials: ResMut<Assets<StandardMaterial>>,
27) {
28    // circular base
29    commands.spawn((
30        Mesh3d(meshes.add(Circle::new(4.0))),
31        MeshMaterial3d(materials.add(Color::WHITE)),
32        Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
33    ));
34
35    // cube
36    commands.spawn((
37        Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
38        MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))),
39        Transform::from_xyz(0.0, 0.5, 0.0),
40        Cube(1.0),
41    ));
42
43    // light
44    commands.spawn((
45        PointLight {
46            shadows_enabled: true,
47            ..default()
48        },
49        Transform::from_xyz(4.0, 8.0, 4.0),
50    ));
51
52    // camera
53    commands.spawn((
54        Camera3d::default(),
55        Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y),
56    ));
57}
Source

pub const fn rbga_linear(red: f32, green: f32, blue: f32, alpha: f32) -> Color

👎Deprecated: Use Color::linear_rgba instead.

Creates a new Color object storing a LinearRgba color.

Source

pub const fn linear_rgba(red: f32, green: f32, blue: f32, alpha: f32) -> Color

Creates a new Color object storing a LinearRgba color.

Source

pub const fn rgb_linear(red: f32, green: f32, blue: f32) -> Color

👎Deprecated: Use Color::linear_rgb instead.

Creates a new Color object storing a LinearRgba color with an alpha of 1.0.

Source

pub const fn linear_rgb(red: f32, green: f32, blue: f32) -> Color

Creates a new Color object storing a LinearRgba color with an alpha of 1.0.

Examples found in repository?
examples/stress_tests/bevymark.rs (line 346)
327fn mouse_handler(
328    mut commands: Commands,
329    args: Res<Args>,
330    time: Res<Time>,
331    mouse_button_input: Res<ButtonInput<MouseButton>>,
332    window: Single<&Window>,
333    bird_resources: ResMut<BirdResources>,
334    mut counter: ResMut<BevyCounter>,
335    mut rng: Local<Option<ChaCha8Rng>>,
336    mut wave: Local<usize>,
337) {
338    if rng.is_none() {
339        // We're seeding the PRNG here to make this example deterministic for testing purposes.
340        // This isn't strictly required in practical use unless you need your app to be deterministic.
341        *rng = Some(ChaCha8Rng::seed_from_u64(42));
342    }
343    let rng = rng.as_mut().unwrap();
344
345    if mouse_button_input.just_released(MouseButton::Left) {
346        counter.color = Color::linear_rgb(rng.gen(), rng.gen(), rng.gen());
347    }
348
349    if mouse_button_input.pressed(MouseButton::Left) {
350        let spawn_count = (BIRDS_PER_SECOND as f64 * time.delta_secs_f64()) as usize;
351        spawn_birds(
352            &mut commands,
353            args.into_inner(),
354            &window.resolution,
355            &mut counter,
356            spawn_count,
357            bird_resources.into_inner(),
358            None,
359            *wave,
360        );
361        *wave += 1;
362    }
363}
364
365fn bird_velocity_transform(
366    half_extents: Vec2,
367    mut translation: Vec3,
368    velocity_rng: &mut ChaCha8Rng,
369    waves: Option<usize>,
370    dt: f32,
371) -> (Transform, Vec3) {
372    let mut velocity = Vec3::new(MAX_VELOCITY * (velocity_rng.gen::<f32>() - 0.5), 0., 0.);
373
374    if let Some(waves) = waves {
375        // Step the movement and handle collisions as if the wave had been spawned at fixed time intervals
376        // and with dt-spaced frames of simulation
377        for _ in 0..(waves * (FIXED_TIMESTEP / dt).round() as usize) {
378            step_movement(&mut translation, &mut velocity, dt);
379            handle_collision(half_extents, &translation, &mut velocity);
380        }
381    }
382    (
383        Transform::from_translation(translation).with_scale(Vec3::splat(BIRD_SCALE)),
384        velocity,
385    )
386}
387
388const FIXED_DELTA_TIME: f32 = 1.0 / 60.0;
389
390#[allow(clippy::too_many_arguments)]
391fn spawn_birds(
392    commands: &mut Commands,
393    args: &Args,
394    primary_window_resolution: &WindowResolution,
395    counter: &mut BevyCounter,
396    spawn_count: usize,
397    bird_resources: &mut BirdResources,
398    waves_to_simulate: Option<usize>,
399    wave: usize,
400) {
401    let bird_x = (primary_window_resolution.width() / -2.) + HALF_BIRD_SIZE;
402    let bird_y = (primary_window_resolution.height() / 2.) - HALF_BIRD_SIZE;
403
404    let half_extents = 0.5 * primary_window_resolution.size();
405
406    let color = counter.color;
407    let current_count = counter.count;
408
409    match args.mode {
410        Mode::Sprite => {
411            let batch = (0..spawn_count)
412                .map(|count| {
413                    let bird_z = if args.ordered_z {
414                        (current_count + count) as f32 * 0.00001
415                    } else {
416                        bird_resources.transform_rng.gen::<f32>()
417                    };
418
419                    let (transform, velocity) = bird_velocity_transform(
420                        half_extents,
421                        Vec3::new(bird_x, bird_y, bird_z),
422                        &mut bird_resources.velocity_rng,
423                        waves_to_simulate,
424                        FIXED_DELTA_TIME,
425                    );
426
427                    let color = if args.vary_per_instance {
428                        Color::linear_rgb(
429                            bird_resources.color_rng.gen(),
430                            bird_resources.color_rng.gen(),
431                            bird_resources.color_rng.gen(),
432                        )
433                    } else {
434                        color
435                    };
436                    (
437                        Sprite {
438                            image: bird_resources
439                                .textures
440                                .choose(&mut bird_resources.material_rng)
441                                .unwrap()
442                                .clone(),
443                            color,
444                            ..default()
445                        },
446                        transform,
447                        Bird { velocity },
448                    )
449                })
450                .collect::<Vec<_>>();
451            commands.spawn_batch(batch);
452        }
453        Mode::Mesh2d => {
454            let batch = (0..spawn_count)
455                .map(|count| {
456                    let bird_z = if args.ordered_z {
457                        (current_count + count) as f32 * 0.00001
458                    } else {
459                        bird_resources.transform_rng.gen::<f32>()
460                    };
461
462                    let (transform, velocity) = bird_velocity_transform(
463                        half_extents,
464                        Vec3::new(bird_x, bird_y, bird_z),
465                        &mut bird_resources.velocity_rng,
466                        waves_to_simulate,
467                        FIXED_DELTA_TIME,
468                    );
469
470                    let material =
471                        if args.vary_per_instance || args.material_texture_count > args.waves {
472                            bird_resources
473                                .materials
474                                .choose(&mut bird_resources.material_rng)
475                                .unwrap()
476                                .clone()
477                        } else {
478                            bird_resources.materials[wave % bird_resources.materials.len()].clone()
479                        };
480                    (
481                        Mesh2d(bird_resources.quad.clone()),
482                        MeshMaterial2d(material),
483                        transform,
484                        Bird { velocity },
485                    )
486                })
487                .collect::<Vec<_>>();
488            commands.spawn_batch(batch);
489        }
490    }
491
492    counter.count += spawn_count;
493    counter.color = Color::linear_rgb(
494        bird_resources.color_rng.gen(),
495        bird_resources.color_rng.gen(),
496        bird_resources.color_rng.gen(),
497    );
498}
More examples
Hide additional examples
examples/2d/cpu_draw.rs (line 97)
86fn draw(
87    my_handle: Res<MyProcGenImage>,
88    mut images: ResMut<Assets<Image>>,
89    // used to keep track of where we are
90    mut i: Local<u32>,
91    mut draw_color: Local<Color>,
92) {
93    let mut rng = rand::thread_rng();
94
95    if *i == 0 {
96        // Generate a random color on first run.
97        *draw_color = Color::linear_rgb(rng.gen(), rng.gen(), rng.gen());
98    }
99
100    // Get the image from Bevy's asset storage.
101    let image = images.get_mut(&my_handle.0).expect("Image not found");
102
103    // Compute the position of the pixel to draw.
104
105    let center = Vec2::new(IMAGE_WIDTH as f32 / 2.0, IMAGE_HEIGHT as f32 / 2.0);
106    let max_radius = IMAGE_HEIGHT.min(IMAGE_WIDTH) as f32 / 2.0;
107    let rot_speed = 0.0123;
108    let period = 0.12345;
109
110    let r = ops::sin(*i as f32 * period) * max_radius;
111    let xy = Vec2::from_angle(*i as f32 * rot_speed) * r + center;
112    let (x, y) = (xy.x as u32, xy.y as u32);
113
114    // Get the old color of that pixel.
115    let old_color = image.get_color_at(x, y).unwrap();
116
117    // If the old color is our current color, change our drawing color.
118    let tolerance = 1.0 / 255.0;
119    if old_color.distance(&draw_color) <= tolerance {
120        *draw_color = Color::linear_rgb(rng.gen(), rng.gen(), rng.gen());
121    }
122
123    // Set the new color, but keep old alpha value from image.
124    image
125        .set_color_at(x, y, draw_color.with_alpha(old_color.alpha()))
126        .unwrap();
127
128    *i += 1;
129}
examples/3d/motion_blur.rs (line 80)
55fn setup_scene(
56    asset_server: Res<AssetServer>,
57    mut images: ResMut<Assets<Image>>,
58    mut commands: Commands,
59    mut meshes: ResMut<Assets<Mesh>>,
60    mut materials: ResMut<Assets<StandardMaterial>>,
61) {
62    commands.insert_resource(AmbientLight {
63        color: Color::WHITE,
64        brightness: 300.0,
65    });
66    commands.insert_resource(CameraMode::Chase);
67    commands.spawn((
68        DirectionalLight {
69            illuminance: 3_000.0,
70            shadows_enabled: true,
71            ..default()
72        },
73        Transform::default().looking_to(Vec3::new(-1.0, -0.7, -1.0), Vec3::X),
74    ));
75    // Sky
76    commands.spawn((
77        Mesh3d(meshes.add(Sphere::default())),
78        MeshMaterial3d(materials.add(StandardMaterial {
79            unlit: true,
80            base_color: Color::linear_rgb(0.1, 0.6, 1.0),
81            ..default()
82        })),
83        Transform::default().with_scale(Vec3::splat(-4000.0)),
84    ));
85    // Ground
86    let mut plane: Mesh = Plane3d::default().into();
87    let uv_size = 4000.0;
88    let uvs = vec![[uv_size, 0.0], [0.0, 0.0], [0.0, uv_size], [uv_size; 2]];
89    plane.insert_attribute(Mesh::ATTRIBUTE_UV_0, uvs);
90    commands.spawn((
91        Mesh3d(meshes.add(plane)),
92        MeshMaterial3d(materials.add(StandardMaterial {
93            base_color: Color::WHITE,
94            perceptual_roughness: 1.0,
95            base_color_texture: Some(images.add(uv_debug_texture())),
96            ..default()
97        })),
98        Transform::from_xyz(0.0, -0.65, 0.0).with_scale(Vec3::splat(80.)),
99    ));
100
101    spawn_cars(&asset_server, &mut meshes, &mut materials, &mut commands);
102    spawn_trees(&mut meshes, &mut materials, &mut commands);
103    spawn_barriers(&mut meshes, &mut materials, &mut commands);
104}
105
106fn spawn_cars(
107    asset_server: &AssetServer,
108    meshes: &mut Assets<Mesh>,
109    materials: &mut Assets<StandardMaterial>,
110    commands: &mut Commands,
111) {
112    const N_CARS: usize = 20;
113    let box_mesh = meshes.add(Cuboid::new(0.3, 0.15, 0.55));
114    let cylinder = meshes.add(Cylinder::default());
115    let logo = asset_server.load("branding/icon.png");
116    let wheel_matl = materials.add(StandardMaterial {
117        base_color: Color::WHITE,
118        base_color_texture: Some(logo.clone()),
119        ..default()
120    });
121
122    let mut matl = |color| {
123        materials.add(StandardMaterial {
124            base_color: color,
125            ..default()
126        })
127    };
128
129    let colors = [
130        matl(Color::linear_rgb(1.0, 0.0, 0.0)),
131        matl(Color::linear_rgb(1.0, 1.0, 0.0)),
132        matl(Color::BLACK),
133        matl(Color::linear_rgb(0.0, 0.0, 1.0)),
134        matl(Color::linear_rgb(0.0, 1.0, 0.0)),
135        matl(Color::linear_rgb(1.0, 0.0, 1.0)),
136        matl(Color::linear_rgb(0.5, 0.5, 0.0)),
137        matl(Color::linear_rgb(1.0, 0.5, 0.0)),
138    ];
139
140    for i in 0..N_CARS {
141        let color = colors[i % colors.len()].clone();
142        commands
143            .spawn((
144                Mesh3d(box_mesh.clone()),
145                MeshMaterial3d(color.clone()),
146                Transform::from_scale(Vec3::splat(0.5)),
147                Moves(i as f32 * 2.0),
148            ))
149            .insert_if(CameraTracked, || i == 0)
150            .with_children(|parent| {
151                parent.spawn((
152                    Mesh3d(box_mesh.clone()),
153                    MeshMaterial3d(color),
154                    Transform::from_xyz(0.0, 0.08, 0.03).with_scale(Vec3::new(1.0, 1.0, 0.5)),
155                ));
156                let mut spawn_wheel = |x: f32, z: f32| {
157                    parent.spawn((
158                        Mesh3d(cylinder.clone()),
159                        MeshMaterial3d(wheel_matl.clone()),
160                        Transform::from_xyz(0.14 * x, -0.045, 0.15 * z)
161                            .with_scale(Vec3::new(0.15, 0.04, 0.15))
162                            .with_rotation(Quat::from_rotation_z(std::f32::consts::FRAC_PI_2)),
163                        Rotates,
164                    ));
165                };
166                spawn_wheel(1.0, 1.0);
167                spawn_wheel(1.0, -1.0);
168                spawn_wheel(-1.0, 1.0);
169                spawn_wheel(-1.0, -1.0);
170            });
171    }
172}
173
174fn spawn_barriers(
175    meshes: &mut Assets<Mesh>,
176    materials: &mut Assets<StandardMaterial>,
177    commands: &mut Commands,
178) {
179    const N_CONES: usize = 100;
180    let capsule = meshes.add(Capsule3d::default());
181    let matl = materials.add(StandardMaterial {
182        base_color: Color::srgb_u8(255, 87, 51),
183        reflectance: 1.0,
184        ..default()
185    });
186    let mut spawn_with_offset = |offset: f32| {
187        for i in 0..N_CONES {
188            let pos = race_track_pos(
189                offset,
190                (i as f32) / (N_CONES as f32) * std::f32::consts::PI * 2.0,
191            );
192            commands.spawn((
193                Mesh3d(capsule.clone()),
194                MeshMaterial3d(matl.clone()),
195                Transform::from_xyz(pos.x, -0.65, pos.y).with_scale(Vec3::splat(0.07)),
196            ));
197        }
198    };
199    spawn_with_offset(0.04);
200    spawn_with_offset(-0.04);
201}
202
203fn spawn_trees(
204    meshes: &mut Assets<Mesh>,
205    materials: &mut Assets<StandardMaterial>,
206    commands: &mut Commands,
207) {
208    const N_TREES: usize = 30;
209    let capsule = meshes.add(Capsule3d::default());
210    let sphere = meshes.add(Sphere::default());
211    let leaves = materials.add(Color::linear_rgb(0.0, 1.0, 0.0));
212    let trunk = materials.add(Color::linear_rgb(0.4, 0.2, 0.2));
213
214    let mut spawn_with_offset = |offset: f32| {
215        for i in 0..N_TREES {
216            let pos = race_track_pos(
217                offset,
218                (i as f32) / (N_TREES as f32) * std::f32::consts::PI * 2.0,
219            );
220            let [x, z] = pos.into();
221            commands.spawn((
222                Mesh3d(sphere.clone()),
223                MeshMaterial3d(leaves.clone()),
224                Transform::from_xyz(x, -0.3, z).with_scale(Vec3::splat(0.3)),
225            ));
226            commands.spawn((
227                Mesh3d(capsule.clone()),
228                MeshMaterial3d(trunk.clone()),
229                Transform::from_xyz(x, -0.5, z).with_scale(Vec3::new(0.05, 0.3, 0.05)),
230            ));
231        }
232    };
233    spawn_with_offset(0.07);
234    spawn_with_offset(-0.07);
235}
Source

pub const fn hsla( hue: f32, saturation: f32, lightness: f32, alpha: f32, ) -> Color

Creates a new Color object storing a Hsla color.

Examples found in repository?
examples/shader/custom_shader_instancing.rs (line 58)
49fn setup(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>) {
50    commands.spawn((
51        Mesh3d(meshes.add(Cuboid::new(0.5, 0.5, 0.5))),
52        InstanceMaterialData(
53            (1..=10)
54                .flat_map(|x| (1..=10).map(move |y| (x as f32 / 10.0, y as f32 / 10.0)))
55                .map(|(x, y)| InstanceData {
56                    position: Vec3::new(x * 10.0 - 5.0, y * 10.0 - 5.0, 0.0),
57                    scale: 1.0,
58                    color: LinearRgba::from(Color::hsla(x * 360., y, 0.5, 1.0)).to_f32_array(),
59                })
60                .collect(),
61        ),
62        // NOTE: Frustum culling is done based on the Aabb of the Mesh and the GlobalTransform.
63        // As the cube is at the origin, if its Aabb moves outside the view frustum, all the
64        // instanced cubes will be culled.
65        // The InstanceMaterialData contains the 'GlobalTransform' information for this custom
66        // instancing, and that is not taken into account with the built-in frustum culling.
67        // We must disable the built-in frustum culling by adding the `NoFrustumCulling` marker
68        // component to avoid incorrect culling.
69        NoFrustumCulling,
70    ));
71
72    // camera
73    commands.spawn((
74        Camera3d::default(),
75        Transform::from_xyz(0.0, 0.0, 15.0).looking_at(Vec3::ZERO, Vec3::Y),
76    ));
77}
Source

pub const fn hsl(hue: f32, saturation: f32, lightness: f32) -> Color

Creates a new Color object storing a Hsla color with an alpha of 1.0.

Examples found in repository?
examples/ecs/observers.rs (line 166)
161fn draw_shapes(mut gizmos: Gizmos, mines: Query<&Mine>) {
162    for mine in &mines {
163        gizmos.circle_2d(
164            mine.pos,
165            mine.size,
166            Color::hsl((mine.size - 4.0) / 16.0 * 360.0, 1.0, 0.8),
167        );
168    }
169}
More examples
Hide additional examples
examples/ui/ui_material.rs (line 88)
79fn animate(
80    mut materials: ResMut<Assets<CustomUiMaterial>>,
81    q: Query<&MaterialNode<CustomUiMaterial>>,
82    time: Res<Time>,
83) {
84    let duration = 2.0;
85    for handle in &q {
86        if let Some(material) = materials.get_mut(handle) {
87            // rainbow color effect
88            let new_color = Color::hsl((time.elapsed_secs() * 60.0) % 360.0, 1., 0.5);
89            let border_color = Color::hsl((time.elapsed_secs() * 60.0) % 360.0, 0.75, 0.75);
90            material.color = new_color.to_linear().to_vec4();
91            material.slider =
92                ((time.elapsed_secs() % (duration * 2.0)) - duration).abs() / duration;
93            material.border_color = border_color.to_linear().to_vec4();
94        }
95    }
96}
examples/testbed/2d.rs (line 88)
61    pub fn setup(
62        mut commands: Commands,
63        mut meshes: ResMut<Assets<Mesh>>,
64        mut materials: ResMut<Assets<ColorMaterial>>,
65    ) {
66        commands.spawn((Camera2d, StateScoped(super::Scene::Shapes)));
67
68        let shapes = [
69            meshes.add(Circle::new(50.0)),
70            meshes.add(CircularSector::new(50.0, 1.0)),
71            meshes.add(CircularSegment::new(50.0, 1.25)),
72            meshes.add(Ellipse::new(25.0, 50.0)),
73            meshes.add(Annulus::new(25.0, 50.0)),
74            meshes.add(Capsule2d::new(25.0, 50.0)),
75            meshes.add(Rhombus::new(75.0, 100.0)),
76            meshes.add(Rectangle::new(50.0, 100.0)),
77            meshes.add(RegularPolygon::new(50.0, 6)),
78            meshes.add(Triangle2d::new(
79                Vec2::Y * 50.0,
80                Vec2::new(-50.0, -50.0),
81                Vec2::new(50.0, -50.0),
82            )),
83        ];
84        let num_shapes = shapes.len();
85
86        for (i, shape) in shapes.into_iter().enumerate() {
87            // Distribute colors evenly across the rainbow.
88            let color = Color::hsl(360. * i as f32 / num_shapes as f32, 0.95, 0.7);
89
90            commands.spawn((
91                Mesh2d(shape),
92                MeshMaterial2d(materials.add(color)),
93                Transform::from_xyz(
94                    // Distribute shapes from -X_EXTENT/2 to +X_EXTENT/2.
95                    -X_EXTENT / 2. + i as f32 / (num_shapes - 1) as f32 * X_EXTENT,
96                    0.0,
97                    0.0,
98                ),
99                StateScoped(super::Scene::Shapes),
100            ));
101        }
102    }
examples/2d/2d_shapes.rs (line 52)
25fn setup(
26    mut commands: Commands,
27    mut meshes: ResMut<Assets<Mesh>>,
28    mut materials: ResMut<Assets<ColorMaterial>>,
29) {
30    commands.spawn(Camera2d);
31
32    let shapes = [
33        meshes.add(Circle::new(50.0)),
34        meshes.add(CircularSector::new(50.0, 1.0)),
35        meshes.add(CircularSegment::new(50.0, 1.25)),
36        meshes.add(Ellipse::new(25.0, 50.0)),
37        meshes.add(Annulus::new(25.0, 50.0)),
38        meshes.add(Capsule2d::new(25.0, 50.0)),
39        meshes.add(Rhombus::new(75.0, 100.0)),
40        meshes.add(Rectangle::new(50.0, 100.0)),
41        meshes.add(RegularPolygon::new(50.0, 6)),
42        meshes.add(Triangle2d::new(
43            Vec2::Y * 50.0,
44            Vec2::new(-50.0, -50.0),
45            Vec2::new(50.0, -50.0),
46        )),
47    ];
48    let num_shapes = shapes.len();
49
50    for (i, shape) in shapes.into_iter().enumerate() {
51        // Distribute colors evenly across the rainbow.
52        let color = Color::hsl(360. * i as f32 / num_shapes as f32, 0.95, 0.7);
53
54        commands.spawn((
55            Mesh2d(shape),
56            MeshMaterial2d(materials.add(color)),
57            Transform::from_xyz(
58                // Distribute shapes from -X_EXTENT/2 to +X_EXTENT/2.
59                -X_EXTENT / 2. + i as f32 / (num_shapes - 1) as f32 * X_EXTENT,
60                0.0,
61                0.0,
62            ),
63        ));
64    }
65
66    #[cfg(not(target_arch = "wasm32"))]
67    commands.spawn((
68        Text::new("Press space to toggle wireframes"),
69        Node {
70            position_type: PositionType::Absolute,
71            top: Val::Px(12.0),
72            left: Val::Px(12.0),
73            ..default()
74        },
75    ));
76}
examples/stress_tests/many_buttons.rs (line 136)
121fn setup_flex(mut commands: Commands, asset_server: Res<AssetServer>, args: Res<Args>) {
122    warn!(include_str!("warning_string.txt"));
123    let image = if 0 < args.image_freq {
124        Some(asset_server.load("branding/icon.png"))
125    } else {
126        None
127    };
128
129    let buttons_f = args.buttons as f32;
130    let border = if args.no_borders {
131        UiRect::ZERO
132    } else {
133        UiRect::all(Val::VMin(0.05 * 90. / buttons_f))
134    };
135
136    let as_rainbow = |i: usize| Color::hsl((i as f32 / buttons_f) * 360.0, 0.9, 0.8);
137    commands.spawn(Camera2d);
138    commands
139        .spawn(Node {
140            flex_direction: FlexDirection::Column,
141            justify_content: JustifyContent::Center,
142            align_items: AlignItems::Center,
143            width: Val::Percent(100.),
144            height: Val::Percent(100.),
145            ..default()
146        })
147        .with_children(|commands| {
148            for column in 0..args.buttons {
149                commands.spawn(Node::default()).with_children(|commands| {
150                    for row in 0..args.buttons {
151                        let color = as_rainbow(row % column.max(1));
152                        let border_color = Color::WHITE.with_alpha(0.5).into();
153                        spawn_button(
154                            commands,
155                            color,
156                            buttons_f,
157                            column,
158                            row,
159                            !args.no_text,
160                            border,
161                            border_color,
162                            image
163                                .as_ref()
164                                .filter(|_| (column + row) % args.image_freq == 0)
165                                .cloned(),
166                        );
167                    }
168                });
169            }
170        });
171}
172
173fn setup_grid(mut commands: Commands, asset_server: Res<AssetServer>, args: Res<Args>) {
174    warn!(include_str!("warning_string.txt"));
175    let image = if 0 < args.image_freq {
176        Some(asset_server.load("branding/icon.png"))
177    } else {
178        None
179    };
180
181    let buttons_f = args.buttons as f32;
182    let border = if args.no_borders {
183        UiRect::ZERO
184    } else {
185        UiRect::all(Val::VMin(0.05 * 90. / buttons_f))
186    };
187
188    let as_rainbow = |i: usize| Color::hsl((i as f32 / buttons_f) * 360.0, 0.9, 0.8);
189    commands.spawn(Camera2d);
190    commands
191        .spawn(Node {
192            display: Display::Grid,
193            width: Val::Percent(100.),
194            height: Val::Percent(100.0),
195            grid_template_columns: RepeatedGridTrack::flex(args.buttons as u16, 1.0),
196            grid_template_rows: RepeatedGridTrack::flex(args.buttons as u16, 1.0),
197            ..default()
198        })
199        .with_children(|commands| {
200            for column in 0..args.buttons {
201                for row in 0..args.buttons {
202                    let color = as_rainbow(row % column.max(1));
203                    let border_color = Color::WHITE.with_alpha(0.5).into();
204                    spawn_button(
205                        commands,
206                        color,
207                        buttons_f,
208                        column,
209                        row,
210                        !args.no_text,
211                        border,
212                        border_color,
213                        image
214                            .as_ref()
215                            .filter(|_| (column + row) % args.image_freq == 0)
216                            .cloned(),
217                    );
218                }
219            }
220        });
221}
examples/stress_tests/many_lights.rs (line 84)
44fn setup(
45    mut commands: Commands,
46    mut meshes: ResMut<Assets<Mesh>>,
47    mut materials: ResMut<Assets<StandardMaterial>>,
48) {
49    warn!(include_str!("warning_string.txt"));
50
51    const LIGHT_RADIUS: f32 = 0.3;
52    const LIGHT_INTENSITY: f32 = 1000.0;
53    const RADIUS: f32 = 50.0;
54    const N_LIGHTS: usize = 100_000;
55
56    commands.spawn((
57        Mesh3d(meshes.add(Sphere::new(RADIUS).mesh().ico(9).unwrap())),
58        MeshMaterial3d(materials.add(Color::WHITE)),
59        Transform::from_scale(Vec3::NEG_ONE),
60    ));
61
62    let mesh = meshes.add(Cuboid::default());
63    let material = materials.add(StandardMaterial {
64        base_color: DEEP_PINK.into(),
65        ..default()
66    });
67
68    // NOTE: This pattern is good for testing performance of culling as it provides roughly
69    // the same number of visible meshes regardless of the viewing angle.
70    // NOTE: f64 is used to avoid precision issues that produce visual artifacts in the distribution
71    let golden_ratio = 0.5f64 * (1.0f64 + 5.0f64.sqrt());
72
73    // Spawn N_LIGHTS many lights
74    commands.spawn_batch((0..N_LIGHTS).map(move |i| {
75        let mut rng = thread_rng();
76
77        let spherical_polar_theta_phi = fibonacci_spiral_on_sphere(golden_ratio, i, N_LIGHTS);
78        let unit_sphere_p = spherical_polar_to_cartesian(spherical_polar_theta_phi);
79
80        (
81            PointLight {
82                range: LIGHT_RADIUS,
83                intensity: LIGHT_INTENSITY,
84                color: Color::hsl(rng.gen_range(0.0..360.0), 1.0, 0.5),
85                ..default()
86            },
87            Transform::from_translation((RADIUS as f64 * unit_sphere_p).as_vec3()),
88        )
89    }));
90
91    // camera
92    match std::env::args().nth(1).as_deref() {
93        Some("orthographic") => commands.spawn((
94            Camera3d::default(),
95            Projection::from(OrthographicProjection {
96                scaling_mode: ScalingMode::FixedHorizontal {
97                    viewport_width: 20.0,
98                },
99                ..OrthographicProjection::default_3d()
100            }),
101        )),
102        _ => commands.spawn(Camera3d::default()),
103    };
104
105    // add one cube, the only one with strong handles
106    // also serves as a reference point during rotation
107    commands.spawn((
108        Mesh3d(mesh),
109        MeshMaterial3d(material),
110        Transform {
111            translation: Vec3::new(0.0, RADIUS, 0.0),
112            scale: Vec3::splat(5.0),
113            ..default()
114        },
115    ));
116}
Source

pub const fn hsva(hue: f32, saturation: f32, value: f32, alpha: f32) -> Color

Creates a new Color object storing a Hsva color.

Source

pub const fn hsv(hue: f32, saturation: f32, value: f32) -> Color

Creates a new Color object storing a Hsva color with an alpha of 1.0.

Examples found in repository?
examples/stress_tests/many_cameras_lights.rs (line 49)
24fn setup(
25    mut commands: Commands,
26    mut meshes: ResMut<Assets<Mesh>>,
27    mut materials: ResMut<Assets<StandardMaterial>>,
28    window: Query<&Window>,
29) {
30    // circular base
31    commands.spawn((
32        Mesh3d(meshes.add(Circle::new(4.0))),
33        MeshMaterial3d(materials.add(Color::WHITE)),
34        Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
35    ));
36
37    // cube
38    commands.spawn((
39        Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
40        MeshMaterial3d(materials.add(Color::WHITE)),
41        Transform::from_xyz(0.0, 0.5, 0.0),
42    ));
43
44    // lights
45    for i in 0..NUM_LIGHTS {
46        let angle = (i as f32) / (NUM_LIGHTS as f32) * PI * 2.0;
47        commands.spawn((
48            PointLight {
49                color: Color::hsv(angle.to_degrees(), 1.0, 1.0),
50                intensity: 2_000_000.0 / NUM_LIGHTS as f32,
51                shadows_enabled: true,
52                ..default()
53            },
54            Transform::from_xyz(sin(angle) * 4.0, 2.0, cos(angle) * 4.0),
55        ));
56    }
57
58    // cameras
59    let window = window.single();
60    let width = window.resolution.width() / CAMERA_COLS as f32 * window.resolution.scale_factor();
61    let height = window.resolution.height() / CAMERA_ROWS as f32 * window.resolution.scale_factor();
62    let mut i = 0;
63    for y in 0..CAMERA_COLS {
64        for x in 0..CAMERA_ROWS {
65            let angle = i as f32 / (CAMERA_ROWS * CAMERA_COLS) as f32 * PI * 2.0;
66            commands.spawn((
67                Camera3d::default(),
68                Camera {
69                    viewport: Some(Viewport {
70                        physical_position: UVec2::new(
71                            (x as f32 * width) as u32,
72                            (y as f32 * height) as u32,
73                        ),
74                        physical_size: UVec2::new(width as u32, height as u32),
75                        ..default()
76                    }),
77                    order: i,
78                    ..default()
79                },
80                Transform::from_xyz(sin(angle) * 4.0, 2.5, cos(angle) * 4.0)
81                    .looking_at(Vec3::ZERO, Vec3::Y),
82            ));
83            i += 1;
84        }
85    }
86}
Source

pub const fn hwba(hue: f32, whiteness: f32, blackness: f32, alpha: f32) -> Color

Creates a new Color object storing a Hwba color.

Source

pub const fn hwb(hue: f32, whiteness: f32, blackness: f32) -> Color

Creates a new Color object storing a Hwba color with an alpha of 1.0.

Source

pub const fn laba(lightness: f32, a: f32, b: f32, alpha: f32) -> Color

Creates a new Color object storing a Laba color.

Source

pub const fn lab(lightness: f32, a: f32, b: f32) -> Color

Creates a new Color object storing a Laba color with an alpha of 1.0.

Source

pub const fn lcha(lightness: f32, chroma: f32, hue: f32, alpha: f32) -> Color

Creates a new Color object storing a Lcha color.

Source

pub const fn lch(lightness: f32, chroma: f32, hue: f32) -> Color

Creates a new Color object storing a Lcha color with an alpha of 1.0.

Source

pub const fn oklaba(lightness: f32, a: f32, b: f32, alpha: f32) -> Color

Creates a new Color object storing a Oklaba color.

Source

pub const fn oklab(lightness: f32, a: f32, b: f32) -> Color

Creates a new Color object storing a Oklaba color with an alpha of 1.0.

Source

pub const fn oklcha(lightness: f32, chroma: f32, hue: f32, alpha: f32) -> Color

Creates a new Color object storing a Oklcha color.

Source

pub const fn oklch(lightness: f32, chroma: f32, hue: f32) -> Color

Creates a new Color object storing a Oklcha color with an alpha of 1.0.

Source

pub const fn xyza(x: f32, y: f32, z: f32, alpha: f32) -> Color

Creates a new Color object storing a Xyza color.

Source

pub const fn xyz(x: f32, y: f32, z: f32) -> Color

Creates a new Color object storing a Xyza color with an alpha of 1.0.

Trait Implementations§

Source§

impl Alpha for Color

Source§

fn with_alpha(&self, alpha: f32) -> Color

Return a new version of this color with the given alpha value.
Source§

fn alpha(&self) -> f32

Return a the alpha component of this color.
Source§

fn set_alpha(&mut self, alpha: f32)

Sets the alpha component of this color.
Source§

fn is_fully_transparent(&self) -> bool

Is the alpha component of this color less than or equal to 0.0?
Source§

fn is_fully_opaque(&self) -> bool

Is the alpha component of this color greater than or equal to 1.0?
Source§

impl Clone for Color

Source§

fn clone(&self) -> Color

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Color

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for Color

Source§

fn default() -> Color

A fully white Color::LinearRgba color with an alpha of 1.0.

Source§

impl<'de> Deserialize<'de> for Color

Source§

fn deserialize<__D>( __deserializer: __D, ) -> Result<Color, <__D as Deserializer<'de>>::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Enum for Color
where Color: Any + Send + Sync, Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn field(&self, __name_param: &str) -> Option<&(dyn PartialReflect + 'static)>

Returns a reference to the value of the field (in the current variant) with the given name. Read more
Source§

fn field_at( &self, __index_param: usize, ) -> Option<&(dyn PartialReflect + 'static)>

Returns a reference to the value of the field (in the current variant) at the given index.
Source§

fn field_mut( &mut self, __name_param: &str, ) -> Option<&mut (dyn PartialReflect + 'static)>

Returns a mutable reference to the value of the field (in the current variant) with the given name. Read more
Source§

fn field_at_mut( &mut self, __index_param: usize, ) -> Option<&mut (dyn PartialReflect + 'static)>

Returns a mutable reference to the value of the field (in the current variant) at the given index.
Source§

fn index_of(&self, __name_param: &str) -> Option<usize>

Returns the index of the field (in the current variant) with the given name. Read more
Source§

fn name_at(&self, __index_param: usize) -> Option<&str>

Returns the name of the field (in the current variant) with the given index. Read more
Source§

fn iter_fields(&self) -> VariantFieldIter<'_>

Returns an iterator over the values of the current variant’s fields.
Source§

fn field_len(&self) -> usize

Returns the number of fields in the current variant.
Source§

fn variant_name(&self) -> &str

The name of the current variant.
Source§

fn variant_index(&self) -> usize

The index of the current variant.
Source§

fn variant_type(&self) -> VariantType

The type of the current variant.
Source§

fn clone_dynamic(&self) -> DynamicEnum

Source§

fn is_variant(&self, variant_type: VariantType) -> bool

Returns true if the current variant’s type matches the given one.
Source§

fn variant_path(&self) -> String

Returns the full path to the current variant.
Source§

fn get_represented_enum_info(&self) -> Option<&'static EnumInfo>

Will return None if TypeInfo is not available.
Source§

impl EuclideanDistance for Color

Source§

fn distance_squared(&self, other: &Color) -> f32

Distance squared from self to other.
Source§

fn distance(&self, other: &Self) -> f32

Distance from self to other.
Source§

impl From<Color> for ClearColorConfig

Source§

fn from(value: Color) -> ClearColorConfig

Converts to this type from the input type.
Source§

impl From<Color> for ColorMaterial

Source§

fn from(color: Color) -> ColorMaterial

Converts to this type from the input type.
Source§

impl From<Color> for Hsla

Source§

fn from(value: Color) -> Hsla

Converts to this type from the input type.
Source§

impl From<Color> for Hsva

Source§

fn from(value: Color) -> Hsva

Converts to this type from the input type.
Source§

impl From<Color> for Hwba

Source§

fn from(value: Color) -> Hwba

Converts to this type from the input type.
Source§

impl From<Color> for Laba

Source§

fn from(value: Color) -> Laba

Converts to this type from the input type.
Source§

impl From<Color> for Lcha

Source§

fn from(value: Color) -> Lcha

Converts to this type from the input type.
Source§

impl From<Color> for LinearRgba

Source§

fn from(value: Color) -> LinearRgba

Converts to this type from the input type.
Source§

impl From<Color> for Oklaba

Source§

fn from(value: Color) -> Oklaba

Converts to this type from the input type.
Source§

impl From<Color> for Oklcha

Source§

fn from(value: Color) -> Oklcha

Converts to this type from the input type.
Source§

impl From<Color> for Srgba

Source§

fn from(value: Color) -> Srgba

Converts to this type from the input type.
Source§

impl From<Color> for StandardMaterial

Source§

fn from(color: Color) -> StandardMaterial

Converts to this type from the input type.
Source§

impl From<Color> for Xyza

Source§

fn from(value: Color) -> Xyza

Converts to this type from the input type.
Source§

impl From<Hsla> for Color

Source§

fn from(value: Hsla) -> Color

Converts to this type from the input type.
Source§

impl From<Hsva> for Color

Source§

fn from(value: Hsva) -> Color

Converts to this type from the input type.
Source§

impl From<Hwba> for Color

Source§

fn from(value: Hwba) -> Color

Converts to this type from the input type.
Source§

impl From<Laba> for Color

Source§

fn from(value: Laba) -> Color

Converts to this type from the input type.
Source§

impl From<Lcha> for Color

Source§

fn from(value: Lcha) -> Color

Converts to this type from the input type.
Source§

impl From<LinearRgba> for Color

Source§

fn from(value: LinearRgba) -> Color

Converts to this type from the input type.
Source§

impl From<Oklaba> for Color

Source§

fn from(value: Oklaba) -> Color

Converts to this type from the input type.
Source§

impl From<Oklcha> for Color

Source§

fn from(value: Oklcha) -> Color

Converts to this type from the input type.
Source§

impl From<Srgba> for Color

Source§

fn from(value: Srgba) -> Color

Converts to this type from the input type.
Source§

impl From<Xyza> for Color

Source§

fn from(value: Xyza) -> Color

Converts to this type from the input type.
Source§

impl FromArg for &'static Color
where Color: Any + Send + Sync, Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

type This<'from_arg> = &'from_arg Color

The type to convert into. Read more
Source§

fn from_arg( arg: Arg<'_>, ) -> Result<<&'static Color as FromArg>::This<'_>, ArgError>

Creates an item from an argument. Read more
Source§

impl FromArg for &'static mut Color
where Color: Any + Send + Sync, Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

type This<'from_arg> = &'from_arg mut Color

The type to convert into. Read more
Source§

fn from_arg( arg: Arg<'_>, ) -> Result<<&'static mut Color as FromArg>::This<'_>, ArgError>

Creates an item from an argument. Read more
Source§

impl FromArg for Color
where Color: Any + Send + Sync, Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

type This<'from_arg> = Color

The type to convert into. Read more
Source§

fn from_arg(arg: Arg<'_>) -> Result<<Color as FromArg>::This<'_>, ArgError>

Creates an item from an argument. Read more
Source§

impl FromReflect for Color
where Color: Any + Send + Sync, Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn from_reflect(__param0: &(dyn PartialReflect + 'static)) -> Option<Color>

Constructs a concrete instance of Self from a reflected value.
Source§

fn take_from_reflect( reflect: Box<dyn PartialReflect>, ) -> Result<Self, Box<dyn PartialReflect>>

Attempts to downcast the given value to Self using, constructing the value using from_reflect if that fails. Read more
Source§

impl GetOwnership for &Color
where Color: Any + Send + Sync, Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn ownership() -> Ownership

Returns the ownership of Self.
Source§

impl GetOwnership for &mut Color
where Color: Any + Send + Sync, Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn ownership() -> Ownership

Returns the ownership of Self.
Source§

impl GetOwnership for Color
where Color: Any + Send + Sync, Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn ownership() -> Ownership

Returns the ownership of Self.
Source§

impl GetTypeRegistration for Color
where Color: Any + Send + Sync, Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn get_type_registration() -> TypeRegistration

Returns the default TypeRegistration for this type.
Source§

fn register_type_dependencies(registry: &mut TypeRegistry)

Registers other types needed by this type. Read more
Source§

impl Hue for Color

Source§

fn with_hue(&self, hue: f32) -> Color

Return a new version of this color with the hue channel set to the given value.
Source§

fn hue(&self) -> f32

Return the hue of this color [0.0, 360.0].
Source§

fn set_hue(&mut self, hue: f32)

Sets the hue of this color.
Source§

fn rotate_hue(&self, degrees: f32) -> Self

Return a new version of this color with the hue channel rotated by the given degrees.
Source§

impl IntoReturn for &Color
where Color: Any + Send + Sync, Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn into_return<'into_return>(self) -> Return<'into_return>
where &Color: 'into_return,

Converts Self into a Return value.
Source§

impl IntoReturn for &mut Color
where Color: Any + Send + Sync, Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn into_return<'into_return>(self) -> Return<'into_return>
where &mut Color: 'into_return,

Converts Self into a Return value.
Source§

impl IntoReturn for Color
where Color: Any + Send + Sync, Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn into_return<'into_return>(self) -> Return<'into_return>
where Color: 'into_return,

Converts Self into a Return value.
Source§

impl Luminance for Color

Source§

fn luminance(&self) -> f32

Return the luminance of this color (0.0 - 1.0).
Source§

fn with_luminance(&self, value: f32) -> Color

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.
Source§

fn darker(&self, amount: f32) -> Color

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. Read more
Source§

fn lighter(&self, amount: f32) -> Color

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. Read more
Source§

impl Mix for Color

Source§

fn mix(&self, other: &Color, factor: f32) -> Color

Linearly interpolate between this and another color, by factor. Factor should be between 0.0 and 1.0.
Source§

fn mix_assign(&mut self, other: Self, factor: f32)

Linearly interpolate between this and another color, by factor, storing the result in this color. Factor should be between 0.0 and 1.0.
Source§

impl PartialEq for Color

Source§

fn eq(&self, other: &Color) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialReflect for Color
where Color: Any + Send + Sync, Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn get_represented_type_info(&self) -> Option<&'static TypeInfo>

Returns the TypeInfo of the type represented by this value. Read more
Source§

fn clone_value(&self) -> Box<dyn PartialReflect>

Clones the value as a Reflect trait object. Read more
Source§

fn try_apply( &mut self, __value_param: &(dyn PartialReflect + 'static), ) -> Result<(), ApplyError>

Tries to apply a reflected value to this value. Read more
Source§

fn reflect_kind(&self) -> ReflectKind

Returns a zero-sized enumeration of “kinds” of type. Read more
Source§

fn reflect_ref(&self) -> ReflectRef<'_>

Returns an immutable enumeration of “kinds” of type. Read more
Source§

fn reflect_mut(&mut self) -> ReflectMut<'_>

Returns a mutable enumeration of “kinds” of type. Read more
Source§

fn reflect_owned(self: Box<Color>) -> ReflectOwned

Returns an owned enumeration of “kinds” of type. Read more
Source§

fn try_into_reflect( self: Box<Color>, ) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>>

Attempts to cast this type to a boxed, fully-reflected value.
Source§

fn try_as_reflect(&self) -> Option<&(dyn Reflect + 'static)>

Attempts to cast this type to a fully-reflected value.
Source§

fn try_as_reflect_mut(&mut self) -> Option<&mut (dyn Reflect + 'static)>

Attempts to cast this type to a mutable, fully-reflected value.
Source§

fn into_partial_reflect(self: Box<Color>) -> Box<dyn PartialReflect>

Casts this type to a boxed, reflected value. Read more
Source§

fn as_partial_reflect(&self) -> &(dyn PartialReflect + 'static)

Casts this type to a reflected value. Read more
Source§

fn as_partial_reflect_mut(&mut self) -> &mut (dyn PartialReflect + 'static)

Casts this type to a mutable, reflected value. Read more
Source§

fn reflect_hash(&self) -> Option<u64>

Returns a hash of the value (which includes the type). Read more
Source§

fn reflect_partial_eq( &self, value: &(dyn PartialReflect + 'static), ) -> Option<bool>

Returns a “partial equality” comparison result. Read more
Source§

fn apply(&mut self, value: &(dyn PartialReflect + 'static))

Applies a reflected value to this value. Read more
Source§

fn debug(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Debug formatter for the value. Read more
Source§

fn serializable(&self) -> Option<Serializable<'_>>

Returns a serializable version of the value. Read more
Source§

fn is_dynamic(&self) -> bool

Indicates whether or not this type is a dynamic type. Read more
Source§

impl Reflect for Color
where Color: Any + Send + Sync, Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn into_any(self: Box<Color>) -> Box<dyn Any>

Returns the value as a Box<dyn Any>. Read more
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Returns the value as a &dyn Any. Read more
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Returns the value as a &mut dyn Any. Read more
Source§

fn into_reflect(self: Box<Color>) -> Box<dyn Reflect>

Casts this type to a boxed, fully-reflected value.
Source§

fn as_reflect(&self) -> &(dyn Reflect + 'static)

Casts this type to a fully-reflected value.
Source§

fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)

Casts this type to a mutable, fully-reflected value.
Source§

fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>>

Performs a type-checked assignment of a reflected value to this value. Read more
Source§

impl Serialize for Color

Source§

fn serialize<__S>( &self, __serializer: __S, ) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl TypePath for Color
where Color: Any + Send + Sync,

Source§

fn type_path() -> &'static str

Returns the fully qualified path of the underlying type. Read more
Source§

fn short_type_path() -> &'static str

Returns a short, pretty-print enabled path to the type. Read more
Source§

fn type_ident() -> Option<&'static str>

Returns the name of the type, or None if it is anonymous. Read more
Source§

fn crate_name() -> Option<&'static str>

Returns the name of the crate the type is in, or None if it is anonymous. Read more
Source§

fn module_path() -> Option<&'static str>

Returns the path to the module the type is in, or None if it is anonymous. Read more
Source§

impl Typed for Color
where Color: Any + Send + Sync, Srgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, LinearRgba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsla: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hsva: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Hwba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Laba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Lcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklaba: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Oklcha: FromReflect + TypePath + MaybeTyped + RegisterForReflection, Xyza: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn type_info() -> &'static TypeInfo

Returns the compile-time info for the underlying type.
Source§

impl Copy for Color

Source§

impl StructuralPartialEq for Color

Auto Trait Implementations§

§

impl Freeze for Color

§

impl RefUnwindSafe for Color

§

impl Send for Color

§

impl Sync for Color

§

impl Unpin for Color

§

impl UnwindSafe for Color

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T, U> AsBindGroupShaderType<U> for T
where U: ShaderType, &'a T: for<'a> Into<U>,

Source§

fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U

Return the T ShaderType for self. When used in AsBindGroup derives, it is safe to assume that all images in self exist.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> Conv for T

Source§

fn conv<T>(self) -> T
where Self: Into<T>,

Converts self into T using Into<T>. Read more
Source§

impl<T> Downcast<T> for T

Source§

fn downcast(&self) -> &T

Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DynamicTypePath for T
where T: TypePath,

Source§

impl<T> DynamicTyped for T
where T: Typed,

Source§

impl<T> FmtForward for T

Source§

fn fmt_binary(self) -> FmtBinary<Self>
where Self: Binary,

Causes self to use its Binary implementation when Debug-formatted.
Source§

fn fmt_display(self) -> FmtDisplay<Self>
where Self: Display,

Causes self to use its Display implementation when Debug-formatted.
Source§

fn fmt_lower_exp(self) -> FmtLowerExp<Self>
where Self: LowerExp,

Causes self to use its LowerExp implementation when Debug-formatted.
Source§

fn fmt_lower_hex(self) -> FmtLowerHex<Self>
where Self: LowerHex,

Causes self to use its LowerHex implementation when Debug-formatted.
Source§

fn fmt_octal(self) -> FmtOctal<Self>
where Self: Octal,

Causes self to use its Octal implementation when Debug-formatted.
Source§

fn fmt_pointer(self) -> FmtPointer<Self>
where Self: Pointer,

Causes self to use its Pointer implementation when Debug-formatted.
Source§

fn fmt_upper_exp(self) -> FmtUpperExp<Self>
where Self: UpperExp,

Causes self to use its UpperExp implementation when Debug-formatted.
Source§

fn fmt_upper_hex(self) -> FmtUpperHex<Self>
where Self: UpperHex,

Causes self to use its UpperHex implementation when Debug-formatted.
Source§

fn fmt_list(self) -> FmtList<Self>
where &'a Self: for<'a> IntoIterator,

Formats each item in a sequence. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S> FromSample<S> for S

Source§

fn from_sample_(s: S) -> S

Source§

impl<T> FromWorld for T
where T: Default,

Source§

fn from_world(_world: &mut World) -> T

Creates Self using default().

Source§

impl<T> GetPath for T
where T: Reflect + ?Sized,

Source§

fn reflect_path<'p>( &self, path: impl ReflectPath<'p>, ) -> Result<&(dyn PartialReflect + 'static), ReflectPathError<'p>>

Returns a reference to the value specified by path. Read more
Source§

fn reflect_path_mut<'p>( &mut self, path: impl ReflectPath<'p>, ) -> Result<&mut (dyn PartialReflect + 'static), ReflectPathError<'p>>

Returns a mutable reference to the value specified by path. Read more
Source§

fn path<'p, T>( &self, path: impl ReflectPath<'p>, ) -> Result<&T, ReflectPathError<'p>>
where T: Reflect,

Returns a statically typed reference to the value specified by path. Read more
Source§

fn path_mut<'p, T>( &mut self, path: impl ReflectPath<'p>, ) -> Result<&mut T, ReflectPathError<'p>>
where T: Reflect,

Returns a statically typed mutable reference to the value specified by path. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

Source§

fn into_sample(self) -> T

Source§

impl<T> NoneValue for T
where T: Default,

Source§

type NoneType = T

Source§

fn null_value() -> T

The none-equivalent value.
Source§

impl<T> Pipe for T
where T: ?Sized,

Source§

fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R
where Self: Sized,

Pipes by value. This is generally the method you want to use. Read more
Source§

fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> R
where R: 'a,

Borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> R
where R: 'a,

Mutably borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
where Self: Borrow<B>, B: 'a + ?Sized, R: 'a,

Borrows self, then passes self.borrow() into the pipe function. Read more
Source§

fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
where Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Source§

fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
where Self: AsRef<U>, U: 'a + ?Sized, R: 'a,

Borrows self, then passes self.as_ref() into the pipe function.
Source§

fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
where Self: AsMut<U>, U: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.as_mut() into the pipe function.
Source§

fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
where Self: Deref<Target = T>, T: 'a + ?Sized, R: 'a,

Borrows self, then passes self.deref() into the pipe function.
Source§

fn pipe_deref_mut<'a, T, R>( &'a mut self, func: impl FnOnce(&'a mut T) -> R, ) -> R
where Self: DerefMut<Target = T> + Deref, T: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.deref_mut() into the pipe function.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

Source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
Source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
Source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> Serialize for T
where T: Serialize + ?Sized,

Source§

fn erased_serialize(&self, serializer: &mut dyn Serializer) -> Result<(), Error>

Source§

fn do_erased_serialize( &self, serializer: &mut dyn Serializer, ) -> Result<(), ErrorImpl>

Source§

impl<T> Tap for T

Source§

fn tap(self, func: impl FnOnce(&Self)) -> Self

Immutable access to a value. Read more
Source§

fn tap_mut(self, func: impl FnOnce(&mut Self)) -> Self

Mutable access to a value. Read more
Source§

fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Immutable access to the Borrow<B> of a value. Read more
Source§

fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Mutable access to the BorrowMut<B> of a value. Read more
Source§

fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Immutable access to the AsRef<R> view of a value. Read more
Source§

fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Mutable access to the AsMut<R> view of a value. Read more
Source§

fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Immutable access to the Deref::Target of a value. Read more
Source§

fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Mutable access to the Deref::Target of a value. Read more
Source§

fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self

Calls .tap() only in debug builds, and is erased in release builds.
Source§

fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self

Calls .tap_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Calls .tap_borrow() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Calls .tap_ref() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Calls .tap_deref() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

Source§

fn to_sample_(self) -> U

Source§

impl<T> TryConv for T

Source§

fn try_conv<T>(self) -> Result<T, Self::Error>
where Self: TryInto<T>,

Attempts to convert self into T using TryInto<T>. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> TypeData for T
where T: 'static + Send + Sync + Clone,

Source§

impl<T> Upcast<T> for T

Source§

fn upcast(&self) -> Option<&T>

Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ConditionalSend for T
where T: Send,

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

Source§

impl<T> Reflectable for T

Source§

impl<T> Settings for T
where T: 'static + Send + Sync,

Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,