bevy::prelude

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)
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
fn animate(
    mut materials: ResMut<Assets<CustomUiMaterial>>,
    q: Query<&MaterialNode<CustomUiMaterial>>,
    time: Res<Time>,
) {
    let duration = 2.0;
    for handle in &q {
        if let Some(material) = materials.get_mut(handle) {
            // rainbow color effect
            let new_color = Color::hsl((time.elapsed_secs() * 60.0) % 360.0, 1., 0.5);
            let border_color = Color::hsl((time.elapsed_secs() * 60.0) % 360.0, 0.75, 0.75);
            material.color = new_color.to_linear().to_vec4();
            material.slider =
                ((time.elapsed_secs() % (duration * 2.0)) - duration).abs() / duration;
            material.border_color = border_color.to_linear().to_vec4();
        }
    }
}
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)
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
fn update_colors(
    keyboard_input: Res<ButtonInput<KeyCode>>,
    mut config: ResMut<Wireframe2dConfig>,
    mut wireframe_colors: Query<&mut Wireframe2dColor>,
    mut text: Single<&mut Text>,
) {
    text.0 = format!(
        "Controls
---------------
Z - Toggle global
X - Change global color
C - Change color of the circle wireframe

Wireframe2dConfig
-------------
Global: {}
Color: {:?}",
        config.global,
        config.default_color.to_srgba(),
    );

    // Toggle showing a wireframe on all meshes
    if keyboard_input.just_pressed(KeyCode::KeyZ) {
        config.global = !config.global;
    }

    // Toggle the global wireframe color
    if keyboard_input.just_pressed(KeyCode::KeyX) {
        config.default_color = if config.default_color == WHITE.into() {
            RED.into()
        } else {
            WHITE.into()
        };
    }

    // Toggle the color of a wireframe using `Wireframe2dColor` and not the global color
    if keyboard_input.just_pressed(KeyCode::KeyC) {
        for mut color in &mut wireframe_colors {
            color.color = if color.color == GREEN.into() {
                RED.into()
            } else {
                GREEN.into()
            };
        }
    }
}
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)
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
fn spawn_coated_glass_bubble_sphere(
    commands: &mut Commands,
    materials: &mut Assets<StandardMaterial>,
    sphere: &Handle<Mesh>,
) {
    commands
        .spawn((
            Mesh3d(sphere.clone()),
            MeshMaterial3d(materials.add(StandardMaterial {
                clearcoat: 1.0,
                clearcoat_perceptual_roughness: 0.1,
                metallic: 0.5,
                perceptual_roughness: 0.1,
                base_color: Color::srgba(0.9, 0.9, 0.9, 0.3),
                alpha_mode: AlphaMode::Blend,
                ..default()
            })),
            Transform::from_xyz(-1.0, -1.0, 0.0).with_scale(Vec3::splat(SPHERE_SCALE)),
        ))
        .insert(ExampleSphere);
}
More examples
Hide additional examples
examples/2d/transparency_2d.rs (line 23)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
    commands.spawn(Camera2d);

    let sprite_handle = asset_server.load("branding/icon.png");

    commands.spawn(Sprite::from_image(sprite_handle.clone()));
    commands.spawn((
        Sprite {
            image: sprite_handle.clone(),
            // Alpha channel of the color controls transparency.
            color: Color::srgba(0.0, 0.0, 1.0, 0.7),
            ..default()
        },
        Transform::from_xyz(100.0, 0.0, 0.0),
    ));
    commands.spawn((
        Sprite {
            image: sprite_handle,
            color: Color::srgba(0.0, 1.0, 0.0, 0.3),
            ..default()
        },
        Transform::from_xyz(200.0, 0.0, 0.0),
    ));
}
examples/3d/atmospheric_fog.rs (line 31)
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
fn setup_camera_fog(mut commands: Commands) {
    commands.spawn((
        Camera3d::default(),
        Transform::from_xyz(-1.0, 0.1, 1.0).looking_at(Vec3::new(0.0, 0.0, 0.0), Vec3::Y),
        DistanceFog {
            color: Color::srgba(0.35, 0.48, 0.66, 1.0),
            directional_light_color: Color::srgba(1.0, 0.95, 0.85, 0.5),
            directional_light_exponent: 30.0,
            falloff: FogFalloff::from_visibility_colors(
                15.0, // distance in world units up to which objects retain visibility (>= 5% contrast)
                Color::srgb(0.35, 0.5, 0.66), // atmospheric extinction color (after light is lost due to absorption by atmospheric particles)
                Color::srgb(0.8, 0.844, 1.0), // atmospheric inscattering color (light gained due to scattering from the sun)
            ),
        },
    ));
}
examples/3d/texture.rs (line 39)
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
fn setup(
    mut commands: Commands,
    asset_server: Res<AssetServer>,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    // load a texture and retrieve its aspect ratio
    let texture_handle = asset_server.load("branding/bevy_logo_dark_big.png");
    let aspect = 0.25;

    // create a new quad mesh. this is what we will apply the texture to
    let quad_width = 8.0;
    let quad_handle = meshes.add(Rectangle::new(quad_width, quad_width * aspect));

    // this material renders the texture normally
    let material_handle = materials.add(StandardMaterial {
        base_color_texture: Some(texture_handle.clone()),
        alpha_mode: AlphaMode::Blend,
        unlit: true,
        ..default()
    });

    // this material modulates the texture to make it red (and slightly transparent)
    let red_material_handle = materials.add(StandardMaterial {
        base_color: Color::srgba(1.0, 0.0, 0.0, 0.5),
        base_color_texture: Some(texture_handle.clone()),
        alpha_mode: AlphaMode::Blend,
        unlit: true,
        ..default()
    });

    // and lets make this one blue! (and also slightly transparent)
    let blue_material_handle = materials.add(StandardMaterial {
        base_color: Color::srgba(0.0, 0.0, 1.0, 0.5),
        base_color_texture: Some(texture_handle),
        alpha_mode: AlphaMode::Blend,
        unlit: true,
        ..default()
    });

    // textured quad - normal
    commands.spawn((
        Mesh3d(quad_handle.clone()),
        MeshMaterial3d(material_handle),
        Transform::from_xyz(0.0, 0.0, 1.5).with_rotation(Quat::from_rotation_x(-PI / 5.0)),
    ));
    // textured quad - modulated
    commands.spawn((
        Mesh3d(quad_handle.clone()),
        MeshMaterial3d(red_material_handle),
        Transform::from_rotation(Quat::from_rotation_x(-PI / 5.0)),
    ));
    // textured quad - modulated
    commands.spawn((
        Mesh3d(quad_handle),
        MeshMaterial3d(blue_material_handle),
        Transform::from_xyz(0.0, 0.0, -1.5).with_rotation(Quat::from_rotation_x(-PI / 5.0)),
    ));
    // camera
    commands.spawn((
        Camera3d::default(),
        Transform::from_xyz(3.0, 5.0, 8.0).looking_at(Vec3::ZERO, Vec3::Y),
    ));
}
examples/ui/transparency_ui.rs (line 49)
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
    commands.spawn(Camera2d);

    let font_handle = asset_server.load("fonts/FiraSans-Bold.ttf");

    commands
        .spawn(Node {
            width: Val::Percent(100.0),
            height: Val::Percent(100.0),
            align_items: AlignItems::Center,
            justify_content: JustifyContent::SpaceAround,
            ..default()
        })
        .with_children(|parent| {
            parent
                .spawn((
                    Button,
                    Node {
                        width: Val::Px(150.0),
                        height: Val::Px(65.0),
                        justify_content: JustifyContent::Center,
                        align_items: AlignItems::Center,
                        ..default()
                    },
                    BackgroundColor(Color::srgb(0.1, 0.5, 0.1)),
                ))
                .with_children(|parent| {
                    parent.spawn((
                        Text::new("Button 1"),
                        TextFont {
                            font: font_handle.clone(),
                            font_size: 33.0,
                            ..default()
                        },
                        // Alpha channel of the color controls transparency.
                        TextColor(Color::srgba(1.0, 1.0, 1.0, 0.2)),
                    ));
                });

            // Button with a different color,
            // to demonstrate the text looks different due to its transparency.
            parent
                .spawn((
                    Button,
                    Node {
                        width: Val::Px(150.0),
                        height: Val::Px(65.0),
                        justify_content: JustifyContent::Center,
                        align_items: AlignItems::Center,
                        ..default()
                    },
                    BackgroundColor(Color::srgb(0.5, 0.1, 0.5)),
                ))
                .with_children(|parent| {
                    parent.spawn((
                        Text::new("Button 2"),
                        TextFont {
                            font: font_handle.clone(),
                            font_size: 33.0,
                            ..default()
                        },
                        // Alpha channel of the color controls transparency.
                        TextColor(Color::srgba(1.0, 1.0, 1.0, 0.2)),
                    ));
                });
        });
}
examples/math/random_sampling.rs (line 75)
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    // Use seeded rng and store it in a resource; this makes the random output reproducible.
    let seeded_rng = ChaCha8Rng::seed_from_u64(19878367467712);
    commands.insert_resource(RandomSource(seeded_rng));

    // Make a plane for establishing space.
    commands.spawn((
        Mesh3d(meshes.add(Plane3d::default().mesh().size(12.0, 12.0))),
        MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))),
        Transform::from_xyz(0.0, -2.5, 0.0),
    ));

    // Store the shape we sample from in a resource:
    let shape = Cuboid::from_length(2.9);
    commands.insert_resource(SampledShape(shape));

    // The sampled shape shown transparently:
    commands.spawn((
        Mesh3d(meshes.add(shape)),
        MeshMaterial3d(materials.add(StandardMaterial {
            base_color: Color::srgba(0.2, 0.1, 0.6, 0.3),
            alpha_mode: AlphaMode::Blend,
            cull_mode: None,
            ..default()
        })),
    ));

    // A light:
    commands.spawn((
        PointLight {
            shadows_enabled: true,
            ..default()
        },
        Transform::from_xyz(4.0, 8.0, 4.0),
    ));

    // A camera:
    commands.spawn((
        Camera3d::default(),
        Transform::from_xyz(-2.0, 3.0, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
    ));

    // Store the mesh and material for sample points in resources:
    commands.insert_resource(PointMesh(
        meshes.add(
            Sphere::new(0.03)
                .mesh()
                .kind(SphereKind::Ico { subdivisions: 3 }),
        ),
    ));
    commands.insert_resource(PointMaterial(materials.add(StandardMaterial {
        base_color: Color::srgb(1.0, 0.8, 0.8),
        metallic: 0.8,
        ..default()
    })));

    // Instructions for the example:
    commands.spawn((
        Text::new(
            "Controls:\n\
            M: Toggle between sampling boundary and interior.\n\
            R: Restart (erase all samples).\n\
            S: Add one random sample.\n\
            D: Add 100 random samples.\n\
            Rotate camera by holding left mouse and panning left/right.",
        ),
        Node {
            position_type: PositionType::Absolute,
            top: Val::Px(12.0),
            left: Val::Px(12.0),
            ..default()
        },
    ));

    // The mode starts with interior points.
    commands.insert_resource(Mode::Interior);

    // Starting mouse-pressed state is false.
    commands.insert_resource(MousePressed(false));
}
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
13
    const RED: Color = Color::srgb(1.0, 0.0, 0.0);
    const GREEN: Color = Color::srgb(0.0, 1.0, 0.0);
