use std::convert::TryFrom;
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use image::{DynamicImage, RgbaImage};
use lazy_static::lazy_static;
use winit::window::Icon;
use crate::math::Size;
lazy_static! {
static ref GLOBAL_ID_CELL: AtomicU64 = AtomicU64::new(0);
}
#[macro_export]
macro_rules! include_texture {
($image_path:expr) => {{
let image_bytes = std::include_bytes!($image_path);
<$crate::texture::Texture as std::convert::TryFrom<&[u8]>>::try_from(image_bytes)
}};
}
#[derive(Debug, Clone)]
pub struct Texture {
id: u64,
pub image: Arc<RgbaImage>,
}
impl Texture {
#[must_use]
pub const fn id(&self) -> u64 {
self.id
}
#[must_use]
pub fn new(image: Arc<RgbaImage>) -> Self {
let id = GLOBAL_ID_CELL.fetch_add(1, Ordering::SeqCst);
Self { id, image }
}
pub fn load<P: AsRef<Path>>(path: P) -> crate::Result<Self> {
let img = image::open(path)?;
Ok(Self::from(&img))
}
#[must_use]
pub fn size(&self) -> Size<u32> {
let (w, h) = self.image.dimensions();
Size::new(w, h)
}
#[must_use]
pub fn rgba_pixels(&self) -> Vec<u8> {
(*self.image).clone().into_vec()
}
pub fn window_icon(&self) -> Result<Icon, winit::window::BadIcon> {
Icon::from_rgba(self.rgba_pixels(), self.image.width(), self.image.height())
}
}
impl<'a> TryFrom<&'a [u8]> for Texture {
type Error = crate::Error;
fn try_from(bytes: &[u8]) -> crate::Result<Self> {
let img = image::load_from_memory(bytes)?;
Ok(Self::from(&img))
}
}
impl<'a> From<&'a DynamicImage> for Texture {
fn from(img: &'a DynamicImage) -> Self {
let img = img.to_rgba8();
Self::new(Arc::new(img))
}
}