iced_wgpu/image/atlas/
allocator.rs
1use guillotiere::{AtlasAllocator, Size};
2
3pub struct Allocator {
4 raw: AtlasAllocator,
5 allocations: usize,
6}
7
8impl Allocator {
9 pub fn new(size: u32) -> Allocator {
10 let raw = AtlasAllocator::new(Size::new(size as i32, size as i32));
11
12 Allocator {
13 raw,
14 allocations: 0,
15 }
16 }
17
18 pub fn allocate(&mut self, width: u32, height: u32) -> Option<Region> {
19 let allocation =
20 self.raw.allocate(Size::new(width as i32, height as i32))?;
21
22 self.allocations += 1;
23
24 Some(Region { allocation })
25 }
26
27 pub fn deallocate(&mut self, region: &Region) {
28 self.raw.deallocate(region.allocation.id);
29
30 self.allocations = self.allocations.saturating_sub(1);
31 }
32
33 pub fn is_empty(&self) -> bool {
34 self.allocations == 0
35 }
36
37 pub fn allocations(&self) -> usize {
38 self.allocations
39 }
40}
41
42pub struct Region {
43 allocation: guillotiere::Allocation,
44}
45
46impl Region {
47 pub fn position(&self) -> (u32, u32) {
48 let rectangle = &self.allocation.rectangle;
49
50 (rectangle.min.x as u32, rectangle.min.y as u32)
51 }
52
53 pub fn size(&self) -> crate::core::Size<u32> {
54 let size = self.allocation.rectangle.size();
55
56 crate::core::Size::new(size.width as u32, size.height as u32)
57 }
58}
59
60impl std::fmt::Debug for Allocator {
61 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62 write!(f, "Allocator")
63 }
64}
65
66impl std::fmt::Debug for Region {
67 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68 f.debug_struct("Region")
69 .field("id", &self.allocation.id)
70 .field("rectangle", &self.allocation.rectangle)
71 .finish()
72 }
73}