More examples
Hide additional examples
examples/games/game_menu.rs (line 7)
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
const TEXT_COLOR: Color = Color::srgb(0.9, 0.9, 0.9);

// Enum that will be used as a global state for the game
#[derive(Clone, Copy, Default, Eq, PartialEq, Debug, Hash, States)]
enum GameState {
    #[default]
    Splash,
    Menu,
    Game,
}

// One of the two settings that can be set through the menu. It will be a resource in the app
#[derive(Resource, Debug, Component, PartialEq, Eq, Clone, Copy)]
enum DisplayQuality {
    Low,
    Medium,
    High,
}

// One of the two settings that can be set through the menu. It will be a resource in the app
#[derive(Resource, Debug, Component, PartialEq, Eq, Clone, Copy)]
struct Volume(u32);

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        // Insert as resource the initial value for the settings resources
        .insert_resource(DisplayQuality::Medium)
        .insert_resource(Volume(7))
        // Declare the game state, whose starting value is determined by the `Default` trait
        .init_state::<GameState>()
        .add_systems(Startup, setup)
        // Adds the plugins for each state
        .add_plugins((splash::splash_plugin, menu::menu_plugin, game::game_plugin))
        .run();
}

fn setup(mut commands: Commands) {
    commands.spawn(Camera2d);
}

mod splash {
    use bevy::prelude::*;

    use super::{despawn_screen, GameState};

    // This plugin will display a splash screen with Bevy logo for 1 second before switching to the menu
    pub fn splash_plugin(app: &mut App) {
        // As this plugin is managing the splash screen, it will focus on the state `GameState::Splash`
        app
            // When entering the state, spawn everything needed for this screen
            .add_systems(OnEnter(GameState::Splash), splash_setup)
            // While in this state, run the `countdown` system
            .add_systems(Update, countdown.run_if(in_state(GameState::Splash)))
            // When exiting the state, despawn everything that was spawned for this screen
            .add_systems(OnExit(GameState::Splash), despawn_screen::<OnSplashScreen>);
    }

    // Tag component used to tag entities added on the splash screen
    #[derive(Component)]
    struct OnSplashScreen;

    // Newtype to use a `Timer` for this screen as a resource
    #[derive(Resource, Deref, DerefMut)]
    struct SplashTimer(Timer);

    fn splash_setup(mut commands: Commands, asset_server: Res<AssetServer>) {
        let icon = asset_server.load("branding/icon.png");
        // Display the logo
        commands
            .spawn((
                Node {
                    align_items: AlignItems::Center,
                    justify_content: JustifyContent::Center,
                    width: Val::Percent(100.0),
                    height: Val::Percent(100.0),
                    ..default()
                },
                OnSplashScreen,
            ))
            .with_children(|parent| {
                parent.spawn((
                    ImageNode::new(icon),
                    Node {
                        // This will set the logo to be 200px wide, and auto adjust its height
                        width: Val::Px(200.0),
                        ..default()
                    },
                ));
            });
        // Insert the timer as a resource
        commands.insert_resource(SplashTimer(Timer::from_seconds(1.0, TimerMode::Once)));
    }

    // Tick the timer, and change state when finished
    fn countdown(
        mut game_state: ResMut<NextState<GameState>>,
        time: Res<Time>,
        mut timer: ResMut<SplashTimer>,
    ) {
        if timer.tick(time.delta()).finished() {
            game_state.set(GameState::Menu);
        }
    }
}

mod game {
    use bevy::{
        color::palettes::basic::{BLUE, LIME},
        prelude::*,
    };

    use super::{despawn_screen, DisplayQuality, GameState, Volume, TEXT_COLOR};

    // This plugin will contain the game. In this case, it's just be a screen that will
    // display the current settings for 5 seconds before returning to the menu
    pub fn game_plugin(app: &mut App) {
        app.add_systems(OnEnter(GameState::Game), game_setup)
            .add_systems(Update, game.run_if(in_state(GameState::Game)))
            .add_systems(OnExit(GameState::Game), despawn_screen::<OnGameScreen>);
    }

    // Tag component used to tag entities added on the game screen
    #[derive(Component)]
    struct OnGameScreen;

    #[derive(Resource, Deref, DerefMut)]
    struct GameTimer(Timer);

    fn game_setup(
        mut commands: Commands,
        display_quality: Res<DisplayQuality>,
        volume: Res<Volume>,
    ) {
        commands
            .spawn((
                Node {
                    width: Val::Percent(100.0),
                    height: Val::Percent(100.0),
                    // center children
                    align_items: AlignItems::Center,
                    justify_content: JustifyContent::Center,
                    ..default()
                },
                OnGameScreen,
            ))
            .with_children(|parent| {
                // First create a `Node` for centering what we want to display
                parent
                    .spawn((
                        Node {
                            // This will display its children in a column, from top to bottom
                            flex_direction: FlexDirection::Column,
                            // `align_items` will align children on the cross axis. Here the main axis is
                            // vertical (column), so the cross axis is horizontal. This will center the
                            // children
                            align_items: AlignItems::Center,
                            ..default()
                        },
                        BackgroundColor(Color::BLACK),
                    ))
                    .with_children(|p| {
                        p.spawn((
                            Text::new("Will be back to the menu shortly..."),
                            TextFont {
                                font_size: 67.0,
                                ..default()
                            },
                            TextColor(TEXT_COLOR),
                            Node {
                                margin: UiRect::all(Val::Px(50.0)),
                                ..default()
                            },
                        ));
                        p.spawn((
                            Text::default(),
                            Node {
                                margin: UiRect::all(Val::Px(50.0)),
                                ..default()
                            },
                        ))
                        .with_children(|p| {
                            p.spawn((
                                TextSpan(format!("quality: {:?}", *display_quality)),
                                TextFont {
                                    font_size: 50.0,
                                    ..default()
                                },
                                TextColor(BLUE.into()),
                            ));
                            p.spawn((
                                TextSpan::new(" - "),
                                TextFont {
                                    font_size: 50.0,
                                    ..default()
                                },
                                TextColor(TEXT_COLOR),
                            ));
                            p.spawn((
                                TextSpan(format!("volume: {:?}", *volume)),
                                TextFont {
                                    font_size: 50.0,
                                    ..default()
                                },
                                TextColor(LIME.into()),
                            ));
                        });
                    });
            });
        // Spawn a 5 seconds timer to trigger going back to the menu
        commands.insert_resource(GameTimer(Timer::from_seconds(5.0, TimerMode::Once)));
    }

    // Tick the timer, and change state when finished
    fn game(
        time: Res<Time>,
        mut game_state: ResMut<NextState<GameState>>,
        mut timer: ResMut<GameTimer>,
    ) {
        if timer.tick(time.delta()).finished() {
            game_state.set(GameState::Menu);
        }
    }
}

mod menu {
    use bevy::{app::AppExit, color::palettes::css::CRIMSON, prelude::*};

    use super::{despawn_screen, DisplayQuality, GameState, Volume, TEXT_COLOR};

