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
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,
GenericImage,
Pixel
};
pub use gfx_texture::{ Texture, ImageSize, TextureSettings };
fn load_rgba8(path: &Path) -> ImageResult<RgbaImage> {
image::open(path).map(|img| match img {
DynamicImage::ImageRgba8(img) => img,
img => img.to_rgba()
})
}
pub enum ColorMapError {
Img(ImageError),
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)
}
}
pub struct ColorMap(RgbaImage);
impl ColorMap {
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()))
}
}
pub fn get(&self, x: f32, y: f32) -> [u8; 3] {
let x = x.max(0.0).min(1.0);
let y = y.max(0.0).min(1.0);
let y = x * y;
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]]
}
}
pub struct AtlasBuilder {
image: RgbaImage,
path: PathBuf,
unit_width: u32,
unit_height: u32,
completed_tiles_size: u32,
position: u32,
tile_positions: HashMap<String, (u32, u32)>,
min_alpha_cache: HashMap<(u32, u32, u32, u32), u8>
}
impl 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()
}
}
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;
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 (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)];
}
}
}
*match self.tile_positions.entry(name.to_string()) {
Occupied(entry) => entry.into_mut(),
Vacant(entry) => entry.insert((x * uw, y * uh))
}
}
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
}
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()
}
}