Skip to main content

strata_render/
texture_atlas.rs

1//! GPU Texture Atlas with Shelf Bin-Packing, Sub-Allocation, and LRU Eviction in VRAM.
2//!
3//! Provides dynamic sub-allocation of 2D VRAM texture space for images, vector icons,
4//! and rendered canvas elements with zero texture thrashing and automated LRU recycling.
5
6use crate::gpu_context::{GpuDevice, GpuTextureHandle};
7use crate::swapchain::SwapchainFormat;
8use std::collections::HashMap;
9
10/// Allocated sub-region within the GPU texture atlas.
11#[derive(Debug, Clone, Copy, PartialEq)]
12pub struct AtlasRegion {
13    pub id: u64,
14    pub x: u32,
15    pub y: u32,
16    pub width: u32,
17    pub height: u32,
18    pub uv_bounds: [f32; 4], // [u_min, v_min, u_max, v_max]
19    pub last_used_frame: u64,
20}
21
22/// Horizontal shelf for 2D bin-packing within the atlas.
23#[derive(Debug, Clone)]
24struct Shelf {
25    y: u32,
26    height: u32,
27    current_x: u32,
28}
29
30/// High-performance GPU texture atlas with dynamic shelf bin-packing and LRU cache eviction.
31pub struct GpuTextureAtlas {
32    pub width: u32,
33    pub height: u32,
34    pub format: SwapchainFormat,
35    pub texture: GpuTextureHandle,
36    shelves: Vec<Shelf>,
37    allocated_regions: HashMap<u64, AtlasRegion>,
38    next_region_id: u64,
39    next_shelf_y: u32,
40    total_allocations: u64,
41    total_evictions: u64,
42}
43
44impl GpuTextureAtlas {
45    /// Creates a new GPU texture atlas on the device with the specified dimensions (e.g. 2048x2048 or 4096x4096).
46    pub fn new(device: &GpuDevice, width: u32, height: u32, format: SwapchainFormat) -> Self {
47        let texture = device.create_texture(width, height, format, false);
48        Self {
49            width,
50            height,
51            format,
52            texture,
53            shelves: Vec::new(),
54            allocated_regions: HashMap::new(),
55            next_region_id: 1,
56            next_shelf_y: 0,
57            total_allocations: 0,
58            total_evictions: 0,
59        }
60    }
61
62    /// Allocates a sub-rectangle in the texture atlas for the given dimensions,
63    /// evicting least-recently-used regions if necessary.
64    pub fn allocate(&mut self, req_w: u32, req_h: u32, current_frame: u64) -> Option<AtlasRegion> {
65        if req_w == 0 || req_h == 0 || req_w > self.width || req_h > self.height {
66            return None;
67        }
68
69        // 1. Try to fit into an existing shelf with the least height waste
70        let mut best_shelf_idx: Option<usize> = None;
71        let mut best_waste = u32::MAX;
72
73        for (idx, shelf) in self.shelves.iter().enumerate() {
74            if shelf.height >= req_h && (shelf.current_x + req_w) <= self.width {
75                let waste = shelf.height - req_h;
76                if waste < best_waste {
77                    best_waste = waste;
78                    best_shelf_idx = Some(idx);
79                }
80            }
81        }
82
83        if let Some(idx) = best_shelf_idx {
84            let shelf = &mut self.shelves[idx];
85            let x = shelf.current_x;
86            let y = shelf.y;
87            shelf.current_x += req_w;
88
89            return Some(self.register_region(x, y, req_w, req_h, current_frame));
90        }
91
92        // 2. Try creating a new shelf below current shelves
93        if self.next_shelf_y + req_h <= self.height {
94            let shelf = Shelf {
95                y: self.next_shelf_y,
96                height: req_h,
97                current_x: req_w,
98            };
99            let x = 0;
100            let y = self.next_shelf_y;
101            self.next_shelf_y += req_h;
102            self.shelves.push(shelf);
103
104            return Some(self.register_region(x, y, req_w, req_h, current_frame));
105        }
106
107        // 3. Atlas full: Evict LRU region and reclaim memory if needed
108        self.evict_lru_regions(req_w, req_h, current_frame);
109
110        // Retry allocation on reset shelf space
111        if self.next_shelf_y + req_h <= self.height {
112            let x = 0;
113            let y = self.next_shelf_y;
114            self.next_shelf_y += req_h;
115            self.shelves.push(Shelf {
116                y,
117                height: req_h,
118                current_x: req_w,
119            });
120            Some(self.register_region(x, y, req_w, req_h, current_frame))
121        } else {
122            None
123        }
124    }
125
126    /// Registers and stores an allocated sub-region with normalized UV coordinates.
127    fn register_region(
128        &mut self,
129        x: u32,
130        y: u32,
131        w: u32,
132        h: u32,
133        current_frame: u64,
134    ) -> AtlasRegion {
135        let id = self.next_region_id;
136        self.next_region_id += 1;
137        self.total_allocations += 1;
138
139        let uv_min_x = x as f32 / self.width as f32;
140        let uv_min_y = y as f32 / self.height as f32;
141        let uv_max_x = (x + w) as f32 / self.width as f32;
142        let uv_max_y = (y + h) as f32 / self.height as f32;
143
144        let region = AtlasRegion {
145            id,
146            x,
147            y,
148            width: w,
149            height: h,
150            uv_bounds: [uv_min_x, uv_min_y, uv_max_x, uv_max_y],
151            last_used_frame: current_frame,
152        };
153
154        self.allocated_regions.insert(id, region);
155        region
156    }
157
158    /// Evicts the least recently used regions from the atlas to reclaim space.
159    fn evict_lru_regions(&mut self, _needed_w: u32, _needed_h: u32, _current_frame: u64) {
160        if self.allocated_regions.is_empty() {
161            return;
162        }
163
164        // Find oldest regions not accessed in recent frames
165        let mut sorted: Vec<(u64, u64)> = self
166            .allocated_regions
167            .iter()
168            .map(|(&id, r)| (id, r.last_used_frame))
169            .collect();
170        sorted.sort_by_key(|&(_, frame)| frame);
171
172        // Evict oldest 25% of regions
173        let evict_count = (sorted.len() / 4).max(1);
174        for &(id, _) in sorted.iter().take(evict_count) {
175            self.allocated_regions.remove(&id);
176            self.total_evictions += 1;
177        }
178
179        // If compaction needed, repack remaining regions preserving their IDs
180        if self.allocated_regions.len() < 10 && !self.shelves.is_empty() {
181            let mut remaining: Vec<AtlasRegion> =
182                self.allocated_regions.values().copied().collect();
183            self.shelves.clear();
184            self.next_shelf_y = 0;
185            for r in &mut remaining {
186                let mut placed = false;
187                for shelf in &mut self.shelves {
188                    if shelf.height >= r.height && (shelf.current_x + r.width) <= self.width {
189                        r.x = shelf.current_x;
190                        r.y = shelf.y;
191                        shelf.current_x += r.width;
192                        placed = true;
193                        break;
194                    }
195                }
196                if !placed && self.next_shelf_y + r.height <= self.height {
197                    let y = self.next_shelf_y;
198                    self.shelves.push(Shelf {
199                        y,
200                        height: r.height,
201                        current_x: r.width,
202                    });
203                    self.next_shelf_y += r.height;
204                    r.x = 0;
205                    r.y = y;
206                }
207                r.uv_bounds = [
208                    r.x as f32 / self.width as f32,
209                    r.y as f32 / self.height as f32,
210                    (r.x + r.width) as f32 / self.width as f32,
211                    (r.y + r.height) as f32 / self.height as f32,
212                ];
213                self.allocated_regions.insert(r.id, *r);
214            }
215        }
216    }
217
218    /// Touches a region to update its LRU timestamp.
219    pub fn touch(&mut self, region_id: u64, current_frame: u64) {
220        if let Some(region) = self.allocated_regions.get_mut(&region_id) {
221            region.last_used_frame = current_frame;
222        }
223    }
224
225    /// Uploads CPU pixels into an allocated atlas sub-region.
226    pub fn upload_sub_image(&mut self, region: &AtlasRegion, pixels: &[u8]) {
227        let bpp = self.format.bytes_per_pixel();
228        let region_stride = region.width as usize * bpp;
229        let atlas_stride = self.width as usize * bpp;
230
231        for row in 0..region.height as usize {
232            let src_start = row * region_stride;
233            let src_end = src_start + region_stride;
234            let dst_start = (region.y as usize + row) * atlas_stride + (region.x as usize * bpp);
235
236            if src_end <= pixels.len() && (dst_start + region_stride) <= self.texture.data.len() {
237                self.texture.data[dst_start..dst_start + region_stride]
238                    .copy_from_slice(&pixels[src_start..src_end]);
239            }
240        }
241    }
242
243    /// Returns the number of currently active allocated regions.
244    pub fn allocated_region_count(&self) -> usize {
245        self.allocated_regions.len()
246    }
247
248    /// Deallocates an existing region by ID.
249    pub fn deallocate(&mut self, region_id: u64) -> bool {
250        self.allocated_regions.remove(&region_id).is_some()
251    }
252
253    /// Explicitly triggers LRU cache eviction of aged regions.
254    pub fn evict_lru(&mut self, current_frame: u64) {
255        self.evict_lru_regions(0, 0, current_frame);
256    }
257
258    /// Returns allocation statistics: (allocated_count, total_allocations, total_evictions).
259    pub fn stats(&self) -> (usize, u64, u64) {
260        (
261            self.allocated_regions.len(),
262            self.total_allocations,
263            self.total_evictions,
264        )
265    }
266}