    // This plugin manages the menu, with 5 different screens:
    // - a main menu with "New Game", "Settings", "Quit"
    // - a settings menu with two submenus and a back button
    // - two settings screen with a setting that can be set and a back button
    pub fn menu_plugin(app: &mut App) {
        app
            // At start, the menu is not enabled. This will be changed in `menu_setup` when
            // entering the `GameState::Menu` state.
            // Current screen in the menu is handled by an independent state from `GameState`
            .init_state::<MenuState>()
            .add_systems(OnEnter(GameState::Menu), menu_setup)
            // Systems to handle the main menu screen
            .add_systems(OnEnter(MenuState::Main), main_menu_setup)
            .add_systems(OnExit(MenuState::Main), despawn_screen::<OnMainMenuScreen>)
            // Systems to handle the settings menu screen
            .add_systems(OnEnter(MenuState::Settings), settings_menu_setup)
            .add_systems(
                OnExit(MenuState::Settings),
                despawn_screen::<OnSettingsMenuScreen>,
            )
            // Systems to handle the display settings screen
            .add_systems(
                OnEnter(MenuState::SettingsDisplay),
                display_settings_menu_setup,
            )
            .add_systems(
                Update,
                (setting_button::<DisplayQuality>.run_if(in_state(MenuState::SettingsDisplay)),),
            )
            .add_systems(
                OnExit(MenuState::SettingsDisplay),
                despawn_screen::<OnDisplaySettingsMenuScreen>,
            )
            // Systems to handle the sound settings screen
            .add_systems(OnEnter(MenuState::SettingsSound), sound_settings_menu_setup)
            .add_systems(
                Update,
                setting_button::<Volume>.run_if(in_state(MenuState::SettingsSound)),
            )
            .add_systems(
                OnExit(MenuState::SettingsSound),
                despawn_screen::<OnSoundSettingsMenuScreen>,
            )
            // Common systems to all screens that handles buttons behavior
            .add_systems(
                Update,
                (menu_action, button_system).run_if(in_state(GameState::Menu)),
            );
    }

    // State used for the current menu screen
    #[derive(Clone, Copy, Default, Eq, PartialEq, Debug, Hash, States)]
    enum MenuState {
        Main,
        Settings,
        SettingsDisplay,
        SettingsSound,
        #[default]
        Disabled,
    }

    // Tag component used to tag entities added on the main menu screen
    #[derive(Component)]
    struct OnMainMenuScreen;

    // Tag component used to tag entities added on the settings menu screen
    #[derive(Component)]
    struct OnSettingsMenuScreen;

    // Tag component used to tag entities added on the display settings menu screen
    #[derive(Component)]
    struct OnDisplaySettingsMenuScreen;

    // Tag component used to tag entities added on the sound settings menu screen
    #[derive(Component)]
    struct OnSoundSettingsMenuScreen;

    const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15);
    const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25);
    const HOVERED_PRESSED_BUTTON: Color = Color::srgb(0.25, 0.65, 0.25);
    const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35);
examples/games/stepping.rs (line 88)
88
const FONT_COLOR: Color = Color::srgb(0.2, 0.2, 0.2);
examples/math/sampling_primitives.rs (line 64)
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
const SKY_COLOR: Color = Color::srgb(0.02, 0.06, 0.15);

const SMALL_3D: f32 = 0.5;
const BIG_3D: f32 = 1.0;

// primitives

const CUBOID: Cuboid = Cuboid {
    half_size: Vec3::new(SMALL_3D, BIG_3D, SMALL_3D),
};

const SPHERE: Sphere = Sphere {
    radius: 1.5 * SMALL_3D,
};

const TRIANGLE_3D: Triangle3d = Triangle3d {
    vertices: [
        Vec3::new(BIG_3D, -BIG_3D * 0.5, 0.0),
        Vec3::new(0.0, BIG_3D, 0.0),
        Vec3::new(-BIG_3D, -BIG_3D * 0.5, 0.0),
    ],
};

const CAPSULE_3D: Capsule3d = Capsule3d {
    radius: SMALL_3D,
    half_length: SMALL_3D,
};

const CYLINDER: Cylinder = Cylinder {
    radius: SMALL_3D,
    half_height: SMALL_3D,
};

const TETRAHEDRON: Tetrahedron = Tetrahedron {
    vertices: [
        Vec3::new(-BIG_3D, -BIG_3D * 0.67, BIG_3D * 0.5),
        Vec3::new(BIG_3D, -BIG_3D * 0.67, BIG_3D * 0.5),
        Vec3::new(0.0, -BIG_3D * 0.67, -BIG_3D * 1.17),
        Vec3::new(0.0, BIG_3D, 0.0),
    ],
};

// Components, Resources

/// Resource for the random sampling mode, telling whether to sample the interior or the boundary.
#[derive(Resource)]
enum SamplingMode {
    Interior,
    Boundary,
}

/// Resource for storing whether points should spawn by themselves
#[derive(Resource)]
enum SpawningMode {
    Manual,
    Automatic,
}

/// Resource for tracking how many points should be spawned
#[derive(Resource)]
struct SpawnQueue(usize);

#[derive(Resource)]
struct PointCounter(usize);

/// Resource storing the shapes being sampled and their translations.
#[derive(Resource)]
struct SampledShapes(Vec<(Shape, Vec3)>);

impl SampledShapes {
    fn new() -> Self {
        let shapes = Shape::list_all_shapes();

        let n_shapes = shapes.len();

        let translations =
            (0..n_shapes).map(|i| (i as f32 - n_shapes as f32 / 2.0) * DISTANCE_BETWEEN_SHAPES);

        SampledShapes(shapes.into_iter().zip(translations).collect())
    }
}

/// Enum listing the shapes that can be sampled
#[derive(Clone, Copy)]
enum Shape {
    Cuboid,
    Sphere,
    Capsule,
    Cylinder,
    Tetrahedron,
    Triangle,
}
struct ShapeMeshBuilder {
    shape: Shape,
}

impl Shape {
    /// Return a vector containing all implemented shapes
    fn list_all_shapes() -> Vec<Shape> {
        vec![
            Shape::Cuboid,
            Shape::Sphere,
            Shape::Capsule,
            Shape::Cylinder,
            Shape::Tetrahedron,
            Shape::Triangle,
        ]
    }
}

impl ShapeSample for Shape {
    type Output = Vec3;
    fn sample_interior<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec3 {
        match self {
            Shape::Cuboid => CUBOID.sample_interior(rng),
            Shape::Sphere => SPHERE.sample_interior(rng),
            Shape::Capsule => CAPSULE_3D.sample_interior(rng),
            Shape::Cylinder => CYLINDER.sample_interior(rng),
            Shape::Tetrahedron => TETRAHEDRON.sample_interior(rng),
            Shape::Triangle => TRIANGLE_3D.sample_interior(rng),
        }
    }

    fn sample_boundary<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::Output {
        match self {
            Shape::Cuboid => CUBOID.sample_boundary(rng),
            Shape::Sphere => SPHERE.sample_boundary(rng),
            Shape::Capsule => CAPSULE_3D.sample_boundary(rng),
            Shape::Cylinder => CYLINDER.sample_boundary(rng),
            Shape::Tetrahedron => TETRAHEDRON.sample_boundary(rng),
            Shape::Triangle => TRIANGLE_3D.sample_boundary(rng),
        }
    }
}

impl Meshable for Shape {
    type Output = ShapeMeshBuilder;

    fn mesh(&self) -> Self::Output {
        ShapeMeshBuilder { shape: *self }
    }
}

impl MeshBuilder for ShapeMeshBuilder {
    fn build(&self) -> Mesh {
        match self.shape {
            Shape::Cuboid => CUBOID.mesh().into(),
            Shape::Sphere => SPHERE.mesh().into(),
            Shape::Capsule => CAPSULE_3D.mesh().into(),
            Shape::Cylinder => CYLINDER.mesh().into(),
            Shape::Tetrahedron => TETRAHEDRON.mesh().into(),
            Shape::Triangle => TRIANGLE_3D.mesh().into(),
        }
    }
}

/// The source of randomness used by this example.
#[derive(Resource)]
struct RandomSource(ChaCha8Rng);

/// A container for the handle storing the mesh used to display sampled points as spheres.
#[derive(Resource)]
struct PointMesh(Handle<Mesh>);

/// A container for the handle storing the material used to display sampled points.
#[derive(Resource)]
struct PointMaterial {
    interior: Handle<StandardMaterial>,
    boundary: Handle<StandardMaterial>,
}

/// Marker component for sampled points.
#[derive(Component)]
struct SamplePoint;

/// Component for animating the spawn animation of lights.
#[derive(Component)]
struct SpawningPoint {
    progress: f32,
}

/// Marker component for lights which should change intensity.
#[derive(Component)]
struct DespawningPoint {
    progress: f32,
}

/// Marker component for lights which should change intensity.
#[derive(Component)]
struct FireflyLights;

/// The pressed state of the mouse, used for camera motion.
#[derive(Resource)]
struct MousePressed(bool);

/// Camera movement component.
#[derive(Component)]
struct CameraRig {
    /// Rotation around the vertical axis of the camera (radians).
    /// Positive changes makes the camera look more from the right.
    pub yaw: f32,
    /// Rotation around the horizontal axis of the camera (radians) (-pi/2; pi/2).
    /// Positive looks down from above.
    pub pitch: f32,
    /// Distance from the center, smaller distance causes more zoom.
    pub distance: f32,
    /// Location in 3D space at which the camera is looking and around which it is orbiting.
    pub target: Vec3,
}

fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    shapes: Res<SampledShapes>,
) {
    // Use seeded rng and store it in a resource; this makes the random output reproducible.
    let seeded_rng = ChaCha8Rng::seed_from_u64(4); // Chosen by a fair die roll, guaranteed to be random.
    commands.insert_resource(RandomSource(seeded_rng));

    // Make a plane for establishing space.
    commands.spawn((
        Mesh3d(meshes.add(Plane3d::default().mesh().size(20.0, 20.0))),
        MeshMaterial3d(materials.add(StandardMaterial {
            base_color: Color::srgb(0.3, 0.5, 0.3),
            perceptual_roughness: 0.95,
            metallic: 0.0,
            ..default()
        })),
        Transform::from_xyz(0.0, -2.5, 0.0),
    ));

    let shape_material = materials.add(StandardMaterial {
        base_color: Color::srgba(0.2, 0.1, 0.6, 0.3),
        reflectance: 0.0,
        alpha_mode: AlphaMode::Blend,
        cull_mode: None,
        ..default()
    });

    // Spawn shapes to be sampled
    for (shape, translation) in shapes.0.iter() {
        // The sampled shape shown transparently:
        commands.spawn((
            Mesh3d(meshes.add(shape.mesh())),
            MeshMaterial3d(shape_material.clone()),
            Transform::from_translation(*translation),
        ));

        // Lights which work as the bulk lighting of the fireflies:
        commands.spawn((
            PointLight {
                range: 4.0,
                radius: 0.6,
                intensity: 1.0,
                shadows_enabled: false,
                color: Color::LinearRgba(INSIDE_POINT_COLOR),
                ..default()
            },
            Transform::from_translation(*translation),
            FireflyLights,
        ));
    }

    // Global light:
    commands.spawn((
        PointLight {
            color: SKY_COLOR,
            intensity: 2_000.0,
            shadows_enabled: false,
            ..default()
        },
        Transform::from_xyz(4.0, 8.0, 4.0),
    ));

    // A camera:
    commands.spawn((
        Camera3d::default(),
        Camera {
            hdr: true, // HDR is required for bloom
            clear_color: ClearColorConfig::Custom(SKY_COLOR),
            ..default()
        },
        Tonemapping::TonyMcMapface,
        Transform::from_xyz(-2.0, 3.0, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
        Bloom::NATURAL,
        CameraRig {
            yaw: 0.56,
            pitch: 0.45,
            distance: 8.0,
            target: Vec3::ZERO,
        },
    ));

    // Store the mesh and material for sample points in resources:
    commands.insert_resource(PointMesh(
        meshes.add(Sphere::new(0.03).mesh().ico(1).unwrap()),
    ));
    commands.insert_resource(PointMaterial {
        interior: materials.add(StandardMaterial {
            base_color: Color::BLACK,
            reflectance: 0.05,
            emissive: 2.5 * INSIDE_POINT_COLOR,
            ..default()
        }),
        boundary: materials.add(StandardMaterial {
            base_color: Color::BLACK,
            reflectance: 0.05,
            emissive: 1.5 * BOUNDARY_POINT_COLOR,
            ..default()
        }),
    });

    // Instructions for the example:
    commands.spawn((
        Text::new(
            "Controls:\n\
            M: Toggle between sampling boundary and interior.\n\
            A: Toggle automatic spawning & despawning of points.\n\
            R: Restart (erase all samples).\n\
            S: Add one random sample.\n\
            D: Add 100 random samples.\n\
            Rotate camera by holding left mouse and panning.\n\
            Zoom camera by scrolling via mouse or +/-.\n\
            Move camera by L/R arrow keys.\n\
            Tab: Toggle this text",
        ),
        Node {
            position_type: PositionType::Absolute,
            top: Val::Px(12.0),
            left: Val::Px(12.0),
            ..default()
        },
    ));

    // No points are scheduled to spawn initially.
    commands.insert_resource(SpawnQueue(0));

    // No points have been spawned initially.
    commands.insert_resource(PointCounter(0));

    // The mode starts with interior points.
    commands.insert_resource(SamplingMode::Interior);

    // Points spawn automatically by default.
    commands.insert_resource(SpawningMode::Automatic);

    // Starting mouse-pressed state is false.
    commands.insert_resource(MousePressed(false));
}
examples/ui/display_and_visibility.rs (line 10)
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
const HIDDEN_COLOR: Color = Color::srgb(1.0, 0.7, 0.7);

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        // Only run the app when there is user input. This will significantly reduce CPU/GPU use.
        .insert_resource(WinitSettings::desktop_app())
        .add_systems(Startup, setup)
        .add_systems(
            Update,
            (
                buttons_handler::<Display>,
                buttons_handler::<Visibility>,
                text_hover,
            ),
        )
        .run();
}

#[derive(Component)]
struct Target<T> {
    id: Entity,
    phantom: std::marker::PhantomData<T>,
}

impl<T> Target<T> {
    fn new(id: Entity) -> Self {
        Self {
            id,
            phantom: std::marker::PhantomData,
        }
    }
}

trait TargetUpdate {
    type TargetComponent: Component;
    const NAME: &'static str;
    fn update_target(&self, target: &mut Self::TargetComponent) -> String;
}

impl TargetUpdate for Target<Display> {
    type TargetComponent = Node;
    const NAME: &'static str = "Display";
    fn update_target(&self, node: &mut Self::TargetComponent) -> String {
        node.display = match node.display {
            Display::Flex => Display::None,
            Display::None => Display::Flex,
            Display::Block | Display::Grid => unreachable!(),
        };
        format!("{}::{:?} ", Self::NAME, node.display)
    }
}

impl TargetUpdate for Target<Visibility> {
    type TargetComponent = Visibility;
    const NAME: &'static str = "Visibility";
    fn update_target(&self, visibility: &mut Self::TargetComponent) -> String {
        *visibility = match *visibility {
            Visibility::Inherited => Visibility::Visible,
            Visibility::Visible => Visibility::Hidden,
            Visibility::Hidden => Visibility::Inherited,
        };
        format!("{}::{visibility:?}", Self::NAME)
    }
}

fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
    let palette: [Color; 4] = PALETTE.map(|hex| Srgba::hex(hex).unwrap().into());

    let text_font = TextFont {
        font: asset_server.load("fonts/FiraSans-Bold.ttf"),
        ..default()
    };

    commands.spawn(Camera2d);
    commands
        .spawn((
            Node {
                width: Val::Percent(100.),
                height: Val::Percent(100.),
                flex_direction: FlexDirection::Column,
                align_items: AlignItems::Center,
                justify_content: JustifyContent::SpaceEvenly,
                ..Default::default()
            },
            BackgroundColor(Color::BLACK),
        ))
        .with_children(|parent| {
            parent.spawn((
                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"),
                text_font.clone(),
                TextLayout::new_with_justify(JustifyText::Center),
                Node {
                    margin: UiRect::bottom(Val::Px(10.)),
                    ..Default::default()
                },
            ));

            parent
                .spawn(Node {
                    width: Val::Percent(100.),
                    ..default()
                })
                .with_children(|parent| {
                    let mut target_ids = vec![];
                    parent
                        .spawn(Node {
                            width: Val::Percent(50.),
                            height: Val::Px(520.),
                            justify_content: JustifyContent::Center,
                            ..default()
                        })
                        .with_children(|parent| {
                            target_ids = spawn_left_panel(parent, &palette);
                        });

                    parent
                        .spawn(Node {
                            width: Val::Percent(50.),
                            justify_content: JustifyContent::Center,
                            ..default()
                        })
                        .with_children(|parent| {
                            spawn_right_panel(parent, text_font, &palette, target_ids);
                        });
                });

            parent
                .spawn(Node {
                    flex_direction: FlexDirection::Row,
                    align_items: AlignItems::Start,
                    justify_content: JustifyContent::Start,
                    column_gap: Val::Px(10.),
                    ..default()
                })
                .with_children(|builder| {
                    let text_font = TextFont {
                        font: asset_server.load("fonts/FiraSans-Bold.ttf"),
                        ..default()
                    };

                    builder.spawn((
                        Text::new("Display::None\nVisibility::Hidden\nVisibility::Inherited"),
                        text_font.clone(),
                        TextColor(HIDDEN_COLOR),
                        TextLayout::new_with_justify(JustifyText::Center),
                    ));
                    builder.spawn((
                        Text::new("-\n-\n-"),
                        text_font.clone(),
                        TextColor(DARK_GRAY.into()),
                        TextLayout::new_with_justify(JustifyText::Center),
                    ));
                    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));
                });
        });
}

