Skip to content

Commit c1bb4b2

Browse files
bushrat011899joseph-gioandriyDev
authored
[Adopted] Add a method for asynchronously waiting for an asset to load (#15913)
# Objective Currently, is is very painful to wait for an asset to load from the context of an `async` task. While bevy's `AssetServer` is asynchronous at its core, the public API is mainly focused on being used from synchronous contexts such as bevy systems. Currently, the best way of waiting for an asset handle to finish loading is to have a system that runs every frame, and either listens for `AssetEvents` or manually polls the asset server. While this is an acceptable interface for bevy systems, it is extremely awkward to do this in a way that integrates well with the `async` task system. At my work we had to create our own (inefficient) abstraction that encapsulated the boilerplate of checking an asset's load status and waking up a task when it's done. ## Solution Add the method `AssetServer::wait_for_asset`, which returns a future that suspends until the asset associated with a given `Handle` either finishes loading or fails to load. ## Testing - CI ## Notes This is an adoption of #14431, the above description is directly from that original PR. --------- Co-authored-by: Joseph <21144246+JoJoJet@users.noreply.github.com> Co-authored-by: andriyDev <andriydzikh@gmail.com>
1 parent 63a3a98 commit c1bb4b2

File tree

2 files changed

+153
-4
lines changed

2 files changed

+153
-4
lines changed

crates/bevy_asset/src/server/info.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use alloc::sync::{Arc, Weak};
88
use bevy_ecs::world::World;
99
use bevy_tasks::Task;
1010
use bevy_utils::{tracing::warn, Entry, HashMap, HashSet, TypeIdMap};
11-
use core::any::TypeId;
11+
use core::{any::TypeId, task::Waker};
1212
use crossbeam_channel::Sender;
1313
use derive_more::derive::{Display, Error, From};
1414
use either::Either;
@@ -36,6 +36,8 @@ pub(crate) struct AssetInfo {
3636
/// The number of handle drops to skip for this asset.
3737
/// See usage (and comments) in `get_or_create_path_handle` for context.
3838
handle_drops_to_skip: usize,
39+
/// List of tasks waiting for this asset to complete loading
40+
pub(crate) waiting_tasks: Vec<Waker>,
3941
}
4042

4143
impl AssetInfo {
@@ -54,6 +56,7 @@ impl AssetInfo {
5456
dependants_waiting_on_load: HashSet::default(),
5557
dependants_waiting_on_recursive_dep_load: HashSet::default(),
5658
handle_drops_to_skip: 0,
59+
waiting_tasks: Vec::new(),
5760
}
5861
}
5962
}
@@ -616,6 +619,9 @@ impl AssetInfos {
616619
info.load_state = LoadState::Failed(error.clone());
617620
info.dep_load_state = DependencyLoadState::Failed(error.clone());
618621
info.rec_dep_load_state = RecursiveDependencyLoadState::Failed(error.clone());
622+
for waker in info.waiting_tasks.drain(..) {
623+
waker.wake();
624+
}
619625
(
620626
core::mem::take(&mut info.dependants_waiting_on_load),
621627
core::mem::take(&mut info.dependants_waiting_on_recursive_dep_load),

crates/bevy_asset/src/server/mod.rs

Lines changed: 146 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ use bevy_utils::{
2525
tracing::{error, info},
2626
HashSet,
2727
};
28-
use core::{any::TypeId, future::Future, panic::AssertUnwindSafe};
28+
use core::{any::TypeId, future::Future, panic::AssertUnwindSafe, task::Poll};
2929
use crossbeam_channel::{Receiver, Sender};
3030
use derive_more::derive::{Display, Error, From};
3131
use either::Either;
@@ -413,7 +413,7 @@ impl AssetServer {
413413
&self,
414414
handle: UntypedHandle,
415415
path: AssetPath<'static>,
416-
mut infos: RwLockWriteGuard<AssetInfos>,
416+
infos: RwLockWriteGuard<AssetInfos>,
417417
guard: G,
418418
) {
419419
// drop the lock on `AssetInfos` before spawning a task that may block on it in single-threaded
@@ -433,7 +433,10 @@ impl AssetServer {
433433
});
434434

435435
#[cfg(not(any(target_arch = "wasm32", not(feature = "multi_threaded"))))]
436-
infos.pending_tasks.insert(handle.id(), task);
436+
{
437+
let mut infos = infos;
438+
infos.pending_tasks.insert(handle.id(), task);
439+
}
437440

438441
#[cfg(any(target_arch = "wasm32", not(feature = "multi_threaded")))]
439442
task.detach();
@@ -1336,6 +1339,132 @@ impl AssetServer {
13361339
})
13371340
})
13381341
}
1342+
1343+
/// Returns a future that will suspend until the specified asset and its dependencies finish
1344+
/// loading.
1345+
///
1346+
/// # Errors
1347+
///
1348+
/// This will return an error if the asset or any of its dependencies fail to load,
1349+
/// or if the asset has not been queued up to be loaded.
1350+
pub async fn wait_for_asset<A: Asset>(
1351+
&self,
1352+
// NOTE: We take a reference to a handle so we know it will outlive the future,
1353+
// which ensures the handle won't be dropped while waiting for the asset.
1354+
handle: &Handle<A>,
1355+
) -> Result<(), WaitForAssetError> {
1356+
self.wait_for_asset_id(handle.id().untyped()).await
1357+
}
1358+
1359+
/// Returns a future that will suspend until the specified asset and its dependencies finish
1360+
/// loading.
1361+
///
1362+
/// # Errors
1363+
///
1364+
/// This will return an error if the asset or any of its dependencies fail to load,
1365+
/// or if the asset has not been queued up to be loaded.
1366+
pub async fn wait_for_asset_untyped(
1367+
&self,
1368+
// NOTE: We take a reference to a handle so we know it will outlive the future,
1369+
// which ensures the handle won't be dropped while waiting for the asset.
1370+
handle: &UntypedHandle,
1371+
) -> Result<(), WaitForAssetError> {
1372+
self.wait_for_asset_id(handle.id()).await
1373+
}
1374+
1375+
/// Returns a future that will suspend until the specified asset and its dependencies finish
1376+
/// loading.
1377+
///
1378+
/// Note that since an asset ID does not count as a reference to the asset,
1379+
/// the future returned from this method will *not* keep the asset alive.
1380+
/// This may lead to the asset unexpectedly being dropped while you are waiting for it to
1381+
/// finish loading.
1382+
///
1383+
/// When calling this method, make sure a strong handle is stored elsewhere to prevent the
1384+
/// asset from being dropped.
1385+
/// If you have access to an asset's strong [`Handle`], you should prefer to call
1386+
/// [`AssetServer::wait_for_asset`]
1387+
/// or [`wait_for_assest_untyped`](Self::wait_for_asset_untyped) to ensure the asset finishes
1388+
/// loading.
1389+
///
1390+
/// # Errors
1391+
///
1392+
/// This will return an error if the asset or any of its dependencies fail to load,
1393+
/// or if the asset has not been queued up to be loaded.
1394+
pub async fn wait_for_asset_id(
1395+
&self,
1396+
id: impl Into<UntypedAssetId>,
1397+
) -> Result<(), WaitForAssetError> {
1398+
let id = id.into();
1399+
core::future::poll_fn(move |cx| self.wait_for_asset_id_poll_fn(cx, id)).await
1400+
}
1401+
1402+
/// Used by [`wait_for_asset_id`](AssetServer::wait_for_asset_id) in [`poll_fn`](core::future::poll_fn).
1403+
fn wait_for_asset_id_poll_fn(
1404+
&self,
1405+
cx: &mut core::task::Context<'_>,
1406+
id: UntypedAssetId,
1407+
) -> Poll<Result<(), WaitForAssetError>> {
1408+
let infos = self.data.infos.read();
1409+
1410+
let Some(info) = infos.get(id) else {
1411+
return Poll::Ready(Err(WaitForAssetError::NotLoaded));
1412+
};
1413+
1414+
match (&info.load_state, &info.rec_dep_load_state) {
1415+
(LoadState::Loaded, RecursiveDependencyLoadState::Loaded) => Poll::Ready(Ok(())),
1416+
// Return an error immediately if the asset is not in the process of loading
1417+
(LoadState::NotLoaded, _) => Poll::Ready(Err(WaitForAssetError::NotLoaded)),
1418+
// If the asset is loading, leave our waker behind
1419+
(LoadState::Loading, _)
1420+
| (_, RecursiveDependencyLoadState::Loading)
1421+
| (LoadState::Loaded, RecursiveDependencyLoadState::NotLoaded) => {
1422+
// Check if our waker is already there
1423+
let has_waker = info
1424+
.waiting_tasks
1425+
.iter()
1426+
.any(|waker| waker.will_wake(cx.waker()));
1427+
1428+
if has_waker {
1429+
return Poll::Pending;
1430+
}
1431+
1432+
let mut infos = {
1433+
// Must drop read-only guard to acquire write guard
1434+
drop(infos);
1435+
self.data.infos.write()
1436+
};
1437+
1438+
let Some(info) = infos.get_mut(id) else {
1439+
return Poll::Ready(Err(WaitForAssetError::NotLoaded));
1440+
};
1441+
1442+
// If the load state changed while reacquiring the lock, immediately
1443+
// reawaken the task
1444+
let is_loading = matches!(
1445+
(&info.load_state, &info.rec_dep_load_state),
1446+
(LoadState::Loading, _)
1447+
| (_, RecursiveDependencyLoadState::Loading)
1448+
| (LoadState::Loaded, RecursiveDependencyLoadState::NotLoaded)
1449+
);
1450+
1451+
if !is_loading {
1452+
cx.waker().wake_by_ref();
1453+
} else {
1454+
// Leave our waker behind
1455+
info.waiting_tasks.push(cx.waker().clone());
1456+
}
1457+
1458+
Poll::Pending
1459+
}
1460+
(LoadState::Failed(error), _) => {
1461+
Poll::Ready(Err(WaitForAssetError::Failed(error.clone())))
1462+
}
1463+
(_, RecursiveDependencyLoadState::Failed(error)) => {
1464+
Poll::Ready(Err(WaitForAssetError::DependencyFailed(error.clone())))
1465+
}
1466+
}
1467+
}
13391468
}
13401469

