Skip to main content

image_atlas/
image.rs

1use std::{error, fmt};
2
3use crate::{RequestRect, solve_offline, solve_online, Bin};
4
5/// The packing algorithm used for texture atlas generation.
6#[repr(C)]
7#[derive(Clone, Copy, PartialEq, Eq, Hash, Default, Debug)]
8#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
9pub enum AtlasAlgorithm {
10    /// Offline packing algorithm (default). produces a more optimal layout.
11    #[default]
12    Offline,
13    /// Online packing algorithm. Faster than the offline algorithm, but the resulting layout may not be optimal.
14    Online,
15}
16
17/// The padding strategy applied between texture entries.
18#[repr(C)]
19#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
20#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
21pub enum AtlasPadding {
22    /// No padding or a fixed pixel padding width.
23    Padding(u32),
24    /// Grid/block-based padding. The block size must be a power of two.
25    Block(u32),
26}
27
28impl Default for AtlasPadding {
29    fn default() -> Self {
30        AtlasPadding::Padding(Default::default())
31    }
32}
33
34/// The mipmap generation option for the texture atlas.
35#[repr(C)]
36#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
37#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
38pub enum AtlasMipOption {
39    /// Do not generate mipmaps. Uses the specified padding strategy.
40    NoMip(AtlasPadding),
41    /// Generate mipmaps using the specified padding strategy and sampling filter.
42    Mip(AtlasPadding, image::imageops::FilterType),
43}
44
45impl Default for AtlasMipOption {
46    fn default() -> Self {
47        AtlasMipOption::NoMip(Default::default())
48    }
49}
50
51/// The texture wrapping/tiling behavior used during padding resampling.
52#[repr(C)]
53#[derive(Clone, Copy, PartialEq, Eq, Hash, Default, Debug)]
54#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
55pub enum AtlasEntryMipOption {
56    // Clamp to edge. Pixels outside the texture boundaries take the color of the edge pixels.
57    #[default]
58    Clamp,
59    /// Repeat the texture horizontally and vertically.
60    Repeat,
61    /// Repeat the texture, but flip it horizontally and vertically at every integer boundary.
62    Mirror,
63}
64
65/// An individual texture entry configuration to be packed into the atlas.
66#[derive(Clone, PartialEq, Eq, Default, Debug)]
67#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
68pub struct AtlasEntry<I: image::GenericImageView> {
69    /// The source image.
70    pub texture: I,
71    /// The tiling/wrapping behavior used when bleeding into the padding space.
72    pub mip: AtlasEntryMipOption,
73}
74
75/// Configuration descriptor for generating a texture atlas.
76#[derive(Clone, PartialEq, Eq, Default, Debug)]
77pub struct AtlasDescriptor<'a, I: image::GenericImageView> {
78    /// The width and height of the generated atlas page (pages are always square).
79    pub size: u32,
80    /// The mipmap configuration and sampling settings.
81    pub mip: AtlasMipOption,
82    /// A slice of image entries to pack into the atlas.
83    pub entries: &'a [AtlasEntry<I>],
84    /// The bin-packing algorithm to use.
85    pub algorithm: AtlasAlgorithm,
86}
87
88/// Creates a new texture atlas from the provided descriptor.
89///
90/// # Errors
91///
92/// Returns an [`AtlasError`] if:
93/// - Mipmapping is enabled but `size` is not a power of two ([`AtlasError::InvalidSize`]).
94/// - [`AtlasPadding::Block`] is used but the block size is not a power of two ([`AtlasError::InvalidBlockSize`]).
95/// - The packing algorithm fails to fit the textures into the specified size constraints ([`AtlasError::Packing`]).
96///
97/// # Examples
98///
99/// ```rust
100/// use image_atlas::image::*;
101/// 
102/// let descriptor = &AtlasDescriptor {
103///     size: 2048,
104///     mip: AtlasMipOption::Mip(AtlasPadding::Block(32), image::imageops::FilterType::Lanczos3),
105///     entries: &[AtlasEntry {
106///         texture: image::RgbImage::new(512, 512),  // Your texture here.
107///         mip: AtlasEntryMipOption::Clamp,
108///     }],
109///     algorithm: AtlasAlgorithm::Offline,
110/// };
111/// 
112/// let atlas = create_atlas(&descriptor).expect("Failed to generate texture atlas");
113/// 
114/// let texcoord = &atlas.texcoords[0];
115/// let texture = &atlas.textures[texcoord.page_id].mip_maps[0];
116/// ```
117#[rustfmt::skip]
118pub fn create_atlas<I>(desc: &AtlasDescriptor<'_, I>) -> Result<Atlas<I::Pixel>, AtlasError>
119where
120    I: image::GenericImage,
121    I::Pixel: 'static,
122{
123    match desc.mip {
124        AtlasMipOption::NoMip(AtlasPadding::Padding(_)) => create_atlas_with_padding(desc),
125        AtlasMipOption::Mip(AtlasPadding::Padding(_), _) => create_atlas_with_padding(desc),
126        AtlasMipOption::NoMip(AtlasPadding::Block(_)) => create_atlas_with_block(desc),
127        AtlasMipOption::Mip(AtlasPadding::Block(_), _) => create_atlas_with_block(desc),
128    }
129}
130
131fn create_atlas_with_padding<I>(desc: &AtlasDescriptor<'_, I>) -> Result<Atlas<I::Pixel>, AtlasError>
132where
133    I: image::GenericImage,
134    I::Pixel: 'static,
135{
136    // check if size is power of two when mip map is enabled
137    if let AtlasMipOption::Mip(_, _) = desc.mip && !desc.size.is_power_of_two() {
138        return Err(AtlasError::InvalidSize(desc.size));
139    }
140
141    // get padding size from mip option
142    let padding = match desc.mip {
143        AtlasMipOption::NoMip(AtlasPadding::Padding(padding)) => padding,
144        AtlasMipOption::Mip(AtlasPadding::Padding(padding), _) => padding,
145        _ => unreachable!(),
146    };
147
148    let mut requests = Vec::new();
149    for (i, entry) in desc.entries.iter().enumerate() {
150        let request = RequestRect {
151            id: i,
152            width: entry.texture.width() + padding * 2,
153            height: entry.texture.height() + padding * 2,
154        };
155        requests.push(request);
156    }
157    let pages = solve_packing(desc.algorithm, &requests, desc.size).ok_or(AtlasError::Packing)?;
158    let page_count = pages.len();
159    let packed_locations = pages.into_iter()
160        .enumerate()
161        .flat_map(|(page_id, page)| {
162            page.occupied_rects.into_iter()
163                .map(move |rect| (page_id, rect.id, rect.rect))
164        })
165        .collect::<Vec<_>>();
166
167    let mut texcoords = vec![Texcoord::default(); requests.len()];
168    for (page_id, rect_id, rect) in &packed_locations {
169        let texcoord = Texcoord {
170            page_id: *page_id,
171            min_x: rect.x + padding,
172            min_y: rect.y + padding,
173            max_x: rect.x + rect.width - padding,
174            max_y: rect.y + rect.height - padding,
175            size: desc.size,
176        };
177        texcoords[*rect_id] = texcoord;
178    }
179
180    // get mip level count from mip option
181    let mip_level_count = if let AtlasMipOption::Mip(_, _) = desc.mip { desc.size.ilog2() + 1 } else { 1 };
182    let mut textures = vec![Texture::new(desc.size, mip_level_count); page_count];
183    for (page_id, rect_id, rect) in &packed_locations {
184        let entry = &desc.entries[*rect_id];
185        let src = resample_entry(&entry.texture, entry.mip, padding, padding, rect.width, rect.height);
186        let target = &mut textures[*page_id].mip_maps[0];
187        image::imageops::replace(target, &src, rect.x as i64, rect.y as i64);
188    }
189
190    // generate mip maps if mip option is enabled
191    if let AtlasMipOption::Mip(_, filter) = desc.mip {
192        for mip_level in 1..mip_level_count {
193            let size = desc.size >> mip_level;
194
195            for texture in &mut textures {
196                let src = &texture.mip_maps[0];
197
198                let mip_map = image::imageops::resize(src, size, size, filter);
199
200                let target = &mut texture.mip_maps[mip_level as usize];
201                image::imageops::replace(target, &mip_map, 0, 0);
202            }
203        }
204    }
205
206    Ok(Atlas {
207        page_count,
208        size: desc.size,
209        mip_level_count,
210        textures,
211        texcoords,
212    })
213}
214
215fn create_atlas_with_block<I>(desc: &AtlasDescriptor<'_, I>) -> Result<Atlas<I::Pixel>, AtlasError>
216where
217    I: image::GenericImage,
218    I::Pixel: 'static,
219{
220    // check if size is power of two when mip map is enabled
221    if let AtlasMipOption::Mip(_, _) = desc.mip && !desc.size.is_power_of_two() {
222        return Err(AtlasError::InvalidSize(desc.size));
223    }
224
225    let block_size = match desc.mip {
226        AtlasMipOption::NoMip(AtlasPadding::Block(block_size)) => block_size,
227        AtlasMipOption::Mip(AtlasPadding::Block(block_size), _) => block_size,
228        _ => unreachable!(),
229    };
230    if !block_size.is_power_of_two() {
231        return Err(AtlasError::InvalidBlockSize(block_size));
232    }
233    let padding = block_size >> 1;
234
235    let mut requests = Vec::new();
236    for (i, entry) in desc.entries.iter().enumerate() {
237        let request = RequestRect {
238            id: i,
239            width: ((entry.texture.width() + block_size) as f32 / block_size as f32).ceil() as u32,
240            height: ((entry.texture.height() + block_size) as f32 / block_size as f32).ceil() as u32,
241        };
242        requests.push(request);
243    }
244    let pages = solve_packing(desc.algorithm, &requests, desc.size).ok_or(AtlasError::Packing)?;
245    let page_count = pages.len();
246    let packed_locations = pages.into_iter()
247        .enumerate()
248        .flat_map(|(page_id, page)| {
249            page.occupied_rects.into_iter()
250                .map(move |rect| (page_id, rect.id, rect.rect))
251        })
252        .collect::<Vec<_>>();
253
254    let mut texcoords = vec![Texcoord::default(); requests.len()];
255    for (page_id, rect_id, rect) in &packed_locations {
256        let texture = &desc.entries[*rect_id].texture;
257
258        let texcoord = Texcoord {
259            page_id: *page_id,
260            min_x: rect.x * block_size + padding,
261            min_y: rect.y * block_size + padding,
262            max_x: rect.x * block_size + padding + texture.width(),
263            max_y: rect.y * block_size + padding + texture.height(),
264            size: desc.size,
265        };
266        texcoords[*rect_id] = texcoord;
267    }
268
269    // get mip level count from mip option
270    let mip_level_count = if let AtlasMipOption::Mip(_, _) = desc.mip { block_size.ilog2() + 1 } else { 1 };
271    let mut textures = vec![Texture::new(desc.size, mip_level_count); page_count];
272    for (page_id, rect_id, rect) in &packed_locations {
273        let entry = &desc.entries[*rect_id];
274        let src = resample_entry(&entry.texture, entry.mip, padding, padding, rect.width * block_size, rect.height * block_size);
275        let target = &mut textures[*page_id].mip_maps[0];
276        image::imageops::replace(target, &src, (rect.x * block_size) as i64, (rect.y * block_size) as i64);
277    }
278
279    // generate mip maps if mip option is enabled
280    if let AtlasMipOption::Mip(_, filter) = desc.mip {
281        for (page_id, rect_id, rect) in &packed_locations {
282            let entry = &desc.entries[*rect_id];
283            let src = resample_entry(&entry.texture, entry.mip, padding, padding, rect.width * block_size, rect.height * block_size);
284
285            for mip_level in 1..mip_level_count {
286                let width = src.width() >> mip_level;
287                let height = src.height() >> mip_level;
288                let mip_map = image::imageops::resize(&src, width, height, filter);
289
290                let target = &mut textures[*page_id].mip_maps[mip_level as usize];
291                let x = rect.x as i64 * (block_size >> mip_level) as i64;
292                let y = rect.y as i64 * (block_size >> mip_level) as i64;
293                image::imageops::replace(target, &mip_map, x, y);
294            }
295        }
296    }
297
298    Ok(Atlas {
299        page_count,
300        size: desc.size,
301        mip_level_count,
302        textures,
303        texcoords,
304    })
305}
306
307#[inline]
308fn solve_packing(
309    algorithm: AtlasAlgorithm,
310    requests: &[RequestRect],
311    size: u32
312) -> Option<Vec<Bin>> {
313    match algorithm {
314        AtlasAlgorithm::Offline => solve_offline(requests, size, size, false),
315        AtlasAlgorithm::Online => solve_online(requests, size, size, false),
316    }
317}
318
319#[inline]
320#[rustfmt::skip]
321fn resample_entry<I>(
322    src: &I,
323    mip: AtlasEntryMipOption,
324    shift_x: u32,
325    shift_y: u32,
326    width: u32,
327    height: u32,
328) -> image::ImageBuffer<I::Pixel, Vec<<I::Pixel as image::Pixel>::Subpixel>>
329where
330    I: image::GenericImage,
331{
332    let mut target = image::ImageBuffer::new(width, height);
333    match mip {
334        AtlasEntryMipOption::Clamp => {
335            for x in 0..width {
336                for y in 0..height {
337                    let sx = u32::min(x.saturating_sub(shift_x), src.width() - 1);
338                    let sy = u32::min(y.saturating_sub(shift_y), src.height() - 1);
339                    *target.get_pixel_mut(x, y) = src.get_pixel(sx, sy);
340                }
341            }
342        }
343        AtlasEntryMipOption::Repeat => {
344            for x in 0..width {
345                for y in 0..height {
346                    let sx = x.saturating_sub(shift_x).rem_euclid(src.width());
347                    let sy = y.saturating_sub(shift_y).rem_euclid(src.height());
348                    *target.get_pixel_mut(x, y) = src.get_pixel(sx, sy);
349                }
350            }
351        }
352        AtlasEntryMipOption::Mirror => {
353            for x in 0..width {
354                for y in 0..height {
355                    let mut sx = x.saturating_sub(shift_x).rem_euclid(src.width());
356                    let mut sy = y.saturating_sub(shift_y).rem_euclid(src.height());
357                    let xx = x.saturating_sub(shift_x).div_euclid(src.width());
358                    let yy = y.saturating_sub(shift_y).div_euclid(src.height());
359                    if xx & 1 == 0 { sx = src.width() - 1 - sx; }
360                    if yy & 1 == 0 { sy = src.height() - 1 - sy; }
361                    *target.get_pixel_mut(x, y) = src.get_pixel(sx, sy);
362                }
363            }
364        }
365    }
366    target
367}
368
369/// The generated texture atlas result.
370#[derive(Clone, Default)]
371pub struct Atlas<P: image::Pixel> {
372    /// The number of total texture pages generated.
373    pub page_count: usize,
374    /// The width and height of each atlas page.
375    pub size: u32,
376    /// The number of mipmap levels per texture (1 means no mipmaps).
377    pub mip_level_count: u32,
378    /// The generated target textures container.
379    pub textures: Vec<Texture<P>>,
380    /// The calculated texture coordinates mapped to the input entries in the same order.
381    pub texcoords: Vec<Texcoord>,
382}
383
384impl<P> fmt::Debug for Atlas<P>
385where
386    P: image::Pixel + fmt::Debug,
387    P::Subpixel: fmt::Debug,
388{
389    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
390        f.debug_struct("Atlas")
391            .field("page_count", &self.page_count)
392            .field("size", &self.size)
393            .field("mip_level_count", &self.mip_level_count)
394            .field("textures", &self.textures)
395            .field("texcoords", &self.texcoords)
396            .finish()
397    }
398}
399
400/// A container representing an individual output texture layer within the atlas.
401#[derive(Clone, Default)]
402pub struct Texture<P: image::Pixel> {
403    /// The width and height of the base texture level.
404    pub size: u32,
405    /// The total number of generated mipmap levels.
406    pub mip_level_count: u32,
407    /// A collection of buffers representing each mipmap level.
408    pub mip_maps: Vec<image::ImageBuffer<P, Vec<P::Subpixel>>>,
409}
410
411impl<P: image::Pixel> Texture<P> {
412    #[inline]
413    fn new(size: u32, mip_level_count: u32) -> Self {
414        let mip_maps = (0..mip_level_count)
415            .map(|mip_level| size >> mip_level)
416            .map(|size| image::ImageBuffer::new(size, size))
417            .collect::<Vec<_>>();
418        Self {
419            size,
420            mip_level_count,
421            mip_maps,
422        }
423    }
424}
425
426impl<P> fmt::Debug for Texture<P>
427where
428    P: image::Pixel + fmt::Debug,
429    P::Subpixel: fmt::Debug,
430{
431    #[inline]
432    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
433        f.debug_struct("Texture")
434            .field("size", &self.size)
435            .field("mip_level_count", &self.mip_level_count)
436            .field("mip_maps", &self.mip_maps)
437            .finish()
438    }
439}
440
441/// Pixel-space texture coordinates representing the bounding box of a packed entry.
442///
443/// Use [`Texcoord::to_f32`] or [`Texcoord::to_f64`] to convert these to normalized UV coordinates.
444#[repr(C)]
445#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
446#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
447pub struct Texcoord {
448    /// The page index inside the [`Atlas::textures`] array.
449    pub page_id: usize,
450    /// The minimum X boundary in pixel units.
451    pub min_x: u32,
452    /// The minimum Y boundary in pixel units.
453    pub min_y: u32,
454    /// The maximum X boundary in pixel units.
455    pub max_x: u32,
456    /// The maximum Y boundary in pixel units.
457    pub max_y: u32,
458    /// The total width/height size of the page (used for normalization).
459    pub size: u32,
460}
461
462impl Texcoord {
463    /// Converts pixel-space coordinates into normalized `f32` UV coordinates.
464    #[inline]
465    pub fn to_f32(self) -> Texcoord32 {
466        Texcoord32 {
467            page_id: self.page_id,
468            min_x: self.min_x as f32 / self.size as f32,
469            min_y: self.min_y as f32 / self.size as f32,
470            max_x: self.max_x as f32 / self.size as f32,
471            max_y: self.max_y as f32 / self.size as f32,
472        }
473    }
474
475    /// Converts pixel-space coordinates into normalized `f64` UV coordinates.
476    #[inline]
477    pub fn to_f64(self) -> Texcoord64 {
478        Texcoord64 {
479            page_id: self.page_id,
480            min_x: self.min_x as f64 / self.size as f64,
481            min_y: self.min_y as f64 / self.size as f64,
482            max_x: self.max_x as f64 / self.size as f64,
483            max_y: self.max_y as f64 / self.size as f64,
484        }
485    }
486}
487
488/// Normalized 0.0 to 1.0 texture coordinates using `f32`.
489#[repr(C)]
490#[derive(Clone, Copy, PartialEq, Default, Debug)]
491#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
492pub struct Texcoord32 {
493    /// The page index inside the [`Atlas::textures`] array.
494    pub page_id: usize,
495    /// The minimum U/X position (normalized).
496    pub min_x: f32,
497    /// The minimum V/Y position (normalized).
498    pub min_y: f32,
499    /// The maximum U/X position (normalized).
500    pub max_x: f32,
501    /// The maximum V/Y position (normalized).
502    pub max_y: f32,
503}
504
505impl From<Texcoord> for Texcoord32 {
506    #[inline]
507    fn from(value: Texcoord) -> Self {
508        value.to_f32()
509    }
510}
511
512/// Normalized 0.0 to 1.0 texture coordinates using `f64`.
513#[repr(C)]
514#[derive(Clone, Copy, PartialEq, Default, Debug)]
515#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
516pub struct Texcoord64 {
517    /// The page index inside the [`Atlas::textures`] array.
518    pub page_id: usize,
519    /// The minimum U/X position (normalized).
520    pub min_x: f64,
521    /// The minimum V/Y position (normalized).
522    pub min_y: f64,
523    /// The maximum U/X position (normalized).
524    pub max_x: f64,
525    /// The maximum V/Y position (normalized).
526    pub max_y: f64,
527}
528
529impl From<Texcoord> for Texcoord64 {
530    #[inline]
531    fn from(value: Texcoord) -> Self {
532        value.to_f64()
533    }
534}
535
536/// Errors that can occur during the texture atlas generation process.
537#[derive(Debug)]
538pub enum AtlasError {
539    /// The requested atlas size is not a power of two. Contains the invalid size value.
540    InvalidSize(u32),
541    /// The requested padding block size is not a power of two. Contains the invalid block size value.
542    InvalidBlockSize(u32),
543    /// The packing solver failed. This usually means an entry's dimension is too large to fit into the specified atlas size.
544    Packing,
545}
546
547impl fmt::Display for AtlasError {
548    #[rustfmt::skip]
549    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
550        match self {
551            AtlasError::InvalidSize(size) => write!(f, "size is not power of two: {}.", size),
552            AtlasError::InvalidBlockSize(block_size) => write!(f, "block size is not power of two: {}.", block_size),
553            AtlasError::Packing => write!(f, "packing error occurred. entry width and/or height is too large."),
554        }
555    }
556}
557
558impl error::Error for AtlasError {}