fn spawn_left_panel(builder: &mut ChildBuilder, palette: &[Color; 4]) -> Vec<Entity> {
    let mut target_ids = vec![];
    builder
        .spawn((
            Node {
                padding: UiRect::all(Val::Px(10.)),
                ..default()
            },
            BackgroundColor(Color::WHITE),
        ))
        .with_children(|parent| {
            parent
                .spawn((Node::default(), BackgroundColor(Color::BLACK)))
                .with_children(|parent| {
                    let id = parent
                        .spawn((
                            Node {
                                align_items: AlignItems::FlexEnd,
                                justify_content: JustifyContent::FlexEnd,
                                ..default()
                            },
                            BackgroundColor(palette[0]),
                            Outline {
                                width: Val::Px(4.),
                                color: DARK_CYAN.into(),
                                offset: Val::Px(10.),
                            },
                        ))
                        .with_children(|parent| {
                            parent.spawn(Node {
                                width: Val::Px(100.),
                                height: Val::Px(500.),
                                ..default()
                            });

                            let id = parent
                                .spawn((
                                    Node {
                                        height: Val::Px(400.),
                                        align_items: AlignItems::FlexEnd,
                                        justify_content: JustifyContent::FlexEnd,
                                        ..default()
                                    },
                                    BackgroundColor(palette[1]),
                                ))
                                .with_children(|parent| {
                                    parent.spawn(Node {
                                        width: Val::Px(100.),
                                        height: Val::Px(400.),
                                        ..default()
                                    });

                                    let id = parent
                                        .spawn((
                                            Node {
                                                height: Val::Px(300.),
                                                align_items: AlignItems::FlexEnd,
                                                justify_content: JustifyContent::FlexEnd,
                                                ..default()
                                            },
                                            BackgroundColor(palette[2]),
                                        ))
                                        .with_children(|parent| {
                                            parent.spawn(Node {
                                                width: Val::Px(100.),
                                                height: Val::Px(300.),
                                                ..default()
                                            });

                                            let id = parent
                                                .spawn((
                                                    Node {
                                                        width: Val::Px(200.),
                                                        height: Val::Px(200.),
                                                        ..default()
                                                    },
                                                    BackgroundColor(palette[3]),
                                                ))
                                                .id();
                                            target_ids.push(id);
                                        })
                                        .id();
                                    target_ids.push(id);
                                })
                                .id();
                            target_ids.push(id);
                        })
                        .id();
                    target_ids.push(id);
                });
        });
    target_ids
}

fn spawn_right_panel(
    parent: &mut ChildBuilder,
    text_font: TextFont,
    palette: &[Color; 4],
    mut target_ids: Vec<Entity>,
) {
    let spawn_buttons = |parent: &mut ChildBuilder, target_id| {
        spawn_button::<Display>(parent, text_font.clone(), target_id);
        spawn_button::<Visibility>(parent, text_font.clone(), target_id);
    };
    parent
        .spawn((
            Node {
                padding: UiRect::all(Val::Px(10.)),
                ..default()
            },
            BackgroundColor(Color::WHITE),
        ))
        .with_children(|parent| {
            parent
                .spawn((
                    Node {
                        width: Val::Px(500.),
                        height: Val::Px(500.),
                        flex_direction: FlexDirection::Column,
                        align_items: AlignItems::FlexEnd,
                        justify_content: JustifyContent::SpaceBetween,
                        padding: UiRect {
                            left: Val::Px(5.),
                            top: Val::Px(5.),
                            ..default()
                        },
                        ..default()
                    },
                    BackgroundColor(palette[0]),
                    Outline {
                        width: Val::Px(4.),
                        color: DARK_CYAN.into(),
                        offset: Val::Px(10.),
                    },
                ))
                .with_children(|parent| {
                    spawn_buttons(parent, target_ids.pop().unwrap());

                    parent
                        .spawn((
                            Node {
                                width: Val::Px(400.),
                                height: Val::Px(400.),
                                flex_direction: FlexDirection::Column,
                                align_items: AlignItems::FlexEnd,
                                justify_content: JustifyContent::SpaceBetween,
                                padding: UiRect {
                                    left: Val::Px(5.),
                                    top: Val::Px(5.),
                                    ..default()
                                },
                                ..default()
                            },
                            BackgroundColor(palette[1]),
                        ))
                        .with_children(|parent| {
                            spawn_buttons(parent, target_ids.pop().unwrap());

                            parent
                                .spawn((
                                    Node {
                                        width: Val::Px(300.),
                                        height: Val::Px(300.),
                                        flex_direction: FlexDirection::Column,
                                        align_items: AlignItems::FlexEnd,
                                        justify_content: JustifyContent::SpaceBetween,
                                        padding: UiRect {
                                            left: Val::Px(5.),
                                            top: Val::Px(5.),
                                            ..default()
                                        },
                                        ..default()
                                    },
                                    BackgroundColor(palette[2]),
                                ))
                                .with_children(|parent| {
                                    spawn_buttons(parent, target_ids.pop().unwrap());

                                    parent
                                        .spawn((
                                            Node {
                                                width: Val::Px(200.),
                                                height: Val::Px(200.),
                                                align_items: AlignItems::FlexStart,
                                                justify_content: JustifyContent::SpaceBetween,
                                                flex_direction: FlexDirection::Column,
                                                padding: UiRect {
                                                    left: Val::Px(5.),
                                                    top: Val::Px(5.),
                                                    ..default()
                                                },
                                                ..default()
                                            },
                                            BackgroundColor(palette[3]),
                                        ))
                                        .with_children(|parent| {
                                            spawn_buttons(parent, target_ids.pop().unwrap());

                                            parent.spawn(Node {
                                                width: Val::Px(100.),
                                                height: Val::Px(100.),
                                                ..default()
                                            });
                                        });
                                });
                        });
                });
        });
}

fn spawn_button<T>(parent: &mut ChildBuilder, text_font: TextFont, target: Entity)
where
    T: Default + std::fmt::Debug + Send + Sync + 'static,
    Target<T>: TargetUpdate,
{
    parent
        .spawn((
            Button,
            Node {
                align_self: AlignSelf::FlexStart,
                padding: UiRect::axes(Val::Px(5.), Val::Px(1.)),
                ..default()
            },
            BackgroundColor(Color::BLACK.with_alpha(0.5)),
            Target::<T>::new(target),
        ))
        .with_children(|builder| {
            builder.spawn((
                Text(format!("{}::{:?}", Target::<T>::NAME, T::default())),
                text_font,
                TextLayout::new_with_justify(JustifyText::Center),
            ));
        });
}

fn buttons_handler<T>(
    mut left_panel_query: Query<&mut <Target<T> as TargetUpdate>::TargetComponent>,
    mut visibility_button_query: Query<(&Target<T>, &Interaction, &Children), Changed<Interaction>>,
    mut text_query: Query<(&mut Text, &mut TextColor)>,
) where
    T: Send + Sync,
    Target<T>: TargetUpdate + Component,
{
    for (target, interaction, children) in visibility_button_query.iter_mut() {
        if matches!(interaction, Interaction::Pressed) {
            let mut target_value = left_panel_query.get_mut(target.id).unwrap();
            for &child in children {
                if let Ok((mut text, mut text_color)) = text_query.get_mut(child) {
                    **text = target.update_target(target_value.as_mut());
                    text_color.0 = if text.contains("None") || text.contains("Hidden") {
                        Color::srgb(1.0, 0.7, 0.7)
                    } else {
                        Color::WHITE
                    };
                }
            }
        }
    }
}
examples/games/breakout.rs (line 45)
45
46
47
48
49
50
51
const BACKGROUND_COLOR: Color = Color::srgb(0.9, 0.9, 0.9);
const PADDLE_COLOR: Color = Color::srgb(0.3, 0.3, 0.7);
const BALL_COLOR: Color = Color::srgb(1.0, 0.5, 0.5);
const BRICK_COLOR: Color = Color::srgb(0.5, 0.5, 1.0);
const WALL_COLOR: Color = Color::srgb(0.8, 0.8, 0.8);
const TEXT_COLOR: Color = Color::srgb(0.5, 0.5, 1.0);
const 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)
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    mut images: ResMut<Assets<Image>>,
    asset_server: Res<AssetServer>,
) {
    // Plane
    commands.spawn((
        Mesh3d(meshes.add(Plane3d::default().mesh().size(50.0, 50.0))),
        MeshMaterial3d(materials.add(Color::srgb(0.1, 0.2, 0.1))),
    ));

    let cube_material = materials.add(StandardMaterial {
        base_color_texture: Some(images.add(uv_debug_texture())),
        ..default()
    });

    // Cubes
    for i in 0..5 {
        commands.spawn((
            Mesh3d(meshes.add(Cuboid::new(0.25, 0.25, 0.25))),
            MeshMaterial3d(cube_material.clone()),
            Transform::from_xyz(i as f32 * 0.25 - 1.0, 0.125, -i as f32 * 0.5),
        ));
    }

    // Flight Helmet
    commands.spawn(SceneRoot(asset_server.load(
        GltfAssetLabel::Scene(0).from_asset("models/FlightHelmet/FlightHelmet.gltf"),
    )));

    // Light
    commands.spawn((
        DirectionalLight {
            illuminance: light_consts::lux::FULL_DAYLIGHT,
            shadows_enabled: true,
            ..default()
        },
        Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, PI * -0.15, PI * -0.15)),
        CascadeShadowConfigBuilder {
            maximum_distance: 3.0,
            first_cascade_far_bound: 0.9,
            ..default()
        }
        .build(),
    ));

    // Camera
    commands.spawn((
        Camera3d::default(),
        Camera {
            hdr: true,
            ..default()
        },
        Transform::from_xyz(0.7, 0.7, 1.0).looking_at(Vec3::new(0.0, 0.3, 0.0), Vec3::Y),
        ContrastAdaptiveSharpening {
            enabled: false,
            ..default()
        },
        EnvironmentMapLight {
            diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"),
            specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
            intensity: 150.0,
            ..default()
        },
        DistanceFog {
            color: Color::srgba_u8(43, 44, 47, 255),
            falloff: FogFalloff::Linear {
                start: 1.0,
                end: 4.0,
            },
            ..default()
        },
    ));

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

    // cube
    commands.spawn((
        Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
        MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))),
        Transform::from_xyz(0.0, 0.5, 0.0),
        Cube(1.0),
    ));

    // light
    commands.spawn((
        PointLight {
            shadows_enabled: true,
            ..default()
        },
        Transform::from_xyz(4.0, 8.0, 4.0),
    ));

    // camera
    commands.spawn((
        Camera3d::default(),
        Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y),
    ));
}
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)
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
fn mouse_handler(
    mut commands: Commands,
    args: Res<Args>,
    time: Res<Time>,
    mouse_button_input: Res<ButtonInput<MouseButton>>,
    window: Single<&Window>,
    bird_resources: ResMut<BirdResources>,
    mut counter: ResMut<BevyCounter>,
    mut rng: Local<Option<ChaCha8Rng>>,
    mut wave: Local<usize>,
) {
    if rng.is_none() {
        // We're seeding the PRNG here to make this example deterministic for testing purposes.
        // This isn't strictly required in practical use unless you need your app to be deterministic.
        *rng = Some(ChaCha8Rng::seed_from_u64(42));
    }
    let rng = rng.as_mut().unwrap();

    if mouse_button_input.just_released(MouseButton::Left) {
        counter.color = Color::linear_rgb(rng.gen(), rng.gen(), rng.gen());
    }

    if mouse_button_input.pressed(MouseButton::Left) {
        let spawn_count = (BIRDS_PER_SECOND as f64 * time.delta_secs_f64()) as usize;
        spawn_birds(
            &mut commands,
            args.into_inner(),
            &window.resolution,
            &mut counter,
            spawn_count,
            bird_resources.into_inner(),
            None,
            *wave,
        );
        *wave += 1;
    }
}

