Skip to main content

three_rs/textures/
data_texture.rs

1//! Port of `three.js/src/textures/DataTexture.js` — the flat 2-D data texture
2//! `BatchedMesh` keeps its per-instance matrices, colours and the indirect
3//! (draw-ordinal → instance-id) table in.
4//!
5//! Three's `DataTexture` is `NearestFilter` with no mipmaps and is only ever
6//! read with `textureLoad`, so — like `DataArrayTexture` — it has no sampler
7//! binding at all.
8
9use super::TextureId;
10use std::cell::{Ref, RefCell};
11use std::rc::Rc;
12
13/// `texture.type` / `texture.format`, the only two combinations the ladder
14/// needs: `FloatType` + `RGBAFormat` (`rgba32float`) and `UnsignedIntType` +
15/// `RedIntegerFormat` (`r32uint`).
16#[derive(Clone, Debug)]
17#[non_exhaustive]
18pub enum DataTextureData {
19    /// `Float32Array`, four channels per texel — `rgba32float`.
20    F32(Vec<f32>),
21    /// `Uint32Array`, one channel per texel — `r32uint`.
22    U32(Vec<u32>),
23}
24
25/// The state behind a [`DataTexture`] handle.
26pub struct DataTextureInner {
27    /// `texture.image.data`.
28    pub data: DataTextureData,
29    /// `texture.image.width`.
30    pub width: u32,
31    /// `texture.image.height`.
32    pub height: u32,
33    /// `texture.version`, bumped by `needsUpdate = true`. The renderer
34    /// re-uploads when this runs ahead of `uploaded`.
35    pub version: u32,
36    uploaded: u32,
37    pub(crate) gpu: Option<wgpu::Texture>,
38}
39
40/// Cloning is a handle copy, as in JS.
41#[derive(Clone)]
42pub struct DataTexture(Rc<RefCell<DataTextureInner>>, TextureId);
43
44impl std::fmt::Debug for DataTexture {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        f.debug_tuple("DataTexture").field(&self.0).finish()
47    }
48}
49
50impl DataTexture {
51    /// `dataTexture.dispose()` — drops this handle, and nothing more: a texture
52    /// handle is an `Rc`, so the renderer frees the GPU side once every handle
53    /// is gone, at the top of the next render (`docs/scene-graph.md`,
54    /// "Identity and eviction"). Dropping the handle does the same; this
55    /// exists so three.js code ports line for line.
56    pub fn dispose(self) {}
57
58    /// `new DataTexture( new Float32Array( w * h * 4 ), w, h, RGBAFormat, FloatType )`.
59    pub fn new_f32(data: Vec<f32>, width: u32, height: u32) -> Self {
60        Self::new(DataTextureData::F32(data), width, height)
61    }
62
63    /// `new DataTexture( new Uint32Array( w * h ), w, h, RedIntegerFormat, UnsignedIntType )`.
64    pub fn new_u32(data: Vec<u32>, width: u32, height: u32) -> Self {
65        Self::new(DataTextureData::U32(data), width, height)
66    }
67
68    fn new(data: DataTextureData, width: u32, height: u32) -> Self {
69        Self(
70            Rc::new(RefCell::new(DataTextureInner {
71                data,
72                width,
73                height,
74                version: 1,
75                uploaded: 0,
76                gpu: None,
77            })),
78            TextureId::next(),
79        )
80    }
81
82    /// `texture.id` — unique per texture, stable for its lifetime.
83    pub fn id(&self) -> usize {
84        self.1.get()
85    }
86
87    /// The handle's liveness, without the handle; see [`TextureOwner`].
88    ///
89    /// [`TextureOwner`]: super::TextureOwner
90    pub(crate) fn owner(&self) -> super::TextureOwner {
91        Rc::downgrade(&self.0) as super::TextureOwner
92    }
93
94    /// Borrows the texture's data, width and height.
95    pub fn borrow(&self) -> Ref<'_, DataTextureInner> {
96        self.0.borrow()
97    }
98
99    /// `( texture.image.width, texture.image.height )`.
100    pub fn size(&self) -> (u32, u32) {
101        let inner = self.0.borrow();
102        (inner.width, inner.height)
103    }
104
105    /// `texture.image.data` is an integer array — the binding is
106    /// `texture_2d<u32>` rather than `texture_2d<f32>`.
107    pub(crate) fn is_uint(&self) -> bool {
108        matches!(self.0.borrow().data, DataTextureData::U32(_))
109    }
110
111    /// `texture.needsUpdate = true`.
112    pub fn set_needs_update(&self) {
113        self.0.borrow_mut().version += 1;
114    }
115
116    /// Edit the float payload in place and bump the version.
117    pub fn with_f32_mut<R>(&self, f: impl FnOnce(&mut [f32]) -> R) -> R {
118        let mut inner = self.0.borrow_mut();
119        inner.version += 1;
120        match &mut inner.data {
121            DataTextureData::F32(v) => f(v),
122            DataTextureData::U32(_) => panic!("three-rs: data texture is not a float texture"),
123        }
124    }
125
126    /// Edit the uint payload in place and bump the version.
127    pub fn with_u32_mut<R>(&self, f: impl FnOnce(&mut [u32]) -> R) -> R {
128        let mut inner = self.0.borrow_mut();
129        inner.version += 1;
130        match &mut inner.data {
131            DataTextureData::U32(v) => f(v),
132            DataTextureData::F32(_) => panic!("three-rs: data texture is not a uint texture"),
133        }
134    }
135
136    /// Read the float payload — `getMatrixAt` and the unit tests.
137    pub fn with_f32<R>(&self, f: impl FnOnce(&[f32]) -> R) -> R {
138        let inner = self.0.borrow();
139        match &inner.data {
140            DataTextureData::F32(v) => f(v),
141            DataTextureData::U32(_) => panic!("three-rs: data texture is not a float texture"),
142        }
143    }
144
145    /// Read the uint payload.
146    pub fn with_u32<R>(&self, f: impl FnOnce(&[u32]) -> R) -> R {
147        let inner = self.0.borrow();
148        match &inner.data {
149            DataTextureData::U32(v) => f(v),
150            DataTextureData::F32(_) => panic!("three-rs: data texture is not a uint texture"),
151        }
152    }
153
154    pub(crate) fn set_gpu(&self, gpu: wgpu::Texture) {
155        self.0.borrow_mut().gpu = Some(gpu);
156    }
157
158    pub(crate) fn has_gpu(&self) -> bool {
159        self.0.borrow().gpu.is_some()
160    }
161
162    /// True when the CPU-side payload has moved on since the last upload.
163    pub(crate) fn needs_upload(&self) -> bool {
164        let inner = self.0.borrow();
165        inner.gpu.is_none() || inner.uploaded != inner.version
166    }
167
168    pub(crate) fn mark_uploaded(&self) {
169        let mut inner = self.0.borrow_mut();
170        inner.uploaded = inner.version;
171    }
172
173    /// Runs `f` with the uploaded GPU texture. Panics if the texture has not
174    /// been uploaded yet.
175    pub fn with_gpu<R>(&self, f: impl FnOnce(&wgpu::Texture) -> R) -> R {
176        let inner = self.0.borrow();
177        f(inner
178            .gpu
179            .as_ref()
180            .expect("three-rs: data texture not uploaded"))
181    }
182}
183
184impl std::fmt::Debug for DataTextureInner {
185    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
186        let len = match &self.data {
187            DataTextureData::F32(v) => v.len(),
188            DataTextureData::U32(v) => v.len(),
189        };
190        f.debug_struct("DataTextureInner")
191            .field("data", &super::texture::DataLen(len))
192            .field("width", &self.width)
193            .field("height", &self.height)
194            .field("gpu", &self.gpu)
195            .finish()
196    }
197}