yatp_cli/
context.rs

1use std::path::PathBuf;
2
3use crate::{dictionary::Dictionary, format, packer::Packer, Rect, Size};
4
5/// Bundle of a `Packer` and a `Dictionary`
6#[derive(Debug)]
7pub struct Context {
8    packer: Packer,
9    dictionary: Dictionary,
10}
11
12impl Context {
13    /// Create a new context with given `size`
14    pub fn new(size: Size) -> Self {
15        Self {
16            packer: Packer::new(size),
17            dictionary: Dictionary::new(size),
18        }
19    }
20
21    /// Packs image loaded from the provided `path` into the packer with the provided `gap` and
22    /// records it into the dictionary. Returns the `rect` the texture was packed in if successful
23    pub fn pack(&mut self, path: &PathBuf, gap: u32) -> Option<Rect> {
24        let image = image::open(path).ok()?;
25
26        if let Some(rect) = self.packer.pack(&image, gap) {
27            self.dictionary.record(path, &rect);
28            return Some(rect);
29        }
30
31        None
32    }
33
34    /// Saves both the packer and the dictionary to a file with given `name`, `image` format and
35    /// `dictionary` format. If dictionary is `None` then the dictionary is not serialized
36    pub fn save_to_file(
37        &self,
38        name: &str,
39        image: format::ImageFormat,
40        dict: Option<format::DictionaryFormat>,
41    ) -> anyhow::Result<()> {
42        self.packer.save(name, image)?;
43
44        if let Some(dict) = dict {
45            self.dictionary.save(name, dict)?;
46        }
47        Ok(())
48    }
49}