fn bird_velocity_transform(
    half_extents: Vec2,
    mut translation: Vec3,
    velocity_rng: &mut ChaCha8Rng,
    waves: Option<usize>,
    dt: f32,
) -> (Transform, Vec3) {
    let mut velocity = Vec3::new(MAX_VELOCITY * (velocity_rng.gen::<f32>() - 0.5), 0., 0.);

    if let Some(waves) = waves {
        // Step the movement and handle collisions as if the wave had been spawned at fixed time intervals
        // and with dt-spaced frames of simulation
        for _ in 0..(waves * (FIXED_TIMESTEP / dt).round() as usize) {
            step_movement(&mut translation, &mut velocity, dt);
            handle_collision(half_extents, &translation, &mut velocity);
        }
    }
    (
        Transform::from_translation(translation).with_scale(Vec3::splat(BIRD_SCALE)),
        velocity,
    )
}

const FIXED_DELTA_TIME: f32 = 1.0 / 60.0;

#[allow(clippy::too_many_arguments)]
fn spawn_birds(
    commands: &mut Commands,
    args: &Args,
    primary_window_resolution: &WindowResolution,
    counter: &mut BevyCounter,
    spawn_count: usize,
    bird_resources: &mut BirdResources,
    waves_to_simulate: Option<usize>,
    wave: usize,
) {
    let bird_x = (primary_window_resolution.width() / -2.) + HALF_BIRD_SIZE;
    let bird_y = (primary_window_resolution.height() / 2.) - HALF_BIRD_SIZE;

    let half_extents = 0.5 * primary_window_resolution.size();

    let color = counter.color;
    let current_count = counter.count;

    match args.mode {
        Mode::Sprite => {
            let batch = (0..spawn_count)
                .map(|count| {
                    let bird_z = if args.ordered_z {
                        (current_count + count) as f32 * 0.00001
                    } else {
                        bird_resources.transform_rng.gen::<f32>()
                    };

                    let (transform, velocity) = bird_velocity_transform(
                        half_extents,
                        Vec3::new(bird_x, bird_y, bird_z),
                        &mut bird_resources.velocity_rng,
                        waves_to_simulate,
                        FIXED_DELTA_TIME,
                    );

                    let color = if args.vary_per_instance {
                        Color::linear_rgb(
                            bird_resources.color_rng.gen(),
                            bird_resources.color_rng.gen(),
                            bird_resources.color_rng.gen(),
                        )
                    } else {
                        color
                    };
                    (
                        Sprite {
                            image: bird_resources
                                .textures
                                .choose(&mut bird_resources.material_rng)
                                .unwrap()
                                .clone(),
                            color,
                            ..default()
                        },
                        transform,
                        Bird { velocity },
                    )
                })
                .collect::<Vec<_>>();
            commands.spawn_batch(batch);
        }
        Mode::Mesh2d => {
            let batch = (0..spawn_count)
                .map(|count| {
                    let bird_z = if args.ordered_z {
                        (current_count + count) as f32 * 0.00001
                    } else {
                        bird_resources.transform_rng.gen::<f32>()
                    };

                    let (transform, velocity) = bird_velocity_transform(
                        half_extents,
                        Vec3::new(bird_x, bird_y, bird_z),
                        &mut bird_resources.velocity_rng,
                        waves_to_simulate,
                        FIXED_DELTA_TIME,
                    );

                    let material =
                        if args.vary_per_instance || args.material_texture_count > args.waves {
                            bird_resources
                                .materials
                                .choose(&mut bird_resources.material_rng)
                                .unwrap()
                                .clone()
                        } else {
                            bird_resources.materials[wave % bird_resources.materials.len()].clone()
                        };
                    (
                        Mesh2d(bird_resources.quad.clone()),
                        MeshMaterial2d(material),
                        transform,
                        Bird { velocity },
                    )
                })
                .collect::<Vec<_>>();
            commands.spawn_batch(batch);
        }
    }

    counter.count += spawn_count;
    counter.color = Color::linear_rgb(
        bird_resources.color_rng.gen(),
        bird_resources.color_rng.gen(),
        bird_resources.color_rng.gen(),
    );
}
More examples
Hide additional examples
examples/2d/cpu_draw.rs (line 97)
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
fn draw(
    my_handle: Res<MyProcGenImage>,
    mut images: ResMut<Assets<Image>>,
    // used to keep track of where we are
    mut i: Local<u32>,
    mut draw_color: Local<Color>,
) {
    let mut rng = rand::thread_rng();

    if *i == 0 {
        // Generate a random color on first run.
        *draw_color = Color::linear_rgb(rng.gen(), rng.gen(), rng.gen());
    }

    // Get the image from Bevy's asset storage.
    let image = images.get_mut(&my_handle.0).expect("Image not found");

    // Compute the position of the pixel to draw.

    let center = Vec2::new(IMAGE_WIDTH as f32 / 2.0, IMAGE_HEIGHT as f32 / 2.0);
    let max_radius = IMAGE_HEIGHT.min(IMAGE_WIDTH) as f32 / 2.0;
    let rot_speed = 0.0123;
    let period = 0.12345;

    let r = ops::sin(*i as f32 * period) * max_radius;
    let xy = Vec2::from_angle(*i as f32 * rot_speed) * r + center;
    let (x, y) = (xy.x as u32, xy.y as u32);

    // Get the old color of that pixel.
    let old_color = image.get_color_at(x, y).unwrap();

    // If the old color is our current color, change our drawing color.
    let tolerance = 1.0 / 255.0;
    if old_color.distance(&draw_color) <= tolerance {
        *draw_color = Color::linear_rgb(rng.gen(), rng.gen(), rng.gen());
    }

    // Set the new color, but keep old alpha value from image.
    image
        .set_color_at(x, y, draw_color.with_alpha(old_color.alpha()))
        .unwrap();

    *i += 1;
}
examples/3d/motion_blur.rs (line 80)
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
fn setup_scene(
    asset_server: Res<AssetServer>,
    mut images: ResMut<Assets<Image>>,
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    commands.insert_resource(AmbientLight {
        color: Color::WHITE,
        brightness: 300.0,
    });
    commands.insert_resource(CameraMode::Chase);
    commands.spawn((
        DirectionalLight {
            illuminance: 3_000.0,
            shadows_enabled: true,
            ..default()
        },
        Transform::default().looking_to(Vec3::new(-1.0, -0.7, -1.0), Vec3::X),
    ));
    // Sky
    commands.spawn((
        Mesh3d(meshes.add(Sphere::default())),
        MeshMaterial3d(materials.add(StandardMaterial {
            unlit: true,
            base_color: Color::linear_rgb(0.1, 0.6, 1.0),
            ..default()
        })),
        Transform::default().with_scale(Vec3::splat(-4000.0)),
    ));
    // Ground
    let mut plane: Mesh = Plane3d::default().into();
    let uv_size = 4000.0;
    let uvs = vec![[uv_size, 0.0], [0.0, 0.0], [0.0, uv_size], [uv_size; 2]];
    plane.insert_attribute(Mesh::ATTRIBUTE_UV_0, uvs);
    commands.spawn((
        Mesh3d(meshes.add(plane)),
        MeshMaterial3d(materials.add(StandardMaterial {
            base_color: Color::WHITE,
            perceptual_roughness: 1.0,
            base_color_texture: Some(images.add(uv_debug_texture())),
            ..default()
        })),
        Transform::from_xyz(0.0, -0.65, 0.0).with_scale(Vec3::splat(80.)),
    ));

    spawn_cars(&asset_server, &mut meshes, &mut materials, &mut commands);
    spawn_trees(&mut meshes, &mut materials, &mut commands);
    spawn_barriers(&mut meshes, &mut materials, &mut commands);
}

