catwalk3d 1.2.0

Headless model thumbnails rendered entirely in Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! Z-up geometry and linear-color appearances used by the software renderer.

use image::RgbaImage;
use std::collections::{BTreeMap, HashSet};
use std::ops::{Add, Div, Mul, Neg, Sub};
use std::sync::Arc;

/// A three-component position or direction in double precision.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[must_use]
pub struct Vec3 {
    /// Component along the X axis.
    pub x: f64,
    /// Component along the Y axis.
    pub y: f64,
    /// Component along the vertical Z axis.
    pub z: f64,
}

impl Vec3 {
    /// Construct a vector without changing or validating its components.
    pub const fn new(x: f64, y: f64, z: f64) -> Self {
        Self { x, y, z }
    }
    /// Return the scalar dot product with another vector.
    #[must_use]
    pub fn dot(self, b: Self) -> f64 {
        self.x * b.x + self.y * b.y + self.z * b.z
    }
    /// Return the right-handed cross product with another vector.
    pub fn cross(self, b: Self) -> Self {
        Self::new(
            self.y * b.z - self.z * b.y,
            self.z * b.x - self.x * b.z,
            self.x * b.y - self.y * b.x,
        )
    }
    /// Return the Euclidean length using overflow-resistant hypotenuse operations.
    #[must_use]
    pub fn length(self) -> f64 {
        self.x.hypot(self.y).hypot(self.z)
    }
    /// Return a unit vector, or the zero vector for zero or non-finite length.
    pub fn normalized(self) -> Self {
        let length = self.length();
        if length > 0.0 && length.is_finite() {
            self / length
        } else {
            Self::default()
        }
    }
    /// Return whether all three components are finite floating-point values.
    #[must_use]
    pub fn is_finite(self) -> bool {
        self.x.is_finite() && self.y.is_finite() && self.z.is_finite()
    }
}

impl Add for Vec3 {
    type Output = Self;
    fn add(self, b: Self) -> Self {
        Self::new(self.x + b.x, self.y + b.y, self.z + b.z)
    }
}
impl Sub for Vec3 {
    type Output = Self;
    fn sub(self, b: Self) -> Self {
        Self::new(self.x - b.x, self.y - b.y, self.z - b.z)
    }
}
impl Mul<f64> for Vec3 {
    type Output = Self;
    fn mul(self, s: f64) -> Self {
        Self::new(self.x * s, self.y * s, self.z * s)
    }
}
impl Div<f64> for Vec3 {
    type Output = Self;
    fn div(self, s: f64) -> Self {
        Self::new(self.x / s, self.y / s, self.z / s)
    }
}
impl Neg for Vec3 {
    type Output = Self;
    fn neg(self) -> Self {
        self * -1.0
    }
}
impl From<[f32; 3]> for Vec3 {
    fn from(v: [f32; 3]) -> Self {
        Self::new(f64::from(v[0]), f64::from(v[1]), f64::from(v[2]))
    }
}

/// A triangle with an optional legacy sRGB flat color.
#[derive(Clone, Debug)]
pub struct Triangle {
    /// Its three corner positions in winding order.
    pub vertices: [Vec3; 3],
    /// An sRGB color; absent colors use the renderer's configured default.
    pub color: Option<[u8; 3]>,
}

/// A point rendered at a fixed screen-space size.
#[derive(Clone, Debug)]
pub struct Point {
    /// Point position in scene coordinates.
    pub position: Vec3,
    /// Optional sRGB color overriding the renderer's default.
    pub color: Option<[u8; 3]>,
}

/// A line segment with linearly interpolated depth.
#[derive(Clone, Debug)]
pub struct Line {
    /// Segment endpoints in scene coordinates.
    pub vertices: [Vec3; 2],
    /// Optional sRGB color overriding the renderer's default.
    pub color: Option<[u8; 3]>,
}

/// Handling of texture coordinates outside the image's unit square.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TextureWrap {
    /// Repeat the image at every integer coordinate.
    #[default]
    Repeat,
    /// Extend the nearest edge texel beyond the image.
    ClampToEdge,
    /// Repeat the image with alternating mirrored intervals.
    MirroredRepeat,
}

/// Base-level texture reconstruction used for each sampled UV coordinate.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TextureFilter {
    /// Select the closest image texel.
    Nearest,
    /// Interpolate four neighboring texels in the texture's selected color space.
    #[default]
    Linear,
}

/// Color space in which neighboring texture RGB values are interpolated.
/// Alpha always interpolates linearly, independent of the RGB policy.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TextureInterpolationSpace {
    /// Decode sRGB texels before interpolation, as required by glTF.
    #[default]
    Linear,
    /// Interpolate encoded sRGB texels before decoding, as required by 3MF.
    Srgb,
}

