Skip to main content

three_rs/textures/
data3d_texture.rs

1//! Ports of `three.js/src/textures/Data3DTexture.js` and
2//! `src/renderers/common/Storage3DTexture.js` — the two volume textures.
3//!
4//! One Rust type covers both, the way `Texture` covers `StorageTexture`: they
5//! differ in their constructor defaults and in whether the GPU texture is
6//! created with `STORAGE_BINDING`, and nothing else the port reads.
7//!
8//! - `Data3DTexture` holds CPU bytes, is `NearestFilter` on both filters,
9//!   `ClampToEdgeWrapping` on all three axes, `generateMipmaps = false`,
10//!   `flipY = false` and `unpackAlignment = 1`. `webgpu_volume_perlin` sets
11//!   `format = RedFormat` and both filters to `LinearFilter` on it.
12//! - `Storage3DTexture` holds no bytes — a compute kernel writes it — and is
13//!   `LinearFilter` on both filters with `mipmapsAutoUpdate = false`.
14//!
15//! Sampled, either is a `texture_3d<f32>` read through `texture3D()`
16//! ([`crate::nodes::tsl::texture_3d`]); stored to, a
17//! `texture_storage_3d<format, access>` ([`crate::nodes::tsl::texture_store`]).
18
19use super::texture::DataLen;
20use super::{MinFilter, TextureFilter, TextureId, Wrapping};
21use std::cell::{Ref, RefCell};
22use std::rc::Rc;
23
24/// The state behind a [`Data3DTexture`] handle.
25pub struct Data3DTextureInner {
26    /// `image.width`.
27    pub width: u32,
28    /// `image.height`.
29    pub height: u32,
30    /// `image.depth`.
31    pub depth: u32,
32    /// `image.data`, tightly packed texel rows, slice after slice — the
33    /// `Uint8Array` of `webgpu_volume_perlin` for an `r8unorm` texture. `None`
34    /// for a storage texture, which the GPU fills.
35    pub data: Option<Vec<u8>>,
36    /// `texture.format` + `texture.type`, spelled as the GPU format
37    /// `WebGPUTextureUtils.getFormat()` would pick.
38    pub format: wgpu::TextureFormat,
39    /// `texture.magFilter`.
40    pub mag_filter: TextureFilter,
41    /// `texture.minFilter`.
42    pub min_filter: MinFilter,
43    /// `texture.wrapS`.
44    pub wrap_s: Wrapping,
45    /// `texture.wrapT`.
46    pub wrap_t: Wrapping,
47    /// `texture.wrapR` — the third axis, unique to a volume texture.
48    pub wrap_r: Wrapping,
49    /// `texture.isStorageTexture` — created with `STORAGE_BINDING` and bound
50    /// as `texture_storage_3d` by `storageTexture()` / `textureStore()`.
51    pub is_storage: bool,
52    /// `texture.version`, bumped by `needsUpdate = true`.
53    pub version: u32,
54    uploaded: u32,
55    pub(crate) gpu: Option<wgpu::Texture>,
56}
57
58/// Cloning is a handle copy, as in JS.
59#[derive(Clone)]
60pub struct Data3DTexture(Rc<RefCell<Data3DTextureInner>>, TextureId);
61
62impl std::fmt::Debug for Data3DTexture {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        f.debug_tuple("Data3DTexture").field(&self.0).finish()
65    }
66}
67
68impl Data3DTexture {
69    /// `data3DTexture.dispose()` — drops this handle, and nothing more: a texture
70    /// handle is an `Rc`, so the renderer frees the GPU side once every handle
71    /// is gone, at the top of the next render (`docs/scene-graph.md`,
72    /// "Identity and eviction"). Dropping the handle does the same; this
73    /// exists so three.js code ports line for line.
74    pub fn dispose(self) {}
75
76    /// `new Data3DTexture( data, width, height, depth )` with
77    /// `texture.format` already applied as `format`: `RedFormat` +
78    /// `UnsignedByteType` is [`wgpu::TextureFormat::R8Unorm`], the default
79    /// `RGBAFormat` is [`wgpu::TextureFormat::Rgba8Unorm`].
80    ///
81    /// Panics if `data` is not exactly `width * height * depth` texels of
82    /// `format` — a short volume would shear every slice after the first.
83    pub fn new(
84        data: Vec<u8>,
85        width: u32,
86        height: u32,
87        depth: u32,
88        format: wgpu::TextureFormat,
89    ) -> Self {
90        let texel = format
91            .block_copy_size(None)
92            .expect("three-rs: the texture format has no single block size");
93        assert_eq!(
94            data.len(),
95            (width * height * depth * texel) as usize,
96            "three-rs: a {width}x{height}x{depth} {format:?} Data3DTexture holds {} bytes",
97            width * height * depth * texel
98        );
99        Self::with(Some(data), width, height, depth, format, false)
100    }
101
102    /// `new Storage3DTexture( width, height, depth )`: `rgba8unorm` until
103    /// [`set_format`](Self::set_format) says otherwise (`texture.type =
104    /// HalfFloatType` is `rgba16float`), `LinearFilter` on both filters.
105    ///
106    /// `mipmapsAutoUpdate = false` and every read three makes of one goes
107    /// through `texture3D( t, null, 0 )`, i.e. level 0, so the port allocates
108    /// the one level that is ever written or read rather than the full chain
109    /// three allocates and leaves empty.
110    pub fn storage(width: u32, height: u32, depth: u32) -> Self {
111        let texture = Self::with(
112            None,
113            width,
114            height,
115            depth,
116            wgpu::TextureFormat::Rgba8Unorm,
117            true,
118        );
119        {
120            let mut inner = texture.0.borrow_mut();
121            inner.mag_filter = TextureFilter::Linear;
122            inner.min_filter = MinFilter::Linear;
123        }
124        texture
125    }
126
127    fn with(
128        data: Option<Vec<u8>>,
129        width: u32,
130        height: u32,
131        depth: u32,
132        format: wgpu::TextureFormat,
133        is_storage: bool,
134    ) -> Self {
135        Self(
136            Rc::new(RefCell::new(Data3DTextureInner {
137                width,
138                height,
139                depth,
140                data,
141                format,
142                mag_filter: TextureFilter::Nearest,
143                min_filter: MinFilter::Nearest,
144                wrap_s: Wrapping::ClampToEdge,
145                wrap_t: Wrapping::ClampToEdge,
146                wrap_r: Wrapping::ClampToEdge,
147                is_storage,
148                version: 1,
149                uploaded: 0,
150                gpu: None,
151            })),
152            TextureId::next(),
153        )
154    }
155
156    /// `texture.id` — unique per texture, stable for its lifetime.
157    pub fn id(&self) -> usize {
158        self.1.get()
159    }
160
161    /// The liveness handle the renderer's caches sweep on; see
162    /// [`TextureOwner`].
163    ///
164    /// [`TextureOwner`]: super::TextureOwner
165    pub(crate) fn owner(&self) -> super::TextureOwner {
166        Rc::downgrade(&self.0) as super::TextureOwner
167    }
168
169    /// Borrows the texture's data, size, format and sampling state.
170    pub fn borrow(&self) -> Ref<'_, Data3DTextureInner> {
171        self.0.borrow()
172    }
173
174    /// `( image.width, image.height, image.depth )`.
175    pub fn size(&self) -> (u32, u32, u32) {
176        let inner = self.0.borrow();
177        (inner.width, inner.height, inner.depth)
178    }
179
180    /// The GPU format `texture.format` / `texture.type` was translated to.
181    pub fn format(&self) -> wgpu::TextureFormat {
182        self.0.borrow().format
183    }
184
185    /// `texture.format` / `texture.type` before the first upload.
186    pub fn set_format(&self, format: wgpu::TextureFormat) {
187        let mut inner = self.0.borrow_mut();
188        assert!(
189            inner.gpu.is_none(),
190            "three-rs: the format of a Data3DTexture is fixed once it is on the GPU"
191        );
192        inner.format = format;
193    }
194
195    /// `texture.isStorageTexture`.
196    pub fn is_storage(&self) -> bool {
197        self.0.borrow().is_storage
198    }
199
200    /// `texture.minFilter = value`.
201    pub fn set_min_filter(&self, min_filter: MinFilter) {
202        self.0.borrow_mut().min_filter = min_filter;
203    }
204
205    /// `texture.magFilter = value`.
206    pub fn set_mag_filter(&self, mag_filter: TextureFilter) {
207        self.0.borrow_mut().mag_filter = mag_filter;
208    }
209
210    /// `texture.wrapS = wrap_s; texture.wrapT = wrap_t; texture.wrapR = wrap_r`.
211    pub fn set_wrapping(&self, wrap_s: Wrapping, wrap_t: Wrapping, wrap_r: Wrapping) {
212        let mut inner = self.0.borrow_mut();
213        inner.wrap_s = wrap_s;
214        inner.wrap_t = wrap_t;
215        inner.wrap_r = wrap_r;
216    }
217
218    /// `WGSLNodeBuilder.isUnfilterable()` for this texture: `NearestFilter` on
219    /// both filters (the `Data3DTexture` default), or a format the GPU cannot
220    /// filter.
221    pub(crate) fn is_unfilterable(&self) -> bool {
222        let inner = self.0.borrow();
223        let nearest =
224            inner.mag_filter == TextureFilter::Nearest && inner.min_filter == MinFilter::Nearest;
225        nearest
226            || !matches!(
227                inner.format.sample_type(None, None),
228                Some(wgpu::TextureSampleType::Float { filterable: true })
229            )
230    }
231
232    /// `texture.needsUpdate = true`.
233    pub fn set_needs_update(&self) {
234        self.0.borrow_mut().version += 1;
235    }
236
237    /// `texture.image.data.set( data ); texture.needsUpdate = true`.
238    pub fn set_data(&self, data: Vec<u8>) {
239        let mut inner = self.0.borrow_mut();
240        assert!(
241            !inner.is_storage,
242            "three-rs: a Storage3DTexture is written by the GPU, not from the CPU"
243        );
244        let expected = inner.data.as_ref().map_or(0, Vec::len);
245        assert_eq!(
246            data.len(),
247            expected,
248            "three-rs: set_data got {} bytes for a Data3DTexture that holds {expected}",
249            data.len()
250        );
251        inner.data = Some(data);
252        inner.version += 1;
253    }
254
255    /// `texture.version`.
256    pub fn version(&self) -> u32 {
257        self.0.borrow().version
258    }
259
260    pub(crate) fn set_gpu(&self, gpu: wgpu::Texture) {
261        self.0.borrow_mut().gpu = Some(gpu);
262    }
263
264    pub(crate) fn has_gpu(&self) -> bool {
265        self.0.borrow().gpu.is_some()
266    }
267
268    /// True when the GPU texture is missing, or — for a data texture — the
269    /// bytes have moved on since the last upload. A storage texture is never
270    /// uploaded to, so once it exists it is current.
271    pub(crate) fn needs_upload(&self) -> bool {
272        let inner = self.0.borrow();
273        inner.gpu.is_none() || (!inner.is_storage && inner.uploaded != inner.version)
274    }
275
276    pub(crate) fn mark_uploaded(&self) {
277        let mut inner = self.0.borrow_mut();
278        inner.uploaded = inner.version;
279    }
280
281    /// Runs `f` with the uploaded GPU texture. Panics if the texture has not
282    /// been uploaded yet.
283    pub fn with_gpu<R>(&self, f: impl FnOnce(&wgpu::Texture) -> R) -> R {
284        let inner = self.0.borrow();
285        f(inner
286            .gpu
287            .as_ref()
288            .expect("three-rs: 3D texture not uploaded"))
289    }
290}
291
292impl std::fmt::Debug for Data3DTextureInner {
293    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
294        f.debug_struct("Data3DTextureInner")
295            .field("width", &self.width)
296            .field("height", &self.height)
297            .field("depth", &self.depth)
298            .field("data", &self.data.as_ref().map(|data| DataLen(data.len())))
299            .field("format", &self.format)
300            .field("mag_filter", &self.mag_filter)
301            .field("min_filter", &self.min_filter)
302            .field("wrap_s", &self.wrap_s)
303            .field("wrap_t", &self.wrap_t)
304            .field("wrap_r", &self.wrap_r)
305            .field("is_storage", &self.is_storage)
306            .field("gpu", &self.gpu)
307            .finish()
308    }
309}
310
311#[cfg(test)]
312mod tests {
313    use super::*;
314
315    /// `Data3DTexture`'s constructor defaults (`Data3DTexture.js`).
316    #[test]
317    fn a_data_3d_texture_is_nearest_and_clamped() {
318        let texture = Data3DTexture::new(vec![0; 8], 2, 2, 2, wgpu::TextureFormat::R8Unorm);
319        let inner = texture.borrow();
320        assert_eq!(inner.mag_filter, TextureFilter::Nearest);
321        assert_eq!(inner.min_filter, MinFilter::Nearest);
322        assert_eq!(inner.wrap_r, Wrapping::ClampToEdge);
323        assert!(!inner.is_storage);
324        drop(inner);
325        assert!(texture.is_unfilterable());
326        assert!(texture.needs_upload());
327    }
328
329    /// `webgpu_volume_perlin` turns both filters to `LinearFilter`, which is
330    /// what makes the volume `textureSampleLevel`-able.
331    #[test]
332    fn linear_filters_make_it_filterable() {
333        let texture = Data3DTexture::new(vec![0; 8], 2, 2, 2, wgpu::TextureFormat::R8Unorm);
334        texture.set_min_filter(MinFilter::Linear);
335        texture.set_mag_filter(TextureFilter::Linear);
336        assert!(!texture.is_unfilterable());
337    }
338
339    #[test]
340    #[should_panic(expected = "holds 32 bytes")]
341    fn the_byte_count_follows_the_format() {
342        Data3DTexture::new(vec![0; 8], 2, 2, 2, wgpu::TextureFormat::Rgba8Unorm);
343    }
344
345    /// `Storage3DTexture`'s constructor defaults (`Storage3DTexture.js`).
346    #[test]
347    fn a_storage_3d_texture_is_linear_and_empty() {
348        let texture = Data3DTexture::storage(4, 4, 4);
349        assert!(texture.is_storage());
350        assert!(!texture.is_unfilterable());
351        assert!(texture.borrow().data.is_none());
352        assert_eq!(texture.format(), wgpu::TextureFormat::Rgba8Unorm);
353    }
354
355    #[test]
356    fn set_data_bumps_the_version() {
357        let texture = Data3DTexture::new(vec![0; 8], 2, 2, 2, wgpu::TextureFormat::R8Unorm);
358        let before = texture.version();
359        texture.set_data(vec![1; 8]);
360        assert_eq!(texture.version(), before + 1);
361    }
362}