Skip to content

Commit

Permalink
extract modules and types
Browse files Browse the repository at this point in the history
  • Loading branch information
B-Reif committed Jul 17, 2021
1 parent 9243693 commit 84dee73
Show file tree
Hide file tree
Showing 12 changed files with 442 additions and 107 deletions.
6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
[package]
name = "bevy_proto_aseprite"
name = "bevy_asefile"
version = "0.1.0"
authors = ["alpine_alpaca <[email protected]>"]
authors = ["alpine_alpaca <[email protected]>", "B-Reif"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
bevy = "0.5"
asefile = "0.2"
asefile = { git = "https://github.com/B-Reif/asefile", branch = "main" }
anyhow = "1.0"

[dev-dependencies]
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Basic tooling to use Aseprite animations with Bevy.
Basic tooling to use Aseprite animations with Bevy. Forked from bevy_proto_aseprite.

# Example

Expand Down
2 changes: 1 addition & 1 deletion examples/simple/ids.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use bevy_proto_aseprite::anim_id::AnimationId;
use bevy_asefile::anim_id::AnimationId;
use strum::{EnumIter, EnumProperty, IntoEnumIterator};

#[derive(Debug, Clone, PartialEq, Eq, Hash, EnumProperty, EnumIter)]
Expand Down
4 changes: 2 additions & 2 deletions examples/simple/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::path::Path;

use bevy::{input::system::exit_on_esc_system, prelude::*};
use bevy_proto_aseprite::{
use bevy_asefile::{
self,
anim_id::{AnimationById, AnimationId},
animate::{self, Animation, AnimationInfo},
Expand Down Expand Up @@ -65,7 +65,7 @@ pub fn spawn_sprites(mut commands: Commands, anim_ids: Res<AnimationById<AnimId>
//commands.spawn_bundle(OrthographicCameraBundle::new_2d());
commands.spawn_bundle({
let mut b = OrthographicCameraBundle::new_2d();
b.orthographic_projection.scale = 1.0 / 3.0; // scale to 3x
b.orthographic_projection.scale = 1.0 / 3.0; // scale to 3x
b
});

Expand Down
29 changes: 29 additions & 0 deletions src/animation.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
use asefile::{AsepriteFile, Tag};
use std::path::PathBuf;

#[derive(Debug)]
pub(crate) struct Animation {
pub(crate) file: PathBuf,
pub(crate) tag: Option<String>,
pub(crate) sprites: Vec<usize>,
}
impl Animation {
pub(crate) fn new(name: &PathBuf, ase: &AsepriteFile, sprite_offset: usize) -> Self {
Self {
file: name.clone(),
tag: None,
sprites: (0..ase.num_frames())
.map(|f| sprite_offset + f as usize)
.collect(),
}
}
pub(crate) fn from_tag(name: &PathBuf, sprite_offset: usize, tag: &Tag) -> Self {
Animation {
file: name.clone(),
tag: Some(tag.name().to_owned()),
sprites: (tag.from_frame()..tag.to_frame() + 1)
.map(|f| sprite_offset + f as usize)
.collect(),
}
}
}
50 changes: 50 additions & 0 deletions src/ase.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
use std::{fmt, path::PathBuf};

use asefile::AsepriteFile;
use bevy::utils::HashMap;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct AseId(u32);
impl AseId {
pub fn new(inner: u32) -> Self {
Self(inner)
}
pub fn inner(&self) -> &u32 {
&self.0
}
}
impl fmt::Display for AseId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "AseId({})", self.0)
}
}

pub(crate) struct AseKeyed {
pub(crate) id: AseId,
pub(crate) path: PathBuf,
pub(crate) file: AsepriteFile,
}

pub(crate) struct AsesById(HashMap<AseId, AseKeyed>);
impl AsesById {
pub(crate) fn inner(&self) -> &HashMap<AseId, AseKeyed> {
&self.0
}
pub fn iter(&self) -> std::collections::hash_map::Iter<'_, AseId, AseKeyed> {
self.0.iter()
}
}
impl From<Vec<(PathBuf, AsepriteFile)>> for AsesById {
fn from(vec: Vec<(PathBuf, AsepriteFile)>) -> Self {
Self(
vec.into_iter()
.enumerate()
.map(|(idx, (path, file))| {
let id = AseId::new(idx as u32);
let value = AseKeyed { id, path, file };
(id, value)
})
.collect(),
)
}
}
111 changes: 11 additions & 100 deletions src/aseloader.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::animate::{Animation, AnimationInfo, Frame, Sprite};
use asefile::{AsepriteFile, Tag};
use crate::processing;
use asefile::{AsepriteFile, Tag, Tileset, TilesetId};
use bevy::{
asset::{AssetLoader, BoxedFuture, LoadState, LoadedAsset},
prelude::*,
Expand Down Expand Up @@ -69,7 +70,7 @@ impl AssetLoader for AsepriteAssetLoader {
// #[derive(Debug)]
pub struct AsepriteLoader {
todo_handles: Vec<Handle<AsepriteAsset>>,
done: Arc<Mutex<Vec<ProcessedAse<Texture>>>>,
done: Arc<Mutex<Vec<processing::AseAssets<Texture>>>>,
in_progress: Arc<AtomicU32>,
}

Expand Down Expand Up @@ -128,8 +129,7 @@ impl AsepriteLoader {

let output = self.done.clone();
let task = pool.spawn(async move {
let processed = create_animations(inputs);
// println!("Batch finished");
let processed = processing::AseAssets::<Texture>::new(inputs);
let mut out = output.lock().unwrap();
out.push(processed);
});
Expand Down Expand Up @@ -160,12 +160,8 @@ impl AsepriteLoader {
finish_animations(r, animations, anim_info, textures, atlases);
self.in_progress.fetch_sub(1, Ordering::SeqCst);
}

// println!("Need to process results: {}", results.len());
}

// fn create_textures(&mut self, pool: &AsyncComputeTaskPool) {}

pub fn check_pending(&self) -> u32 {
self.in_progress.load(Ordering::SeqCst)
}
Expand All @@ -175,32 +171,8 @@ impl AsepriteLoader {
}
}

fn create_animations(ases: Vec<(PathBuf, AsepriteFile)>) -> ProcessedAse<Texture> {
let mut tmp_sprites: Vec<TempSpriteInfo<Texture>> = Vec::new();
let mut tmp_anim_info: Vec<TempAnimInfo> = Vec::new();
for (name, ase) in &ases {
debug!("Processing Aseprite file: {}", name.display());
let sprite_offset = tmp_sprites.len();

for frame in 0..ase.num_frames() {
tmp_sprites.push(TempSpriteInfo::<Texture>::new(ase, frame));
}

tmp_anim_info.push(TempAnimInfo::new(name, ase, sprite_offset));

for tag_id in 0..ase.num_tags() {
let tag = ase.tag(tag_id);
tmp_anim_info.push(TempAnimInfo::from_tag(name, sprite_offset, tag));
}
}
ProcessedAse {
sprites: tmp_sprites,
anims: tmp_anim_info,
}
}

fn finish_animations(
input: ProcessedAse<Texture>,
input: processing::AseAssets<Texture>,
animations: &mut Assets<Animation>,
anim_info: &mut AnimationInfo,
textures: &mut Assets<Texture>,
Expand All @@ -209,20 +181,20 @@ fn finish_animations(
let mut texture_atlas_builder = TextureAtlasBuilder::default();

let start = Instant::now();
let tmp_sprites: Vec<TempSpriteInfo<Handle<Texture>>> = input
let tmp_sprites: Vec<processing::Sprite<Handle<Texture>>> = input
.sprites
.into_iter()
.map(
|TempSpriteInfo {
|processing::Sprite {
frame,
tex,
texture: tex,
duration,
}| {
let tex_handle = textures.add(tex);
let texture = textures.get(&tex_handle).unwrap();
texture_atlas_builder.add_texture(tex_handle.clone_weak(), texture);
TempSpriteInfo {
tex: tex_handle,
processing::Sprite {
texture: tex_handle,
frame,
duration,
}
Expand All @@ -240,7 +212,7 @@ fn finish_animations(
let mut frames = Vec::with_capacity(tmp_anim.sprites.len());
for sprite_id in tmp_anim.sprites {
let tmp_sprite = &tmp_sprites[sprite_id];
let atlas_index = atlas.get_texture_index(&tmp_sprite.tex).unwrap();
let atlas_index = atlas.get_texture_index(&tmp_sprite.texture).unwrap();
frames.push(Frame {
sprite: Sprite {
atlas: atlas_handle.clone(),
Expand All @@ -254,67 +226,6 @@ fn finish_animations(
}
}

struct ProcessedAse<T> {
sprites: Vec<TempSpriteInfo<T>>,
anims: Vec<TempAnimInfo>,
}

// #[derive(Debug)]
struct TempSpriteInfo<T> {
// file: PathBuf,
frame: u32,
tex: T,
duration: u32,
}
impl TempSpriteInfo<Texture> {
fn new(ase: &AsepriteFile, frame: u32) -> Self {
let img = ase.frame(frame).image();
let size = Extent3d {
width: ase.width() as u32,
height: ase.height() as u32,
depth: 1,
};
let texture = Texture::new_fill(
size,
TextureDimension::D2,
img.as_raw(),
TextureFormat::Rgba8UnormSrgb,
);
Self {
frame,
tex: texture,
duration: ase.frame(frame).duration(),
}
}
}

#[derive(Debug)]
struct TempAnimInfo {
file: PathBuf,
tag: Option<String>,
sprites: Vec<usize>,
}
impl TempAnimInfo {
fn new(name: &PathBuf, ase: &AsepriteFile, sprite_offset: usize) -> Self {
Self {
file: name.clone(),
tag: None,
sprites: (0..ase.num_frames())
.map(|f| sprite_offset + f as usize)
.collect(),
}
}
fn from_tag(name: &PathBuf, sprite_offset: usize, tag: &Tag) -> Self {
TempAnimInfo {
file: name.clone(),
tag: Some(tag.name().to_owned()),
sprites: (tag.from_frame()..tag.to_frame() + 1)
.map(|f| sprite_offset + f as usize)
.collect(),
}
}
}

pub fn aseprite_loader(
mut loader: ResMut<AsepriteLoader>,
task_pool: ResMut<AsyncComputeTaskPool>,
Expand Down
Empty file added src/framedata.rs
Empty file.
7 changes: 7 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
pub mod anim_id;
pub mod animate;
mod animation;
mod ase;
pub mod aseloader;
mod processing;
mod sprite;
mod tileset;
pub mod timer;

#[cfg(test)]
Expand All @@ -10,3 +15,5 @@ mod tests {
assert_eq!(2 + 2, 4);
}
}

pub use tileset::{TileSize, Tileset, TilesetId};
Loading

0 comments on commit 84dee73

Please sign in to comment.