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
use derive_builder::Builder;
use crate::shape::{Color, Shape, PositionedShape};
#[derive(Builder)]
pub struct Compositor {
pub width: usize,
pub height: usize,
pub background: Color,
#[builder(setter(skip))]
shapes: Vec<(String, PositionedShape)>,
}
impl Compositor {
pub fn new(width: usize, height: usize, background: Color) -> Self {
Self {
width,
height,
background,
shapes: Vec::new()
}
}
pub fn builder() -> CompositorBuilder {
CompositorBuilder::default()
}
pub fn add(&mut self, name: &str, shape: PositionedShape) -> &mut Self {
self.shapes.push((name.into(), shape));
self
}
pub fn get_positioned(&mut self, name: &str) -> Option<&mut PositionedShape> {
self
.shapes
.iter_mut()
.filter_map(|(curr_name, shape)| if curr_name == name { Some(shape) } else { None }).next()
}
pub fn get<T: Shape>(&mut self, name: &str) -> Option<&mut T> {
self
.get_positioned(name)
.and_then(|shape| shape.inner_mut::<T>())
}
}
impl Shape for Compositor {
fn render(&self) -> Vec<Vec<Option<Color>>> {
let mut result = vec![vec![Some(self.background); self.width]; self.height];
for (_name, shape) in &self.shapes {
for (y, row) in shape.shape.render().iter().enumerate() {
for (x, color) in row.iter().enumerate() {
let real_x = shape.x + x;
let real_y = shape.y + y;
if real_y >= result.len() || real_x >= result[real_y].len() {
continue;
}
if let Some(color) = color {
let opacity = color.alpha as f32 / 255f32;
let rev_opacity = 1f32 - opacity;
let mut prev_color = result[real_y][real_x].unwrap();
if prev_color.alpha != 255 {
prev_color *= (prev_color.alpha as f32) / 255f32;
prev_color.alpha = 255;
}
let new_color = Some(Color {
red: (color.red as f32 * opacity + prev_color.red as f32 * rev_opacity) as u8,
green: (color.green as f32 * opacity + prev_color.green as f32 * rev_opacity) as u8,
blue: (color.blue as f32 * opacity + prev_color.blue as f32 * rev_opacity) as u8,
alpha: 255
});
result[real_y][real_x] = new_color;
}
}
}
}
result
}
}