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
|
use crate::{Frame, Pixel, Ref, View, P2};
use std::ops::{Add, Index, IndexMut, Sub};
impl Frame {
pub fn export(&self, view: View) -> Vec<Pixel> {
let mut o = vec![];
for y in view.a.y..view.b.y {
for x in view.a.x..view.b.x {
o.push(self[P2 { x, y }])
}
}
o
}
pub fn import(&mut self, view: View, mut source: &[Pixel]) {
for y in view.a.y..view.b.y {
for x in view.a.x..view.b.x {
self[P2 { x, y }] = source[0];
source = &source[1..];
}
}
}
pub fn new(size: P2) -> Self {
Self {
pixels: vec![Pixel::default(); size.area()],
size,
}
}
}
impl Ref {
pub fn apply<F: Fn(&mut Self)>(mut self, f: F) -> Self {
f(&mut self);
self
}
}
impl Add for Pixel {
type Output = Pixel;
#[inline]
fn add(self, rhs: Self) -> Self::Output {
Self {
r: self.r + rhs.r,
g: self.g + rhs.g,
b: self.b + rhs.b,
}
}
}
impl P2 {
pub const ZERO: P2 = P2 { x: 0, y: 0 };
#[inline]
pub fn area(&self) -> usize {
(self.x * self.y) as usize
}
}
impl View {
#[inline]
pub fn all(b: P2) -> Self {
Self {
a: P2::default(),
b,
}
}
#[inline]
pub fn size(&self) -> P2 {
self.b - self.a
}
}
impl Add for P2 {
type Output = P2;
#[inline]
fn add(self, rhs: Self) -> Self::Output {
Self {
x: self.x + rhs.x,
y: self.y + rhs.y,
}
}
}
impl Sub for P2 {
type Output = P2;
#[inline]
fn sub(self, rhs: Self) -> Self::Output {
Self {
x: self.x - rhs.x,
y: self.y - rhs.y,
}
}
}
impl Index<P2> for Frame {
type Output = Pixel;
#[inline]
fn index(&self, P2 { x, y }: P2) -> &Self::Output {
&self
.pixels
.get(x as usize + (y as usize * self.size.x as usize))
.unwrap_or(&Pixel { r: 0, g: 0, b: 0 })
}
}
impl IndexMut<P2> for Frame {
#[inline]
fn index_mut(&mut self, P2 { x, y }: P2) -> &mut Self::Output {
&mut self.pixels[x as usize + (y as usize * self.size.x as usize)]
}
}
pub trait ToArray {
type Output;
fn to_array(self) -> [Self::Output; 2];
}
impl<A> ToArray for (A, A) {
type Output = A;
fn to_array(self) -> [A; 2] {
[self.0, self.1]
}
}
|