Skip to main content

wgpu_types/
texture.rs

1use core::ops::Range;
2
3use macro_rules_attribute::derive;
4
5use crate::{link_to_wgpu_docs, link_to_wgpu_item, ConstDefault, Extent3d, Origin3d};
6
7#[cfg(any(feature = "serde", test))]
8use serde::{Deserialize, Serialize};
9
10#[cfg(doc)]
11use crate::{BindingType, Features};
12
13mod external_image;
14mod external_texture;
15mod format;
16
17pub use external_image::*;
18pub use external_texture::*;
19pub use format::*;
20
21/// Dimensionality of a texture.
22///
23/// Corresponds to [WebGPU `GPUTextureDimension`](
24/// https://gpuweb.github.io/gpuweb/#enumdef-gputexturedimension).
25#[repr(C)]
26#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
27#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
28pub enum TextureDimension {
29    /// 1D texture
30    #[cfg_attr(feature = "serde", serde(rename = "1d"))]
31    D1,
32    /// 2D texture
33    #[cfg_attr(feature = "serde", serde(rename = "2d"))]
34    D2,
35    /// 3D texture
36    #[cfg_attr(feature = "serde", serde(rename = "3d"))]
37    D3,
38}
39
40/// Order in which texture data is laid out in memory.
41#[derive(Clone, Copy, ConstDefault!, Debug, PartialEq, Eq, Hash)]
42#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
43pub enum TextureDataOrder {
44    /// The texture is laid out densely in memory as:
45    ///
46    /// ```text
47    /// Layer0Mip0 Layer0Mip1 Layer0Mip2
48    /// Layer1Mip0 Layer1Mip1 Layer1Mip2
49    /// Layer2Mip0 Layer2Mip1 Layer2Mip2
50    /// ````
51    ///
52    /// This is the layout used by dds files.
53    #[custom(default)]
54    LayerMajor,
55    /// The texture is laid out densely in memory as:
56    ///
57    /// ```text
58    /// Layer0Mip0 Layer1Mip0 Layer2Mip0
59    /// Layer0Mip1 Layer1Mip1 Layer2Mip1
60    /// Layer0Mip2 Layer1Mip2 Layer2Mip2
61    /// ```
62    ///
63    /// This is the layout used by ktx and ktx2 files.
64    MipMajor,
65}
66
67/// Dimensions of a particular texture view.
68///
69/// Corresponds to [WebGPU `GPUTextureViewDimension`](
70/// https://gpuweb.github.io/gpuweb/#enumdef-gputextureviewdimension).
71#[repr(C)]
72#[derive(Copy, Clone, Debug, ConstDefault!, Hash, Eq, PartialEq)]
73#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
74pub enum TextureViewDimension {
75    /// A one dimensional texture. `texture_1d` in WGSL and `texture1D` in GLSL.
76    #[cfg_attr(feature = "serde", serde(rename = "1d"))]
77    D1,
78    /// A two dimensional texture. `texture_2d` in WGSL and `texture2D` in GLSL.
79    #[cfg_attr(feature = "serde", serde(rename = "2d"))]
80    #[custom(default)]
81    D2,
82    /// A two dimensional array texture. `texture_2d_array` in WGSL and `texture2DArray` in GLSL.
83    #[cfg_attr(feature = "serde", serde(rename = "2d-array"))]
84    D2Array,
85    /// A cubemap texture. `texture_cube` in WGSL and `textureCube` in GLSL.
86    #[cfg_attr(feature = "serde", serde(rename = "cube"))]
87    Cube,
88    /// A cubemap array texture. `texture_cube_array` in WGSL and `textureCubeArray` in GLSL.
89    #[cfg_attr(feature = "serde", serde(rename = "cube-array"))]
90    CubeArray,
91    /// A three dimensional texture. `texture_3d` in WGSL and `texture3D` in GLSL.
92    #[cfg_attr(feature = "serde", serde(rename = "3d"))]
93    D3,
94}
95
96impl TextureViewDimension {
97    /// Get the texture dimension required of this texture view dimension.
98    #[must_use]
99    pub fn compatible_texture_dimension(self) -> TextureDimension {
100        match self {
101            Self::D1 => TextureDimension::D1,
102            Self::D2 | Self::D2Array | Self::Cube | Self::CubeArray => TextureDimension::D2,
103            Self::D3 => TextureDimension::D3,
104        }
105    }
106}
107
108/// Selects a subset of the data a [`Texture`] holds.
109///
110/// Used in [texture views](TextureViewDescriptor) and
111/// [texture copy operations](TexelCopyTextureInfo).
112///
113/// Corresponds to [WebGPU `GPUTextureAspect`](
114/// https://gpuweb.github.io/gpuweb/#enumdef-gputextureaspect).
115///
116#[doc = link_to_wgpu_item!(struct Texture)]
117#[repr(C)]
118#[derive(Copy, Clone, Debug, ConstDefault!, Hash, Eq, PartialEq)]
119#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
120#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
121pub enum TextureAspect {
122    /// All applicable aspects
123    ///
124    /// For formats with a single aspect (including regular color formats), this means that
125    /// aspect. For combined depth+stencil formats, this means both the depth and stencil
126    /// aspects. For multi-planar formats, this means all planes.
127    #[custom(default)]
128    All,
129    /// Stencil.
130    StencilOnly,
131    /// Depth.
132    DepthOnly,
133    /// Plane 0.
134    Plane0,
135    /// Plane 1.
136    Plane1,
137    /// Plane 2.
138    Plane2,
139}
140
141impl TextureAspect {
142    /// Returns the texture aspect for a given plane.
143    #[must_use]
144    pub fn from_plane(plane: u32) -> Option<Self> {
145        Some(match plane {
146            0 => Self::Plane0,
147            1 => Self::Plane1,
148            2 => Self::Plane2,
149            _ => return None,
150        })
151    }
152
153    /// Returns the plane for a given texture aspect.
154    #[must_use]
155    pub fn to_plane(&self) -> Option<u32> {
156        match self {
157            TextureAspect::Plane0 => Some(0),
158            TextureAspect::Plane1 => Some(1),
159            TextureAspect::Plane2 => Some(2),
160            _ => None,
161        }
162    }
163}
164
165bitflags::bitflags! {
166    /// Different ways that you can use a texture.
167    ///
168    /// The usages determine what kind of memory the texture is allocated from and what
169    /// actions the texture can partake in.
170    ///
171    /// Corresponds to [WebGPU `GPUTextureUsageFlags`](
172    /// https://gpuweb.github.io/gpuweb/#typedefdef-gputextureusageflags).
173    #[repr(transparent)]
174    #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
175    #[cfg_attr(feature = "serde", serde(transparent))]
176    #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
177    pub struct TextureUsages: u32 {
178        //
179        // ---- Start numbering at 1 << 0 ----
180        //
181        // WebGPU features:
182        //
183        /// Allows a texture to be the source in a [`CommandEncoder::copy_texture_to_buffer`] or
184        /// [`CommandEncoder::copy_texture_to_texture`] operation.
185        const COPY_SRC = 1 << 0;
186        /// Allows a texture to be the destination in a  [`CommandEncoder::copy_buffer_to_texture`],
187        /// [`CommandEncoder::copy_texture_to_texture`], or [`Queue::write_texture`] operation.
188        const COPY_DST = 1 << 1;
189        /// Allows a texture to be a [`BindingType::Texture`] in a bind group.
190        const TEXTURE_BINDING = 1 << 2;
191        /// Allows a texture to be a [`BindingType::StorageTexture`] in a bind group.
192        const STORAGE_BINDING = 1 << 3;
193        /// Allows a texture to be an output attachment of a render pass.
194        ///
195        /// Consider adding [`TextureUsages::TRANSIENT_ATTACHMENT`] if the contents are not reused.
196        const RENDER_ATTACHMENT = 1 << 4;
197
198        /// Specifies the contents of this texture will not be used in another pass to potentially reduce memory usage and bandwidth.
199        ///
200        /// No-op on platforms on platforms that do not benefit from transient textures.
201        /// Generally mobile and Apple chips care about this.
202        ///
203        /// Incompatible with ALL other usages except [`TextureUsages::RENDER_ATTACHMENT`] and requires it.
204        ///
205        /// Requires [`LoadOp::Clear`] or [`LoadOp::DontCare`] (if it is available) and [`StoreOp::Discard`].
206        const TRANSIENT_ATTACHMENT = 1 << 5;
207
208        //
209        // ---- Restart Numbering for Native Features ---
210        //
211        // Native Features:
212        //
213        /// Allows a texture to be used with image atomics. Requires [`Features::TEXTURE_ATOMIC`].
214        const STORAGE_ATOMIC = 1 << 16;
215    }
216}
217
218bitflags::bitflags! {
219    /// Similar to `TextureUsages`, but used only for `CommandEncoder::transition_resources`.
220    #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
221    #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
222    #[cfg_attr(feature = "serde", serde(transparent))]
223    pub struct TextureUses: u32 {
224        /// The texture is in unknown state.
225        const UNINITIALIZED = 1 << 0;
226        /// Ready to present image to the surface.
227        const PRESENT = 1 << 1;
228        /// The source of a hardware copy.
229        /// cbindgen:ignore
230        const COPY_SRC = 1 << 2;
231        /// The destination of a hardware copy.
232        /// cbindgen:ignore
233        const COPY_DST = 1 << 3;
234        /// Read-only sampled or fetched resource.
235        const RESOURCE = 1 << 4;
236        /// The color target of a renderpass.
237        const COLOR_TARGET = 1 << 5;
238        /// Read-only depth usage.
239        const DEPTH_READ = 1 << 6;
240        /// Read-write depth usage
241        const DEPTH_WRITE = 1 << 7;
242        /// Read-only stencil usage.
243        const STENCIL_READ = 1 << 8;
244        /// Read-write stencil usage
245        const STENCIL_WRITE = 1 << 9;
246        /// Read-only storage texture usage. Corresponds to a UAV in d3d, so is exclusive, despite being read only.
247        /// cbindgen:ignore
248        const STORAGE_READ_ONLY = 1 << 10;
249        /// Write-only storage texture usage.
250        /// cbindgen:ignore
251        const STORAGE_WRITE_ONLY = 1 << 11;
252        /// Read-write storage texture usage.
253        /// cbindgen:ignore
254        const STORAGE_READ_WRITE = 1 << 12;
255        /// Image atomic enabled storage.
256        /// cbindgen:ignore
257        const STORAGE_ATOMIC = 1 << 13;
258        /// Transient texture that may not have any backing memory. Not a resource state stored in the trackers, only used for passing down usages to create_texture.
259        const TRANSIENT = 1 << 14;
260        /// The combination of states that a texture may be in _at the same time_.
261        /// cbindgen:ignore
262        const INCLUSIVE = Self::COPY_SRC.bits() | Self::RESOURCE.bits() | Self::DEPTH_READ.bits()| Self::STENCIL_READ.bits() | Self::STORAGE_READ_ONLY.bits();
263        /// The combination of states that a texture must exclusively be in.
264        /// cbindgen:ignore
265        const EXCLUSIVE = Self::COPY_DST.bits() | Self::COLOR_TARGET.bits() | Self::STORAGE_WRITE_ONLY.bits() | Self::STORAGE_READ_WRITE.bits() | Self::STORAGE_ATOMIC.bits() | Self::PRESENT.bits();
266
267        /// Flag used by the wgpu-core texture tracker to say a texture is in different states for every sub-resource
268        const COMPLEX = 1 << 15;
269        /// Flag used by the wgpu-core texture tracker to say that the tracker does not know the state of the sub-resource.
270        /// This is different from UNINITIALIZED as that says the tracker does know, but the texture has not been initialized.
271        const UNKNOWN = 1 << 16;
272
273        /// Flag used by texture tracker to say the read-only depth aspect of texture is sampled.
274        const DEPTH_SAMPLED = 1 << 17;
275        /// Flag used by texture tracker to say the read-only stencil aspect of texture is sampled.
276        const STENCIL_SAMPLED = 1 << 18;
277    }
278}
279
280/// A texture transition for use with `CommandEncoder::transition_resources`.
281#[derive(Clone, Debug)]
282#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
283pub struct TextureTransition<T> {
284    /// The texture to transition.
285    pub texture: T,
286    /// An optional selector to transition only part of the texture.
287    ///
288    /// If None, the entire texture will be transitioned.
289    pub selector: Option<TextureSelector>,
290    /// The new state to transition to.
291    pub state: TextureUses,
292}
293
294/// Specifies a particular set of subresources in a texture.
295#[derive(Clone, Debug, PartialEq, Eq)]
296#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
297pub struct TextureSelector {
298    /// Range of mips to use.
299    pub mips: Range<u32>,
300    /// Range of layers to use.
301    pub layers: Range<u32>,
302}
303
304/// Specific type of a sample in a texture binding.
305///
306/// Corresponds to [WebGPU `GPUTextureSampleType`](
307/// https://gpuweb.github.io/gpuweb/#enumdef-gputexturesampletype).
308#[repr(C)]
309#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
310#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
311pub enum TextureSampleType {
312    /// Sampling returns floats.
313    ///
314    /// Example WGSL syntax:
315    /// ```rust,ignore
316    /// @group(0) @binding(0)
317    /// var t: texture_2d<f32>;
318    /// ```
319    ///
320    /// Example GLSL syntax:
321    /// ```cpp,ignore
322    /// layout(binding = 0)
323    /// uniform texture2D t;
324    /// ```
325    Float {
326        /// If this is `false`, the texture can't be sampled with
327        /// a filtering sampler.
328        ///
329        /// Even if this is `true`, it's possible to sample with
330        /// a **non-filtering** sampler.
331        filterable: bool,
332    },
333    /// Sampling does the depth reference comparison.
334    ///
335    /// This is also compatible with a non-filtering sampler.
336    ///
337    /// Example WGSL syntax:
338    /// ```rust,ignore
339    /// @group(0) @binding(0)
340    /// var t: texture_depth_2d;
341    /// ```
342    ///
343    /// Example GLSL syntax:
344    /// ```cpp,ignore
345    /// layout(binding = 0)
346    /// uniform texture2DShadow t;
347    /// ```
348    Depth,
349    /// Sampling returns signed integers.
350    ///
351    /// Example WGSL syntax:
352    /// ```rust,ignore
353    /// @group(0) @binding(0)
354    /// var t: texture_2d<i32>;
355    /// ```
356    ///
357    /// Example GLSL syntax:
358    /// ```cpp,ignore
359    /// layout(binding = 0)
360    /// uniform itexture2D t;
361    /// ```
362    Sint,
363    /// Sampling returns unsigned integers.
364    ///
365    /// Example WGSL syntax:
366    /// ```rust,ignore
367    /// @group(0) @binding(0)
368    /// var t: texture_2d<u32>;
369    /// ```
370    ///
371    /// Example GLSL syntax:
372    /// ```cpp,ignore
373    /// layout(binding = 0)
374    /// uniform utexture2D t;
375    /// ```
376    Uint,
377}
378
379impl Default for TextureSampleType {
380    fn default() -> Self {
381        Self::Float { filterable: true }
382    }
383}
384
385/// Specific type of a sample in a texture binding.
386///
387/// For use in [`BindingType::StorageTexture`].
388///
389/// Corresponds to [WebGPU `GPUStorageTextureAccess`](
390/// https://gpuweb.github.io/gpuweb/#enumdef-gpustoragetextureaccess).
391#[repr(C)]
392#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
393#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
394#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
395pub enum StorageTextureAccess {
396    /// The texture can only be written in the shader and it:
397    /// - may or may not be annotated with `write` (WGSL).
398    /// - must be annotated with `writeonly` (GLSL).
399    ///
400    /// Example WGSL syntax:
401    /// ```rust,ignore
402    /// @group(0) @binding(0)
403    /// var my_storage_image: texture_storage_2d<r32float, write>;
404    /// ```
405    ///
406    /// Example GLSL syntax:
407    /// ```cpp,ignore
408    /// layout(set=0, binding=0, r32f) writeonly uniform image2D myStorageImage;
409    /// ```
410    WriteOnly,
411    /// The texture can only be read in the shader and it must be annotated with `read` (WGSL) or
412    /// `readonly` (GLSL).
413    ///
414    /// [`Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES`] must be enabled to use this access
415    /// mode. This is a native-only extension.
416    ///
417    /// Example WGSL syntax:
418    /// ```rust,ignore
419    /// @group(0) @binding(0)
420    /// var my_storage_image: texture_storage_2d<r32float, read>;
421    /// ```
422    ///
423    /// Example GLSL syntax:
424    /// ```cpp,ignore
425    /// layout(set=0, binding=0, r32f) readonly uniform image2D myStorageImage;
426    /// ```
427    ReadOnly,
428    /// The texture can be both read and written in the shader and must be annotated with
429    /// `read_write` in WGSL.
430    ///
431    /// [`Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES`] must be enabled to use this access
432    /// mode.  This is a nonstandard, native-only extension.
433    ///
434    /// Example WGSL syntax:
435    /// ```rust,ignore
436    /// @group(0) @binding(0)
437    /// var my_storage_image: texture_storage_2d<r32float, read_write>;
438    /// ```
439    ///
440    /// Example GLSL syntax:
441    /// ```cpp,ignore
442    /// layout(set=0, binding=0, r32f) uniform image2D myStorageImage;
443    /// ```
444    ReadWrite,
445    /// The texture can be both read and written in the shader via atomics and must be annotated
446    /// with `read_write` in WGSL.
447    ///
448    /// [`Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES`] must be enabled to use this access
449    /// mode.  This is a nonstandard, native-only extension.
450    ///
451    /// Example WGSL syntax:
452    /// ```rust,ignore
453    /// @group(0) @binding(0)
454    /// var my_storage_image: texture_storage_2d<r32uint, atomic>;
455    /// ```
456    Atomic,
457}
458
459/// Specifies the component swizzle for a channel.
460///
461/// Used in [`TextureComponentSwizzle`]
462#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
463#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
464pub enum ComponentSwizzle {
465    /// Force its value to 0.
466    Zero,
467    /// Force its value to 1.
468    One,
469    /// Take its value from the red channel of the texture.
470    R,
471    /// Take its value from the green channel of the texture.
472    G,
473    /// Take its value from the blue channel of the texture.
474    B,
475    /// Take its value from the alpha channel of the texture.
476    A,
477}
478
479/// Specifies the texture component swizzle for each channel.
480///
481/// Used in [`TextureViewDescriptor::swizzle`].
482///
483/// Example:
484/// ```rust
485/// # use wgpu_types::{TextureComponentSwizzle, ComponentSwizzle};
486/// // The swizzle maps `xgxr` to `rg01`, or maps `rgba` to `ag01`
487/// TextureComponentSwizzle {
488///     r: ComponentSwizzle::A,
489///     g: ComponentSwizzle::G,
490///     b: ComponentSwizzle::Zero,
491///     a: ComponentSwizzle::One,
492/// };
493/// ```
494#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
495#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
496pub struct TextureComponentSwizzle {
497    /// Replace the red channel with the [`ComponentSwizzle`].
498    pub r: ComponentSwizzle,
499    /// Replace the green channel with the [`ComponentSwizzle`].
500    pub g: ComponentSwizzle,
501    /// Replace the blue channel with the [`ComponentSwizzle`].
502    pub b: ComponentSwizzle,
503    /// Replace the alpha channel with the [`ComponentSwizzle`].
504    pub a: ComponentSwizzle,
505}
506
507impl Default for TextureComponentSwizzle {
508    fn default() -> Self {
509        Self {
510            r: ComponentSwizzle::R,
511            g: ComponentSwizzle::G,
512            b: ComponentSwizzle::B,
513            a: ComponentSwizzle::A,
514        }
515    }
516}
517
518impl TextureComponentSwizzle {
519    fn select(&self, component: ComponentSwizzle) -> ComponentSwizzle {
520        match component {
521            ComponentSwizzle::Zero => ComponentSwizzle::Zero,
522            ComponentSwizzle::One => ComponentSwizzle::One,
523            ComponentSwizzle::R => self.r,
524            ComponentSwizzle::G => self.g,
525            ComponentSwizzle::B => self.b,
526            ComponentSwizzle::A => self.a,
527        }
528    }
529
530    /// Computes a swizzle that when applied, is equivalent to applying `self` then `other`,
531    /// like the order of WGSL swizzles (`value.rgba.rgba`).
532    pub fn compose(&self, other: Self) -> Self {
533        Self {
534            r: self.select(other.r),
535            g: self.select(other.g),
536            b: self.select(other.b),
537            a: self.select(other.a),
538        }
539    }
540}
541
542/// Describes a [`TextureView`].
543///
544/// For use with [`Texture::create_view()`].
545///
546/// Corresponds to [WebGPU `GPUTextureViewDescriptor`](
547/// https://gpuweb.github.io/gpuweb/#dictdef-gputextureviewdescriptor).
548///
549#[doc = link_to_wgpu_item!(struct TextureView)]
550#[doc = link_to_wgpu_docs!(["`Texture::create_view()`"]: "struct.Texture.html#method.create_view")]
551#[derive(Clone, Debug, Default, Eq, PartialEq)]
552#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
553pub struct TextureViewDescriptor<L> {
554    /// Debug label of the texture view. This will show up in graphics debuggers for easy identification.
555    pub label: L,
556    /// Format of the texture view. Either must be the same as the texture format or in the list
557    /// of `view_formats` in the texture's descriptor.
558    pub format: Option<TextureFormat>,
559    /// The dimension of the texture view. For 1D textures, this must be `D1`. For 2D textures it must be one of
560    /// `D2`, `D2Array`, `Cube`, and `CubeArray`. For 3D textures it must be `D3`
561    pub dimension: Option<TextureViewDimension>,
562    /// The allowed usage(s) for the texture view. Must be a subset of the usage flags of the texture.
563    /// If not provided, defaults to the full set of usage flags of the texture.
564    pub usage: Option<TextureUsages>,
565    /// Aspect of the texture. Color textures must be [`TextureAspect::All`].
566    pub aspect: TextureAspect,
567    /// Base mip level.
568    pub base_mip_level: u32,
569    /// Mip level count.
570    /// If `Some(count)`, `base_mip_level + count` must be less or equal to underlying texture mip count.
571    /// If `None`, considered to include the rest of the mipmap levels, but at least 1 in total.
572    pub mip_level_count: Option<u32>,
573    /// Base array layer.
574    pub base_array_layer: u32,
575    /// Layer count.
576    /// If `Some(count)`, `base_array_layer + count` must be less or equal to the underlying array count.
577    /// If `None`, considered to include the rest of the array layers, but at least 1 in total.
578    pub array_layer_count: Option<u32>,
579    /// Texture component swizzle.
580    /// When the texture view is accessed by a shader, the red/green/blue/alpha channels are replaced
581    /// by the value corresponding to the component specified in [`TextureComponentSwizzle`].
582    ///
583    /// This requires [`Features::TEXTURE_COMPONENT_SWIZZLE`] if it is not identity swizzle.
584    pub swizzle: TextureComponentSwizzle,
585}
586
587impl<L> TextureViewDescriptor<L> {
588    /// Takes a closure and maps the label of the texture view descriptor into another.
589    #[must_use]
590    pub fn map_label<'a, K>(&'a self, fun: impl FnOnce(&'a L) -> K) -> TextureViewDescriptor<K> {
591        TextureViewDescriptor {
592            label: fun(&self.label),
593            format: self.format,
594            dimension: self.dimension,
595            usage: self.usage,
596            aspect: self.aspect,
597            base_mip_level: self.base_mip_level,
598            mip_level_count: self.mip_level_count,
599            base_array_layer: self.base_array_layer,
600            array_layer_count: self.array_layer_count,
601            swizzle: self.swizzle,
602        }
603    }
604}
605
606/// Describes a [`Texture`](../wgpu/struct.Texture.html).
607///
608/// Corresponds to [WebGPU `GPUTextureDescriptor`](
609/// https://gpuweb.github.io/gpuweb/#dictdef-gputexturedescriptor).
610#[repr(C)]
611#[derive(Clone, Debug, PartialEq, Eq, Hash)]
612#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
613pub struct TextureDescriptor<L, V> {
614    /// Debug label of the texture. This will show up in graphics debuggers for easy identification.
615    pub label: L,
616    /// Size of the texture. All components must be greater than zero. For a
617    /// regular 1D/2D texture, the unused sizes will be 1. For 2DArray textures,
618    /// Z is the number of 2D textures in that array.
619    pub size: Extent3d,
620    /// Mip count of texture. For a texture with no extra mips, this must be 1.
621    pub mip_level_count: u32,
622    /// Sample count of texture. If this is not 1, texture must have [`BindingType::Texture::multisampled`] set to true.
623    pub sample_count: u32,
624    /// Dimensions of the texture.
625    pub dimension: TextureDimension,
626    /// Format of the texture.
627    pub format: TextureFormat,
628    /// Allowed usages of the texture. If used in other ways, the operation will panic.
629    pub usage: TextureUsages,
630    /// Specifies what view formats will be allowed when calling `Texture::create_view` on this texture.
631    ///
632    /// View formats of the same format as the texture are always allowed.
633    ///
634    /// Note: currently, only the srgb-ness is allowed to change. (ex: `Rgba8Unorm` texture + `Rgba8UnormSrgb` view)
635    pub view_formats: V,
636    /// For devices without [`ARBITRARY_BINDING_VIEW_DIMENSIONS`](crate::DownlevelFlags::ARBITRARY_BINDING_VIEW_DIMENSIONS):
637    /// views of this texture used as bindings must have this as their `dimension`. Pass it
638    /// explicitly, or pass `None` to have it inferred from the texture's dimension and layer count.
639    /// Otherwise it is ignored.
640    pub texture_binding_view_dimension: Option<TextureViewDimension>,
641}
642
643impl<L, V> TextureDescriptor<L, V> {
644    /// Takes a closure and maps the label of the texture descriptor into another.
645    #[must_use]
646    pub fn map_label<'a, K>(&'a self, fun: impl FnOnce(&'a L) -> K) -> TextureDescriptor<K, V>
647    where
648        V: Clone,
649    {
650        TextureDescriptor {
651            label: fun(&self.label),
652            size: self.size,
653            mip_level_count: self.mip_level_count,
654            sample_count: self.sample_count,
655            dimension: self.dimension,
656            format: self.format,
657            usage: self.usage,
658            view_formats: self.view_formats.clone(),
659            texture_binding_view_dimension: self.texture_binding_view_dimension,
660        }
661    }
662
663    /// Maps the label and view formats of the texture descriptor into another.
664    #[must_use]
665    pub fn map_label_and_view_formats<'a, K, M>(
666        &'a self,
667        l_fun: impl FnOnce(&'a L) -> K,
668        v_fun: impl FnOnce(&'a V) -> M,
669    ) -> TextureDescriptor<K, M> {
670        TextureDescriptor {
671            label: l_fun(&self.label),
672            size: self.size,
673            mip_level_count: self.mip_level_count,
674            sample_count: self.sample_count,
675            dimension: self.dimension,
676            format: self.format,
677            usage: self.usage,
678            view_formats: v_fun(&self.view_formats),
679            texture_binding_view_dimension: self.texture_binding_view_dimension,
680        }
681    }
682
683    /// Calculates the extent at a given mip level.
684    ///
685    /// If the given mip level is larger than possible, returns None.
686    ///
687    /// Treats the depth as part of the mipmaps. If calculating
688    /// for a 2DArray texture, which does not mipmap depth, set depth to 1.
689    ///
690    /// ```rust
691    /// # use wgpu_types as wgpu;
692    /// # type TextureDescriptor<'a> = wgpu::TextureDescriptor<(), &'a [wgpu::TextureFormat]>;
693    /// let desc  = TextureDescriptor {
694    ///   label: (),
695    ///   size: wgpu::Extent3d { width: 100, height: 60, depth_or_array_layers: 1 },
696    ///   mip_level_count: 7,
697    ///   sample_count: 1,
698    ///   dimension: wgpu::TextureDimension::D3,
699    ///   format: wgpu::TextureFormat::Rgba8Sint,
700    ///   usage: wgpu::TextureUsages::empty(),
701    ///   view_formats: &[],
702    ///   texture_binding_view_dimension: None,
703    /// };
704    ///
705    /// assert_eq!(desc.mip_level_size(0), Some(wgpu::Extent3d { width: 100, height: 60, depth_or_array_layers: 1 }));
706    /// assert_eq!(desc.mip_level_size(1), Some(wgpu::Extent3d { width: 50, height: 30, depth_or_array_layers: 1 }));
707    /// assert_eq!(desc.mip_level_size(2), Some(wgpu::Extent3d { width: 25, height: 15, depth_or_array_layers: 1 }));
708    /// assert_eq!(desc.mip_level_size(3), Some(wgpu::Extent3d { width: 12, height: 7, depth_or_array_layers: 1 }));
709    /// assert_eq!(desc.mip_level_size(4), Some(wgpu::Extent3d { width: 6, height: 3, depth_or_array_layers: 1 }));
710    /// assert_eq!(desc.mip_level_size(5), Some(wgpu::Extent3d { width: 3, height: 1, depth_or_array_layers: 1 }));
711    /// assert_eq!(desc.mip_level_size(6), Some(wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 }));
712    /// assert_eq!(desc.mip_level_size(7), None);
713    /// ```
714    #[must_use]
715    pub fn mip_level_size(&self, level: u32) -> Option<Extent3d> {
716        if level >= self.mip_level_count {
717            return None;
718        }
719
720        Some(self.size.mip_level_size(level, self.dimension))
721    }
722
723    /// Computes the [render extent] of this texture.
724    ///
725    /// This is a low-level helper exported for use by wgpu-core.
726    ///
727    /// # Panics
728    ///
729    /// - If the mip level is out of range.
730    /// - If `self` is a multi-planar format and `plane` does not specify a valid plane.
731    /// - If `self` is a single-plane format and a `plane` is specified.
732    ///
733    /// [render extent]: https://gpuweb.github.io/gpuweb/#abstract-opdef-compute-render-extent
734    #[doc(hidden)]
735    #[must_use]
736    pub fn compute_render_extent(&self, mip_level: u32, plane: Option<u32>) -> Extent3d {
737        // Rendering never targets more than one mip level, array layer, volume slice, or
738        // texture plane. The two-dimensional render extent is the full plane.
739        Extent3d {
740            depth_or_array_layers: 1,
741            ..self.plane_size(mip_level, plane)
742        }
743    }
744
745    /// Computes the size of the indicated plane of this texture.
746    ///
747    /// This is a low-level helper used by [`compute_render_extent`], and exported for use
748    /// by texture copy validation in wgpu-core.
749    ///
750    /// # Panics
751    ///
752    /// - If the mip level is out of range.
753    /// - If `self` is a multi-planar format and `plane` does not specify a valid plane.
754    /// - If `self` is a single-plane format and a `plane` is specified.
755    #[doc(hidden)]
756    #[must_use]
757    pub fn plane_size(&self, mip_level: u32, plane: Option<u32>) -> Extent3d {
758        // This ought to be a panic condition within `subsampling_factors`, but it is a
759        // documented public function, and did not previously panic in this case.
760        assert_eq!(plane.is_some(), self.format.is_multi_planar_format());
761
762        let Extent3d {
763            width,
764            height,
765            depth_or_array_layers,
766        } = self.mip_level_size(mip_level).expect("invalid mip level");
767
768        let (w_subsampling, h_subsampling) = self.format.subsampling_factors(plane);
769
770        debug_assert!(width % w_subsampling == 0);
771        debug_assert!(height % h_subsampling == 0);
772
773        let width = width / w_subsampling;
774        let height = height / h_subsampling;
775
776        Extent3d {
777            width,
778            height,
779            depth_or_array_layers,
780        }
781    }
782
783    /// Returns the number of array layers.
784    ///
785    /// <https://gpuweb.github.io/gpuweb/#abstract-opdef-array-layer-count>
786    #[must_use]
787    pub fn array_layer_count(&self) -> u32 {
788        match self.dimension {
789            TextureDimension::D1 | TextureDimension::D3 => 1,
790            TextureDimension::D2 => self.size.depth_or_array_layers,
791        }
792    }
793
794    /// Returns the theoretical memory footprint of a texture.
795    ///
796    /// Actual memory usage may greatly exceed this value due to alignment and padding.
797    #[must_use]
798    pub fn theoretical_memory_footprint(&self) -> u64 {
799        (0..self.mip_level_count).fold(0, |acc, level| {
800            acc.saturating_add(
801                self.format.theoretical_memory_footprint(
802                    self.mip_level_size(level)
803                        .expect("mipmap level should be inbounds"),
804                ),
805            )
806        })
807    }
808
809    /// Infer the view dimension from a given descriptor.
810    ///
811    /// This is used when ARBITRARY_BINDING_VIEW_DIMENSIONS is not set.
812    /// See <https://gpuweb.github.io/gpuweb/#dom-gpudevice-createtexture>
813    #[must_use]
814    pub fn default_view_dimension(&self) -> TextureViewDimension {
815        match self.dimension {
816            TextureDimension::D1 => TextureViewDimension::D1,
817            TextureDimension::D2 => {
818                if self.array_layer_count() == 1 {
819                    TextureViewDimension::D2
820                } else {
821                    TextureViewDimension::D2Array
822                }
823            }
824            TextureDimension::D3 => TextureViewDimension::D3,
825        }
826    }
827}
828
829/// Describes a `Sampler`.
830///
831/// For use with `Device::create_sampler`.
832///
833/// Corresponds to [WebGPU `GPUSamplerDescriptor`](
834/// https://gpuweb.github.io/gpuweb/#dictdef-gpusamplerdescriptor).
835#[derive(Clone, Debug, PartialEq)]
836#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
837pub struct SamplerDescriptor<L> {
838    /// Debug label of the sampler. This will show up in graphics debuggers for easy identification.
839    pub label: L,
840    /// How to deal with out of bounds accesses in the u (i.e. x) direction
841    pub address_mode_u: AddressMode,
842    /// How to deal with out of bounds accesses in the v (i.e. y) direction
843    pub address_mode_v: AddressMode,
844    /// How to deal with out of bounds accesses in the w (i.e. z) direction
845    pub address_mode_w: AddressMode,
846    /// How to filter the texture when it needs to be magnified (made larger)
847    pub mag_filter: FilterMode,
848    /// How to filter the texture when it needs to be minified (made smaller)
849    pub min_filter: FilterMode,
850    /// How to filter between mip map levels
851    pub mipmap_filter: MipmapFilterMode,
852    /// Minimum level of detail (i.e. mip level) to use
853    pub lod_min_clamp: f32,
854    /// Maximum level of detail (i.e. mip level) to use
855    pub lod_max_clamp: f32,
856    /// If this is enabled, this is a comparison sampler using the given comparison function.
857    pub compare: Option<crate::CompareFunction>,
858    /// Must be at least 1. If this is not 1, all filter modes must be linear.
859    pub anisotropy_clamp: u16,
860    /// Border color to use when `address_mode` is [`AddressMode::ClampToBorder`]
861    pub border_color: Option<SamplerBorderColor>,
862}
863
864impl<L: Default> Default for SamplerDescriptor<L> {
865    fn default() -> Self {
866        Self {
867            label: Default::default(),
868            address_mode_u: Default::default(),
869            address_mode_v: Default::default(),
870            address_mode_w: Default::default(),
871            mag_filter: Default::default(),
872            min_filter: Default::default(),
873            mipmap_filter: Default::default(),
874            lod_min_clamp: 0.0,
875            lod_max_clamp: 32.0,
876            compare: None,
877            anisotropy_clamp: 1,
878            border_color: None,
879        }
880    }
881}
882
883impl<L> SamplerDescriptor<L> {
884    /// Takes a closure and maps the label of the sampler descriptor into another.
885    #[must_use]
886    pub fn map_label<'a, K>(&'a self, fun: impl FnOnce(&'a L) -> K) -> SamplerDescriptor<K> {
887        SamplerDescriptor {
888            label: fun(&self.label),
889            address_mode_u: self.address_mode_u,
890            address_mode_v: self.address_mode_v,
891            address_mode_w: self.address_mode_w,
892            mag_filter: self.mag_filter,
893            min_filter: self.min_filter,
894            mipmap_filter: self.mipmap_filter,
895            lod_min_clamp: self.lod_min_clamp,
896            lod_max_clamp: self.lod_max_clamp,
897            compare: self.compare,
898            anisotropy_clamp: self.anisotropy_clamp,
899            border_color: self.border_color,
900        }
901    }
902}
903
904/// How edges should be handled in texture addressing.
905///
906/// Corresponds to [WebGPU `GPUAddressMode`](
907/// https://gpuweb.github.io/gpuweb/#enumdef-gpuaddressmode).
908#[repr(C)]
909#[derive(Copy, Clone, Debug, ConstDefault!, Hash, Eq, PartialEq)]
910#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
911#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
912pub enum AddressMode {
913    /// Clamp the value to the edge of the texture
914    ///
915    /// -0.25 -> 0.0
916    /// 1.25  -> 1.0
917    #[custom(default)]
918    ClampToEdge = 0,
919    /// Repeat the texture in a tiling fashion
920    ///
921    /// -0.25 -> 0.75
922    /// 1.25 -> 0.25
923    Repeat = 1,
924    /// Repeat the texture, mirroring it every repeat
925    ///
926    /// -0.25 -> 0.25
927    /// 1.25 -> 0.75
928    MirrorRepeat = 2,
929    /// Clamp the value to the border of the texture
930    /// Requires feature [`Features::ADDRESS_MODE_CLAMP_TO_BORDER`]
931    ///
932    /// -0.25 -> border
933    /// 1.25 -> border
934    ClampToBorder = 3,
935}
936
937/// Texel mixing mode when sampling between texels.
938///
939/// Corresponds to [WebGPU `GPUFilterMode`](
940/// https://gpuweb.github.io/gpuweb/#enumdef-gpufiltermode).
941#[repr(C)]
942#[derive(Copy, Clone, Debug, ConstDefault!, Hash, Eq, PartialEq)]
943#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
944#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
945pub enum FilterMode {
946    /// Nearest neighbor sampling.
947    ///
948    /// This creates a pixelated effect.
949    #[custom(default)]
950    Nearest = 0,
951    /// Linear Interpolation
952    ///
953    /// This makes textures smooth but blurry.
954    Linear = 1,
955}
956
957/// Texel mixing mode when sampling between texels.
958///
959/// Corresponds to [WebGPU `GPUMipmapFilterMode`](
960/// https://gpuweb.github.io/gpuweb/#enumdef-gpumipmapfiltermode).
961#[repr(C)]
962#[derive(Copy, Clone, Debug, ConstDefault!, Hash, Eq, PartialEq)]
963#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
964#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
965pub enum MipmapFilterMode {
966    /// Nearest neighbor sampling.
967    ///
968    /// Return the value of the texel nearest to the texture coordinates.
969    #[custom(default)]
970    Nearest = 0,
971    /// Linear Interpolation
972    ///
973    /// Select two texels in each dimension and return a linear interpolation between their values.
974    Linear = 1,
975}
976
977/// Color variation to use when sampler addressing mode is [`AddressMode::ClampToBorder`]
978#[repr(C)]
979#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
980#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
981pub enum SamplerBorderColor {
982    /// [0, 0, 0, 0]
983    TransparentBlack,
984    /// [0, 0, 0, 1]
985    OpaqueBlack,
986    /// [1, 1, 1, 1]
987    OpaqueWhite,
988
989    /// On the Metal backend, this is equivalent to `TransparentBlack` for
990    /// textures that have an alpha component, and equivalent to `OpaqueBlack`
991    /// for textures that do not have an alpha component. On other backends,
992    /// this is equivalent to `TransparentBlack`. Requires
993    /// [`Features::ADDRESS_MODE_CLAMP_TO_ZERO`]. Not supported on the web.
994    Zero,
995}
996
997/// Layout of a texture in a buffer's memory.
998///
999/// The bytes per row and rows per image can be hard to figure out so here are some examples:
1000///
1001/// | Resolution | Format | Bytes per block | Pixels per block | Bytes per row                          | Rows per image               |
1002/// |------------|--------|-----------------|------------------|----------------------------------------|------------------------------|
1003/// | 256x256    | RGBA8  | 4               | 1 * 1 * 1        | 256 * 4 = Some(1024)                   | None                         |
1004/// | 32x16x8    | RGBA8  | 4               | 1 * 1 * 1        | 32 * 4 = 128 padded to 256 = Some(256) | None                         |
1005/// | 256x256    | BC3    | 16              | 4 * 4 * 1        | 16 * (256 / 4) = 1024 = Some(1024)     | None                         |
1006/// | 64x64x8    | BC3    | 16              | 4 * 4 * 1        | 16 * (64 / 4) = 256 = Some(256)        | 64 / 4 = 16 = Some(16)       |
1007///
1008/// Corresponds to [WebGPU `GPUTexelCopyBufferLayout`](
1009/// https://gpuweb.github.io/gpuweb/#dictdef-gpuimagedatalayout).
1010#[repr(C)]
1011#[derive(Clone, Copy, Debug, ConstDefault!)]
1012#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1013pub struct TexelCopyBufferLayout {
1014    /// Offset into the buffer that is the start of the texture. Must be a multiple of texture block size.
1015    /// For non-compressed textures, this is 1.
1016    pub offset: crate::BufferAddress,
1017    /// Bytes per "row" in an image.
1018    ///
1019    /// A row is one row of pixels or of compressed blocks in the x direction.
1020    ///
1021    /// This value is required if there are multiple rows (i.e. height or depth is more than one pixel or pixel block for compressed textures)
1022    ///
1023    /// Must be a multiple of 256 for [`CommandEncoder::copy_buffer_to_texture`][CEcbtt]
1024    /// and [`CommandEncoder::copy_texture_to_buffer`][CEcttb], unless
1025    /// [`Features::UNRESTRICTED_BYTES_PER_ROW`] is enabled. You must manually pad the
1026    /// buffer as if the image width is a multiple of 256. An image of size (500, 500) can be
1027    /// written to a buffer of size (512, 500) with `bytes_per_row` of 512,
1028    ///
1029    /// [`Queue::write_texture`][Qwt] does not have this requirement.
1030    ///
1031    /// Must be a multiple of the texture block size. For non-compressed textures, this is 1.
1032    ///
1033    #[doc = link_to_wgpu_docs!(["CEcbtt"]: "struct.CommandEncoder.html#method.copy_buffer_to_texture")]
1034    #[doc = link_to_wgpu_docs!(["CEcttb"]: "struct.CommandEncoder.html#method.copy_texture_to_buffer")]
1035    #[doc = link_to_wgpu_docs!(["Qwt"]: "struct.Queue.html#method.write_texture")]
1036    pub bytes_per_row: Option<u32>,
1037    /// "Rows" that make up a single "image".
1038    ///
1039    /// A row is one row of pixels or of compressed blocks in the x direction.
1040    ///
1041    /// An image is one layer in the z direction of a 3D image or 2DArray texture.
1042    ///
1043    /// The amount of rows per image may be larger than the actual amount of rows of data.
1044    ///
1045    /// Required if there are multiple images (i.e. the depth is more than one).
1046    pub rows_per_image: Option<u32>,
1047}
1048
1049/// View of a buffer which can be used to copy to/from a texture.
1050///
1051/// Corresponds to [WebGPU `GPUTexelCopyBufferInfo`](
1052/// https://gpuweb.github.io/gpuweb/#dictdef-gpuimagecopybuffer).
1053#[repr(C)]
1054#[derive(Copy, Clone, Debug)]
1055#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1056pub struct TexelCopyBufferInfo<B> {
1057    /// The buffer to be copied to/from.
1058    pub buffer: B,
1059    /// The layout of the texture data in this buffer.
1060    pub layout: TexelCopyBufferLayout,
1061}
1062
1063/// View of a texture which can be used to copy to/from a buffer/texture.
1064///
1065/// Corresponds to [WebGPU `GPUTexelCopyTextureInfo`](
1066/// https://gpuweb.github.io/gpuweb/#dictdef-gpuimagecopytexture).
1067#[repr(C)]
1068#[derive(Copy, Clone, Debug)]
1069#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1070pub struct TexelCopyTextureInfo<T> {
1071    /// The texture to be copied to/from.
1072    pub texture: T,
1073    /// The target mip level of the texture.
1074    pub mip_level: u32,
1075    /// The base texel of the texture in the selected `mip_level`. Together
1076    /// with the `copy_size` argument to copy functions, defines the
1077    /// sub-region of the texture to copy.
1078    #[cfg_attr(feature = "serde", serde(default))]
1079    pub origin: Origin3d,
1080    /// The copy aspect.
1081    #[cfg_attr(feature = "serde", serde(default))]
1082    pub aspect: TextureAspect,
1083}
1084
1085impl<T> TexelCopyTextureInfo<T> {
1086    /// Adds color space and premultiplied alpha information to make this
1087    /// descriptor tagged.
1088    pub fn to_tagged(
1089        self,
1090        color_space: PredefinedColorSpace,
1091        premultiplied_alpha: bool,
1092    ) -> CopyExternalImageDestInfo<T> {
1093        CopyExternalImageDestInfo {
1094            texture: self.texture,
1095            mip_level: self.mip_level,
1096            origin: self.origin,
1097            aspect: self.aspect,
1098            color_space,
1099            premultiplied_alpha,
1100        }
1101    }
1102}
1103
1104/// Subresource range within an image
1105#[repr(C)]
1106#[derive(Clone, Copy, Debug, ConstDefault!, Eq, PartialEq)]
1107#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1108#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
1109pub struct ImageSubresourceRange {
1110    /// Aspect of the texture. Color textures must be [`TextureAspect::All`][TAA].
1111    ///
1112    #[doc = link_to_wgpu_docs!(["TAA"]: "enum.TextureAspect.html#variant.All")]
1113    pub aspect: TextureAspect,
1114    /// Base mip level.
1115    pub base_mip_level: u32,
1116    /// Mip level count.
1117    /// If `Some(count)`, `base_mip_level + count` must be less or equal to underlying texture mip count.
1118    /// If `None`, considered to include the rest of the mipmap levels, but at least 1 in total.
1119    pub mip_level_count: Option<u32>,
1120    /// Base array layer.
1121    pub base_array_layer: u32,
1122    /// Layer count.
1123    /// If `Some(count)`, `base_array_layer + count` must be less or equal to the underlying array count.
1124    /// If `None`, considered to include the rest of the array layers, but at least 1 in total.
1125    pub array_layer_count: Option<u32>,
1126}
1127
1128impl ImageSubresourceRange {
1129    /// Returns if the given range represents a full resource, with a texture of the given
1130    /// layer count and mip count.
1131    ///
1132    /// ```rust
1133    /// # use wgpu_types as wgpu;
1134    ///
1135    /// let range_none = wgpu::ImageSubresourceRange {
1136    ///     aspect: wgpu::TextureAspect::All,
1137    ///     base_mip_level: 0,
1138    ///     mip_level_count: None,
1139    ///     base_array_layer: 0,
1140    ///     array_layer_count: None,
1141    /// };
1142    /// assert_eq!(range_none.is_full_resource(wgpu::TextureFormat::Stencil8, 5, 10), true);
1143    ///
1144    /// let range_some = wgpu::ImageSubresourceRange {
1145    ///     aspect: wgpu::TextureAspect::All,
1146    ///     base_mip_level: 0,
1147    ///     mip_level_count: Some(5),
1148    ///     base_array_layer: 0,
1149    ///     array_layer_count: Some(10),
1150    /// };
1151    /// assert_eq!(range_some.is_full_resource(wgpu::TextureFormat::Stencil8, 5, 10), true);
1152    ///
1153    /// let range_mixed = wgpu::ImageSubresourceRange {
1154    ///     aspect: wgpu::TextureAspect::StencilOnly,
1155    ///     base_mip_level: 0,
1156    ///     // Only partial resource
1157    ///     mip_level_count: Some(3),
1158    ///     base_array_layer: 0,
1159    ///     array_layer_count: None,
1160    /// };
1161    /// assert_eq!(range_mixed.is_full_resource(wgpu::TextureFormat::Stencil8, 5, 10), false);
1162    /// ```
1163    #[must_use]
1164    pub fn is_full_resource(
1165        &self,
1166        format: TextureFormat,
1167        mip_levels: u32,
1168        array_layers: u32,
1169    ) -> bool {
1170        // Mip level count and array layer count need to deal with both the None and Some(count) case.
1171        let mip_level_count = self.mip_level_count.unwrap_or(mip_levels);
1172        let array_layer_count = self.array_layer_count.unwrap_or(array_layers);
1173
1174        let aspect_eq = Some(format) == format.aspect_specific_format(self.aspect);
1175
1176        let base_mip_level_eq = self.base_mip_level == 0;
1177        let mip_level_count_eq = mip_level_count == mip_levels;
1178
1179        let base_array_layer_eq = self.base_array_layer == 0;
1180        let array_layer_count_eq = array_layer_count == array_layers;
1181
1182        aspect_eq
1183            && base_mip_level_eq
1184            && mip_level_count_eq
1185            && base_array_layer_eq
1186            && array_layer_count_eq
1187    }
1188
1189    /// Returns the mip level range of a subresource range describes for a specific texture.
1190    #[must_use]
1191    pub fn mip_range(&self, mip_level_count: u32) -> Range<u32> {
1192        self.base_mip_level..match self.mip_level_count {
1193            Some(mip_level_count) => self.base_mip_level.saturating_add(mip_level_count),
1194            None => mip_level_count,
1195        }
1196    }
1197
1198    /// Returns the layer range of a subresource range describes for a specific texture.
1199    #[must_use]
1200    pub fn layer_range(&self, array_layer_count: u32) -> Range<u32> {
1201        self.base_array_layer..match self.array_layer_count {
1202            Some(array_layer_count) => self.base_array_layer.saturating_add(array_layer_count),
1203            None => array_layer_count,
1204        }
1205    }
1206}
1207
1208#[cfg(test)]
1209mod tests {
1210    use super::*;
1211    use crate::Extent3d;
1212
1213    #[test]
1214    fn test_physical_size() {
1215        let format = TextureFormat::Bc1RgbaUnormSrgb; // 4x4 blocks
1216        assert_eq!(
1217            Extent3d {
1218                width: 7,
1219                height: 7,
1220                depth_or_array_layers: 1
1221            }
1222            .physical_size(format),
1223            Extent3d {
1224                width: 8,
1225                height: 8,
1226                depth_or_array_layers: 1
1227            }
1228        );
1229        // Doesn't change, already aligned
1230        assert_eq!(
1231            Extent3d {
1232                width: 8,
1233                height: 8,
1234                depth_or_array_layers: 1
1235            }
1236            .physical_size(format),
1237            Extent3d {
1238                width: 8,
1239                height: 8,
1240                depth_or_array_layers: 1
1241            }
1242        );
1243        let format = TextureFormat::Astc {
1244            block: AstcBlock::B8x5,
1245            channel: AstcChannel::Unorm,
1246        }; // 8x5 blocks
1247        assert_eq!(
1248            Extent3d {
1249                width: 7,
1250                height: 7,
1251                depth_or_array_layers: 1
1252            }
1253            .physical_size(format),
1254            Extent3d {
1255                width: 8,
1256                height: 10,
1257                depth_or_array_layers: 1
1258            }
1259        );
1260    }
1261
1262    #[test]
1263    fn test_max_mips() {
1264        // 1D
1265        assert_eq!(
1266            Extent3d {
1267                width: 240,
1268                height: 1,
1269                depth_or_array_layers: 1
1270            }
1271            .max_mips(TextureDimension::D1),
1272            1
1273        );
1274        // 2D
1275        assert_eq!(
1276            Extent3d {
1277                width: 1,
1278                height: 1,
1279                depth_or_array_layers: 1
1280            }
1281            .max_mips(TextureDimension::D2),
1282            1
1283        );
1284        assert_eq!(
1285            Extent3d {
1286                width: 60,
1287                height: 60,
1288                depth_or_array_layers: 1
1289            }
1290            .max_mips(TextureDimension::D2),
1291            6
1292        );
1293        assert_eq!(
1294            Extent3d {
1295                width: 240,
1296                height: 1,
1297                depth_or_array_layers: 1000
1298            }
1299            .max_mips(TextureDimension::D2),
1300            8
1301        );
1302        // 3D
1303        assert_eq!(
1304            Extent3d {
1305                width: 16,
1306                height: 30,
1307                depth_or_array_layers: 60
1308            }
1309            .max_mips(TextureDimension::D3),
1310            6
1311        );
1312    }
1313}