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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
use std::num::{NonZeroU32, NonZeroU8};
use bitflags::bitflags;
use crate::header::{Caps2, Header, ResourceDimension};
use crate::DecodingError;
use crate::{
util::{get_mipmap_size, NON_ZERO_U32_ONE},
LayoutError, PixelInfo, Size,
};
pub trait DataRegion {
/// The number of bytes this object occupies in the data section of a DDS file.
///
/// It is guaranteed that `self.offset() + self.len() <= u64::MAX`.
fn data_len(&self) -> u64;
/// The byte offset of this object in the data section of a DDS file.
fn data_offset(&self) -> u64;
/// The byte offset of the byte after this object in the data section of a DDS file.
///
/// This is equivalent to `self.offset() + self.len()`.
fn data_end(&self) -> u64 {
self.data_offset() + self.data_len()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SurfaceDescriptor {
width: NonZeroU32,
height: NonZeroU32,
offset: u64,
len: u64,
}
impl SurfaceDescriptor {
/// Internal constructor.
///
/// This **assumes** that the arguments are valid and only performs checks
/// in debug.
fn new(width: NonZeroU32, height: NonZeroU32, offset: u64, len: u64) -> Self {
debug_assert!(len > 0);
debug_assert!(offset.checked_add(len).is_some());
Self {
width,
height,
offset,
len,
}
}
pub fn width(&self) -> u32 {
self.width.get()
}
pub fn height(&self) -> u32 {
self.height.get()
}
pub fn size(&self) -> Size {
Size::new(self.width(), self.height())
}
}
impl DataRegion for SurfaceDescriptor {
fn data_len(&self) -> u64 {
self.len
}
fn data_offset(&self) -> u64 {
self.offset
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct VolumeDescriptor {
width: NonZeroU32,
height: NonZeroU32,
depth: NonZeroU32,
offset: u64,
slice_len: u64,
}
impl VolumeDescriptor {
fn new(
width: NonZeroU32,
height: NonZeroU32,
depth: NonZeroU32,
offset: u64,
slice_len: u64,
) -> Self {
debug_assert!(slice_len > 0);
// check that `offset + len` does not overflow
debug_assert!(slice_len
.checked_mul(depth.get() as u64)
.and_then(|len| offset.checked_add(len))
.is_some());
Self {
width,
height,
depth,
offset,
slice_len,
}
}
pub fn width(&self) -> u32 {
self.width.get()
}
pub fn height(&self) -> u32 {
self.height.get()
}
pub fn depth(&self) -> u32 {
self.depth.get()
}
pub fn size(&self) -> Size {
Size::new(self.width(), self.height())
}
pub fn get_depth_slice(&self, depth: u32) -> Option<SurfaceDescriptor> {
if depth < self.depth() {
Some(SurfaceDescriptor {
width: self.width,
height: self.height,
offset: self.offset + depth as u64 * self.slice_len,
len: self.slice_len,
})
} else {
None
}
}
/// Iterates over all depth slices of the volume.
///
/// To get the depth value of a slice, use `.enumerate()`. Example:
///
/// ```no_run
/// # use dds::{VolumeDescriptor, DataRegion};
/// # fn get_volume() -> VolumeDescriptor { todo!() }
/// let volume: VolumeDescriptor = get_volume();
/// for (depth, slice) in volume.iter_depth_slices().enumerate() {
/// println!("Slice {} starts at {}", depth, slice.data_offset());
/// }
/// ```
pub fn iter_depth_slices(&self) -> impl Iterator<Item = SurfaceDescriptor> {
let Self {
width,
height,
offset,
slice_len,
..
} = *self;
(0..self.depth()).map(move |depth| SurfaceDescriptor {
width,
height,
offset: offset + depth as u64 * slice_len,
len: slice_len,
})
}
}
impl DataRegion for VolumeDescriptor {
fn data_len(&self) -> u64 {
// Cannot overflow. See `VolumeDescriptor::new`.
self.slice_len * self.depth() as u64
}
fn data_offset(&self) -> u64 {
self.offset
}
}
fn to_short_len(len: u64) -> Option<NonZeroU32> {
len.try_into().ok().and_then(NonZeroU32::new)
}
fn get_texture_len(
width: NonZeroU32,
height: NonZeroU32,
mipmaps: NonZeroU8,
pixels: PixelInfo,
) -> Option<u64> {
let size = Size::new(width.get(), height.get());
let mut len: u64 = 0;
for level in 0..mipmaps.get() {
let mip_len = pixels.surface_bytes(size.get_mipmap(level))?;
len = len.checked_add(mip_len)?;
}
Some(len)
}
/// A 2D texture with mipmaps (if any).
///
/// See [`DataLayout::Texture`] for more information.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Texture {
width: NonZeroU32,
height: NonZeroU32,
mipmaps: NonZeroU8,
pixels: PixelInfo,
offset_index: u32,
// A cache for data length. This is used to avoid recomputing the length
// when the length is isn't too large.
short_len: Option<NonZeroU32>,
}
impl Texture {
/// Creates a new texture at offset 0.
fn create_at_offset_0(
width: NonZeroU32,
height: NonZeroU32,
mipmaps: NonZeroU8,
pixels: PixelInfo,
) -> Result<Self, LayoutError> {
// Check that length and all other calculations do not overflow
let len =
get_texture_len(width, height, mipmaps, pixels).ok_or(LayoutError::DataLayoutTooBig)?;
Ok(Self {
width,
height,
mipmaps,
pixels,
offset_index: 0,
short_len: to_short_len(len),
})
}
pub fn pixel_info(&self) -> PixelInfo {
self.pixels
}
/// The level 0 size of this texture.
fn size(&self) -> Size {
Size::new(self.width.get(), self.height.get())
}
/// The level 0 mipmap of this texture.
pub fn main(&self) -> SurfaceDescriptor {
// PANIC SAFETY: This cannot overflow, because we already checked in the constructor
let len = self.pixels.surface_bytes(self.size()).unwrap();
SurfaceDescriptor::new(self.width, self.height, self.data_offset(), len)
}
pub fn mipmaps(&self) -> u8 {
self.mipmaps.get()
}
pub fn get(&self, level: u8) -> Option<SurfaceDescriptor> {
self.iter_mips().nth(level as usize)
}
pub fn iter_mips(&self) -> impl Iterator<Item = SurfaceDescriptor> {
let mut offset = self.data_offset();
let size_0 = self.size();
let pixels = self.pixels;
(0..self.mipmaps.get()).map(move |level| {
let width = get_mipmap_size(size_0.width, level);
let height = get_mipmap_size(size_0.height, level);
let size = Size::new(width.get(), height.get());
// Panic Safety: This cannot overflow, because we already checked in the constructor
let len = pixels.surface_bytes(size).unwrap();
let surface = SurfaceDescriptor::new(width, height, offset, len);
offset += len;
surface
})
}
/// Internal method. This **assumes** that `offset + len` does not overflow.
fn set_offset_index(&mut self, index: u32) {
self.offset_index = index;
}
}
impl DataRegion for Texture {
fn data_len(&self) -> u64 {
if let Some(short_len) = self.short_len {
short_len.get() as u64
} else {
// Panic Safety: This cannot overflow, because we already checked in the constructor
get_texture_len(self.width, self.height, self.mipmaps, self.pixels).unwrap()
}
}
fn data_offset(&self) -> u64 {
self.offset_index as u64 * self.data_len()
}
fn data_end(&self) -> u64 {
(self.offset_index as u64 + 1) * self.data_len()
}
}
fn get_volume_len(
width: NonZeroU32,
height: NonZeroU32,
depth: NonZeroU32,
mipmaps: NonZeroU8,
pixels: PixelInfo,
) -> Option<u64> {
let mut len: u64 = 0;
for level in 0..mipmaps.get() {
let width = get_mipmap_size(width.get(), level);
let height = get_mipmap_size(height.get(), level);
let depth = get_mipmap_size(depth.get(), level);
let slice_size = Size::new(width.get(), height.get());
let slice_len = pixels.surface_bytes(slice_size)?;
let mip_len = slice_len.checked_mul(depth.get() as u64)?;
len = len.checked_add(mip_len)?;
}
Some(len)
}
/// A 3D texture with mipmaps (if any).
///
/// See [`DataLayout::Volume`] for more information.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Volume {
width: NonZeroU32,
height: NonZeroU32,
depth: NonZeroU32,
mipmaps: NonZeroU8,
pixels: PixelInfo,
}
impl Volume {
/// Creates a new volume at offset 0.
fn create_at_offset_0(
width: NonZeroU32,
height: NonZeroU32,
depth: NonZeroU32,
mipmaps: NonZeroU8,
pixels: PixelInfo,
) -> Result<Self, LayoutError> {
// compute the length of the entire volume (including mips) to check
// for overflows, so we can assume no overflows in the rest of the code
_ = get_volume_len(width, height, depth, mipmaps, pixels)
.ok_or(LayoutError::DataLayoutTooBig)?;
Ok(Self {
width,
height,
depth,
mipmaps,
pixels,
})
}
pub fn pixel_info(&self) -> PixelInfo {
self.pixels
}
/// The level 0 mipmap of this volume.
pub fn main(&self) -> VolumeDescriptor {
let slice_size = Size::new(self.width.get(), self.height.get());
// Panic Safety: This cannot overflow, because we already checked in the constructor
let slice_len = self.pixels.surface_bytes(slice_size).unwrap();
VolumeDescriptor {
width: self.width,
height: self.height,
depth: self.depth,
offset: 0,
slice_len,
}
}
pub fn mipmaps(&self) -> u8 {
self.mipmaps.get()
}
pub fn get(&self, level: u8) -> Option<VolumeDescriptor> {
self.iter_mips().nth(level as usize)
}
pub fn iter_mips(&self) -> impl Iterator<Item = VolumeDescriptor> {
let mut offset = 0;
let width_0 = self.width.get();
let height_0 = self.height.get();
let depth_0 = self.depth.get();
let pixels = self.pixels;
(0..self.mipmaps.get()).map(move |level| {
let width = get_mipmap_size(width_0, level);
let height = get_mipmap_size(height_0, level);
let depth = get_mipmap_size(depth_0, level);
let slice_size = Size::new(width.get(), height.get());
// Panic Safety: This cannot overflow, because we already checked in the constructor
let slice_len = pixels.surface_bytes(slice_size).unwrap();
let volume = VolumeDescriptor::new(width, height, depth, offset, slice_len);
offset += depth.get() as u64 * slice_len;
volume
})
}
}
impl DataRegion for Volume {
fn data_len(&self) -> u64 {
// Panic Safety: This cannot overflow, because we already checked in the constructor
get_volume_len(
self.width,
self.height,
self.depth,
self.mipmaps,
self.pixels,
)
.unwrap()
}
fn data_offset(&self) -> u64 {
// if there is a volume, it is the only object in the data section
0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TextureArrayKind {
/// An array of textures.
Textures,
/// An array of cube maps.
///
/// The number of textures in the array is a multiple of 6.
CubeMaps,
/// An array of at most 5 sides of a cube maps.
PartialCubeMap(CubeMapFaces),
}
bitflags! {
/// A bitset representing which faces of a cube map are present.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct CubeMapFaces: u8 {
const POSITIVE_X = 0b0000_0001;
const NEGATIVE_X = 0b0000_0010;
const POSITIVE_Y = 0b0000_0100;
const NEGATIVE_Y = 0b0000_1000;
const POSITIVE_Z = 0b0001_0000;
const NEGATIVE_Z = 0b0010_0000;
const ALL = Self::POSITIVE_X.bits() | Self::NEGATIVE_X.bits() | Self::POSITIVE_Y.bits() | Self::NEGATIVE_Y.bits() | Self::POSITIVE_Z.bits() | Self::NEGATIVE_Z.bits();
}
}
impl From<Caps2> for CubeMapFaces {
fn from(value: Caps2) -> Self {
let faces = (value & Caps2::CUBE_MAP_ALL_FACES).bits();
CubeMapFaces::from_bits_truncate((faces >> 10) as u8)
}
}
impl From<CubeMapFaces> for Caps2 {
fn from(value: CubeMapFaces) -> Self {
let faces = value.bits() & 0b11_1111;
Caps2::from_bits_truncate((faces as u32) << 10)
}
}
impl CubeMapFaces {
/// Returns the number of cube map sides set in this bit mask.
pub fn count(&self) -> u32 {
self.bits().count_ones()
}
}
/// An array of textures.
///
/// See [`DataLayout::TextureArray`] for more information.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct TextureArray {
kind: TextureArrayKind,
array_len: u32,
width: NonZeroU32,
height: NonZeroU32,
mipmaps: NonZeroU8,
pixels: PixelInfo,
texture_short_len: Option<NonZeroU32>,
}
impl TextureArray {
fn new(kind: TextureArrayKind, array_len: u32, first: Texture) -> Result<Self, LayoutError> {
// must start at offset 0
debug_assert_eq!(first.data_offset(), 0);
// Check that the entire array does not overflow
_ = first
.data_len()
.checked_mul(array_len as u64)
.ok_or(LayoutError::DataLayoutTooBig)?;
Ok(Self {
kind,
array_len,
width: first.width,
height: first.height,
mipmaps: first.mipmaps,
pixels: first.pixels,
texture_short_len: first.short_len,
})
}
pub fn pixel_info(&self) -> PixelInfo {
self.pixels
}
pub fn kind(&self) -> TextureArrayKind {
self.kind
}
pub fn is_empty(&self) -> bool {
self.array_len == 0
}
pub fn len(&self) -> usize {
self.array_len as usize
}
pub fn size(&self) -> Size {
Size::new(self.width.get(), self.height.get())
}
pub fn mipmaps(&self) -> u8 {
self.mipmaps.get()
}
pub(crate) fn first(&self) -> Texture {
Texture {
width: self.width,
height: self.height,
mipmaps: self.mipmaps,
pixels: self.pixels,
offset_index: 0,
short_len: self.texture_short_len,
}
}
pub fn get(&self, index: usize) -> Option<Texture> {
if index < self.array_len as usize {
let mut texture = self.first();
texture.set_offset_index(index as u32);
Some(texture)
} else {
None
}
}
pub fn iter(&self) -> impl Iterator<Item = Texture> {
let mut texture = self.first();
(0..self.array_len).map(move |index| {
texture.set_offset_index(index);
texture
})
}
}
impl DataRegion for TextureArray {
fn data_len(&self) -> u64 {
// Panic Safety: this can't overflow, because we checked in the constructor
self.first().data_len() * self.array_len as u64
}
fn data_offset(&self) -> u64 {
0
}
}
/// The type and layout of the surfaces/volumes in the data section of a DDS file.
///
/// DDS is a container format and supports a few different data types (e.g.
/// images, volumes, cube maps). While varied, the data section of a DDS file
/// is always a contiguous block of data and its layout is 100% determined by
/// the header. There are no gaps, padding, or markers in the data section,
/// just the raw data of the surfaces/volumes. This makes it necessary for
/// readers to know the layout of the data in order to read it correctly.
///
/// [`DataLayout`] contains all of this information while providing a simple
/// interface to iterate over the surfaces/volumes.
///
/// Note: [`DataLayout`] provides no methods to read the data itself. Use
/// [`Decoder`](crate::Decoder) or [`Encoder`](crate::Encoder) to read/write the
/// data section.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DataLayout {
/// A single texture with mipmaps (if any).
///
/// Example:
///
/// ```
/// # use dds::{*, header::*};
/// let header = Header::new_image(123, 345, Format::BC1_UNORM).with_mipmaps();
/// let layout = DataLayout::from_header(&header).unwrap();
/// let texture = layout.texture().unwrap();
/// assert_eq!(texture.main().size(), Size::new(123, 345));
///
/// // iterate over all mipmaps
/// for (level, mipmap) in texture.iter_mips().enumerate() {
/// println!("Mipmap {}: {}x{}", level, mipmap.width(), mipmap.height());
/// }
/// ```
Texture(Texture),
/// A 3D texture with mipmaps (if any).
///
/// DDS uses depth slices to represent 3D textures.
///
/// Example:
///
/// ```
/// # use dds::{*, header::*};
/// let header = Header::new_volume(123, 345, 678, Format::BC1_UNORM).with_mipmaps();
/// let layout = DataLayout::from_header(&header).unwrap();
/// let volume = layout.volume().unwrap();
/// assert_eq!(volume.main().size(), Size::new(123, 345));
/// assert_eq!(volume.main().depth(), 678);
///
/// // iterate over all mipmaps
/// for (level, mipmap) in volume.iter_mips().enumerate() {
/// println!("Mipmap {}: {}x{}x{}", level, mipmap.width(), mipmap.height(), mipmap.depth());
/// }
/// ```
Volume(Volume),
/// A simply array of 2D textures.
///
/// All textures within the array have the same size, mipmap count, and
/// pixel format.
///
/// Example:
///
/// ```
/// # use dds::{*, header::*};
/// let mut header = Dx10Header::new_image(123, 345, DxgiFormat::BC1_UNORM);
/// header.array_size = 10;
/// let layout = DataLayout::from_header(&header.into()).unwrap();
/// let array = layout.texture_array().unwrap();
/// assert_eq!(array.len(), 10);
/// assert_eq!(array.size(), Size::new(123, 345));
///
/// // iterate over all textures in the array
/// for texture in array.iter() {
/// for (level, mipmap) in texture.iter_mips().enumerate() {
/// println!("Mipmap {}: {}x{}", level, mipmap.width(), mipmap.height());
/// }
/// }
/// ```
///
/// ## Cube maps
///
/// Cube maps are a special case of texture arrays. You can differentiate
/// between normal texture arrays and cube maps using [`TextureArray::kind()`].
///
/// The faces of a cube map are always stored in the order:
///
/// 1. Positive X
/// 2. Negative X
/// 3. Positive Y
/// 4. Negative Y
/// 5. Positive Z
/// 6. Negative Z
///
/// Note that cube maps come in 2 flavors: full cube maps and partial cube
/// maps. Partial cube maps are cube maps with fewer than 6 faces (see
/// [`TextureArrayKind::PartialCubeMap`]) and are **not** supported by DX10+.
/// In practice, partial cube maps are rarely used. This library only supports
/// them for completeness.
///
/// Example:
///
/// ```
/// # use dds::{*, header::*};
/// let mut header = Header::new_cube_map(256, 256, Format::BC1_UNORM).with_mipmaps();
/// let layout = DataLayout::from_header(&header).unwrap();
/// let array = layout.texture_array().unwrap();
/// assert_eq!(array.kind(), TextureArrayKind::CubeMaps);
/// assert_eq!(array.len(), 6); // 6 faces
/// assert_eq!(array.size(), Size::new(256, 256));
///
/// let positive_x = array.get(0).unwrap();
/// let negative_x = array.get(1).unwrap();
/// let positive_y = array.get(2).unwrap();
/// let negative_y = array.get(3).unwrap();
/// let positive_z = array.get(4).unwrap();
/// let negative_z = array.get(5).unwrap();
/// ```
///
/// DX10 also supports arrays of cube maps. Example:
///
/// ```
/// # use dds::{*, header::*};
/// let mut header = Dx10Header::new_cube_map(256, 256, DxgiFormat::BC1_UNORM);
/// header.array_size = 3;
/// let layout = DataLayout::from_header(&header.into()).unwrap();
/// let array = layout.texture_array().unwrap();
/// assert_eq!(array.kind(), TextureArrayKind::CubeMaps);
/// assert_eq!(array.len(), 18); // 6 faces * 3 cube maps
/// ```
TextureArray(TextureArray),
}
impl DataLayout {
pub fn from_header(header: &Header) -> Result<Self, DecodingError> {
let layout = Self::from_header_with(header, PixelInfo::from_header(header)?)?;
Ok(layout)
}
pub fn from_header_with(header: &Header, pixel_info: PixelInfo) -> Result<Self, LayoutError> {
match header {
Header::Dx10(dx10) => {
if dx10.is_cube_map() {
if dx10.resource_dimension != ResourceDimension::Texture2D {
return Err(LayoutError::InvalidCubeMapFaces);
}
let info = SurfaceLayoutInfo::from_header(header, pixel_info)?;
let array_size = dx10.array_size;
// "For a 2D texture that is also a cube-map texture, array_size represents the number of cubes."
let cube_map_faces = array_size
.checked_mul(6)
.ok_or(LayoutError::ArraySizeTooBig(array_size))?;
return Ok(Self::TextureArray(
info.create_array(TextureArrayKind::CubeMaps, cube_map_faces)?,
));
}
match dx10.resource_dimension {
ResourceDimension::Texture1D | ResourceDimension::Texture2D => {
let mut info = SurfaceLayoutInfo::from_header(header, pixel_info)?;
if dx10.resource_dimension == ResourceDimension::Texture1D {
info.height = NON_ZERO_U32_ONE;
}
let array_size = dx10.array_size;
if array_size == 1 {
Ok(Self::Texture(info.create()?))
} else {
Ok(Self::TextureArray(
info.create_array(TextureArrayKind::Textures, array_size)?,
))
}
}
ResourceDimension::Texture3D => {
let info = VolumeLayoutInfo::from_header(header, pixel_info)?;
Ok(Self::Volume(info.create()?))
}
}
}
Header::Dx9(dx9) => {
if let Some(faces) = dx9.cube_map_faces() {
if dx9.is_volume() {
return Err(LayoutError::InvalidCubeMapFaces);
}
let info = SurfaceLayoutInfo::from_header(header, pixel_info)?;
let face_count = faces.count();
let kind = if face_count == 6 {
TextureArrayKind::CubeMaps
} else {
TextureArrayKind::PartialCubeMap(faces)
};
Ok(Self::TextureArray(info.create_array(kind, face_count)?))
} else if dx9.is_volume() {
let info = VolumeLayoutInfo::from_header(header, pixel_info)?;
Ok(Self::Volume(info.create()?))
} else {
let info = SurfaceLayoutInfo::from_header(header, pixel_info)?;
Ok(Self::Texture(info.create()?))
}
}
}
}
/// The size of the level 0 object.
///
/// For single textures and texture arrays, this will return the size of the
/// texture (mipmap level 0). For cube maps, this will return the size of
/// the individual faces (mipmap level 0). For volume textures, this will
/// return the size of the first depth slice (mipmap level 0).
pub fn main_size(&self) -> Size {
match self {
DataLayout::Texture(texture) => texture.size(),
DataLayout::Volume(volume) => volume.main().size(),
DataLayout::TextureArray(texture_array) => texture_array.size(),
}
}
/// If this layout is a [`DataLayout::Texture`], returns the texture.
pub fn texture(&self) -> Option<Texture> {
match self {
DataLayout::Texture(texture) => Some(*texture),
_ => None,
}
}
/// If this layout is a [`DataLayout::Volume`], returns the volume.
pub fn volume(&self) -> Option<Volume> {
match self {
DataLayout::Volume(volume) => Some(*volume),
_ => None,
}
}
/// If this layout is a [`DataLayout::TextureArray`], returns the texture
/// array.
pub fn texture_array(&self) -> Option<TextureArray> {
match self {
DataLayout::TextureArray(array) => Some(*array),
_ => None,
}
}
/// Whether this layout is a [`DataLayout::Texture`].
pub fn is_texture(&self) -> bool {
matches!(self, DataLayout::Texture(_))
}
/// Whether this layout is a [`DataLayout::Volume`].
pub fn is_volume(&self) -> bool {
matches!(self, DataLayout::Volume(_))
}
/// Whether this layout is a [`DataLayout::TextureArray`].
pub fn is_texture_array(&self) -> bool {
matches!(self, DataLayout::TextureArray(_))
}
/// Whether this layout is a cube map or partial cube map.
///
/// If `true` is returned, this layout is guaranteed to be a
/// [`DataLayout::TextureArray`]. The [`TextureArray::kind()`] will be
/// either [`TextureArrayKind::CubeMaps`] or
/// [`TextureArrayKind::PartialCubeMap`].
///
/// The texture array is **not** guaranteed to be contain exactly one
/// (partial) cube map, meaning that the texture array may contain
/// multiple (partial) cube maps.
pub fn is_cube_map(&self) -> bool {
matches!(
self,
DataLayout::TextureArray(TextureArray {
kind: TextureArrayKind::CubeMaps | TextureArrayKind::PartialCubeMap(_),
..
})
)
}
pub fn pixel_info(&self) -> PixelInfo {
match self {
DataLayout::Texture(texture) => texture.pixel_info(),
DataLayout::Volume(volume) => volume.pixel_info(),
DataLayout::TextureArray(array) => array.pixel_info(),
}
}
}
impl DataRegion for DataLayout {
fn data_len(&self) -> u64 {
match self {
DataLayout::Texture(texture) => texture.data_len(),
DataLayout::Volume(volume) => volume.data_len(),
DataLayout::TextureArray(textures) => textures.data_len(),
}
}
fn data_offset(&self) -> u64 {
// the data layout describes the entire data section, so it has to start at 0
0
}
}
fn parse_dimension(dim: u32) -> Result<NonZeroU32, LayoutError> {
NonZeroU32::new(dim).ok_or(LayoutError::ZeroDimension)
}
fn parse_mipmap_count(mipmaps: NonZeroU32) -> Result<NonZeroU8, LayoutError> {
NonZeroU8::try_from(mipmaps).map_err(|_| LayoutError::TooManyMipMaps(mipmaps.get()))
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct SurfaceLayoutInfo {
width: NonZeroU32,
height: NonZeroU32,
mipmaps: NonZeroU8,
pixels: PixelInfo,
}
impl SurfaceLayoutInfo {
fn from_header(header: &Header, pixels: PixelInfo) -> Result<Self, LayoutError> {
Ok(Self {
width: parse_dimension(header.width())?,
height: parse_dimension(header.height())?,
mipmaps: parse_mipmap_count(header.mipmap_count())?,
pixels,
})
}
fn create(&self) -> Result<Texture, LayoutError> {
Texture::create_at_offset_0(self.width, self.height, self.mipmaps, self.pixels)
}
fn create_array(
&self,
kind: TextureArrayKind,
array_len: u32,
) -> Result<TextureArray, LayoutError> {
TextureArray::new(kind, array_len, self.create()?)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct VolumeLayoutInfo {
width: NonZeroU32,
height: NonZeroU32,
depth: NonZeroU32,
mipmaps: NonZeroU8,
pixels: PixelInfo,
}
impl VolumeLayoutInfo {
fn from_header(header: &Header, pixels: PixelInfo) -> Result<Self, LayoutError> {
Ok(Self {
width: parse_dimension(header.width())?,
height: parse_dimension(header.height())?,
depth: parse_dimension(header.depth().ok_or(LayoutError::MissingDepth)?)?,
mipmaps: parse_mipmap_count(header.mipmap_count())?,
pixels,
})
}
fn create(&self) -> Result<Volume, LayoutError> {
Volume::create_at_offset_0(
self.width,
self.height,
self.depth,
self.mipmaps,
self.pixels,
)
}
}