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
use std::fs::File;
use std::io;
use std::marker::PhantomData;
use png;
use png::HasParameters;
use mask::Mask;
use pixel::PixFmt;
pub struct Raster<F: PixFmt> {
width : u32,
height : u32,
pixels : Vec<F>,
}
impl<F: PixFmt> Raster<F> {
pub fn new(width: u32, height: u32) -> Raster<F> {
let len = width * height;
let mut pixels = Vec::with_capacity(capacity(len));
for _ in 0..len {
pixels.push(F::default());
}
Raster { width, height, pixels }
}
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
fn len(&self) -> usize {
(self.width * self.height) as usize
}
pub fn as_slice(&self) -> &[F] {
&self.pixels
}
pub fn as_slice_mut(&mut self) -> &mut [F] {
&mut self.pixels
}
pub fn as_u8_slice(&self) -> &[u8] {
F::as_u8_slice(&self.pixels)
}
pub fn as_u8_slice_mut(&mut self) -> &mut [u8] {
F::as_u8_slice_mut(&mut self.pixels)
}
pub fn clear(&mut self) {
debug_assert_eq!(self.len(), self.pixels.len());
for p in self.pixels.iter_mut() {
*p = F::default();
}
}
pub fn over(&mut self, mask: &mut Mask, clr: F) {
debug_assert_eq!(self.len(), self.pixels.len());
F::over(&mut self.pixels, mask.pixels(), clr);
mask.clear();
}
pub fn write_png(mut self, filename: &str) -> io::Result<()> {
debug_assert_eq!(self.len(), self.pixels.len());
F::divide_alpha(&mut self.pixels);
let fl = File::create(filename)?;
let ref mut bw = io::BufWriter::new(fl);
let mut enc = png::Encoder::new(bw, self.width, self.height);
enc.set(F::color_type()).set(png::BitDepth::Eight);
let mut writer = enc.write_header()?;
let pix = F::as_u8_slice(&mut self.pixels);
writer.write_image_data(pix)?;
Ok(())
}
}
fn capacity(len: u32) -> usize {
(((len + 7) >> 3) << 3) as usize
}
pub struct RasterB<F: PixFmt> {
width : u32,
height : u32,
pixels : PhantomData<F>,
}
impl<F: PixFmt> RasterB<F> {
pub fn new(width: u32, height: u32) -> RasterB<F> {
let pixels = PhantomData;
RasterB { width, height, pixels }
}
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
fn len(&self) -> usize {
(self.width * self.height) as usize
}
pub fn clear(&self, pixels: &mut [F]) {
assert_eq!(self.len(), pixels.len());
for p in pixels.iter_mut() {
*p = F::default();
}
}
pub fn over(&self, mask: &mut Mask, clr: F, mut pixels: &mut [F]) {
assert_eq!(self.len(), pixels.len());
F::over(&mut pixels, mask.pixels(), clr);
mask.clear();
}
}