Skip to content
This repository has been archived by the owner on Sep 26, 2023. It is now read-only.

Commit

Permalink
AssetManager + PackagedScene (beginning)
Browse files Browse the repository at this point in the history
  • Loading branch information
konceptosociala committed Jun 5, 2023
1 parent ece2670 commit 5ee6246
Show file tree
Hide file tree
Showing 17 changed files with 497 additions and 166 deletions.
33 changes: 33 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ serde = { version = "1.0.152", features = ["derive"] }
typetag = "0.2.8"
ron = "0.8.0"
lz4 = "1.24.0"
tar = "0.4.38"

# Misc
parking_lot = { version = "0.12.1", features = ["serde"] }
Expand Down
Binary file added assets.pkg
Binary file not shown.
5 changes: 5 additions & 0 deletions assets/my_scene.ron
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
Scene(
assets: AssetManager(
audio: AudioManager(
sounds: [],
cast_count: 128,
listener_count: 8,
),
textures: [],
materials: [],
),
Expand Down
11 changes: 5 additions & 6 deletions examples/audio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ fn main() {

fn create_audio(
mut asset_manager: Write<AssetManager>,
mut audio_manager: Write<AudioManager>,
mut cmd: Write<CommandBuffer>,
) -> DesperoResult<()> {
let mut sound = Sound::new_from_file("assets/birds.mp3")?;
let cast = audio_manager.new_cast(AudioSceneId::Main);

let cast = asset_manager.audio.new_cast();
sound.set_cast(&cast);
audio_manager.play(sound);
let handle = asset_manager.audio.push_sound(sound);

asset_manager.audio.play(handle)?;

let texture_id = asset_manager.create_texture("assets/uv.jpg", Filter::Nearest);
let mesh = Mesh::load_obj("assets/model.obj").swap_remove(0);
Expand All @@ -41,8 +41,7 @@ fn create_audio(
.is_active(true)
.build(),
AudioListener::new(
&mut audio_manager,
AudioSceneId::Main,
&mut asset_manager.audio,
),
Transform::from_translation(Vector3::new(0.0, 0.0, 5.0)),
));
Expand Down
64 changes: 4 additions & 60 deletions src/assets/asset_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,44 +7,14 @@ use parking_lot::{MappedMutexGuard, Mutex, MutexGuard};
#[cfg(feature = "render")]
use ash::vk;

use crate::{audio::{sound::Sound}, prelude::DesperoResult};
use super::AssetHandle;
use crate::audio::AudioManager;
#[cfg(feature = "render")]
use crate::render::*;

#[derive(Default, Copy, Clone, Debug, Hash, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssetHandle(usize);

impl AssetHandle {
pub fn new() -> Self {
AssetHandle::default()
}

pub fn from_index(index: usize) -> Self {
AssetHandle(index)
}

pub fn invalid() -> Self {
AssetHandle(usize::MAX)
}

pub fn unwrap(&self) -> usize {
self.0
}

pub fn append(&mut self, count: usize) {
self.0 += count;
}
}

impl From<AssetHandle> for u32 {
fn from(value: AssetHandle) -> Self {
value.unwrap() as u32
}
}

#[derive(Default, Debug, Serialize, Deserialize)]
pub struct AssetManager {
pub sounds: Vec<Sound>,
pub audio: AudioManager,
#[cfg(feature = "render")]
pub textures: Vec<Texture>,
#[cfg(feature = "render")]
Expand All @@ -54,40 +24,14 @@ pub struct AssetManager {
impl AssetManager {
pub fn new() -> Self {
AssetManager::default()
}

pub fn create_sound(
&mut self,
path: &'static str,
) -> DesperoResult<AssetHandle> {
let index = self.sounds.len();
self.sounds.push(Sound::new_from_file(path)?);

Ok(AssetHandle(index))
}

pub fn get_sound(&self, handle: AssetHandle) -> Option<&Sound> {
self.sounds.get(handle.0)
}

pub fn get_sound_mut(&mut self, handle: AssetHandle) -> Option<&mut Sound> {
self.sounds.get_mut(handle.0)
}

pub fn append(&mut self, other: Self) {
self.sounds.extend(other.sounds);
#[cfg(feature = "render")]{
self.textures.extend(other.textures);
self.materials.extend(other.materials);
}
}

pub fn cleanup(
&mut self,
#[cfg(feature = "render")]
renderer: &mut Renderer,
){
self.sounds.clear();
self.audio.cleanup();

#[cfg(feature = "render")]{
for texture in &mut self.textures {
Expand Down
46 changes: 46 additions & 0 deletions src/assets/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,49 @@ pub use scene::*;
pub use ser_component::*;
pub use settings::*;
pub use world_serializer::*;

use serde::{Serialize, Deserialize};

#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub enum AssetLoadType {
#[default]
Resource,
Path(String),
}

impl<T: ToString> From<T> for AssetLoadType {
fn from(value: T) -> Self {
AssetLoadType::Path(value.to_string())
}
}

#[derive(Default, Copy, Clone, Debug, Hash, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssetHandle(usize);

impl AssetHandle {
pub fn new() -> Self {
AssetHandle::default()
}

pub fn from_index(index: usize) -> Self {
AssetHandle(index)
}

pub fn invalid() -> Self {
AssetHandle(usize::MAX)
}

pub fn unwrap(&self) -> usize {
self.0
}

pub fn append(&mut self, count: usize) {
self.0 += count;
}
}

impl From<AssetHandle> for u32 {
fn from(value: AssetHandle) -> Self {
value.unwrap() as u32
}
}
76 changes: 62 additions & 14 deletions src/assets/scene.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::path::Path;
use std::fs::read_to_string;
use std::sync::Arc;
use std::fs::File;
use tar::EntryType;
use ron::ser::{Serializer, PrettyConfig};

use serde::{
Expand Down Expand Up @@ -39,6 +40,58 @@ impl Scene {
)?)
}

/// Load scene with assets from compressed `.lvl` package.
/// It is `.tar.lz4` package which can be created manually or with
/// [Metio Editor](https://konceptosociala.eu.org/softvaro/metio).
///
/// It has the following structure:
///
/// ```text
/// my_awesome_scene.lvl/
/// ├─ scene.ron
/// ├─ textures/
/// │ ├─ texture1.jpg
/// │ ├─ texture2.png
/// ├─ sounds/
/// │ ├─ sound1.mp3
/// ```
pub fn load_packaged<P: AsRef<Path>>(path: P) -> DesperoResult<Self> {
// TODO: Packaged scene
//
let mut asset_manager = AssetManager::new();

let package = File::open("assets.pkg")?;
let decoded = lz4::Decoder::new(package)?;
let mut archive = tar::Archive::new(decoded);

for file in archive.entries().unwrap() {
let file = file.unwrap();
let header = file.header();
match header.entry_type() {
EntryType::Regular => {
if header.path().unwrap() == Path::new("manager.ron") {
asset_manager = ron::de::from_reader(file)?;
}
},
EntryType::Directory => {
// if `sounds`:
//
//

// if `textures`:
// for texture in asset_manager.textures {
// let reader = BufReader::new(file);
// let image = image::load(reader, ImageFormat::from_path(path));
// texture.generate_from(image);
// }
//
},
_ => {},
}
}
Ok(Self::new())
}

pub fn save<P: AsRef<std::path::Path>>(&self, path: P) -> DesperoResult<()> {
let buf = File::create(path)?;
let mut ser = Serializer::new(buf, Some(
Expand All @@ -58,43 +111,38 @@ pub trait SpawnSceneExt {

impl SpawnSceneExt for CommandBuffer {
fn spawn_scene(&mut self, scene: Scene, asset_manager: &mut AssetManager) {
self.write(|world| {
world.clear();
});

for entity in scene.entities {
let mut entity_builder = EntityBuilder::new();

for component in entity.components {
component.add_into(&mut entity_builder);
}

#[cfg(feature = "render")]
if let Some(ref mut handle) = &mut entity_builder.get_mut::<&mut AssetHandle>() {
handle.append(asset_manager.materials.len())
}

self.spawn(entity_builder.build());
}

asset_manager.append(scene.assets);
*asset_manager = scene.assets;
}
}

impl SpawnSceneExt for World {
fn spawn_scene(&mut self, scene: Scene, asset_manager: &mut AssetManager) {
self.clear();

for entity in scene.entities {
let mut entity_builder = EntityBuilder::new();

for component in entity.components {
component.add_into(&mut entity_builder);
}

#[cfg(feature = "render")]
if let Some(ref mut handle) = &mut entity_builder.get_mut::<&mut AssetHandle>() {
handle.append(asset_manager.materials.len())
// TODO: Append textures
}

self.spawn(entity_builder.build());
}

asset_manager.append(scene.assets);
*asset_manager = scene.assets;
}
}
}
5 changes: 2 additions & 3 deletions src/audio/cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use kira::tween::Tween;
use crate::error::DesperoResult;
use crate::audio::{
error::AudioError,
AudioManager, AudioSceneId,
AudioManager,
};
use crate::math::transform::Transform;

Expand All @@ -15,9 +15,8 @@ pub struct AudioCast {
impl AudioCast {
pub fn new(
audio_manager: &mut AudioManager,
scene_id: AudioSceneId,
) -> Self {
audio_manager.new_cast(scene_id)
audio_manager.new_cast()
}

pub(crate) fn set_transform(&mut self, t: &Transform) -> DesperoResult<()> {
Expand Down
Loading

0 comments on commit 5ee6246

Please sign in to comment.