image_dds 0.7.2

Convert images to and from compressed DDS formats
Documentation
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
use crate::{
    calculate_offset, error::CreateImageError, max_mipmap_count, mip_dimension, mip_size,
    ImageFormat, SurfaceError,
};

/// A surface with an image format known at runtime.
#[derive(Debug, PartialEq, Clone, Copy)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Surface<T> {
    /// The width of the surface in pixels.
    pub width: u32,
    /// The height of the surface in pixels.
    pub height: u32,
    /// The depth of the surface in pixels.
    /// This should be `1` for 2D surfaces.
    pub depth: u32,
    /// The number of array layers in the surface.
    /// This should be `1` for most surfaces and `6` for cube maps.
    pub layers: u32,
    /// The number of mipmaps in the surface.
    /// This should be `1` if the surface has only the base mip level.
    /// All array layers are assumed to have the same number of mipmaps.
    pub mipmaps: u32,
    /// The format of the bytes in [data](#structfield.data).
    pub image_format: ImageFormat,
    /// The combined image data ordered by layer and then mipmap without additional padding.
    ///
    /// A surface with L layers and M mipmaps would have the following layout:
    /// Layer 0 Mip 0, Layer 0 Mip 1,  ..., Layer L-1 Mip M-1
    pub data: T,
}

impl<T: AsRef<[u8]>> Surface<T> {
    /// Get the range of image data corresponding to the specified `layer`, `depth_level`, and `mipmap`.
    ///
    /// The dimensions of the returned data should be calculated using [mip_dimension].
    /// Returns [None] if the expected range is not fully contained within the buffer.
    pub fn get(&self, layer: u32, depth_level: u32, mipmap: u32) -> Option<&[u8]> {
        get_mipmap(
            self.data.as_ref(),
            (self.width, self.height, self.depth),
            self.mipmaps,
            self.image_format,
            layer,
            depth_level,
            mipmap,
        )
    }

    // TODO: Add tests for each of these cases.
    pub(crate) fn validate(&self) -> Result<(), SurfaceError> {
        if self.width == 0 || self.height == 0 || self.depth == 0 {
            return Err(SurfaceError::ZeroSizedSurface {
                width: self.width,
                height: self.height,
                depth: self.depth,
            });
        }

        let max_mipmaps = max_mipmap_count(self.width.max(self.height).max(self.depth));
        if self.mipmaps > max_mipmaps {
            return Err(SurfaceError::UnexpectedMipmapCount {
                mipmaps: self.mipmaps,
                max_mipmaps,
            });
        }

        let (block_width, block_height, block_depth) = self.image_format.block_dimensions();
        let block_size_in_bytes = self.image_format.block_size_in_bytes();
        let base_layer_size = mip_size(
            self.width as usize,
            self.height as usize,
            self.depth as usize,
            block_width as usize,
            block_height as usize,
            block_depth as usize,
            block_size_in_bytes,
        )
        .ok_or(SurfaceError::PixelCountWouldOverflow {
            width: self.width,
            height: self.height,
            depth: self.depth,
        })?;

        // TODO: validate the combined length of layers + mipmaps.
        // TODO: Calculate the correct expected size.
        if base_layer_size > self.data.as_ref().len() {
            return Err(SurfaceError::NotEnoughData {
                expected: base_layer_size,
                actual: self.data.as_ref().len(),
            });
        }

        // TODO: Return the mipmap and array offsets.
        Ok(())
    }
}

impl<T> Surface<Vec<T>> {
    /// Convert to a surface with borrowed data.
    pub fn as_ref(&self) -> Surface<&[T]> {
        Surface {
            width: self.width,
            height: self.height,
            depth: self.depth,
            layers: self.layers,
            mipmaps: self.mipmaps,
            image_format: self.image_format,
            data: self.data.as_ref(),
        }
    }
}

/// An uncompressed [ImageFormat::Rgba8Unorm] surface with 4 bytes per pixel.
#[derive(Debug, PartialEq, Clone, Copy)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SurfaceRgba8<T> {
    /// The width of the surface in pixels.
    pub width: u32,
    /// The height of the surface in pixels.
    pub height: u32,
    /// The depth of the surface in pixels.
    /// This should be `1` for 2D surfaces.
    pub depth: u32,
    /// The number of array layers in the surface.
    /// This should be `1` for most surfaces and `6` for cube maps.
    pub layers: u32,
    /// The number of mipmaps in the surface.
    /// This should be `1` if the surface has only the base mip level.
    /// All array layers are assumed to have the same number of mipmaps.
    pub mipmaps: u32,
    /// The combined image data ordered by layer and then mipmap without additional padding.
    ///
    /// A surface with L layers and M mipmaps would have the following layout:
    /// Layer 0 Mip 0, Layer 0 Mip 1,  ..., Layer L-1 Mip M-1
    pub data: T,
}

