cadmpeg-step 0.3.0

Serialize cadmpeg IR documents as ISO 10303-21 STEP AP214 files.
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
// SPDX-License-Identifier: Apache-2.0
//! Geometric validation-property decoding and mesh self-checks.

use std::collections::{BTreeMap, BTreeSet};

use cadmpeg_ir::document::CadIr;
use cadmpeg_ir::math::Point3;

use crate::parse::{Exchange, RawRecord, Value};

use super::geometry::GeometryResult;

pub(super) struct ValidationResult {
    pub typed_records: BTreeSet<u64>,
    pub notes: Vec<String>,
    pub warnings: Vec<String>,
}

#[derive(Clone, Copy)]
enum Expected {
    Area(f64),
    Volume(f64),
    Centroid(Point3),
}

pub(super) fn decode(
    exchange: &Exchange,
    geometry: &GeometryResult,
    ir: &mut CadIr,
) -> ValidationResult {
    let representations = exchange
        .records
        .iter()
        .filter_map(|(&id, record)| {
            if !matches!(
                record.simple_name(),
                Some("REPRESENTATION" | "SHAPE_REPRESENTATION")
            ) {
                return None;
            }
            Some((id, record.parameter(1)?.list()?.first()?.reference()?))
        })
        .collect::<BTreeMap<_, _>>();
    let properties = exchange
        .records
        .iter()
        .filter_map(|(&id, record)| {
            if record.simple_name() == Some("PROPERTY_DEFINITION")
                && record
                    .parameter(0)?
                    .text()?
                    .eq_ignore_ascii_case("geometric validation property")
            {
                Some((
                    id,
                    record
                        .parameter(1)
                        .and_then(ValueExt::text)
                        .unwrap_or_default(),
                ))
            } else {
                None
            }
        })
        .collect::<BTreeMap<_, _>>();
    let computed = mesh_properties(ir);
    let mut typed = BTreeSet::new();
    let mut validation_points = BTreeSet::new();
    let mut validation_representations = BTreeSet::new();
    let mut notes = Vec::new();
    let mut warnings = Vec::new();

    for (&relation_id, relation) in &exchange.records {
        if relation.simple_name() != Some("PROPERTY_DEFINITION_REPRESENTATION") {
            continue;
        }
        let Some(property_id) = relation.parameter(0).and_then(ValueExt::reference) else {
            continue;
        };
        let Some(description) = properties.get(&property_id) else {
            continue;
        };
        let Some(representation_id) = relation.parameter(1).and_then(ValueExt::reference) else {
            continue;
        };
        let Some(&item_id) = representations.get(&representation_id) else {
            continue;
        };
        let Some(item) = exchange.records.get(&item_id) else {
            continue;
        };
        let expected = expected_value(item, exchange, geometry.length_scale);
        let Some(expected) = expected else {
            warnings.push(format!(
                "geometric validation property #{property_id} has an unsupported value"
            ));
            continue;
        };
        if matches!(expected, Expected::Centroid(_)) {
            validation_points.insert(item_id);
        }
        validation_representations.insert(representation_id);
        typed.extend([property_id, relation_id, representation_id, item_id]);
        if let Some(unit) = item.parameter(2).and_then(ValueExt::reference) {
            collect_unit_records(unit, exchange, &mut typed);
        }
        let (kind, expected_text, actual) = match expected {
            Expected::Area(value) => ("surface area", value.to_string(), computed.map(|p| p.area)),
            Expected::Volume(value) => ("volume", value.to_string(), computed.map(|p| p.volume)),
            Expected::Centroid(value) => (
                "centroid",
                format!("({},{},{})", value.x, value.y, value.z),
                computed.map(|p| p.centroid_distance(value)),
            ),
        };
        if let Some(actual) = actual {
            let actual_text = match expected {
                Expected::Centroid(_) => format!("distance {actual}"),
                _ => actual.to_string(),
            };
            notes.push(format!(
                "geometric validation {kind} {description}: expected {expected_text}, tessellation approximation {actual_text}"
            ));
        } else {
            notes.push(format!(
                "geometric validation {kind} {description}: expected {expected_text}"
            ));
        }
    }
    let mut referenced_validation_points = BTreeSet::new();
    for (&record_id, record) in &exchange.records {
        if validation_representations.contains(&record_id) {
            continue;
        }
        for value in record
            .partials
            .iter()
            .flat_map(|partial| &partial.parameters)
        {
            collect_validation_references(
                value,
                &validation_points,
                &mut referenced_validation_points,
            );
        }
    }
    ir.model.points.retain(|point| {
        let id = step_id(&point.id.0);
        !validation_points.contains(&id) || referenced_validation_points.contains(&id)
    });
    ValidationResult {
        typed_records: typed,
        notes,
        warnings,
    }
}

