Skip to main content

three_rs/textures/
cube_texture.rs

1//! Port of `three.js/src/textures/CubeTexture.js` + the `Texture.js` fields the
2//! WebGPU backend reads (rung 3 subset).
3//!
4//! Handle semantics match JS object identity: the example hands the same
5//! `CubeTexture` to `scene.background` and to `material.envMap`, and the
6//! renderer must upload it once.
7
8use std::cell::Ref;
9
10use super::texture::MinFilter;
11use super::{TextureFilter, TextureId, TextureType};
12use crate::math::ColorSpace;
13use std::cell::RefCell;
14use std::rc::Rc;
15
16/// `three.js/src/constants.js` texture mappings.
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18#[non_exhaustive]
19pub enum Mapping {
20    /// `CubeReflectionMapping`.
21    CubeReflection,
22    /// `CubeRefractionMapping`.
23    CubeRefraction,
24}
25
26/// One image of `CubeTexture.images`, top-down — what `ImageLoader` hands the
27/// backend after the browser has decoded the PNG, or the `DataTexture`
28/// `HDRCubeTextureLoader` builds per face.
29///
30/// `data` is in the texture's own format, not always RGBA8: an
31/// `HDRCubeTextureLoader` face is four binary16 channels per texel, eight
32/// bytes. The owning [`CubeTexture`]'s `texture_type` says which, and the
33/// upload takes its stride from the format rather than assuming four bytes.
34#[derive(Clone)]
35pub struct Image {
36    /// The face width, in texels.
37    pub width: u32,
38    /// The face height, in texels.
39    pub height: u32,
40    /// The decoded texel bytes, in the owning texture's format.
41    pub data: Vec<u8>,
42}
43
44impl Image {
45    /// An RGBA8 face, the `UnsignedByteType` default.
46    pub fn rgba8(width: u32, height: u32, data: Vec<u8>) -> Self {
47        assert_eq!(
48            data.len() as u32,
49            width * height * 4,
50            "three-rs: an RGBA8 cube face holds four bytes per texel"
51        );
52        Self {
53            width,
54            height,
55            data,
56        }
57    }
58
59    /// An `rgba16float` face from one binary16 bit pattern per channel — what
60    /// [`HdrData::HalfFloat`](crate::loaders::HdrData::HalfFloat) holds.
61    pub fn rgba16float(width: u32, height: u32, data: &[u16]) -> Self {
62        assert_eq!(
63            data.len() as u32,
64            width * height * 4,
65            "three-rs: an rgba16float cube face holds four halves per texel"
66        );
67        Self {
68            width,
69            height,
70            data: bytemuck::cast_slice(data).to_vec(),
71        }
72    }
73}
74
75/// The state behind a [`CubeTexture`] handle.
76#[derive(Debug)]
77pub struct CubeTextureInner {
78    /// `CubeTexture.images`, in the order px, nx, py, ny, pz, nz.
79    pub images: Vec<Image>,
80    /// `texture.mapping`.
81    pub mapping: Mapping,
82    /// `texture.colorSpace`.
83    pub color_space: ColorSpace,
84    /// `Texture.type` — `UnsignedByteType` for a PNG cube, `HalfFloatType` for
85    /// the one `HDRCubeTextureLoader` builds.
86    pub texture_type: TextureType,
87    /// `CubeTexture` overwrites `Texture.flipY` with `false`.
88    pub flip_y: bool,
89    /// `Texture.mipmaps`. For an *uncompressed* cube texture three.js uses
90    /// this array for the mips **only** — level 0 stays in `images` — so entry
91    /// `j` here is mip level `j + 1`, and each entry is six faces in the same
92    /// px, nx, py, ny, pz, nz order as `images`
93    /// (`WebGPUTextureUtils._copyCubeMapToTexture()`, which copies
94    /// `mipmaps[ j ].images[ i ]` to `mipLevel = j + 1`).
95    pub mipmaps: Vec<Vec<Image>>,
96    /// `Texture.generateMipmaps`, `true` by default.
97    pub generate_mipmaps: bool,
98    /// `Texture.anisotropy`.
99    pub anisotropy: u16,
100    /// `texture.magFilter`.
101    pub mag_filter: TextureFilter,
102    /// `texture.minFilter`.
103    pub min_filter: MinFilter,
104    pub(crate) gpu: Option<wgpu::Texture>,
105}
106
107/// Cloning is a handle copy.
108#[derive(Clone)]
109pub struct CubeTexture(Rc<RefCell<CubeTextureInner>>, TextureId);
110
111/// The id is identity, not content: leaving it out keeps the `Debug` of a
112/// binding description — what `examples/dump_wgsl.rs` prints beside the WGSL —
113/// a function of the texture itself.
114impl std::fmt::Debug for CubeTexture {
115    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116        f.debug_tuple("CubeTexture").field(&self.0).finish()
117    }
118}
119
120impl CubeTexture {
121    /// `cubeTexture.dispose()` — drops this handle, and nothing more: a texture
122    /// handle is an `Rc`, so the renderer frees the GPU side once every handle
123    /// is gone, at the top of the next render (`docs/scene-graph.md`,
124    /// "Identity and eviction"). Dropping the handle does the same; this
125    /// exists so three.js code ports line for line.
126    pub fn dispose(self) {}
127
128    /// `new CubeTexture()`: `CubeReflectionMapping`, `ClampToEdgeWrapping`,
129    /// `LinearFilter` / `LinearMipmapLinearFilter`, `RGBAFormat`,
130    /// `UnsignedByteType`, `NoColorSpace`, `flipY = false`.
131    pub fn new(images: Vec<Image>) -> Self {
132        Self(
133            Rc::new(RefCell::new(CubeTextureInner {
134                images,
135                mapping: Mapping::CubeReflection,
136                color_space: ColorSpace::NoColorSpace,
137                texture_type: TextureType::UnsignedByte,
138                flip_y: false,
139                mipmaps: Vec::new(),
140                generate_mipmaps: true,
141                anisotropy: 1,
142                mag_filter: TextureFilter::Linear,
143                min_filter: MinFilter::LinearMipmapLinear,
144                gpu: None,
145            })),
146            TextureId::next(),
147        )
148    }
149
150    /// `new CubeRenderTarget( size ).texture` — six faces of the right shape
151    /// and no pixels, to be rendered into rather than uploaded.
152    ///
153    /// `generateMipmaps` is false and both filters are `LinearFilter`, which is
154    /// what `fromEquirectangularTexture` copies off an `HDRLoader` texture, and
155    /// what three's own dump of `webgpu_postprocessing_bloom_emissive` shows:
156    /// the 512² cube it converts the 1024×512 HDR into has `mipLevelCount: 1`.
157    pub fn render_target(size: u32, texture_type: TextureType) -> Self {
158        let face = Image {
159            width: size,
160            height: size,
161            data: Vec::new(),
162        };
163        let texture = Self::new(vec![face; 6]);
164        {
165            let mut inner = texture.0.borrow_mut();
166            inner.texture_type = texture_type;
167            inner.generate_mipmaps = false;
168            inner.min_filter = MinFilter::Linear;
169            inner.mag_filter = TextureFilter::Linear;
170        }
171        texture
172    }
173
174    /// `PMREMGenerator._createRenderTarget( size, generateMipmaps, … )` — a
175    /// `HalfFloatType` cube render target with `LinearMipmapLinearFilter`.
176    ///
177    /// `levels` is the number of mip levels the GPU texture gets:
178    ///
179    /// * `Some( n )` is `_allocateTarget()`'s PMREM, whose `texture.mipmaps`
180    ///   lists one `{ width: size >> lod }` per prefiltered level. Three's
181    ///   render-target cube counts level 0 in that list; this port's
182    ///   [`CubeTextureInner::mipmaps`] never does, so it holds `n - 1` entries.
183    ///   Each level is rendered, none is generated.
184    /// * `None` is `_getSourceTarget()`'s `generateMipmaps: true`: the full
185    ///   chain, box-filtered from level 0 once its six faces are drawn.
186    pub(crate) fn pmrem_render_target(size: u32, levels: Option<u32>) -> Self {
187        let texture = Self::render_target(size, TextureType::HalfFloat);
188        {
189            let mut inner = texture.0.borrow_mut();
190            inner.min_filter = MinFilter::LinearMipmapLinear;
191            match levels {
192                Some(levels) => {
193                    inner.mipmaps = (1..levels)
194                        .map(|lod| {
195                            let face = Image {
196                                width: size >> lod,
197                                height: size >> lod,
198                                data: Vec::new(),
199                            };
200                            vec![face; 6]
201                        })
202                        .collect();
203                }
204                None => inner.generate_mipmaps = true,
205            }
206        }
207        texture
208    }
209
210    /// `texture.colorSpace = value`.
211    pub fn set_color_space(&self, color_space: ColorSpace) {
212        self.0.borrow_mut().color_space = color_space;
213    }
214
215    /// `texture.colorSpace`.
216    pub fn color_space(&self) -> ColorSpace {
217        self.0.borrow().color_space
218    }
219
220    /// `texture.mapping`.
221    pub fn mapping(&self) -> Mapping {
222        self.0.borrow().mapping
223    }
224
225    /// `texture.type = HalfFloatType`, with the filters and mip policy
226    /// `HDRCubeTextureLoader` sets alongside it left to the caller.
227    pub fn set_texture_type(&self, texture_type: TextureType) -> Result<(), crate::error::Error> {
228        if !texture_type.is_color() {
229            return Err(crate::error::Error::UnsupportedTextureType {
230                what: "colour",
231                texture_type,
232            });
233        }
234        self.0.borrow_mut().texture_type = texture_type;
235        Ok(())
236    }
237
238    /// `texture.type`.
239    pub fn texture_type(&self) -> TextureType {
240        self.0.borrow().texture_type
241    }
242
243    /// `texture.generateMipmaps = value`.
244    pub fn set_generate_mipmaps(&self, generate_mipmaps: bool) {
245        self.0.borrow_mut().generate_mipmaps = generate_mipmaps;
246    }
247
248    /// `texture.mipmaps = [ … ]` — hand-authored mip levels, level 1 first.
249    ///
250    /// Each entry is the six faces of one level, in the `images` order; the
251    /// page that uses this (`webgpu_materials_cubemap_mipmaps`) loads each
252    /// level as its own `CubeTexture` and assigns `texture.mipmaps` the list
253    /// of them after `shift()`-ing level 0 into `images`.
254    pub fn set_mipmaps(&self, mipmaps: Vec<Vec<Image>>) {
255        assert!(
256            mipmaps.iter().all(|level| level.len() == 6),
257            "three-rs: a cube mip level has six faces"
258        );
259        self.0.borrow_mut().mipmaps = mipmaps;
260    }
261
262    /// `texture.clone()` — a **new** texture (new id, so its own GPU
263    /// resource) over the same decoded faces, carrying every flag across, as
264    /// `Texture.copy()` does. Distinct from `Clone`, which is three.js'
265    /// object identity: the same texture under another name.
266    pub fn clone_texture(&self) -> Self {
267        let inner = self.0.borrow();
268        Self(
269            Rc::new(RefCell::new(CubeTextureInner {
270                images: inner.images.clone(),
271                mapping: inner.mapping,
272                color_space: inner.color_space,
273                texture_type: inner.texture_type,
274                flip_y: inner.flip_y,
275                mipmaps: inner.mipmaps.clone(),
276                generate_mipmaps: inner.generate_mipmaps,
277                anisotropy: inner.anisotropy,
278                mag_filter: inner.mag_filter,
279                min_filter: inner.min_filter,
280                gpu: None,
281            })),
282            TextureId::next(),
283        )
284    }
285
286    /// `texture.minFilter` / `texture.magFilter`.
287    pub fn set_filters(&self, min_filter: MinFilter, mag_filter: TextureFilter) {
288        let mut inner = self.0.borrow_mut();
289        inner.min_filter = min_filter;
290        inner.mag_filter = mag_filter;
291    }
292
293    /// `WebGPUTextureUtils.getFormat()` for `RGBAFormat` plus the texture's
294    /// type: the sRGB transfer function is applied by the GPU on sample, which
295    /// is why `WGSLNodeBuilder.needsToWorkingColorSpace()` stays `false` and no
296    /// colour-space node appears in the generated WGSL.
297    ///
298    /// `HalfFloatType` has no sRGB variant and never wants one — the HDR faces
299    /// are `LinearSRGBColorSpace`, i.e. the working space itself.
300    pub fn gpu_format(&self) -> wgpu::TextureFormat {
301        match self.texture_type() {
302            TextureType::HalfFloat => wgpu::TextureFormat::Rgba16Float,
303            _ => match self.color_space() {
304                ColorSpace::Srgb => wgpu::TextureFormat::Rgba8UnormSrgb,
305                ColorSpace::NoColorSpace | ColorSpace::LinearSrgb => {
306                    wgpu::TextureFormat::Rgba8Unorm
307                }
308            },
309        }
310    }
311
312    /// `Textures.getMipLevels()`, plus the `isCubeTexture` correction beside
313    /// its call site in `Textures.updateTexture()`.
314    ///
315    /// `needsMipmaps()` is `generateMipmaps === true || mipmaps.length > 0`, so
316    /// a texture with hand-supplied levels is mipmapped even with
317    /// `generateMipmaps = false`. `getMipLevels()` then returns
318    /// `mipmaps.length`, which for an uncompressed cube counts the mips only —
319    /// hence `if ( texture.isCubeTexture && texture.mipmaps.length > 0 )
320    /// options.levels ++`, the `+ 1` for level 0. Nine levels for the
321    /// `angus` 256² cube with its eight hand-authored mips, which is what
322    /// three.js' own descriptor says.
323    pub fn mip_level_count(&self) -> u32 {
324        let inner = self.0.borrow();
325        if !inner.mipmaps.is_empty() {
326            return inner.mipmaps.len() as u32 + 1;
327        }
328        if !inner.generate_mipmaps {
329            return 1;
330        }
331        let size = inner.images[0].width.max(inner.images[0].height) as f64;
332        size.log2().floor() as u32 + 1
333    }
334
335    /// `( image.width, image.height )` of face 0.
336    pub fn size(&self) -> (u32, u32) {
337        let inner = self.0.borrow();
338        (inner.images[0].width, inner.images[0].height)
339    }
340
341    /// `texture.id` — unique per texture, stable for its lifetime.
342    pub fn id(&self) -> usize {
343        self.1.get()
344    }
345
346    /// The handle's liveness, without the handle; see [`TextureOwner`].
347    ///
348    /// [`TextureOwner`]: super::TextureOwner
349    pub(crate) fn owner(&self) -> super::TextureOwner {
350        Rc::downgrade(&self.0) as super::TextureOwner
351    }
352
353    /// The faces and the flags, as `Texture::borrow()` gives them — enough to
354    /// assert the upload's stride, face order and row order without a GPU.
355    pub fn borrow(&self) -> Ref<'_, CubeTextureInner> {
356        self.0.borrow()
357    }
358
359    pub(crate) fn inner(&self) -> &RefCell<CubeTextureInner> {
360        &self.0
361    }
362}
363
364/// As `TextureInner`: six decoded faces are six megabyte buffers.
365impl std::fmt::Debug for Image {
366    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
367        f.debug_struct("Image")
368            .field("width", &self.width)
369            .field("height", &self.height)
370            .field("data", &super::texture::DataLen(self.data.len()))
371            .finish()
372    }
373}