Struct LoadContext

Source
pub struct LoadContext<'a> { /* private fields */ }
Expand description

A context that provides access to assets in AssetLoaders, tracks dependencies, and collects asset load state.

Any asset state accessed by LoadContext will be tracked and stored for use in dependency events and asset preprocessing.

Implementations§

Source§

impl<'a> LoadContext<'a>

Source

pub fn begin_labeled_asset(&self) -> LoadContext<'_>

Begins a new labeled asset load. Use the returned LoadContext to load dependencies for the new asset and call LoadContext::finish to finalize the asset load. When finished, make sure you call LoadContext::add_labeled_asset to add the results back to the parent context. Prefer LoadContext::labeled_asset_scope when possible, which will automatically add the labeled LoadContext back to the parent context. LoadContext::begin_labeled_asset exists largely to enable parallel asset loading.

See AssetPath for more on labeled assets.

let mut handles = Vec::new();
for i in 0..2 {
    let mut labeled = load_context.begin_labeled_asset();
    handles.push(std::thread::spawn(move || {
        (i.to_string(), labeled.finish(Image::default()))
    }));
}

for handle in handles {
    let (label, loaded_asset) = handle.join().unwrap();
    load_context.add_loaded_labeled_asset(label, loaded_asset);
}
Source

pub fn labeled_asset_scope<A>( &mut self, label: String, load: impl FnOnce(&mut LoadContext<'_>) -> A, ) -> Handle<A>
where A: Asset,

Creates a new LoadContext for the given label. The load function is responsible for loading an Asset of type A. load will be called immediately and the result will be used to finalize the LoadContext, resulting in a new LoadedAsset, which is registered under the label label.

This exists to remove the need to manually call LoadContext::begin_labeled_asset and then manually register the result with LoadContext::add_labeled_asset.

See AssetPath for more on labeled assets.

Source

pub fn add_labeled_asset<A>(&mut self, label: String, asset: A) -> Handle<A>
where A: Asset,

This will add the given asset as a “labeled Asset” with the label label.

§Warning

This will not assign dependencies to the given asset. If adding an asset with dependencies generated from calls such as LoadContext::load, use LoadContext::labeled_asset_scope or LoadContext::begin_labeled_asset to generate a new LoadContext to track the dependencies for the labeled asset.

See AssetPath for more on labeled assets.

Source

pub fn add_loaded_labeled_asset<A>( &mut self, label: impl Into<CowArc<'static, str>>, loaded_asset: LoadedAsset<A>, ) -> Handle<A>
where A: Asset,

Add a LoadedAsset that is a “labeled sub asset” of the root path of this load context. This can be used in combination with LoadContext::begin_labeled_asset to parallelize sub asset loading.

See AssetPath for more on labeled assets.

Source

pub fn has_labeled_asset<'b>(&self, label: impl Into<CowArc<'b, str>>) -> bool

Returns true if an asset with the label label exists in this context.

See AssetPath for more on labeled assets.

Source

pub fn finish<A>(self, value: A) -> LoadedAsset<A>
where A: Asset,

“Finishes” this context by populating the final Asset value.

Source

pub fn path(&self) -> &Path

Gets the source path for this load context.

Examples found in repository?
examples/asset/asset_decompression.rs (line 49)
43    async fn load(
44        &self,
45        reader: &mut dyn Reader,
46        _settings: &(),
47        load_context: &mut LoadContext<'_>,
48    ) -> Result<Self::Asset, Self::Error> {
49        let compressed_path = load_context.path();
50        let file_name = compressed_path
51            .file_name()
52            .ok_or(GzAssetLoaderError::IndeterminateFilePath)?
53            .to_string_lossy();
54        let uncompressed_file_name = file_name
55            .strip_suffix(".gz")
56            .ok_or(GzAssetLoaderError::IndeterminateFilePath)?;
57        let contained_path = compressed_path.join(uncompressed_file_name);
58
59        let mut bytes_compressed = Vec::new();
60
61        reader.read_to_end(&mut bytes_compressed).await?;
62
63        let mut decoder = GzDecoder::new(bytes_compressed.as_slice());
64
65        let mut bytes_uncompressed = Vec::new();
66
67        decoder.read_to_end(&mut bytes_uncompressed)?;
68
69        // Now that we have decompressed the asset, let's pass it back to the
70        // context to continue loading
71
72        let mut reader = VecReader::new(bytes_uncompressed);
73
74        let uncompressed = load_context
75            .loader()
76            .with_unknown_type()
77            .immediate()
78            .with_reader(&mut reader)
79            .load(contained_path)
80            .await?;
81
82        Ok(GzAsset { uncompressed })
83    }
Source

pub fn asset_path(&self) -> &AssetPath<'static>

Gets the source asset path for this load context.

Source

pub async fn read_asset_bytes<'b, 'c>( &'b mut self, path: impl Into<AssetPath<'c>>, ) -> Result<Vec<u8>, ReadAssetBytesError>

Reads the asset at the given path and returns its bytes

Source

pub fn get_label_handle<'b, A>( &mut self, label: impl Into<CowArc<'b, str>>, ) -> Handle<A>
where A: Asset,

Returns a handle to an asset of type A with the label label. This LoadContext must produce an asset of the given type and the given label or the dependencies of this asset will never be considered “fully loaded”. However you can call this method before or after adding the labeled asset.

Source

pub fn loader(&mut self) -> NestedLoader<'a, '_, StaticTyped, Deferred>

Create a builder for loading nested assets in this context.

Examples found in repository?
examples/asset/processing/asset_processing.rs (line 153)
141    async fn load(
142        &self,
143        reader: &mut dyn Reader,
144        _settings: &Self::Settings,
145        load_context: &mut LoadContext<'_>,
146    ) -> Result<CoolText, Self::Error> {
147        let mut bytes = Vec::new();
148        reader.read_to_end(&mut bytes).await?;
149        let ron: CoolTextRon = ron::de::from_bytes(&bytes)?;
150        let mut base_text = ron.text;
151        for embedded in ron.embedded_dependencies {
152            let loaded = load_context
153                .loader()
154                .immediate()
155                .load::<Text>(&embedded)
156                .await?;
157            base_text.push_str(&loaded.get().0);
158        }
159        for (path, settings_override) in ron.dependencies_with_settings {
160            let loaded = load_context
161                .loader()
162                .with_settings(move |settings| {
163                    *settings = settings_override.clone();
164                })
165                .immediate()
166                .load::<Text>(&path)
167                .await?;
168            base_text.push_str(&loaded.get().0);
169        }
170        Ok(CoolText {
171            text: base_text,
172            dependencies: ron
173                .dependencies
174                .iter()
175                .map(|p| load_context.load(p))
176                .collect(),
177        })
178    }
More examples
Hide additional examples
examples/asset/asset_decompression.rs (line 75)
43    async fn load(
44        &self,
45        reader: &mut dyn Reader,
46        _settings: &(),
47        load_context: &mut LoadContext<'_>,
48    ) -> Result<Self::Asset, Self::Error> {
49        let compressed_path = load_context.path();
50        let file_name = compressed_path
51            .file_name()
52            .ok_or(GzAssetLoaderError::IndeterminateFilePath)?
53            .to_string_lossy();
54        let uncompressed_file_name = file_name
55            .strip_suffix(".gz")
56            .ok_or(GzAssetLoaderError::IndeterminateFilePath)?;
57        let contained_path = compressed_path.join(uncompressed_file_name);
58
59        let mut bytes_compressed = Vec::new();
60
61        reader.read_to_end(&mut bytes_compressed).await?;
62
63        let mut decoder = GzDecoder::new(bytes_compressed.as_slice());
64
65        let mut bytes_uncompressed = Vec::new();
66
67        decoder.read_to_end(&mut bytes_uncompressed)?;
68
69        // Now that we have decompressed the asset, let's pass it back to the
70        // context to continue loading
71
72        let mut reader = VecReader::new(bytes_uncompressed);
73
74        let uncompressed = load_context
75            .loader()
76            .with_unknown_type()
77            .immediate()
78            .with_reader(&mut reader)
79            .load(contained_path)
80            .await?;
81
82        Ok(GzAsset { uncompressed })
83    }
Source

pub fn load<'b, A>(&mut self, path: impl Into<AssetPath<'b>>) -> Handle<A>
where A: Asset,