fn expected_value(record: &RawRecord, exchange: &Exchange, scale: f64) -> Option<Expected> {
    if record.simple_name() == Some("CARTESIAN_POINT") {
        let values = record.parameter(1)?.list()?;
        if values.len() != 3 {
            return None;
        }
        return Some(Expected::Centroid(Point3::new(
            values[0].number()? * scale,
            values[1].number()? * scale,
            values[2].number()? * scale,
        )));
    }
    if record.simple_name() != Some("MEASURE_REPRESENTATION_ITEM") {
        return None;
    }
    match record.parameter(1)? {
        Value::Typed(kind, value) if kind == "AREA_MEASURE" => Some(Expected::Area(
            value.number()? * measure_scale(record, exchange, scale, 2),
        )),
        Value::Typed(kind, value) if kind == "VOLUME_MEASURE" => Some(Expected::Volume(
            value.number()? * measure_scale(record, exchange, scale, 3),
        )),
        _ => None,
    }
}

fn measure_scale(record: &RawRecord, exchange: &Exchange, fallback: f64, order: i32) -> f64 {
    record
        .parameter(2)
        .and_then(ValueExt::reference)
        .and_then(|unit| exchange.records.get(&unit))
        .and_then(|unit| {
            if unit.simple_name() != Some("DERIVED_UNIT") {
                return None;
            }
            unit.parameter(0)?
                .list()?
                .iter()
                .try_fold(1.0, |scale, element| {
                    let element = exchange.records.get(&element.reference()?)?;
                    let base = element.parameter(0)?.reference()?;
                    let exponent = element.parameter(1)?.number()?;
                    let base =
                        super::geometry::unit_scale_mm(base, exchange, &mut BTreeSet::new())?;
                    Some(scale * base.powf(exponent))
                })
        })
        .unwrap_or_else(|| fallback.powi(order))
}

fn collect_unit_records(id: u64, exchange: &Exchange, typed: &mut BTreeSet<u64>) {
    typed.insert(id);
    let Some(record) = exchange.records.get(&id) else {
        return;
    };
    if record.simple_name() != Some("DERIVED_UNIT") {
        return;
    }
    for element in record
        .parameter(0)
        .and_then(ValueExt::list)
        .into_iter()
        .flatten()
        .filter_map(ValueExt::reference)
    {
        typed.insert(element);
        if let Some(base) = exchange
            .records
            .get(&element)
            .and_then(|record| record.parameter(0))
            .and_then(ValueExt::reference)
        {
            typed.insert(base);
        }
    }
}

#[derive(Clone, Copy)]
struct MeshProperties {
    area: f64,
    volume: f64,
    centroid: Point3,
}

impl MeshProperties {
    fn centroid_distance(self, expected: Point3) -> f64 {
        (self.centroid.x - expected.x)
            .hypot(self.centroid.y - expected.y)
            .hypot(self.centroid.z - expected.z)
    }
}

