csx 0.0.2

Pure Rust continuous-structure geometry and material modeling, compatible with CSXCAD and openEMS
Documentation
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//! Affine transformations of primitives.
//!
//! A [`Transform`] is an ordered list of elementary [`TransformOp`]s. The
//! operations are applied to the primitive's geometry in list order — the
//! first entry is applied first — and always act in Cartesian space, on
//! drawing-unit coordinates. Rotation angles are in radians unless
//! [`Transform::set_angles_in_degrees`] was enabled; files always store
//! radians. Operation arguments are [`Scalar`]s and may therefore be
//! parametric; [`Transform::update`] re-evaluates them.
//!
//! The forward matrix maps local (shape) coordinates to world coordinates;
//! inside tests use the cached inverse to map query points back.
//!
//! ```
//! use core::f64::consts::FRAC_PI_2;
//! use csx::{Transform, Vec3};
//!
//! let mut t = Transform::new();
//! // First move 1 along x, then rotate 90° about z.
//! t.translate(Vec3::new(1.0, 0.0, 0.0)).rotate_axis(2, FRAC_PI_2);
//!
//! let p = t.apply(Vec3::ZERO);
//! assert!((p - Vec3::new(0.0, 1.0, 0.0)).norm() < 1e-12);
//! assert!(t.apply_inverse(p).norm() < 1e-12);
//! ```

use crate::error::{Error, Result};
use crate::math::{Mat4, Vec3};
use crate::param::{ParameterSet, Scalar};

/// One elementary transformation.
///
/// The variant names map to the CSXCAD XML element names returned by
/// [`TransformOp::name`]; arguments are listed in file order by
/// [`TransformOp::args`].
///
/// ```
/// use csx::{Scalar, TransformOp};
///
/// let op = TransformOp::from_name_args("Translate", [1.0, 2.0, 3.0].map(Scalar::new))?;
/// assert_eq!(op.name(), "Translate");
/// assert_eq!(op.args().map(Scalar::value).collect::<Vec<_>>(), [1.0, 2.0, 3.0]);
/// # Ok::<(), csx::Error>(())
/// ```
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum TransformOp {
    /// Translation by a vector.
    Translate([Scalar; 3]),
    /// Rotation about an axis through the origin: axis vector then angle.
    RotateOrigin([Scalar; 3], Scalar),
    /// Rotation about the x axis.
    RotateX(Scalar),
    /// Rotation about the y axis.
    RotateY(Scalar),
    /// Rotation about the z axis.
    RotateZ(Scalar),
    /// Uniform scaling.
    Scale(Scalar),
    /// Non-uniform scaling.
    Scale3([Scalar; 3]),
    /// Arbitrary 4×4 matrix: 16 values in row-major order acting on column
    /// vectors, `p' = M · [x y z 1]ᵀ` (the translation is in the last
    /// column). This matches the behaviour of CSXCAD.
    Matrix(Box<[Scalar; 16]>),
}

