use crate::{
math::Matrix2d,
triangulation,
types::{Color, Rectangle, SourceRectangle},
DrawState, Graphics, ImageSize,
};
#[derive(Copy, Clone)]
pub struct Image {
pub color: Option<Color>,
pub rectangle: Option<Rectangle>,
pub source_rectangle: Option<SourceRectangle>,
}
impl Image {
pub fn new() -> Image {
Image {
color: None,
source_rectangle: None,
rectangle: None,
}
}
pub fn new_color(color: Color) -> Image {
Image {
color: Some(color),
source_rectangle: None,
rectangle: None,
}
}
pub fn color(mut self, value: Color) -> Self {
self.color = Some(value);
self
}
pub fn maybe_color(mut self, value: Option<Color>) -> Self {
self.color = value;
self
}
pub fn rect<R: Into<Rectangle>>(mut self, value: R) -> Self {
self.rectangle = Some(value.into());
self
}
pub fn maybe_rect<R: Into<Rectangle>>(mut self, value: Option<R>) -> Self {
self.rectangle = value.map(|v| v.into());
self
}
pub fn src_rect(mut self, value: SourceRectangle) -> Self {
self.source_rectangle = Some(value);
self
}
pub fn maybe_src_rect(mut self, value: Option<SourceRectangle>) -> Self {
self.source_rectangle = value;
self
}
#[inline(always)]
pub fn draw<G>(
&self,
texture: &<G as Graphics>::Texture,
draw_state: &DrawState,
transform: Matrix2d,
g: &mut G,
) where
G: Graphics,
{
g.image(self, texture, draw_state, transform);
}
pub fn draw_tri<G>(
&self,
texture: &<G as Graphics>::Texture,
draw_state: &DrawState,
transform: Matrix2d,
g: &mut G,
) where
G: Graphics,
{
use crate::math::Scalar;
let color = self.color.unwrap_or([1.0; 4]);
let source_rectangle = self.source_rectangle.unwrap_or({
let (w, h) = texture.get_size();
[0.0, 0.0, w as Scalar, h as Scalar]
});
let rectangle = self.rectangle.unwrap_or([
0.0,
0.0,
source_rectangle[2] as Scalar,
source_rectangle[3] as Scalar,
]);
g.tri_list_uv(draw_state, &color, texture, |f| {
f(
&triangulation::rect_tri_list_xy(transform, rectangle),
&triangulation::rect_tri_list_uv(texture, source_rectangle),
)
});
}
}
impl Default for Image {
fn default() -> Self {
Image::new()
}
}
pub fn draw_many<G>(
rects: &[(Rectangle, SourceRectangle)],
color: Color,
texture: &<G as Graphics>::Texture,
draw_state: &DrawState,
transform: Matrix2d,
g: &mut G,
) where
G: Graphics,
{
g.tri_list_uv(draw_state, &color, texture, |f| {
for r in rects {
f(
&triangulation::rect_tri_list_xy(transform, r.0),
&triangulation::rect_tri_list_uv(texture, r.1),
)
}
});
}
#[cfg(test)]
mod test {
use super::Image;
#[test]
fn test_image() {
let _img = Image::new()
.color([1.0; 4])
.rect([0.0, 0.0, 100.0, 100.0])
.src_rect([0.0, 0.0, 32.0, 32.0]);
}
}