impl<T> SurfaceRgba8<Vec<T>> {
    /// Convert to a surface with borrowed data.
    pub fn as_ref(&self) -> SurfaceRgba8<&[T]> {
        SurfaceRgba8 {
            width: self.width,
            height: self.height,
            depth: self.depth,
            layers: self.layers,
            mipmaps: self.mipmaps,
            data: self.data.as_ref(),
        }
    }
}

impl<T: AsRef<[u8]>> SurfaceRgba8<T> {
    /// Get the range of 2D image data corresponding to the specified `layer`, `depth_level`, and `mipmap`.
    ///
    /// The dimensions of the returned data should be calculated using [mip_dimension].
    /// Returns [None] if the expected range is not fully contained within the buffer.
    pub fn get(&self, layer: u32, depth_level: u32, mipmap: u32) -> Option<&[u8]> {
        get_mipmap(
            self.data.as_ref(),
            (self.width, self.height, self.depth),
            self.mipmaps,
            ImageFormat::Rgba8Unorm,
            layer,
            depth_level,
            mipmap,
        )
    }

    /// Get the image corresponding to the specified `layer`, `depth_level`, and `mipmap`.
    ///
    /// Returns [None] if the expected range is not fully contained within the buffer.
    #[cfg(feature = "image")]
    pub fn get_image(&self, layer: u32, depth_level: u32, mipmap: u32) -> Option<image::RgbaImage> {
        self.get(layer, depth_level, mipmap).and_then(|data| {
            image::RgbaImage::from_raw(
                mip_dimension(self.width, mipmap),
                mip_dimension(self.height, mipmap),
                data.to_vec(),
            )
        })
    }

    pub(crate) fn validate(&self) -> Result<(), SurfaceError> {
        Surface {
            width: self.width,
            height: self.height,
            depth: self.depth,
            layers: self.layers,
            mipmaps: self.mipmaps,
            image_format: ImageFormat::Rgba8Unorm,
            data: self.data.as_ref(),
        }
        .validate()
    }
}

#[cfg(feature = "image")]
impl<'a> SurfaceRgba8<&'a [u8]> {
    /// Create a 2D view over the data in `image` without any copies.
    pub fn from_image(image: &'a image::RgbaImage) -> Self {
        SurfaceRgba8 {
            width: image.width(),
            height: image.height(),
            depth: 1,
            layers: 1,
            mipmaps: 1,
            data: image.as_raw(),
        }
    }

    /// Create a 2D view with layers over the data in `image` without any copies.
    ///
    /// Array layers should be stacked vertically in `image` with an overall height `height*layers`.
    pub fn from_image_layers(image: &'a image::RgbaImage, layers: u32) -> Self {
        SurfaceRgba8 {
            width: image.width(),
            height: image.height() / layers,
            depth: 1,
            layers,
            mipmaps: 1,
            data: image.as_raw(),
        }
    }

    /// Create a 3D view over the data in `image` without any copies.
    ///
    /// Depth slices should be stacked vertically in `image` with an overall height `height*depth`.
    pub fn from_image_depth(image: &'a image::RgbaImage, depth: u32) -> Self {
        SurfaceRgba8 {
            width: image.width(),
            height: image.height() / depth,
            depth,
            layers: 1,
            mipmaps: 1,
            data: image.as_raw(),
        }
    }
}

#[cfg(feature = "image")]
impl<T: AsRef<[u8]>> SurfaceRgba8<T> {
    /// Create an image for all layers and depth slices for the given `mipmap`.
    ///
    /// Array layers and depth slices are arranged vertically from top to bottom.
    pub fn to_image(&self, mipmap: u32) -> Result<image::RgbaImage, CreateImageError> {
        // Mipmaps have different dimensions.
        // A single 2D image can only represent data from a single mip level across layers.
        let mut image_data = Vec::new();
        for layer in 0..self.layers {
            for level in 0..self.depth {
                let data = self.get(layer, level, mipmap).unwrap();
                image_data.extend_from_slice(&data);
            }
        }
        let data_length = image_data.len();

        // Arrange depth and array layers vertically.
        // This layout allows copyless conversions to an RGBA8 surface.
        let width = mip_dimension(self.width, mipmap);
        let height =
            mip_dimension(self.height, mipmap) * mip_dimension(self.depth, mipmap) * self.layers;

        image::RgbaImage::from_raw(width, height, image_data).ok_or(
            crate::CreateImageError::InvalidSurfaceDimensions {
                width,
                height,
                data_length,
            },
        )
    }
}