impl TransformOp {
    /// XML element name of the operation.
    pub fn name(&self) -> &'static str {
        match self {
            TransformOp::Translate(_) => "Translate",
            TransformOp::RotateOrigin(..) => "Rotate_Origin",
            TransformOp::RotateX(_) => "Rotate_X",
            TransformOp::RotateY(_) => "Rotate_Y",
            TransformOp::RotateZ(_) => "Rotate_Z",
            TransformOp::Scale(_) => "Scale",
            TransformOp::Scale3(_) => "Scale3",
            TransformOp::Matrix(_) => "Matrix",
        }
    }

    /// Arguments in their textual (file) order.
    pub fn args(&self) -> impl Iterator<Item = &Scalar> + '_ {
        let (main, extra): (&[Scalar], Option<&Scalar>) = match self {
            TransformOp::Translate(v) | TransformOp::Scale3(v) => (v, None),
            TransformOp::RotateOrigin(v, a) => (v, Some(a)),
            TransformOp::RotateX(a)
            | TransformOp::RotateY(a)
            | TransformOp::RotateZ(a)
            | TransformOp::Scale(a) => (core::slice::from_ref(a), None),
            TransformOp::Matrix(m) => (&m[..], None),
        };
        main.iter().chain(extra)
    }

    /// Builds an operation from its element name and arguments.
    ///
    /// Accepted names and argument counts: `Translate` (3), `Rotate_Origin`
    /// (axis x, y, z, angle), `Rotate_X` / `Rotate_Y` / `Rotate_Z` (1),
    /// `Scale` or `Scale3` (1 or 3) and `Matrix` (16, row major).
    ///
    /// # Errors
    ///
    /// [`Error::Format`] for an unknown name or a wrong argument count.
    pub fn from_name_args(
        name: &str,
        args: impl IntoIterator<Item = Scalar>,
    ) -> Result<TransformOp> {
        let args: Vec<Scalar> = args.into_iter().collect();
        let n = args.len();
        let bad = || Error::Format(format!("transformation {name} with {n} argument(s)"));
        let mut it = args.into_iter();
        let mut next = || it.next().ok_or_else(bad);
        Ok(match (name, n) {
            ("Translate", 3) => TransformOp::Translate([next()?, next()?, next()?]),
            ("Rotate_Origin", 4) => TransformOp::RotateOrigin([next()?, next()?, next()?], next()?),
            ("Rotate_X", 1) => TransformOp::RotateX(next()?),
            ("Rotate_Y", 1) => TransformOp::RotateY(next()?),
            ("Rotate_Z", 1) => TransformOp::RotateZ(next()?),
            ("Scale" | "Scale3", 1) => TransformOp::Scale(next()?),
            ("Scale" | "Scale3", 3) => TransformOp::Scale3([next()?, next()?, next()?]),
            ("Matrix", 16) => {
                let mut m: [Scalar; 16] = Default::default();
                for s in &mut m {
                    *s = next()?;
                }
                TransformOp::Matrix(Box::new(m))
            }
            _ => return Err(bad()),
        })
    }

    fn update(&mut self, p: &ParameterSet) -> Result<()> {
        match self {
            TransformOp::Translate(v) | TransformOp::Scale3(v) => {
                v.iter_mut().try_for_each(|s| s.update(p))
            }
            TransformOp::RotateOrigin(v, a) => {
                v.iter_mut().try_for_each(|s| s.update(p))?;
                a.update(p)
            }
            TransformOp::RotateX(a)
            | TransformOp::RotateY(a)
            | TransformOp::RotateZ(a)
            | TransformOp::Scale(a) => a.update(p),
            TransformOp::Matrix(m) => m.iter_mut().try_for_each(|s| s.update(p)),
        }
    }

    fn matrix(&self, deg: bool) -> Mat4 {
        let ang = |a: &Scalar| {
            if deg {
                a.value().to_radians()
            } else {
                a.value()
            }
        };
        let v3 = |v: &[Scalar; 3]| Vec3::new(v[0].value(), v[1].value(), v[2].value());
        match self {
            TransformOp::Translate(v) => Mat4::translation(v3(v)),
            TransformOp::RotateOrigin(v, a) => Mat4::rotation(v3(v), ang(a)),
            TransformOp::RotateX(a) => Mat4::rotation(Vec3::unit(0), ang(a)),
            TransformOp::RotateY(a) => Mat4::rotation(Vec3::unit(1), ang(a)),
            TransformOp::RotateZ(a) => Mat4::rotation(Vec3::unit(2), ang(a)),
            TransformOp::Scale(s) => {
                let s = s.value();
                Mat4::scaling(Vec3::new(s, s, s))
            }
            TransformOp::Scale3(v) => Mat4::scaling(v3(v)),
            TransformOp::Matrix(m) => Mat4::from_row_major(&core::array::from_fn(|i| m[i].value())),
        }
    }

    /// The operation as a matrix acting on column vectors (`p' = M·p`),
    /// with rotation angles in radians (`degrees = false`) or degrees.
    pub fn to_mat4(&self, degrees: bool) -> Mat4 {
        self.matrix(degrees)
    }
}

/// An ordered list of transformations with cached forward and inverse
/// matrices.
#[derive(Debug, Clone, PartialEq)]
pub struct Transform {
    ops: Vec<TransformOp>,
    degrees: bool,
    matrix: Mat4,
    inverse: Mat4,
    invertible: bool,
}

impl Default for Transform {
    fn default() -> Self {
        Transform {
            ops: Vec::new(),
            degrees: false,
            matrix: Mat4::IDENTITY,
            inverse: Mat4::IDENTITY,
            invertible: true,
        }
    }
}

impl Transform {
    /// Identity transform.
    ///
    /// ```
    /// let t = csx::Transform::new();
    /// assert!(t.is_empty() && t.matrix().is_identity());
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Whether rotation angles are interpreted in degrees (default: radians).
    pub fn angles_in_degrees(&self) -> bool {
        self.degrees
    }