13411470
/// A system that manages internal [`AssetServer`] events, such as finalizing asset loads.
@@ -1359,6 +1488,11 @@ pub fn handle_internal_asset_events(world: &mut World) {
13591488
.get(&id.type_id())
13601489
.expect("Asset event sender should exist");
13611490
sender(world, id);
1491+
if let Some(info) = infos.get_mut(id) {
1492+
for waker in info.waiting_tasks.drain(..) {
1493+
waker.wake();
1494+
}
1495+
}
13621496
}
13631497
InternalAssetEvent::Failed { id, path, error } => {
13641498
infos.process_asset_fail(id, error.clone());
@@ -1710,3 +1844,12 @@ impl core::fmt::Debug for AssetServer {
17101844
/// This is appended to asset sources when loading a [`LoadedUntypedAsset`]. This provides a unique
17111845
/// source for a given [`AssetPath`].
17121846
const UNTYPED_SOURCE_SUFFIX: &str = "--untyped";
1847+
1848+
/// An error when attempting to wait asynchronously for an [`Asset`] to load.
1849+
#[derive(Error, Debug, Clone, Display)]
1850+
pub enum WaitForAssetError {
1851+
#[display("tried to wait for an asset that is not being loaded")]
1852+
NotLoaded,
1853+
Failed(Arc<AssetLoadError>),
1854+
DependencyFailed(Arc<AssetLoadError>),
1855+
}

0 commit comments

Comments
 (0)