Retrieves a handle for the asset at the given path and adds that path as a dependency of the asset. If the current context is a normal AssetServer::load, an actual asset load will be kicked off immediately, which ensures the load happens as soon as possible. “Normal loads” kicked from within a normal Bevy App will generally configure the context to kick off loads immediately. If the current context is configured to not load dependencies automatically (ex: AssetProcessor), a load will not be kicked off automatically. It is then the calling context’s responsibility to begin a load if necessary.

If you need to override asset settings, asset type, or load directly, please see LoadContext::loader.

Examples found in repository?
examples/asset/processing/asset_processing.rs (line 175)
141    async fn load(
142        &self,
143        reader: &mut dyn Reader,
144        _settings: &Self::Settings,
145        load_context: &mut LoadContext<'_>,
146    ) -> Result<CoolText, Self::Error> {
147        let mut bytes = Vec::new();
148        reader.read_to_end(&mut bytes).await?;
149        let ron: CoolTextRon = ron::de::from_bytes(&bytes)?;
150        let mut base_text = ron.text;
151        for embedded in ron.embedded_dependencies {
152            let loaded = load_context
153                .loader()
154                .immediate()
155                .load::<Text>(&embedded)
156                .await?;
157            base_text.push_str(&loaded.get().0);
158        }
159        for (path, settings_override) in ron.dependencies_with_settings {
160            let loaded = load_context
161                .loader()
162                .with_settings(move |settings| {
163                    *settings = settings_override.clone();
164                })
165                .immediate()
166                .load::<Text>(&path)
167                .await?;
168            base_text.push_str(&loaded.get().0);
169        }
170        Ok(CoolText {
171            text: base_text,
172            dependencies: ron
173                .dependencies
174                .iter()
175                .map(|p| load_context.load(p))
176                .collect(),
177        })
178    }