fn spawn_cars(
    asset_server: &AssetServer,
    meshes: &mut Assets<Mesh>,
    materials: &mut Assets<StandardMaterial>,
    commands: &mut Commands,
) {
    const N_CARS: usize = 20;
    let box_mesh = meshes.add(Cuboid::new(0.3, 0.15, 0.55));
    let cylinder = meshes.add(Cylinder::default());
    let logo = asset_server.load("branding/icon.png");
    let wheel_matl = materials.add(StandardMaterial {
        base_color: Color::WHITE,
        base_color_texture: Some(logo.clone()),
        ..default()
    });

    let mut matl = |color| {
        materials.add(StandardMaterial {
            base_color: color,
            ..default()
        })
    };

    let colors = [
        matl(Color::linear_rgb(1.0, 0.0, 0.0)),
        matl(Color::linear_rgb(1.0, 1.0, 0.0)),
        matl(Color::BLACK),
        matl(Color::linear_rgb(0.0, 0.0, 1.0)),
        matl(Color::linear_rgb(0.0, 1.0, 0.0)),
        matl(Color::linear_rgb(1.0, 0.0, 1.0)),
        matl(Color::linear_rgb(0.5, 0.5, 0.0)),
        matl(Color::linear_rgb(1.0, 0.5, 0.0)),
    ];

    for i in 0..N_CARS {
        let color = colors[i % colors.len()].clone();
        commands
            .spawn((
                Mesh3d(box_mesh.clone()),
                MeshMaterial3d(color.clone()),
                Transform::from_scale(Vec3::splat(0.5)),
                Moves(i as f32 * 2.0),
            ))
            .insert_if(CameraTracked, || i == 0)
            .with_children(|parent| {
                parent.spawn((
                    Mesh3d(box_mesh.clone()),
                    MeshMaterial3d(color),
                    Transform::from_xyz(0.0, 0.08, 0.03).with_scale(Vec3::new(1.0, 1.0, 0.5)),
                ));
                let mut spawn_wheel = |x: f32, z: f32| {
                    parent.spawn((
                        Mesh3d(cylinder.clone()),
                        MeshMaterial3d(wheel_matl.clone()),
                        Transform::from_xyz(0.14 * x, -0.045, 0.15 * z)
                            .with_scale(Vec3::new(0.15, 0.04, 0.15))
                            .with_rotation(Quat::from_rotation_z(std::f32::consts::FRAC_PI_2)),
                        Rotates,
                    ));
                };
                spawn_wheel(1.0, 1.0);
                spawn_wheel(1.0, -1.0);
                spawn_wheel(-1.0, 1.0);
                spawn_wheel(-1.0, -1.0);
            });
    }
}

fn spawn_barriers(
    meshes: &mut Assets<Mesh>,
    materials: &mut Assets<StandardMaterial>,
    commands: &mut Commands,
) {
    const N_CONES: usize = 100;
    let capsule = meshes.add(Capsule3d::default());
    let matl = materials.add(StandardMaterial {
        base_color: Color::srgb_u8(255, 87, 51),
        reflectance: 1.0,
        ..default()
    });
    let mut spawn_with_offset = |offset: f32| {
        for i in 0..N_CONES {
            let pos = race_track_pos(
                offset,
                (i as f32) / (N_CONES as f32) * std::f32::consts::PI * 2.0,
            );
            commands.spawn((
                Mesh3d(capsule.clone()),
                MeshMaterial3d(matl.clone()),
                Transform::from_xyz(pos.x, -0.65, pos.y).with_scale(Vec3::splat(0.07)),
            ));
        }
    };
    spawn_with_offset(0.04);
    spawn_with_offset(-0.04);
}

fn spawn_trees(
    meshes: &mut Assets<Mesh>,
    materials: &mut Assets<StandardMaterial>,
    commands: &mut Commands,
) {
    const N_TREES: usize = 30;
    let capsule = meshes.add(Capsule3d::default());
    let sphere = meshes.add(Sphere::default());
    let leaves = materials.add(Color::linear_rgb(0.0, 1.0, 0.0));
    let trunk = materials.add(Color::linear_rgb(0.4, 0.2, 0.2));

    let mut spawn_with_offset = |offset: f32| {
        for i in 0..N_TREES {
            let pos = race_track_pos(
                offset,
                (i as f32) / (N_TREES as f32) * std::f32::consts::PI * 2.0,
            );
            let [x, z] = pos.into();
            commands.spawn((
                Mesh3d(sphere.clone()),
                MeshMaterial3d(leaves.clone()),
                Transform::from_xyz(x, -0.3, z).with_scale(Vec3::splat(0.3)),
            ));
            commands.spawn((
                Mesh3d(capsule.clone()),
                MeshMaterial3d(trunk.clone()),
                Transform::from_xyz(x, -0.5, z).with_scale(Vec3::new(0.05, 0.3, 0.05)),
            ));
        }
    };
    spawn_with_offset(0.07);
    spawn_with_offset(-0.07);
}
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)
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
fn setup(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>) {
    commands.spawn((
        Mesh3d(meshes.add(Cuboid::new(0.5, 0.5, 0.5))),
        InstanceMaterialData(
            (1..=10)
                .flat_map(|x| (1..=10).map(move |y| (x as f32 / 10.0, y as f32 / 10.0)))
                .map(|(x, y)| InstanceData {
                    position: Vec3::new(x * 10.0 - 5.0, y * 10.0 - 5.0, 0.0),
                    scale: 1.0,
                    color: LinearRgba::from(Color::hsla(x * 360., y, 0.5, 1.0)).to_f32_array(),
                })
                .collect(),
        ),
        // NOTE: Frustum culling is done based on the Aabb of the Mesh and the GlobalTransform.
        // As the cube is at the origin, if its Aabb moves outside the view frustum, all the
        // instanced cubes will be culled.
        // The InstanceMaterialData contains the 'GlobalTransform' information for this custom
        // instancing, and that is not taken into account with the built-in frustum culling.
        // We must disable the built-in frustum culling by adding the `NoFrustumCulling` marker
        // component to avoid incorrect culling.
        NoFrustumCulling,
    ));

    // camera
    commands.spawn((
        Camera3d::default(),
        Transform::from_xyz(0.0, 0.0, 15.0).looking_at(Vec3::ZERO, Vec3::Y),
    ));
}
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)
161
162
163
164
165
166
167
168
169
fn draw_shapes(mut gizmos: Gizmos, mines: Query<&Mine>) {
    for mine in &mines {
        gizmos.circle_2d(
            mine.pos,
            mine.size,
            Color::hsl((mine.size - 4.0) / 16.0 * 360.0, 1.0, 0.8),
        );
    }
}
More examples
Hide additional examples
examples/ui/ui_material.rs (line 88)
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
fn animate(
    mut materials: ResMut<Assets<CustomUiMaterial>>,
    q: Query<&MaterialNode<CustomUiMaterial>>,
    time: Res<Time>,
) {
    let duration = 2.0;
    for handle in &q {
        if let Some(material) = materials.get_mut(handle) {
            // rainbow color effect
            let new_color = Color::hsl((time.elapsed_secs() * 60.0) % 360.0, 1., 0.5);
            let border_color = Color::hsl((time.elapsed_secs() * 60.0) % 360.0, 0.75, 0.75);
            material.color = new_color.to_linear().to_vec4();
            material.slider =
                ((time.elapsed_secs() % (duration * 2.0)) - duration).abs() / duration;
            material.border_color = border_color.to_linear().to_vec4();
        }
    }
}
examples/testbed/2d.rs (line 88)
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
    pub fn setup(
        mut commands: Commands,
        mut meshes: ResMut<Assets<Mesh>>,
        mut materials: ResMut<Assets<ColorMaterial>>,
    ) {
        commands.spawn((Camera2d, StateScoped(super::Scene::Shapes)));

        let shapes = [
            meshes.add(Circle::new(50.0)),
            meshes.add(CircularSector::new(50.0, 1.0)),
            meshes.add(CircularSegment::new(50.0, 1.25)),
            meshes.add(Ellipse::new(25.0, 50.0)),
            meshes.add(Annulus::new(25.0, 50.0)),
            meshes.add(Capsule2d::new(25.0, 50.0)),
            meshes.add(Rhombus::new(75.0, 100.0)),
            meshes.add(Rectangle::new(50.0, 100.0)),
            meshes.add(RegularPolygon::new(50.0, 6)),
            meshes.add(Triangle2d::new(
                Vec2::Y * 50.0,
                Vec2::new(-50.0, -50.0),
                Vec2::new(50.0, -50.0),
            )),
        ];
        let num_shapes = shapes.len();

        for (i, shape) in shapes.into_iter().enumerate() {
            // Distribute colors evenly across the rainbow.
            let color = Color::hsl(360. * i as f32 / num_shapes as f32, 0.95, 0.7);

            commands.spawn((
                Mesh2d(shape),
                MeshMaterial2d(materials.add(color)),
                Transform::from_xyz(
                    // Distribute shapes from -X_EXTENT/2 to +X_EXTENT/2.
                    -X_EXTENT / 2. + i as f32 / (num_shapes - 1) as f32 * X_EXTENT,
                    0.0,
                    0.0,
                ),
                StateScoped(super::Scene::Shapes),
            ));
        }
    }
