use std::io::Read; use bevy_ecs::system::Resource; use resvg::{tiny_skia, usvg}; #[derive(Debug, Clone)] pub struct ImgData { pub bytes: Vec, pub width: u32, pub height: u32, } #[derive(Resource)] pub struct Assets {} impl Assets { pub fn new() -> Self { Assets {} } pub fn get(&self, local_path: impl Into) -> Option { let local_path = local_path.into(); let bytes = std::fs::read(format!("src/assets/{}", local_path)).unwrap(); if local_path.ends_with(".svg") { let opt = usvg::Options { default_size: usvg::Size::from_wh(20.0, 20.0).unwrap(), ..Default::default() }; let tree = usvg::Tree::from_data(&bytes, &opt) .expect(&format!("Couldn't parse svg {}", local_path)); let tree_size = tree.size().to_int_size(); let size = usvg::Size::from_wh(200.0, 200.0).unwrap().to_int_size(); assert!(size.width() > 0 && size.height() > 0); let mut pixmap = tiny_skia::Pixmap::new(size.width(), size.height()) .expect("Failed to construct pixmap"); resvg::render( &tree, tiny_skia::Transform::from_scale( (size.width() as f32) / (tree_size.height() as f32), (size.height() as f32) / (tree_size.height() as f32), ), &mut pixmap.as_mut(), ); let data = ImgData { bytes: pixmap.data().to_vec(), width: size.width(), height: size.height(), }; Some(data) } else if local_path.ends_with(".png") { let img = image::load_from_memory(&bytes).unwrap(); let rgba = img.to_rgba8(); let data = ImgData { bytes: rgba.bytes().map(|byte| byte.unwrap()).collect::>(), width: rgba.width(), height: rgba.height(), }; Some(data) } else { panic!("Unsupported sprite type"); } } }