bevy/examples/asset/custom_asset_reader.rs
Emerson Coskey 7d40e3ec87
Migrate bevy_sprite to required components (#15489)
# Objective

Continue migration of bevy APIs to required components, following
guidance of https://hackmd.io/@bevy/required_components/

## Solution

- Make `Sprite` require `Transform` and `Visibility` and
`SyncToRenderWorld`
- move image and texture atlas handles into `Sprite`
- deprecate `SpriteBundle`
- remove engine uses of `SpriteBundle`

## Testing

ran cargo tests on bevy_sprite and tested several sprite examples.

---

## Migration Guide

Replace all uses of `SpriteBundle` with `Sprite`. There are several new
convenience constructors: `Sprite::from_image`,
`Sprite::from_atlas_image`, `Sprite::from_color`.

WARNING: use of `Handle<Image>` and `TextureAtlas` as components on
sprite entities will NO LONGER WORK. Use the fields on `Sprite` instead.
I would have removed the `Component` impls from `TextureAtlas` and
`Handle<Image>` except it is still used within ui. We should fix this
moving forward with the migration.
2024-10-09 16:17:26 +00:00

65 lines
2 KiB
Rust

//! Implements a custom asset io loader.
//! An [`AssetReader`] is what the asset server uses to read the raw bytes of assets.
//! It does not know anything about the asset formats, only how to talk to the underlying storage.
use bevy::{
asset::io::{
AssetReader, AssetReaderError, AssetSource, AssetSourceId, ErasedAssetReader, PathStream,
Reader,
},
prelude::*,
};
use std::path::Path;
/// A custom asset reader implementation that wraps a given asset reader implementation
struct CustomAssetReader(Box<dyn ErasedAssetReader>);
impl AssetReader for CustomAssetReader {
async fn read<'a>(&'a self, path: &'a Path) -> Result<impl Reader + 'a, AssetReaderError> {
info!("Reading {:?}", path);
self.0.read(path).await
}
async fn read_meta<'a>(&'a self, path: &'a Path) -> Result<impl Reader + 'a, AssetReaderError> {
self.0.read_meta(path).await
}
async fn read_directory<'a>(
&'a self,
path: &'a Path,
) -> Result<Box<PathStream>, AssetReaderError> {
self.0.read_directory(path).await
}
async fn is_directory<'a>(&'a self, path: &'a Path) -> Result<bool, AssetReaderError> {
self.0.is_directory(path).await
}
}
/// A plugins that registers our new asset reader
struct CustomAssetReaderPlugin;
impl Plugin for CustomAssetReaderPlugin {
fn build(&self, app: &mut App) {
app.register_asset_source(
AssetSourceId::Default,
AssetSource::build().with_reader(|| {
Box::new(CustomAssetReader(
// This is the default reader for the current platform
AssetSource::get_default_reader("assets".to_string())(),
))
}),
);
}
}
fn main() {
App::new()
.add_plugins((CustomAssetReaderPlugin, DefaultPlugins))
.add_systems(Startup, setup)
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
commands.spawn(Sprite::from_image(asset_server.load("branding/icon.png")));
}