docs/bevy/examples/asset/custom_asset_reader.rs 2.1 K · 65 lines · raw · history

1 //! Implements a custom asset io loader.
2 //! An [`AssetReader`] is what the asset server uses to read the raw bytes of assets.
3 //! It does not know anything about the asset formats, only how to talk to the underlying storage.
4
5 use bevy::{
6 asset::io::{
7 AssetReader, AssetReaderError, AssetSource, AssetSourceBuilder, AssetSourceId,
8 ErasedAssetReader, PathStream, Reader,
9 },
10 prelude::*,
11 };
12 use std::path::Path;
13
14 /// A custom asset reader implementation that wraps a given asset reader implementation
15 struct CustomAssetReader(Box<dyn ErasedAssetReader>);
16
17 impl AssetReader for CustomAssetReader {
18 async fn read<'a>(&'a self, path: &'a Path) -> Result<impl Reader + 'a, AssetReaderError> {
19 info!("Reading {}", path.display());
20 self.0.read(path).await
21 }
22 async fn read_meta<'a>(&'a self, path: &'a Path) -> Result<impl Reader + 'a, AssetReaderError> {
23 self.0.read_meta(path).await
24 }
25
26 async fn read_directory<'a>(
27 &'a self,
28 path: &'a Path,
29 ) -> Result<Box<PathStream>, AssetReaderError> {
30 self.0.read_directory(path).await
31 }
32
33 async fn is_directory<'a>(&'a self, path: &'a Path) -> Result<bool, AssetReaderError> {
34 self.0.is_directory(path).await
35 }
36 }
37
38 /// A plugins that registers our new asset reader
39 struct CustomAssetReaderPlugin;
40
41 impl Plugin for CustomAssetReaderPlugin {
42 fn build(&self, app: &mut App) {
43 app.register_asset_source(
44 AssetSourceId::Default,
45 AssetSourceBuilder::new(|| {
46 Box::new(CustomAssetReader(
47 // This is the default reader for the current platform
48 AssetSource::get_default_reader("assets".to_string())(),
49 ))
50 }),
51 );
52 }
53 }
54
55 fn main() {
56 App::new()
57 .add_plugins((CustomAssetReaderPlugin, DefaultPlugins))
58 .add_systems(Startup, setup)
59 .run();
60 }
61
62 fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
63 commands.spawn(Camera2d);
64 commands.spawn(Sprite::from_image(asset_server.load("branding/icon.png")));
65 }