fn mesh_properties(ir: &CadIr) -> Option<MeshProperties> {
    let body = (ir.model.bodies.len() == 1).then(|| ir.model.bodies[0].id.clone())?;
    let meshes = ir
        .model
        .tessellations
        .iter()
        .filter(|mesh| mesh.body.as_ref() == Some(&body));
    let mut area = 0.0;
    let mut area_centroid = [0.0; 3];
    let mut signed_volume = 0.0;
    let mut volume_centroid = [0.0; 3];
    let mut triangles = 0usize;
    let mut watertight = true;
    let mut coordinate_scale = 0.0_f64;
    for mesh in meshes {
        let mut edge_uses = BTreeMap::<(u32, u32), usize>::new();
        for triangle in &mesh.triangles {
            let [a, b, c] = triangle.map(|index| mesh.vertices.get(index as usize).copied());
            let (Some(a), Some(b), Some(c)) = (a, b, c) else {
                return None;
            };
            for [first, second] in [
                [triangle[0], triangle[1]],
                [triangle[1], triangle[2]],
                [triangle[2], triangle[0]],
            ] {
                *edge_uses
                    .entry((first.min(second), first.max(second)))
                    .or_default() += 1;
            }
            coordinate_scale = coordinate_scale
                .max(a.x.abs())
                .max(a.y.abs())
                .max(a.z.abs())
                .max(b.x.abs())
                .max(b.y.abs())
                .max(b.z.abs())
                .max(c.x.abs())
                .max(c.y.abs())
                .max(c.z.abs());
            let ab = [b.x - a.x, b.y - a.y, b.z - a.z];
            let ac = [c.x - a.x, c.y - a.y, c.z - a.z];
            let cross = [
                ab[1] * ac[2] - ab[2] * ac[1],
                ab[2] * ac[0] - ab[0] * ac[2],
                ab[0] * ac[1] - ab[1] * ac[0],
            ];
            let triangle_area = 0.5 * cross[0].hypot(cross[1]).hypot(cross[2]);
            area += triangle_area;
            for axis in 0..3 {
                area_centroid[axis] +=
                    triangle_area * [a.x + b.x + c.x, a.y + b.y + c.y, a.z + b.z + c.z][axis] / 3.0;
            }
            let tetra_volume = (a.x * (b.y * c.z - b.z * c.y)
                + a.y * (b.z * c.x - b.x * c.z)
                + a.z * (b.x * c.y - b.y * c.x))
                / 6.0;
            signed_volume += tetra_volume;
            for axis in 0..3 {
                volume_centroid[axis] +=
                    tetra_volume * [a.x + b.x + c.x, a.y + b.y + c.y, a.z + b.z + c.z][axis] / 4.0;
            }
            triangles += 1;
        }
        watertight &= !edge_uses.is_empty() && edge_uses.values().all(|uses| *uses == 2);
    }
    if triangles == 0 || area == 0.0 {
        return None;
    }
    let volume_epsilon =
        f64::EPSILON * coordinate_scale.max(1.0).powi(3) * (triangles as f64).max(1.0);
    let centroid = if watertight && signed_volume.abs() > volume_epsilon {
        Point3::new(
            volume_centroid[0] / signed_volume,
            volume_centroid[1] / signed_volume,
            volume_centroid[2] / signed_volume,
        )
    } else {
        Point3::new(
            area_centroid[0] / area,
            area_centroid[1] / area,
            area_centroid[2] / area,
        )
    };
    Some(MeshProperties {
        area,
        volume: signed_volume.abs(),
        centroid,
    })
}

fn step_id(id: &str) -> u64 {
    id.rsplit('#')
        .next()
        .and_then(|id| id.parse().ok())
        .unwrap_or(u64::MAX)
}

fn collect_validation_references(
    value: &Value,
    validation_points: &BTreeSet<u64>,
    referenced: &mut BTreeSet<u64>,
) {
    match value {
        Value::Reference(id) if validation_points.contains(id) => {
            referenced.insert(*id);
        }
        Value::List(values) => {
            for value in values {
                collect_validation_references(value, validation_points, referenced);
            }
        }
        Value::Typed(_, value) => {
            collect_validation_references(value, validation_points, referenced);
        }
        _ => {}
    }
}

trait RecordExt {
    fn simple_name(&self) -> Option<&str>;
    fn parameter(&self, index: usize) -> Option<&Value>;
}
impl RecordExt for RawRecord {
    fn simple_name(&self) -> Option<&str> {
        (self.partials.len() == 1).then(|| self.partials[0].name.as_str())
    }
    fn parameter(&self, index: usize) -> Option<&Value> {
        self.partials.first()?.parameters.get(index)
    }
}
trait ValueExt {
    fn reference(&self) -> Option<u64>;
    fn list(&self) -> Option<&[Value]>;
    fn number(&self) -> Option<f64>;
    fn text(&self) -> Option<String>;
}
impl ValueExt for Value {
    fn reference(&self) -> Option<u64> {
        if let Value::Reference(id) = self {
            Some(*id)
        } else {
            None
        }
    }
    fn list(&self) -> Option<&[Value]> {
        if let Value::List(values) = self {
            Some(values)
        } else {
            None
        }
    }
    fn number(&self) -> Option<f64> {
        match self {
            Value::Integer(value) => Some(*value as f64),
            Value::Real(value) => Some(*value),
            _ => None,
        }
    }
    fn text(&self) -> Option<String> {
        if let Value::String(bytes) = self {
            crate::strings::decode(bytes).ok()
        } else {
            None
        }
    }
}