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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
//! Create textures and build texture atlas.

use std::collections::HashMap;
use std::collections::hash_map::Entry::{ Occupied, Vacant };
use std::fmt::{ Debug, Formatter, Error };
use std::path::{ Path, PathBuf };
use std::mem;

use gfx;
use image::{
    self,
    ImageBuffer,
    RgbaImage,
    DynamicImage,
    ImageResult,
    SubImage,
    ImageError,
    GenericImageView,
    Pixel
};

pub use gfx_texture::{ Texture, ImageSize, TextureSettings };

// Loads RGBA image from path.
fn load_rgba8(path: &Path) -> ImageResult<RgbaImage> {
    image::open(path).map(|img| match img {
        DynamicImage::ImageRgba8(img) => img,
        img => img.to_rgba()
    })
}

/// An enumeration of ColorMap errors.
pub enum ColorMapError {
    /// The image opening error.
    Img(ImageError),

    /// The image size error.
    Size(u32, u32, String)
}

impl Debug for ColorMapError {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        match *self {
            ColorMapError::Img(ref e) => e.fmt(f),
            ColorMapError::Size(w, h, ref path) =>
                format!("ColorMap expected 256x256, found {}x{} in '{}'", w, h, path).fmt(f)
        }
    }
}

impl From<ImageError> for ColorMapError {
    fn from(img_err: ImageError) -> Self {
        ColorMapError::Img(img_err)
    }
}

/// A 256x256 image that stores colors.
pub struct ColorMap(RgbaImage);

impl ColorMap {
    /// Creates a new `ColorMap` from path.
    pub fn from_path<P>(path: P) -> Result<Self, ColorMapError>
        where P: AsRef<Path>
    {
        let img = try!(load_rgba8(path.as_ref()));

        match img.dimensions() {
            (256, 256) => Ok(ColorMap(img)),
            (w, h) => Err(ColorMapError::Size(w, h, path.as_ref().display().to_string()))
        }
    }

    /// Gets RGB color from the color map.
    pub fn get(&self, x: f32, y: f32) -> [u8; 3] {
        // Clamp to [0.0, 1.0].
        let x = x.max(0.0).min(1.0);
        let y = y.max(0.0).min(1.0);

        // Scale y from [0.0, 1.0] to [0.0, x], forming a triangle.
        let y = x * y;

        // Origin is in the bottom-right corner.
        let x = ((1.0 - x) * 255.0) as u8;
        let y = ((1.0 - y) * 255.0) as u8;

        let col = self.0.get_pixel(x as u32, y as u32).channels();
        [col[0], col[1], col[2]]
    }
}

/// Builds an atlas of textures.
pub struct AtlasBuilder {
    image: RgbaImage,
    // Base path for loading tiles.
    path: PathBuf,
    // Size of an individual tile.
    unit_width: u32,
    unit_height: u32,
    // Size of the entirely occupied square, in tiles.
    completed_tiles_size: u32,
    // Position in the current strip.
    position: u32,
    // Position cache for loaded tiles (in pixels).
    tile_positions: HashMap<String, (u32, u32)>,
    // Lowest-alpha cache for rectangles in the atlas.
    min_alpha_cache: HashMap<(u32, u32, u32, u32), u8>
}

impl AtlasBuilder {
    /// Creates a new `AtlasBuilder`.
    pub fn new<P>(path: P, unit_width: u32, unit_height: u32) -> Self
        where P: Into<PathBuf>
    {
        AtlasBuilder {
            image: ImageBuffer::new(unit_width * 4, unit_height * 4),
            path: path.into(),
            unit_width: unit_width,
            unit_height: unit_height,
            completed_tiles_size: 0,
            position: 0,
            tile_positions: HashMap::new(),
            min_alpha_cache: HashMap::new()
        }
    }

    /// Loads a file into the texture atlas.
    /// Checks if the file is loaded and returns position within the atlas.
    /// The name should be specified without file extension.
    /// PNG is the only supported format.
    pub fn load(&mut self, name: &str) -> (u32, u32) {
        if let Some(&pos) = self.tile_positions.get(name) {
            return pos
        }

        let mut path = self.path.join(name);
        path.set_extension("png");
        let img = load_rgba8(&path).unwrap();

        let (iw, ih) = img.dimensions();
        assert!(iw == self.unit_width);
        assert!((ih % self.unit_height) == 0);
        if ih > self.unit_height {
            println!("ignoring {} extra frames in '{}'", (ih / self.unit_height) - 1, name);
        }

        let (uw, uh) = (self.unit_width, self.unit_height);
        let (w, h) = self.image.dimensions();
        let size = self.completed_tiles_size;

        // Expand the image buffer if necessary.
        if self.position == 0 && (uw * size >= w || uh * size >= h) {
            let old = mem::replace(&mut self.image, ImageBuffer::new(w * 2, h * 2));
            for ix in 0 .. w {
                for iy in 0 .. h {
                    *self.image.get_pixel_mut(ix, iy) = old[(ix, iy)];
                }
            }

            /*
            let mut dest = SubImage::new(&mut self.image, 0, 0, w, h);
            for ((_, _, a), b) in dest.pixels_mut().zip(old.pixels()) {
                *a = *b;
            }
            */
        }

        let (x, y) = if self.position < size {
            (self.position, size)
        } else {
            (size, self.position - size)
        };

        self.position += 1;
        if self.position >= size * 2 + 1 {
            self.position = 0;
            self.completed_tiles_size += 1;
        }

        {
            let (x, y, w, h) = (x * uw, y * uh, uw, uh);
            for ix in 0 .. w {
                for iy in 0 .. h {
                    *self.image.get_pixel_mut(ix + x, iy + y) = img[(ix, iy)];
                }
            }
        }

        /*
        let mut dest = SubImage::new(&mut self.image, x * uw, y * uh, uw, uh);
        for ((_, _, a), b) in dest.pixels_mut().zip(img.pixels()) {
            *a = *b;
        }
        */

        *match self.tile_positions.entry(name.to_string()) {
            Occupied(entry) => entry.into_mut(),
            Vacant(entry) => entry.insert((x * uw, y * uh))
        }
    }

    /// Finds the minimum alpha value in a given sub texture of the image.
    pub fn min_alpha(&mut self, rect: [u32; 4]) -> u8 {
        let x = rect[0];
        let y = rect[1];
        let w = rect[2];
        let h = rect[3];
        if let Some(&alpha) = self.min_alpha_cache.get(&(x, y, w, h)) {
            return alpha
        }

        let tile = SubImage::new(&mut self.image, x, y, w, h);
        let min_alpha = tile.pixels().map(|(_, _, p)| p[3]).min().unwrap_or(0);
        self.min_alpha_cache.insert((x, y, w, h), min_alpha);
        min_alpha
    }

    /// Returns the complete texture atlas as a texture.
    pub fn complete<R, F>(self, factory: &mut F) -> Texture<R>
        where R: gfx::Resources, F: gfx::Factory<R>
    {
        let settings = TextureSettings::new().generate_mipmap(true);
        Texture::from_image(factory, &self.image, &settings).unwrap()
    }
}