    /// Selects degree (`true`) or radian (`false`) rotation angles for all
    /// rotation operations of this transform.
    ///
    /// ```
    /// use csx::{Transform, Vec3};
    ///
    /// let mut t = Transform::new();
    /// t.set_angles_in_degrees(true);
    /// t.rotate_axis(2, 90.0);
    /// assert!((t.apply(Vec3::unit(0)) - Vec3::unit(1)).norm() < 1e-12);
    /// ```
    pub fn set_angles_in_degrees(&mut self, deg: bool) {
        self.degrees = deg;
        self.rebuild();
    }

    /// The operations in application order.
    pub fn ops(&self) -> &[TransformOp] {
        &self.ops
    }

    /// True if no operation is present.
    pub fn is_empty(&self) -> bool {
        self.ops.is_empty()
    }

    /// Appends an operation (applied after the existing ones).
    pub fn push(&mut self, op: TransformOp) -> &mut Self {
        self.ops.push(op);
        self.rebuild();
        self
    }

    /// Appends a translation.
    pub fn translate(&mut self, v: Vec3) -> &mut Self {
        self.push(TransformOp::Translate(v.0.map(Scalar::new)))
    }

    /// Appends a right-handed rotation about an arbitrary axis through the
    /// origin (angle unit per [`Transform::angles_in_degrees`]).
    pub fn rotate(&mut self, axis: Vec3, angle: f64) -> &mut Self {
        self.push(TransformOp::RotateOrigin(
            axis.0.map(Scalar::new),
            angle.into(),
        ))
    }

    /// Appends a right-handed rotation about the coordinate axis `dir`
    /// (0 = x, 1 = y, any other value = z; angle unit per
    /// [`Transform::angles_in_degrees`]).
    pub fn rotate_axis(&mut self, dir: usize, angle: f64) -> &mut Self {
        let a = Scalar::new(angle);
        self.push(match dir {
            0 => TransformOp::RotateX(a),
            1 => TransformOp::RotateY(a),
            _ => TransformOp::RotateZ(a),
        })
    }

    /// Appends a uniform scaling.
    pub fn scale(&mut self, s: f64) -> &mut Self {
        self.push(TransformOp::Scale(s.into()))
    }

    /// Appends an arbitrary matrix acting on column vectors (`p' = m·p`).
    ///
    /// ```
    /// use csx::{Mat4, Transform, Vec3};
    ///
    /// let mut t = Transform::new();
    /// t.push_matrix(&Mat4::translation(Vec3::new(0.0, 0.0, 5.0)));
    /// assert_eq!(t.apply(Vec3::ZERO), Vec3::new(0.0, 0.0, 5.0));
    /// ```
    pub fn push_matrix(&mut self, m: &Mat4) -> &mut Self {
        self.push(TransformOp::Matrix(Box::new(
            m.to_row_major().map(Scalar::new),
        )))
    }

    /// Removes all operations.
    pub fn clear(&mut self) {
        self.ops.clear();
        self.rebuild();
    }

    /// Re-evaluates parametric arguments and rebuilds the matrices.
    ///
    /// ```
    /// use csx::{ParameterSet, Scalar, Transform, TransformOp, Vec3};
    ///
    /// let mut t = Transform::new();
    /// t.push(TransformOp::Translate([Scalar::expr("dx"), 0.0.into(), 0.0.into()]));
    /// let mut params = ParameterSet::new();
    /// params.set("dx", 2.5);
    /// t.update(&params)?;
    /// assert_eq!(t.apply(Vec3::ZERO), Vec3::new(2.5, 0.0, 0.0));
    /// # Ok::<(), csx::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Errors from evaluating an argument ([`Error::Parse`],
    /// [`Error::UnknownVariable`], [`Error::Invalid`] for NaN results), or
    /// [`Error::Invalid`] when the combined matrix is singular (the
    /// matrices are rebuilt anyway; see [`Transform::is_invertible`]).
    pub fn update(&mut self, p: &ParameterSet) -> Result<()> {
        self.ops.iter_mut().try_for_each(|o| o.update(p))?;
        self.rebuild();
        if !self.invertible {
            return Err(Error::Invalid("singular transformation".into()));
        }
        Ok(())
    }

    fn rebuild(&mut self) {
        self.matrix = self
            .ops
            .iter()
            .fold(Mat4::IDENTITY, |acc, op| op.matrix(self.degrees) * acc);
        match self.matrix.inverse() {
            Some(inv) => {
                self.inverse = inv;
                self.invertible = true;
            }
            None => {
                self.inverse = Mat4::IDENTITY;
                self.invertible = false;
            }
        }
    }