/// An sRGB color texture. Alpha is linear; UV (0, 0) is the upper-left
/// image corner, following glTF's image origin convention.
#[derive(Clone, Debug)]
pub struct Texture {
    /// Shared source texels in straight-alpha, sRGB RGBA8 form.
    pub image: Arc<RgbaImage>,
    /// Wrapping along the horizontal U coordinate.
    pub wrap_s: TextureWrap,
    /// Wrapping along the vertical V coordinate.
    pub wrap_t: TextureWrap,
    /// Magnification filtering.
    pub filter: TextureFilter,
    /// Minification filtering, selected from projected UV derivatives. The
    /// renderer uses the base level rather than constructing mipmaps.
    pub min_filter: TextureFilter,
    /// RGB interpolation policy; sampled colors always enter shading in linear space.
    pub interpolation_space: TextureInterpolationSpace,
}

/// Interpretation of the multiplied material, vertex and texture alpha.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum AlphaMode {
    /// Ignore alpha and write opaque color and depth.
    #[default]
    Opaque,
    /// Discard samples below a threshold; retained samples are fully opaque.
    Mask {
        /// Minimum retained alpha; finite nonnegative values above one discard everything.
        cutoff: f64,
    },
    /// Composite samples over their depth-sorted background in linear color.
    Blend,
}

/// Optional appearance for one triangle. Colors are linear RGBA multipliers;
/// normals are world-space directions. A texture requires three UV pairs.
/// Texture RGB follows its interpolation policy and enters multiplication in linear space.
#[derive(Clone, Debug)]
pub struct TriangleAppearance {
    /// Linear RGBA material multiplier, with components between zero and one.
    /// An otherwise default, normals-only appearance inherits the triangle's
    /// sRGB color or renderer fallback; an explicit white triangle remains white.
    pub base_color: [f64; 4],
    /// Optional linear RGBA multipliers at the three triangle corners.
    pub colors: Option<[[f64; 4]; 3]>,
    /// Optional UV pairs at the three corners; (0, 0) is the image's upper-left.
    pub texcoords: Option<[[f64; 2]; 3]>,
    /// Optional finite, nonzero world-space normals at the three corners.
    pub normals: Option<[Vec3; 3]>,
    /// Optional base-color texture, requiring texture coordinates.
    pub texture: Option<Texture>,
    /// Coverage or blending applied after color and alpha multiplication.
    pub alpha_mode: AlphaMode,
    /// Whether to bypass lighting and display the multiplied base color directly.
    pub unlit: bool,
    /// General mesh importers retain visible back faces by default. Importers
    /// with material culling semantics can set this to false.
    pub double_sided: bool,
}

impl Default for TriangleAppearance {
    fn default() -> Self {
        Self {
            base_color: [1.0; 4],
            colors: None,
            texcoords: None,
            normals: None,
            texture: None,
            alpha_mode: AlphaMode::Opaque,
            unlit: false,
            double_sided: true,
        }
    }
}

/// Coordinates use Z up. Importers convert formats with other conventions.
#[derive(Clone, Debug, Default)]
pub struct Scene {
    /// Surface triangles in a common coordinate system.
    pub triangles: Vec<Triangle>,
    /// Colored points in that coordinate system.
    pub points: Vec<Point>,
    /// Colored line segments in that coordinate system.
    pub lines: Vec<Line>,
    /// Triangle indices with appearance attributes. Missing entries retain the
    /// original flat color renderer, including its established output colors.
    pub appearances: BTreeMap<usize, TriangleAppearance>,
}