#[cfg(feature = "image")]
impl SurfaceRgba8<Vec<u8>> {
    /// Create an image for all layers and depth slices without copying.
    ///
    /// Fails if the surface has more than one mipmap.
    /// Array layers and depth slices are arranged vertically from top to bottom.
    pub fn into_image(self) -> Result<image::RgbaImage, CreateImageError> {
        // Arrange depth and array layers vertically.
        // This layout allows copyless conversions to an RGBA8 surface.
        let width = self.width;
        let height = self.height * self.depth * self.layers;

        if self.mipmaps > 1 {
            return Err(CreateImageError::UnexpectedMipmapCount {
                mipmaps: self.mipmaps,
                max_mipmaps: 1,
            });
        }

        let data_length = self.data.len();
        image::RgbaImage::from_raw(width, height, self.data).ok_or(
            crate::CreateImageError::InvalidSurfaceDimensions {
                width,
                height,
                data_length,
            },
        )
    }
}

/// An uncompressed [ImageFormat::Rgba32Float] surface with 16 bytes per pixel.
#[derive(Debug, PartialEq, Clone, Copy)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SurfaceRgba32Float<T> {
    /// The width of the surface in pixels.
    pub width: u32,
    /// The height of the surface in pixels.
    pub height: u32,
    /// The depth of the surface in pixels.
    /// This should be `1` for 2D surfaces.
    pub depth: u32,
    /// The number of array layers in the surface.
    /// This should be `1` for most surfaces and `6` for cube maps.
    pub layers: u32,
    /// The number of mipmaps in the surface.
    /// This should be `1` if the surface has only the base mip level.
    /// All array layers are assumed to have the same number of mipmaps.
    pub mipmaps: u32,
    /// The combined `f32` image data ordered by layer and then mipmap without additional padding.
    ///
    /// A surface with L layers and M mipmaps would have the following layout:
    /// Layer 0 Mip 0, Layer 0 Mip 1,  ..., Layer L-1 Mip M-1
    pub data: T,
}

impl<T> SurfaceRgba32Float<Vec<T>> {
    /// Convert to a surface with borrowed data.
    pub fn as_ref(&self) -> SurfaceRgba32Float<&[T]> {
        SurfaceRgba32Float {
            width: self.width,
            height: self.height,
            depth: self.depth,
            layers: self.layers,
            mipmaps: self.mipmaps,
            data: self.data.as_ref(),
        }
    }
}

impl<T: AsRef<[f32]>> SurfaceRgba32Float<T> {
    /// Get the range of 2D image data corresponding to the specified `layer`, `depth_level`, and `mipmap`.
    ///
    /// The dimensions of the returned data should be calculated using [mip_dimension].
    /// Returns [None] if the expected range is not fully contained within the buffer.
    pub fn get(&self, layer: u32, depth_level: u32, mipmap: u32) -> Option<&[f32]> {
        get_mipmap(
            self.data.as_ref(),
            (self.width, self.height, self.depth),
            self.mipmaps,
            ImageFormat::Rgba32Float,
            layer,
            depth_level,
            mipmap,
        )
    }

    /// Get the image corresponding to the specified `layer`, `depth_level`, and `mipmap`.
    ///
    /// Returns [None] if the expected range is not fully contained within the buffer.
    #[cfg(feature = "image")]
    pub fn get_image(
        &self,
        layer: u32,
        depth_level: u32,
        mipmap: u32,
    ) -> Option<image::Rgba32FImage> {
        self.get(layer, depth_level, mipmap).and_then(|data| {
            image::Rgba32FImage::from_raw(
                mip_dimension(self.width, mipmap),
                mip_dimension(self.height, mipmap),
                data.to_vec(),
            )
        })
    }

    pub(crate) fn validate(&self) -> Result<(), SurfaceError> {
        Surface {
            width: self.width,
            height: self.height,
            depth: self.depth,
            layers: self.layers,
            mipmaps: self.mipmaps,
            image_format: ImageFormat::Rgba32Float,
            data: bytemuck::cast_slice(self.data.as_ref()),
        }
        .validate()
    }
}

