pub enum Color {
}bevy_color only.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.
Okhsla(Okhsla)
A color in the Okhsl color space with alpha.
Okhsva(Okhsva)
A color in the Okhsv color space with alpha.
Okhwba(Okhwba)
A color in the Okhwb 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?
90fn animate(
91 mut materials: ResMut<Assets<CustomUiMaterial>>,
92 q: Query<&MaterialNode<CustomUiMaterial>>,
93 time: Res<Time>,
94) {
95 let duration = 2.0;
96 for handle in &q {
97 if let Some(mut material) = materials.get_mut(handle) {
98 // rainbow color effect
99 let new_color = Color::hsl((time.elapsed_secs() * 60.0) % 360.0, 1., 0.5);
100 let border_color = Color::hsl((time.elapsed_secs() * 60.0) % 360.0, 0.75, 0.75);
101 material.color = new_color.to_linear().to_vec4();
102 material.slider.x =
103 ((time.elapsed_secs() % (duration * 2.0)) - duration).abs() / duration;
104 material.border_color = border_color.to_linear().to_vec4();
105 }
106 }
107}More examples
217fn spawn_light_textures(
218 commands: &mut Commands,
219 asset_server: &AssetServer,
220 meshes: &mut Assets<Mesh>,
221 materials: &mut Assets<StandardMaterial>,
222) {
223 commands.spawn((
224 SpotLight {
225 color: Color::srgb(1.0, 1.0, 0.8),
226 intensity: 10e6,
227 outer_angle: 0.25,
228 inner_angle: 0.25,
229 shadow_maps_enabled: true,
230 ..default()
231 },
232 Transform::from_translation(Vec3::new(6.0, 1.0, 2.0)).looking_at(Vec3::ZERO, Vec3::Y),
233 BaseScale(Vec3::ONE),
234 SpotLightTexture {
235 image: asset_server.load("lightmaps/torch_spotlight_texture.png"),
236 },
237 Visibility::Inherited,
238 Selection::SpotLight,
239 ));
240
241 commands.spawn((
242 Visibility::Hidden,
243 Transform::from_translation(Vec3::new(0.0, 1.8, 0.01)).with_scale(Vec3::splat(0.25)),
244 BaseScale(Vec3::splat(0.25)),
245 Selection::PointLight,
246 children![
247 WorldAssetRoot(
248 asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/Faces/faces.glb")),
249 ),
250 (
251 Mesh3d(meshes.add(Sphere::new(1.0))),
252 MeshMaterial3d(materials.add(StandardMaterial {
253 emissive: Color::srgb(0.0, 0.0, 300.0).to_linear(),
254 ..default()
255 })),
256 ),
257 (
258 PointLight {
259 color: Color::srgb(0.0, 0.0, 1.0),
260 intensity: 1e6,
261 shadow_maps_enabled: true,
262 ..default()
263 },
264 PointLightTexture {
265 image: asset_server.load("lightmaps/faces_pointlight_texture_blurred.png"),
266 cubemap_layout: CubemapLayout::CrossVertical,
267 },
268 )
269 ],
270 ));
271}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?
102fn on_drag_enter(
103 mut event: On<PointerDragEnter>,
104 button: Single<Entity, With<DraggableButton>>,
105 mut commands: Commands,
106 mut meshes: ResMut<Assets<Mesh>>,
107 mut materials: ResMut<Assets<ColorMaterial>>,
108) {
109 if event.dragged == *button {
110 let Some(position) = event.hit.position else {
111 return;
112 };
113 commands.spawn((
114 GhostPreview,
115 Mesh2d(meshes.add(Circle::new(ELEMENT_SIZE))),
116 MeshMaterial2d(materials.add(Color::srgba(1.0, 1.0, 0.6, 0.5))),
117 Transform::from_translation(position + 2. * Vec3::Z),
118 Pickable::IGNORE,
119 ));
120 event.propagate(false);
121 }
122}More examples
140fn spawn_coated_glass_bubble_sphere(
141 commands: &mut Commands,
142 materials: &mut Assets<StandardMaterial>,
143 sphere: &Handle<Mesh>,
144) {
145 commands
146 .spawn((
147 Mesh3d(sphere.clone()),
148 MeshMaterial3d(materials.add(StandardMaterial {
149 clearcoat: 1.0,
150 clearcoat_perceptual_roughness: 0.1,
151 metallic: 0.5,
152 perceptual_roughness: 0.1,
153 base_color: Color::srgba(0.9, 0.9, 0.9, 0.3),
154 alpha_mode: AlphaMode::Blend,
155 ..default()
156 })),
157 Transform::from_xyz(-1.0, -1.0, 0.0).with_scale(Vec3::splat(SPHERE_SCALE)),
158 ))
159 .insert(ExampleSphere);
160}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}26fn setup_system(
27 mut commands: Commands,
28 mut meshes: ResMut<Assets<Mesh>>,
29 mut standard_materials: ResMut<Assets<StandardMaterial>>,
30) {
31 commands.spawn((
32 // You need to spawn an entity with this component
33 InfiniteGrid,
34 // Optional component you can use to configure the grid
35 InfiniteGridSettings::default(),
36 ));
37
38 commands.spawn((
39 Camera3d::default(),
40 Transform::from_xyz(-12.5, 5.0, 10.0).looking_at(Vec3::ZERO, Vec3::Y),
41 FreeCamera::default(),
42 ));
43
44 commands.spawn((
45 DirectionalLight { ..default() },
46 Transform::from_translation(Vec3::X * 15. + Vec3::Y * 20.).looking_at(Vec3::ZERO, Vec3::Y),
47 ));
48
49 // cube
50 commands.spawn((
51 Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
52 MeshMaterial3d(
53 standard_materials.add(StandardMaterial::from_color(Color::srgba(
54 1.0, 1.0, 1.0, 0.5,
55 ))),
56 ),
57 Transform::from_xyz(0.0, 2.0, 0.0),
58 ));
59
60 commands.spawn((
61 Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
62 MeshMaterial3d(
63 standard_materials.add(StandardMaterial::from_color(Color::srgba(
64 1.0, 1.0, 1.0, 0.5,
65 ))),
66 ),
67 Transform::from_xyz(0.0, -2.0, 0.0),
68 ));
69}405fn spawn_ui(commands: &mut Commands) {
406 commands.spawn((
407 Node {
408 position_type: PositionType::Absolute,
409 bottom: px(12.0),
410 left: px(12.0),
411 flex_direction: FlexDirection::Column,
412 align_items: AlignItems::FlexStart,
413 padding: px(10.0).all(),
414 border_radius: BorderRadius::all(px(4.0)),
415 ..default()
416 },
417 BackgroundColor(Color::srgba(0.0, 0.0, 0.0, 0.92)),
418 children![
419 heading("PLAYBACK"),
420 row("Space", ControlRow::Pause),
421 static_row("< >", "Scrub objects"),
422 heading("TEST MATERIAL"),
423 row("1", ControlRow::Metallic),
424 row("3-7", ControlRow::Presets),
425 (
426 Node {
427 align_items: AlignItems::Center,
428 column_gap: px(KEY_GAP),
429 margin: UiRect::left(px(KEY_WIDTH + KEY_GAP)),
430 ..default()
431 },
432 children![
433 (
434 RoughnessValueText,
435 Text::default(),
436 TextFont::from_font_size(LABEL_SIZE),
437 TextColor(LABEL_COLOR),
438 ),
439 roughness_slider(),
440 ],
441 ),
442 heading("RIGHT MIRROR"),
443 row("8", ControlRow::MirrorPan),
444 row("9", ControlRow::MirrorSlide),
445 heading("RENDERER"),
446 row("P", ControlRow::Renderer),
447 row("2", ControlRow::Denoising),
448 ],
449 ));
450
451 commands.spawn((
452 Node {
453 position_type: PositionType::Absolute,
454 right: px(0.0),
455 padding: px(4.0).all(),
456 border_radius: BorderRadius::bottom_left(px(4.0)),
457 ..default()
458 },
459 BackgroundColor(Color::srgba(0.10, 0.10, 0.10, 0.8)),
460 children![(
461 PerformanceText,
462 Text::default(),
463 TextFont {
464 font_size: FontSize::Px(8.0),
465 ..default()
466 },
467 )],
468 ));
469}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, PartialEq, Eq, Clone, Copy)]
20enum DisplayQuality {
21 Low,
22 Medium,
23 High,
24}
25
26#[derive(Component)]
27struct Setting<T>(T);
28
29// One of the two settings that can be set through the menu. It will be a resource in the app
30#[derive(Resource, Debug, PartialEq, Eq, Clone, Copy)]
31struct Volume(u32);
32
33fn main() {
34 App::new()
35 .add_plugins(DefaultPlugins)
36 // Insert as resource the initial value for the settings resources
37 .insert_resource(DisplayQuality::Medium)
38 .insert_resource(Volume(7))
39 // Declare the game state, whose starting value is determined by the `Default` trait
40 .init_state::<GameState>()
41 .add_systems(Startup, setup)
42 // Adds the plugins for each state
43 .add_plugins((splash::splash_plugin, menu::menu_plugin, game::game_plugin))
44 .run();
45}
46
47fn setup(mut commands: Commands) {
48 commands.spawn(Camera2d);
49}
50
51mod splash {
52 use bevy::prelude::*;
53
54 use super::GameState;
55
56 // This plugin will display a splash screen with Bevy logo for 1 second before switching to the menu
57 pub fn splash_plugin(app: &mut App) {
58 // As this plugin is managing the splash screen, it will focus on the state `GameState::Splash`
59 app
60 // When entering the state, spawn everything needed for this screen
61 .add_systems(OnEnter(GameState::Splash), splash_setup)
62 // While in this state, run the `countdown` system
63 .add_systems(Update, countdown.run_if(in_state(GameState::Splash)));
64 }
65
66 // Tag component used to tag entities added on the splash screen
67 #[derive(Component)]
68 struct OnSplashScreen;
69
70 // Newtype to use a `Timer` for this screen as a resource
71 #[derive(Resource, Deref, DerefMut)]
72 struct SplashTimer(Timer);
73
74 fn splash_setup(mut commands: Commands, asset_server: Res<AssetServer>) {
75 let icon = asset_server.load("branding/icon.png");
76 // Display the logo
77 commands.spawn((
78 // This entity will be despawned when exiting the state
79 DespawnOnExit(GameState::Splash),
80 Node {
81 align_items: AlignItems::Center,
82 justify_content: JustifyContent::Center,
83 width: percent(100),
84 height: percent(100),
85 ..default()
86 },
87 OnSplashScreen,
88 children![(
89 ImageNode::new(icon),
90 Node {
91 // This will set the logo to be 200px wide, and auto adjust its height
92 width: px(200),
93 ..default()
94 },
95 )],
96 ));
97 // Insert the timer as a resource
98 commands.insert_resource(SplashTimer(Timer::from_seconds(1.0, TimerMode::Once)));
99 }
100
101 // Tick the timer, and change state when finished
102 fn countdown(
103 mut game_state: ResMut<NextState<GameState>>,
104 time: Res<Time>,
105 mut timer: ResMut<SplashTimer>,
106 ) {
107 if timer.tick(time.delta()).is_finished() {
108 game_state.set(GameState::Menu);
109 }
110 }
111}
112
113mod game {
114 use bevy::{
115 color::palettes::basic::{BLUE, LIME},
116 prelude::*,
117 };
118
119 use super::{DisplayQuality, GameState, Volume, TEXT_COLOR};
120
121 // This plugin will contain the game. In this case, it's just be a screen that will
122 // display the current settings for 5 seconds before returning to the menu
123 pub fn game_plugin(app: &mut App) {
124 app.add_systems(OnEnter(GameState::Game), game_setup)
125 .add_systems(Update, game.run_if(in_state(GameState::Game)));
126 }
127
128 // Tag component used to tag entities added on the game screen
129 #[derive(Component)]
130 struct OnGameScreen;
131
132 #[derive(Resource, Deref, DerefMut)]
133 struct GameTimer(Timer);
134
135 fn game_setup(
136 mut commands: Commands,
137 display_quality: Res<DisplayQuality>,
138 volume: Res<Volume>,
139 ) {
140 commands.spawn((
141 DespawnOnExit(GameState::Game),
142 Node {
143 width: percent(100),
144 height: percent(100),
145 // center children
146 align_items: AlignItems::Center,
147 justify_content: JustifyContent::Center,
148 ..default()
149 },
150 OnGameScreen,
151 children![(
152 Node {
153 // This will display its children in a column, from top to bottom
154 flex_direction: FlexDirection::Column,
155 // `align_items` will align children on the cross axis. Here the main axis is
156 // vertical (column), so the cross axis is horizontal. This will center the
157 // children
158 align_items: AlignItems::Center,
159 ..default()
160 },
161 BackgroundColor(Color::BLACK),
162 children![
163 (
164 Text::new("Will be back to the menu shortly..."),
165 TextFont {
166 font_size: FontSize::Px(67.0),
167 ..default()
168 },
169 TextColor(TEXT_COLOR),
170 Node {
171 margin: UiRect::all(px(50)),
172 ..default()
173 },
174 ),
175 (
176 Text::default(),
177 Node {
178 margin: UiRect::all(px(50)),
179 ..default()
180 },
181 children![
182 (
183 TextSpan(format!("quality: {:?}", *display_quality)),
184 TextFont {
185 font_size: FontSize::Px(50.0),
186 ..default()
187 },
188 TextColor(BLUE.into()),
189 ),
190 (
191 TextSpan::new(" - "),
192 TextFont {
193 font_size: FontSize::Px(50.0),
194 ..default()
195 },
196 TextColor(TEXT_COLOR),
197 ),
198 (
199 TextSpan(format!("volume: {:?}", *volume)),
200 TextFont {
201 font_size: FontSize::Px(50.0),
202 ..default()
203 },
204 TextColor(LIME.into()),
205 ),
206 ]
207 ),
208 ]
209 )],
210 ));
211 // Spawn a 5 seconds timer to trigger going back to the menu
212 commands.insert_resource(GameTimer(Timer::from_seconds(5.0, TimerMode::Once)));
213 }
214
215 // Tick the timer, and change state when finished
216 fn game(
217 time: Res<Time>,
218 mut game_state: ResMut<NextState<GameState>>,
219 mut timer: ResMut<GameTimer>,
220 ) {
221 if timer.tick(time.delta()).is_finished() {
222 game_state.set(GameState::Menu);
223 }
224 }
225}
226
227mod menu {
228 use bevy::{
229 app::AppExit,
230 color::palettes::css::CRIMSON,
231 ecs::component::Mutable,
232 ecs::spawn::{SpawnIter, SpawnWith},
233 picking::prelude::*,
234 prelude::*,
235 ui::Checked,
236 ui_widgets::{Activate, ActivateOnPress, Button, RadioButton, RadioGroup, ValueChange},
237 };
238
239 use super::{DisplayQuality, GameState, Setting, Volume, TEXT_COLOR};
240
241 // This plugin manages the menu, with 5 different screens:
242 // - a main menu with "New Game", "Settings", "Quit"
243 // - a settings menu with two submenus and a back button
244 // - two settings screen with a setting that can be set and a back button
245 pub fn menu_plugin(app: &mut App) {
246 app
247 // At start, the menu is not enabled. This will be changed in `menu_setup` when
248 // entering the `GameState::Menu` state.
249 // Current screen in the menu is handled by an independent state from `GameState`
250 .init_state::<MenuState>()
251 .add_systems(OnEnter(GameState::Menu), menu_setup)
252 // Systems to handle the main menu screen
253 .add_systems(OnEnter(MenuState::Main), main_menu_setup)
254 // Systems to handle the settings menu screen
255 .add_systems(OnEnter(MenuState::Settings), settings_menu_setup)
256 // Systems to handle the display settings screen
257 .add_systems(
258 OnEnter(MenuState::SettingsDisplay),
259 display_settings_menu_setup,
260 )
261 .add_observer(
262 on_value_change_setting_radio::<DisplayQuality>
263 .run_if(in_state(MenuState::SettingsDisplay)),
264 )
265 // Systems to handle the sound settings screen
266 .add_systems(OnEnter(MenuState::SettingsSound), sound_settings_menu_setup)
267 .add_observer(
268 on_value_change_setting_radio::<Volume>.run_if(in_state(MenuState::SettingsSound)),
269 )
270 // Observer that handles navigation within the app upon pressing certain buttons.
271 .add_observer(on_button_activate_update_states)
272 // Observers for button styling (regular buttons and radio buttons)
273 .add_observer(on_button_over_style)
274 .add_observer(on_button_out_style)
275 .add_observer(on_radio_button_press_style)
276 .add_observer(on_radio_button_release_style);
277 }
278
279 // State used for the current menu screen
280 #[derive(Clone, Copy, Default, Eq, PartialEq, Debug, Hash, States)]
281 enum MenuState {
282 Main,
283 Settings,
284 SettingsDisplay,
285 SettingsSound,
286 #[default]
287 Disabled,
288 }
289
290 // Tag component used to tag entities added on the main menu screen
291 #[derive(Component)]
292 struct OnMainMenuScreen;
293
294 // Tag component used to tag entities added on the settings menu screen
295 #[derive(Component)]
296 struct OnSettingsMenuScreen;
297
298 // Tag component used to tag entities added on the display settings menu screen
299 #[derive(Component)]
300 struct OnDisplaySettingsMenuScreen;
301
302 // Tag component used to tag entities added on the sound settings menu screen
303 #[derive(Component)]
304 struct OnSoundSettingsMenuScreen;
305
306 const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15);
307 const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25);
308 const HOVERED_PRESSED_BUTTON: Color = Color::srgb(0.25, 0.65, 0.25);
309 const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35);25const COLOR_TRACK: Color = Color::srgb(0.2, 0.2, 0.2);
26const COLOR_FILL: Color = Color::srgb(0.35, 0.65, 0.35);
27const COLOR_FILL_DRAGGING: Color = Color::srgb(0.45, 0.85, 0.45);
28const COLOR_THUMB_IDLE: Color = Color::srgb(0.85, 0.55, 0.1);
29const COLOR_THUMB_HOVER: Color = Color::srgb(1.0, 0.75, 0.2);
30const COLOR_DECOY_IDLE: Color = Color::srgb(0.2, 0.45, 0.8);
31const COLOR_DECOY_HOVER: Color = Color::srgb(0.9, 0.2, 0.2);
32const COLOR_TOGGLE_ON: Color = Color::srgb(0.15, 0.65, 0.3);
33const COLOR_TOGGLE_OFF: Color = Color::srgb(0.55, 0.15, 0.15);
34const COLOR_RESET_IDLE: Color = Color::srgb(0.3, 0.3, 0.55);
35const COLOR_RESET_HOVER: Color = Color::srgb(0.5, 0.5, 0.75);
36
37/// The normalized (0 – 1) position of the slider thumb.
38#[derive(Resource)]
39struct SliderValue(f32);
40
41impl Default for SliderValue {
42 fn default() -> Self {
43 Self(SLIDER_DEFAULT_VALUE)
44 }
45}
46
47/// Whether [`PointerCaptureMap`] is used while dragging the thumb.
48#[derive(Resource)]
49struct CaptureEnabled(bool);
50
51impl Default for CaptureEnabled {
52 fn default() -> Self {
53 Self(true)
54 }
55}
56
57#[derive(Component)]
58struct SliderThumb;
59
60#[derive(Component)]
61struct SliderFill;
62
63#[derive(Component)]
64struct SliderLabel;
65
66#[derive(Component)]
67struct ToggleLabel;
68
69#[derive(Component)]
70struct ToggleButton;
71
72#[derive(Component)]
73struct ResetButton;
74
75#[derive(Component)]
76struct DecoyButton;
77
78/// X offset of the left edge of the thumb node.
79fn thumb_left(v: f32) -> f32 {
80 v.clamp(0.0, 1.0) * (TRACK_WIDTH - THUMB_SIZE)
81}
82
83/// Width of the fill bar (reaches to the center of the thumb).
84fn fill_width(v: f32) -> f32 {
85 v.clamp(0.0, 1.0) * (TRACK_WIDTH - THUMB_SIZE) + THUMB_HALF
86}
87
88fn main() {
89 App::new()
90 .add_plugins(DefaultPlugins)
91 .init_resource::<SliderValue>()
92 .init_resource::<CaptureEnabled>()
93 .add_systems(Startup, setup)
94 .add_systems(Update, (sync_thumb_and_label, sync_fill))
95 .run();
96}
97
98fn setup(mut commands: Commands) {
99 commands.spawn(Camera2d);
100
101 // Root column – centered, full-screen, non-pickable container.
102 commands
103 .spawn((
104 Node {
105 width: Val::Percent(100.0),
106 height: Val::Percent(100.0),
107 flex_direction: FlexDirection::Column,
108 align_items: AlignItems::Center,
109 justify_content: JustifyContent::Center,
110 row_gap: Val::Px(28.0),
111 ..default()
112 },
113 Pickable::IGNORE,
114 ))
115 .with_children(|root| {
116 root.spawn((
117 Text::new(
118 "Drag the slider over the blue buttons.\n\
119 With capture ON they stay blue. With capture OFF they incorrectly turn red.",
120 ),
121 TextFont::from_font_size(15.0),
122 TextColor(Color::srgb(0.75, 0.75, 0.75)),
123 ));
124
125 root.spawn((
126 Node {
127 flex_direction: FlexDirection::Row,
128 align_items: AlignItems::Center,
129 column_gap: Val::Px(10.0),
130 ..default()
131 },
132 Pickable::IGNORE,
133 ))
134 .with_children(|row| {
135 row.spawn((
136 Text::new("0.0"),
137 TextFont::from_font_size(13.0),
138 TextColor(Color::srgb(0.55, 0.55, 0.55)),
139 ));
140
141 row.spawn((
142 Node {
143 width: Val::Px(TRACK_WIDTH),
144 height: Val::Px(TRACK_HEIGHT),
145 position_type: PositionType::Relative,
146 align_items: AlignItems::Center,
147 ..default()
148 },
149 BackgroundColor(COLOR_TRACK),
150 Pickable::IGNORE,
151 ))
152 .with_children(|track| {
153 track.spawn((
154 SliderFill,
155 Node {
156 width: Val::Px(fill_width(SLIDER_DEFAULT_VALUE)),
157 height: Val::Px(FILL_HEIGHT),
158 position_type: PositionType::Absolute,
159 left: Val::Px(0.0),
160 ..default()
161 },
162 BackgroundColor(COLOR_FILL),
163 Pickable::IGNORE,
164 ));
165
166 track
167 .spawn((
168 SliderThumb,
169 Node {
170 width: Val::Px(THUMB_SIZE),
171 height: Val::Px(THUMB_SIZE),
172 position_type: PositionType::Absolute,
173 left: Val::Px(thumb_left(SLIDER_DEFAULT_VALUE)),
174 border_radius: BorderRadius::all(Val::Px(4.0)),
175 ..default()
176 },
177 BackgroundColor(COLOR_THUMB_IDLE),
178 ))
179 .observe(on_drag_start)
180 .observe(on_drag)
181 .observe(on_drag_end)
182 .observe(
183 |_: On<PointerOver>,
184 mut q: Single<&mut BackgroundColor, With<SliderThumb>>| {
185 q.0 = COLOR_THUMB_HOVER;
186 },
187 )
188 .observe(
189 |_: On<PointerOut>,
190 mut q: Single<&mut BackgroundColor, With<SliderThumb>>| {
191 q.0 = COLOR_THUMB_IDLE;
192 },
193 );
194 });
195
196 row.spawn((
197 Text::new("1.0"),
198 TextFont::from_font_size(13.0),
199 TextColor(Color::srgb(0.55, 0.55, 0.55)),
200 ));
201 });
202
203 root.spawn((
204 SliderLabel,
205 Text::new(format!("Value: {:.2}", SLIDER_DEFAULT_VALUE)),
206 TextFont::from_font_size(18.0),
207 ));
208
209 root.spawn((
210 Node {
211 flex_direction: FlexDirection::Row,
212 column_gap: Val::Px(16.0),
213 ..default()
214 },
215 Pickable::IGNORE,
216 ))
217 .with_children(|row| {
218 for label in ["Button A", "Button B", "Button C", "Button D", "Button E"] {
219 spawn_decoy_button(row, label);
220 }
221 });
222
223 root.spawn((
224 Node {
225 flex_direction: FlexDirection::Row,
226 column_gap: Val::Px(20.0),
227 align_items: AlignItems::Center,
228 ..default()
229 },
230 Pickable::IGNORE,
231 ))
232 .with_children(|row| {
233 row.spawn((
234 ToggleButton,
235 Node {
236 padding: UiRect::axes(Val::Px(20.0), Val::Px(10.0)),
237 border_radius: BorderRadius::all(Val::Px(6.0)),
238 ..default()
239 },
240 BackgroundColor(COLOR_TOGGLE_ON),
241 ))
242 .with_children(|btn| {
243 btn.spawn((
244 ToggleLabel,
245 Text::new("Capture: ON (click to toggle)"),
246 TextFont::from_font_size(16.0),
247 TextColor(Color::WHITE),
248 Pickable::IGNORE,
249 ));
250 })
251 .observe(on_toggle_click);
252
253 row.spawn((
254 ResetButton,
255 Node {
256 padding: UiRect::axes(Val::Px(20.0), Val::Px(10.0)),
257 border_radius: BorderRadius::all(Val::Px(6.0)),
258 ..default()
259 },
260 BackgroundColor(COLOR_RESET_IDLE),
261 ))
262 .with_children(|btn| {
263 btn.spawn((
264 Text::new("Reset"),
265 TextFont::from_font_size(16.0),
266 TextColor(Color::WHITE),
267 Pickable::IGNORE,
268 ));
269 })
270 .observe(
271 |_: On<PointerOver>, mut q: Single<&mut BackgroundColor, With<ResetButton>>| {
272 q.0 = COLOR_RESET_HOVER;
273 },
274 )
275 .observe(
276 |_: On<PointerOut>, mut q: Single<&mut BackgroundColor, With<ResetButton>>| {
277 q.0 = COLOR_RESET_IDLE;
278 },
279 )
280 .observe(on_reset_click);
281 });
282 });
283}13const SLIDER_TRACK: Color = Color::srgb(0.05, 0.05, 0.05);
14const SLIDER_THUMB: Color = Color::srgb(0.35, 0.75, 0.35);
15
16fn main() {
17 App::new()
18 .add_plugins((DefaultPlugins, TabNavigationPlugin))
19 .add_systems(Startup, setup)
20 .add_systems(Update, (update_slider_visuals, update_value_labels))
21 .run();
22}
23
24#[derive(Component)]
25struct ValueLabel(Entity);
26
27#[derive(Component)]
28struct DemoSlider;
29
30#[derive(Component)]
31struct DemoSliderThumb;
32
33#[derive(Component)]
34struct VerticalSlider;
35
36fn setup(mut commands: Commands, assets: Res<AssetServer>) {
37 commands.spawn(Camera2d);
38
39 commands
40 .spawn((
41 Node {
42 width: percent(100),
43 height: percent(100),
44 align_items: AlignItems::Center,
45 justify_content: JustifyContent::Center,
46 display: Display::Flex,
47 flex_direction: FlexDirection::Row,
48 column_gap: px(50),
49 ..default()
50 },
51 TabGroup::default(),
52 ))
53 .with_children(|parent| {
54 // Vertical slider
55 parent
56 .spawn(Node {
57 display: Display::Flex,
58 flex_direction: FlexDirection::Column,
59 align_items: AlignItems::Center,
60 row_gap: px(10),
61 ..default()
62 })
63 .with_children(|parent| {
64 parent.spawn((
65 Text::new("Vertical"),
66 TextFont {
67 font: assets.load("fonts/FiraSans-Bold.ttf").into(),
68 font_size: FontSize::Px(20.0),
69 ..default()
70 },
71 TextColor(Color::srgb(0.9, 0.9, 0.9)),
72 ));
73
74 let label_id = parent
75 .spawn((
76 Text::new("50"),
77 TextFont {
78 font: assets.load("fonts/FiraSans-Bold.ttf").into(),
79 font_size: FontSize::Px(24.0),
80 ..default()
81 },
82 TextColor(Color::srgb(0.9, 0.9, 0.9)),
83 ))
84 .id();
85
86 parent.spawn((
87 vertical_slider(),
88 ValueLabel(label_id),
89 observe(slider_self_update),
90 ));
91 });
92
93 // Horizontal slider
94 parent
95 .spawn(Node {
96 display: Display::Flex,
97 flex_direction: FlexDirection::Column,
98 align_items: AlignItems::Center,
99 row_gap: px(10),
100 ..default()
101 })
102 .with_children(|parent| {
103 parent.spawn((
104 Text::new("Horizontal"),
105 TextFont {
106 font: assets.load("fonts/FiraSans-Bold.ttf").into(),
107 font_size: FontSize::Px(20.0),
108 ..default()
109 },
110 TextColor(Color::srgb(0.9, 0.9, 0.9)),
111 ));
112
113 let label_id = parent
114 .spawn((
115 Text::new("50"),
116 TextFont {
117 font: assets.load("fonts/FiraSans-Bold.ttf").into(),
118 font_size: FontSize::Px(24.0),
119 ..default()
120 },
121 TextColor(Color::srgb(0.9, 0.9, 0.9)),
122 ))
123 .id();
124
125 parent.spawn((
126 horizontal_slider(),
127 ValueLabel(label_id),
128 observe(slider_self_update),
129 ));
130 });
131 });
132}- examples/showcase/breakout.rs
- examples/state/custom_transitions.rs
- examples/state/states.rs
- examples/ui/widgets/button.rs
- examples/ui/widgets/standard_widgets.rs
- examples/ui/widgets/standard_widgets_observers.rs
- examples/showcase/desk_toy.rs
- examples/ui/layout/flex_layout.rs
- examples/ui/layout/size_constraints.rs
- examples/3d/solari_reflections.rs
- examples/state/computed_states.rs
- examples/state/sub_states.rs
- examples/2d/tilemap_chunk_orientation.rs
- examples/window/clear_color.rs
- examples/ecs/removal_detection.rs
- examples/3d/fog.rs
- examples/math/cubic_splines.rs
- examples/async_tasks/async_compute.rs
- examples/ui/text/text.rs
- examples/async_tasks/async_channel_pattern.rs
- examples/ecs/state_scoped.rs
- examples/camera/2d_top_down_camera.rs
- examples/3d/3d_viewport_to_world.rs
- examples/ui/widgets/headless_tabs.rs
- examples/ui/scroll_and_overflow/scrollbars.rs
- examples/asset/multi_asset_sync.rs
- examples/ui/layout/anchor_layout.rs
- examples/shader_advanced/fullscreen_material.rs
- tests/window/minimizing.rs
- tests/window/resizing.rs
- examples/3d/atmospheric_fog.rs
- examples/testbed/2d.rs
- examples/animation/animated_mesh.rs
- examples/window/scale_factor_override.rs
- examples/3d/parenting.rs
- examples/animation/animation_graph.rs
- examples/ui/scroll_and_overflow/overflow_debug.rs
- examples/app/settings.rs
- examples/shader/shader_material_screenspace_texture.rs
- examples/3d/mesh_ray_cast.rs
- examples/camera/2d_screen_shake.rs
- examples/camera/camera_orbit.rs
- examples/animation/animation_masks.rs
- examples/window/screenshot.rs
- examples/shader_advanced/custom_post_processing.rs
- tests/window/desktop_request_redraw.rs
- examples/3d/two_passes.rs
- examples/gltf/gltf_extension_animation_graph.rs
- examples/shader_advanced/deferred_raymarch.rs
- examples/window/low_power.rs
- examples/movement/smooth_follow.rs
- examples/ui/relative_cursor_position.rs
- examples/3d/vertex_colors.rs
- examples/animation/animated_mesh_control.rs
- examples/3d/orthographic.rs
- examples/3d/spherical_area_lights.rs
- examples/stress_tests/many_meshlet_materials.rs
- examples/2d/bloom_2d.rs
- examples/gizmos/axes.rs
- examples/stress_tests/many_buttons.rs
- examples/3d/order_independent_transparency.rs
- examples/3d/ssao.rs
- examples/animation/animated_mesh_events.rs
- examples/3d/light_textures.rs
- examples/ecs/error_handling.rs
- examples/camera/projection_zoom.rs
- examples/3d/rect_light.rs
- examples/ui/images/ui_texture_slice.rs
- examples/3d/visibility_range.rs
- tests/3d/test_invalid_skinned_mesh.rs
- examples/time/virtual_time.rs
- examples/testbed/ui.rs
- examples/3d/anti_aliasing.rs
- examples/picking/dragdrop_picking.rs
- examples/transforms/align.rs
- examples/math/random_sampling.rs
- examples/testbed/3d.rs
- examples/gizmos/3d_gizmos.rs
- examples/picking/sprite_picking.rs
- examples/ui/images/ui_texture_atlas_slice.rs
- examples/ecs/iter_combinations.rs
- examples/ui/text/text_wrap_debug.rs
- examples/3d/render_to_texture.rs
- examples/showcase/alien_cake_addict.rs
- examples/ui/styling/transparency_ui.rs
- examples/3d/transparency_3d.rs
- examples/asset/alter_mesh.rs
- examples/ui/text/system_fonts.rs
- examples/3d/auto_exposure.rs
- examples/asset/asset_loading.rs
- examples/ui/scroll_and_overflow/overflow.rs
- examples/ui/scroll_and_overflow/overflow_clip_margin.rs
- examples/shader/shader_prepass.rs
- examples/3d/split_screen.rs
- examples/gizmos/transform_gizmo.rs
- examples/ui/widgets/tab_navigation.rs
- examples/ui/scroll_and_overflow/scroll.rs
- examples/3d/decal.rs
- examples/ui/scroll_and_overflow/overflow_transform.rs
- examples/stress_tests/many_foxes.rs
- examples/ui/ui_drag_and_drop.rs
- examples/3d/deferred_rendering.rs
- examples/3d/contact_shadows.rs
- examples/2d/text2d.rs
- examples/animation/custom_skinned_mesh.rs
- examples/usage/debug_frustum_culling.rs
- examples/3d/blend_modes.rs
- examples/animation/animated_transform.rs
- examples/3d/solari.rs
- examples/3d/camera_sub_view.rs
- examples/ui/text/text_debug.rs
- examples/ui/layout/grid.rs
- examples/3d/transmission.rs
- examples/ui/styling/borders.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?
412fn setup(
413 mut commands: Commands,
414 mut meshes: ResMut<Assets<Mesh>>,
415 mut materials: ResMut<Assets<StandardMaterial>>,
416 mut images: ResMut<Assets<Image>>,
417 asset_server: Res<AssetServer>,
418) {
419 // Plane
420 commands.spawn((
421 Mesh3d(meshes.add(Plane3d::default().mesh().size(20.0, 20.0))),
422 MeshMaterial3d(materials.add(Color::srgb(0.1, 0.2, 0.1))),
423 ));
424
425 let cube_material = materials.add(StandardMaterial {
426 base_color_texture: Some(images.add(uv_debug_texture())),
427 ..default()
428 });
429
430 // Cubes
431 for i in 0..5 {
432 commands.spawn((
433 Mesh3d(meshes.add(Cuboid::new(0.25, 0.25, 0.25))),
434 MeshMaterial3d(cube_material.clone()),
435 Transform::from_xyz(i as f32 * 0.25 - 1.0, 0.125, -i as f32 * 0.5),
436 ));
437 }
438
439 // Flight Helmet
440 commands.spawn(WorldAssetRoot(asset_server.load(
441 GltfAssetLabel::Scene(0).from_asset("models/FlightHelmet/FlightHelmet.gltf"),
442 )));
443
444 // Light
445 commands.spawn((
446 DirectionalLight {
447 illuminance: light_consts::lux::FULL_DAYLIGHT,
448 shadow_maps_enabled: true,
449 ..default()
450 },
451 Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, PI * -0.15, PI * -0.15)),
452 CascadeShadowConfigBuilder {
453 maximum_distance: 3.0,
454 first_cascade_far_bound: 0.9,
455 ..default()
456 }
457 .build(),
458 ));
459
460 // Camera
461 commands.spawn((
462 Camera3d::default(),
463 Hdr,
464 Transform::from_xyz(0.7, 0.7, 1.0).looking_at(Vec3::new(0.0, 0.3, 0.0), Vec3::Y),
465 ContrastAdaptiveSharpening {
466 enabled: false,
467 ..default()
468 },
469 EnvironmentMapLight {
470 diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"),
471 specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
472 intensity: 150.0,
473 ..default()
474 },
475 DistanceFog {
476 color: Color::srgba_u8(43, 44, 47, 255),
477 falloff: FogFalloff::Linear {
478 start: 1.0,
479 end: 4.0,
480 },
481 ..default()
482 },
483 ));
484
485 // example instructions
486 commands.spawn((
487 Text::default(),
488 Node {
489 position_type: PositionType::Absolute,
490 top: px(12),
491 left: px(12),
492 ..default()
493 },
494 ));
495}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: On<PointerClick>,
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
60fn on_click_spawn_cube(
61 _click: On<PointerClick>,
62 mut commands: Commands,
63 mut meshes: ResMut<Assets<Mesh>>,
64 mut materials: ResMut<Assets<StandardMaterial>>,
65 mut num: Local<usize>,
66) {
67 commands
68 .spawn((
69 Mesh3d(meshes.add(Cuboid::new(0.5, 0.5, 0.5))),
70 MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))),
71 Transform::from_xyz(0.0, 0.25 + 0.55 * *num as f32, 0.0),
72 ))
73 // With the MeshPickingPlugin added, you can add pointer event observers to meshes:
74 .observe(on_drag_rotate);
75 *num += 1;
76}13fn scene() -> impl SceneList {
14 bsn_list! {
15 #CircularBase
16 Mesh3d(asset_value(Circle::new(4.0)))
17 MeshMaterial3d::<StandardMaterial>(asset_value(Color::WHITE))
18 Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2))
19 --
20 #Cube
21 Mesh3d(asset_value(Cuboid::new(1.0, 1.0, 1.0)))
22 MeshMaterial3d::<StandardMaterial>(asset_value(Color::srgb_u8(124, 144, 255)))
23 Transform::from_xyz(0.0, 0.5, 0.0)
24 --
25 PointLight {
26 shadow_maps_enabled: true,
27 }
28 Transform::from_xyz(4.0, 8.0, 4.0)
29 --
30 Camera3d
31 Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y)
32 }
33}121fn spawn_test_scene(
122 mut commands: Commands,
123 mut meshes: ResMut<Assets<Mesh>>,
124 mut materials: ResMut<Assets<StandardMaterial>>,
125) {
126 commands.spawn((
127 Mesh3d(meshes.add(Circle::new(4.0))),
128 MeshMaterial3d(materials.add(Color::WHITE)),
129 Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
130 ));
131 commands.spawn((
132 Mesh3d(meshes.add(Cuboid::new(2.0, 2.0, 2.0))),
133 MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))),
134 Transform::from_xyz(0.0, 1.0, 0.0),
135 ));
136 commands.spawn((
137 PointLight {
138 shadow_maps_enabled: true,
139 ..default()
140 },
141 Transform::from_xyz(4.0, 8.0, 4.0),
142 ));
143}241fn add_camera(commands: &mut Commands, asset_server: &AssetServer, color_grading: ColorGrading) {
242 commands.spawn((
243 Camera3d::default(),
244 Hdr,
245 Transform::from_xyz(0.7, 0.7, 1.0).looking_at(Vec3::new(0.0, 0.3, 0.0), Vec3::Y),
246 color_grading,
247 DistanceFog {
248 color: Color::srgb_u8(43, 44, 47),
249 falloff: FogFalloff::Linear {
250 start: 1.0,
251 end: 8.0,
252 },
253 ..default()
254 },
255 EnvironmentMapLight {
256 diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"),
257 specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
258 intensity: 2000.0,
259 ..default()
260 },
261 ));
262}82fn setup(
83 mut commands: Commands,
84 mut meshes: ResMut<Assets<Mesh>>,
85 mut materials: ResMut<Assets<StandardMaterial>>,
86) {
87 commands.spawn((
88 Mesh3d(meshes.add(Cuboid::new(0.5, 0.5, 0.5))),
89 MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))),
90 Transform::from_xyz(0.0, 0.5, 0.0),
91 ));
92 // light
93 commands.spawn((
94 PointLight {
95 shadow_maps_enabled: true,
96 ..default()
97 },
98 Transform::from_xyz(4.0, 8.0, 4.0),
99 ));
100 // camera
101 commands.spawn((
102 Camera3d::default(),
103 Transform::from_xyz(-9.0, 1.0, -9.0).looking_at(Vec3::new(9., 4., 9.), Vec3::Y),
104 // disable msaa for simplicity
105 Msaa::Off,
106 #[cfg(feature = "free_camera")]
107 FreeCamera::default(),
108 ));
109}- examples/3d/motion_blur.rs
- examples/3d/tonemapping.rs
- examples/3d/post_processing.rs
- examples/remote/server.rs
- examples/camera/custom_projection.rs
- examples/diagnostics/log_diagnostics.rs
- examples/stress_tests/many_cubes.rs
- examples/3d/skybox.rs
- examples/stress_tests/bevymark.rs
- examples/app/headless_renderer.rs
- examples/app/render_recovery.rs
- examples/shader_advanced/custom_render_phase.rs
- examples/3d/spotlight.rs
- examples/gizmos/light_gizmos.rs
- examples/3d/parallax_mapping.rs
- examples/3d/deferred_rendering.rs
Sourcepub const fn srgba_u32(color: u32) -> Color
pub const fn srgba_u32(color: u32) -> Color
Creates a new Color object storing a Srgba color from a u32 value with the alpha value extracted from the input.
For example, a value of 0x000000ff results in black with full opacity, and a value of 0xff000080 results in red with half opacity.
§Examples
let black = Color::srgba_u32(0x000000ff);
let semi_transparent_red = Color::srgba_u32(0xff000080);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]
Examples found in repository?
17fn setup(mut commands: Commands, assets: Res<AssetServer>) {
18 let chunk_size = UVec2::splat(8);
19 let tile_display_size = UVec2::splat(64);
20
21 // We'll use each possible orientation, one per column
22 let orientation = [
23 TileOrientation::Default,
24 TileOrientation::Rotate90,
25 TileOrientation::Rotate180,
26 TileOrientation::Rotate270,
27 TileOrientation::MirrorH,
28 TileOrientation::MirrorHRotate90,
29 TileOrientation::MirrorHRotate180,
30 TileOrientation::MirrorHRotate270,
31 ];
32
33 // Show different color/alpha on each row
34 let colors = [
35 Color::WHITE,
36 Color::linear_rgb(1.0, 0.0, 0.0),
37 Color::linear_rgb(0.0, 1.0, 0.0),
38 Color::linear_rgb(0.0, 0.0, 1.0),
39 Color::linear_rgba(1.0, 0.0, 0.0, 0.25),
40 Color::linear_rgba(0.0, 1.0, 0.0, 0.25),
41 Color::linear_rgba(0.0, 0.0, 1.0, 0.25),
42 Color::linear_rgba(1.0, 1.0, 1.0, 0.5),
43 ];
44
45 let tile_data = (0..chunk_size.element_product())
46 .map(|i| {
47 let row = i / 8;
48 let col = i % 8;
49 Some(TileData {
50 // Alternate tiles per row
51 tileset_index: (row % 2) as u16,
52 color: colors[row as usize],
53 // Last (top) row is invisible
54 visible: row != 7,
55 orientation: orientation[col as usize],
56 })
57 })
58 .collect();
59
60 commands.spawn((
61 TilemapChunk {
62 chunk_size,
63 tile_display_size,
64 tileset: assets
65 .load_builder()
66 .with_settings(|settings: &mut ImageLoaderSettings| {
67 // The tileset texture is expected to be an array of tile textures, so we tell the
68 // `ImageLoader` that our texture is composed of 2 stacked tile images.
69 settings.array_layout = Some(ImageArrayLayout::RowCount { rows: 2 });
70 })
71 .load("textures/arrow.png"),
72 alpha_mode: AlphaMode2d::Blend,
73 },
74 TilemapChunkTileData(tile_data),
75 ));
76
77 commands.spawn(Camera2d);
78}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
299fn mouse_handler(
300 mut commands: Commands,
301 args: Res<Args>,
302 time: Res<Time>,
303 mouse_button_input: Res<ButtonInput<MouseButton>>,
304 cube_resources: ResMut<CubeResources>,
305 mut counter: ResMut<BevyCounter>,
306 mut rng: Local<Option<ChaCha8Rng>>,
307 mut wave: Local<usize>,
308) {
309 if rng.is_none() {
310 *rng = Some(ChaCha8Rng::seed_from_u64(42));
311 }
312 let rng = rng.as_mut().unwrap();
313
314 if mouse_button_input.just_released(MouseButton::Left) {
315 counter.color = Color::linear_rgb(rng.random(), rng.random(), rng.random());
316 }
317
318 if mouse_button_input.pressed(MouseButton::Left) {
319 let spawn_count = (CUBES_PER_SECOND as f64 * time.delta_secs_f64()) as usize;
320 spawn_cubes(
321 &mut commands,
322 args.into_inner(),
323 &mut counter,
324 spawn_count,
325 cube_resources.into_inner(),
326 None,
327 *wave,
328 );
329 *wave += 1;
330 }
331}
332
333fn cube_velocity_transform(
334 mut translation: Vec3,
335 velocity_rng: &mut ChaCha8Rng,
336 waves: Option<usize>,
337 dt: f32,
338) -> (Transform, Vec3) {
339 let mut velocity = Vec3::new(0., 0., MAX_VELOCITY * velocity_rng.random::<f32>());
340
341 if let Some(waves) = waves {
342 for _ in 0..(waves * (FIXED_TIMESTEP / dt).round() as usize) {
343 step_movement(&mut translation, &mut velocity, dt);
344 handle_collision(&translation, &mut velocity);
345 }
346 }
347 (Transform::from_translation(translation), velocity)
348}
349
350const FIXED_DELTA_TIME: f32 = 1.0 / 60.0;
351
352fn spawn_cubes(
353 commands: &mut Commands,
354 args: &Args,
355 counter: &mut BevyCounter,
356 spawn_count: usize,
357 cube_resources: &mut CubeResources,
358 waves_to_simulate: Option<usize>,
359 wave: usize,
360) {
361 let batch_material = cube_resources.materials[wave % cube_resources.materials.len()].clone();
362
363 let spawn_y = VOLUME_SIZE.y / 2.0 - HALF_CUBE_SIZE;
364 let spawn_z = -VOLUME_SIZE.z / 2.0 + HALF_CUBE_SIZE;
365
366 let batch = (0..spawn_count)
367 .map(|_| {
368 let spawn_pos = Vec3::new(
369 (cube_resources.transform_rng.random::<f32>() - 0.5) * VOLUME_SIZE.x,
370 spawn_y,
371 spawn_z,
372 );
373
374 let (transform, velocity) = cube_velocity_transform(
375 spawn_pos,
376 &mut cube_resources.velocity_rng,
377 waves_to_simulate,
378 FIXED_DELTA_TIME,
379 );
380
381 let material = if args.vary_per_instance {
382 cube_resources
383 .materials
384 .choose(&mut cube_resources.material_rng)
385 .unwrap()
386 .clone()
387 } else {
388 batch_material.clone()
389 };
390
391 (
392 Mesh3d(cube_resources.cube_mesh.clone()),
393 MeshMaterial3d(material),
394 transform,
395 Cube { velocity },
396 )
397 })
398 .collect::<Vec<_>>();
399 commands.spawn_batch(batch);
400
401 counter.count += spawn_count;
402 counter.color = Color::linear_rgb(
403 cube_resources.color_rng.random(),
404 cube_resources.color_rng.random(),
405 cube_resources.color_rng.random(),
406 );
407}
408
409fn step_movement(translation: &mut Vec3, velocity: &mut Vec3, dt: f32) {
410 translation.x += velocity.x * dt;
411 translation.y += velocity.y * dt;
412 translation.z += velocity.z * dt;
413 velocity.y += GRAVITY * dt;
414}
415
416fn movement_system(
417 args: Res<Args>,
418 time: Res<Time>,
419 mut cube_query: Query<(&mut Cube, &mut Transform)>,
420) {
421 let dt = if args.benchmark {
422 FIXED_DELTA_TIME
423 } else {
424 time.delta_secs()
425 };
426 for (mut cube, mut transform) in &mut cube_query {
427 step_movement(&mut transform.translation, &mut cube.velocity, dt);
428 }
429}
430
431fn handle_collision(translation: &Vec3, velocity: &mut Vec3) {
432 if (velocity.x > 0. && translation.x + HALF_CUBE_SIZE > VOLUME_SIZE.x / 2.0)
433 || (velocity.x <= 0. && translation.x - HALF_CUBE_SIZE < -VOLUME_SIZE.x / 2.0)
434 {
435 velocity.x = -velocity.x;
436 }
437 if (velocity.z > 0. && translation.z + HALF_CUBE_SIZE > VOLUME_SIZE.z / 2.0)
438 || (velocity.z <= 0. && translation.z - HALF_CUBE_SIZE < -VOLUME_SIZE.z / 2.0)
439 {
440 velocity.z = -velocity.z;
441 }
442
443 let velocity_y = velocity.y;
444 if velocity_y < 0. && translation.y - HALF_CUBE_SIZE < -VOLUME_SIZE.y / 2.0 {
445 velocity.y = -velocity_y;
446 }
447 if translation.y + HALF_CUBE_SIZE > VOLUME_SIZE.y / 2.0 && velocity_y > 0.0 {
448 velocity.y = 0.0;
449 }
450}
451
452fn collision_system(mut cube_query: Query<(&mut Cube, &Transform)>) {
453 cube_query.par_iter_mut().for_each(|(mut cube, transform)| {
454 handle_collision(&transform.translation, &mut cube.velocity);
455 });
456}
457
458fn counter_system(
459 diagnostics: Res<DiagnosticsStore>,
460 counter: Res<BevyCounter>,
461 query: Single<Entity, With<StatsText>>,
462 mut writer: TextUiWriter,
463) {
464 let text = *query;
465
466 if counter.is_changed() {
467 *writer.text(text, 2) = counter.count.to_string();
468 }
469
470 if let Some(fps) = diagnostics.get(&FrameTimeDiagnosticsPlugin::FPS) {
471 if let Some(raw) = fps.value() {
472 *writer.text(text, 4) = format!("{raw:.2}");
473 }
474 if let Some(sma) = fps.average() {
475 *writer.text(text, 6) = format!("{sma:.2}");
476 }
477 if let Some(ema) = fps.smoothed() {
478 *writer.text(text, 8) = format!("{ema:.2}");
479 }
480 };
481}
482
483fn init_textures(textures: &mut Vec<Handle<Image>>, args: &Args, images: &mut Assets<Image>) {
484 let mut color_rng = ChaCha8Rng::seed_from_u64(42);
485 while textures.len() < args.material_texture_count {
486 let pixel = [
487 color_rng.random(),
488 color_rng.random(),
489 color_rng.random(),
490 255,
491 ];
492 textures.push(images.add(Image::new_fill(
493 Extent3d {
494 width: CUBE_TEXTURE_SIZE as u32,
495 height: CUBE_TEXTURE_SIZE as u32,
496 depth_or_array_layers: 1,
497 },
498 TextureDimension::D2,
499 &pixel,
500 TextureFormat::Rgba8UnormSrgb,
501 RenderAssetUsages::RENDER_WORLD,
502 )));
503 }
504}
505
506fn init_materials(
507 args: &Args,
508 textures: &[Handle<Image>],
509 assets: &mut Assets<StandardMaterial>,
510) -> Vec<Handle<StandardMaterial>> {
511 let mut capacity = if args.vary_per_instance {
512 args.per_wave * args.waves
513 } else {
514 args.material_texture_count.max(args.waves)
515 };
516 if !args.benchmark {
517 capacity = capacity.max(256);
518 }
519 capacity = capacity.max(1);
520
521 let alpha_mode = match args.alpha_mode {
522 AlphaMode::Opaque => bevy::prelude::AlphaMode::Opaque,
523 AlphaMode::Blend => bevy::prelude::AlphaMode::Blend,
524 AlphaMode::AlphaMask => bevy::prelude::AlphaMode::Mask(0.5),
525 };
526
527 let mut materials = Vec::with_capacity(capacity);
528 materials.push(assets.add(StandardMaterial {
529 base_color: Color::WHITE,
530 base_color_texture: textures.first().cloned(),
531 alpha_mode,
532 ..default()
533 }));
534
535 let mut color_rng = ChaCha8Rng::seed_from_u64(42);
536 let mut texture_rng = ChaCha8Rng::seed_from_u64(42);
537 materials.extend(
538 std::iter::repeat_with(|| {
539 assets.add(StandardMaterial {
540 base_color: Color::linear_rgb(
541 color_rng.random(),
542 color_rng.random(),
543 color_rng.random(),
544 ),
545 base_color_texture: textures.choose(&mut texture_rng).cloned(),
546 alpha_mode,
547 ..default()
548 })
549 })
550 .take(capacity - materials.len()),
551 );
552
553 materials
554}321fn mouse_handler(
322 mut commands: Commands,
323 args: Res<Args>,
324 time: Res<Time>,
325 mouse_button_input: Res<ButtonInput<MouseButton>>,
326 window: Query<&Window>,
327 bird_resources: ResMut<BirdResources>,
328 mut counter: ResMut<BevyCounter>,
329 mut rng: Local<Option<ChaCha8Rng>>,
330 mut wave: Local<usize>,
331) {
332 let Ok(window) = window.single() else {
333 return;
334 };
335
336 if rng.is_none() {
337 // We're seeding the PRNG here to make this example deterministic for testing purposes.
338 // This isn't strictly required in practical use unless you need your app to be deterministic.
339 *rng = Some(ChaCha8Rng::seed_from_u64(500));
340 }
341 let rng = rng.as_mut().unwrap();
342
343 if mouse_button_input.just_released(MouseButton::Left) {
344 counter.color = Color::linear_rgb(rng.random(), rng.random(), rng.random());
345 }
346
347 if mouse_button_input.pressed(MouseButton::Left) {
348 let spawn_count = (BIRDS_PER_SECOND as f64 * time.delta_secs_f64()) as usize;
349 spawn_birds(
350 &mut commands,
351 args.into_inner(),
352 &window.resolution,
353 &mut counter,
354 spawn_count,
355 bird_resources.into_inner(),
356 None,
357 *wave,
358 );
359 *wave += 1;
360 }
361}
362
363fn bird_velocity_transform(
364 half_extents: Vec2,
365 mut translation: Vec3,
366 velocity_rng: &mut ChaCha8Rng,
367 waves: Option<usize>,
368 dt: f32,
369) -> (Transform, Vec3) {
370 let mut velocity = Vec3::new(MAX_VELOCITY * (velocity_rng.random::<f32>() - 0.5), 0., 0.);
371
372 if let Some(waves) = waves {
373 // Step the movement and handle collisions as if the wave had been spawned at fixed time intervals
374 // and with dt-spaced frames of simulation
375 for _ in 0..(waves * (FIXED_TIMESTEP / dt).round() as usize) {
376 step_movement(&mut translation, &mut velocity, dt);
377 handle_collision(half_extents, &translation, &mut velocity);
378 }
379 }
380 (
381 Transform::from_translation(translation).with_scale(Vec3::splat(BIRD_SCALE)),
382 velocity,
383 )
384}
385
386const FIXED_DELTA_TIME: f32 = 1.0 / 60.0;
387
388fn spawn_birds(
389 commands: &mut Commands,
390 args: &Args,
391 primary_window_resolution: &WindowResolution,
392 counter: &mut BevyCounter,
393 spawn_count: usize,
394 bird_resources: &mut BirdResources,
395 waves_to_simulate: Option<usize>,
396 wave: usize,
397) {
398 let bird_x = (primary_window_resolution.width() / -2.) + HALF_BIRD_SIZE;
399 let bird_y = (primary_window_resolution.height() / 2.) - HALF_BIRD_SIZE;
400
401 let half_extents = 0.5 * primary_window_resolution.size();
402
403 let color = counter.color;
404 let current_count = counter.count;
405
406 match args.mode {
407 Mode::Sprite => {
408 let alpha_mode = match args.alpha_mode {
409 AlphaMode::Opaque => SpriteAlphaMode::Opaque,
410 AlphaMode::Blend => SpriteAlphaMode::Blend,
411 AlphaMode::AlphaMask => SpriteAlphaMode::Mask(0.5),
412 };
413
414 let batch = (0..spawn_count)
415 .map(|count| {
416 let bird_z = if args.ordered_z {
417 (current_count + count) as f32 * 0.00001
418 } else {
419 bird_resources.transform_rng.random::<f32>()
420 };
421
422 let (transform, velocity) = bird_velocity_transform(
423 half_extents,
424 Vec3::new(bird_x, bird_y, bird_z),
425 &mut bird_resources.velocity_rng,
426 waves_to_simulate,
427 FIXED_DELTA_TIME,
428 );
429
430 let color = if args.vary_per_instance {
431 Color::linear_rgb(
432 bird_resources.color_rng.random(),
433 bird_resources.color_rng.random(),
434 bird_resources.color_rng.random(),
435 )
436 } else {
437 color
438 };
439 (
440 Sprite {
441 image: bird_resources
442 .textures
443 .choose(&mut bird_resources.material_rng)
444 .unwrap()
445 .clone(),
446 color,
447 alpha_mode,
448 ..default()
449 },
450 transform,
451 Bird { velocity },
452 )
453 })
454 .collect::<Vec<_>>();
455 commands.spawn_batch(batch);
456 }
457 Mode::Mesh2d => {
458 let batch = (0..spawn_count)
459 .map(|count| {
460 let bird_z = if args.ordered_z {
461 (current_count + count) as f32 * 0.00001
462 } else {
463 bird_resources.transform_rng.random::<f32>()
464 };
465
466 let (transform, velocity) = bird_velocity_transform(
467 half_extents,
468 Vec3::new(bird_x, bird_y, bird_z),
469 &mut bird_resources.velocity_rng,
470 waves_to_simulate,
471 FIXED_DELTA_TIME,
472 );
473
474 let material =
475 if args.vary_per_instance || args.material_texture_count > args.waves {
476 bird_resources
477 .materials
478 .choose(&mut bird_resources.material_rng)
479 .unwrap()
480 .clone()
481 } else {
482 bird_resources.materials[wave % bird_resources.materials.len()].clone()
483 };
484 (
485 Mesh2d(bird_resources.quad.clone()),
486 MeshMaterial2d(material),
487 transform,
488 Bird { velocity },
489 )
490 })
491 .collect::<Vec<_>>();
492 commands.spawn_batch(batch);
493 }
494 }
495
496 counter.count += spawn_count;
497 counter.color = Color::linear_rgb(
498 bird_resources.color_rng.random(),
499 bird_resources.color_rng.random(),
500 bird_resources.color_rng.random(),
501 );
502}92fn draw(
93 my_handle: Res<MyProcGenImage>,
94 mut images: ResMut<Assets<Image>>,
95 // Used to keep track of where we are
96 mut i: Local<u32>,
97 mut draw_color: Local<Color>,
98 mut seeded_rng: ResMut<SeededRng>,
99) {
100 if *i == 0 {
101 // Generate a random color on first run.
102 *draw_color = Color::linear_rgb(
103 seeded_rng.0.random(),
104 seeded_rng.0.random(),
105 seeded_rng.0.random(),
106 );
107 }
108
109 // Get the image from Bevy's asset storage.
110 let mut image = images.get_mut(&my_handle.0).expect("Image not found");
111
112 // Compute the position of the pixel to draw.
113
114 let center = Vec2::new(IMAGE_WIDTH as f32 / 2.0, IMAGE_HEIGHT as f32 / 2.0);
115 let max_radius = IMAGE_HEIGHT.min(IMAGE_WIDTH) as f32 / 2.0;
116 let rot_speed = 0.0123;
117 let period = 0.12345;
118
119 let r = ops::sin(*i as f32 * period) * max_radius;
120 let xy = Vec2::from_angle(*i as f32 * rot_speed) * r + center;
121 let (x, y) = (xy.x as u32, xy.y as u32);
122
123 // Get the old color of that pixel.
124 let old_color = image.get_color_at(x, y).unwrap();
125
126 // If the old color is our current color, change our drawing color.
127 let tolerance = 1.0 / 255.0;
128 if old_color.distance(&draw_color) <= tolerance {
129 *draw_color = Color::linear_rgb(
130 seeded_rng.0.random(),
131 seeded_rng.0.random(),
132 seeded_rng.0.random(),
133 );
134 }
135
136 // Set the new color, but keep old alpha value from image.
137 image
138 .set_color_at(x, y, draw_color.with_alpha(old_color.alpha()))
139 .unwrap();
140
141 *i += 1;
142}126fn setup(
127 mut commands: Commands,
128 mut meshes: ResMut<Assets<Mesh>>,
129 mut materials: ResMut<Assets<ColorMaterial>>,
130 window: Single<&Window>,
131) {
132 let window_size = window.resolution.physical_size().as_vec2();
133
134 // Initialize centered, non-window-filling viewport
135 commands.spawn((
136 Camera2d,
137 Camera {
138 viewport: Some(Viewport {
139 physical_position: (window_size * 0.125).as_uvec2(),
140 physical_size: (window_size * 0.75).as_uvec2(),
141 ..default()
142 }),
143 ..default()
144 },
145 ));
146
147 // Create a minimal UI explaining how to interact with the example
148 commands.spawn((
149 Text::new(
150 "Move the mouse to see the circle follow your cursor.\n\
151 Use the arrow keys to move the camera.\n\
152 Use the comma and period keys to zoom in and out.\n\
153 Use the WASD keys to move the viewport.\n\
154 Use the IJKL keys to resize the viewport.",
155 ),
156 Node {
157 position_type: PositionType::Absolute,
158 top: px(12),
159 left: px(12),
160 ..default()
161 },
162 ));
163
164 // Add mesh to make camera movement visible
165 commands.spawn((
166 Mesh2d(meshes.add(Rectangle::new(40.0, 20.0))),
167 MeshMaterial2d(materials.add(Color::from(GREEN))),
168 ));
169
170 // Add background to visualize viewport bounds
171 commands.spawn((
172 Mesh2d(meshes.add(Rectangle::new(50000.0, 50000.0))),
173 MeshMaterial2d(materials.add(Color::linear_rgb(0.01, 0.01, 0.01))),
174 Transform::from_translation(Vec3::new(0.0, 0.0, -200.0)),
175 ));
176}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(GlobalAmbientLight {
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 shadow_maps_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 let make_wheel = |x: f32, z: f32| {
140 (
141 Mesh3d(cylinder.clone()),
142 MeshMaterial3d(wheel_matl.clone()),
143 Transform::from_xyz(0.14 * x, -0.045, 0.15 * z)
144 .with_scale(Vec3::new(0.15, 0.04, 0.15))
145 .with_rotation(Quat::from_rotation_z(std::f32::consts::FRAC_PI_2)),
146 Rotates,
147 )
148 };
149
150 for i in 0..N_CARS {
151 let color = colors[i % colors.len()].clone();
152 commands
153 .spawn((
154 Mesh3d(box_mesh.clone()),
155 MeshMaterial3d(color.clone()),
156 Transform::from_scale(Vec3::splat(0.5)),
157 Moves(i as f32 * 2.0),
158 children![
159 (
160 Mesh3d(box_mesh.clone()),
161 MeshMaterial3d(color),
162 Transform::from_xyz(0.0, 0.08, 0.03).with_scale(Vec3::new(1.0, 1.0, 0.5)),
163 ),
164 make_wheel(1.0, 1.0),
165 make_wheel(1.0, -1.0),
166 make_wheel(-1.0, 1.0),
167 make_wheel(-1.0, -1.0)
168 ],
169 ))
170 .insert_if(CameraTracked, || i == 0);
171 }
172}
173
174fn spawn_barriers(
175 meshes: &mut Assets<Mesh>,
176 materials: &mut Assets<StandardMaterial>,
177 commands: &mut Commands,
178) {
179 const N_CONES: usize = 100;
180 let capsule = meshes.add(Capsule3d::default());
181 let matl = materials.add(StandardMaterial {
182 base_color: Color::srgb_u8(255, 87, 51),
183 reflectance: 1.0,
184 ..default()
185 });
186 let mut spawn_with_offset = |offset: f32| {
187 for i in 0..N_CONES {
188 let pos = race_track_pos(
189 offset,
190 (i as f32) / (N_CONES as f32) * std::f32::consts::PI * 2.0,
191 );
192 commands.spawn((
193 Mesh3d(capsule.clone()),
194 MeshMaterial3d(matl.clone()),
195 Transform::from_xyz(pos.x, -0.65, pos.y).with_scale(Vec3::splat(0.07)),
196 ));
197 }
198 };
199 spawn_with_offset(0.04);
200 spawn_with_offset(-0.04);
201}
202
203fn spawn_trees(
204 meshes: &mut Assets<Mesh>,
205 materials: &mut Assets<StandardMaterial>,
206 commands: &mut Commands,
207) {
208 const N_TREES: usize = 30;
209 let capsule = meshes.add(Capsule3d::default());
210 let sphere = meshes.add(Sphere::default());
211 let leaves = materials.add(Color::linear_rgb(0.0, 1.0, 0.0));
212 let trunk = materials.add(Color::linear_rgb(0.4, 0.2, 0.2));
213
214 let mut spawn_with_offset = |offset: f32| {
215 for i in 0..N_TREES {
216 let pos = race_track_pos(
217 offset,
218 (i as f32) / (N_TREES as f32) * std::f32::consts::PI * 2.0,
219 );
220 let [x, z] = pos.into();
221 commands.spawn((
222 Mesh3d(sphere.clone()),
223 MeshMaterial3d(leaves.clone()),
224 Transform::from_xyz(x, -0.3, z).with_scale(Vec3::splat(0.3)),
225 ));
226 commands.spawn((
227 Mesh3d(capsule.clone()),
228 MeshMaterial3d(trunk.clone()),
229 Transform::from_xyz(x, -0.5, z).with_scale(Vec3::new(0.05, 0.3, 0.05)),
230 ));
231 }
232 };
233 spawn_with_offset(0.07);
234 spawn_with_offset(-0.07);
235}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?
56fn setup(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>) {
57 commands.spawn((
58 Mesh3d(meshes.add(Cuboid::new(0.5, 0.5, 0.5))),
59 InstanceMaterialData(
60 (1..=10)
61 .flat_map(|x| (1..=10).map(move |y| (x as f32 / 10.0, y as f32 / 10.0)))
62 .map(|(x, y)| InstanceData {
63 position: Vec3::new(x * 10.0 - 5.0, y * 10.0 - 5.0, 0.0),
64 scale: 1.0,
65 color: LinearRgba::from(Color::hsla(x * 360., y, 0.5, 1.0)).to_f32_array(),
66 })
67 .collect(),
68 ),
69 // NOTE: Frustum culling is done based on the Aabb of the Mesh and the GlobalTransform.
70 // As the cube is at the origin, if its Aabb moves outside the view frustum, all the
71 // instanced cubes will be culled.
72 // The InstanceMaterialData contains the 'GlobalTransform' information for this custom
73 // instancing, and that is not taken into account with the built-in frustum culling.
74 // We must disable the built-in frustum culling by adding the `NoFrustumCulling` marker
75 // component to avoid incorrect culling.
76 NoFrustumCulling,
77 ));
78
79 // camera
80 commands.spawn((
81 Camera3d::default(),
82 Transform::from_xyz(0.0, 0.0, 15.0).looking_at(Vec3::ZERO, Vec3::Y),
83 // We need this component because we use `draw_indexed` and `draw`
84 // instead of `draw_indirect_indexed` and `draw_indirect` in
85 // `DrawMeshInstanced::render`.
86 NoIndirectDrawing,
87 ));
88}More examples
202 pub fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
203 commands.spawn((Camera2d, DespawnOnExit(super::Scene::Text)));
204
205 for (i, justify) in [
206 Justify::Left,
207 Justify::Right,
208 Justify::Center,
209 Justify::Justified,
210 ]
211 .into_iter()
212 .enumerate()
213 {
214 let y = 230. - 150. * i as f32;
215 spawn_anchored_text(&mut commands, -300. * Vec3::X + y * Vec3::Y, justify, None);
216 spawn_anchored_text(
217 &mut commands,
218 300. * Vec3::X + y * Vec3::Y,
219 justify,
220 Some(TextBounds::new(150., 60.)),
221 );
222 }
223
224 let sans_serif = TextFont::from(asset_server.load("fonts/FiraSans-Bold.ttf"));
225
226 const NUM_ITERATIONS: usize = 10;
227 for i in 0..NUM_ITERATIONS {
228 let fraction = i as f32 / (NUM_ITERATIONS - 1) as f32;
229
230 commands.spawn((
231 Text2d::new("Bevy"),
232 sans_serif.clone(),
233 Transform::from_xyz(0.0, fraction * 200.0, i as f32)
234 .with_scale(1.0 + Vec2::splat(fraction).extend(1.))
235 .with_rotation(Quat::from_rotation_z(fraction * core::f32::consts::PI)),
236 TextColor(Color::hsla(fraction * 360.0, 0.8, 0.8, 0.8)),
237 DespawnOnExit(super::Scene::Text),
238 ));
239 }
240
241 commands.spawn((
242 Text2d::new("This text is invisible."),
243 Visibility::Hidden,
244 DespawnOnExit(super::Scene::Text),
245 ));
246 }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
91fn animate_materials(
92 material_handles: Query<&MeshMaterial3d<StandardMaterial>>,
93 time: Res<Time>,
94 mut materials: ResMut<Assets<StandardMaterial>>,
95) {
96 for (i, material_handle) in material_handles.iter().enumerate() {
97 if let Some(mut material) = materials.get_mut(material_handle) {
98 let color = Color::hsl(
99 ((i as f32 * 2.345 + time.elapsed_secs()) * 100.0) % 360.0,
100 1.0,
101 0.5,
102 );
103 material.base_color = color;
104 }
105 }
106}90fn animate(
91 mut materials: ResMut<Assets<CustomUiMaterial>>,
92 q: Query<&MaterialNode<CustomUiMaterial>>,
93 time: Res<Time>,
94) {
95 let duration = 2.0;
96 for handle in &q {
97 if let Some(mut material) = materials.get_mut(handle) {
98 // rainbow color effect
99 let new_color = Color::hsl((time.elapsed_secs() * 60.0) % 360.0, 1., 0.5);
100 let border_color = Color::hsl((time.elapsed_secs() * 60.0) % 360.0, 0.75, 0.75);
101 material.color = new_color.to_linear().to_vec4();
102 material.slider.x =
103 ((time.elapsed_secs() % (duration * 2.0)) - duration).abs() / duration;
104 material.border_color = border_color.to_linear().to_vec4();
105 }
106 }
107}104fn setup_scene(
105 mut commands: Commands,
106 mut meshes: ResMut<Assets<Mesh>>,
107 mut materials: ResMut<Assets<ColorMaterial>>,
108) {
109 commands.spawn(Camera2d);
110
111 let named_shapes = [
112 (Name::new("Annulus"), meshes.add(Annulus::new(25.0, 50.0))),
113 (
114 Name::new("Bestagon"),
115 meshes.add(RegularPolygon::new(50.0, 6)),
116 ),
117 (Name::new("Rhombus"), meshes.add(Rhombus::new(75.0, 100.0))),
118 ];
119 let num_shapes = named_shapes.len();
120
121 for (i, (name, shape)) in named_shapes.into_iter().enumerate() {
122 // Distribute colors evenly across the rainbow.
123 let color = Color::hsl(360. * i as f32 / num_shapes as f32, 0.95, 0.7);
124
125 commands.spawn((
126 name,
127 DisableOnClick,
128 Mesh2d(shape),
129 MeshMaterial2d(materials.add(color)),
130 Transform::from_xyz(
131 // Distribute shapes from -X_EXTENT/2 to +X_EXTENT/2.
132 -X_EXTENT / 2. + i as f32 / (num_shapes - 1) as f32 * X_EXTENT,
133 0.0,
134 0.0,
135 ),
136 ));
137 }
138}144fn animate_gradients(
145 mut gradients: Query<(&mut BackgroundGradient, &GradientNode)>,
146 args: Res<Args>,
147 time: Res<Time>,
148) {
149 if !args.animate {
150 return;
151 }
152
153 let t = time.elapsed_secs();
154
155 for (mut bg_gradient, node) in &mut gradients {
156 let offset = node.index as f32 * 0.01;
157 let hue_shift = sin(t + offset) * 0.5 + 0.5;
158
159 if let Some(Gradient::Linear(gradient)) = bg_gradient.0.get_mut(0) {
160 let color1 = Color::hsl(hue_shift * 360.0, 1.0, 0.5);
161 let color2 = Color::hsl((hue_shift + 0.3) * 360.0 % 360.0, 1.0, 0.5);
162
163 gradient.stops = vec![
164 ColorStop::new(color1, percent(0)),
165 ColorStop::new(color2, percent(100)),
166 ColorStop::new(
167 Color::hsl((hue_shift + 0.1) * 360.0 % 360.0, 1.0, 0.5),
168 percent(20),
169 ),
170 ColorStop::new(
171 Color::hsl((hue_shift + 0.15) * 360.0 % 360.0, 1.0, 0.5),
172 percent(40),
173 ),
174 ColorStop::new(
175 Color::hsl((hue_shift + 0.2) * 360.0 % 360.0, 1.0, 0.5),
176 percent(60),
177 ),
178 ColorStop::new(
179 Color::hsl((hue_shift + 0.25) * 360.0 % 360.0, 1.0, 0.5),
180 percent(80),
181 ),
182 ColorStop::new(
183 Color::hsl((hue_shift + 0.28) * 360.0 % 360.0, 1.0, 0.5),
184 percent(90),
185 ),
186 ];
187 }
188 }
189}121 pub fn setup(
122 mut commands: Commands,
123 mut meshes: ResMut<Assets<Mesh>>,
124 mut materials: ResMut<Assets<ColorMaterial>>,
125 ) {
126 commands.spawn((Camera2d, DespawnOnExit(super::Scene::Shapes)));
127
128 let shapes = [
129 meshes.add(Circle::new(50.0)),
130 meshes.add(CircularSector::new(50.0, 1.0)),
131 meshes.add(CircularSegment::new(50.0, 1.25)),
132 meshes.add(Ellipse::new(25.0, 50.0)),
133 meshes.add(Annulus::new(25.0, 50.0)),
134 meshes.add(Capsule2d::new(25.0, 50.0)),
135 meshes.add(Rhombus::new(75.0, 100.0)),
136 meshes.add(Rectangle::new(50.0, 100.0)),
137 meshes.add(RegularPolygon::new(50.0, 6)),
138 meshes.add(Triangle2d::new(
139 Vec2::Y * 50.0,
140 Vec2::new(-50.0, -50.0),
141 Vec2::new(50.0, -50.0),
142 )),
143 ];
144 let num_shapes = shapes.len();
145
146 for (i, shape) in shapes.into_iter().enumerate() {
147 // Distribute colors evenly across the rainbow.
148 let color = Color::hsl(360. * i as f32 / num_shapes as f32, 0.95, 0.7);
149
150 commands.spawn((
151 Mesh2d(shape),
152 MeshMaterial2d(materials.add(color)),
153 Transform::from_xyz(
154 // Distribute shapes from -X_EXTENT/2 to +X_EXTENT/2.
155 -X_EXTENT / 2. + i as f32 / (num_shapes - 1) as f32 * X_EXTENT,
156 0.0,
157 0.0,
158 ),
159 DespawnOnExit(super::Scene::Shapes),
160 ));
161 }
162 }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?
101fn setup(
102 mut commands: Commands,
103 asset_server: Res<AssetServer>,
104 app_status: Res<AppStatus>,
105 mut meshes: ResMut<Assets<Mesh>>,
106 mut standard_materials: ResMut<Assets<StandardMaterial>>,
107) {
108 // Spawns a camera.
109 commands.spawn((
110 Transform::from_xyz(-2.0, 0.0, 3.5).looking_at(Vec3::ZERO, Vec3::Y),
111 Hdr,
112 Camera3d::default(),
113 Skybox {
114 image: Some(asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2")),
115 brightness: 3000.0,
116 ..default()
117 },
118 EnvironmentMapLight {
119 diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"),
120 specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
121 // We want relatively high intensity here in order for the specular
122 // tint to show up well.
123 intensity: 25000.0,
124 ..default()
125 },
126 ));
127
128 // Spawn the sphere.
129 commands.spawn((
130 Transform::from_rotation(Quat::from_rotation_x(PI * 0.5)),
131 Mesh3d(meshes.add(Sphere::default().mesh().uv(32, 18))),
132 MeshMaterial3d(standard_materials.add(StandardMaterial {
133 // We want only reflected specular light here, so we set the base
134 // color as black.
135 base_color: Color::BLACK,
136 reflectance: 1.0,
137 specular_tint: Color::hsva(app_status.hue, 1.0, 1.0, 1.0),
138 // The object must not be metallic, or else the reflectance is
139 // ignored per the Filament spec:
140 //
141 // <https://google.github.io/filament/Filament.md.html#listing_fnormal>
142 metallic: 0.0,
143 perceptual_roughness: 0.0,
144 ..default()
145 })),
146 ));
147
148 spawn_buttons(&mut commands);
149}
150
151/// Rotates the camera a bit every frame.
152fn rotate_camera(mut cameras: Query<&mut Transform, With<Camera3d>>) {
153 for mut camera_transform in cameras.iter_mut() {
154 camera_transform.translation =
155 Quat::from_rotation_y(ROTATION_SPEED) * camera_transform.translation;
156 camera_transform.look_at(Vec3::ZERO, Vec3::Y);
157 }
158}
159
160/// Alters the hue of the solid color a bit every frame.
161fn shift_hue(
162 mut app_status: ResMut<AppStatus>,
163 objects_with_materials: Query<&MeshMaterial3d<StandardMaterial>>,
164 mut standard_materials: ResMut<Assets<StandardMaterial>>,
165) {
166 if app_status.tint_type != TintType::Solid {
167 return;
168 }
169
170 app_status.hue += HUE_SHIFT_SPEED;
171
172 for material_handle in objects_with_materials.iter() {
173 let Some(mut material) = standard_materials.get_mut(material_handle) else {
174 continue;
175 };
176 material.specular_tint = Color::hsva(app_status.hue, 1.0, 1.0, 1.0);
177 }
178}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?
39fn setup(
40 mut commands: Commands,
41 mut meshes: ResMut<Assets<Mesh>>,
42 mut materials: ResMut<Assets<StandardMaterial>>,
43 window: Query<&Window>,
44) -> Result {
45 warn!(include_str!("warning_string.txt"));
46
47 // circular base
48 commands.spawn((
49 Mesh3d(meshes.add(Circle::new(4.0))),
50 MeshMaterial3d(materials.add(Color::WHITE)),
51 Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
52 ));
53
54 // cube
55 commands.spawn((
56 Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
57 MeshMaterial3d(materials.add(Color::WHITE)),
58 Transform::from_xyz(0.0, 0.5, 0.0),
59 ));
60
61 // lights
62 for i in 0..NUM_LIGHTS {
63 let angle = (i as f32) / (NUM_LIGHTS as f32) * PI * 2.0;
64 commands.spawn((
65 PointLight {
66 color: Color::hsv(angle.to_degrees(), 1.0, 1.0),
67 intensity: 2_000_000.0 / NUM_LIGHTS as f32,
68 shadow_maps_enabled: true,
69 ..default()
70 },
71 Transform::from_xyz(sin(angle) * 4.0, 2.0, cos(angle) * 4.0),
72 ));
73 }
74
75 // cameras
76 let window = window.single()?;
77 let width = window.resolution.width() / CAMERA_COLS as f32 * window.resolution.scale_factor();
78 let height = window.resolution.height() / CAMERA_ROWS as f32 * window.resolution.scale_factor();
79 let mut i = 0;
80 for y in 0..CAMERA_COLS {
81 for x in 0..CAMERA_ROWS {
82 let angle = i as f32 / (CAMERA_ROWS * CAMERA_COLS) as f32 * PI * 2.0;
83 commands.spawn((
84 Camera3d::default(),
85 Camera {
86 viewport: Some(Viewport {
87 physical_position: UVec2::new(
88 (x as f32 * width) as u32,
89 (y as f32 * height) as u32,
90 ),
91 physical_size: UVec2::new(width as u32, height as u32),
92 ..default()
93 }),
94 order: i,
95 ..default()
96 },
97 Transform::from_xyz(sin(angle) * 4.0, 2.5, cos(angle) * 4.0)
98 .looking_at(Vec3::ZERO, Vec3::Y),
99 ));
100 i += 1;
101 }
102 }
103 Ok(())
104}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
impl Copy for Color
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 Color
impl Enum for Color
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) -> Result<DynamicEnum, ReflectCloneError>
fn to_dynamic_enum(&self) -> Result<DynamicEnum, ReflectCloneError>
DynamicEnum from this enum. Read moreSource§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 LinearRgba
impl From<Color> for LinearRgba
Source§fn from(value: Color) -> LinearRgba
fn from(value: Color) -> LinearRgba
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 StandardMaterial
impl From<Color> for StandardMaterial
Source§fn from(color: Color) -> StandardMaterial
fn from(color: Color) -> StandardMaterial
Source§impl From<Color> for AngularColorStop
impl From<Color> for AngularColorStop
Source§fn from(color: Color) -> AngularColorStop
fn from(color: Color) -> AngularColorStop
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<LinearRgba> for Color
impl From<LinearRgba> for Color
Source§fn from(value: LinearRgba) -> Color
fn from(value: LinearRgba) -> Color
Source§impl FromReflect for Color
impl FromReflect for Color
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 GetTypeRegistration for Color
impl GetTypeRegistration for Color
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 Color
impl IntoReturn for Color
Source§impl Luminance for Color
impl Luminance for Color
Source§fn luminance(&self) -> f32
fn luminance(&self) -> f32
[0.0, 1.0]. An HDR
color’s luminance can be above or below 1.0.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, so this operation is not suitable
for HDR colors. To scale an HDR color, use with_luminance. 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 Color
impl PartialReflect for Color
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_partial_cmp(
&self,
value: &(dyn PartialReflect + 'static),
) -> Option<Ordering>
fn reflect_partial_cmp( &self, value: &(dyn PartialReflect + 'static), ) -> Option<Ordering>
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 to_dynamic(&self) -> Result<Box<dyn PartialReflect>, ReflectCloneError>
fn to_dynamic(&self) -> Result<Box<dyn PartialReflect>, ReflectCloneError>
Source§fn reflect_clone_and_take<T>(&self) -> Result<T, ReflectCloneError>
fn reflect_clone_and_take<T>(&self) -> Result<T, ReflectCloneError>
PartialReflect, combines reflect_clone and
take in a useful fashion, automatically constructing an appropriate
ReflectCloneError if the downcast fails.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 Color
impl Reflect for Color
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,
impl StructuralPartialEq for Color
Source§impl TryStableInterpolate for Color
impl TryStableInterpolate for Color
Source§type Error = MismatchedUnitsError
type Error = MismatchedUnitsError
Source§fn try_interpolate_stable(
&self,
other: &Color,
t: f32,
) -> Result<Color, <Color as TryStableInterpolate>::Error>
fn try_interpolate_stable( &self, other: &Color, t: f32, ) -> Result<Color, <Color as TryStableInterpolate>::Error>
Source§fn try_interpolate_stable_assign(
&mut self,
other: &Self,
t: f32,
) -> Result<(), Self::Error>
fn try_interpolate_stable_assign( &mut self, other: &Self, t: f32, ) -> Result<(), Self::Error>
try_interpolate_stable that assigns the result to self for convenience.
On failure, self remains unchanged. Read moreSource§fn try_smooth_nudge(
&mut self,
target: &Self,
decay_rate: f32,
delta: f32,
) -> Result<(), Self::Error>
fn try_smooth_nudge( &mut self, target: &Self, decay_rate: f32, delta: f32, ) -> Result<(), Self::Error>
StableInterpolate::smooth_nudge but fallible.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>
Auto Trait Implementations§
impl Freeze for Color
impl RefUnwindSafe for Color
impl Send for Color
impl Sync for Color
impl Unpin for Color
impl UnsafeUnpin 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
impl<T> Brush for T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> ConditionalSend for Twhere
T: Send,
impl<T> DeserializeOwned for Twhere
T: for<'de> Deserialize<'de>,
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
impl<S, T> Duplex<S> for Twhere
T: FromSample<S> + ToSample<S>,
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.impl<T> ErasedDestructor for Twhere
T: 'static,
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> FromTemplate for T
impl<T> FromTemplate for T
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, W> HasTypeWitness<W> for Twhere
W: MakeTypeWitness<Arg = T>,
T: ?Sized,
impl<T, W> HasTypeWitness<W> for Twhere
W: MakeTypeWitness<Arg = T>,
T: ?Sized,
impl<T> HitDataExtra for T
Source§impl<T> Identity for Twhere
T: ?Sized,
impl<T> Identity for Twhere
T: ?Sized,
Source§impl<T> InitializeFromFunction<T> for T
impl<T> InitializeFromFunction<T> for T
Source§fn initialize_from_function(f: fn() -> T) -> T
fn initialize_from_function(f: fn() -> T) -> T
Source§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<T> IntoResult<T> for T
impl<T> IntoResult<T> for T
Source§fn into_result(self) -> Result<T, RunSystemError>
fn into_result(self) -> Result<T, RunSystemError>
Source§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<G> PatchFromTemplate for Gwhere
G: FromTemplate,
impl<G> PatchFromTemplate for Gwhere
G: FromTemplate,
Source§fn patch<F>(func: F) -> TemplatePatch<F, <G as PatchFromTemplate>::Template>
fn patch<F>(func: F) -> TemplatePatch<F, <G as PatchFromTemplate>::Template>
func, and turns it into a TemplatePatch.Source§impl<T> PatchTemplate for Twhere
T: Template,
impl<T> PatchTemplate for Twhere
T: Template,
Source§fn patch_template<F>(func: F) -> TemplatePatch<F, T>
fn patch_template<F>(func: F) -> TemplatePatch<F, 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.impl<T> Read<Exclusive, BecauseExclusive> for Twhere
T: ?Sized,
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().impl<T> Reflectable for T
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>
impl<T> Settings for T
Source§impl<Ret> SpawnIfAsync<(), Ret> for Ret
impl<Ret> SpawnIfAsync<(), Ret> for Ret
Source§impl<T, O> SuperFrom<T> for Owhere
O: From<T>,
impl<T, O> SuperFrom<T> for Owhere
O: From<T>,
Source§fn super_from(input: T) -> O
fn super_from(input: T) -> O
Source§impl<T, O, M> SuperInto<O, M> for Twhere
O: SuperFrom<T, M>,
impl<T, O, M> SuperInto<O, M> for Twhere
O: SuperFrom<T, M>,
Source§fn super_into(self) -> O
fn super_into(self) -> O
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.Source§impl<T> Template for T
impl<T> Template for T
Source§fn build_template(
&self,
_context: &mut TemplateContext<'_, '_>,
) -> Result<<T as Template>::Output, BevyError>
fn build_template( &self, _context: &mut TemplateContext<'_, '_>, ) -> Result<<T as Template>::Output, BevyError>
entity context to produce a Template::Output.Source§fn clone_template(&self) -> T
fn clone_template(&self) -> T
Clone.Source§impl<T, U> ToSample<U> for Twhere
U: FromSample<T>,
impl<T, U> ToSample<U> for Twhere
U: FromSample<T>,
fn to_sample_(self) -> U
Source§impl<T> TypeData for T
impl<T> TypeData for T
Source§fn clone_type_data(&self) -> Box<dyn TypeData>
fn clone_type_data(&self) -> Box<dyn TypeData>
self.