-
Notifications
You must be signed in to change notification settings - Fork 26
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #30 from boylede/add-postcard
add postcard format
- Loading branch information
Showing
6 changed files
with
190 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
use bevy::prelude::*; | ||
use bevy::reflect::TypePath; | ||
use bevy_common_assets::postcard::PostcardAssetPlugin; | ||
|
||
fn main() { | ||
App::new() | ||
.add_plugins(( | ||
DefaultPlugins, | ||
PostcardAssetPlugin::<Level>::new(&["level.postcard"]), | ||
)) | ||
.insert_resource(Msaa::Off) | ||
.init_state::<AppState>() | ||
.add_systems(Startup, setup) | ||
.add_systems(Update, spawn_level.run_if(in_state(AppState::Loading))) | ||
.run() | ||
} | ||
|
||
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { | ||
let level = LevelHandle(asset_server.load("trees.level.postcard")); | ||
commands.insert_resource(level); | ||
let tree = ImageHandle(asset_server.load("tree.png")); | ||
commands.insert_resource(tree); | ||
commands.spawn(Camera2dBundle::default()); | ||
} | ||
|
||
fn spawn_level( | ||
mut commands: Commands, | ||
level: Res<LevelHandle>, | ||
tree: Res<ImageHandle>, | ||
mut levels: ResMut<Assets<Level>>, | ||
mut state: ResMut<NextState<AppState>>, | ||
) { | ||
if let Some(level) = levels.remove(level.0.id()) { | ||
for position in level.positions { | ||
commands.spawn(SpriteBundle { | ||
transform: Transform::from_translation(position.into()), | ||
texture: tree.0.clone(), | ||
..default() | ||
}); | ||
} | ||
state.set(AppState::Level); | ||
} | ||
} | ||
|
||
#[derive(serde::Deserialize, Asset, TypePath)] | ||
struct Level { | ||
positions: Vec<[f32; 3]>, | ||
} | ||
|
||
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)] | ||
enum AppState { | ||
#[default] | ||
Loading, | ||
Level, | ||
} | ||
|
||
#[derive(Resource)] | ||
struct ImageHandle(Handle<Image>); | ||
|
||
#[derive(Resource)] | ||
struct LevelHandle(Handle<Level>); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,113 @@ | ||
use bevy::{ | ||
app::{App, Plugin}, | ||
asset::{ | ||
io::Reader, saver::AssetSaver, Asset, AssetApp, AssetLoader, AsyncReadExt, AsyncWriteExt, | ||
LoadContext, | ||
}, | ||
prelude::*, | ||
utils::{thiserror, BoxedFuture}, | ||
}; | ||
use postcard::{from_bytes, to_stdvec}; | ||
use serde::{Deserialize, Serialize}; | ||
use std::marker::PhantomData; | ||
use thiserror::Error; | ||
|
||
/// Plugin to load your asset type `A` from `Postcard` files. | ||
pub struct PostcardAssetPlugin<A> { | ||
extensions: Vec<&'static str>, | ||
_marker: PhantomData<A>, | ||
} | ||
|
||
impl<A> Plugin for PostcardAssetPlugin<A> | ||
where | ||
for<'de> A: Deserialize<'de> + Asset, | ||
{ | ||
fn build(&self, app: &mut App) { | ||
app.init_asset::<A>() | ||
.register_asset_loader(PostcardAssetLoader::<A> { | ||
extensions: self.extensions.clone(), | ||
_marker: PhantomData, | ||
}); | ||
} | ||
} | ||
|
||
impl<A> PostcardAssetPlugin<A> | ||
where | ||
for<'de> A: Deserialize<'de> + Asset, | ||
{ | ||
/// Create a new plugin that will load assets from files with the given extensions. | ||
pub fn new(extensions: &[&'static str]) -> Self { | ||
Self { | ||
extensions: extensions.to_owned(), | ||
_marker: PhantomData, | ||
} | ||
} | ||
} | ||
|
||
struct PostcardAssetLoader<A> { | ||
extensions: Vec<&'static str>, | ||
_marker: PhantomData<A>, | ||
} | ||
|
||
/// Possible errors that can be produced by [`PostcardAssetLoader`] or [`PostcardAssetSaver`] | ||
#[non_exhaustive] | ||
#[derive(Debug, Error)] | ||
pub enum PostcardAssetError { | ||
/// An [IO Error](std::io::Error) | ||
#[error("Could not read the file: {0}")] | ||
Io(#[from] std::io::Error), | ||
/// A [Postcard Error](postcard::Error) | ||
#[error("Could not parse Postcard: {0}")] | ||
PostcardError(#[from] postcard::Error), | ||
} | ||
|
||
impl<A> AssetLoader for PostcardAssetLoader<A> | ||
where | ||
for<'de> A: Deserialize<'de> + Asset, | ||
{ | ||
type Asset = A; | ||
type Settings = (); | ||
type Error = PostcardAssetError; | ||
|
||
fn load<'a>( | ||
&'a self, | ||
reader: &'a mut Reader, | ||
_settings: &'a (), | ||
_load_context: &'a mut LoadContext, | ||
) -> BoxedFuture<'a, Result<Self::Asset, Self::Error>> { | ||
Box::pin(async move { | ||
let mut bytes = Vec::new(); | ||
reader.read_to_end(&mut bytes).await?; | ||
let asset = from_bytes::<A>(&bytes)?; | ||
Ok(asset) | ||
}) | ||
} | ||
|
||
fn extensions(&self) -> &[&str] { | ||
&self.extensions | ||
} | ||
} | ||
|
||
struct PostcardAssetSaver<A> { | ||
_marker: PhantomData<A>, | ||
} | ||
|
||
impl<A: Asset + Serialize> AssetSaver for PostcardAssetSaver<A> { | ||
type Asset = A; | ||
type Settings = (); | ||
type OutputLoader = (); | ||
type Error = PostcardAssetError; | ||
|
||
fn save<'a>( | ||
&'a self, | ||
writer: &'a mut bevy::asset::io::Writer, | ||
asset: bevy::asset::saver::SavedAsset<'a, Self::Asset>, | ||
_settings: &'a Self::Settings, | ||
) -> BoxedFuture<'a, Result<<Self::OutputLoader as AssetLoader>::Settings, Self::Error>> { | ||
Box::pin(async move { | ||
let bytes = to_stdvec(&asset.get())?; | ||
writer.write_all(&bytes).await?; | ||
Ok(()) | ||
}) | ||
} | ||
} |