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
use crate::{ext::*, math::*, *};
use std::rc::Rc;
pub struct SpriteAtlasBuilder<'a> {
images: Vec<(image::Image, &'a mut Option<Sprite>)>,
mag_filter: FilterMode,
min_filter: FilterMode,
max_height: u32,
total_width: u32,
}
impl<'a> SpriteAtlasBuilder<'a> {
pub fn new() -> Self {
Self {
images: vec![],
max_height: 0,
total_width: 0,
mag_filter: Default::default(),
min_filter: Default::default(),
}
}
pub fn with_image(mut self, img: image::Image, sprite: &'a mut Option<Sprite>) -> Self {
self.total_width += img.width();
self.max_height = self.max_height.max(img.height());
self.images.push((img, sprite));
self
}
pub fn with_filter_modes(mut self, mag_filter: FilterMode, min_filter: FilterMode) -> Self {
self.mag_filter = mag_filter;
self.min_filter = min_filter;
self
}
pub fn build(self, renderer: &Renderer) -> Result<()> {
let mut atlas = image::Image::new(self.total_width, self.max_height);
let mut sprite_bounds = vec![];
let mut x = 0;
for (img, sprite) in self.images {
sprite_bounds.push((
Rect {
location: Vector2 { x: x, y: 0 },
dimensions: img.dimensions(),
},
sprite,
));
atlas.blit(&img, Vector2 { x, y: 0 }.convert());
x += img.width();
}
let texture = Rc::new(Texture::from_image(
renderer.wgpu_device().device(),
renderer.wgpu_device().queue(),
atlas,
self.mag_filter,
self.min_filter,
TextureType::Plain,
)?);
for (bounds, sprite) in sprite_bounds {
*sprite = Some(Sprite::from_texture_with_bounds(
renderer,
&texture,
bounds.convert(),
)?);
}
Ok(())
}
}