Auto Trait Implementations§

§

impl<'a> Freeze for LoadContext<'a>

§

impl<'a> !RefUnwindSafe for LoadContext<'a>

§

impl<'a> Send for LoadContext<'a>

§

impl<'a> Sync for LoadContext<'a>

§

impl<'a> Unpin for LoadContext<'a>

§

impl<'a> !UnwindSafe for LoadContext<'a>

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

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

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

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

impl<T> Conv for T

Source§

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

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

impl<T> Downcast<T> for T

Source§

fn downcast(&self) -> &T

Source§

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

Source§

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

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

Converts 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)

Converts &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)

Converts &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 T
where T: Any,

Source§

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

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

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

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

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

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

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

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

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

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

Source§

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

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

impl<T> FmtForward for T

Source§

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Formats each item in a sequence. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S> FromSample<S> for S

Source§

fn from_sample_(s: S) -> S

Source§

impl<T> Instrument for T

Source§

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

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

fn in_current_span(self) -> Instrumented<Self>

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

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

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

impl<T> IntoEither for T

Source§

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

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

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

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

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

Source§

fn into_sample(self) -> T

Source§

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

Source§

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

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

Initializes a with the given initializer. Read more
Source§

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

Dereferences the given pointer. Read more
Source§

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

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

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

impl<T> Tap for T

Source§

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

Immutable access to a value. Read more
Source§

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

Mutable access to a value. Read more
Source§

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Source§

fn to_sample_(self) -> U

Source§

impl<T> TryConv for T

Source§

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

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

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

Source§

type Error = Infallible

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

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

Performs the conversion.
Source§

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

Source§

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

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

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

Performs the conversion.
Source§

impl<T> Upcast<T> for T

Source§

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

Source§

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

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

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

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

fn with_current_subscriber(self) -> WithDispatch<Self>

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

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

Source§

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

Source§

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

Source§

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

Source§

impl<T> WasmNotSendSync for T

Source§

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