use super::{Graphics, PixelFormat};
use crate::geom::Vector;
use crate::QuicksilverError;
use std::path::Path;
use std::rc::Rc;
#[derive(Clone)]
pub struct Image {
tex: Rc<golem::Texture>,
}
impl Image {
fn new(texture: golem::Texture) -> Image {
Image {
tex: Rc::new(texture),
}
}
pub fn from_raw(
gfx: &Graphics,
data: &[u8],
width: u32,
height: u32,
format: PixelFormat,
) -> Result<Image, QuicksilverError> {
Ok(Image::new(gfx.create_image(data, width, height, format)?))
}
pub fn from_encoded_bytes(gfx: &Graphics, raw: &[u8]) -> Result<Image, QuicksilverError> {
let img = image::load_from_memory(raw)?.to_rgba();
let width = img.width();
let height = img.height();
Ok(Image::from_raw(
gfx,
img.into_raw().as_slice(),
width,
height,
PixelFormat::RGBA,
)?)
}
pub async fn load(gfx: &Graphics, path: impl AsRef<Path>) -> Result<Image, QuicksilverError> {
let file_contents = platter::load_file(path).await?;
Image::from_encoded_bytes(gfx, file_contents.as_slice())
}
pub(crate) fn raw(&self) -> &golem::Texture {
&self.tex
}
pub(crate) fn ptr_eq(&self, other: &Image) -> bool {
Rc::ptr_eq(&self.tex, &other.tex)
}
pub fn size(&self) -> Vector {
Vector {
x: self.raw().width() as f32,
y: self.raw().height() as f32,
}
}
}