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.
§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
impl Color
Sourcepub const WHITE: Color
pub const WHITE: Color
A fully white Color::LinearRgba
color with an alpha of 1.0.
Sourcepub const BLACK: Color
pub const BLACK: Color
A fully black Color::LinearRgba
color with an alpha of 1.0.
Sourcepub const NONE: Color
pub const NONE: Color
A fully transparent Color::LinearRgba
color with 0 red, green and blue.
Sourcepub fn to_linear(&self) -> LinearRgba
pub fn to_linear(&self) -> LinearRgba
Return the color as a linear RGBA color.
Examples found in repository?
89fn animate(
90 mut materials: ResMut<Assets<CustomUiMaterial>>,
91 q: Query<&MaterialNode<CustomUiMaterial>>,
92 time: Res<Time>,
93) {
94 let duration = 2.0;
95 for handle in &q {
96 if let Some(material) = materials.get_mut(handle) {
97 // rainbow color effect
98 let new_color = Color::hsl((time.elapsed_secs() * 60.0) % 360.0, 1., 0.5);
99 let border_color = Color::hsl((time.elapsed_secs() * 60.0) % 360.0, 0.75, 0.75);
100 material.color = new_color.to_linear().to_vec4();
101 material.slider.x =
102 ((time.elapsed_secs() % (duration * 2.0)) - duration).abs() / duration;
103 material.border_color = border_color.to_linear().to_vec4();
104 }
105 }
106}
Sourcepub fn to_srgba(&self) -> Srgba
pub fn to_srgba(&self) -> Srgba
Return the color as an SRGBA color.
Examples found in repository?
102fn update_colors(
103 keyboard_input: Res<ButtonInput<KeyCode>>,
104 mut config: ResMut<Wireframe2dConfig>,
105 mut wireframe_colors: Query<&mut Wireframe2dColor>,
106 mut text: Single<&mut Text>,
107) {
108 text.0 = format!(
109 "Controls
110---------------
111Z - Toggle global
112X - Change global color
113C - Change color of the circle wireframe
114
115Wireframe2dConfig
116-------------
117Global: {}
118Color: {:?}",
119 config.global,
120 config.default_color.to_srgba(),
121 );
122
123 // Toggle showing a wireframe on all meshes
124 if keyboard_input.just_pressed(KeyCode::KeyZ) {
125 config.global = !config.global;
126 }
127
128 // Toggle the global wireframe color
129 if keyboard_input.just_pressed(KeyCode::KeyX) {
130 config.default_color = if config.default_color == WHITE.into() {
131 RED.into()
132 } else {
133 WHITE.into()
134 };
135 }
136
137 // Toggle the color of a wireframe using `Wireframe2dColor` and not the global color
138 if keyboard_input.just_pressed(KeyCode::KeyC) {
139 for mut color in &mut wireframe_colors {
140 color.color = if color.color == GREEN.into() {
141 RED.into()
142 } else {
143 GREEN.into()
144 };
145 }
146 }
147}
Sourcepub const fn srgba(red: f32, green: f32, blue: f32, alpha: f32) -> Color
pub const fn srgba(red: f32, green: f32, blue: f32, alpha: f32) -> Color
Creates a new Color
object storing a Srgba
color.
§Arguments
red
- Red channel. [0.0, 1.0]green
- Green channel. [0.0, 1.0]blue
- Blue channel. [0.0, 1.0]alpha
- Alpha channel. [0.0, 1.0]
Examples found in repository?
119fn spawn_coated_glass_bubble_sphere(
120 commands: &mut Commands,
121 materials: &mut Assets<StandardMaterial>,
122 sphere: &Handle<Mesh>,
123) {
124 commands
125 .spawn((
126 Mesh3d(sphere.clone()),
127 MeshMaterial3d(materials.add(StandardMaterial {
128 clearcoat: 1.0,
129 clearcoat_perceptual_roughness: 0.1,
130 metallic: 0.5,
131 perceptual_roughness: 0.1,
132 base_color: Color::srgba(0.9, 0.9, 0.9, 0.3),
133 alpha_mode: AlphaMode::Blend,
134 ..default()
135 })),
136 Transform::from_xyz(-1.0, -1.0, 0.0).with_scale(Vec3::splat(SPHERE_SCALE)),
137 ))
138 .insert(ExampleSphere);
139}
More examples
13fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
14 commands.spawn(Camera2d);
15
16 let sprite_handle = asset_server.load("branding/icon.png");
17
18 commands.spawn((
19 Sprite::from_image(sprite_handle.clone()),
20 Transform::from_xyz(-100.0, 0.0, 0.0),
21 ));
22 commands.spawn((
23 Sprite {
24 image: sprite_handle.clone(),
25 // Alpha channel of the color controls transparency.
26 color: Color::srgba(0.0, 0.0, 1.0, 0.7),
27 ..default()
28 },
29 Transform::from_xyz(0.0, 0.0, 0.1),
30 ));
31 commands.spawn((
32 Sprite {
33 image: sprite_handle,
34 color: Color::srgba(0.0, 1.0, 0.0, 0.3),
35 ..default()
36 },
37 Transform::from_xyz(100.0, 0.0, 0.2),
38 ));
39}
26fn setup_camera_fog(mut commands: Commands) {
27 commands.spawn((
28 Camera3d::default(),
29 Transform::from_xyz(-1.0, 0.1, 1.0).looking_at(Vec3::new(0.0, 0.0, 0.0), Vec3::Y),
30 DistanceFog {
31 color: Color::srgba(0.35, 0.48, 0.66, 1.0),
32 directional_light_color: Color::srgba(1.0, 0.95, 0.85, 0.5),
33 directional_light_exponent: 30.0,
34 falloff: FogFalloff::from_visibility_colors(
35 15.0, // distance in world units up to which objects retain visibility (>= 5% contrast)
36 Color::srgb(0.35, 0.5, 0.66), // atmospheric extinction color (after light is lost due to absorption by atmospheric particles)
37 Color::srgb(0.8, 0.844, 1.0), // atmospheric inscattering color (light gained due to scattering from the sun)
38 ),
39 },
40 ));
41}
15fn setup(
16 mut commands: Commands,
17 asset_server: Res<AssetServer>,
18 mut meshes: ResMut<Assets<Mesh>>,
19 mut materials: ResMut<Assets<StandardMaterial>>,
20) {
21 // load a texture and retrieve its aspect ratio
22 let texture_handle = asset_server.load("branding/bevy_logo_dark_big.png");
23 let aspect = 0.25;
24
25 // create a new quad mesh. this is what we will apply the texture to
26 let quad_width = 8.0;
27 let quad_handle = meshes.add(Rectangle::new(quad_width, quad_width * aspect));
28
29 // this material renders the texture normally
30 let material_handle = materials.add(StandardMaterial {
31 base_color_texture: Some(texture_handle.clone()),
32 alpha_mode: AlphaMode::Blend,
33 unlit: true,
34 ..default()
35 });
36
37 // this material modulates the texture to make it red (and slightly transparent)
38 let red_material_handle = materials.add(StandardMaterial {
39 base_color: Color::srgba(1.0, 0.0, 0.0, 0.5),
40 base_color_texture: Some(texture_handle.clone()),
41 alpha_mode: AlphaMode::Blend,
42 unlit: true,
43 ..default()
44 });
45
46 // and lets make this one blue! (and also slightly transparent)
47 let blue_material_handle = materials.add(StandardMaterial {
48 base_color: Color::srgba(0.0, 0.0, 1.0, 0.5),
49 base_color_texture: Some(texture_handle),
50 alpha_mode: AlphaMode::Blend,
51 unlit: true,
52 ..default()
53 });
54
55 // textured quad - normal
56 commands.spawn((
57 Mesh3d(quad_handle.clone()),
58 MeshMaterial3d(material_handle),
59 Transform::from_xyz(0.0, 0.0, 1.5).with_rotation(Quat::from_rotation_x(-PI / 5.0)),
60 ));
61 // textured quad - modulated
62 commands.spawn((
63 Mesh3d(quad_handle.clone()),
64 MeshMaterial3d(red_material_handle),
65 Transform::from_rotation(Quat::from_rotation_x(-PI / 5.0)),
66 ));
67 // textured quad - modulated
68 commands.spawn((
69 Mesh3d(quad_handle),
70 MeshMaterial3d(blue_material_handle),
71 Transform::from_xyz(0.0, 0.0, -1.5).with_rotation(Quat::from_rotation_x(-PI / 5.0)),
72 ));
73 // camera
74 commands.spawn((
75 Camera3d::default(),
76 Transform::from_xyz(3.0, 5.0, 8.0).looking_at(Vec3::ZERO, Vec3::Y),
77 ));
78}
99fn build_ui(
100 mut commands: Commands,
101 asset_server: Res<AssetServer>,
102 schedules: Res<Schedules>,
103 mut stepping: ResMut<Stepping>,
104 mut state: ResMut<State>,
105) {
106 let mut text_spans = Vec::new();
107 let mut always_run = Vec::new();
108
109 let Ok(schedule_order) = stepping.schedules() else {
110 return;
111 };
112
113 // go through the stepping schedules and construct a list of systems for
114 // each label
115 for label in schedule_order {
116 let schedule = schedules.get(*label).unwrap();
117 text_spans.push((
118 TextSpan(format!("{label:?}\n")),
119 TextFont {
120 font: asset_server.load(FONT_BOLD),
121 ..default()
122 },
123 TextColor(FONT_COLOR),
124 ));
125
126 // grab the list of systems in the schedule, in the order the
127 // single-threaded executor would run them.
128 let Ok(systems) = schedule.systems() else {
129 return;
130 };
131
132 for (node_id, system) in systems {
133 // skip bevy default systems; we don't want to step those
134 if system.name().starts_with("bevy") {
135 always_run.push((*label, node_id));
136 continue;
137 }
138
139 // Add an entry to our systems list so we can find where to draw
140 // the cursor when the stepping cursor is at this system
141 // we add plus 1 to account for the empty root span
142 state.systems.push((*label, node_id, text_spans.len() + 1));
143
144 // Add a text section for displaying the cursor for this system
145 text_spans.push((
146 TextSpan::new(" "),
147 TextFont::default(),
148 TextColor(FONT_COLOR),
149 ));
150
151 // add the name of the system to the ui
152 text_spans.push((
153 TextSpan(format!("{}\n", system.name())),
154 TextFont::default(),
155 TextColor(FONT_COLOR),
156 ));
157 }
158 }
159
160 for (label, node) in always_run.drain(..) {
161 stepping.always_run_node(label, node);
162 }
163
164 commands.spawn((
165 Text::default(),
166 SteppingUi,
167 Node {
168 position_type: PositionType::Absolute,
169 top: state.ui_top,
170 left: state.ui_left,
171 padding: UiRect::all(Val::Px(10.0)),
172 ..default()
173 },
174 BackgroundColor(Color::srgba(1.0, 1.0, 1.0, 0.33)),
175 Visibility::Hidden,
176 Children::spawn(text_spans),
177 ));
178}
14fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
15 commands.spawn(Camera2d);
16
17 let font_handle = asset_server.load("fonts/FiraSans-Bold.ttf");
18
19 commands
20 .spawn(Node {
21 width: Val::Percent(100.0),
22 height: Val::Percent(100.0),
23 align_items: AlignItems::Center,
24 justify_content: JustifyContent::SpaceAround,
25 ..default()
26 })
27 .with_children(|parent| {
28 parent
29 .spawn((
30 Button,
31 Node {
32 width: Val::Px(150.0),
33 height: Val::Px(65.0),
34 justify_content: JustifyContent::Center,
35 align_items: AlignItems::Center,
36 ..default()
37 },
38 BackgroundColor(Color::srgb(0.1, 0.5, 0.1)),
39 ))
40 .with_children(|parent| {
41 parent.spawn((
42 Text::new("Button 1"),
43 TextFont {
44 font: font_handle.clone(),
45 font_size: 33.0,
46 ..default()
47 },
48 // Alpha channel of the color controls transparency.
49 TextColor(Color::srgba(1.0, 1.0, 1.0, 0.2)),
50 ));
51 });
52
53 // Button with a different color,
54 // to demonstrate the text looks different due to its transparency.
55 parent
56 .spawn((
57 Button,
58 Node {
59 width: Val::Px(150.0),
60 height: Val::Px(65.0),
61 justify_content: JustifyContent::Center,
62 align_items: AlignItems::Center,
63 ..default()
64 },
65 BackgroundColor(Color::srgb(0.5, 0.1, 0.5)),
66 ))
67 .with_children(|parent| {
68 parent.spawn((
69 Text::new("Button 2"),
70 TextFont {
71 font: font_handle.clone(),
72 font_size: 33.0,
73 ..default()
74 },
75 // Alpha channel of the color controls transparency.
76 TextColor(Color::srgba(1.0, 1.0, 1.0, 0.2)),
77 ));
78 });
79 });
80}
Sourcepub const fn srgb(red: f32, green: f32, blue: f32) -> Color
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.
§Arguments
red
- Red channel. [0.0, 1.0]green
- Green channel. [0.0, 1.0]blue
- Blue channel. [0.0, 1.0]
Examples found in repository?
More examples
7const TEXT_COLOR: Color = Color::srgb(0.9, 0.9, 0.9);
8
9// Enum that will be used as a global state for the game
10#[derive(Clone, Copy, Default, Eq, PartialEq, Debug, Hash, States)]
11enum GameState {
12 #[default]
13 Splash,
14 Menu,
15 Game,
16}
17
18// One of the two settings that can be set through the menu. It will be a resource in the app
19#[derive(Resource, Debug, Component, PartialEq, Eq, Clone, Copy)]
20enum DisplayQuality {
21 Low,
22 Medium,
23 High,
24}
25
26// One of the two settings that can be set through the menu. It will be a resource in the app
27#[derive(Resource, Debug, Component, PartialEq, Eq, Clone, Copy)]
28struct Volume(u32);
29
30fn main() {
31 App::new()
32 .add_plugins(DefaultPlugins)
33 // Insert as resource the initial value for the settings resources
34 .insert_resource(DisplayQuality::Medium)
35 .insert_resource(Volume(7))
36 // Declare the game state, whose starting value is determined by the `Default` trait
37 .init_state::<GameState>()
38 .add_systems(Startup, setup)
39 // Adds the plugins for each state
40 .add_plugins((splash::splash_plugin, menu::menu_plugin, game::game_plugin))
41 .run();
42}
43
44fn setup(mut commands: Commands) {
45 commands.spawn(Camera2d);
46}
47
48mod splash {
49 use bevy::prelude::*;
50
51 use super::{despawn_screen, GameState};
52
53 // This plugin will display a splash screen with Bevy logo for 1 second before switching to the menu
54 pub fn splash_plugin(app: &mut App) {
55 // As this plugin is managing the splash screen, it will focus on the state `GameState::Splash`
56 app
57 // When entering the state, spawn everything needed for this screen
58 .add_systems(OnEnter(GameState::Splash), splash_setup)
59 // While in this state, run the `countdown` system
60 .add_systems(Update, countdown.run_if(in_state(GameState::Splash)))
61 // When exiting the state, despawn everything that was spawned for this screen
62 .add_systems(OnExit(GameState::Splash), despawn_screen::<OnSplashScreen>);
63 }
64
65 // Tag component used to tag entities added on the splash screen
66 #[derive(Component)]
67 struct OnSplashScreen;
68
69 // Newtype to use a `Timer` for this screen as a resource
70 #[derive(Resource, Deref, DerefMut)]
71 struct SplashTimer(Timer);
72
73 fn splash_setup(mut commands: Commands, asset_server: Res<AssetServer>) {
74 let icon = asset_server.load("branding/icon.png");
75 // Display the logo
76 commands.spawn((
77 Node {
78 align_items: AlignItems::Center,
79 justify_content: JustifyContent::Center,
80 width: Val::Percent(100.0),
81 height: Val::Percent(100.0),
82 ..default()
83 },
84 OnSplashScreen,
85 children![(
86 ImageNode::new(icon),
87 Node {
88 // This will set the logo to be 200px wide, and auto adjust its height
89 width: Val::Px(200.0),
90 ..default()
91 },
92 )],
93 ));
94 // Insert the timer as a resource
95 commands.insert_resource(SplashTimer(Timer::from_seconds(1.0, TimerMode::Once)));
96 }
97
98 // Tick the timer, and change state when finished
99 fn countdown(
100 mut game_state: ResMut<NextState<GameState>>,
101 time: Res<Time>,
102 mut timer: ResMut<SplashTimer>,
103 ) {
104 if timer.tick(time.delta()).finished() {
105 game_state.set(GameState::Menu);
106 }
107 }
108}
109
110mod game {
111 use bevy::{
112 color::palettes::basic::{BLUE, LIME},
113 prelude::*,
114 };
115
116 use super::{despawn_screen, DisplayQuality, GameState, Volume, TEXT_COLOR};
117
118 // This plugin will contain the game. In this case, it's just be a screen that will
119 // display the current settings for 5 seconds before returning to the menu
120 pub fn game_plugin(app: &mut App) {
121 app.add_systems(OnEnter(GameState::Game), game_setup)
122 .add_systems(Update, game.run_if(in_state(GameState::Game)))
123 .add_systems(OnExit(GameState::Game), despawn_screen::<OnGameScreen>);
124 }
125
126 // Tag component used to tag entities added on the game screen
127 #[derive(Component)]
128 struct OnGameScreen;
129
130 #[derive(Resource, Deref, DerefMut)]
131 struct GameTimer(Timer);
132
133 fn game_setup(
134 mut commands: Commands,
135 display_quality: Res<DisplayQuality>,
136 volume: Res<Volume>,
137 ) {
138 commands.spawn((
139 Node {
140 width: Val::Percent(100.0),
141 height: Val::Percent(100.0),
142 // center children
143 align_items: AlignItems::Center,
144 justify_content: JustifyContent::Center,
145 ..default()
146 },
147 OnGameScreen,
148 children![(
149 Node {
150 // This will display its children in a column, from top to bottom
151 flex_direction: FlexDirection::Column,
152 // `align_items` will align children on the cross axis. Here the main axis is
153 // vertical (column), so the cross axis is horizontal. This will center the
154 // children
155 align_items: AlignItems::Center,
156 ..default()
157 },
158 BackgroundColor(Color::BLACK),
159 children![
160 (
161 Text::new("Will be back to the menu shortly..."),
162 TextFont {
163 font_size: 67.0,
164 ..default()
165 },
166 TextColor(TEXT_COLOR),
167 Node {
168 margin: UiRect::all(Val::Px(50.0)),
169 ..default()
170 },
171 ),
172 (
173 Text::default(),
174 Node {
175 margin: UiRect::all(Val::Px(50.0)),
176 ..default()
177 },
178 children![
179 (
180 TextSpan(format!("quality: {:?}", *display_quality)),
181 TextFont {
182 font_size: 50.0,
183 ..default()
184 },
185 TextColor(BLUE.into()),
186 ),
187 (
188 TextSpan::new(" - "),
189 TextFont {
190 font_size: 50.0,
191 ..default()
192 },
193 TextColor(TEXT_COLOR),
194 ),
195 (
196 TextSpan(format!("volume: {:?}", *volume)),
197 TextFont {
198 font_size: 50.0,
199 ..default()
200 },
201 TextColor(LIME.into()),
202 ),
203 ]
204 ),
205 ]
206 )],
207 ));
208 // Spawn a 5 seconds timer to trigger going back to the menu
209 commands.insert_resource(GameTimer(Timer::from_seconds(5.0, TimerMode::Once)));
210 }
211
212 // Tick the timer, and change state when finished
213 fn game(
214 time: Res<Time>,
215 mut game_state: ResMut<NextState<GameState>>,
216 mut timer: ResMut<GameTimer>,
217 ) {
218 if timer.tick(time.delta()).finished() {
219 game_state.set(GameState::Menu);
220 }
221 }
222}
223
224mod menu {
225 use bevy::{
226 app::AppExit,
227 color::palettes::css::CRIMSON,
228 ecs::spawn::{SpawnIter, SpawnWith},
229 prelude::*,
230 };
231
232 use super::{despawn_screen, DisplayQuality, GameState, Volume, TEXT_COLOR};
233
234 // This plugin manages the menu, with 5 different screens:
235 // - a main menu with "New Game", "Settings", "Quit"
236 // - a settings menu with two submenus and a back button
237 // - two settings screen with a setting that can be set and a back button
238 pub fn menu_plugin(app: &mut App) {
239 app
240 // At start, the menu is not enabled. This will be changed in `menu_setup` when
241 // entering the `GameState::Menu` state.
242 // Current screen in the menu is handled by an independent state from `GameState`
243 .init_state::<MenuState>()
244 .add_systems(OnEnter(GameState::Menu), menu_setup)
245 // Systems to handle the main menu screen
246 .add_systems(OnEnter(MenuState::Main), main_menu_setup)
247 .add_systems(OnExit(MenuState::Main), despawn_screen::<OnMainMenuScreen>)
248 // Systems to handle the settings menu screen
249 .add_systems(OnEnter(MenuState::Settings), settings_menu_setup)
250 .add_systems(
251 OnExit(MenuState::Settings),
252 despawn_screen::<OnSettingsMenuScreen>,
253 )
254 // Systems to handle the display settings screen
255 .add_systems(
256 OnEnter(MenuState::SettingsDisplay),
257 display_settings_menu_setup,
258 )
259 .add_systems(
260 Update,
261 (setting_button::<DisplayQuality>.run_if(in_state(MenuState::SettingsDisplay)),),
262 )
263 .add_systems(
264 OnExit(MenuState::SettingsDisplay),
265 despawn_screen::<OnDisplaySettingsMenuScreen>,
266 )
267 // Systems to handle the sound settings screen
268 .add_systems(OnEnter(MenuState::SettingsSound), sound_settings_menu_setup)
269 .add_systems(
270 Update,
271 setting_button::<Volume>.run_if(in_state(MenuState::SettingsSound)),
272 )
273 .add_systems(
274 OnExit(MenuState::SettingsSound),
275 despawn_screen::<OnSoundSettingsMenuScreen>,
276 )
277 // Common systems to all screens that handles buttons behavior
278 .add_systems(
279 Update,
280 (menu_action, button_system).run_if(in_state(GameState::Menu)),
281 );
282 }
283
284 // State used for the current menu screen
285 #[derive(Clone, Copy, Default, Eq, PartialEq, Debug, Hash, States)]
286 enum MenuState {
287 Main,
288 Settings,
289 SettingsDisplay,
290 SettingsSound,
291 #[default]
292 Disabled,
293 }
294
295 // Tag component used to tag entities added on the main menu screen
296 #[derive(Component)]
297 struct OnMainMenuScreen;
298
299 // Tag component used to tag entities added on the settings menu screen
300 #[derive(Component)]
301 struct OnSettingsMenuScreen;
302
303 // Tag component used to tag entities added on the display settings menu screen
304 #[derive(Component)]
305 struct OnDisplaySettingsMenuScreen;
306
307 // Tag component used to tag entities added on the sound settings menu screen
308 #[derive(Component)]
309 struct OnSoundSettingsMenuScreen;
310
311 const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15);
312 const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25);
313 const HOVERED_PRESSED_BUTTON: Color = Color::srgb(0.25, 0.65, 0.25);
314 const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35);
64const SKY_COLOR: Color = Color::srgb(0.02, 0.06, 0.15);
65
66const SMALL_3D: f32 = 0.5;
67const BIG_3D: f32 = 1.0;
68
69// primitives
70
71const CUBOID: Cuboid = Cuboid {
72 half_size: Vec3::new(SMALL_3D, BIG_3D, SMALL_3D),
73};
74
75const SPHERE: Sphere = Sphere {
76 radius: 1.5 * SMALL_3D,
77};
78
79const TRIANGLE_3D: Triangle3d = Triangle3d {
80 vertices: [
81 Vec3::new(BIG_3D, -BIG_3D * 0.5, 0.0),
82 Vec3::new(0.0, BIG_3D, 0.0),
83 Vec3::new(-BIG_3D, -BIG_3D * 0.5, 0.0),
84 ],
85};
86
87const CAPSULE_3D: Capsule3d = Capsule3d {
88 radius: SMALL_3D,
89 half_length: SMALL_3D,
90};
91
92const CYLINDER: Cylinder = Cylinder {
93 radius: SMALL_3D,
94 half_height: SMALL_3D,
95};
96
97const TETRAHEDRON: Tetrahedron = Tetrahedron {
98 vertices: [
99 Vec3::new(-BIG_3D, -BIG_3D * 0.67, BIG_3D * 0.5),
100 Vec3::new(BIG_3D, -BIG_3D * 0.67, BIG_3D * 0.5),
101 Vec3::new(0.0, -BIG_3D * 0.67, -BIG_3D * 1.17),
102 Vec3::new(0.0, BIG_3D, 0.0),
103 ],
104};
105
106// Components, Resources
107
108/// Resource for the random sampling mode, telling whether to sample the interior or the boundary.
109#[derive(Resource)]
110enum SamplingMode {
111 Interior,
112 Boundary,
113}
114
115/// Resource for storing whether points should spawn by themselves
116#[derive(Resource)]
117enum SpawningMode {
118 Manual,
119 Automatic,
120}
121
122/// Resource for tracking how many points should be spawned
123#[derive(Resource)]
124struct SpawnQueue(usize);
125
126#[derive(Resource)]
127struct PointCounter(usize);
128
129/// Resource storing the shapes being sampled and their translations.
130#[derive(Resource)]
131struct SampledShapes(Vec<(Shape, Vec3)>);
132
133impl SampledShapes {
134 fn new() -> Self {
135 let shapes = Shape::list_all_shapes();
136
137 let n_shapes = shapes.len();
138
139 let translations =
140 (0..n_shapes).map(|i| (i as f32 - n_shapes as f32 / 2.0) * DISTANCE_BETWEEN_SHAPES);
141
142 SampledShapes(shapes.into_iter().zip(translations).collect())
143 }
144}
145
146/// Enum listing the shapes that can be sampled
147#[derive(Clone, Copy)]
148enum Shape {
149 Cuboid,
150 Sphere,
151 Capsule,
152 Cylinder,
153 Tetrahedron,
154 Triangle,
155}
156struct ShapeMeshBuilder {
157 shape: Shape,
158}
159
160impl Shape {
161 /// Return a vector containing all implemented shapes
162 fn list_all_shapes() -> Vec<Shape> {
163 vec![
164 Shape::Cuboid,
165 Shape::Sphere,
166 Shape::Capsule,
167 Shape::Cylinder,
168 Shape::Tetrahedron,
169 Shape::Triangle,
170 ]
171 }
172}
173
174impl ShapeSample for Shape {
175 type Output = Vec3;
176 fn sample_interior<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec3 {
177 match self {
178 Shape::Cuboid => CUBOID.sample_interior(rng),
179 Shape::Sphere => SPHERE.sample_interior(rng),
180 Shape::Capsule => CAPSULE_3D.sample_interior(rng),
181 Shape::Cylinder => CYLINDER.sample_interior(rng),
182 Shape::Tetrahedron => TETRAHEDRON.sample_interior(rng),
183 Shape::Triangle => TRIANGLE_3D.sample_interior(rng),
184 }
185 }
186
187 fn sample_boundary<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::Output {
188 match self {
189 Shape::Cuboid => CUBOID.sample_boundary(rng),
190 Shape::Sphere => SPHERE.sample_boundary(rng),
191 Shape::Capsule => CAPSULE_3D.sample_boundary(rng),
192 Shape::Cylinder => CYLINDER.sample_boundary(rng),
193 Shape::Tetrahedron => TETRAHEDRON.sample_boundary(rng),
194 Shape::Triangle => TRIANGLE_3D.sample_boundary(rng),
195 }
196 }
197}
198
199impl Meshable for Shape {
200 type Output = ShapeMeshBuilder;
201
202 fn mesh(&self) -> Self::Output {
203 ShapeMeshBuilder { shape: *self }
204 }
205}
206
207impl MeshBuilder for ShapeMeshBuilder {
208 fn build(&self) -> Mesh {
209 match self.shape {
210 Shape::Cuboid => CUBOID.mesh().into(),
211 Shape::Sphere => SPHERE.mesh().into(),
212 Shape::Capsule => CAPSULE_3D.mesh().into(),
213 Shape::Cylinder => CYLINDER.mesh().into(),
214 Shape::Tetrahedron => TETRAHEDRON.mesh().into(),
215 Shape::Triangle => TRIANGLE_3D.mesh().into(),
216 }
217 }
218}
219
220/// The source of randomness used by this example.
221#[derive(Resource)]
222struct RandomSource(ChaCha8Rng);
223
224/// A container for the handle storing the mesh used to display sampled points as spheres.
225#[derive(Resource)]
226struct PointMesh(Handle<Mesh>);
227
228/// A container for the handle storing the material used to display sampled points.
229#[derive(Resource)]
230struct PointMaterial {
231 interior: Handle<StandardMaterial>,
232 boundary: Handle<StandardMaterial>,
233}
234
235/// Marker component for sampled points.
236#[derive(Component)]
237struct SamplePoint;
238
239/// Component for animating the spawn animation of lights.
240#[derive(Component)]
241struct SpawningPoint {
242 progress: f32,
243}
244
245/// Marker component for lights which should change intensity.
246#[derive(Component)]
247struct DespawningPoint {
248 progress: f32,
249}
250
251/// Marker component for lights which should change intensity.
252#[derive(Component)]
253struct FireflyLights;
254
255/// The pressed state of the mouse, used for camera motion.
256#[derive(Resource)]
257struct MousePressed(bool);
258
259/// Camera movement component.
260#[derive(Component)]
261struct CameraRig {
262 /// Rotation around the vertical axis of the camera (radians).
263 /// Positive changes makes the camera look more from the right.
264 pub yaw: f32,
265 /// Rotation around the horizontal axis of the camera (radians) (-pi/2; pi/2).
266 /// Positive looks down from above.
267 pub pitch: f32,
268 /// Distance from the center, smaller distance causes more zoom.
269 pub distance: f32,
270 /// Location in 3D space at which the camera is looking and around which it is orbiting.
271 pub target: Vec3,
272}
273
274fn setup(
275 mut commands: Commands,
276 mut meshes: ResMut<Assets<Mesh>>,
277 mut materials: ResMut<Assets<StandardMaterial>>,
278 shapes: Res<SampledShapes>,
279) {
280 // Use seeded rng and store it in a resource; this makes the random output reproducible.
281 let seeded_rng = ChaCha8Rng::seed_from_u64(4); // Chosen by a fair die roll, guaranteed to be random.
282 commands.insert_resource(RandomSource(seeded_rng));
283
284 // Make a plane for establishing space.
285 commands.spawn((
286 Mesh3d(meshes.add(Plane3d::default().mesh().size(20.0, 20.0))),
287 MeshMaterial3d(materials.add(StandardMaterial {
288 base_color: Color::srgb(0.3, 0.5, 0.3),
289 perceptual_roughness: 0.95,
290 metallic: 0.0,
291 ..default()
292 })),
293 Transform::from_xyz(0.0, -2.5, 0.0),
294 ));
295
296 let shape_material = materials.add(StandardMaterial {
297 base_color: Color::srgba(0.2, 0.1, 0.6, 0.3),
298 reflectance: 0.0,
299 alpha_mode: AlphaMode::Blend,
300 cull_mode: None,
301 ..default()
302 });
303
304 // Spawn shapes to be sampled
305 for (shape, translation) in shapes.0.iter() {
306 // The sampled shape shown transparently:
307 commands.spawn((
308 Mesh3d(meshes.add(shape.mesh())),
309 MeshMaterial3d(shape_material.clone()),
310 Transform::from_translation(*translation),
311 ));
312
313 // Lights which work as the bulk lighting of the fireflies:
314 commands.spawn((
315 PointLight {
316 range: 4.0,
317 radius: 0.6,
318 intensity: 1.0,
319 shadows_enabled: false,
320 color: Color::LinearRgba(INSIDE_POINT_COLOR),
321 ..default()
322 },
323 Transform::from_translation(*translation),
324 FireflyLights,
325 ));
326 }
327
328 // Global light:
329 commands.spawn((
330 PointLight {
331 color: SKY_COLOR,
332 intensity: 2_000.0,
333 shadows_enabled: false,
334 ..default()
335 },
336 Transform::from_xyz(4.0, 8.0, 4.0),
337 ));
338
339 // A camera:
340 commands.spawn((
341 Camera3d::default(),
342 Camera {
343 hdr: true, // HDR is required for bloom
344 clear_color: ClearColorConfig::Custom(SKY_COLOR),
345 ..default()
346 },
347 Tonemapping::TonyMcMapface,
348 Transform::from_xyz(-2.0, 3.0, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
349 Bloom::NATURAL,
350 CameraRig {
351 yaw: 0.56,
352 pitch: 0.45,
353 distance: 8.0,
354 target: Vec3::ZERO,
355 },
356 ));
357
358 // Store the mesh and material for sample points in resources:
359 commands.insert_resource(PointMesh(
360 meshes.add(Sphere::new(0.03).mesh().ico(1).unwrap()),
361 ));
362 commands.insert_resource(PointMaterial {
363 interior: materials.add(StandardMaterial {
364 base_color: Color::BLACK,
365 reflectance: 0.05,
366 emissive: 2.5 * INSIDE_POINT_COLOR,
367 ..default()
368 }),
369 boundary: materials.add(StandardMaterial {
370 base_color: Color::BLACK,
371 reflectance: 0.05,
372 emissive: 1.5 * BOUNDARY_POINT_COLOR,
373 ..default()
374 }),
375 });
376
377 // Instructions for the example:
378 commands.spawn((
379 Text::new(
380 "Controls:\n\
381 M: Toggle between sampling boundary and interior.\n\
382 A: Toggle automatic spawning & despawning of points.\n\
383 R: Restart (erase all samples).\n\
384 S: Add one random sample.\n\
385 D: Add 100 random samples.\n\
386 Rotate camera by holding left mouse and panning.\n\
387 Zoom camera by scrolling via mouse or +/-.\n\
388 Move camera by L/R arrow keys.\n\
389 Tab: Toggle this text",
390 ),
391 Node {
392 position_type: PositionType::Absolute,
393 top: Val::Px(12.0),
394 left: Val::Px(12.0),
395 ..default()
396 },
397 ));
398
399 // No points are scheduled to spawn initially.
400 commands.insert_resource(SpawnQueue(0));
401
402 // No points have been spawned initially.
403 commands.insert_resource(PointCounter(0));
404
405 // The mode starts with interior points.
406 commands.insert_resource(SamplingMode::Interior);
407
408 // Points spawn automatically by default.
409 commands.insert_resource(SpawningMode::Automatic);
410
411 // Starting mouse-pressed state is false.
412 commands.insert_resource(MousePressed(false));
413}
11const HIDDEN_COLOR: Color = Color::srgb(1.0, 0.7, 0.7);
12
13fn main() {
14 App::new()
15 .add_plugins(DefaultPlugins)
16 // Only run the app when there is user input. This will significantly reduce CPU/GPU use.
17 .insert_resource(WinitSettings::desktop_app())
18 .add_systems(Startup, setup)
19 .add_systems(
20 Update,
21 (
22 buttons_handler::<Display>,
23 buttons_handler::<Visibility>,
24 text_hover,
25 ),
26 )
27 .run();
28}
29
30#[derive(Component)]
31struct Target<T> {
32 id: Entity,
33 phantom: std::marker::PhantomData<T>,
34}
35
36impl<T> Target<T> {
37 fn new(id: Entity) -> Self {
38 Self {
39 id,
40 phantom: std::marker::PhantomData,
41 }
42 }
43}
44
45trait TargetUpdate {
46 type TargetComponent: Component<Mutability = Mutable>;
47 const NAME: &'static str;
48 fn update_target(&self, target: &mut Self::TargetComponent) -> String;
49}
50
51impl TargetUpdate for Target<Display> {
52 type TargetComponent = Node;
53 const NAME: &'static str = "Display";
54 fn update_target(&self, node: &mut Self::TargetComponent) -> String {
55 node.display = match node.display {
56 Display::Flex => Display::None,
57 Display::None => Display::Flex,
58 Display::Block | Display::Grid => unreachable!(),
59 };
60 format!("{}::{:?} ", Self::NAME, node.display)
61 }
62}
63
64impl TargetUpdate for Target<Visibility> {
65 type TargetComponent = Visibility;
66 const NAME: &'static str = "Visibility";
67 fn update_target(&self, visibility: &mut Self::TargetComponent) -> String {
68 *visibility = match *visibility {
69 Visibility::Inherited => Visibility::Visible,
70 Visibility::Visible => Visibility::Hidden,
71 Visibility::Hidden => Visibility::Inherited,
72 };
73 format!("{}::{visibility:?}", Self::NAME)
74 }
75}
76
77fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
78 let palette: [Color; 4] = PALETTE.map(|hex| Srgba::hex(hex).unwrap().into());
79
80 let text_font = TextFont {
81 font: asset_server.load("fonts/FiraSans-Bold.ttf"),
82 ..default()
83 };
84
85 commands.spawn(Camera2d);
86 commands
87 .spawn((
88 Node {
89 width: Val::Percent(100.),
90 height: Val::Percent(100.),
91 flex_direction: FlexDirection::Column,
92 align_items: AlignItems::Center,
93 justify_content: JustifyContent::SpaceEvenly,
94 ..Default::default()
95 },
96 BackgroundColor(Color::BLACK),
97 ))
98 .with_children(|parent| {
99 parent.spawn((
100 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"),
101 text_font.clone(),
102 TextLayout::new_with_justify(JustifyText::Center),
103 Node {
104 margin: UiRect::bottom(Val::Px(10.)),
105 ..Default::default()
106 },
107 ));
108
109 parent
110 .spawn(Node {
111 width: Val::Percent(100.),
112 ..default()
113 })
114 .with_children(|parent| {
115 let mut target_ids = vec![];
116 parent
117 .spawn(Node {
118 width: Val::Percent(50.),
119 height: Val::Px(520.),
120 justify_content: JustifyContent::Center,
121 ..default()
122 })
123 .with_children(|parent| {
124 target_ids = spawn_left_panel(parent, &palette);
125 });
126
127 parent
128 .spawn(Node {
129 width: Val::Percent(50.),
130 justify_content: JustifyContent::Center,
131 ..default()
132 })
133 .with_children(|parent| {
134 spawn_right_panel(parent, text_font, &palette, target_ids);
135 });
136 });
137
138 parent
139 .spawn(Node {
140 flex_direction: FlexDirection::Row,
141 align_items: AlignItems::Start,
142 justify_content: JustifyContent::Start,
143 column_gap: Val::Px(10.),
144 ..default()
145 })
146 .with_children(|builder| {
147 let text_font = TextFont {
148 font: asset_server.load("fonts/FiraSans-Bold.ttf"),
149 ..default()
150 };
151
152 builder.spawn((
153 Text::new("Display::None\nVisibility::Hidden\nVisibility::Inherited"),
154 text_font.clone(),
155 TextColor(HIDDEN_COLOR),
156 TextLayout::new_with_justify(JustifyText::Center),
157 ));
158 builder.spawn((
159 Text::new("-\n-\n-"),
160 text_font.clone(),
161 TextColor(DARK_GRAY.into()),
162 TextLayout::new_with_justify(JustifyText::Center),
163 ));
164 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));
165 });
166 });
167}
168
169fn spawn_left_panel(builder: &mut ChildSpawnerCommands, palette: &[Color; 4]) -> Vec<Entity> {
170 let mut target_ids = vec![];
171 builder
172 .spawn((
173 Node {
174 padding: UiRect::all(Val::Px(10.)),
175 ..default()
176 },
177 BackgroundColor(Color::WHITE),
178 ))
179 .with_children(|parent| {
180 parent
181 .spawn((Node::default(), BackgroundColor(Color::BLACK)))
182 .with_children(|parent| {
183 let id = parent
184 .spawn((
185 Node {
186 align_items: AlignItems::FlexEnd,
187 justify_content: JustifyContent::FlexEnd,
188 ..default()
189 },
190 BackgroundColor(palette[0]),
191 Outline {
192 width: Val::Px(4.),
193 color: DARK_CYAN.into(),
194 offset: Val::Px(10.),
195 },
196 ))
197 .with_children(|parent| {
198 parent.spawn(Node {
199 width: Val::Px(100.),
200 height: Val::Px(500.),
201 ..default()
202 });
203
204 let id = parent
205 .spawn((
206 Node {
207 height: Val::Px(400.),
208 align_items: AlignItems::FlexEnd,
209 justify_content: JustifyContent::FlexEnd,
210 ..default()
211 },
212 BackgroundColor(palette[1]),
213 ))
214 .with_children(|parent| {
215 parent.spawn(Node {
216 width: Val::Px(100.),
217 height: Val::Px(400.),
218 ..default()
219 });
220
221 let id = parent
222 .spawn((
223 Node {
224 height: Val::Px(300.),
225 align_items: AlignItems::FlexEnd,
226 justify_content: JustifyContent::FlexEnd,
227 ..default()
228 },
229 BackgroundColor(palette[2]),
230 ))
231 .with_children(|parent| {
232 parent.spawn(Node {
233 width: Val::Px(100.),
234 height: Val::Px(300.),
235 ..default()
236 });
237
238 let id = parent
239 .spawn((
240 Node {
241 width: Val::Px(200.),
242 height: Val::Px(200.),
243 ..default()
244 },
245 BackgroundColor(palette[3]),
246 ))
247 .id();
248 target_ids.push(id);
249 })
250 .id();
251 target_ids.push(id);
252 })
253 .id();
254 target_ids.push(id);
255 })
256 .id();
257 target_ids.push(id);
258 });
259 });
260 target_ids
261}
262
263fn spawn_right_panel(
264 parent: &mut ChildSpawnerCommands,
265 text_font: TextFont,
266 palette: &[Color; 4],
267 mut target_ids: Vec<Entity>,
268) {
269 let spawn_buttons = |parent: &mut ChildSpawnerCommands, target_id| {
270 spawn_button::<Display>(parent, text_font.clone(), target_id);
271 spawn_button::<Visibility>(parent, text_font.clone(), target_id);
272 };
273 parent
274 .spawn((
275 Node {
276 padding: UiRect::all(Val::Px(10.)),
277 ..default()
278 },
279 BackgroundColor(Color::WHITE),
280 ))
281 .with_children(|parent| {
282 parent
283 .spawn((
284 Node {
285 width: Val::Px(500.),
286 height: Val::Px(500.),
287 flex_direction: FlexDirection::Column,
288 align_items: AlignItems::FlexEnd,
289 justify_content: JustifyContent::SpaceBetween,
290 padding: UiRect {
291 left: Val::Px(5.),
292 top: Val::Px(5.),
293 ..default()
294 },
295 ..default()
296 },
297 BackgroundColor(palette[0]),
298 Outline {
299 width: Val::Px(4.),
300 color: DARK_CYAN.into(),
301 offset: Val::Px(10.),
302 },
303 ))
304 .with_children(|parent| {
305 spawn_buttons(parent, target_ids.pop().unwrap());
306
307 parent
308 .spawn((
309 Node {
310 width: Val::Px(400.),
311 height: Val::Px(400.),
312 flex_direction: FlexDirection::Column,
313 align_items: AlignItems::FlexEnd,
314 justify_content: JustifyContent::SpaceBetween,
315 padding: UiRect {
316 left: Val::Px(5.),
317 top: Val::Px(5.),
318 ..default()
319 },
320 ..default()
321 },
322 BackgroundColor(palette[1]),
323 ))
324 .with_children(|parent| {
325 spawn_buttons(parent, target_ids.pop().unwrap());
326
327 parent
328 .spawn((
329 Node {
330 width: Val::Px(300.),
331 height: Val::Px(300.),
332 flex_direction: FlexDirection::Column,
333 align_items: AlignItems::FlexEnd,
334 justify_content: JustifyContent::SpaceBetween,
335 padding: UiRect {
336 left: Val::Px(5.),
337 top: Val::Px(5.),
338 ..default()
339 },
340 ..default()
341 },
342 BackgroundColor(palette[2]),
343 ))
344 .with_children(|parent| {
345 spawn_buttons(parent, target_ids.pop().unwrap());
346
347 parent
348 .spawn((
349 Node {
350 width: Val::Px(200.),
351 height: Val::Px(200.),
352 align_items: AlignItems::FlexStart,
353 justify_content: JustifyContent::SpaceBetween,
354 flex_direction: FlexDirection::Column,
355 padding: UiRect {
356 left: Val::Px(5.),
357 top: Val::Px(5.),
358 ..default()
359 },
360 ..default()
361 },
362 BackgroundColor(palette[3]),
363 ))
364 .with_children(|parent| {
365 spawn_buttons(parent, target_ids.pop().unwrap());
366
367 parent.spawn(Node {
368 width: Val::Px(100.),
369 height: Val::Px(100.),
370 ..default()
371 });
372 });
373 });
374 });
375 });
376 });
377}
378
379fn spawn_button<T>(parent: &mut ChildSpawnerCommands, text_font: TextFont, target: Entity)
380where
381 T: Default + std::fmt::Debug + Send + Sync + 'static,
382 Target<T>: TargetUpdate,
383{
384 parent
385 .spawn((
386 Button,
387 Node {
388 align_self: AlignSelf::FlexStart,
389 padding: UiRect::axes(Val::Px(5.), Val::Px(1.)),
390 ..default()
391 },
392 BackgroundColor(Color::BLACK.with_alpha(0.5)),
393 Target::<T>::new(target),
394 ))
395 .with_children(|builder| {
396 builder.spawn((
397 Text(format!("{}::{:?}", Target::<T>::NAME, T::default())),
398 text_font,
399 TextLayout::new_with_justify(JustifyText::Center),
400 ));
401 });
402}
403
404fn buttons_handler<T>(
405 mut left_panel_query: Query<&mut <Target<T> as TargetUpdate>::TargetComponent>,
406 mut visibility_button_query: Query<(&Target<T>, &Interaction, &Children), Changed<Interaction>>,
407 mut text_query: Query<(&mut Text, &mut TextColor)>,
408) where
409 T: Send + Sync,
410 Target<T>: TargetUpdate + Component,
411{
412 for (target, interaction, children) in visibility_button_query.iter_mut() {
413 if matches!(interaction, Interaction::Pressed) {
414 let mut target_value = left_panel_query.get_mut(target.id).unwrap();
415 for &child in children {
416 if let Ok((mut text, mut text_color)) = text_query.get_mut(child) {
417 **text = target.update_target(target_value.as_mut());
418 text_color.0 = if text.contains("None") || text.contains("Hidden") {
419 Color::srgb(1.0, 0.7, 0.7)
420 } else {
421 Color::WHITE
422 };
423 }
424 }
425 }
426 }
427}
- examples/state/custom_transitions.rs
- examples/state/states.rs
- examples/ui/button.rs
- examples/ui/tab_navigation.rs
- examples/games/desk_toy.rs
- examples/ui/flex_layout.rs
- examples/ui/size_constraints.rs
- examples/state/computed_states.rs
- examples/state/sub_states.rs
- examples/window/clear_color.rs
- examples/3d/fog.rs
- examples/ecs/removal_detection.rs
- examples/math/cubic_splines.rs
- examples/async_tasks/async_compute.rs
- examples/ui/text.rs
- examples/ui/ghost_nodes.rs
- examples/camera/2d_top_down_camera.rs
- examples/3d/3d_viewport_to_world.rs
- examples/asset/multi_asset_sync.rs
- tests/window/minimizing.rs
- tests/window/resizing.rs
- examples/3d/atmospheric_fog.rs
- examples/animation/animated_mesh.rs
- examples/shader/custom_post_processing.rs
- examples/animation/animation_graph.rs
- examples/testbed/2d.rs
- examples/shader/shader_material_screenspace_texture.rs
- examples/3d/mesh_ray_cast.rs
- examples/camera/camera_orbit.rs
- examples/animation/animation_masks.rs
- examples/3d/parenting.rs
- examples/window/screenshot.rs
- examples/3d/two_passes.rs
- examples/window/scale_factor_override.rs
- examples/camera/2d_screen_shake.rs
- examples/ui/overflow_debug.rs
- examples/window/low_power.rs
- examples/movement/smooth_follow.rs
- examples/ui/relative_cursor_position.rs
- examples/3d/vertex_colors.rs
- examples/3d/orthographic.rs
- examples/stress_tests/many_buttons.rs
- examples/3d/spherical_area_lights.rs
- examples/gizmos/axes.rs
- examples/2d/bloom_2d.rs
- examples/animation/animated_mesh_events.rs
- examples/3d/ssao.rs
- examples/ecs/error_handling.rs
- examples/camera/projection_zoom.rs
- examples/3d/order_independent_transparency.rs
- examples/ui/ui_texture_slice.rs
- examples/3d/visibility_range.rs
- examples/animation/animated_mesh_control.rs
- examples/time/virtual_time.rs
- examples/gizmos/3d_gizmos.rs
- examples/3d/anti_aliasing.rs
- examples/ui/transparency_ui.rs
- examples/transforms/align.rs
- examples/math/random_sampling.rs
- examples/ui/ui_texture_atlas_slice.rs
- examples/testbed/ui.rs
- examples/picking/sprite_picking.rs
- examples/ecs/iter_combinations.rs
- examples/ui/text_wrap_debug.rs
- examples/games/alien_cake_addict.rs
- examples/asset/alter_mesh.rs
- examples/3d/transparency_3d.rs
- examples/3d/render_to_texture.rs
- examples/asset/asset_loading.rs
- examples/3d/auto_exposure.rs
- examples/ui/overflow.rs
- examples/ui/overflow_clip_margin.rs
- examples/shader/shader_prepass.rs
- examples/stress_tests/many_foxes.rs
- examples/3d/split_screen.rs
- examples/2d/text2d.rs
- examples/3d/deferred_rendering.rs
- examples/animation/custom_skinned_mesh.rs
- examples/3d/blend_modes.rs
- examples/animation/animated_transform.rs
- examples/3d/camera_sub_view.rs
- examples/ui/text_debug.rs
- examples/ui/grid.rs
- examples/3d/transmission.rs
- examples/ui/borders.rs
- examples/ui/scroll.rs
- examples/testbed/full_ui.rs
Sourcepub const fn srgb_from_array(array: [f32; 3]) -> Color
pub const fn srgb_from_array(array: [f32; 3]) -> Color
Sourcepub const fn srgba_u8(red: u8, green: u8, blue: u8, alpha: u8) -> Color
pub const fn srgba_u8(red: u8, green: u8, blue: u8, alpha: u8) -> Color
Creates a new Color
object storing a Srgba
color from u8
values.
§Arguments
red
- Red channel. [0, 255]green
- Green channel. [0, 255]blue
- Blue channel. [0, 255]alpha
- Alpha channel. [0, 255]
Examples found in repository?
252fn setup(
253 mut commands: Commands,
254 mut meshes: ResMut<Assets<Mesh>>,
255 mut materials: ResMut<Assets<StandardMaterial>>,
256 mut images: ResMut<Assets<Image>>,
257 asset_server: Res<AssetServer>,
258) {
259 // Plane
260 commands.spawn((
261 Mesh3d(meshes.add(Plane3d::default().mesh().size(50.0, 50.0))),
262 MeshMaterial3d(materials.add(Color::srgb(0.1, 0.2, 0.1))),
263 ));
264
265 let cube_material = materials.add(StandardMaterial {
266 base_color_texture: Some(images.add(uv_debug_texture())),
267 ..default()
268 });
269
270 // Cubes
271 for i in 0..5 {
272 commands.spawn((
273 Mesh3d(meshes.add(Cuboid::new(0.25, 0.25, 0.25))),
274 MeshMaterial3d(cube_material.clone()),
275 Transform::from_xyz(i as f32 * 0.25 - 1.0, 0.125, -i as f32 * 0.5),
276 ));
277 }
278
279 // Flight Helmet
280 commands.spawn(SceneRoot(asset_server.load(
281 GltfAssetLabel::Scene(0).from_asset("models/FlightHelmet/FlightHelmet.gltf"),
282 )));
283
284 // Light
285 commands.spawn((
286 DirectionalLight {
287 illuminance: light_consts::lux::FULL_DAYLIGHT,
288 shadows_enabled: true,
289 ..default()
290 },
291 Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, PI * -0.15, PI * -0.15)),
292 CascadeShadowConfigBuilder {
293 maximum_distance: 3.0,
294 first_cascade_far_bound: 0.9,
295 ..default()
296 }
297 .build(),
298 ));
299
300 // Camera
301 commands.spawn((
302 Camera3d::default(),
303 Camera {
304 hdr: true,
305 ..default()
306 },
307 Transform::from_xyz(0.7, 0.7, 1.0).looking_at(Vec3::new(0.0, 0.3, 0.0), Vec3::Y),
308 ContrastAdaptiveSharpening {
309 enabled: false,
310 ..default()
311 },
312 EnvironmentMapLight {
313 diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"),
314 specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
315 intensity: 150.0,
316 ..default()
317 },
318 DistanceFog {
319 color: Color::srgba_u8(43, 44, 47, 255),
320 falloff: FogFalloff::Linear {
321 start: 1.0,
322 end: 4.0,
323 },
324 ..default()
325 },
326 ));
327
328 // example instructions
329 commands.spawn((
330 Text::default(),
331 Node {
332 position_type: PositionType::Absolute,
333 top: Val::Px(12.0),
334 left: Val::Px(12.0),
335 ..default()
336 },
337 ));
338}
Sourcepub const fn srgb_u8(red: u8, green: u8, blue: u8) -> Color
pub const 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.
§Arguments
red
- Red channel. [0, 255]green
- Green channel. [0, 255]blue
- Blue channel. [0, 255]
Examples found in repository?
86fn on_click_spawn_cube(
87 _click: Trigger<Pointer<Click>>,
88 mut commands: Commands,
89 mut meshes: ResMut<Assets<Mesh>>,
90 mut materials: ResMut<Assets<StandardMaterial>>,
91 mut num: Local<usize>,
92) {
93 commands
94 .spawn((
95 Mesh3d(meshes.add(Cuboid::new(0.5, 0.5, 0.5))),
96 MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))),
97 Transform::from_xyz(0.0, 0.25 + 0.55 * *num as f32, 0.0),
98 ))
99 // With the MeshPickingPlugin added, you can add pointer event observers to meshes:
100 .observe(on_drag_rotate);
101 *num += 1;
102}
More examples
64fn on_click_spawn_cube(
65 _click: Trigger<Pointer<Click>>,
66 mut commands: Commands,
67 mut meshes: ResMut<Assets<Mesh>>,
68 mut materials: ResMut<Assets<StandardMaterial>>,
69 mut num: Local<usize>,
70) {
71 commands
72 .spawn((
73 Mesh3d(meshes.add(Cuboid::new(0.5, 0.5, 0.5))),
74 MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))),
75 Transform::from_xyz(0.0, 0.25 + 0.55 * *num as f32, 0.0),
76 ))
77 // With the MeshPickingPlugin added, you can add pointer event observers to meshes:
78 .observe(on_drag_rotate);
79 *num += 1;
80}
334fn add_camera(commands: &mut Commands, asset_server: &AssetServer, color_grading: ColorGrading) {
335 commands.spawn((
336 Camera3d::default(),
337 Camera {
338 hdr: true,
339 ..default()
340 },
341 Transform::from_xyz(0.7, 0.7, 1.0).looking_at(Vec3::new(0.0, 0.3, 0.0), Vec3::Y),
342 color_grading,
343 DistanceFog {
344 color: Color::srgb_u8(43, 44, 47),
345 falloff: FogFalloff::Linear {
346 start: 1.0,
347 end: 8.0,
348 },
349 ..default()
350 },
351 EnvironmentMapLight {
352 diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"),
353 specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
354 intensity: 2000.0,
355 ..default()
356 },
357 ));
358}
173fn spawn_barriers(
174 meshes: &mut Assets<Mesh>,
175 materials: &mut Assets<StandardMaterial>,
176 commands: &mut Commands,
177) {
178 const N_CONES: usize = 100;
179 let capsule = meshes.add(Capsule3d::default());
180 let matl = materials.add(StandardMaterial {
181 base_color: Color::srgb_u8(255, 87, 51),
182 reflectance: 1.0,
183 ..default()
184 });
185 let mut spawn_with_offset = |offset: f32| {
186 for i in 0..N_CONES {
187 let pos = race_track_pos(
188 offset,
189 (i as f32) / (N_CONES as f32) * std::f32::consts::PI * 2.0,
190 );
191 commands.spawn((
192 Mesh3d(capsule.clone()),
193 MeshMaterial3d(matl.clone()),
194 Transform::from_xyz(pos.x, -0.65, pos.y).with_scale(Vec3::splat(0.07)),
195 ));
196 }
197 };
198 spawn_with_offset(0.04);
199 spawn_with_offset(-0.04);
200}
60fn spawn_camera(commands: &mut Commands, asset_server: &AssetServer) {
61 commands.spawn((
62 Camera3d::default(),
63 Camera {
64 hdr: true,
65 ..default()
66 },
67 Transform::from_xyz(0.7, 0.7, 1.0).looking_at(Vec3::new(0.0, 0.3, 0.0), Vec3::Y),
68 DistanceFog {
69 color: Color::srgb_u8(43, 44, 47),
70 falloff: FogFalloff::Linear {
71 start: 1.0,
72 end: 8.0,
73 },
74 ..default()
75 },
76 EnvironmentMapLight {
77 diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"),
78 specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
79 intensity: 2000.0,
80 ..default()
81 },
82 // Include the `ChromaticAberration` component.
83 ChromaticAberration::default(),
84 ));
85}
13fn setup(
14 mut commands: Commands,
15 mut meshes: ResMut<Assets<Mesh>>,
16 mut materials: ResMut<Assets<StandardMaterial>>,
17) {
18 // circular base
19 commands.spawn((
20 Mesh3d(meshes.add(Circle::new(4.0))),
21 MeshMaterial3d(materials.add(Color::WHITE)),
22 Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
23 ));
24 // cube
25 commands.spawn((
26 Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
27 MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))),
28 Transform::from_xyz(0.0, 0.5, 0.0),
29 ));
30 // light
31 commands.spawn((
32 PointLight {
33 shadows_enabled: true,
34 ..default()
35 },
36 Transform::from_xyz(4.0, 8.0, 4.0),
37 ));
38 // camera
39 commands.spawn((
40 Camera3d::default(),
41 Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y),
42 ));
43}
- examples/diagnostics/log_diagnostics.rs
- examples/3d/tonemapping.rs
- examples/remote/server.rs
- examples/camera/custom_projection.rs
- examples/3d/skybox.rs
- examples/shader/custom_render_phase.rs
- examples/stress_tests/many_cubes.rs
- examples/app/headless_renderer.rs
- examples/stress_tests/bevymark.rs
- examples/gizmos/light_gizmos.rs
- examples/3d/spotlight.rs
- examples/3d/parallax_mapping.rs
- examples/3d/deferred_rendering.rs
Sourcepub const fn linear_rgba(red: f32, green: f32, blue: f32, alpha: f32) -> Color
pub const fn linear_rgba(red: f32, green: f32, blue: f32, alpha: f32) -> Color
Creates a new Color
object storing a LinearRgba
color.
§Arguments
red
- Red channel. [0.0, 1.0]green
- Green channel. [0.0, 1.0]blue
- Blue channel. [0.0, 1.0]alpha
- Alpha channel. [0.0, 1.0]
Sourcepub const fn linear_rgb(red: f32, green: f32, blue: f32) -> Color
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.
§Arguments
red
- Red channel. [0.0, 1.0]green
- Green channel. [0.0, 1.0]blue
- Blue channel. [0.0, 1.0]
Examples found in repository?
More examples
325fn mouse_handler(
326 mut commands: Commands,
327 args: Res<Args>,
328 time: Res<Time>,
329 mouse_button_input: Res<ButtonInput<MouseButton>>,
330 window: Query<&Window>,
331 bird_resources: ResMut<BirdResources>,
332 mut counter: ResMut<BevyCounter>,
333 mut rng: Local<Option<ChaCha8Rng>>,
334 mut wave: Local<usize>,
335) {
336 let Ok(window) = window.single() else {
337 return;
338 };
339
340 if rng.is_none() {
341 // We're seeding the PRNG here to make this example deterministic for testing purposes.
342 // This isn't strictly required in practical use unless you need your app to be deterministic.
343 *rng = Some(ChaCha8Rng::seed_from_u64(42));
344 }
345 let rng = rng.as_mut().unwrap();
346
347 if mouse_button_input.just_released(MouseButton::Left) {
348 counter.color = Color::linear_rgb(rng.r#gen(), rng.r#gen(), rng.r#gen());
349 }
350
351 if mouse_button_input.pressed(MouseButton::Left) {
352 let spawn_count = (BIRDS_PER_SECOND as f64 * time.delta_secs_f64()) as usize;
353 spawn_birds(
354 &mut commands,
355 args.into_inner(),
356 &window.resolution,
357 &mut counter,
358 spawn_count,
359 bird_resources.into_inner(),
360 None,
361 *wave,
362 );
363 *wave += 1;
364 }
365}
366
367fn bird_velocity_transform(
368 half_extents: Vec2,
369 mut translation: Vec3,
370 velocity_rng: &mut ChaCha8Rng,
371 waves: Option<usize>,
372 dt: f32,
373) -> (Transform, Vec3) {
374 let mut velocity = Vec3::new(MAX_VELOCITY * (velocity_rng.r#gen::<f32>() - 0.5), 0., 0.);
375
376 if let Some(waves) = waves {
377 // Step the movement and handle collisions as if the wave had been spawned at fixed time intervals
378 // and with dt-spaced frames of simulation
379 for _ in 0..(waves * (FIXED_TIMESTEP / dt).round() as usize) {
380 step_movement(&mut translation, &mut velocity, dt);
381 handle_collision(half_extents, &translation, &mut velocity);
382 }
383 }
384 (
385 Transform::from_translation(translation).with_scale(Vec3::splat(BIRD_SCALE)),
386 velocity,
387 )
388}
389
390const FIXED_DELTA_TIME: f32 = 1.0 / 60.0;
391
392fn spawn_birds(
393 commands: &mut Commands,
394 args: &Args,
395 primary_window_resolution: &WindowResolution,
396 counter: &mut BevyCounter,
397 spawn_count: usize,
398 bird_resources: &mut BirdResources,
399 waves_to_simulate: Option<usize>,
400 wave: usize,
401) {
402 let bird_x = (primary_window_resolution.width() / -2.) + HALF_BIRD_SIZE;
403 let bird_y = (primary_window_resolution.height() / 2.) - HALF_BIRD_SIZE;
404
405 let half_extents = 0.5 * primary_window_resolution.size();
406
407 let color = counter.color;
408 let current_count = counter.count;
409
410 match args.mode {
411 Mode::Sprite => {
412 let batch = (0..spawn_count)
413 .map(|count| {
414 let bird_z = if args.ordered_z {
415 (current_count + count) as f32 * 0.00001
416 } else {
417 bird_resources.transform_rng.r#gen::<f32>()
418 };
419
420 let (transform, velocity) = bird_velocity_transform(
421 half_extents,
422 Vec3::new(bird_x, bird_y, bird_z),
423 &mut bird_resources.velocity_rng,
424 waves_to_simulate,
425 FIXED_DELTA_TIME,
426 );
427
428 let color = if args.vary_per_instance {
429 Color::linear_rgb(
430 bird_resources.color_rng.r#gen(),
431 bird_resources.color_rng.r#gen(),
432 bird_resources.color_rng.r#gen(),
433 )
434 } else {
435 color
436 };
437 (
438 Sprite {
439 image: bird_resources
440 .textures
441 .choose(&mut bird_resources.material_rng)
442 .unwrap()
443 .clone(),
444 color,
445 ..default()
446 },
447 transform,
448 Bird { velocity },
449 )
450 })
451 .collect::<Vec<_>>();
452 commands.spawn_batch(batch);
453 }
454 Mode::Mesh2d => {
455 let batch = (0..spawn_count)
456 .map(|count| {
457 let bird_z = if args.ordered_z {
458 (current_count + count) as f32 * 0.00001
459 } else {
460 bird_resources.transform_rng.r#gen::<f32>()
461 };
462
463 let (transform, velocity) = bird_velocity_transform(
464 half_extents,
465 Vec3::new(bird_x, bird_y, bird_z),
466 &mut bird_resources.velocity_rng,
467 waves_to_simulate,
468 FIXED_DELTA_TIME,
469 );
470
471 let material =
472 if args.vary_per_instance || args.material_texture_count > args.waves {
473 bird_resources
474 .materials
475 .choose(&mut bird_resources.material_rng)
476 .unwrap()
477 .clone()
478 } else {
479 bird_resources.materials[wave % bird_resources.materials.len()].clone()
480 };
481 (
482 Mesh2d(bird_resources.quad.clone()),
483 MeshMaterial2d(material),
484 transform,
485 Bird { velocity },
486 )
487 })
488 .collect::<Vec<_>>();
489 commands.spawn_batch(batch);
490 }
491 }
492
493 counter.count += spawn_count;
494 counter.color = Color::linear_rgb(
495 bird_resources.color_rng.r#gen(),
496 bird_resources.color_rng.r#gen(),
497 bird_resources.color_rng.r#gen(),
498 );
499}
94fn draw(
95 my_handle: Res<MyProcGenImage>,
96 mut images: ResMut<Assets<Image>>,
97 // Used to keep track of where we are
98 mut i: Local<u32>,
99 mut draw_color: Local<Color>,
100 mut seeded_rng: ResMut<SeededRng>,
101) {
102 if *i == 0 {
103 // Generate a random color on first run.
104 *draw_color = Color::linear_rgb(
105 seeded_rng.0.r#gen(),
106 seeded_rng.0.r#gen(),
107 seeded_rng.0.r#gen(),
108 );
109 }
110
111 // Get the image from Bevy's asset storage.
112 let image = images.get_mut(&my_handle.0).expect("Image not found");
113
114 // Compute the position of the pixel to draw.
115
116 let center = Vec2::new(IMAGE_WIDTH as f32 / 2.0, IMAGE_HEIGHT as f32 / 2.0);
117 let max_radius = IMAGE_HEIGHT.min(IMAGE_WIDTH) as f32 / 2.0;
118 let rot_speed = 0.0123;
119 let period = 0.12345;
120
121 let r = ops::sin(*i as f32 * period) * max_radius;
122 let xy = Vec2::from_angle(*i as f32 * rot_speed) * r + center;
123 let (x, y) = (xy.x as u32, xy.y as u32);
124
125 // Get the old color of that pixel.
126 let old_color = image.get_color_at(x, y).unwrap();
127
128 // If the old color is our current color, change our drawing color.
129 let tolerance = 1.0 / 255.0;
130 if old_color.distance(&draw_color) <= tolerance {
131 *draw_color = Color::linear_rgb(
132 seeded_rng.0.r#gen(),
133 seeded_rng.0.r#gen(),
134 seeded_rng.0.r#gen(),
135 );
136 }
137
138 // Set the new color, but keep old alpha value from image.
139 image
140 .set_color_at(x, y, draw_color.with_alpha(old_color.alpha()))
141 .unwrap();
142
143 *i += 1;
144}
141fn setup(
142 mut commands: Commands,
143 mut meshes: ResMut<Assets<Mesh>>,
144 mut materials: ResMut<Assets<ColorMaterial>>,
145 window: Single<&Window>,
146) {
147 let window_size = window.resolution.physical_size().as_vec2();
148
149 // Initialize centered, non-window-filling viewport
150 commands.spawn((
151 Camera2d,
152 Camera {
153 viewport: Some(Viewport {
154 physical_position: (window_size * 0.125).as_uvec2(),
155 physical_size: (window_size * 0.75).as_uvec2(),
156 ..default()
157 }),
158 ..default()
159 },
160 ));
161
162 // Create a minimal UI explaining how to interact with the example
163 commands.spawn((
164 Text::new(
165 "Move the mouse to see the circle follow your cursor.\n\
166 Use the arrow keys to move the camera.\n\
167 Use the comma and period keys to zoom in and out.\n\
168 Use the WASD keys to move the viewport.\n\
169 Use the IJKL keys to resize the viewport.",
170 ),
171 Node {
172 position_type: PositionType::Absolute,
173 top: Val::Px(12.0),
174 left: Val::Px(12.0),
175 ..default()
176 },
177 ));
178
179 // Add mesh to make camera movement visible
180 commands.spawn((
181 Mesh2d(meshes.add(Rectangle::new(40.0, 20.0))),
182 MeshMaterial2d(materials.add(Color::from(GREEN))),
183 ));
184
185 // Add background to visualize viewport bounds
186 commands.spawn((
187 Mesh2d(meshes.add(Rectangle::new(50000.0, 50000.0))),
188 MeshMaterial2d(materials.add(Color::linear_rgb(0.01, 0.01, 0.01))),
189 Transform::from_translation(Vec3::new(0.0, 0.0, -200.0)),
190 ));
191}
53fn setup_scene(
54 asset_server: Res<AssetServer>,
55 mut images: ResMut<Assets<Image>>,
56 mut commands: Commands,
57 mut meshes: ResMut<Assets<Mesh>>,
58 mut materials: ResMut<Assets<StandardMaterial>>,
59) {
60 commands.insert_resource(AmbientLight {
61 color: Color::WHITE,
62 brightness: 300.0,
63 ..default()
64 });
65 commands.insert_resource(CameraMode::Chase);
66 commands.spawn((
67 DirectionalLight {
68 illuminance: 3_000.0,
69 shadows_enabled: true,
70 ..default()
71 },
72 Transform::default().looking_to(Vec3::new(-1.0, -0.7, -1.0), Vec3::X),
73 ));
74 // Sky
75 commands.spawn((
76 Mesh3d(meshes.add(Sphere::default())),
77 MeshMaterial3d(materials.add(StandardMaterial {
78 unlit: true,
79 base_color: Color::linear_rgb(0.1, 0.6, 1.0),
80 ..default()
81 })),
82 Transform::default().with_scale(Vec3::splat(-4000.0)),
83 ));
84 // Ground
85 let mut plane: Mesh = Plane3d::default().into();
86 let uv_size = 4000.0;
87 let uvs = vec![[uv_size, 0.0], [0.0, 0.0], [0.0, uv_size], [uv_size; 2]];
88 plane.insert_attribute(Mesh::ATTRIBUTE_UV_0, uvs);
89 commands.spawn((
90 Mesh3d(meshes.add(plane)),
91 MeshMaterial3d(materials.add(StandardMaterial {
92 base_color: Color::WHITE,
93 perceptual_roughness: 1.0,
94 base_color_texture: Some(images.add(uv_debug_texture())),
95 ..default()
96 })),
97 Transform::from_xyz(0.0, -0.65, 0.0).with_scale(Vec3::splat(80.)),
98 ));
99
100 spawn_cars(&asset_server, &mut meshes, &mut materials, &mut commands);
101 spawn_trees(&mut meshes, &mut materials, &mut commands);
102 spawn_barriers(&mut meshes, &mut materials, &mut commands);
103}
104
105fn spawn_cars(
106 asset_server: &AssetServer,
107 meshes: &mut Assets<Mesh>,
108 materials: &mut Assets<StandardMaterial>,
109 commands: &mut Commands,
110) {
111 const N_CARS: usize = 20;
112 let box_mesh = meshes.add(Cuboid::new(0.3, 0.15, 0.55));
113 let cylinder = meshes.add(Cylinder::default());
114 let logo = asset_server.load("branding/icon.png");
115 let wheel_matl = materials.add(StandardMaterial {
116 base_color: Color::WHITE,
117 base_color_texture: Some(logo.clone()),
118 ..default()
119 });
120
121 let mut matl = |color| {
122 materials.add(StandardMaterial {
123 base_color: color,
124 ..default()
125 })
126 };
127
128 let colors = [
129 matl(Color::linear_rgb(1.0, 0.0, 0.0)),
130 matl(Color::linear_rgb(1.0, 1.0, 0.0)),
131 matl(Color::BLACK),
132 matl(Color::linear_rgb(0.0, 0.0, 1.0)),
133 matl(Color::linear_rgb(0.0, 1.0, 0.0)),
134 matl(Color::linear_rgb(1.0, 0.0, 1.0)),
135 matl(Color::linear_rgb(0.5, 0.5, 0.0)),
136 matl(Color::linear_rgb(1.0, 0.5, 0.0)),
137 ];
138
139 for i in 0..N_CARS {
140 let color = colors[i % colors.len()].clone();
141 commands
142 .spawn((
143 Mesh3d(box_mesh.clone()),
144 MeshMaterial3d(color.clone()),
145 Transform::from_scale(Vec3::splat(0.5)),
146 Moves(i as f32 * 2.0),
147 ))
148 .insert_if(CameraTracked, || i == 0)
149 .with_children(|parent| {
150 parent.spawn((
151 Mesh3d(box_mesh.clone()),
152 MeshMaterial3d(color),
153 Transform::from_xyz(0.0, 0.08, 0.03).with_scale(Vec3::new(1.0, 1.0, 0.5)),
154 ));
155 let mut spawn_wheel = |x: f32, z: f32| {
156 parent.spawn((
157 Mesh3d(cylinder.clone()),
158 MeshMaterial3d(wheel_matl.clone()),
159 Transform::from_xyz(0.14 * x, -0.045, 0.15 * z)
160 .with_scale(Vec3::new(0.15, 0.04, 0.15))
161 .with_rotation(Quat::from_rotation_z(std::f32::consts::FRAC_PI_2)),
162 Rotates,
163 ));
164 };
165 spawn_wheel(1.0, 1.0);
166 spawn_wheel(1.0, -1.0);
167 spawn_wheel(-1.0, 1.0);
168 spawn_wheel(-1.0, -1.0);
169 });
170 }
171}
172
173fn spawn_barriers(
174 meshes: &mut Assets<Mesh>,
175 materials: &mut Assets<StandardMaterial>,
176 commands: &mut Commands,
177) {
178 const N_CONES: usize = 100;
179 let capsule = meshes.add(Capsule3d::default());
180 let matl = materials.add(StandardMaterial {
181 base_color: Color::srgb_u8(255, 87, 51),
182 reflectance: 1.0,
183 ..default()
184 });
185 let mut spawn_with_offset = |offset: f32| {
186 for i in 0..N_CONES {
187 let pos = race_track_pos(
188 offset,
189 (i as f32) / (N_CONES as f32) * std::f32::consts::PI * 2.0,
190 );
191 commands.spawn((
192 Mesh3d(capsule.clone()),
193 MeshMaterial3d(matl.clone()),
194 Transform::from_xyz(pos.x, -0.65, pos.y).with_scale(Vec3::splat(0.07)),
195 ));
196 }
197 };
198 spawn_with_offset(0.04);
199 spawn_with_offset(-0.04);
200}
201
202fn spawn_trees(
203 meshes: &mut Assets<Mesh>,
204 materials: &mut Assets<StandardMaterial>,
205 commands: &mut Commands,
206) {
207 const N_TREES: usize = 30;
208 let capsule = meshes.add(Capsule3d::default());
209 let sphere = meshes.add(Sphere::default());
210 let leaves = materials.add(Color::linear_rgb(0.0, 1.0, 0.0));
211 let trunk = materials.add(Color::linear_rgb(0.4, 0.2, 0.2));
212
213 let mut spawn_with_offset = |offset: f32| {
214 for i in 0..N_TREES {
215 let pos = race_track_pos(
216 offset,
217 (i as f32) / (N_TREES as f32) * std::f32::consts::PI * 2.0,
218 );
219 let [x, z] = pos.into();
220 commands.spawn((
221 Mesh3d(sphere.clone()),
222 MeshMaterial3d(leaves.clone()),
223 Transform::from_xyz(x, -0.3, z).with_scale(Vec3::splat(0.3)),
224 ));
225 commands.spawn((
226 Mesh3d(capsule.clone()),
227 MeshMaterial3d(trunk.clone()),
228 Transform::from_xyz(x, -0.5, z).with_scale(Vec3::new(0.05, 0.3, 0.05)),
229 ));
230 }
231 };
232 spawn_with_offset(0.07);
233 spawn_with_offset(-0.07);
234}
Sourcepub const fn hsla(
hue: f32,
saturation: f32,
lightness: f32,
alpha: f32,
) -> Color
pub const fn hsla( hue: f32, saturation: f32, lightness: f32, alpha: f32, ) -> Color
Creates a new Color
object storing a Hsla
color.
§Arguments
hue
- Hue channel. [0.0, 360.0]saturation
- Saturation channel. [0.0, 1.0]lightness
- Lightness channel. [0.0, 1.0]alpha
- Alpha channel. [0.0, 1.0]
Examples found in repository?
49fn setup(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>) {
50 commands.spawn((
51 Mesh3d(meshes.add(Cuboid::new(0.5, 0.5, 0.5))),
52 InstanceMaterialData(
53 (1..=10)
54 .flat_map(|x| (1..=10).map(move |y| (x as f32 / 10.0, y as f32 / 10.0)))
55 .map(|(x, y)| InstanceData {
56 position: Vec3::new(x * 10.0 - 5.0, y * 10.0 - 5.0, 0.0),
57 scale: 1.0,
58 color: LinearRgba::from(Color::hsla(x * 360., y, 0.5, 1.0)).to_f32_array(),
59 })
60 .collect(),
61 ),
62 // NOTE: Frustum culling is done based on the Aabb of the Mesh and the GlobalTransform.
63 // As the cube is at the origin, if its Aabb moves outside the view frustum, all the
64 // instanced cubes will be culled.
65 // The InstanceMaterialData contains the 'GlobalTransform' information for this custom
66 // instancing, and that is not taken into account with the built-in frustum culling.
67 // We must disable the built-in frustum culling by adding the `NoFrustumCulling` marker
68 // component to avoid incorrect culling.
69 NoFrustumCulling,
70 ));
71
72 // camera
73 commands.spawn((
74 Camera3d::default(),
75 Transform::from_xyz(0.0, 0.0, 15.0).looking_at(Vec3::ZERO, Vec3::Y),
76 // We need this component because we use `draw_indexed` and `draw`
77 // instead of `draw_indirect_indexed` and `draw_indirect` in
78 // `DrawMeshInstanced::render`.
79 NoIndirectDrawing,
80 ));
81}
More examples
155 pub fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
156 commands.spawn((Camera2d, StateScoped(super::Scene::Text)));
157
158 for (i, justify) in [
159 JustifyText::Left,
160 JustifyText::Right,
161 JustifyText::Center,
162 JustifyText::Justified,
163 ]
164 .into_iter()
165 .enumerate()
166 {
167 let y = 230. - 150. * i as f32;
168 spawn_anchored_text(&mut commands, -300. * Vec3::X + y * Vec3::Y, justify, None);
169 spawn_anchored_text(
170 &mut commands,
171 300. * Vec3::X + y * Vec3::Y,
172 justify,
173 Some(TextBounds::new(150., 55.)),
174 );
175 }
176
177 let sans_serif = TextFont::from_font(asset_server.load("fonts/FiraSans-Bold.ttf"));
178
179 const NUM_ITERATIONS: usize = 10;
180 for i in 0..NUM_ITERATIONS {
181 let fraction = i as f32 / (NUM_ITERATIONS - 1) as f32;
182
183 commands.spawn((
184 Text2d::new("Bevy"),
185 sans_serif.clone(),
186 Transform::from_xyz(0.0, fraction * 200.0, i as f32)
187 .with_scale(1.0 + Vec2::splat(fraction).extend(1.))
188 .with_rotation(Quat::from_rotation_z(fraction * core::f32::consts::PI)),
189 TextColor(Color::hsla(fraction * 360.0, 0.8, 0.8, 0.8)),
190 StateScoped(super::Scene::Text),
191 ));
192 }
193
194 commands.spawn((
195 Text2d::new("This text is invisible."),
196 Visibility::Hidden,
197 StateScoped(super::Scene::Text),
198 ));
199 }
Sourcepub const fn hsl(hue: f32, saturation: f32, lightness: f32) -> Color
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.
§Arguments
hue
- Hue channel. [0.0, 360.0]saturation
- Saturation channel. [0.0, 1.0]lightness
- Lightness channel. [0.0, 1.0]
Examples found in repository?
More examples
88fn animate_materials(
89 material_handles: Query<&MeshMaterial3d<StandardMaterial>>,
90 time: Res<Time>,
91 mut materials: ResMut<Assets<StandardMaterial>>,
92) {
93 for (i, material_handle) in material_handles.iter().enumerate() {
94 if let Some(material) = materials.get_mut(material_handle) {
95 let color = Color::hsl(
96 ((i as f32 * 2.345 + time.elapsed_secs()) * 100.0) % 360.0,
97 1.0,
98 0.5,
99 );
100 material.base_color = color;
101 }
102 }
103}
89fn animate(
90 mut materials: ResMut<Assets<CustomUiMaterial>>,
91 q: Query<&MaterialNode<CustomUiMaterial>>,
92 time: Res<Time>,
93) {
94 let duration = 2.0;
95 for handle in &q {
96 if let Some(material) = materials.get_mut(handle) {
97 // rainbow color effect
98 let new_color = Color::hsl((time.elapsed_secs() * 60.0) % 360.0, 1., 0.5);
99 let border_color = Color::hsl((time.elapsed_secs() * 60.0) % 360.0, 0.75, 0.75);
100 material.color = new_color.to_linear().to_vec4();
101 material.slider.x =
102 ((time.elapsed_secs() % (duration * 2.0)) - duration).abs() / duration;
103 material.border_color = border_color.to_linear().to_vec4();
104 }
105 }
106}
105fn setup_scene(
106 mut commands: Commands,
107 mut meshes: ResMut<Assets<Mesh>>,
108 mut materials: ResMut<Assets<ColorMaterial>>,
109) {
110 commands.spawn(Camera2d);
111
112 let named_shapes = [
113 (Name::new("Annulus"), meshes.add(Annulus::new(25.0, 50.0))),
114 (
115 Name::new("Bestagon"),
116 meshes.add(RegularPolygon::new(50.0, 6)),
117 ),
118 (Name::new("Rhombus"), meshes.add(Rhombus::new(75.0, 100.0))),
119 ];
120 let num_shapes = named_shapes.len();
121
122 for (i, (name, shape)) in named_shapes.into_iter().enumerate() {
123 // Distribute colors evenly across the rainbow.
124 let color = Color::hsl(360. * i as f32 / num_shapes as f32, 0.95, 0.7);
125
126 commands.spawn((
127 name,
128 DisableOnClick,
129 Mesh2d(shape),
130 MeshMaterial2d(materials.add(color)),
131 Transform::from_xyz(
132 // Distribute shapes from -X_EXTENT/2 to +X_EXTENT/2.
133 -X_EXTENT / 2. + i as f32 / (num_shapes - 1) as f32 * X_EXTENT,
134 0.0,
135 0.0,
136 ),
137 ));
138 }
139}
67 pub fn setup(
68 mut commands: Commands,
69 mut meshes: ResMut<Assets<Mesh>>,
70 mut materials: ResMut<Assets<ColorMaterial>>,
71 ) {
72 commands.spawn((Camera2d, StateScoped(super::Scene::Shapes)));
73
74 let shapes = [
75 meshes.add(Circle::new(50.0)),
76 meshes.add(CircularSector::new(50.0, 1.0)),
77 meshes.add(CircularSegment::new(50.0, 1.25)),
78 meshes.add(Ellipse::new(25.0, 50.0)),
79 meshes.add(Annulus::new(25.0, 50.0)),
80 meshes.add(Capsule2d::new(25.0, 50.0)),
81 meshes.add(Rhombus::new(75.0, 100.0)),
82 meshes.add(Rectangle::new(50.0, 100.0)),
83 meshes.add(RegularPolygon::new(50.0, 6)),
84 meshes.add(Triangle2d::new(
85 Vec2::Y * 50.0,
86 Vec2::new(-50.0, -50.0),
87 Vec2::new(50.0, -50.0),
88 )),
89 ];
90 let num_shapes = shapes.len();
91
92 for (i, shape) in shapes.into_iter().enumerate() {
93 // Distribute colors evenly across the rainbow.
94 let color = Color::hsl(360. * i as f32 / num_shapes as f32, 0.95, 0.7);
95
96 commands.spawn((
97 Mesh2d(shape),
98 MeshMaterial2d(materials.add(color)),
99 Transform::from_xyz(
100 // Distribute shapes from -X_EXTENT/2 to +X_EXTENT/2.
101 -X_EXTENT / 2. + i as f32 / (num_shapes - 1) as f32 * X_EXTENT,
102 0.0,
103 0.0,
104 ),
105 StateScoped(super::Scene::Shapes),
106 ));
107 }
108 }
25fn setup(
26 mut commands: Commands,
27 mut meshes: ResMut<Assets<Mesh>>,
28 mut materials: ResMut<Assets<ColorMaterial>>,
29) {
30 commands.spawn(Camera2d);
31
32 let shapes = [
33 meshes.add(Circle::new(50.0)),
34 meshes.add(CircularSector::new(50.0, 1.0)),
35 meshes.add(CircularSegment::new(50.0, 1.25)),
36 meshes.add(Ellipse::new(25.0, 50.0)),
37 meshes.add(Annulus::new(25.0, 50.0)),
38 meshes.add(Capsule2d::new(25.0, 50.0)),
39 meshes.add(Rhombus::new(75.0, 100.0)),
40 meshes.add(Rectangle::new(50.0, 100.0)),
41 meshes.add(RegularPolygon::new(50.0, 6)),
42 meshes.add(Triangle2d::new(
43 Vec2::Y * 50.0,
44 Vec2::new(-50.0, -50.0),
45 Vec2::new(50.0, -50.0),
46 )),
47 ];
48 let num_shapes = shapes.len();
49
50 for (i, shape) in shapes.into_iter().enumerate() {
51 // Distribute colors evenly across the rainbow.
52 let color = Color::hsl(360. * i as f32 / num_shapes as f32, 0.95, 0.7);
53
54 commands.spawn((
55 Mesh2d(shape),
56 MeshMaterial2d(materials.add(color)),
57 Transform::from_xyz(
58 // Distribute shapes from -X_EXTENT/2 to +X_EXTENT/2.
59 -X_EXTENT / 2. + i as f32 / (num_shapes - 1) as f32 * X_EXTENT,
60 0.0,
61 0.0,
62 ),
63 ));
64 }
65
66 #[cfg(not(target_arch = "wasm32"))]
67 commands.spawn((
68 Text::new("Press space to toggle wireframes"),
69 Node {
70 position_type: PositionType::Absolute,
71 top: Val::Px(12.0),
72 left: Val::Px(12.0),
73 ..default()
74 },
75 ));
76}
Sourcepub const fn hsva(hue: f32, saturation: f32, value: f32, alpha: f32) -> Color
pub const fn hsva(hue: f32, saturation: f32, value: f32, alpha: f32) -> Color
Creates a new Color
object storing a Hsva
color.
§Arguments
hue
- Hue channel. [0.0, 360.0]saturation
- Saturation channel. [0.0, 1.0]value
- Value channel. [0.0, 1.0]alpha
- Alpha channel. [0.0, 1.0]
Examples found in repository?
75fn setup(
76 mut commands: Commands,
77 asset_server: Res<AssetServer>,
78 app_status: Res<AppStatus>,
79 mut meshes: ResMut<Assets<Mesh>>,
80 mut standard_materials: ResMut<Assets<StandardMaterial>>,
81) {
82 // Spawns a camera.
83 commands.spawn((
84 Transform::from_xyz(-2.0, 0.0, 3.5).looking_at(Vec3::ZERO, Vec3::Y),
85 Camera {
86 hdr: true,
87 ..default()
88 },
89 Camera3d::default(),
90 Skybox {
91 image: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
92 brightness: 3000.0,
93 ..default()
94 },
95 EnvironmentMapLight {
96 diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"),
97 specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
98 // We want relatively high intensity here in order for the specular
99 // tint to show up well.
100 intensity: 25000.0,
101 ..default()
102 },
103 ));
104
105 // Spawn the sphere.
106 commands.spawn((
107 Transform::from_rotation(Quat::from_rotation_x(PI * 0.5)),
108 Mesh3d(meshes.add(Sphere::default().mesh().uv(32, 18))),
109 MeshMaterial3d(standard_materials.add(StandardMaterial {
110 // We want only reflected specular light here, so we set the base
111 // color as black.
112 base_color: Color::BLACK,
113 reflectance: 1.0,
114 specular_tint: Color::hsva(app_status.hue, 1.0, 1.0, 1.0),
115 // The object must not be metallic, or else the reflectance is
116 // ignored per the Filament spec:
117 //
118 // <https://google.github.io/filament/Filament.html#listing_fnormal>
119 metallic: 0.0,
120 perceptual_roughness: 0.0,
121 ..default()
122 })),
123 ));
124
125 // Spawn the help text.
126 commands.spawn((
127 Node {
128 position_type: PositionType::Absolute,
129 bottom: Val::Px(12.0),
130 left: Val::Px(12.0),
131 ..default()
132 },
133 app_status.create_text(),
134 ));
135}
136
137/// Rotates the camera a bit every frame.
138fn rotate_camera(mut cameras: Query<&mut Transform, With<Camera3d>>) {
139 for mut camera_transform in cameras.iter_mut() {
140 camera_transform.translation =
141 Quat::from_rotation_y(ROTATION_SPEED) * camera_transform.translation;
142 camera_transform.look_at(Vec3::ZERO, Vec3::Y);
143 }
144}
145
146/// Alters the hue of the solid color a bit every frame.
147fn shift_hue(
148 mut app_status: ResMut<AppStatus>,
149 objects_with_materials: Query<&MeshMaterial3d<StandardMaterial>>,
150 mut standard_materials: ResMut<Assets<StandardMaterial>>,
151) {
152 if app_status.tint_type != TintType::Solid {
153 return;
154 }
155
156 app_status.hue += HUE_SHIFT_SPEED;
157
158 for material_handle in objects_with_materials.iter() {
159 let Some(material) = standard_materials.get_mut(material_handle) else {
160 continue;
161 };
162 material.specular_tint = Color::hsva(app_status.hue, 1.0, 1.0, 1.0);
163 }
164}
Sourcepub const fn hsv(hue: f32, saturation: f32, value: f32) -> Color
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.
§Arguments
hue
- Hue channel. [0.0, 360.0]saturation
- Saturation channel. [0.0, 1.0]value
- Value channel. [0.0, 1.0]
Examples found in repository?
24fn setup(
25 mut commands: Commands,
26 mut meshes: ResMut<Assets<Mesh>>,
27 mut materials: ResMut<Assets<StandardMaterial>>,
28 window: Query<&Window>,
29) -> Result {
30 // circular base
31 commands.spawn((
32 Mesh3d(meshes.add(Circle::new(4.0))),
33 MeshMaterial3d(materials.add(Color::WHITE)),
34 Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
35 ));
36
37 // cube
38 commands.spawn((
39 Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
40 MeshMaterial3d(materials.add(Color::WHITE)),
41 Transform::from_xyz(0.0, 0.5, 0.0),
42 ));
43
44 // lights
45 for i in 0..NUM_LIGHTS {
46 let angle = (i as f32) / (NUM_LIGHTS as f32) * PI * 2.0;
47 commands.spawn((
48 PointLight {
49 color: Color::hsv(angle.to_degrees(), 1.0, 1.0),
50 intensity: 2_000_000.0 / NUM_LIGHTS as f32,
51 shadows_enabled: true,
52 ..default()
53 },
54 Transform::from_xyz(sin(angle) * 4.0, 2.0, cos(angle) * 4.0),
55 ));
56 }
57
58 // cameras
59 let window = window.single()?;
60 let width = window.resolution.width() / CAMERA_COLS as f32 * window.resolution.scale_factor();
61 let height = window.resolution.height() / CAMERA_ROWS as f32 * window.resolution.scale_factor();
62 let mut i = 0;
63 for y in 0..CAMERA_COLS {
64 for x in 0..CAMERA_ROWS {
65 let angle = i as f32 / (CAMERA_ROWS * CAMERA_COLS) as f32 * PI * 2.0;
66 commands.spawn((
67 Camera3d::default(),
68 Camera {
69 viewport: Some(Viewport {
70 physical_position: UVec2::new(
71 (x as f32 * width) as u32,
72 (y as f32 * height) as u32,
73 ),
74 physical_size: UVec2::new(width as u32, height as u32),
75 ..default()
76 }),
77 order: i,
78 ..default()
79 },
80 Transform::from_xyz(sin(angle) * 4.0, 2.5, cos(angle) * 4.0)
81 .looking_at(Vec3::ZERO, Vec3::Y),
82 ));
83 i += 1;
84 }
85 }
86 Ok(())
87}
Trait Implementations§
Source§impl Alpha for Color
impl Alpha for Color
Source§fn with_alpha(&self, alpha: f32) -> Color
fn with_alpha(&self, alpha: f32) -> Color
Source§fn is_fully_transparent(&self) -> bool
fn is_fully_transparent(&self) -> bool
Source§fn is_fully_opaque(&self) -> bool
fn is_fully_opaque(&self) -> bool
Source§impl Default for Color
impl Default for Color
Source§fn default() -> Color
fn default() -> Color
A fully white Color::LinearRgba
color with an alpha of 1.0.
Source§impl<'de> Deserialize<'de> for Color
impl<'de> Deserialize<'de> for Color
Source§fn deserialize<__D>(
__deserializer: __D,
) -> Result<Color, <__D as Deserializer<'de>>::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(
__deserializer: __D,
) -> Result<Color, <__D as Deserializer<'de>>::Error>where
__D: Deserializer<'de>,
Source§impl Enum for Colorwhere
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,
impl Enum for Colorwhere
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)>
fn field(&self, __name_param: &str) -> Option<&(dyn PartialReflect + 'static)>
Source§fn field_at(
&self,
__index_param: usize,
) -> Option<&(dyn PartialReflect + 'static)>
fn field_at( &self, __index_param: usize, ) -> Option<&(dyn PartialReflect + 'static)>
Source§fn field_mut(
&mut self,
__name_param: &str,
) -> Option<&mut (dyn PartialReflect + 'static)>
fn field_mut( &mut self, __name_param: &str, ) -> Option<&mut (dyn PartialReflect + 'static)>
Source§fn field_at_mut(
&mut self,
__index_param: usize,
) -> Option<&mut (dyn PartialReflect + 'static)>
fn field_at_mut( &mut self, __index_param: usize, ) -> Option<&mut (dyn PartialReflect + 'static)>
Source§fn index_of(&self, __name_param: &str) -> Option<usize>
fn index_of(&self, __name_param: &str) -> Option<usize>
Source§fn name_at(&self, __index_param: usize) -> Option<&str>
fn name_at(&self, __index_param: usize) -> Option<&str>
Source§fn iter_fields(&self) -> VariantFieldIter<'_> ⓘ
fn iter_fields(&self) -> VariantFieldIter<'_> ⓘ
Source§fn variant_name(&self) -> &str
fn variant_name(&self) -> &str
Source§fn variant_index(&self) -> usize
fn variant_index(&self) -> usize
Source§fn variant_type(&self) -> VariantType
fn variant_type(&self) -> VariantType
Source§fn to_dynamic_enum(&self) -> DynamicEnum
fn to_dynamic_enum(&self) -> DynamicEnum
DynamicEnum
from this enum.Source§fn clone_dynamic(&self) -> DynamicEnum
fn clone_dynamic(&self) -> DynamicEnum
to_dynamic_enum
insteadSource§fn is_variant(&self, variant_type: VariantType) -> bool
fn is_variant(&self, variant_type: VariantType) -> bool
Source§fn variant_path(&self) -> String
fn variant_path(&self) -> String
Source§impl EuclideanDistance for Color
impl EuclideanDistance for Color
Source§impl From<Color> for ClearColorConfig
impl From<Color> for ClearColorConfig
Source§fn from(value: Color) -> ClearColorConfig
fn from(value: Color) -> ClearColorConfig
Source§impl From<Color> for ColorMaterial
impl From<Color> for ColorMaterial
Source§fn from(color: Color) -> ColorMaterial
fn from(color: Color) -> ColorMaterial
Source§impl From<Color> for LinearRgba
impl From<Color> for LinearRgba
Source§fn from(value: Color) -> LinearRgba
fn from(value: Color) -> LinearRgba
Source§impl From<Color> for StandardMaterial
impl From<Color> for StandardMaterial
Source§fn from(color: Color) -> StandardMaterial
fn from(color: Color) -> StandardMaterial
Source§impl From<LinearRgba> for Color
impl From<LinearRgba> for Color
Source§fn from(value: LinearRgba) -> Color
fn from(value: LinearRgba) -> Color
Source§impl FromArg for &'static Colorwhere
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,
impl FromArg for &'static Colorwhere
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§impl FromArg for &'static mut Colorwhere
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,
impl FromArg for &'static mut Colorwhere
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§impl FromArg for Colorwhere
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,
impl FromArg for Colorwhere
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§impl FromReflect for Colorwhere
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,
impl FromReflect for Colorwhere
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>
fn from_reflect(__param0: &(dyn PartialReflect + 'static)) -> Option<Color>
Self
from a reflected value.Source§fn take_from_reflect(
reflect: Box<dyn PartialReflect>,
) -> Result<Self, Box<dyn PartialReflect>>
fn take_from_reflect( reflect: Box<dyn PartialReflect>, ) -> Result<Self, Box<dyn PartialReflect>>
Self
using,
constructing the value using from_reflect
if that fails. Read moreSource§impl GetOwnership for &Colorwhere
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,
impl GetOwnership for &Colorwhere
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§impl GetOwnership for &mut Colorwhere
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,
impl GetOwnership for &mut Colorwhere
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§impl GetOwnership for Colorwhere
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,
impl GetOwnership for Colorwhere
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§impl GetTypeRegistration for Colorwhere
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,
impl GetTypeRegistration for Colorwhere
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
fn get_type_registration() -> TypeRegistration
TypeRegistration
for this type.Source§fn register_type_dependencies(registry: &mut TypeRegistry)
fn register_type_dependencies(registry: &mut TypeRegistry)
Source§impl Hue for Color
impl Hue for Color
Source§impl IntoReturn for &Colorwhere
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,
impl IntoReturn for &Colorwhere
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§impl IntoReturn for &mut Colorwhere
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,
impl IntoReturn for &mut Colorwhere
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§impl IntoReturn for Colorwhere
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,
impl IntoReturn for Colorwhere
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§impl Luminance for Color
impl Luminance for Color
Source§fn with_luminance(&self, value: f32) -> Color
fn with_luminance(&self, value: f32) -> Color
Source§fn darker(&self, amount: f32) -> Color
fn darker(&self, amount: f32) -> Color
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 moreSource§fn lighter(&self, amount: f32) -> Color
fn lighter(&self, amount: f32) -> Color
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 moreSource§impl Mix for Color
impl Mix for Color
Source§fn mix(&self, other: &Color, factor: f32) -> Color
fn mix(&self, other: &Color, factor: f32) -> Color
Source§fn mix_assign(&mut self, other: Self, factor: f32)
fn mix_assign(&mut self, other: Self, factor: f32)
Source§impl PartialReflect for Colorwhere
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,
impl PartialReflect for Colorwhere
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>
fn get_represented_type_info(&self) -> Option<&'static TypeInfo>
Source§fn try_apply(
&mut self,
__value_param: &(dyn PartialReflect + 'static),
) -> Result<(), ApplyError>
fn try_apply( &mut self, __value_param: &(dyn PartialReflect + 'static), ) -> Result<(), ApplyError>
Source§fn reflect_kind(&self) -> ReflectKind
fn reflect_kind(&self) -> ReflectKind
Source§fn reflect_ref(&self) -> ReflectRef<'_>
fn reflect_ref(&self) -> ReflectRef<'_>
Source§fn reflect_mut(&mut self) -> ReflectMut<'_>
fn reflect_mut(&mut self) -> ReflectMut<'_>
Source§fn reflect_owned(self: Box<Color>) -> ReflectOwned
fn reflect_owned(self: Box<Color>) -> ReflectOwned
Source§fn try_into_reflect(
self: Box<Color>,
) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>>
fn try_into_reflect( self: Box<Color>, ) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>>
Source§fn try_as_reflect(&self) -> Option<&(dyn Reflect + 'static)>
fn try_as_reflect(&self) -> Option<&(dyn Reflect + 'static)>
Source§fn try_as_reflect_mut(&mut self) -> Option<&mut (dyn Reflect + 'static)>
fn try_as_reflect_mut(&mut self) -> Option<&mut (dyn Reflect + 'static)>
Source§fn into_partial_reflect(self: Box<Color>) -> Box<dyn PartialReflect>
fn into_partial_reflect(self: Box<Color>) -> Box<dyn PartialReflect>
Source§fn as_partial_reflect(&self) -> &(dyn PartialReflect + 'static)
fn as_partial_reflect(&self) -> &(dyn PartialReflect + 'static)
Source§fn as_partial_reflect_mut(&mut self) -> &mut (dyn PartialReflect + 'static)
fn as_partial_reflect_mut(&mut self) -> &mut (dyn PartialReflect + 'static)
Source§fn reflect_hash(&self) -> Option<u64>
fn reflect_hash(&self) -> Option<u64>
Source§fn reflect_partial_eq(
&self,
value: &(dyn PartialReflect + 'static),
) -> Option<bool>
fn reflect_partial_eq( &self, value: &(dyn PartialReflect + 'static), ) -> Option<bool>
Source§fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError>
fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError>
Self
using reflection. Read moreSource§fn apply(&mut self, value: &(dyn PartialReflect + 'static))
fn apply(&mut self, value: &(dyn PartialReflect + 'static))
Source§fn clone_value(&self) -> Box<dyn PartialReflect>
fn clone_value(&self) -> Box<dyn PartialReflect>
reflect_clone
. To convert reflected values to dynamic ones, use to_dynamic
.Self
into its dynamic representation. Read moreSource§fn to_dynamic(&self) -> Box<dyn PartialReflect>
fn to_dynamic(&self) -> Box<dyn PartialReflect>
Source§fn debug(&self, f: &mut Formatter<'_>) -> Result<(), Error>
fn debug(&self, f: &mut Formatter<'_>) -> Result<(), Error>
Source§fn is_dynamic(&self) -> bool
fn is_dynamic(&self) -> bool
Source§impl Reflect for Colorwhere
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,
impl Reflect for Colorwhere
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 as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut dyn Any
. Read moreSource§fn into_reflect(self: Box<Color>) -> Box<dyn Reflect>
fn into_reflect(self: Box<Color>) -> Box<dyn Reflect>
Source§fn as_reflect(&self) -> &(dyn Reflect + 'static)
fn as_reflect(&self) -> &(dyn Reflect + 'static)
Source§fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)
fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)
Source§impl Saturation for Color
impl Saturation for Color
Source§fn with_saturation(&self, saturation: f32) -> Color
fn with_saturation(&self, saturation: f32) -> Color
Source§fn saturation(&self) -> f32
fn saturation(&self) -> f32
Source§fn set_saturation(&mut self, saturation: f32)
fn set_saturation(&mut self, saturation: f32)
Source§impl Serialize for Color
impl Serialize for Color
Source§fn serialize<__S>(
&self,
__serializer: __S,
) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>where
__S: Serializer,
fn serialize<__S>(
&self,
__serializer: __S,
) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>where
__S: Serializer,
Source§impl TypePath for Color
impl TypePath for Color
Source§fn type_path() -> &'static str
fn type_path() -> &'static str
Source§fn short_type_path() -> &'static str
fn short_type_path() -> &'static str
Source§fn type_ident() -> Option<&'static str>
fn type_ident() -> Option<&'static str>
Source§fn crate_name() -> Option<&'static str>
fn crate_name() -> Option<&'static str>
Source§impl Typed for Colorwhere
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,
impl Typed for Colorwhere
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,
impl Copy for Color
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, U> AsBindGroupShaderType<U> for T
impl<T, U> AsBindGroupShaderType<U> for T
Source§fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U
fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U
T
ShaderType
for self
. When used in AsBindGroup
derives, it is safe to assume that all images in self
exist.Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait>
(where Trait: Downcast
) to Box<dyn Any>
, which can then be
downcast
into Box<dyn ConcreteType>
where ConcreteType
implements Trait
.Source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait>
(where Trait: Downcast
) to Rc<Any>
, which can then be further
downcast
into Rc<ConcreteType>
where ConcreteType
implements Trait
.Source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&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)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&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> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
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>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
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)
fn as_any(&self) -> &(dyn Any + 'static)
&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)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&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> DowncastSend for T
impl<T> DowncastSend for T
Source§impl<T> DowncastSync for T
impl<T> DowncastSync for T
Source§impl<T> DynamicTypePath for Twhere
T: TypePath,
impl<T> DynamicTypePath for Twhere
T: TypePath,
Source§fn reflect_type_path(&self) -> &str
fn reflect_type_path(&self) -> &str
TypePath::type_path
.Source§fn reflect_short_type_path(&self) -> &str
fn reflect_short_type_path(&self) -> &str
Source§fn reflect_type_ident(&self) -> Option<&str>
fn reflect_type_ident(&self) -> Option<&str>
TypePath::type_ident
.Source§fn reflect_crate_name(&self) -> Option<&str>
fn reflect_crate_name(&self) -> Option<&str>
TypePath::crate_name
.Source§fn reflect_module_path(&self) -> Option<&str>
fn reflect_module_path(&self) -> Option<&str>
Source§impl<T> DynamicTyped for Twhere
T: Typed,
impl<T> DynamicTyped for Twhere
T: Typed,
Source§fn reflect_type_info(&self) -> &'static TypeInfo
fn reflect_type_info(&self) -> &'static TypeInfo
Typed::type_info
.Source§impl<T> FmtForward for T
impl<T> FmtForward for T
Source§fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
self
to use its Binary
implementation when Debug
-formatted.Source§fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
self
to use its Display
implementation when
Debug
-formatted.Source§fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
self
to use its LowerExp
implementation when
Debug
-formatted.Source§fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
self
to use its LowerHex
implementation when
Debug
-formatted.Source§fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
self
to use its Octal
implementation when Debug
-formatted.Source§fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
self
to use its Pointer
implementation when
Debug
-formatted.Source§fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
self
to use its UpperExp
implementation when
Debug
-formatted.Source§fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
self
to use its UpperHex
implementation when
Debug
-formatted.Source§impl<S> FromSample<S> for S
impl<S> FromSample<S> for S
fn from_sample_(s: S) -> S
Source§impl<T> FromWorld for Twhere
T: Default,
impl<T> FromWorld for Twhere
T: Default,
Source§fn from_world(_world: &mut World) -> T
fn from_world(_world: &mut World) -> T
Creates Self
using default()
.
Source§impl<T> GetPath for T
impl<T> GetPath for T
Source§fn reflect_path<'p>(
&self,
path: impl ReflectPath<'p>,
) -> Result<&(dyn PartialReflect + 'static), ReflectPathError<'p>>
fn reflect_path<'p>( &self, path: impl ReflectPath<'p>, ) -> Result<&(dyn PartialReflect + 'static), ReflectPathError<'p>>
path
. Read moreSource§fn reflect_path_mut<'p>(
&mut self,
path: impl ReflectPath<'p>,
) -> Result<&mut (dyn PartialReflect + 'static), ReflectPathError<'p>>
fn reflect_path_mut<'p>( &mut self, path: impl ReflectPath<'p>, ) -> Result<&mut (dyn PartialReflect + 'static), ReflectPathError<'p>>
path
. Read moreSource§fn path<'p, T>(
&self,
path: impl ReflectPath<'p>,
) -> Result<&T, ReflectPathError<'p>>where
T: Reflect,
fn path<'p, T>(
&self,
path: impl ReflectPath<'p>,
) -> Result<&T, ReflectPathError<'p>>where
T: Reflect,
path
. Read moreSource§fn path_mut<'p, T>(
&mut self,
path: impl ReflectPath<'p>,
) -> Result<&mut T, ReflectPathError<'p>>where
T: Reflect,
fn path_mut<'p, T>(
&mut self,
path: impl ReflectPath<'p>,
) -> Result<&mut T, ReflectPathError<'p>>where
T: Reflect,
path
. Read moreSource§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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 moreSource§impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
fn into_sample(self) -> T
Source§impl<T> Pipe for Twhere
T: ?Sized,
impl<T> Pipe for Twhere
T: ?Sized,
Source§fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
Source§fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
self
and passes that borrow into the pipe function. Read moreSource§fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
self
and passes that borrow into the pipe function. Read moreSource§fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
Source§fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R,
) -> R
fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
Source§fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
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
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
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
fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
self
, then passes self.deref()
into the pipe function.Source§impl<T> Pointable for T
impl<T> Pointable for T
Source§impl<R, P> ReadPrimitive<R> for P
impl<R, P> ReadPrimitive<R> for P
Source§fn read_from_little_endian(read: &mut R) -> Result<Self, Error>
fn read_from_little_endian(read: &mut R) -> Result<Self, Error>
ReadEndian::read_from_little_endian()
.Source§impl<T> Serialize for T
impl<T> Serialize for T
fn erased_serialize(&self, serializer: &mut dyn Serializer) -> Result<(), Error>
fn do_erased_serialize( &self, serializer: &mut dyn Serializer, ) -> Result<(), ErrorImpl>
Source§impl<T> Tap for T
impl<T> Tap for T
Source§fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
Borrow<B>
of a value. Read moreSource§fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
BorrowMut<B>
of a value. Read moreSource§fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
AsRef<R>
view of a value. Read moreSource§fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
AsMut<R>
view of a value. Read moreSource§fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
Deref::Target
of a value. Read moreSource§fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
Deref::Target
of a value. Read moreSource§fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
.tap()
only in debug builds, and is erased in release builds.Source§fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
.tap_mut()
only in debug builds, and is erased in release
builds.Source§fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
.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
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
.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
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
.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
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
.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
fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
.tap_deref()
only in debug builds, and is erased in release
builds.