#[cfg(feature = "image")]
impl<'a> SurfaceRgba32Float<&'a [f32]> {
    /// Create a 2D view over the data in `image` without any copies.
    pub fn from_image(image: &'a image::Rgba32FImage) -> Self {
        SurfaceRgba32Float {
            width: image.width(),
            height: image.height(),
            depth: 1,
            layers: 1,
            mipmaps: 1,
            data: image.as_raw(),
        }
    }

    /// Create a 2D view with layers over the data in `image` without any copies.
    ///
    /// Array layers should be stacked vertically in `image` with an overall height `height*layers`.
    pub fn from_image_layers(image: &'a image::Rgba32FImage, layers: u32) -> Self {
        SurfaceRgba32Float {
            width: image.width(),
            height: image.height() / layers,
            depth: 1,
            layers,
            mipmaps: 1,
            data: image.as_raw(),
        }
    }

    /// Create a 3D view over the data in `image` without any copies.
    ///
    /// Depth slices should be stacked vertically in `image` with an overall height `height*depth`.
    pub fn from_image_depth(image: &'a image::Rgba32FImage, depth: u32) -> Self {
        SurfaceRgba32Float {
            width: image.width(),
            height: image.height() / depth,
            depth,
            layers: 1,
            mipmaps: 1,
            data: image.as_raw(),
        }
    }
}

#[cfg(feature = "image")]
impl<T: AsRef<[f32]>> SurfaceRgba32Float<T> {
    /// Create an image for all layers and depth slices for the given `mipmap`.
    ///
    /// Array layers are arranged vertically from top to bottom.
    pub fn to_image(&self, mipmap: u32) -> Result<image::Rgba32FImage, CreateImageError> {
        // Mipmaps have different dimensions.
        // A single 2D image can only represent data from a single mip level across layers.
        let mut image_data = Vec::new();
        for layer in 0..self.layers {
            for level in 0..self.depth {
                let data = self.get(layer, level, mipmap).unwrap();
                image_data.extend_from_slice(&data);
            }
        }
        let data_length = image_data.len();

        // Arrange depth slices horizontally and array layers vertically.
        let width = mip_dimension(self.width, mipmap) * mip_dimension(self.depth, mipmap);
        let height = mip_dimension(self.height, mipmap) * self.layers;

        image::Rgba32FImage::from_raw(width, height, image_data).ok_or(
            crate::CreateImageError::InvalidSurfaceDimensions {
                width,
                height,
                data_length,
            },
        )
    }
}

#[cfg(feature = "image")]
impl SurfaceRgba32Float<Vec<f32>> {
    /// Create an image for all layers and depth slices without copying.
    ///
    /// Fails if the surface has more than one mipmap.
    /// Array layers and depth slices are arranged vertically from top to bottom.
    pub fn into_image(self) -> Result<image::Rgba32FImage, CreateImageError> {
        // Arrange depth and array layers vertically.
        // This layout allows copyless conversions to an RGBA8 surface.
        let width = self.width;
        let height = self.height * self.depth * self.layers;

        if self.mipmaps > 1 {
            return Err(CreateImageError::UnexpectedMipmapCount {
                mipmaps: self.mipmaps,
                max_mipmaps: 1,
            });
        }

        let data_length = self.data.len();
        image::Rgba32FImage::from_raw(width, height, self.data).ok_or(
            crate::CreateImageError::InvalidSurfaceDimensions {
                width,
                height,
                data_length,
            },
        )
    }
}

// TODO: Add tests for this.
fn get_mipmap<T>(
    data: &[T],
    dimensions: (u32, u32, u32),
    mipmaps: u32,
    format: ImageFormat,
    layer: u32,
    depth_level: u32,
    mipmap: u32,
) -> Option<&[T]> {
    let (width, height, depth) = dimensions;

    let block_size_in_bytes = format.block_size_in_bytes();
    let block_dimensions = format.block_dimensions();

    // TODO: Create an error for failed offset calculations?
    let offset_in_bytes = calculate_offset(
        layer,
        depth_level,
        mipmap,
        (width, height, depth),
        block_dimensions,
        block_size_in_bytes,
        mipmaps,
    )?;

    // The returned slice is always 2D.
    let mip_width = mip_dimension(width, mipmap);
    let mip_height = mip_dimension(height, mipmap);

    // TODO: Create an error for overflow?
    let size_in_bytes = mip_size(
        mip_width as usize,
        mip_height as usize,
        1,
        block_dimensions.0 as usize,
        block_dimensions.1 as usize,
        block_dimensions.2 as usize,
        block_size_in_bytes,
    )?;

    let start = offset_in_bytes / std::mem::size_of::<T>();
    let count = size_in_bytes / std::mem::size_of::<T>();
    data.get(start..start + count)
}