impl Scene {
    /// Check geometry, appearance references, numeric values and texture budgets.
    ///
    /// # Errors
    /// Returns an error for empty geometry, non-finite positions, missing triangle
    /// references, invalid colors/UVs/normals/cutoffs, missing textured UVs, or
    /// textures exceeding individual or aggregate dimension and pixel limits.
    pub fn validate(&self) -> crate::Result<()> {
        if self.triangles.is_empty() && self.points.is_empty() && self.lines.is_empty() {
            return Err("model contains no renderable geometry".into());
        }
        if self.positions().any(|p| !p.is_finite()) {
            return Err("model contains non-finite coordinates".into());
        }
        let mut textures = HashSet::new();
        let mut texture_pixels = 0_u64;
        for (index, appearance) in &self.appearances {
            if *index >= self.triangles.len() {
                return Err("triangle appearance refers to a missing triangle".into());
            }
            let valid_color = |color: &[f64; 4]| {
                color
                    .iter()
                    .all(|c| c.is_finite() && (0.0..=1.0).contains(c))
            };
            if !valid_color(&appearance.base_color)
                || appearance
                    .colors
                    .is_some_and(|colors| colors.iter().any(|c| !valid_color(c)))
            {
                return Err(
                    "triangle appearance colors must be finite values between zero and one".into(),
                );
            }
            if appearance
                .texcoords
                .is_some_and(|uvs| uvs.iter().flatten().any(|v| !v.is_finite()))
            {
                return Err("triangle texture coordinates must be finite".into());
            }
            if appearance.normals.is_some_and(|normals| {
                normals
                    .iter()
                    .any(|n| !n.is_finite() || !n.length().is_finite() || n.length() == 0.0)
            }) {
                return Err("triangle appearance normals must be finite nonzero directions".into());
            }
            if let AlphaMode::Mask { cutoff } = appearance.alpha_mode
                && (!cutoff.is_finite() || cutoff < 0.0)
            {
                return Err("triangle alpha cutoff must be finite and nonnegative".into());
            }
            if let Some(texture) = &appearance.texture {
                if appearance.texcoords.is_none() {
                    return Err("triangle color texture requires texture coordinates".into());
                }
                let width = texture.image.width();
                let height = texture.image.height();
                let pixels = u64::from(width) * u64::from(height);
                if width == 0
                    || height == 0
                    || width > 8192
                    || height > 8192
                    || pixels > 16 * 1024 * 1024
                {
                    return Err(
                        "triangle texture exceeds the dimension or 16 million pixel limit".into(),
                    );
                }
                if textures.insert(Arc::as_ptr(&texture.image)) {
                    texture_pixels += pixels;
                    if texture_pixels > 64 * 1024 * 1024 {
                        return Err("scene color textures exceed the 64 million pixel limit".into());
                    }
                }
            }
        }
        Ok(())
    }
    /// Iterate all triangle corners, points and line endpoints, including duplicates.
    pub fn positions(&self) -> impl Iterator<Item = Vec3> + '_ {
        self.triangles
            .iter()
            .flat_map(|t| t.vertices)
            .chain(self.points.iter().map(|p| p.position))
            .chain(self.lines.iter().flat_map(|line| line.vertices))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn invalid_triangle_appearance_is_rejected_before_rasterization() {
        let scene = |appearance: TriangleAppearance| Scene {
            triangles: vec![Triangle {
                vertices: [
                    Vec3::default(),
                    Vec3::new(1.0, 0.0, 0.0),
                    Vec3::new(0.0, 1.0, 0.0),
                ],
                color: None,
            }],
            appearances: [(0, appearance)].into_iter().collect(),
            ..Scene::default()
        };
        assert!(scene(TriangleAppearance::default()).validate().is_ok());
        assert!(
            scene(TriangleAppearance {
                alpha_mode: AlphaMode::Mask { cutoff: 1.1 },
                ..TriangleAppearance::default()
            })
            .validate()
            .is_ok()
        );
        assert!(
            scene(TriangleAppearance {
                texcoords: Some([[f64::MAX, 0.0]; 3]),
                ..TriangleAppearance::default()
            })
            .validate()
            .is_ok()
        );
        let invalid = [
            TriangleAppearance {
                base_color: [1.0, 0.0, f64::NAN, 1.0],
                ..TriangleAppearance::default()
            },
            TriangleAppearance {
                colors: Some([[1.1; 4]; 3]),
                ..TriangleAppearance::default()
            },
            TriangleAppearance {
                texcoords: Some([[f64::INFINITY, 0.0]; 3]),
                ..TriangleAppearance::default()
            },
            TriangleAppearance {
                texcoords: Some([[f64::NAN, 0.0]; 3]),
                ..TriangleAppearance::default()
            },
            TriangleAppearance {
                normals: Some([Vec3::default(); 3]),
                ..TriangleAppearance::default()
            },
            TriangleAppearance {
                alpha_mode: AlphaMode::Mask { cutoff: -0.1 },
                ..TriangleAppearance::default()
            },
            TriangleAppearance {
                texture: Some(Texture {
                    image: Arc::new(RgbaImage::new(1, 1)),
                    wrap_s: TextureWrap::Repeat,
                    wrap_t: TextureWrap::Repeat,
                    filter: TextureFilter::Nearest,
                    min_filter: TextureFilter::Nearest,
                    interpolation_space: TextureInterpolationSpace::Linear,
                }),
                ..TriangleAppearance::default()
            },
            TriangleAppearance {
                texture: Some(Texture {
                    image: Arc::new(RgbaImage::new(0, 1)),
                    wrap_s: TextureWrap::Repeat,
                    wrap_t: TextureWrap::Repeat,
                    filter: TextureFilter::Nearest,
                    min_filter: TextureFilter::Nearest,
                    interpolation_space: TextureInterpolationSpace::Linear,
                }),
                texcoords: Some([[0.0; 2]; 3]),
                ..TriangleAppearance::default()
            },
        ];
        for appearance in invalid {
            assert!(scene(appearance).validate().is_err());
        }
        let mut missing = scene(TriangleAppearance::default());
        missing.appearances.insert(1, TriangleAppearance::default());
        assert!(missing.validate().is_err());
    }
}