examples/2d/2d_shapes.rs (line 52)
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<ColorMaterial>>,
) {
    commands.spawn(Camera2d);

    let shapes = [
        meshes.add(Circle::new(50.0)),
        meshes.add(CircularSector::new(50.0, 1.0)),
        meshes.add(CircularSegment::new(50.0, 1.25)),
        meshes.add(Ellipse::new(25.0, 50.0)),
        meshes.add(Annulus::new(25.0, 50.0)),
        meshes.add(Capsule2d::new(25.0, 50.0)),
        meshes.add(Rhombus::new(75.0, 100.0)),
        meshes.add(Rectangle::new(50.0, 100.0)),
        meshes.add(RegularPolygon::new(50.0, 6)),
        meshes.add(Triangle2d::new(
            Vec2::Y * 50.0,
            Vec2::new(-50.0, -50.0),
            Vec2::new(50.0, -50.0),
        )),
    ];
    let num_shapes = shapes.len();

    for (i, shape) in shapes.into_iter().enumerate() {
        // Distribute colors evenly across the rainbow.
        let color = Color::hsl(360. * i as f32 / num_shapes as f32, 0.95, 0.7);

        commands.spawn((
            Mesh2d(shape),
            MeshMaterial2d(materials.add(color)),
            Transform::from_xyz(
                // Distribute shapes from -X_EXTENT/2 to +X_EXTENT/2.
                -X_EXTENT / 2. + i as f32 / (num_shapes - 1) as f32 * X_EXTENT,
                0.0,
                0.0,
            ),
        ));
    }

    #[cfg(not(target_arch = "wasm32"))]
    commands.spawn((
        Text::new("Press space to toggle wireframes"),
        Node {
            position_type: PositionType::Absolute,
            top: Val::Px(12.0),
            left: Val::Px(12.0),
            ..default()
        },
    ));
}
examples/stress_tests/many_buttons.rs (line 136)
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
fn setup_flex(mut commands: Commands, asset_server: Res<AssetServer>, args: Res<Args>) {
    warn!(include_str!("warning_string.txt"));
    let image = if 0 < args.image_freq {
        Some(asset_server.load("branding/icon.png"))
    } else {
        None
    };

    let buttons_f = args.buttons as f32;
    let border = if args.no_borders {
        UiRect::ZERO
    } else {
        UiRect::all(Val::VMin(0.05 * 90. / buttons_f))
    };

    let as_rainbow = |i: usize| Color::hsl((i as f32 / buttons_f) * 360.0, 0.9, 0.8);
    commands.spawn(Camera2d);
    commands
        .spawn(Node {
            flex_direction: FlexDirection::Column,
            justify_content: JustifyContent::Center,
            align_items: AlignItems::Center,
            width: Val::Percent(100.),
            height: Val::Percent(100.),
            ..default()
        })
        .with_children(|commands| {
            for column in 0..args.buttons {
                commands.spawn(Node::default()).with_children(|commands| {
                    for row in 0..args.buttons {
                        let color = as_rainbow(row % column.max(1));
                        let border_color = Color::WHITE.with_alpha(0.5).into();
                        spawn_button(
                            commands,
                            color,
                            buttons_f,
                            column,
                            row,
                            !args.no_text,
                            border,
                            border_color,
                            image
                                .as_ref()
                                .filter(|_| (column + row) % args.image_freq == 0)
                                .cloned(),
                        );
                    }
                });
            }
        });
}

fn setup_grid(mut commands: Commands, asset_server: Res<AssetServer>, args: Res<Args>) {
    warn!(include_str!("warning_string.txt"));
    let image = if 0 < args.image_freq {
        Some(asset_server.load("branding/icon.png"))
    } else {
        None
    };

    let buttons_f = args.buttons as f32;
    let border = if args.no_borders {
        UiRect::ZERO
    } else {
        UiRect::all(Val::VMin(0.05 * 90. / buttons_f))
    };

    let as_rainbow = |i: usize| Color::hsl((i as f32 / buttons_f) * 360.0, 0.9, 0.8);
    commands.spawn(Camera2d);
    commands
        .spawn(Node {
            display: Display::Grid,
            width: Val::Percent(100.),
            height: Val::Percent(100.0),
            grid_template_columns: RepeatedGridTrack::flex(args.buttons as u16, 1.0),
            grid_template_rows: RepeatedGridTrack::flex(args.buttons as u16, 1.0),
            ..default()
        })
        .with_children(|commands| {
            for column in 0..args.buttons {
                for row in 0..args.buttons {
                    let color = as_rainbow(row % column.max(1));
                    let border_color = Color::WHITE.with_alpha(0.5).into();
                    spawn_button(
                        commands,
                        color,
                        buttons_f,
                        column,
                        row,
                        !args.no_text,
                        border,
                        border_color,
                        image
                            .as_ref()
                            .filter(|_| (column + row) % args.image_freq == 0)
                            .cloned(),
                    );
                }
            }
        });
}
examples/stress_tests/many_lights.rs (line 84)
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    warn!(include_str!("warning_string.txt"));

    const LIGHT_RADIUS: f32 = 0.3;
    const LIGHT_INTENSITY: f32 = 1000.0;
    const RADIUS: f32 = 50.0;
    const N_LIGHTS: usize = 100_000;

    commands.spawn((
        Mesh3d(meshes.add(Sphere::new(RADIUS).mesh().ico(9).unwrap())),
        MeshMaterial3d(materials.add(Color::WHITE)),
        Transform::from_scale(Vec3::NEG_ONE),
    ));

    let mesh = meshes.add(Cuboid::default());
    let material = materials.add(StandardMaterial {
        base_color: DEEP_PINK.into(),
        ..default()
    });

    // NOTE: This pattern is good for testing performance of culling as it provides roughly
    // the same number of visible meshes regardless of the viewing angle.
    // NOTE: f64 is used to avoid precision issues that produce visual artifacts in the distribution
    let golden_ratio = 0.5f64 * (1.0f64 + 5.0f64.sqrt());

    // Spawn N_LIGHTS many lights
    commands.spawn_batch((0..N_LIGHTS).map(move |i| {
        let mut rng = thread_rng();

        let spherical_polar_theta_phi = fibonacci_spiral_on_sphere(golden_ratio, i, N_LIGHTS);
        let unit_sphere_p = spherical_polar_to_cartesian(spherical_polar_theta_phi);

        (
            PointLight {
                range: LIGHT_RADIUS,
                intensity: LIGHT_INTENSITY,
                color: Color::hsl(rng.gen_range(0.0..360.0), 1.0, 0.5),
                ..default()
            },
            Transform::from_translation((RADIUS as f64 * unit_sphere_p).as_vec3()),
        )
    }));

    // camera
    match std::env::args().nth(1).as_deref() {
        Some("orthographic") => commands.spawn((
            Camera3d::default(),
            Projection::from(OrthographicProjection {
                scaling_mode: ScalingMode::FixedHorizontal {
                    viewport_width: 20.0,
                },
                ..OrthographicProjection::default_3d()
            }),
        )),
        _ => commands.spawn(Camera3d::default()),
    };

    // add one cube, the only one with strong handles
    // also serves as a reference point during rotation
    commands.spawn((
        Mesh3d(mesh),
        MeshMaterial3d(material),
        Transform {
            translation: Vec3::new(0.0, RADIUS, 0.0),
            scale: Vec3::splat(5.0),
            ..default()
        },
    ));
}
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)
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    window: Query<&Window>,
) {
    // circular base
    commands.spawn((
        Mesh3d(meshes.add(Circle::new(4.0))),
        MeshMaterial3d(materials.add(Color::WHITE)),
        Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
    ));

    // cube
    commands.spawn((
        Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
        MeshMaterial3d(materials.add(Color::WHITE)),
        Transform::from_xyz(0.0, 0.5, 0.0),
    ));

    // lights
    for i in 0..NUM_LIGHTS {
        let angle = (i as f32) / (NUM_LIGHTS as f32) * PI * 2.0;
        commands.spawn((
            PointLight {
                color: Color::hsv(angle.to_degrees(), 1.0, 1.0),
                intensity: 2_000_000.0 / NUM_LIGHTS as f32,
                shadows_enabled: true,
                ..default()
            },
            Transform::from_xyz(sin(angle) * 4.0, 2.0, cos(angle) * 4.0),
        ));
    }

    // cameras
    let window = window.single();
    let width = window.resolution.width() / CAMERA_COLS as f32 * window.resolution.scale_factor();
    let height = window.resolution.height() / CAMERA_ROWS as f32 * window.resolution.scale_factor();
    let mut i = 0;
    for y in 0..CAMERA_COLS {
        for x in 0..CAMERA_ROWS {
            let angle = i as f32 / (CAMERA_ROWS * CAMERA_COLS) as f32 * PI * 2.0;
            commands.spawn((
                Camera3d::default(),
                Camera {
                    viewport: Some(Viewport {
                        physical_position: UVec2::new(
                            (x as f32 * width) as u32,
                            (y as f32 * height) as u32,
                        ),
                        physical_size: UVec2::new(width as u32, height as u32),
                        ..default()
                    }),
                    order: i,
                    ..default()
                },
                Transform::from_xyz(sin(angle) * 4.0, 2.5, cos(angle) * 4.0)
                    .looking_at(Vec3::ZERO, Vec3::Y),
            ));
            i += 1;
        }
    }
}
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,