Skip to main content

alpha2_render/
effect_resource.rs

1use std::collections::HashMap;
2use std::fmt;
3
4use half::f16;
5use wgpu::util::DeviceExt;
6
7use crate::{EffectResourceKind, RenderError, Renderer};
8
9/// Canonical RGB samples for one cubic 3D lookup table.
10#[derive(Clone, Debug, PartialEq)]
11pub struct Lut3dData {
12    /// Equal width, height, and depth of the cube.
13    pub edge_length: u32,
14    /// Per-channel input-domain lower bound declared by the file.
15    pub domain_min: [f32; 3],
16    /// Per-channel input-domain upper bound declared by the file.
17    pub domain_max: [f32; 3],
18    /// RGB samples in blue-major, green-middle, red-fastest order.
19    pub values: Vec<[f32; 3]>,
20}
21
22impl Lut3dData {
23    /// Parses the portable 3D subset of the Adobe/Resolve `.cube` format.
24    ///
25    /// Accepts `TITLE`, comments, per-channel domains, `LUT_3D_INPUT_RANGE`, CRLF, and a leading
26    /// UTF-8 BOM (browsers strip it, `std::fs::read_to_string` keeps it). 1D tables are rejected
27    /// rather than misread.
28    ///
29    /// # Errors
30    /// Returns a line-oriented diagnostic for malformed or unsupported input.
31    pub fn from_cube(text: &str) -> Result<Self, LutParseError> {
32        let mut edge = None;
33        let mut domain_min = [0.0; 3];
34        let mut domain_max = [1.0; 3];
35        let mut values = Vec::new();
36        let text = text.strip_prefix('\u{feff}').unwrap_or(text);
37        for (index, raw) in text.lines().enumerate() {
38            let line_number = index + 1;
39            let line = raw.split('#').next().unwrap_or_default().trim();
40            if line.is_empty() || line.starts_with("TITLE") {
41                continue;
42            }
43            let fields = line.split_whitespace().collect::<Vec<_>>();
44            match fields[0] {
45                "LUT_3D_SIZE" if fields.len() == 2 => {
46                    let parsed = fields[1]
47                        .parse::<u32>()
48                        .map_err(|_| LutParseError::new(line_number, "invalid LUT_3D_SIZE"))?;
49                    if parsed < 2 {
50                        return Err(LutParseError::new(
51                            line_number,
52                            "LUT_3D_SIZE must be at least two",
53                        ));
54                    }
55                    edge = Some(parsed);
56                }
57                "LUT_1D_SIZE" => {
58                    return Err(LutParseError::new(
59                        line_number,
60                        "one-dimensional .cube tables are not supported",
61                    ));
62                }
63                "DOMAIN_MIN" if fields.len() == 4 => {
64                    domain_min = parse_triplet(&fields[1..], line_number)?;
65                }
66                "DOMAIN_MAX" if fields.len() == 4 => {
67                    domain_max = parse_triplet(&fields[1..], line_number)?;
68                }
69                "LUT_3D_INPUT_RANGE" if fields.len() == 3 => {
70                    let min = parse_component(fields[1], line_number)?;
71                    let max = parse_component(fields[2], line_number)?;
72                    domain_min = [min; 3];
73                    domain_max = [max; 3];
74                }
75                directive if directive.chars().next().is_some_and(char::is_alphabetic) => {
76                    return Err(LutParseError::new(
77                        line_number,
78                        format!("unsupported .cube directive {directive}"),
79                    ));
80                }
81                _ if fields.len() == 3 => values.push(parse_triplet(&fields, line_number)?),
82                _ => {
83                    return Err(LutParseError::new(
84                        line_number,
85                        "expected an RGB sample or supported .cube directive",
86                    ));
87                }
88            }
89        }
90        let edge = edge.ok_or_else(|| LutParseError::new(0, "missing LUT_3D_SIZE"))?;
91        let expected = usize::try_from(edge)
92            .ok()
93            .and_then(|value| value.checked_pow(3))
94            .ok_or_else(|| LutParseError::new(0, "LUT size is too large"))?;
95        if values.len() != expected {
96            return Err(LutParseError::new(
97                0,
98                format!("expected {expected} RGB samples, found {}", values.len()),
99            ));
100        }
101        if domain_min
102            .iter()
103            .zip(domain_max)
104            .any(|(min, max)| *min >= max)
105        {
106            return Err(LutParseError::new(
107                0,
108                ".cube input domain minimum must be below its maximum",
109            ));
110        }
111        Ok(Self {
112            edge_length: edge,
113            domain_min,
114            domain_max,
115            values,
116        })
117    }
118
119    pub(crate) fn is_valid(&self, maximum: u32) -> bool {
120        self.edge_length >= 2
121            && self.edge_length <= maximum
122            && usize::try_from(self.edge_length)
123                .ok()
124                .and_then(|value| value.checked_pow(3))
125                .is_some_and(|expected| expected == self.values.len())
126            && self.values.iter().flatten().all(|value| value.is_finite())
127            && self
128                .domain_min
129                .iter()
130                .zip(self.domain_max)
131                .all(|(min, max)| min.is_finite() && max.is_finite() && *min < max)
132    }
133}
134
135fn parse_triplet(fields: &[&str], line: usize) -> Result<[f32; 3], LutParseError> {
136    let mut output = [0.0; 3];
137    for (target, field) in output.iter_mut().zip(fields) {
138        *target = parse_component(field, line)?;
139    }
140    Ok(output)
141}
142
143fn parse_component(field: &str, line: usize) -> Result<f32, LutParseError> {
144    field
145        .parse::<f32>()
146        .ok()
147        .filter(|value| value.is_finite())
148        .ok_or_else(|| LutParseError::new(line, "invalid finite RGB component"))
149}
150
151/// Diagnostic returned while parsing `.cube` text.
152#[derive(Clone, Debug, Eq, PartialEq)]
153pub struct LutParseError {
154    line: usize,
155    message: String,
156}
157
158impl LutParseError {
159    fn new(line: usize, message: impl Into<String>) -> Self {
160        Self {
161            line,
162            message: message.into(),
163        }
164    }
165}
166
167impl fmt::Display for LutParseError {
168    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
169        if self.line == 0 {
170            formatter.write_str(&self.message)
171        } else {
172            write!(formatter, ".cube line {}: {}", self.line, self.message)
173        }
174    }
175}
176
177impl std::error::Error for LutParseError {}
178
179#[derive(Debug)]
180pub(crate) struct RegisteredEffectResource {
181    pub(crate) kind: EffectResourceKind,
182    pub(crate) _texture: wgpu::Texture,
183    pub(crate) view: wgpu::TextureView,
184    pub(crate) metadata: wgpu::Buffer,
185}
186
187/// Entries are shared so a frame keeps drawing with a resource another thread replaces.
188pub(crate) type EffectResourceRegistry = HashMap<String, crate::Shared<RegisteredEffectResource>>;
189
190impl Renderer {
191    /// Uploads or replaces one filterable 3D LUT resource; on failure the registry is unchanged.
192    ///
193    /// # Errors [`RenderError::InvalidEffectResource`] for an invalid id, shape, sample or
194    /// device-incompatible edge length, and [`RenderError::Gpu`] when the device cannot create the
195    /// texture (native only; a browser reports it as an uncaptured error).
196    pub fn register_lut3d(
197        &self,
198        id: impl Into<String>,
199        data: &Lut3dData,
200    ) -> Result<(), RenderError> {
201        let id = id.into();
202        if id.is_empty() || !data.is_valid(self.limits.max_texture_dimension_3d) {
203            return Err(RenderError::InvalidEffectResource);
204        }
205        let mut bytes = Vec::with_capacity(data.values.len() * 8);
206        for rgb in &data.values {
207            for value in [rgb[0], rgb[1], rgb[2], 1.0] {
208                bytes.extend_from_slice(&f16::from_f32(value).to_bits().to_le_bytes());
209            }
210        }
211        let (texture, error) = crate::gpu_errors::capture_creation(self.gpu.device(), || {
212            self.gpu.device().create_texture_with_data(
213                self.gpu.queue(),
214                &wgpu::TextureDescriptor {
215                    label: Some(&format!("alpha2 LUT resource {id}")),
216                    size: wgpu::Extent3d {
217                        width: data.edge_length,
218                        height: data.edge_length,
219                        depth_or_array_layers: data.edge_length,
220                    },
221                    mip_level_count: 1,
222                    sample_count: 1,
223                    dimension: wgpu::TextureDimension::D3,
224                    format: wgpu::TextureFormat::Rgba16Float,
225                    usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
226                    view_formats: &[],
227                },
228                wgpu::util::TextureDataOrder::LayerMajor,
229                &bytes,
230            )
231        });
232        if let Some(kind) = error {
233            return Err(RenderError::Gpu { kind });
234        }
235        let view = crate::pool::default_view(&texture);
236        let mut metadata_bytes = Vec::with_capacity(32);
237        for value in [
238            data.domain_min[0],
239            data.domain_min[1],
240            data.domain_min[2],
241            0.0,
242            data.domain_max[0],
243            data.domain_max[1],
244            data.domain_max[2],
245            0.0,
246        ] {
247            metadata_bytes.extend_from_slice(&value.to_le_bytes());
248        }
249        let metadata = self
250            .gpu
251            .device()
252            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
253                label: Some(&format!("alpha2 LUT metadata {id}")),
254                contents: &metadata_bytes,
255                usage: wgpu::BufferUsages::UNIFORM,
256            });
257        self.effect_resources_mut().insert(
258            id,
259            crate::Shared::new(RegisteredEffectResource {
260                kind: EffectResourceKind::Lut3d,
261                _texture: texture,
262                view,
263                metadata,
264            }),
265        );
266        // Results reference resources by id, and its pixels may have changed.
267        self.clear_result_cache_for(crate::CacheInvalidation::EffectResources);
268        Ok(())
269    }
270
271    /// Removes one uploaded resource, clearing cached results; returns whether it existed.
272    pub fn unregister_effect_resource(&self, id: &str) -> bool {
273        let removed = self.effect_resources_mut().remove(id).is_some();
274        if removed {
275            self.clear_result_cache_for(crate::CacheInvalidation::EffectResources);
276        }
277        removed
278    }
279
280    /// Removes all uploaded effect resources and clears the cached results.
281    pub fn clear_effect_resources(&self) {
282        self.effect_resources_mut().clear();
283        self.clear_result_cache_for(crate::CacheInvalidation::EffectResources);
284    }
285
286    pub(crate) fn effect_resource(
287        &self,
288        id: &str,
289    ) -> Option<crate::Shared<RegisteredEffectResource>> {
290        self.effect_resources
291            .read()
292            .unwrap_or_else(std::sync::PoisonError::into_inner)
293            .get(id)
294            .cloned()
295    }
296
297    fn effect_resources_mut(&self) -> std::sync::RwLockWriteGuard<'_, EffectResourceRegistry> {
298        self.effect_resources
299            .write()
300            .unwrap_or_else(std::sync::PoisonError::into_inner)
301    }
302}
303
304#[cfg(test)]
305mod tests {
306    use super::*;
307
308    #[test]
309    fn parses_a_three_dimensional_cube() {
310        let data = Lut3dData::from_cube(
311            "TITLE \"identity\"\nLUT_3D_SIZE 2\nDOMAIN_MIN 0 0 0\nDOMAIN_MAX 1 1 1\n\
312             0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n",
313        )
314        .expect("valid cube");
315        assert_eq!(data.edge_length, 2);
316        assert_triplet_eq(data.domain_min, [0.0; 3]);
317        assert_eq!(data.values.len(), 8);
318        assert_triplet_eq(data.values[7], [1.0, 1.0, 1.0]);
319    }
320
321    #[test]
322    fn accepts_non_unit_domains_and_rejects_invalid_cubes() {
323        let ranged = Lut3dData::from_cube(
324            "LUT_3D_SIZE 2\nDOMAIN_MIN -1 -0.5 0\nDOMAIN_MAX 1 1.5 2\n\
325             0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n",
326        )
327        .expect("per-channel domains are supported");
328        assert_triplet_eq(ranged.domain_min, [-1.0, -0.5, 0.0]);
329        assert_triplet_eq(ranged.domain_max, [1.0, 1.5, 2.0]);
330        assert!(
331            Lut3dData::from_cube("LUT_3D_SIZE 2\nDOMAIN_MIN 2 2 2\nDOMAIN_MAX 1 1 1\n").is_err()
332        );
333        assert!(Lut3dData::from_cube("LUT_3D_SIZE 2\n0 0 0\n").is_err());
334    }
335
336    #[test]
337    fn a_cube_written_with_a_byte_order_mark_or_crlf_parses_as_without() {
338        // Browsers strip a leading BOM and `fs::read_to_string` keeps it, so the parser must too.
339        let body = "LUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n";
340        let plain = Lut3dData::from_cube(body).expect("valid cube");
341        for text in [
342            format!("\u{feff}{body}"),
343            format!("\u{feff}TITLE \"bom\"\n{body}"),
344            format!("\u{feff}# written by a Windows tool\n{body}"),
345            body.replace('\n', "\r\n"),
346            format!("\u{feff}{}", body.replace('\n', "\r\n")),
347        ] {
348            assert_eq!(Lut3dData::from_cube(&text), Ok(plain.clone()), "{text:?}");
349        }
350        // Only a leading BOM is skipped; elsewhere it is not whitespace.
351        let inner = Lut3dData::from_cube(&body.replace("0 0 1\n", "\u{feff}0 0 1\n"))
352            .expect_err("a mark inside the file is not text the parser knows");
353        assert_eq!(inner.line, 6);
354    }
355
356    #[test]
357    fn a_cube_refuses_one_dimensional_tables_and_unknown_directives_by_line() {
358        let one_dimensional = Lut3dData::from_cube("TITLE \"1d\"\nLUT_1D_SIZE 2\n0 0 0\n1 1 1\n")
359            .expect_err("a 1D table is a different transform");
360        assert_eq!(one_dimensional.line, 2);
361        assert!(one_dimensional.to_string().contains("one-dimensional"));
362        let unknown = Lut3dData::from_cube("LUT_3D_SIZE 2\nLUT_3D_SHAPER 4\n")
363            .expect_err("an unknown directive is refused, not skipped");
364        assert_eq!(unknown.line, 2);
365        assert!(unknown.to_string().contains("LUT_3D_SHAPER"));
366    }
367
368    fn assert_triplet_eq(actual: [f32; 3], expected: [f32; 3]) {
369        assert!(
370            actual
371                .iter()
372                .zip(expected)
373                .all(|(actual, expected)| (*actual - expected).abs() <= f32::EPSILON)
374        );
375    }
376}