Skip to content

Commit

Permalink
Allow AssetServer::load to acquire a guard item. (#13051)
Browse files Browse the repository at this point in the history
# Objective

Supercedes #12881 . Added a simple implementation that allows the user
to react to multiple asset loads both synchronously and asynchronously.

## Solution

Added `load_acquire`, that holds an item and drops it when loading is
finished or failed.

When used synchronously 

Hold an `Arc<()>`, check for `Arc::strong_count() == 1` when all loading
completed.

When used asynchronously 

Hold a `SemaphoreGuard`, await on `acquire_all` for completion.

This implementation has more freedom than the original in my opinion.

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Zachary Harrold <zac@harrold.com.au>
  • Loading branch information
3 people authored May 23, 2024
1 parent 4dbfdcf commit 1d950e6
Show file tree
Hide file tree
Showing 5 changed files with 368 additions and 4 deletions.
13 changes: 13 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,7 @@ futures-lite = "2.0.1"
crossbeam-channel = "0.5.0"
argh = "0.1.12"
thiserror = "1.0"
event-listener = "5.3.0"

[[example]]
name = "hello_world"
Expand Down Expand Up @@ -1413,6 +1414,18 @@ description = "How to configure the texture to repeat instead of the default cla
category = "Assets"
wasm = true

# Assets
[[example]]
name = "multi_asset_sync"
path = "examples/asset/multi_asset_sync.rs"
doc-scrape-examples = true

[package.metadata.example.multi_asset_sync]
name = "Mult-asset synchronization"
description = "Demonstrates how to wait for multiple assets to be loaded."
category = "Assets"
wasm = true

# Async Tasks
[[example]]
name = "async_compute"
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_asset/src/loader_builders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ impl<'ctx, 'builder> NestedLoader<'ctx, 'builder> {
let handle = if self.load_context.should_load_dependencies {
self.load_context
.asset_server
.load_with_meta_transform(path, self.meta_transform)
.load_with_meta_transform(path, self.meta_transform, ())
} else {
self.load_context
.asset_server
Expand Down
51 changes: 48 additions & 3 deletions crates/bevy_asset/src/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,31 @@ impl AssetServer {
/// 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`.
#[must_use = "not using the returned strong handle may result in the unexpected release of the asset"]
pub fn load<'a, A: Asset>(&self, path: impl Into<AssetPath<'a>>) -> Handle<A> {
self.load_with_meta_transform(path, None)
self.load_with_meta_transform(path, None, ())
}

/// Begins loading an [`Asset`] of type `A` stored at `path` while holding a guard item.
/// The guard item is dropped when either the asset is loaded or loading has failed.
///
/// This function returns a "strong" [`Handle`]. When the [`Asset`] is loaded (and enters [`LoadState::Loaded`]), it will be added to the
/// associated [`Assets`] resource.
///
/// The guard item should notify the caller in its [`Drop`] implementation. See example `multi_asset_sync`.
/// Synchronously this can be a [`Arc<AtomicU32>`] that decrements its counter, asynchronously this can be a `Barrier`.
/// This function only guarantees the asset referenced by the [`Handle`] is loaded. If your asset is separated into
/// multiple files, sub-assets referenced by the main asset might still be loading, depend on the implementation of the [`AssetLoader`].
///
/// Additionally, 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`.
#[must_use = "not using the returned strong handle may result in the unexpected release of the asset"]
pub fn load_acquire<'a, A: Asset, G: Send + Sync + 'static>(
&self,
path: impl Into<AssetPath<'a>>,
guard: G,
) -> Handle<A> {
self.load_with_meta_transform(path, None, guard)
}

/// Begins loading an [`Asset`] of type `A` stored at `path`. The given `settings` function will override the asset's
Expand All @@ -282,13 +306,33 @@ impl AssetServer {
path: impl Into<AssetPath<'a>>,
settings: impl Fn(&mut S) + Send + Sync + 'static,
) -> Handle<A> {
self.load_with_meta_transform(path, Some(loader_settings_meta_transform(settings)))
self.load_with_meta_transform(path, Some(loader_settings_meta_transform(settings)), ())
}

/// Begins loading an [`Asset`] of type `A` stored at `path` while holding a guard item.
/// The guard item is dropped when either the asset is loaded or loading has failed.
///
/// This function only guarantees the asset referenced by the [`Handle`] is loaded. If your asset is separated into
/// multiple files, sub-assets referenced by the main asset might still be loading, depend on the implementation of the [`AssetLoader`].
///
/// The given `settings` function will override the asset's
/// [`AssetLoader`] settings. The type `S` _must_ match the configured [`AssetLoader::Settings`] or `settings` changes
/// will be ignored and an error will be printed to the log.
#[must_use = "not using the returned strong handle may result in the unexpected release of the asset"]
pub fn load_acquire_with_settings<'a, A: Asset, S: Settings, G: Send + Sync + 'static>(
&self,
path: impl Into<AssetPath<'a>>,
settings: impl Fn(&mut S) + Send + Sync + 'static,
guard: G,
) -> Handle<A> {
self.load_with_meta_transform(path, Some(loader_settings_meta_transform(settings)), guard)
}

pub(crate) fn load_with_meta_transform<'a, A: Asset>(
pub(crate) fn load_with_meta_transform<'a, A: Asset, G: Send + Sync + 'static>(
&self,
path: impl Into<AssetPath<'a>>,
meta_transform: Option<MetaTransform>,
guard: G,
) -> Handle<A> {
let path = path.into().into_owned();
let (handle, should_load) = self.data.infos.write().get_or_create_path_handle::<A>(
Expand All @@ -305,6 +349,7 @@ impl AssetServer {
if let Err(err) = server.load_internal(owned_handle, path, false, None).await {
error!("{}", err);
}
drop(guard);
})
.detach();
}
Expand Down
1 change: 1 addition & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ Example | Description
[Embedded Asset](../examples/asset/embedded_asset.rs) | Embed an asset in the application binary and load it
[Extra asset source](../examples/asset/extra_source.rs) | Load an asset from a non-standard asset source
[Hot Reloading of Assets](../examples/asset/hot_asset_reloading.rs) | Demonstrates automatic reloading of assets when modified on disk
[Mult-asset synchronization](../examples/asset/multi_asset_sync.rs) | Demonstrates how to wait for multiple assets to be loaded.
[Repeated texture configuration](../examples/asset/repeated_texture.rs) | How to configure the texture to repeat instead of the default clamp to edges

## Async Tasks
Expand Down
Loading

0 comments on commit 1d950e6

Please sign in to comment.