bevy/examples/asset/custom_asset.rs
Arthur Brussee ac49dce4ca
Use async-fn in traits rather than BoxedFuture (#12550)
# Objective

Simplify implementing some asset traits without Box::pin(async move{})
shenanigans.
Fixes (in part) https://github.com/bevyengine/bevy/issues/11308

## Solution
Use async-fn in traits when possible in all traits. Traits with return
position impl trait are not object safe however, and as AssetReader and
AssetWriter are both used with dynamic dispatch, you need a Boxed
version of these futures anyway.

In the future, Rust is [adding
](https://blog.rust-lang.org/2023/12/21/async-fn-rpit-in-traits.html)proc
macros to generate these traits automatically, and at some point in the
future dyn traits should 'just work'. Until then.... this seemed liked
the right approach given more ErasedXXX already exist, but, no clue if
there's plans here! Especially since these are public now, it's a bit of
an unfortunate API, and means this is a breaking change.

In theory this saves some performance when these traits are used with
static dispatch, but, seems like most code paths go through dynamic
dispatch, which boxes anyway.

I also suspect a bunch of the lifetime annotations on these function
could be simplified now as the BoxedFuture was often the only thing
returned which needed a lifetime annotation, but I'm not touching that
for now as traits + lifetimes can be so tricky.

This is a revival of
[pull/11362](https://github.com/bevyengine/bevy/pull/11362) after a
spectacular merge f*ckup, with updates to the latest Bevy. Just to recap
some discussion:
- Overall this seems like a win for code quality, especially when
implementing these traits, but a loss for having to deal with ErasedXXX
variants.
- `ConditionalSend` was the preferred name for the trait that might be
Send, to deal with wasm platforms.
- When reviewing be sure to disable whitespace difference, as that's 95%
of the PR.


## Changelog
- AssetReader, AssetWriter, AssetLoader, AssetSaver and Process now use
async-fn in traits rather than boxed futures.

## Migration Guide
- Custom implementations of AssetReader, AssetWriter, AssetLoader,
AssetSaver and Process should switch to async fn rather than returning a
bevy_utils::BoxedFuture.
- Simultaniously, to use dynamic dispatch on these traits you should
instead use dyn ErasedXXX.
2024-03-18 17:56:57 +00:00

156 lines
4 KiB
Rust

//! Implements loader for a custom asset type.
use bevy::{
asset::{io::Reader, ron, AssetLoader, AsyncReadExt, LoadContext},
prelude::*,
reflect::TypePath,
};
use serde::Deserialize;
use thiserror::Error;
#[derive(Asset, TypePath, Debug, Deserialize)]
struct CustomAsset {
#[allow(dead_code)]
value: i32,
}
#[derive(Default)]
struct CustomAssetLoader;
/// Possible errors that can be produced by [`CustomAssetLoader`]
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum CustomAssetLoaderError {
/// An [IO](std::io) Error
#[error("Could not load asset: {0}")]
Io(#[from] std::io::Error),
/// A [RON](ron) Error
#[error("Could not parse RON: {0}")]
RonSpannedError(#[from] ron::error::SpannedError),
}
impl AssetLoader for CustomAssetLoader {
type Asset = CustomAsset;
type Settings = ();
type Error = CustomAssetLoaderError;
async fn load<'a>(
&'a self,
reader: &'a mut Reader<'_>,
_settings: &'a (),
_load_context: &'a mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let custom_asset = ron::de::from_bytes::<CustomAsset>(&bytes)?;
Ok(custom_asset)
}
fn extensions(&self) -> &[&str] {
&["custom"]
}
}
#[derive(Asset, TypePath, Debug)]
struct Blob {
bytes: Vec<u8>,
}
#[derive(Default)]
struct BlobAssetLoader;
/// Possible errors that can be produced by [`CustomAssetLoader`]
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum BlobAssetLoaderError {
/// An [IO](std::io) Error
#[error("Could not load file: {0}")]
Io(#[from] std::io::Error),
}
impl AssetLoader for BlobAssetLoader {
type Asset = Blob;
type Settings = ();
type Error = BlobAssetLoaderError;
async fn load<'a>(
&'a self,
reader: &'a mut Reader<'_>,
_settings: &'a (),
_load_context: &'a mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
info!("Loading Blob...");
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
Ok(Blob { bytes })
}
}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.init_resource::<State>()
.init_asset::<CustomAsset>()
.init_asset::<Blob>()
.init_asset_loader::<CustomAssetLoader>()
.init_asset_loader::<BlobAssetLoader>()
.add_systems(Startup, setup)
.add_systems(Update, print_on_load)
.run();
}
#[derive(Resource, Default)]
struct State {
handle: Handle<CustomAsset>,
other_handle: Handle<CustomAsset>,
blob: Handle<Blob>,
printed: bool,
}
fn setup(mut state: ResMut<State>, asset_server: Res<AssetServer>) {
// Recommended way to load an asset
state.handle = asset_server.load("data/asset.custom");
// File extensions are optional, but are recommended for project management and last-resort inference
state.other_handle = asset_server.load("data/asset_no_extension");
// Will use BlobAssetLoader instead of CustomAssetLoader thanks to type inference
state.blob = asset_server.load("data/asset.custom");
}
fn print_on_load(
mut state: ResMut<State>,
custom_assets: Res<Assets<CustomAsset>>,
blob_assets: Res<Assets<Blob>>,
) {
let custom_asset = custom_assets.get(&state.handle);
let other_custom_asset = custom_assets.get(&state.other_handle);
let blob = blob_assets.get(&state.blob);
// Can't print results if the assets aren't ready
if state.printed {
return;
}
if custom_asset.is_none() {
info!("Custom Asset Not Ready");
return;
}
if other_custom_asset.is_none() {
info!("Other Custom Asset Not Ready");
return;
}
if blob.is_none() {
info!("Blob Not Ready");
return;
}
info!("Custom asset loaded: {:?}", custom_asset.unwrap());
info!("Custom asset loaded: {:?}", other_custom_asset.unwrap());
info!("Blob Size: {:?} Bytes", blob.unwrap().bytes.len());
// Once printed, we won't print again
state.printed = true;
}