pub struct AssetServer { /* private fields */ }bevy_asset only.Expand description
Loads and tracks the state of Asset values from a configured AssetReader.
This can be used to kick off new asset loads and retrieve their current load states.
The general process to load an asset is:
- Initialize a new
Assettype with theAssetServerviaAssetApp::init_asset, which will internally callAssetServer::register_assetand set up related ECSAssetsstorage and systems. - Register one or more
AssetLoaders for that asset withAssetApp::init_asset_loader - Add the asset to your asset folder (defaults to
assets). - Call
AssetServer::loadwith a path to your asset.
AssetServer can be cloned. It is backed by an Arc so clones will share state. Clones can be freely used in parallel.
Implementations§
Source§impl AssetServer
impl AssetServer
Sourcepub const STARTED_LOAD_COUNT: DiagnosticPath
pub const STARTED_LOAD_COUNT: DiagnosticPath
The number of loads that have been started by the server.
Sourcepub fn new(
sources: Arc<AssetSources>,
mode: AssetServerMode,
watching_for_changes: bool,
unapproved_path_mode: UnapprovedPathMode,
) -> AssetServer
pub fn new( sources: Arc<AssetSources>, mode: AssetServerMode, watching_for_changes: bool, unapproved_path_mode: UnapprovedPathMode, ) -> AssetServer
Create a new instance of AssetServer. If watch_for_changes is true, the AssetReader storage will watch for changes to
asset sources and hot-reload them.
Sourcepub fn new_with_meta_check(
sources: Arc<AssetSources>,
mode: AssetServerMode,
meta_check: AssetMetaCheck,
watching_for_changes: bool,
unapproved_path_mode: UnapprovedPathMode,
) -> AssetServer
pub fn new_with_meta_check( sources: Arc<AssetSources>, mode: AssetServerMode, meta_check: AssetMetaCheck, watching_for_changes: bool, unapproved_path_mode: UnapprovedPathMode, ) -> AssetServer
Create a new instance of AssetServer. If watch_for_changes is true, the AssetReader storage will watch for changes to
asset sources and hot-reload them.
Sourcepub fn get_source<'a>(
&self,
source: impl Into<AssetSourceId<'a>>,
) -> Result<&AssetSource, MissingAssetSourceError>
pub fn get_source<'a>( &self, source: impl Into<AssetSourceId<'a>>, ) -> Result<&AssetSource, MissingAssetSourceError>
Retrieves the AssetSource for the given source.
Sourcepub fn watching_for_changes(&self) -> bool
pub fn watching_for_changes(&self) -> bool
Returns true if the AssetServer watches for changes.
Sourcepub fn register_loader<L>(&self, loader: L)where
L: AssetLoader,
pub fn register_loader<L>(&self, loader: L)where
L: AssetLoader,
Registers a new AssetLoader. AssetLoaders must be registered before they can be used.
Sourcepub fn register_asset<A>(&self, assets: &Assets<A>)where
A: Asset,
pub fn register_asset<A>(&self, assets: &Assets<A>)where
A: Asset,
Sourcepub async fn get_asset_loader_with_extension(
&self,
extension: &str,
) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForExtensionError>
pub async fn get_asset_loader_with_extension( &self, extension: &str, ) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForExtensionError>
Returns the registered AssetLoader associated with the given extension, if it exists.
Sourcepub async fn get_asset_loader_with_type_name(
&self,
type_name: &str,
) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForTypeNameError>
pub async fn get_asset_loader_with_type_name( &self, type_name: &str, ) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForTypeNameError>
Returns the registered AssetLoader associated with the given type name, if it exists.
Sourcepub async fn get_path_asset_loader<'a>(
&self,
path: impl Into<AssetPath<'a>>,
) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForExtensionError>
pub async fn get_path_asset_loader<'a>( &self, path: impl Into<AssetPath<'a>>, ) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForExtensionError>
Retrieves the default AssetLoader for the given path, if one can be found.
Sourcepub async fn get_asset_loader_with_asset_type_id(
&self,
type_id: TypeId,
) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForTypeIdError>
pub async fn get_asset_loader_with_asset_type_id( &self, type_id: TypeId, ) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForTypeIdError>
Retrieves the default AssetLoader for the given Asset TypeId, if one can be found.
Sourcepub async fn get_asset_loader_with_asset_type<A>(
&self,
) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForTypeIdError>where
A: Asset,
pub async fn get_asset_loader_with_asset_type<A>(
&self,
) -> Result<Arc<dyn ErasedAssetLoader>, MissingAssetLoaderForTypeIdError>where
A: Asset,
Retrieves the default AssetLoader for the given Asset type, if one can be found.
Sourcepub fn load<'a, A>(&self, path: impl Into<AssetPath<'a>>) -> Handle<A>where
A: Asset,
pub fn load<'a, A>(&self, path: impl Into<AssetPath<'a>>) -> Handle<A>where
A: Asset,
Begins loading an Asset of type A stored at path. This will not block on the asset load. Instead,
it returns a “strong” Handle. When the Asset is loaded (and enters LoadState::Loaded), it will be added to the
associated Assets resource.
Note that if the asset at this path is already loaded, this function will return the existing handle, and will not waste work spawning a new load task.
In case the file path contains a hashtag (#), the path must be specified using Path
or AssetPath because otherwise the hashtag would be interpreted as separator between
the file path and the label. For example:
// `#path` is a label.
asset_server.load("some/file#path");
// `#path` is part of the file name.
asset_server.load(Path::new("some/file#path"));Furthermore, if you need to load a file with a hashtag in its name and a label, you can
manually construct an AssetPath.
asset_server.load(AssetPath::from_path(Path::new("some/file#path")).with_label("subasset"));You can check the asset’s load state by reading AssetEvent events, calling AssetServer::load_state, or checking
the Assets storage to see if the Asset exists yet.
The asset load will fail and an error will be printed to the logs if the asset stored at path is not of type A.
Examples found in repository?
More examples
- examples/3d/specular_tint.rs
- examples/audio/play_sound_effect.rs
- examples/3d/light_probe_blending.rs
- examples/state/computed_states.rs
- examples/asset/asset_decompression.rs
- examples/3d/mirror.rs
- examples/ecs/removal_detection.rs
- examples/3d/reflection_probes.rs
- examples/2d/move_sprite.rs
- examples/2d/rotate_to_cursor.rs
- examples/camera/pan_camera_controller.rs
- examples/shader_advanced/custom_shader_instancing.rs
- examples/shader_advanced/custom_render_phase.rs
- tests/3d/test_skinned_mesh_bounds.rs
- examples/gltf/gltf_extension_mesh_2d.rs
- examples/3d/clearcoat.rs
- examples/state/sub_states.rs
- examples/asset/web_asset.rs
- examples/shader_advanced/specialized_mesh_pipeline.rs
- examples/2d/sprite_flipping.rs
- examples/gltf/gltf_extension_animation_graph.rs
- examples/scene/world_serialization.rs
- examples/gltf/gltf_skinned_mesh.rs
- examples/3d/pccm.rs
- examples/asset/custom_asset.rs
- examples/2d/dynamic_mip_generation.rs
- examples/asset/processing/asset_processing.rs
- examples/2d/sprite_tile.rs
- examples/gltf/query_gltf_primitives.rs
- examples/3d/lightmaps.rs
- examples/shader/shader_material_2d.rs
- examples/ui/scroll_and_overflow/overflow_debug.rs
- examples/ecs/fallible_params.rs
- examples/3d/ssr.rs
- examples/audio/soundtrack.rs
- examples/3d/occlusion_culling.rs
- examples/gltf/custom_gltf_vertex_attribute.rs
- examples/2d/pixel_grid_snap.rs
- examples/3d/light_textures.rs
- examples/shader/shader_material.rs
- examples/3d/mixed_lighting.rs
- examples/asset/extra_source.rs
- examples/shader_advanced/texture_binding_array.rs
- examples/2d/sprite_slice.rs
- examples/ui/window_fallthrough.rs
- examples/asset/hot_asset_reloading.rs
- examples/ecs/parallel_query.rs
- examples/reflection/mutation_by_reflection.rs
- examples/audio/audio_control.rs
- examples/3d/color_grading.rs
- examples/2d/transparency_2d.rs
- examples/camera/pan_orbit_camera_minimal.rs
- examples/window/window_settings.rs
- examples/3d/clustered_decals.rs
- examples/shader/gpu_readback.rs
- examples/animation/morph_targets.rs
- examples/3d/rotate_environment_map.rs
- examples/ui/widgets/standard_widgets.rs
- examples/ui/widgets/standard_widgets_observers.rs
- examples/3d/clustered_decal_maps.rs
- examples/gltf/load_gltf_extras.rs
- examples/asset/embedded_asset.rs
- examples/shader_advanced/compute_mesh.rs
- examples/2d/sprite_sheet.rs
- examples/3d/order_independent_transparency.rs
- examples/3d/tonemapping.rs
- examples/showcase/loading_screen.rs
- examples/3d/post_processing.rs
- examples/showcase/game_menu.rs
- examples/shader/shader_material_screenspace_texture.rs
- examples/3d/depth_of_field.rs
- examples/ui/images/image_node.rs
- examples/testbed/3d.rs
- examples/shader/shader_material_bindless.rs
- examples/gltf/edit_material_on_gltf.rs
- examples/animation/animation_masks.rs
- examples/ui/text/font_atlas_debug.rs
- examples/3d/animated_material.rs
- examples/3d/pcss.rs
- examples/3d/anisotropy.rs
- examples/ui/widgets/button.rs
- examples/gltf/load_gltf.rs
- examples/animation/animated_mesh.rs
- examples/shader/shader_material_2d_bindless.rs
- examples/shader/extended_material_bindless.rs
- examples/shader/compute_shader_game_of_life.rs
- examples/gltf/update_gltf_scene.rs
- examples/shader/gpu_component_array_buffer.rs
- examples/stress_tests/text_pipeline.rs
- examples/3d/atmospheric_fog.rs
- examples/3d/skybox.rs
- examples/3d/fog_volumes.rs
- examples/window/custom_cursor_image.rs
- examples/2d/mesh2d_vertex_color_texture.rs
- examples/3d/generate_custom_mesh.rs
- examples/ui/text/inline_image.rs
- examples/stress_tests/many_sprites.rs
- examples/audio/spatial_audio_2d.rs
- examples/ui/relative_cursor_position.rs
- examples/ui/ui_material.rs
- examples/animation/animated_mesh_control.rs
- examples/ui/text/font_weights.rs
- examples/testbed/2d.rs
- examples/showcase/contributors.rs
- examples/window/multiple_windows.rs
- examples/ui/ui_scaling.rs
- examples/stress_tests/many_meshlet_materials.rs
- examples/ecs/hierarchy.rs
- examples/ui/images/ui_texture_atlas.rs
- examples/stress_tests/many_animated_sprites.rs
- examples/2d/bloom_2d.rs
- examples/stress_tests/many_morph_targets.rs
- examples/ui/text/font_variations.rs
- examples/animation/animated_ui.rs
- examples/state/custom_transitions.rs
- examples/3d/atmosphere.rs
- examples/animation/animated_mesh_events.rs
- examples/camera/pan_orbit_camera_cad.rs
- examples/audio/spatial_audio_3d.rs
- examples/asset/alter_sprite.rs
- examples/shader/automatic_instancing.rs
- examples/ui/text/text_input.rs
- examples/camera/projection_zoom.rs
- examples/2d/rotation.rs
- examples/stress_tests/many_buttons.rs
- examples/camera/2d_on_ui.rs
- examples/ui/images/ui_texture_slice.rs
- examples/3d/visibility_range.rs
- examples/2d/sprite_animation.rs
- examples/3d/volumetric_fog.rs
- examples/animation/animation_graph.rs
- examples/shader_advanced/mesh_shader_intro.rs
- examples/3d/texture.rs
- examples/3d/motion_blur.rs
- examples/shader_advanced/custom_phase_item.rs
- examples/time/virtual_time.rs
- examples/shader_advanced/custom_post_processing.rs
- examples/asset/compressed_image_saver.rs
- examples/3d/anti_aliasing.rs
- examples/testbed/ui.rs
- examples/camera/pan_orbit_camera_ortho.rs
- examples/transforms/align.rs
- examples/ui/layout/anchor_layout.rs
- examples/shader_advanced/deferred_raymarch.rs
- examples/picking/sprite_picking.rs
- examples/ui/images/ui_texture_atlas_slice.rs
- examples/showcase/stepping.rs
- examples/ui/layout/display_and_visibility.rs
- examples/shader_advanced/manual_material.rs
- examples/2d/mesh2d_alpha_mode.rs
- examples/2d/mesh2d_arcs.rs
- examples/ui/text/text_wrap_debug.rs
- examples/showcase/alien_cake_addict.rs
- examples/ui/styling/transparency_ui.rs
- examples/asset/repeated_texture.rs
- examples/asset/asset_settings.rs
- examples/2d/mesh2d_repeated_texture.rs
- examples/asset/alter_mesh.rs
- examples/3d/meshlet.rs
- examples/3d/pbr.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/ui/layout/flex_layout.rs
- examples/shader/shader_prepass.rs
- examples/stress_tests/bevymark_3d.rs
- examples/ui/widgets/vertical_slider.rs
- examples/stress_tests/bevymark.rs
- examples/3d/split_screen.rs
- examples/3d/solari_reflections.rs
- examples/ui/scroll_and_overflow/scroll.rs
- examples/3d/solari.rs
- examples/showcase/breakout.rs
- examples/3d/decal.rs
- examples/ui/images/image_node_resizing.rs
- examples/ui/text/strikethrough_and_underline.rs
- examples/ui/scroll_and_overflow/overflow_transform.rs
- examples/showcase/desk_toy.rs
- examples/3d/parallax_mapping.rs
- examples/stress_tests/many_text.rs
- examples/2d/texture_atlas.rs
- examples/2d/sprite_scale.rs
- examples/stress_tests/many_foxes.rs
- examples/3d/deferred_rendering.rs
- examples/ui/text/text.rs
- examples/3d/contact_shadows.rs
- examples/2d/text2d.rs
- examples/animation/custom_skinned_mesh.rs
- examples/3d/blend_modes.rs
- examples/3d/lighting.rs
- examples/ui/text/letter_spacing.rs
- examples/showcase/mines.rs
- examples/ui/text/text_debug.rs
- examples/ui/layout/grid.rs
- examples/3d/transmission.rs
- examples/ui/text/multiple_text_inputs.rs
- examples/ui/ui_transform.rs
- examples/ui/text/font_query.rs
- examples/testbed/full_ui.rs
- examples/ui/text/multiline_text_input.rs
Sourcepub fn load_builder(&self) -> LoadBuilder<'_>
pub fn load_builder(&self) -> LoadBuilder<'_>
Returns a LoadBuilder that can be used to start more complex loads. See LoadBuilder
for details.
Examples found in repository?
50 fn from_world(world: &mut World) -> Self {
51 // Load all the decal textures.
52 let asset_server = world.resource::<AssetServer>();
53 AppTextures {
54 decal_base_color_texture: asset_server.load("branding/bevy_bird_dark.png"),
55 decal_normal_map_texture: asset_server
56 .load_builder()
57 .with_settings(|settings: &mut ImageLoaderSettings| settings.is_srgb = false)
58 .load(get_web_asset_url("BevyLogo-Normal.png")),
59 decal_metallic_roughness_map_texture: asset_server
60 .load_builder()
61 .with_settings(|settings: &mut ImageLoaderSettings| settings.is_srgb = false)
62 .load(get_web_asset_url("BevyLogo-MetallicRoughness.png")),
63 decal_emissive_texture: asset_server.load(get_web_asset_url("BevyLogo-Emissive.png")),
64 }
65 }
66}
67
68/// A component that we place on our decals to track them for animation
69/// purposes.
70#[derive(Component)]
71struct ExampleDecal {
72 /// The width and height of the square decal in meters.
73 size: f32,
74 /// What state the decal is in (animating in, idling, or animating out).
75 state: ExampleDecalState,
76}
77
78/// The animation state of a decal.
79///
80/// When each [`Timer`] goes off, the decal advances to the next state.
81enum ExampleDecalState {
82 /// The decal has just been spawned and is animating in.
83 AnimatingIn(Timer),
84 /// The decal has animated in and is waiting to animate out.
85 Idling(Timer),
86 /// The decal is animating out.
87 ///
88 /// When this timer expires, the decal is despawned.
89 AnimatingOut(Timer),
90}
91
92/// All settings that the user can change.
93///
94/// This app only has one: whether newly-spawned decals are emissive.
95#[derive(Clone, Copy, Component, PartialEq)]
96enum AppSetting {
97 /// True if newly-spawned decals have an emissive channel (i.e. they glow),
98 /// or false otherwise.
99 EmissiveDecals(bool),
100}
101
102impl Default for AppSetting {
103 fn default() -> Self {
104 Self::EmissiveDecals(false)
105 }
106}
107
108/// The current values of the settings that the user can change.
109///
110/// This app only has one: whether newly-spawned decals are emissive.
111#[derive(Default, Resource)]
112struct AppStatus {
113 /// True if newly-spawned decals have an emissive channel (i.e. they glow),
114 /// or false otherwise.
115 emissive_decals: bool,
116}
117
118/// Half of the width and height of the plane onto which the decals are
119/// projected.
120const PLANE_HALF_SIZE: f32 = 2.0;
121/// The minimum width and height that a decal may have.
122///
123/// The actual size is determined randomly, using this value as a lower bound.
124const DECAL_MIN_SIZE: f32 = 0.5;
125/// The maximum width and height that a decal may have.
126///
127/// The actual size is determined randomly, using this value as an upper bound.
128const DECAL_MAX_SIZE: f32 = 1.5;
129
130/// How long it takes the decal to grow to its full size when animating in.
131const DECAL_ANIMATE_IN_DURATION: Duration = Duration::from_millis(300);
132/// How long a decal stays in the idle state before starting to animate out.
133const DECAL_IDLE_DURATION: Duration = Duration::from_secs(10);
134/// How long it takes the decal to shrink down to nothing when animating out.
135const DECAL_ANIMATE_OUT_DURATION: Duration = Duration::from_millis(300);
136
137/// The demo entry point.
138fn main() {
139 App::new()
140 .add_plugins((
141 DefaultPlugins
142 .set(WebAssetPlugin {
143 silence_startup_warning: true,
144 })
145 .set(WindowPlugin {
146 primary_window: Some(Window {
147 title: "Bevy Clustered Decal Maps Example".into(),
148 ..default()
149 }),
150 ..default()
151 }),
152 FeathersPlugins,
153 ))
154 .init_resource::<AppStatus>()
155 .init_resource::<AppTextures>()
156 .insert_resource(UiTheme(create_dark_theme()))
157 .add_systems(Startup, setup)
158 .add_systems(Update, draw_gizmos)
159 .add_systems(Update, spawn_decal)
160 .add_systems(Update, animate_decals)
161 .add_observer(handle_emission_type_change)
162 .add_observer(radio_self_update)
163 .insert_resource(SeededRng(ChaCha8Rng::seed_from_u64(19878367467712)))
164 .run();
165}
166
167#[derive(Resource)]
168struct SeededRng(ChaCha8Rng);
169
170/// Spawns all the objects in the scene.
171fn setup(
172 mut commands: Commands,
173 asset_server: Res<AssetServer>,
174 mut meshes: ResMut<Assets<Mesh>>,
175 mut materials: ResMut<Assets<StandardMaterial>>,
176) {
177 spawn_plane_mesh(&mut commands, &asset_server, &mut meshes, &mut materials);
178 spawn_light(&mut commands);
179 spawn_camera(&mut commands);
180 spawn_buttons(&mut commands);
181}
182
183/// Spawns the plane onto which the decals are projected.
184fn spawn_plane_mesh(
185 commands: &mut Commands,
186 asset_server: &AssetServer,
187 meshes: &mut Assets<Mesh>,
188 materials: &mut Assets<StandardMaterial>,
189) {
190 // Create a plane onto which we project decals.
191 //
192 // As the plane has a normal map, we must generate tangents for the
193 // vertices.
194 let plane_mesh = meshes.add(
195 Plane3d {
196 normal: Dir3::NEG_Z,
197 half_size: Vec2::splat(PLANE_HALF_SIZE),
198 }
199 .mesh()
200 .build()
201 .with_duplicated_vertices()
202 .with_computed_flat_normals()
203 .with_generated_tangents()
204 .unwrap(),
205 );
206
207 // Give the plane some texture.
208 //
209 // Note that, as this is a normal map, we must disable sRGB when loading.
210 let normal_map_texture = asset_server
211 .load_builder()
212 .with_settings(|settings: &mut ImageLoaderSettings| settings.is_srgb = false)
213 .load("textures/ScratchedGold-Normal.png");
214
215 // Actually spawn the plane.
216 commands.spawn((
217 Mesh3d(plane_mesh),
218 MeshMaterial3d(materials.add(StandardMaterial {
219 base_color: Color::from(CRIMSON),
220 normal_map_texture: Some(normal_map_texture),
221 ..StandardMaterial::default()
222 })),
223 Transform::IDENTITY,
224 ));
225}More examples
62fn spawn_sphere(
63 commands: &mut Commands,
64 materials: &mut Assets<StandardMaterial>,
65 asset_server: &AssetServer,
66 sphere_mesh: &Handle<Mesh>,
67) {
68 commands.spawn((
69 Mesh3d(sphere_mesh.clone()),
70 MeshMaterial3d(
71 materials.add(StandardMaterial {
72 clearcoat: 1.0,
73 clearcoat_perceptual_roughness: 0.3,
74 clearcoat_normal_texture: Some(
75 asset_server
76 .load_builder()
77 .with_settings(|settings: &mut ImageLoaderSettings| {
78 settings.is_srgb = false;
79 })
80 .load("textures/ScratchedGold-Normal.png"),
81 ),
82 metallic: 0.9,
83 perceptual_roughness: 0.1,
84 base_color: GOLD.into(),
85 ..default()
86 }),
87 ),
88 Transform::from_xyz(0.0, 0.0, 0.0).with_scale(Vec3::splat(1.25)),
89 ));
90}107fn spawn_car_paint_sphere(
108 commands: &mut Commands,
109 materials: &mut Assets<StandardMaterial>,
110 asset_server: &AssetServer,
111 sphere: &Handle<Mesh>,
112) {
113 commands
114 .spawn((
115 Mesh3d(sphere.clone()),
116 MeshMaterial3d(
117 materials.add(StandardMaterial {
118 clearcoat: 1.0,
119 clearcoat_perceptual_roughness: 0.1,
120 normal_map_texture: Some(
121 asset_server
122 .load_builder()
123 .with_settings(|settings: &mut ImageLoaderSettings| {
124 settings.is_srgb = false;
125 })
126 .load("textures/BlueNoise-Normal.png"),
127 ),
128 metallic: 0.9,
129 perceptual_roughness: 0.5,
130 base_color: BLUE.into(),
131 ..default()
132 }),
133 ),
134 Transform::from_xyz(-1.0, 1.0, 0.0).with_scale(Vec3::splat(SPHERE_SCALE)),
135 ))
136 .insert(ExampleSphere);
137}
138
139/// Spawn a semitransparent object with a clearcoat layer.
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}
161
162/// Spawns an object with both a clearcoat normal map (a scratched varnish) and
163/// a main layer normal map (the golf ball pattern).
164///
165/// This object is in glTF format, using the `KHR_materials_clearcoat`
166/// extension.
167fn spawn_golf_ball(commands: &mut Commands, asset_server: &AssetServer) {
168 commands.spawn((
169 WorldAssetRoot(
170 asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/GolfBall/GolfBall.glb")),
171 ),
172 Transform::from_xyz(1.0, 1.0, 0.0).with_scale(Vec3::splat(SPHERE_SCALE)),
173 ExampleSphere,
174 ));
175}
176
177/// Spawns an object with only a clearcoat normal map (a scratch pattern) and no
178/// main layer normal map.
179fn spawn_scratched_gold_ball(
180 commands: &mut Commands,
181 materials: &mut Assets<StandardMaterial>,
182 asset_server: &AssetServer,
183 sphere: &Handle<Mesh>,
184) {
185 commands
186 .spawn((
187 Mesh3d(sphere.clone()),
188 MeshMaterial3d(
189 materials.add(StandardMaterial {
190 clearcoat: 1.0,
191 clearcoat_perceptual_roughness: 0.3,
192 clearcoat_normal_texture: Some(
193 asset_server
194 .load_builder()
195 .with_settings(|settings: &mut ImageLoaderSettings| {
196 settings.is_srgb = false;
197 })
198 .load("textures/ScratchedGold-Normal.png"),
199 ),
200 metallic: 0.9,
201 perceptual_roughness: 0.1,
202 base_color: GOLD.into(),
203 ..default()
204 }),
205 ),
206 Transform::from_xyz(1.0, -1.0, 0.0).with_scale(Vec3::splat(SPHERE_SCALE)),
207 ))
208 .insert(ExampleSphere);
209}144fn setup_assets(mut commands: Commands, asset_server: Res<AssetServer>) {
145 let (barrier, guard) = AssetBarrier::new();
146 commands.insert_resource(OneHundredThings(std::array::from_fn(|i| {
147 let builder = asset_server.load_builder().with_guard(guard.clone());
148 match i % 5 {
149 0 => builder.load("models/GolfBall/GolfBall.glb"),
150 1 => builder.load("models/AlienCake/alien.glb"),
151 2 => builder.load("models/AlienCake/cakeBirthday.glb"),
152 3 => builder.load("models/FlightHelmet/FlightHelmet.gltf"),
153 4 => builder.load("models/torus/torus.gltf"),
154 _ => unreachable!(),
155 }
156 })));
157 let future = barrier.wait_async();
158 commands.insert_resource(barrier);
159
160 let loading_state = Arc::new(AtomicBool::new(false));
161 commands.insert_resource(AsyncLoadingState(loading_state.clone()));
162
163 // await the `AssetBarrierFuture`.
164 AsyncComputeTaskPool::get()
165 .spawn(async move {
166 future.await;
167 // Notify via `AsyncLoadingState`
168 loading_state.store(true, Ordering::Release);
169 })
170 .detach();
171}32fn setup(
33 mut commands: Commands,
34 mut meshes: ResMut<Assets<Mesh>>,
35 mut materials: ResMut<Assets<ArrayTextureMaterial>>,
36 asset_server: Res<AssetServer>,
37) {
38 // Load the texture.
39 let array_texture = asset_server
40 .load_builder()
41 .with_settings(|settings: &mut ImageLoaderSettings| {
42 settings.array_layout = Some(ImageArrayLayout::RowCount {
43 rows: TEXTURE_COUNT,
44 });
45 })
46 .load("textures/array_texture.png");
47
48 // light
49 commands.spawn((
50 DirectionalLight::default(),
51 Transform::from_xyz(3.0, 2.0, 1.0).looking_at(Vec3::ZERO, Vec3::Y),
52 ));
53
54 // camera
55 commands.spawn((
56 Camera3d::default(),
57 Transform::from_xyz(5.0, 5.0, 5.0).looking_at(Vec3::new(1.5, 0.0, 0.0), Vec3::Y),
58 ));
59
60 // Spawn some cubes using the array texture.
61 let mesh_handle = meshes.add(Cuboid::default());
62 let material_handle = materials.add(ArrayTextureMaterial { array_texture });
63 for x in -5..=5 {
64 commands.spawn((
65 Mesh3d(mesh_handle.clone()),
66 MeshMaterial3d(material_handle.clone()),
67 // Pass a different mesh tag to allow selecting different layers of
68 // the array texture in the shader.
69 MeshTag::new(x as u32 % TEXTURE_COUNT),
70 Transform::from_xyz(x as f32 + 0.5, 0.0, 0.0),
71 ));
72 }
73}26fn setup(mut commands: Commands, assets: Res<AssetServer>) {
27 // We're seeding the PRNG here to make this example deterministic for testing purposes.
28 // This isn't strictly required in practical use unless you need your app to be deterministic.
29 let mut rng = ChaCha8Rng::seed_from_u64(42);
30
31 let chunk_size = UVec2::splat(64);
32 let tile_display_size = UVec2::splat(8);
33 let tile_data: Vec<Option<TileData>> = (0..chunk_size.element_product())
34 .map(|_| rng.random_range(0..5))
35 .map(|i| {
36 if i == 0 {
37 None
38 } else {
39 Some(TileData::from_tileset_index(i - 1))
40 }
41 })
42 .collect();
43
44 commands.spawn((
45 TilemapChunk {
46 chunk_size,
47 tile_display_size,
48 tileset: assets
49 .load_builder()
50 .with_settings(|settings: &mut ImageLoaderSettings| {
51 // The tileset texture is expected to be an array of tile textures, so we tell the
52 // `ImageLoader` that our texture is composed of 4 stacked tile images.
53 settings.array_layout = Some(ImageArrayLayout::RowCount { rows: 4 });
54 })
55 .load("textures/array_texture.png"),
56 ..default()
57 },
58 TilemapChunkTileData(tile_data),
59 UpdateTimer(Timer::from_seconds(0.1, TimerMode::Repeating)),
60 ));
61
62 commands.spawn(Camera2d);
63
64 commands.insert_resource(SeededRng(rng));
65}- examples/testbed/3d.rs
- examples/3d/deferred_rendering.rs
- examples/asset/alter_sprite.rs
- examples/3d/atmosphere.rs
- examples/3d/ssr.rs
- examples/2d/tilemap_chunk_orientation.rs
- examples/ui/images/ui_texture_slice_flip_and_tile.rs
- examples/3d/scrolling_fog.rs
- examples/3d/solari_reflections.rs
- examples/asset/repeated_texture.rs
- examples/asset/asset_saving.rs
- examples/asset/asset_settings.rs
- examples/2d/mesh2d_repeated_texture.rs
- examples/asset/alter_mesh.rs
- examples/3d/parallax_mapping.rs
- examples/3d/solari.rs
Sourcepub fn reload<'a>(&self, path: impl Into<AssetPath<'a>>)
pub fn reload<'a>(&self, path: impl Into<AssetPath<'a>>)
Kicks off a reload of the asset stored at the given path. This will only reload the asset if it currently loaded.
Sourcepub fn add<A>(&self, asset: A) -> Handle<A>where
A: Asset,
pub fn add<A>(&self, asset: A) -> Handle<A>where
A: Asset,
Queues a new asset to be tracked by the AssetServer and returns a Handle to it. This can be used to track
dependencies of assets created at runtime.
After the asset has been fully loaded by the AssetServer, it will show up in the relevant Assets storage.
Examples found in repository?
115fn decompress<T: Component + From<Handle<A>>, A: Asset>(
116 mut commands: Commands,
117 asset_server: Res<AssetServer>,
118 mut compressed_assets: ResMut<Assets<GzAsset>>,
119 query: Query<(Entity, &Compressed<A>)>,
120) {
121 for (entity, Compressed { compressed, .. }) in query.iter() {
122 let Some(GzAsset { uncompressed }) = compressed_assets.remove(compressed) else {
123 continue;
124 };
125
126 let uncompressed = uncompressed.take::<A>().unwrap();
127
128 commands
129 .entity(entity)
130 .remove::<Compressed<A>>()
131 .insert(T::from(asset_server.add(uncompressed)));
132 }
133}More examples
101fn setup(mut commands: Commands, asset_server: Res<AssetServer>, app_status: Res<AppStatus>) {
102 commands.spawn((
103 Camera3d::default(),
104 ScreenSpaceTransmission::default(),
105 Transform::from_translation(CAMERA_INITIAL_POSITION).looking_at(Vec3::ZERO, Vec3::Y),
106 ));
107
108 spawn_directional_light(&mut commands);
109
110 commands.spawn((
111 WorldAssetRoot(
112 asset_server.load("models/AnisotropyBarnLamp/AnisotropyBarnLamp.gltf#Scene0"),
113 ),
114 Transform::from_xyz(0.0, 0.07, -0.13),
115 Scene::BarnLamp,
116 ));
117
118 commands.spawn((
119 Mesh3d(
120 asset_server.add(
121 Mesh::from(Sphere::new(0.1))
122 .with_generated_tangents()
123 .unwrap(),
124 ),
125 ),
126 MeshMaterial3d(asset_server.add(StandardMaterial {
127 base_color: palettes::tailwind::GRAY_300.into(),
128 anisotropy_rotation: 0.5,
129 anisotropy_strength: 1.,
130 ..default()
131 })),
132 Scene::Sphere,
133 Visibility::Hidden,
134 ));
135
136 spawn_text(&mut commands, &app_status);
137}119fn setup(mut commands: Commands, asset_server: Res<AssetServer>, app_status: Res<AppStatus>) {
120 commands.spawn((
121 Camera3d::default(),
122 Transform::from_xyz(-0.8, 0.6, -0.8).looking_at(Vec3::new(0.0, 0.35, 0.0), Vec3::Y),
123 ContactShadows::default(),
124 TemporalAntiAliasing::default(), // Contact shadows and AO benefit from TAA
125 // Everything past this point is extra to look pretty.
126 Bloom::default(),
127 Hdr,
128 Skybox {
129 brightness: 1000.0,
130 image: Some(asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2")),
131 ..default()
132 },
133 EnvironmentMapLight {
134 diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"),
135 specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
136 intensity: 1000.0,
137 ..default()
138 },
139 ScreenSpaceAmbientOcclusion::default(),
140 Msaa::Off,
141 Tonemapping::AcesFitted,
142 MotionBlur {
143 shutter_angle: 2.0, // This is really just for fun when spinning the model
144 ..default()
145 },
146 ));
147
148 let directional_light = commands
149 .spawn((
150 DirectionalLight {
151 shadow_maps_enabled: true,
152 contact_shadows_enabled: true,
153 ..default()
154 },
155 Visibility::Hidden,
156 ))
157 .id();
158
159 let point_light = commands
160 .spawn((
161 PointLight {
162 intensity: light_consts::lumens::VERY_LARGE_CINEMA_LIGHT * 0.4,
163 shadow_maps_enabled: true,
164 contact_shadows_enabled: true,
165 ..default()
166 },
167 Visibility::Visible,
168 ))
169 .id();
170
171 let spot_light = commands
172 .spawn((
173 SpotLight {
174 intensity: light_consts::lumens::VERY_LARGE_CINEMA_LIGHT * 0.4,
175 shadow_maps_enabled: true,
176 contact_shadows_enabled: true,
177 ..default()
178 },
179 Visibility::Hidden,
180 ))
181 .id();
182
183 commands
184 .spawn((
185 Transform::from_xyz(-0.8, 1.5, 1.2).looking_at(Vec3::ZERO, Vec3::Y),
186 Visibility::default(),
187 LightContainer,
188 ))
189 .add_child(directional_light)
190 .add_child(point_light)
191 .add_child(spot_light);
192
193 commands
194 .spawn((
195 WorldAssetRoot(asset_server.load(
196 GltfAssetLabel::Scene(0).from_asset("models/FlightHelmet/FlightHelmet.gltf"),
197 )),
198 Transform::from_rotation(Quat::from_rotation_y(std::f32::consts::PI)),
199 ))
200 .observe(
201 |event: On<PointerDrag>,
202 mut query: Query<&mut Transform, With<WorldAssetRoot>>,
203 mut commands: Commands,
204 mut window: Query<Entity, With<PrimaryWindow>>| {
205 for mut transform in query.iter_mut() {
206 transform.rotate_y(event.delta.x * 0.01);
207 }
208 commands
209 .entity(window.single_mut().unwrap())
210 .insert(CursorIcon::System(SystemCursorIcon::Grabbing));
211 },
212 )
213 .observe(
214 |_: On<PointerOver>,
215 mut commands: Commands,
216 mut window: Query<Entity, With<PrimaryWindow>>| {
217 commands
218 .entity(window.single_mut().unwrap())
219 .insert(CursorIcon::System(SystemCursorIcon::Grab));
220 },
221 )
222 .observe(
223 |_: On<PointerOut>,
224 mut commands: Commands,
225 mut window: Query<Entity, With<PrimaryWindow>>| {
226 commands
227 .entity(window.single_mut().unwrap())
228 .insert(CursorIcon::System(SystemCursorIcon::Default));
229 },
230 )
231 .observe(
232 |_: On<PointerDragEnd>,
233 mut commands: Commands,
234 mut window: Query<Entity, With<PrimaryWindow>>| {
235 commands
236 .entity(window.single_mut().unwrap())
237 .insert(CursorIcon::System(SystemCursorIcon::Default));
238 },
239 );
240
241 commands.spawn((
242 Mesh3d(asset_server.add(Circle::default().mesh().into())),
243 MeshMaterial3d(asset_server.add(StandardMaterial {
244 base_color: Color::srgb(0.06, 0.06, 0.06),
245 ..default()
246 })),
247 Transform::from_rotation(Quat::from_axis_angle(Vec3::X, -std::f32::consts::FRAC_PI_2)),
248 GroundPlane,
249 ));
250
251 spawn_buttons(&mut commands, &app_status);
252
253 commands.spawn((
254 Node {
255 position_type: PositionType::Absolute,
256 top: px(12.0),
257 left: px(0.0),
258 right: px(0.0),
259 justify_content: JustifyContent::Center,
260 ..default()
261 },
262 children![(
263 Text::new("Drag model to spin"),
264 TextFont {
265 font_size: FontSize::Px(18.0),
266 ..default()
267 },
268 )],
269 ));
270}Sourcepub fn add_async<A, E>(
&self,
future: impl Future<Output = Result<A, E>> + Send + 'static,
) -> Handle<A>
pub fn add_async<A, E>( &self, future: impl Future<Output = Result<A, E>> + Send + 'static, ) -> Handle<A>
Queues a new asset to be tracked by the AssetServer and returns a Handle to it. This can be used to track
dependencies of assets created at runtime.
After the asset has been fully loaded, it will show up in the relevant Assets storage.
Examples found in repository?
13fn setup(
14 mut commands: Commands,
15 asset_server: Res<AssetServer>,
16 mut materials: ResMut<Assets<StandardMaterial>>,
17 meshes: Res<Assets<Mesh>>,
18) {
19 commands.spawn((Camera3d::default(), Transform::from_xyz(0.0, 0.0, 5.0)));
20
21 commands.spawn((
22 DirectionalLight::default(),
23 Transform::default().looking_to(Dir3::new(Vec3::new(-1.0, -1.0, -1.0)).unwrap(), Dir3::Y),
24 ));
25
26 // The simplest way to generate an asset is to add it directly to the `Assets`.
27 let material_handle = materials.add(StandardMaterial::default());
28
29 commands.spawn((
30 Transform::from_xyz(-2.0, 0.0, 0.0),
31 MeshMaterial3d(material_handle.clone()),
32 // Alternatively, `add_async` creates a task that runs your async function. Once it
33 // completes, the asset is added to the `Assets`. This is "deferred" meaning that the asset
34 // may take a frame to be added after the task completes.
35 Mesh3d(asset_server.add_async(generate_mesh_async())),
36 ));
37
38 // The last way to generate assets is to reserve a handle, and then use `Assets::insert` to
39 // populate the asset later. In this example, the `generate_mesh_system` system runs to populate
40 // the mesh.
41 let mesh_handle = meshes.reserve_handle();
42 commands.insert_resource(HandleToGenerate(mesh_handle.clone()));
43 commands.spawn((
44 Transform::from_xyz(2.0, 0.0, 0.0)
45 .with_rotation(Quat::from_rotation_x(50.0f32.to_radians())),
46 Mesh3d(mesh_handle),
47 MeshMaterial3d(material_handle),
48 ));
49}Sourcepub fn load_folder<'a>(
&self,
path: impl Into<AssetPath<'a>>,
) -> Handle<LoadedFolder>
pub fn load_folder<'a>( &self, path: impl Into<AssetPath<'a>>, ) -> Handle<LoadedFolder>
Loads all assets from the specified folder recursively. The LoadedFolder asset (when it loads) will
contain handles to all assets in the folder. You can wait for all assets to load by checking the LoadedFolder’s
RecursiveDependencyLoadState.
Loading the same folder multiple times will return the same handle. If the file_watcher
feature is enabled, LoadedFolder handles will reload when a file in the folder is
removed, added or moved. This includes files in subdirectories and moving, adding,
or removing complete subdirectories.
Examples found in repository?
More examples
12fn setup(
13 mut commands: Commands,
14 asset_server: Res<AssetServer>,
15 meshes: Res<Assets<Mesh>>,
16 mut materials: ResMut<Assets<StandardMaterial>>,
17) {
18 // By default AssetServer will load assets from inside the "assets" folder.
19 // For example, the next line will load GltfAssetLabel::Primitive{mesh:0,primitive:0}.from_asset("ROOT/assets/models/cube/cube.gltf"),
20 // where "ROOT" is the directory of the Application.
21 //
22 // This can be overridden by setting [`AssetPlugin.file_path`].
23 let cube_handle = asset_server.load(
24 GltfAssetLabel::Primitive {
25 mesh: 0,
26 primitive: 0,
27 }
28 .from_asset("models/cube/cube.gltf"),
29 );
30 let sphere_handle = asset_server.load(
31 GltfAssetLabel::Primitive {
32 mesh: 0,
33 primitive: 0,
34 }
35 .from_asset("models/sphere/sphere.gltf"),
36 );
37
38 // All assets end up in their Assets<T> collection once they are done loading:
39 if let Some(sphere) = meshes.get(&sphere_handle) {
40 // You might notice that this doesn't run! This is because assets load in parallel without
41 // blocking. When an asset has loaded, it will appear in relevant Assets<T>
42 // collection.
43 info!("{:?}", sphere.primitive_topology());
44 } else {
45 info!("sphere hasn't loaded yet");
46 }
47
48 // You can load all assets in a folder like this. They will be loaded in parallel without
49 // blocking. The LoadedFolder asset holds handles to each asset in the folder. These are all
50 // dependencies of the LoadedFolder asset, meaning you can wait for the LoadedFolder asset to
51 // fire AssetEvent::LoadedWithDependencies if you want to wait for all assets in the folder
52 // to load.
53 // If you want to keep the assets in the folder alive, make sure you store the returned handle
54 // somewhere.
55 let _loaded_folder: Handle<LoadedFolder> = asset_server.load_folder("models/torus");
56
57 // If you want a handle to a specific asset in a loaded folder, the easiest way to get one is to call load.
58 // It will _not_ be loaded a second time.
59 // The LoadedFolder asset will ultimately also hold handles to the assets, but waiting for it to load
60 // and finding the right handle is more work!
61 let torus_handle = asset_server.load(
62 GltfAssetLabel::Primitive {
63 mesh: 0,
64 primitive: 0,
65 }
66 .from_asset("models/torus/torus.gltf"),
67 );
68
69 // You can also add assets directly to their Assets<T> storage:
70 let material_handle = materials.add(StandardMaterial {
71 base_color: Color::srgb(0.8, 0.7, 0.6),
72 ..default()
73 });
74
75 // torus
76 commands.spawn((
77 Mesh3d(torus_handle),
78 MeshMaterial3d(material_handle.clone()),
79 Transform::from_xyz(-3.0, 0.0, 0.0),
80 ));
81 // cube
82 commands.spawn((
83 Mesh3d(cube_handle),
84 MeshMaterial3d(material_handle.clone()),
85 Transform::from_xyz(0.0, 0.0, 0.0),
86 ));
87 // sphere
88 commands.spawn((
89 Mesh3d(sphere_handle),
90 MeshMaterial3d(material_handle),
91 Transform::from_xyz(3.0, 0.0, 0.0),
92 ));
93 // light
94 commands.spawn((PointLight::default(), Transform::from_xyz(4.0, 5.0, 4.0)));
95 // camera
96 commands.spawn((
97 Camera3d::default(),
98 Transform::from_xyz(0.0, 3.0, 10.0).looking_at(Vec3::ZERO, Vec3::Y),
99 ));
100}Sourcepub fn get_load_states(
&self,
id: impl Into<UntypedAssetId>,
) -> Option<(LoadState, DependencyLoadState, RecursiveDependencyLoadState)>
pub fn get_load_states( &self, id: impl Into<UntypedAssetId>, ) -> Option<(LoadState, DependencyLoadState, RecursiveDependencyLoadState)>
Retrieves all loads states for the given asset id.
Sourcepub fn get_load_state(&self, id: impl Into<UntypedAssetId>) -> Option<LoadState>
pub fn get_load_state(&self, id: impl Into<UntypedAssetId>) -> Option<LoadState>
Retrieves the main LoadState of a given asset id.
Note that this is “just” the root asset load state. To get the load state of
its dependencies or recursive dependencies, see AssetServer::get_dependency_load_state
and AssetServer::get_recursive_dependency_load_state respectively.
Sourcepub fn get_dependency_load_state(
&self,
id: impl Into<UntypedAssetId>,
) -> Option<DependencyLoadState>
pub fn get_dependency_load_state( &self, id: impl Into<UntypedAssetId>, ) -> Option<DependencyLoadState>
Retrieves the DependencyLoadState of a given asset id’s dependencies.
Note that this is only the load state of direct dependencies of the root asset. To get
the load state of the root asset itself or its recursive dependencies, see
AssetServer::get_load_state and AssetServer::get_recursive_dependency_load_state respectively.
Sourcepub fn get_recursive_dependency_load_state(
&self,
id: impl Into<UntypedAssetId>,
) -> Option<RecursiveDependencyLoadState>
pub fn get_recursive_dependency_load_state( &self, id: impl Into<UntypedAssetId>, ) -> Option<RecursiveDependencyLoadState>
Retrieves the main RecursiveDependencyLoadState of a given asset id’s recursive dependencies.
Note that this is only the load state of recursive dependencies of the root asset. To get
the load state of the root asset itself or its direct dependencies only, see
AssetServer::get_load_state and AssetServer::get_dependency_load_state respectively.
Examples found in repository?
197fn update_loading_data(
198 mut loading_data: ResMut<LoadingData>,
199 mut loading_state: ResMut<LoadingState>,
200 asset_server: Res<AssetServer>,
201 pipelines_ready: Res<PipelinesReady>,
202) {
203 if !loading_data.loading_assets.is_empty() || !pipelines_ready.0 {
204 // If we are still loading assets / pipelines are not fully compiled,
205 // we reset the confirmation frame count.
206 loading_data.confirmation_frames_count = 0;
207
208 loading_data.loading_assets.retain(|asset| {
209 asset_server
210 .get_recursive_dependency_load_state(asset)
211 .is_none_or(|state| !state.is_loaded())
212 });
213
214 // If there are no more assets being monitored, and pipelines
215 // are compiled, then start counting confirmation frames.
216 // Once enough confirmations have passed, everything will be
217 // considered to be fully loaded.
218 } else {
219 loading_data.confirmation_frames_count += 1;
220 if loading_data.confirmation_frames_count == loading_data.confirmation_frames_target {
221 *loading_state = LoadingState::LevelReady;
222 }
223 }
224}Sourcepub fn load_state(&self, id: impl Into<UntypedAssetId>) -> LoadState
pub fn load_state(&self, id: impl Into<UntypedAssetId>) -> LoadState
Retrieves the main LoadState of a given asset id.
This is the same as AssetServer::get_load_state except the result is unwrapped. If
the result is None, LoadState::NotLoaded is returned.
Examples found in repository?
127fn environment_map_load_finish(
128 mut commands: Commands,
129 asset_server: Res<AssetServer>,
130 environment_map: Single<&EnvironmentMapLight>,
131 label_entity: Option<Single<Entity, With<EnvironmentMapLabel>>>,
132) {
133 if asset_server
134 .load_state(&environment_map.diffuse_map)
135 .is_loaded()
136 && asset_server
137 .load_state(&environment_map.specular_map)
138 .is_loaded()
139 {
140 // Do not attempt to remove `label_entity` if it has already been removed.
141 if let Some(label_entity) = label_entity {
142 commands.entity(*label_entity).despawn();
143 }
144 }
145}More examples
148fn asset_loaded(
149 asset_server: Res<AssetServer>,
150 mut images: ResMut<Assets<Image>>,
151 mut cubemap: ResMut<Cubemap>,
152 mut skyboxes: Query<&mut Skybox>,
153) {
154 if !cubemap.is_loaded && asset_server.load_state(&cubemap.image_handle).is_loaded() {
155 info!("Swapping to {}...", CUBEMAPS[cubemap.index].0);
156 let mut image = images.get_mut(&cubemap.image_handle).unwrap();
157 // NOTE: PNGs do not have any metadata that could indicate they contain a cubemap texture,
158 // so they appear as one texture. The following code reconfigures the texture as necessary.
159 if image.texture_descriptor.array_layer_count() == 1 {
160 let layers = image.height() / image.width();
161 image
162 .reinterpret_stacked_2d_as_array(layers)
163 .expect("asset should be 2d texture and height will always be evenly divisible with the given layers");
164 image.texture_view_descriptor = Some(TextureViewDescriptor {
165 dimension: Some(TextureViewDimension::Cube),
166 ..default()
167 });
168 }
169
170 for mut skybox in &mut skyboxes {
171 skybox.image = Some(cubemap.image_handle.clone());
172 }
173
174 cubemap.is_loaded = true;
175 }
176}Sourcepub fn dependency_load_state(
&self,
id: impl Into<UntypedAssetId>,
) -> DependencyLoadState
pub fn dependency_load_state( &self, id: impl Into<UntypedAssetId>, ) -> DependencyLoadState
Retrieves the DependencyLoadState of a given asset id.
This is the same as AssetServer::get_dependency_load_state except the result is unwrapped. If
the result is None, DependencyLoadState::NotLoaded is returned.
Sourcepub fn recursive_dependency_load_state(
&self,
id: impl Into<UntypedAssetId>,
) -> RecursiveDependencyLoadState
pub fn recursive_dependency_load_state( &self, id: impl Into<UntypedAssetId>, ) -> RecursiveDependencyLoadState
Retrieves the RecursiveDependencyLoadState of a given asset id.
This is the same as AssetServer::get_recursive_dependency_load_state except the result is unwrapped. If
the result is None, RecursiveDependencyLoadState::NotLoaded is returned.
Sourcepub fn is_loaded(&self, id: impl Into<UntypedAssetId>) -> bool
pub fn is_loaded(&self, id: impl Into<UntypedAssetId>) -> bool
Convenience method that returns true if the asset has been loaded.
Sourcepub fn is_loaded_with_direct_dependencies(
&self,
id: impl Into<UntypedAssetId>,
) -> bool
pub fn is_loaded_with_direct_dependencies( &self, id: impl Into<UntypedAssetId>, ) -> bool
Convenience method that returns true if the asset and all of its direct dependencies have been loaded.
Sourcepub fn is_loaded_with_dependencies(&self, id: impl Into<UntypedAssetId>) -> bool
pub fn is_loaded_with_dependencies(&self, id: impl Into<UntypedAssetId>) -> bool
Convenience method that returns true if the asset, all of its dependencies, and all of its recursive dependencies have been loaded.
Examples found in repository?
97fn spawn_fox_asset_when_ready(
98 mut commands: Commands,
99 fox_handle: Res<Fox>,
100 asset_server: Res<AssetServer>,
101 gltfs: Res<Assets<Gltf>>,
102 mut graphs: ResMut<Assets<AnimationGraph>>,
103) {
104 if !asset_server.is_loaded_with_dependencies(&fox_handle.0) {
105 // fox is not loaded yet
106 return;
107 }
108
109 let fox = gltfs
110 .get(&fox_handle.0)
111 .expect("a loaded asset should exist in the glTF assets collection");
112
113 // Build the animation graph
114 let (graph, node_indices) = AnimationGraph::from_clips([
115 fox.named_animations["Run"].clone(),
116 fox.named_animations["Walk"].clone(),
117 fox.named_animations["Survey"].clone(),
118 ]);
119
120 // Keep our animation graph in a Resource so that it can be inserted onto
121 // the correct entity once the scene actually loads.
122 let graph_handle = graphs.add(graph);
123 commands.insert_resource(Animations {
124 animations: node_indices,
125 graph_handle,
126 });
127
128 // Fox
129 commands
130 .spawn(WorldAssetRoot(
131 fox.default_scene
132 .clone()
133 .expect("a default scene exists in this file"),
134 ))
135 .observe(setup_scene);
136}Sourcepub fn are_dependencies_loaded(
&self,
value: &impl VisitAssetDependencies,
) -> bool
pub fn are_dependencies_loaded( &self, value: &impl VisitAssetDependencies, ) -> bool
Returns true if all of values dependencies (included recursive dependencies) are loaded.
This allows querying for whether all the handles in a resource or component are loaded.
Sourcepub fn are_direct_dependencies_loaded(
&self,
value: &impl VisitAssetDependencies,
) -> bool
pub fn are_direct_dependencies_loaded( &self, value: &impl VisitAssetDependencies, ) -> bool
Returns true if all of values dependencies (excluding recursive dependencies) are loaded.
This allows querying for whether all the handles in a resource or component are loaded.
Sourcepub fn get_handle<'a, A>(
&self,
path: impl Into<AssetPath<'a>>,
) -> Option<Handle<A>>where
A: Asset,
pub fn get_handle<'a, A>(
&self,
path: impl Into<AssetPath<'a>>,
) -> Option<Handle<A>>where
A: Asset,
Returns an active handle for the given path, if the asset at the given path has already started loading, or is still “alive”.
Examples found in repository?
50fn setup(
51 mut commands: Commands,
52 rpg_sprite_handles: Res<RpgSpriteFolder>,
53 asset_server: Res<AssetServer>,
54 mut texture_atlases: ResMut<Assets<TextureAtlasLayout>>,
55 loaded_folders: Res<Assets<LoadedFolder>>,
56 mut textures: ResMut<Assets<Image>>,
57) {
58 let loaded_folder = loaded_folders.get(&rpg_sprite_handles.0).unwrap();
59
60 // Create texture atlases with different padding and sampling
61
62 let (texture_atlas_linear, linear_sources, linear_texture) = create_texture_atlas(
63 loaded_folder,
64 None,
65 Some(ImageSampler::linear()),
66 &mut textures,
67 );
68 let atlas_linear_handle = texture_atlases.add(texture_atlas_linear);
69
70 let (texture_atlas_nearest, nearest_sources, nearest_texture) = create_texture_atlas(
71 loaded_folder,
72 None,
73 Some(ImageSampler::nearest()),
74 &mut textures,
75 );
76 let atlas_nearest_handle = texture_atlases.add(texture_atlas_nearest);
77
78 let (texture_atlas_linear_padded, linear_padded_sources, linear_padded_texture) =
79 create_texture_atlas(
80 loaded_folder,
81 Some(UVec2::new(6, 6)),
82 Some(ImageSampler::linear()),
83 &mut textures,
84 );
85 let atlas_linear_padded_handle = texture_atlases.add(texture_atlas_linear_padded.clone());
86
87 let (texture_atlas_nearest_padded, nearest_padded_sources, nearest_padded_texture) =
88 create_texture_atlas(
89 loaded_folder,
90 Some(UVec2::new(6, 6)),
91 Some(ImageSampler::nearest()),
92 &mut textures,
93 );
94 let atlas_nearest_padded_handle = texture_atlases.add(texture_atlas_nearest_padded);
95
96 commands.spawn(Camera2d);
97
98 // Padded textures are to the right, unpadded to the left
99
100 // Draw unpadded texture atlas
101 commands.spawn((
102 Sprite::from_image(linear_texture.clone()),
103 Transform {
104 translation: Vec3::new(-250.0, -160.0, 0.0),
105 scale: Vec3::splat(0.5),
106 ..default()
107 },
108 ));
109
110 // Draw padded texture atlas
111 commands.spawn((
112 Sprite::from_image(linear_padded_texture.clone()),
113 Transform {
114 translation: Vec3::new(250.0, -160.0, 0.0),
115 scale: Vec3::splat(0.5),
116 ..default()
117 },
118 ));
119
120 let font = asset_server.load("fonts/FiraSans-Bold.ttf");
121
122 // Padding label text style
123 let text_style: TextFont = TextFont {
124 font: font.clone().into(),
125 font_size: FontSize::Px(42.0),
126 ..default()
127 };
128
129 // Labels to indicate padding
130
131 // No padding
132 create_label(
133 &mut commands,
134 (-250.0, 250.0, 0.0),
135 "No padding",
136 text_style.clone(),
137 );
138
139 // Padding
140 create_label(&mut commands, (250.0, 250.0, 0.0), "Padding", text_style);
141
142 // Get handle to a sprite to render
143 let vendor_handle: Handle<Image> = asset_server
144 .get_handle("textures/rpg/chars/vendor/generic-rpg-vendor.png")
145 .unwrap();
146
147 // Configuration array to render sprites through iteration
148 let configurations: [(
149 &str,
150 Handle<TextureAtlasLayout>,
151 TextureAtlasSources,
152 Handle<Image>,
153 f32,
154 ); 4] = [
155 (
156 "Linear",
157 atlas_linear_handle,
158 linear_sources,
159 linear_texture,
160 -350.0,
161 ),
162 (
163 "Nearest",
164 atlas_nearest_handle,
165 nearest_sources,
166 nearest_texture,
167 -150.0,
168 ),
169 (
170 "Linear",
171 atlas_linear_padded_handle,
172 linear_padded_sources,
173 linear_padded_texture,
174 150.0,
175 ),
176 (
177 "Nearest",
178 atlas_nearest_padded_handle,
179 nearest_padded_sources,
180 nearest_padded_texture,
181 350.0,
182 ),
183 ];
184
185 // Label text style
186 let sampling_label_style = TextFont {
187 font: font.into(),
188 font_size: FontSize::Px(25.0),
189 ..default()
190 };
191
192 let base_y = 80.0; // y position of the sprites
193
194 for (sampling, atlas_handle, atlas_sources, atlas_texture, x) in configurations {
195 // Render a sprite from the texture_atlas
196 create_sprite_from_atlas(
197 &mut commands,
198 (x, base_y, 0.0),
199 atlas_texture,
200 atlas_sources,
201 atlas_handle,
202 &vendor_handle,
203 );
204
205 // Render a label to indicate the sampling setting
206 create_label(
207 &mut commands,
208 (x, base_y + 110.0, 0.0), // Offset to y position of the sprite
209 sampling,
210 sampling_label_style.clone(),
211 );
212 }
213}Sourcepub fn get_id_handle<A>(&self, id: AssetId<A>) -> Option<Handle<A>>where
A: Asset,
pub fn get_id_handle<A>(&self, id: AssetId<A>) -> Option<Handle<A>>where
A: Asset,
Get a Handle from an AssetId.
This only returns Some if id is derived from a Handle that was
loaded through an AssetServer, otherwise it returns None.
Consider using Assets::get_strong_handle in the case the Handle
comes from Assets::add.
Sourcepub fn get_id_handle_untyped(&self, id: UntypedAssetId) -> Option<UntypedHandle>
pub fn get_id_handle_untyped(&self, id: UntypedAssetId) -> Option<UntypedHandle>
Get an UntypedHandle from an UntypedAssetId.
See AssetServer::get_id_handle for details.
Sourcepub fn is_managed(&self, id: impl Into<UntypedAssetId>) -> bool
pub fn is_managed(&self, id: impl Into<UntypedAssetId>) -> bool
Returns true if the given id corresponds to an asset that is managed by this AssetServer.
Otherwise, returns false.
Sourcepub fn get_path_id<'a>(
&self,
path: impl Into<AssetPath<'a>>,
) -> Option<UntypedAssetId>
pub fn get_path_id<'a>( &self, path: impl Into<AssetPath<'a>>, ) -> Option<UntypedAssetId>
Returns an active untyped asset id for the given path, if the asset at the given path has already started loading, or is still “alive”. Returns the first ID in the event of multiple assets being registered against a single path.
§See also
get_path_ids for all handles.
Sourcepub fn get_path_ids<'a>(
&self,
path: impl Into<AssetPath<'a>>,
) -> Vec<UntypedAssetId>
pub fn get_path_ids<'a>( &self, path: impl Into<AssetPath<'a>>, ) -> Vec<UntypedAssetId>
Returns all active untyped asset IDs for the given path, if the assets at the given path have already started loading,
or are still “alive”.
Multiple IDs will be returned in the event that a single path is used by multiple AssetLoader’s.
Sourcepub fn get_handle_untyped<'a>(
&self,
path: impl Into<AssetPath<'a>>,
) -> Option<UntypedHandle>
pub fn get_handle_untyped<'a>( &self, path: impl Into<AssetPath<'a>>, ) -> Option<UntypedHandle>
Returns an active untyped handle for the given path, if the asset at the given path has already started loading, or is still “alive”. Returns the first handle in the event of multiple assets being registered against a single path.
§See also
get_handles_untyped for all handles.
Sourcepub fn get_handles_untyped<'a>(
&self,
path: impl Into<AssetPath<'a>>,
) -> Vec<UntypedHandle>
pub fn get_handles_untyped<'a>( &self, path: impl Into<AssetPath<'a>>, ) -> Vec<UntypedHandle>
Returns all active untyped handles for the given path, if the assets at the given path have already started loading,
or are still “alive”.
Multiple handles will be returned in the event that a single path is used by multiple AssetLoader’s.
Sourcepub fn get_path_and_type_id_handle(
&self,
path: &AssetPath<'_>,
type_id: TypeId,
) -> Option<UntypedHandle>
pub fn get_path_and_type_id_handle( &self, path: &AssetPath<'_>, type_id: TypeId, ) -> Option<UntypedHandle>
Returns an active untyped handle for the given path and TypeId, if the asset at the given path has already started loading,
or is still “alive”.
Sourcepub fn get_path(&self, id: impl Into<UntypedAssetId>) -> Option<AssetPath<'_>>
pub fn get_path(&self, id: impl Into<UntypedAssetId>) -> Option<AssetPath<'_>>
Returns the path for the given id, if it has one.
Examples found in repository?
80fn name_morphs(
81 asset_server: Res<AssetServer>,
82 mut events: MessageReader<AssetEvent<Mesh>>,
83 meshes: Res<Assets<Mesh>>,
84) {
85 for event in events.read() {
86 if let AssetEvent::<Mesh>::Added { id } = event
87 && let Some(path) = asset_server.get_path(*id)
88 && let Some(mesh) = meshes.get(*id)
89 && let Some(names) = mesh.morph_target_names()
90 {
91 info!("Morph target names for {path:?}:");
92
93 for name in names {
94 info!(" {name}");
95 }
96 }
97 }
98}Sourcepub fn mode(&self) -> AssetServerMode
pub fn mode(&self) -> AssetServerMode
Returns the AssetServerMode this server is currently in.
Sourcepub fn preregister_loader<L>(&self, extensions: &[&str])where
L: AssetLoader,
pub fn preregister_loader<L>(&self, extensions: &[&str])where
L: AssetLoader,
Pre-register a loader that will later be added.
Assets loaded with matching extensions will be blocked until the real loader is added.
Sourcepub async fn wait_for_asset<A>(
&self,
handle: &Handle<A>,
) -> Result<(), WaitForAssetError>where
A: Asset,
pub async fn wait_for_asset<A>(
&self,
handle: &Handle<A>,
) -> Result<(), WaitForAssetError>where
A: Asset,
Returns a future that will suspend until the specified asset and its dependencies finish loading.
§Errors
This will return an error if the asset or any of its dependencies fail to load, or if the asset has not been queued up to be loaded.
Sourcepub async fn wait_for_asset_untyped(
&self,
handle: &UntypedHandle,
) -> Result<(), WaitForAssetError>
pub async fn wait_for_asset_untyped( &self, handle: &UntypedHandle, ) -> Result<(), WaitForAssetError>
Returns a future that will suspend until the specified asset and its dependencies finish loading.
§Errors
This will return an error if the asset or any of its dependencies fail to load, or if the asset has not been queued up to be loaded.
Sourcepub async fn wait_for_asset_id(
&self,
id: impl Into<UntypedAssetId>,
) -> Result<(), WaitForAssetError>
pub async fn wait_for_asset_id( &self, id: impl Into<UntypedAssetId>, ) -> Result<(), WaitForAssetError>
Returns a future that will suspend until the specified asset and its dependencies finish loading.
Note that since an asset ID does not count as a reference to the asset, the future returned from this method will not keep the asset alive. This may lead to the asset unexpectedly being dropped while you are waiting for it to finish loading.
When calling this method, make sure a strong handle is stored elsewhere to prevent the
asset from being dropped.
If you have access to an asset’s strong Handle, you should prefer to call
AssetServer::wait_for_asset
or wait_for_asset_untyped to ensure the asset finishes
loading.
§Errors
This will return an error if the asset or any of its dependencies fail to load, or if the asset has not been queued up to be loaded.
Sourcepub async fn write_default_loader_meta_file_for_path(
&self,
path: impl Into<AssetPath<'_>>,
) -> Result<(), WriteDefaultMetaError>
pub async fn write_default_loader_meta_file_for_path( &self, path: impl Into<AssetPath<'_>>, ) -> Result<(), WriteDefaultMetaError>
Writes the default loader meta file for the provided path.
This function only generates meta files that simply load the path directly. To generate a
meta file that will use the default asset processor for the path, see
AssetProcessor::write_default_meta_file_for_path.
Note if there is already a meta file for path, this function returns
Err(WriteDefaultMetaError::MetaAlreadyExists).
Trait Implementations§
Source§impl Clone for AssetServer
impl Clone for AssetServer
Source§fn clone(&self) -> AssetServer
fn clone(&self) -> AssetServer
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl Component for AssetServer
impl Component for AssetServer
Source§const STORAGE_TYPE: StorageType = bevy_ecs::component::StorageType::SparseSet
const STORAGE_TYPE: StorageType = bevy_ecs::component::StorageType::SparseSet
Source§type Mutability = Mutable
type Mutability = Mutable
Component<Mutability = Mutable>,
while immutable components will instead have Component<Mutability = Immutable>. Read moreSource§fn register_required_components(
_requiree: ComponentId,
required_components: &mut RequiredComponentsRegistrator<'_, '_>,
)
fn register_required_components( _requiree: ComponentId, required_components: &mut RequiredComponentsRegistrator<'_, '_>, )
Source§fn clone_behavior() -> ComponentCloneBehavior
fn clone_behavior() -> ComponentCloneBehavior
Source§fn relationship_accessor() -> Option<ComponentRelationshipAccessor<AssetServer>>
fn relationship_accessor() -> Option<ComponentRelationshipAccessor<AssetServer>>
ComponentRelationshipAccessor required for working with relationships in dynamic contexts. Read moreSource§fn on_add() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_add() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn on_insert() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_insert() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn on_discard() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_discard() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn on_remove() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_remove() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn on_despawn() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_despawn() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn map_entities<E>(_this: &mut Self, _mapper: &mut E)where
E: EntityMapper,
fn map_entities<E>(_this: &mut Self, _mapper: &mut E)where
E: EntityMapper,
EntityMapper. This is used to remap entities in contexts like scenes and entity cloning.
When deriving Component, this is populated by annotating fields containing entities with #[entities] Read moreSource§const HAS_SUMMARY_TICK: bool = false
const HAS_SUMMARY_TICK: bool = false
Source§impl Debug for AssetServer
impl Debug for AssetServer
Source§impl GetAssetServer for AssetServer
impl GetAssetServer for AssetServer
Source§fn get_asset_server(&self) -> &AssetServer
fn get_asset_server(&self) -> &AssetServer
AssetServer.Source§impl LoadFromPath for AssetServer
impl LoadFromPath for AssetServer
Source§fn load_from_path_erased(
&mut self,
type_id: TypeId,
path: AssetPath<'static>,
) -> UntypedHandle
fn load_from_path_erased( &mut self, type_id: TypeId, path: AssetPath<'static>, ) -> UntypedHandle
Source§impl LoadFromPath for &AssetServer
impl LoadFromPath for &AssetServer
Source§fn load_from_path_erased(
&mut self,
type_id: TypeId,
path: AssetPath<'static>,
) -> UntypedHandle
fn load_from_path_erased( &mut self, type_id: TypeId, path: AssetPath<'static>, ) -> UntypedHandle
impl Resource for AssetServer
Auto Trait Implementations§
impl !RefUnwindSafe for AssetServer
impl !UnwindSafe for AssetServer
impl Freeze for AssetServer
impl Send for AssetServer
impl Sync for AssetServer
impl Unpin for AssetServer
impl UnsafeUnpin for AssetServer
Blanket Implementations§
Source§impl<T, U> AsBindGroupShaderType<U> for T
impl<T, U> AsBindGroupShaderType<U> for T
Source§fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U
fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U
T ShaderType for self. When used in AsBindGroup
derives, it is safe to assume that all images in self exist.Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<C> Bundle for Cwhere
C: Component,
impl<C> Bundle for Cwhere
C: Component,
fn component_ids( components: &mut ComponentsRegistrator<'_>, ) -> impl Iterator<Item = ComponentId> + use<C>
Source§fn get_component_ids(
components: &Components,
) -> impl Iterator<Item = Option<ComponentId>>
fn get_component_ids( components: &Components, ) -> impl Iterator<Item = Option<ComponentId>>
Source§impl<C> BundleFromComponents for Cwhere
C: Component,
impl<C> BundleFromComponents for Cwhere
C: Component,
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,
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<C> DynamicBundle for Cwhere
C: Component,
impl<C> DynamicBundle for Cwhere
C: Component,
Source§unsafe fn get_components(
ptr: MovingPtr<'_, C>,
func: &mut impl FnMut(StorageType, OwningPtr<'_>),
) -> <C as DynamicBundle>::Effect
unsafe fn get_components( ptr: MovingPtr<'_, C>, func: &mut impl FnMut(StorageType, OwningPtr<'_>), ) -> <C as DynamicBundle>::Effect
Source§unsafe fn apply_effect(
_ptr: MovingPtr<'_, MaybeUninit<C>>,
_entity: &mut EntityWorldMut<'_>,
)
unsafe fn apply_effect( _ptr: MovingPtr<'_, MaybeUninit<C>>, _entity: &mut EntityWorldMut<'_>, )
Source§impl<T> ErasedBundleTemplate for T
impl<T> ErasedBundleTemplate for T
Source§unsafe fn apply(
&self,
context: &mut TemplateContext<'_, '_>,
) -> Result<(), BevyError>
unsafe fn apply( &self, context: &mut TemplateContext<'_, '_>, ) -> Result<(), BevyError>
entity. Read moreSource§fn clone_template(&self) -> Box<dyn ErasedBundleTemplate>
fn clone_template(&self) -> Box<dyn ErasedBundleTemplate>
Clone.impl<T> ErasedDestructor for Twhere
T: 'static,
Source§impl<T> ErasedTemplate for T
impl<T> ErasedTemplate for T
Source§unsafe fn apply(
&self,
context: &mut TemplateContext<'_, '_>,
bundle_writer: &mut BundleWriter<'_>,
) -> Result<(), BevyError>
unsafe fn apply( &self, context: &mut TemplateContext<'_, '_>, bundle_writer: &mut BundleWriter<'_>, ) -> Result<(), BevyError>
entity. Read moreSource§fn clone_template(&self) -> Box<dyn ErasedTemplate>
fn clone_template(&self) -> Box<dyn ErasedTemplate>
Clone.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, 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<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<C> SceneEffect for Cwhere
C: Component,
impl<C> SceneEffect for Cwhere
C: Component,
Source§fn apply(
self,
context: &mut TemplateContext<'_, '_>,
bundle_writer: &mut BundleWriter<'_>,
)
fn apply( self, context: &mut TemplateContext<'_, '_>, bundle_writer: &mut BundleWriter<'_>, )
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.