Skip to main content

astrelis_render/
atlas.rs

1//! Texture atlas with non-uniform rectangle packing.
2//!
3//! Provides efficient texture packing for UI elements, sprites, and other 2D graphics.
4//!
5//! # Example
6//!
7//! ```ignore
8//! use astrelis_render::{TextureAtlas, GraphicsContext};
9//!
10//! let context = GraphicsContext::new_owned_sync().expect("Failed to create graphics context");
11//! let mut atlas = TextureAtlas::new(context.clone(), 512, wgpu::TextureFormat::Rgba8UnormSrgb);
12//!
13//! // Insert images
14//! let key1 = AtlasKey::new("icon1");
15//! if let Some(entry) = atlas.insert(key1, &image_data, Vec2::new(32.0, 32.0)) {
16//!     println!("Inserted at UV: {:?}", entry.uv_rect);
17//! }
18//!
19//! // Upload to GPU
20//! atlas.upload(&context);
21//!
22//! // Retrieve UV coordinates
23//! if let Some(entry) = atlas.get(&key1) {
24//!     // Use entry.uv_rect for rendering
25//! }
26//! ```
27
28use astrelis_core::profiling::profile_function;
29
30use crate::GraphicsContext;
31use crate::extension::AsWgpu;
32use crate::types::GpuTexture;
33use ahash::HashMap;
34use std::sync::Arc;
35
36/// Rectangle for atlas packing (not coordinate-space aware).
37///
38/// This is a simple rectangle type used internally for texture atlas packing.
39/// It does not distinguish between logical/physical coordinates since atlas
40/// operations work in texture-local pixel space.
41#[derive(Debug, Clone, Copy, PartialEq)]
42pub struct AtlasRect {
43    pub x: f32,
44    pub y: f32,
45    pub width: f32,
46    pub height: f32,
47}
48
49impl AtlasRect {
50    /// Create a new atlas rectangle.
51    pub const fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
52        Self {
53            x,
54            y,
55            width,
56            height,
57        }
58    }
59}
60
61/// Rectangle type for atlas packing (internal alias).
62type Rect = AtlasRect;
63
64/// Unique key for an atlas entry.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
66pub struct AtlasKey(u64);
67
68impl AtlasKey {
69    /// Create a new atlas key from a string.
70    pub fn new(s: &str) -> Self {
71        use std::collections::hash_map::DefaultHasher;
72        use std::hash::{Hash, Hasher};
73
74        let mut hasher = DefaultHasher::new();
75        s.hash(&mut hasher);
76        Self(hasher.finish())
77    }
78
79    /// Create an atlas key from a u64.
80    pub fn from_u64(id: u64) -> Self {
81        Self(id)
82    }
83
84    /// Get the raw u64 value.
85    pub fn as_u64(&self) -> u64 {
86        self.0
87    }
88}
89
90/// An entry in the texture atlas.
91#[derive(Debug, Clone, Copy)]
92pub struct AtlasEntry {
93    /// Rectangle in pixel coordinates within the atlas.
94    pub rect: Rect,
95    /// Rectangle in normalized UV coordinates (0.0 to 1.0).
96    pub uv_rect: Rect,
97}
98
99impl AtlasEntry {
100    /// Create a new atlas entry.
101    pub fn new(rect: Rect, atlas_size: f32) -> Self {
102        let uv_rect = Rect {
103            x: rect.x / atlas_size,
104            y: rect.y / atlas_size,
105            width: rect.width / atlas_size,
106            height: rect.height / atlas_size,
107        };
108
109        Self { rect, uv_rect }
110    }
111}
112
113/// Rectangle packing algorithm.
114#[derive(Debug, Clone)]
115#[allow(dead_code)]
116enum PackerNode {
117    /// Empty node that can be split.
118    Empty { rect: Rect },
119    /// Filled node with an entry.
120    Filled { rect: Rect, key: AtlasKey },
121    /// Split node with two children.
122    Split {
123        rect: Rect,
124        left: Box<PackerNode>,
125        right: Box<PackerNode>,
126    },
127}
128
129impl PackerNode {
130    /// Create a new empty node.
131    fn new(rect: Rect) -> Self {
132        Self::Empty { rect }
133    }
134
135    /// Try to insert a rectangle into this node.
136    fn insert(&mut self, key: AtlasKey, width: f32, height: f32) -> Option<Rect> {
137        match self {
138            PackerNode::Empty { rect } => {
139                // Check if the rectangle fits
140                if width > rect.width || height > rect.height {
141                    return None;
142                }
143
144                // Perfect fit
145                if width == rect.width && height == rect.height {
146                    let result = *rect;
147                    *self = PackerNode::Filled { rect: *rect, key };
148                    return Some(result);
149                }
150
151                // Split the node
152                let rect_copy = *rect;
153
154                // Decide whether to split horizontally or vertically
155                let horizontal_waste = rect.width - width;
156                let vertical_waste = rect.height - height;
157
158                let (left_rect, right_rect) = if horizontal_waste > vertical_waste {
159                    // Split horizontally (left/right)
160                    (
161                        Rect {
162                            x: rect.x,
163                            y: rect.y,
164                            width,
165                            height: rect.height,
166                        },
167                        Rect {
168                            x: rect.x + width,
169                            y: rect.y,
170                            width: rect.width - width,
171                            height: rect.height,
172                        },
173                    )
174                } else {
175                    // Split vertically (top/bottom)
176                    (
177                        Rect {
178                            x: rect.x,
179                            y: rect.y,
180                            width: rect.width,
181                            height,
182                        },
183                        Rect {
184                            x: rect.x,
185                            y: rect.y + height,
186                            width: rect.width,
187                            height: rect.height - height,
188                        },
189                    )
190                };
191
192                let mut left = Box::new(PackerNode::new(left_rect));
193                let right = Box::new(PackerNode::new(right_rect));
194
195                // Insert into the left node
196                let result = left.insert(key, width, height);
197
198                *self = PackerNode::Split {
199                    rect: rect_copy,
200                    left,
201                    right,
202                };
203
204                result
205            }
206            PackerNode::Filled { .. } => None,
207            PackerNode::Split { left, right, .. } => {
208                // Try left first, then right
209                left.insert(key, width, height)
210                    .or_else(|| right.insert(key, width, height))
211            }
212        }
213    }
214}
215
216/// Texture atlas with dynamic rectangle packing.
217pub struct TextureAtlas {
218    /// GPU texture with cached view and metadata.
219    texture: GpuTexture,
220    entries: HashMap<AtlasKey, AtlasEntry>,
221    packer: PackerNode,
222    context: Arc<GraphicsContext>,
223    /// Pending uploads (key, data, rect)
224    pending_uploads: Vec<(AtlasKey, Vec<u8>, Rect)>,
225    dirty: bool,
226}
227
228impl TextureAtlas {
229    /// Create a new texture atlas.
230    ///
231    /// # Arguments
232    ///
233    /// * `context` - Graphics context
234    /// * `size` - Size of the atlas texture (must be power of 2)
235    /// * `format` - Texture format
236    pub fn new(context: Arc<GraphicsContext>, size: u32, format: wgpu::TextureFormat) -> Self {
237        profile_function!();
238        let texture = GpuTexture::new_2d(
239            context.device(),
240            Some("TextureAtlas"),
241            size,
242            size,
243            format,
244            wgpu::TextureUsages::TEXTURE_BINDING
245                | wgpu::TextureUsages::COPY_DST
246                | wgpu::TextureUsages::RENDER_ATTACHMENT,
247        );
248
249        let packer = PackerNode::new(Rect {
250            x: 0.0,
251            y: 0.0,
252            width: size as f32,
253            height: size as f32,
254        });
255
256        Self {
257            texture,
258            entries: HashMap::default(),
259            packer,
260            context,
261            pending_uploads: Vec::new(),
262            dirty: false,
263        }
264    }
265
266    /// Insert an image into the atlas.
267    ///
268    /// Returns the atlas entry if the image was successfully inserted.
269    /// Returns None if there's no space in the atlas.
270    ///
271    /// # Arguments
272    ///
273    /// * `key` - Unique key for this image
274    /// * `image_data` - Raw pixel data (must match atlas format)
275    /// * `size` - Size of the image in pixels
276    pub fn insert(
277        &mut self,
278        key: AtlasKey,
279        image_data: &[u8],
280        width: u32,
281        height: u32,
282    ) -> Option<AtlasEntry> {
283        profile_function!();
284        // Check if already exists
285        if let Some(entry) = self.entries.get(&key) {
286            return Some(*entry);
287        }
288
289        // Try to pack the rectangle
290        let rect = self.packer.insert(key, width as f32, height as f32)?;
291
292        // Create entry
293        let entry = AtlasEntry::new(rect, self.texture.width() as f32);
294        self.entries.insert(key, entry);
295
296        // Queue upload
297        self.pending_uploads.push((key, image_data.to_vec(), rect));
298        self.dirty = true;
299
300        Some(entry)
301    }
302
303    /// Get an atlas entry by key.
304    pub fn get(&self, key: &AtlasKey) -> Option<&AtlasEntry> {
305        self.entries.get(key)
306    }
307
308    /// Check if the atlas contains a key.
309    pub fn contains(&self, key: &AtlasKey) -> bool {
310        self.entries.contains_key(key)
311    }
312
313    /// Upload all pending data to the GPU.
314    pub fn upload(&mut self) {
315        profile_function!();
316        if !self.dirty {
317            return;
318        }
319
320        let format = self.texture.format();
321        for (_, data, rect) in &self.pending_uploads {
322            let bytes_per_pixel = match format {
323                wgpu::TextureFormat::Rgba8UnormSrgb | wgpu::TextureFormat::Rgba8Unorm => 4,
324                wgpu::TextureFormat::Bgra8UnormSrgb | wgpu::TextureFormat::Bgra8Unorm => 4,
325                wgpu::TextureFormat::R8Unorm => 1,
326                _ => 4, // Default to 4 bytes
327            };
328
329            self.context.queue().write_texture(
330                wgpu::TexelCopyTextureInfo {
331                    texture: self.texture.as_wgpu(),
332                    mip_level: 0,
333                    origin: wgpu::Origin3d {
334                        x: rect.x as u32,
335                        y: rect.y as u32,
336                        z: 0,
337                    },
338                    aspect: wgpu::TextureAspect::All,
339                },
340                data,
341                wgpu::TexelCopyBufferLayout {
342                    offset: 0,
343                    bytes_per_row: Some(rect.width as u32 * bytes_per_pixel),
344                    rows_per_image: Some(rect.height as u32),
345                },
346                wgpu::Extent3d {
347                    width: rect.width as u32,
348                    height: rect.height as u32,
349                    depth_or_array_layers: 1,
350                },
351            );
352        }
353
354        self.pending_uploads.clear();
355        self.dirty = false;
356    }
357
358    /// Get the texture view for binding.
359    pub fn texture_view(&self) -> &wgpu::TextureView {
360        self.texture.view()
361    }
362
363    /// Get the texture for advanced use cases.
364    pub fn texture(&self) -> &wgpu::Texture {
365        self.texture.as_wgpu()
366    }
367
368    /// Get the size of the atlas.
369    pub fn size(&self) -> u32 {
370        self.texture.width()
371    }
372
373    /// Get the texture format.
374    pub fn format(&self) -> wgpu::TextureFormat {
375        self.texture.format()
376    }
377
378    /// Get the number of entries in the atlas.
379    pub fn len(&self) -> usize {
380        self.entries.len()
381    }
382
383    /// Check if the atlas is empty.
384    pub fn is_empty(&self) -> bool {
385        self.entries.is_empty()
386    }
387
388    /// Clear all entries from the atlas.
389    pub fn clear(&mut self) {
390        self.entries.clear();
391        self.pending_uploads.clear();
392        let size = self.texture.width();
393        self.packer = PackerNode::new(Rect {
394            x: 0.0,
395            y: 0.0,
396            width: size as f32,
397            height: size as f32,
398        });
399        self.dirty = false;
400    }
401}
402
403#[cfg(test)]
404mod tests {
405    use super::*;
406
407    #[test]
408    fn test_atlas_key() {
409        let key1 = AtlasKey::new("test");
410        let key2 = AtlasKey::new("test");
411        let key3 = AtlasKey::new("other");
412
413        assert_eq!(key1, key2);
414        assert_ne!(key1, key3);
415    }
416
417    #[test]
418    fn test_atlas_entry_uv() {
419        let rect = Rect {
420            x: 0.0,
421            y: 0.0,
422            width: 64.0,
423            height: 64.0,
424        };
425        let entry = AtlasEntry::new(rect, 256.0);
426
427        assert_eq!(entry.uv_rect.x, 0.0);
428        assert_eq!(entry.uv_rect.y, 0.0);
429        assert_eq!(entry.uv_rect.width, 0.25);
430        assert_eq!(entry.uv_rect.height, 0.25);
431    }
432
433    #[test]
434    fn test_packer_insertion() {
435        let mut packer = PackerNode::new(Rect {
436            x: 0.0,
437            y: 0.0,
438            width: 256.0,
439            height: 256.0,
440        });
441
442        let key1 = AtlasKey::new("rect1");
443        let rect1 = packer.insert(key1, 64.0, 64.0);
444        assert!(rect1.is_some());
445
446        let key2 = AtlasKey::new("rect2");
447        let rect2 = packer.insert(key2, 32.0, 32.0);
448        assert!(rect2.is_some());
449
450        // Try to insert something too large
451        let key3 = AtlasKey::new("rect3");
452        let rect3 = packer.insert(key3, 512.0, 512.0);
453        assert!(rect3.is_none());
454    }
455
456    #[test]
457    fn test_atlas_basic() {
458        let context = GraphicsContext::new_owned_sync().expect("Failed to create graphics context");
459        let mut atlas = TextureAtlas::new(context, 256, wgpu::TextureFormat::Rgba8UnormSrgb);
460
461        assert_eq!(atlas.size(), 256);
462        assert_eq!(atlas.len(), 0);
463        assert!(atlas.is_empty());
464
465        // Create a 32x32 red square
466        let mut image_data = vec![0u8; 32 * 32 * 4];
467        for i in 0..(32 * 32) {
468            image_data[i * 4] = 255; // R
469            image_data[i * 4 + 1] = 0; // G
470            image_data[i * 4 + 2] = 0; // B
471            image_data[i * 4 + 3] = 255; // A
472        }
473
474        let key = AtlasKey::new("red_square");
475        let entry = atlas.insert(key, &image_data, 32, 32);
476        assert!(entry.is_some());
477        assert_eq!(atlas.len(), 1);
478
479        // Check retrieval
480        let retrieved = atlas.get(&key);
481        assert!(retrieved.is_some());
482
483        // Upload to GPU
484        atlas.upload();
485    }
486
487    #[test]
488    fn test_atlas_multiple_inserts() {
489        let context = GraphicsContext::new_owned_sync().expect("Failed to create graphics context");
490        let mut atlas = TextureAtlas::new(context, 256, wgpu::TextureFormat::Rgba8UnormSrgb);
491
492        // Insert multiple images
493        for i in 0..10 {
494            let image_data = vec![0u8; 16 * 16 * 4];
495            let key = AtlasKey::new(&format!("image_{}", i));
496            let entry = atlas.insert(key, &image_data, 16, 16);
497            assert!(entry.is_some());
498        }
499
500        assert_eq!(atlas.len(), 10);
501        atlas.upload();
502    }
503
504    #[test]
505    fn test_atlas_duplicate_key() {
506        let context = GraphicsContext::new_owned_sync().expect("Failed to create graphics context");
507        let mut atlas = TextureAtlas::new(context, 256, wgpu::TextureFormat::Rgba8UnormSrgb);
508
509        let image_data = vec![0u8; 32 * 32 * 4];
510        let key = AtlasKey::new("duplicate");
511
512        let entry1 = atlas.insert(key, &image_data, 32, 32);
513        assert!(entry1.is_some());
514
515        let entry2 = atlas.insert(key, &image_data, 32, 32);
516        assert!(entry2.is_some());
517
518        // Should only have one entry
519        assert_eq!(atlas.len(), 1);
520    }
521
522    #[test]
523    fn test_atlas_clear() {
524        let context = GraphicsContext::new_owned_sync().expect("Failed to create graphics context");
525        let mut atlas = TextureAtlas::new(context, 256, wgpu::TextureFormat::Rgba8UnormSrgb);
526
527        let image_data = vec![0u8; 32 * 32 * 4];
528        let key = AtlasKey::new("test");
529        atlas.insert(key, &image_data, 32, 32);
530
531        assert_eq!(atlas.len(), 1);
532
533        atlas.clear();
534
535        assert_eq!(atlas.len(), 0);
536        assert!(atlas.is_empty());
537    }
538}