    /// False if the combined matrix is singular (e.g. a zero scale); such a
    /// transform maps every shape to something without interior, and
    /// inside tests of primitives using it return `false`.
    pub fn is_invertible(&self) -> bool {
        self.invertible
    }

    /// Forward matrix (local → world).
    pub fn matrix(&self) -> &Mat4 {
        &self.matrix
    }

    /// Inverse matrix (world → local); the identity when the transform is
    /// not invertible (see [`Transform::is_invertible`]).
    pub fn inverse(&self) -> &Mat4 {
        &self.inverse
    }

    /// Maps a local point to world coordinates.
    #[inline]
    pub fn apply(&self, p: Vec3) -> Vec3 {
        self.matrix.transform_point(p)
    }

    /// Maps a world point back to local coordinates.
    #[inline]
    pub fn apply_inverse(&self, p: Vec3) -> Vec3 {
        self.inverse.transform_point(p)
    }
}

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

    #[test]
    fn matrix_convention() {
        // Verified against CSXCAD: translation in the last column.
        let col = [
            1.0, 0.0, 0.0, 5.0, 0.0, 1.0, 0.0, 6.0, 0.0, 0.0, 1.0, 7.0, 0.0, 0.0, 0.0, 1.0,
        ];
        let op = TransformOp::from_name_args("Matrix", col.map(Scalar::new).to_vec()).unwrap();
        assert_eq!(
            op.to_mat4(false).transform_point(Vec3::ZERO),
            Vec3::new(5.0, 6.0, 7.0)
        );
        // [[0,-1],[1,0]] rotates +x onto +y.
        let rot = [
            0.0, -1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
        ];
        let op = TransformOp::from_name_args("Matrix", rot.map(Scalar::new).to_vec()).unwrap();
        assert!((op.to_mat4(false).transform_point(Vec3::unit(0)) - Vec3::unit(1)).norm() < 1e-12);
        let r = Mat4::rotation(Vec3::unit(2), core::f64::consts::FRAC_PI_2);
        let mut t = Transform::new();
        t.push_matrix(&r);
        assert!((t.apply(Vec3::unit(0)) - Vec3::unit(1)).norm() < 1e-12);
        let mut t2 = Transform::new();
        t2.push_matrix(&Mat4::translation(Vec3::new(1.0, 2.0, 3.0)));
        assert_eq!(t2.apply(Vec3::ZERO), Vec3::new(1.0, 2.0, 3.0));
        // Vector scaling is written as `Scale3`; both names are accepted.
        let s3 = TransformOp::from_name_args("Scale3", vec![1.0.into(), 2.0.into(), 3.0.into()])
            .unwrap();
        assert_eq!(s3.name(), "Scale3");
        assert!(
            TransformOp::from_name_args("Scale", vec![1.0.into(), 2.0.into(), 3.0.into()]).is_ok()
        );
    }
    use core::f64::consts::FRAC_PI_2;

    #[test]
    fn order() {
        let mut t = Transform::new();
        t.translate(Vec3::new(1.0, 0.0, 0.0))
            .rotate_axis(2, FRAC_PI_2);
        // translate first, then rotate: (0,0,0) -> (1,0,0) -> (0,1,0)
        let p = t.apply(Vec3::ZERO);
        assert!((p - Vec3::new(0.0, 1.0, 0.0)).norm() < 1e-12);
        assert!((t.apply_inverse(p)).norm() < 1e-12);
    }

    #[test]
    fn degrees_and_params() {
        let mut t = Transform::new();
        t.set_angles_in_degrees(true);
        t.push(TransformOp::RotateZ(Scalar::expr("ang")));
        let mut ps = ParameterSet::new();
        ps.set("ang", 90.0);
        t.update(&ps).unwrap();
        assert!((t.apply(Vec3::unit(0)) - Vec3::unit(1)).norm() < 1e-12);
        assert!(TransformOp::from_name_args("Translate", vec![1.0.into()]).is_err());
        let mut z = Transform::new();
        z.scale(0.0);
        assert!(!z.is_invertible());
        assert!(Transform::new().is_invertible());
        let op = TransformOp::from_name_args(
            "Rotate_Origin",
            vec![0.0.into(), 0.0.into(), 1.0.into(), 2.0.into()],
        )
        .unwrap();
        assert_eq!(op.args().count(), 4);
    }
}