remove poison err & Segment Asset impl, cleanup

Former-commit-id: a2bf1ed8400da824c18ceb33a02160ecaf7d43fa
This commit is contained in:
Imbris 2019-04-27 22:12:30 -04:00
parent 1d5020634d
commit 990b42a6b0
7 changed files with 44 additions and 51 deletions

View File

@ -6,15 +6,13 @@ use std::{
collections::HashMap, collections::HashMap,
fs::File, fs::File,
io::Read, io::Read,
sync::{Arc, PoisonError, RwLock}, sync::{Arc, RwLock},
}; };
use crate::figure::Segment;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum Error { pub enum Error {
InvalidType, InvalidType,
NotFound, NotFound,
Poison,
} }
impl From<Arc<dyn Any + 'static + Sync + Send>> for Error { impl From<Arc<dyn Any + 'static + Sync + Send>> for Error {
@ -29,12 +27,6 @@ impl From<std::io::Error> for Error {
} }
} }
impl<T> From<PoisonError<T>> for Error {
fn from(_err: PoisonError<T>) -> Self {
Error::Poison
}
}
lazy_static! { lazy_static! {
static ref ASSETS: RwLock<HashMap<String, Arc<dyn Any + 'static + Sync + Send>>> = static ref ASSETS: RwLock<HashMap<String, Arc<dyn Any + 'static + Sync + Send>>> =
RwLock::new(HashMap::new()); RwLock::new(HashMap::new());
@ -50,7 +42,7 @@ lazy_static! {
// TODO: consider assets that we only need in one place or that don't need to be kept in memory? // TODO: consider assets that we only need in one place or that don't need to be kept in memory?
pub fn load<A: Asset + 'static>(specifier: &str) -> Result<Arc<A>, Error> { pub fn load<A: Asset + 'static>(specifier: &str) -> Result<Arc<A>, Error> {
Ok(ASSETS Ok(ASSETS
.write()? .write().unwrap()
.entry(specifier.to_string()) .entry(specifier.to_string())
.or_insert(Arc::new(A::load(specifier)?)) .or_insert(Arc::new(A::load(specifier)?))
.clone() .clone()
@ -64,7 +56,9 @@ pub trait Asset: Send + Sync + Sized {
impl Asset for DynamicImage { impl Asset for DynamicImage {
fn load(specifier: &str) -> Result<Self, Error> { fn load(specifier: &str) -> Result<Self, Error> {
Ok(image::load_from_memory(load_from_path(specifier)?.as_slice()).unwrap()) Ok(image::load_from_memory(
load_from_path(specifier)?.as_slice()
).unwrap())
} }
} }
@ -74,22 +68,16 @@ impl Asset for DotVoxData {
} }
} }
impl Asset for Segment {
fn load(specifier: &str) -> Result<Self, Error> {
Ok(Segment::from(dot_vox::load_bytes(load_from_path(specifier)?.as_slice()).unwrap()))
}
}
// TODO: System to load file from specifiers (eg "core.ui.backgrounds.city") // TODO: System to load file from specifiers (eg "core.ui.backgrounds.city")
fn try_load_from_path(name: &str) -> Option<File> { fn try_load_from_path(name: &str) -> Option<File> {
let basepaths = [ let basepaths = [
[env!("CARGO_MANIFEST_DIR"), "/../assets"].concat(),
// if it's stupid and it works.., // if it's stupid and it works..,
"assets".to_string(), "assets".to_string(),
"../../assets".to_string(), "../../assets".to_string(),
"../assets".to_string(), /* optimizations */ "../assets".to_string(), /* optimizations */
[env!("CARGO_MANIFEST_DIR"), "/assets"].concat(), [env!("CARGO_MANIFEST_DIR"), "/assets"].concat(),
[env!("CARGO_MANIFEST_DIR"), "/../../assets"].concat(), [env!("CARGO_MANIFEST_DIR"), "/../../assets"].concat(),
[env!("CARGO_MANIFEST_DIR"), "/../assets"].concat(),
"../../../assets".to_string(), "../../../assets".to_string(),
[env!("CARGO_MANIFEST_DIR"), "/../../../assets"].concat(), [env!("CARGO_MANIFEST_DIR"), "/../../../assets"].concat(),
]; ];
@ -97,11 +85,11 @@ fn try_load_from_path(name: &str) -> Option<File> {
let filename = [bp, name].concat(); let filename = [bp, name].concat();
match File::open(&filename) { match File::open(&filename) {
Ok(f) => { Ok(f) => {
debug!("loading {} succedeed", filename); debug!("Loading {} successful", filename);
return Some(f); return Some(f);
}, },
Err(e) => { Err(e) => {
debug!("loading {} did not work with error: {}", filename, e); debug!("Loading {} failed: {}", filename, e);
} }
}; };
}; };
@ -112,14 +100,10 @@ pub fn load_from_path(name: &str) -> Result<Vec<u8>, Error> {
match try_load_from_path(name) { match try_load_from_path(name) {
Some(mut f) => { Some(mut f) => {
let mut content: Vec<u8> = vec!(); let mut content: Vec<u8> = vec!();
f.read_to_end(&mut content); f.read_to_end(&mut content)?;
info!("loaded asset successful: {}", name);
Ok(content) Ok(content)
}, },
None => { None => Err(Error::NotFound),
warn!("Loading asset failed, wanted to load {} but could not load it, check debug log!", name);
Err(Error::NotFound)
}
} }
} }

View File

@ -18,8 +18,8 @@ use self::cell::Cell;
/// Figures are used to represent things like characters, NPCs, mobs, etc. /// Figures are used to represent things like characters, NPCs, mobs, etc.
pub type Segment = Dyna<Cell, ()>; pub type Segment = Dyna<Cell, ()>;
impl From<DotVoxData> for Segment { impl From<&DotVoxData> for Segment {
fn from(dot_vox_data: DotVoxData) -> Self { fn from(dot_vox_data: &DotVoxData) -> Self {
if let Some(model) = dot_vox_data.models.get(0) { if let Some(model) = dot_vox_data.models.get(0) {
let palette = dot_vox_data let palette = dot_vox_data
.palette .palette

View File

@ -207,7 +207,7 @@ widget_ids! {
} }
image_ids! { image_ids! {
pub(self) struct<common::figure::Segment> Voxs { struct<dot_vox::DotVoxData> Voxs {
// Bag // Bag
bag_contents: "/voxygen/element/frames/bag.vox", bag_contents: "/voxygen/element/frames/bag.vox",
inv_grid: "/voxygen/element/frames/inv_grid.vox", inv_grid: "/voxygen/element/frames/inv_grid.vox",

View File

@ -5,8 +5,18 @@ use crate::{
}; };
use common::{ use common::{
assets, assets,
comp::character::{Belt, Character, Chest, Foot, Gender, Hand, Head, Pants, Race, Weapon}, comp::character::{
figure::Segment, Character,
Race,
Gender,
Head,
Chest,
Belt,
Pants,
Hand,
Foot,
Weapon,
}
}; };
use conrod_core::{ use conrod_core::{
color, color,
@ -235,14 +245,14 @@ impl Imgs {
let load_img = |filename, ui: &mut Ui| { let load_img = |filename, ui: &mut Ui| {
let fullpath: String = ["/voxygen/", filename].concat(); let fullpath: String = ["/voxygen/", filename].concat();
let image = assets::load::<image::DynamicImage>(fullpath.as_str()) let image = assets::load::<image::DynamicImage>(fullpath.as_str())
.expect("Error loading file"); .unwrap();
ui.new_graphic(image.into()) ui.new_graphic(image.into())
}; };
let load_vox = |filename, ui: &mut Ui| { let load_vox = |filename, ui: &mut Ui| {
let fullpath: String = ["/voxygen/", filename].concat(); let fullpath: String = ["/voxygen/", filename].concat();
let segment = assets::load::<common::figure::Segment>(fullpath.as_str()) let dot_vox = assets::load::<dot_vox::DotVoxData>(fullpath.as_str())
.expect("Error loading file"); .unwrao();
ui.new_graphic(segment.into()) ui.new_graphic(dot_vox.into())
}; };
Imgs { Imgs {
v_logo: load_vox("element/v_logo.vox", ui), v_logo: load_vox("element/v_logo.vox", ui),

View File

@ -1,18 +1,16 @@
use crate::{ use crate::{
render::Renderer, render::Renderer,
ui::{self, ScaleMode, Ui}, ui::{self, ScaleMode, Ui},
window::Window,
GlobalState, DEFAULT_PUBLIC_SERVER, GlobalState, DEFAULT_PUBLIC_SERVER,
}; };
use common::{ use common::{
assets, assets,
figure::Segment,
}; };
use conrod_core::{ use conrod_core::{
color, color,
color::TRANSPARENT, color::TRANSPARENT,
image::Id as ImgId, image::Id as ImgId,
position::{Dimension, Relative}, position::Relative,
text::font::Id as FontId, text::font::Id as FontId,
widget::{text_box::Event as TextBoxEvent, Button, Image, List, Rectangle, Text, TextBox}, widget::{text_box::Event as TextBoxEvent, Button, Image, List, Rectangle, Text, TextBox},
widget_ids, Borderable, Color, Colorable, Labelable, Positionable, Sizeable, Widget, widget_ids, Borderable, Color, Colorable, Labelable, Positionable, Sizeable, Widget,
@ -70,14 +68,14 @@ impl Imgs {
let load_img = |filename, ui: &mut Ui| { let load_img = |filename, ui: &mut Ui| {
let fullpath: String = ["/voxygen/", filename].concat(); let fullpath: String = ["/voxygen/", filename].concat();
let image = assets::load::<image::DynamicImage>(fullpath.as_str()) let image = assets::load::<image::DynamicImage>(fullpath.as_str())
.expect("Error loading file"); .unwrap();
ui.new_graphic(image.into()) ui.new_graphic(image.into())
}; };
let load_vox = |filename, ui: &mut Ui| { let load_vox = |filename, ui: &mut Ui| {
let fullpath: String = ["/voxygen/", filename].concat(); let fullpath: String = ["/voxygen/", filename].concat();
let segment = assets::load::<common::figure::Segment>(fullpath.as_str()) let dot_vox = assets::load::<dot_vox::DotVoxData>(fullpath.as_str())
.expect("Error loading file"); .unwrap();
ui.new_graphic(segment.into()) ui.new_graphic(dot_vox.into())
}; };
Imgs { Imgs {
bg: load_img("background/bg_main.png", ui), bg: load_img("background/bg_main.png", ui),

View File

@ -98,10 +98,11 @@ impl FigureCache {
.retain(|_, (_, last_used)| *last_used + 60 > tick); .retain(|_, (_, last_used)| *last_used + 60 > tick);
} }
fn load_mesh(filename: &'static str, position: Vec3<f32>) -> Mesh<FigurePipeline> { fn load_mesh(filename: &str, position: Vec3<f32>) -> Mesh<FigurePipeline> {
let fullpath: String = ["/voxygen/voxel/", filename].concat(); let fullpath: String = ["/voxygen/voxel/", filename].concat();
assets::load::<Segment>(fullpath.as_str()) Segment::from(
.expect("Error loading file") assets::load::<dot_vox::DotVoxData>(fullpath.as_str()).unwrap().as_ref()
)
.generate_mesh(position) .generate_mesh(position)
} }

View File

@ -1,13 +1,13 @@
use std::sync::Arc; use std::sync::Arc;
use common::figure::Segment;
use fnv::FnvHashMap; use fnv::FnvHashMap;
use guillotiere::{size2, Allocation, AtlasAllocator}; use guillotiere::{size2, Allocation, AtlasAllocator};
use image::DynamicImage; use image::DynamicImage;
use dot_vox::DotVoxData;
use vek::*; use vek::*;
pub enum Graphic { pub enum Graphic {
Image(Arc<DynamicImage>), Image(Arc<DynamicImage>),
Voxel(Arc<Segment>), Voxel(Arc<DotVoxData>),
Blank, Blank,
} }
@ -16,8 +16,8 @@ impl From<Arc<DynamicImage>> for Graphic {
Graphic::Image(image) Graphic::Image(image)
} }
} }
impl From<Arc<Segment>> for Graphic { impl From<Arc<DotVoxData>> for Graphic {
fn from(vox: Arc<Segment>) -> Self { fn from(vox: Arc<DotVoxData>) -> Self {
Graphic::Voxel(vox) Graphic::Voxel(vox)
} }
} }
@ -105,8 +105,8 @@ impl GraphicCache {
.pixels() .pixels()
.map(|p| p.data) .map(|p| p.data)
.collect::<Vec<[u8; 4]>>(), .collect::<Vec<[u8; 4]>>(),
Graphic::Voxel(vox) => { Graphic::Voxel(ref vox) => {
super::renderer::draw_vox(&vox, aabr.size().into()) super::renderer::draw_vox(&vox.as_ref().into(), aabr.size().into())
} }
Graphic::Blank => return None, Graphic::Blank => return None,
}; };