1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
use std::{
    fmt::{self, Debug, Formatter},
    path::Path,
};
use anyhow::{Context, Error};
use image::{DynamicImage, GenericImageView};
use hotg_rune_core::PixelFormat;
use hotg_rune_runtime::{ParameterError};
use crate::run::multi::{Builder, SourceBackedCapability};

#[derive(Clone, PartialEq)]
pub struct Image {
    processed: DynamicImage,
}

impl SourceBackedCapability for Image {
    type Builder = ImageSettings;
    type Source = ImageSource;

    fn generate(&mut self, buffer: &mut [u8]) -> Result<usize, anyhow::Error> {
        let bytes = self.processed.as_bytes();

        let len = std::cmp::min(bytes.len(), buffer.len());
        buffer[..len].copy_from_slice(&bytes[..len]);

        Ok(len)
    }

    fn from_builder(
        builder: ImageSettings,
        image: &ImageSource,
    ) -> Result<Self, anyhow::Error> {
        let (pixel_format, width, height) = builder
            .deconstruct()
            .context("Not all parameters were provided")?;

        let image = image.0.resize_exact(
            width,
            height,
            image::imageops::FilterType::CatmullRom,
        );

        let image = match pixel_format {
            PixelFormat::GrayScale => {
                DynamicImage::ImageLuma8(image.to_luma8())
            },
            PixelFormat::RGB => DynamicImage::ImageRgb8(image.to_rgb8()),
            PixelFormat::BGR => DynamicImage::ImageBgr8(image.to_bgr8()),
        };

        Ok(Image { processed: image })
    }
}

impl Debug for Image {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let Image { processed } = self;

        f.debug_struct("Image")
            .field("processed", processed)
            .finish()
    }
}

#[derive(Debug, Default, Copy, Clone, PartialEq)]
pub struct ImageSettings {
    pixel_format: Option<PixelFormat>,
    width: Option<u32>,
    height: Option<u32>,
}

impl ImageSettings {
    fn deconstruct(self) -> Result<(PixelFormat, u32, u32), Error> {
        let ImageSettings {
            pixel_format,
            width,
            height,
        } = self;

        let pixel_format = pixel_format
            .context("The \"pixel_format\" parameter wasn't set")?;
        let width = width.context("The \"width\" parameter wasn't set")?;
        let height = height.context("The \"height\" parameter wasn't set")?;

        Ok((pixel_format, width, height))
    }
}

impl Builder for ImageSettings {
    fn set_parameter(
        &mut self,
        key: &str,
        value: hotg_rune_core::Value,
    ) -> Result<(), ParameterError> {
        let ImageSettings {
            pixel_format,
            width,
            height,
        } = self;

        match key {
            "pixel_format" => super::try_from_int_value(pixel_format, value),
            "width" => super::try_from_int_value(width, value),
            "height" => super::try_from_int_value(height, value),
            _ => Err(ParameterError::UnsupportedParameter),
        }
    }
}

pub struct ImageSource(DynamicImage);

impl ImageSource {
    pub fn from_file(path: impl AsRef<Path>) -> Result<Self, Error> {
        let path = path.as_ref();
        let img = image::open(path).with_context(|| {
            format!("Unable to read an image from \"{}\"", path.display())
        })?;

        Ok(ImageSource(img))
    }
}

impl Debug for ImageSource {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let dims = self.0.dimensions();
        let pixel = pixel_type_name(&self.0);

        f.debug_struct("ImageSource")
            .field("dimensions", &dims)
            .field("pixel_type", &pixel)
            .finish_non_exhaustive()
    }
}

fn pixel_type_name(image: &DynamicImage) -> &'static str {
    match image {
        DynamicImage::ImageLuma8(_) => "Luma8",
        DynamicImage::ImageLumaA8(_) => "LumaA8",
        DynamicImage::ImageRgb8(_) => "Rgb8",
        DynamicImage::ImageRgba8(_) => "Rgba8",
        DynamicImage::ImageBgr8(_) => "Bgr8",
        DynamicImage::ImageBgra8(_) => "Bgra8",
        DynamicImage::ImageLuma16(_) => "Luma16",
        DynamicImage::ImageLumaA16(_) => "LumaA16",
        DynamicImage::ImageRgb16(_) => "Rgb16",
        DynamicImage::ImageRgba16(_) => "Rgba16",
    }
}