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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
use crate::{prelude::*, renderer::Rendering};
use num_traits::AsPrimitive;
use png::{BitDepth, ColorType, Decoder};
use std::{
borrow::Cow,
error,
ffi::{OsStr, OsString},
fmt,
fs::File,
io::{self, BufReader, BufWriter},
iter::Copied,
path::Path,
result, slice,
};
pub type Result<T> = result::Result<T, Error>;
#[non_exhaustive]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum PixelFormat {
Rgb,
Rgba,
}
impl PixelFormat {
#[inline]
pub fn channels(&self) -> usize {
use PixelFormat::*;
match self {
Rgb => 3,
Rgba => 4,
}
}
}
impl From<png::ColorType> for PixelFormat {
fn from(color_type: png::ColorType) -> Self {
use png::ColorType::*;
match color_type {
Rgb => Self::Rgb,
Rgba => Self::Rgba,
_ => unimplemented!("{:?} is not supported.", color_type),
}
}
}
impl Default for PixelFormat {
fn default() -> Self {
Self::Rgba
}
}
#[derive(Default, Clone)]
pub struct Image {
width: u32,
height: u32,
data: Vec<u8>,
format: PixelFormat,
}
impl Image {
#[inline]
pub fn new(width: u32, height: u32) -> Self {
Self::with_rgba(width, height)
}
#[inline]
pub fn with_rgba(width: u32, height: u32) -> Self {
let format = PixelFormat::Rgba;
let data = vec![0x00; format.channels() * (width * height) as usize];
Self::from_vec(width, height, data, format)
}
#[inline]
pub fn with_rgb(width: u32, height: u32) -> Self {
let format = PixelFormat::Rgb;
let data = vec![0x00; format.channels() * (width * height) as usize];
Self::from_vec(width, height, data, format)
}
#[inline]
pub fn from_bytes<B: AsRef<[u8]>>(
width: u32,
height: u32,
bytes: B,
format: PixelFormat,
) -> Result<Self> {
let bytes = bytes.as_ref();
if bytes.len() != (format.channels() * width as usize * height as usize) {
return Err(Error::InvalidImage((width, height), bytes.len(), format));
}
Ok(Self::from_vec(width, height, bytes.to_vec(), format))
}
#[inline]
pub fn from_pixels<P: AsRef<[Color]>>(
width: u32,
height: u32,
pixels: P,
format: PixelFormat,
) -> Result<Self> {
let pixels = pixels.as_ref();
if pixels.len() != (width as usize * height as usize) {
return Err(Error::InvalidImage((width, height), pixels.len(), format));
}
let bytes: Vec<u8> = match format {
PixelFormat::Rgb => pixels.iter().map(|c| c.rgb_channels()).flatten().collect(),
PixelFormat::Rgba => pixels.iter().map(|c| c.rgba_channels()).flatten().collect(),
};
Ok(Self::from_vec(width, height, bytes, format))
}
#[inline]
pub fn from_vec(width: u32, height: u32, data: Vec<u8>, format: PixelFormat) -> Self {
Self {
width,
height,
data,
format,
}
}
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
let path = path.as_ref();
let ext = path.extension();
if ext != Some(OsStr::new("png")) {
return Err(Error::InvalidFileType(ext.map(|e| e.to_os_string())));
}
let png_file = BufReader::new(File::open(&path)?);
let png = Decoder::new(png_file);
let mut reader = png.read_info()?;
let mut buf = vec![0x00; reader.output_buffer_size()];
let info = reader.next_frame(&mut buf)?;
if info.bit_depth != BitDepth::Eight {
return Err(Error::UnsupportedBitDepth(info.bit_depth));
} else if !matches!(info.color_type, ColorType::Rgb | ColorType::Rgba) {
return Err(Error::UnsupportedColorType(info.color_type));
}
let data = &buf[..info.buffer_size()];
let format = info.color_type.into();
Self::from_bytes(info.width, info.height, &data, format)
}
#[inline]
pub fn width(&self) -> u32 {
self.width
}
#[inline]
pub fn height(&self) -> u32 {
self.height
}
#[inline]
pub fn dimensions(&self) -> (u32, u32) {
(self.width, self.height)
}
#[inline]
pub fn center(&self) -> PointI2 {
point!(self.width() as i32 / 2, self.height() as i32 / 2)
}
#[inline]
pub fn bytes(&self) -> Bytes<'_> {
Bytes(self.as_bytes().iter().copied())
}
#[inline]
pub fn as_bytes(&self) -> &[u8] {
&self.data
}
#[inline]
pub fn as_mut_bytes(&mut self) -> &mut [u8] {
&mut self.data
}
#[inline]
pub fn into_bytes(self) -> Vec<u8> {
self.data
}
#[inline]
pub fn pixels(&self) -> Pixels<'_> {
Pixels(self.format.channels(), self.as_bytes().iter().copied())
}
#[inline]
pub fn into_pixels(self) -> Vec<Color> {
self.data
.chunks(self.format.channels())
.map(|slice| Color::from_slice(ColorMode::Rgb, slice).expect("valid image"))
.collect()
}
#[inline]
pub fn get_pixel(&self, x: u32, y: u32) -> Color {
let idx = self.idx(x, y);
let channels = self.format.channels();
Color::from_slice(ColorMode::Rgb, &self.data[idx..idx + channels]).expect("valid image")
}
#[inline]
pub fn set_pixel<C: Into<Color>>(&mut self, x: u32, y: u32, color: C) {
let color = color.into();
let idx = self.idx(x, y);
let channels = self.format.channels();
self.data[idx..(idx + channels)].clone_from_slice(&color.channels()[..channels]);
}
#[inline]
pub fn update_bytes<B: AsRef<[u8]>>(&mut self, bytes: B) {
self.data.clone_from_slice(bytes.as_ref());
}
#[inline]
pub fn format(&self) -> PixelFormat {
self.format
}
pub fn save<P>(&self, path: P) -> PixResult<()>
where
P: AsRef<Path>,
{
let path = path.as_ref();
let png_file = BufWriter::new(File::create(&path)?);
let mut png = png::Encoder::new(png_file, self.width, self.height);
png.set_color(png::ColorType::Rgba);
png.set_depth(png::BitDepth::Eight);
let mut writer = png.write_header()?;
Ok(writer.write_image_data(self.as_bytes())?)
}
}
impl Image {
#[inline]
fn idx(&self, x: u32, y: u32) -> usize {
self.format.channels() * (y * self.width + x) as usize
}
}
impl PixState {
pub fn image<P>(&mut self, position: P, img: &Image) -> PixResult<()>
where
P: Into<PointI2>,
{
let pos = position.into();
self.image_transformed(
img,
None,
rect![pos.x(), pos.y(), img.width() as i32, img.height() as i32],
0.0,
None,
None,
)
}
pub fn image_transformed<R1, R2, T, C, F>(
&mut self,
img: &Image,
src: R1,
dst: R2,
angle: T,
center: C,
flipped: F,
) -> PixResult<()>
where
R1: Into<Option<Rect<i32>>>,
R2: Into<Option<Rect<i32>>>,
T: AsPrimitive<Scalar>,
C: Into<Option<PointI2>>,
F: Into<Option<Flipped>>,
{
let s = &self.settings;
let mut dst = dst.into();
if let ImageMode::Center = s.image_mode {
dst = dst.map(|dst| Rect::from_center(dst.top_left(), dst.width(), dst.height()));
};
let mut angle: Scalar = angle.as_();
if let AngleMode::Radians = s.angle_mode {
angle = angle.to_degrees();
};
Ok(self.renderer.image(
img,
src.into(),
dst,
angle,
center.into(),
flipped.into(),
s.image_tint,
)?)
}
}
impl fmt::Debug for Image {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Image")
.field("width", &self.width)
.field("height", &self.height)
.field("format", &self.format)
.field("size", &self.data.len())
.finish()
}
}
#[derive(Debug, Clone)]
pub struct Bytes<'a>(Copied<slice::Iter<'a, u8>>);
impl Iterator for Bytes<'_> {
type Item = u8;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
#[derive(Debug, Clone)]
pub struct Pixels<'a>(usize, Copied<slice::Iter<'a, u8>>);
impl Iterator for Pixels<'_> {
type Item = Color;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
let r = self.1.next()?;
let g = self.1.next()?;
let b = self.1.next()?;
let channels = self.0;
match channels {
3 => Some(Color::from_slice(ColorMode::Rgb, [r, g, b]).expect("valid pixel")),
4 => {
let a = self.1.next()?;
Some(Color::from_slice(ColorMode::Rgb, [r, g, b, a]).expect("valid pixel"))
}
_ => unreachable!("invalid number of color channels"),
}
}
}
#[non_exhaustive]
#[derive(Debug)]
pub enum Error {
InvalidImage((u32, u32), usize, PixelFormat),
InvalidFileType(Option<OsString>),
UnsupportedColorType(png::ColorType),
UnsupportedBitDepth(png::BitDepth),
IoError(io::Error),
DecodingError(png::DecodingError),
EncodingError(png::EncodingError),
Other(Cow<'static, str>),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use Error::*;
match self {
InvalidImage(dimensions, len, format) => write!(
f,
"invalid image. dimensions: {:?}, bytes: {}, format: {:?}",
dimensions, len, format
),
InvalidFileType(ext) => write!(f, "invalid file type: {:?}", ext),
UnsupportedColorType(color_type) => write!(f, "invalid color type: {:?}", color_type),
UnsupportedBitDepth(depth) => write!(f, "invalid bit depth: {:?}", depth),
Other(err) => write!(f, "renderer error: {}", err),
err => err.fmt(f),
}
}
}
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
use Error::*;
match self {
IoError(err) => err.source(),
DecodingError(err) => err.source(),
_ => None,
}
}
}
impl From<Error> for PixError {
fn from(err: Error) -> Self {
Self::ImageError(err)
}
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Self {
Error::IoError(err)
}
}
impl From<png::DecodingError> for Error {
fn from(err: png::DecodingError) -> Self {
Error::DecodingError(err)
}
}
impl From<png::EncodingError> for Error {
fn from(err: png::EncodingError) -> Self {
Error::EncodingError(err)
}
}
impl From<png::EncodingError> for PixError {
fn from(err: png::EncodingError) -> Self {
PixError::ImageError(Error::EncodingError(err))
}
}