cadmpeg-ir 0.6.1

CAD data model, validation, diffing, and codec API for cadmpeg.
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
// SPDX-License-Identifier: Apache-2.0
//! Fillet and chamfer operands, dimensions, and radius laws.

mod admission;
use admission::{RadiusAdmission, StandardAdmission};

use super::selection_overlap::{face_selections_overlap, standard_result, OverlapAdmission};
use super::{EdgeSelection, FaceSelection};
use crate::scalar::{
    FiniteReal, Fraction, InteriorAngle, Length, NonNegativeLength, PositiveLength,
};
#[cfg(feature = "schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// Identified radius law form for a radius that is not yet dimensioned.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum RadiusForm {
    /// Same radius along the whole edge chain.
    Constant,
    /// Constant transverse chord length.
    Chordal,
    /// Distinct offsets along the two support faces.
    Asymmetric,
    /// Radius varying along the edge chain.
    Variable,
}

/// Radius assignment along filleted edges.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum RadiusSpec {
    /// The law is not dimensioned; `form` names it when the source identified one.
    Unresolved {
        /// Identified law form, when the source established one.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_form"
        )]
        form: Option<RadiusForm>,
    },
    /// Same radius along the whole edge chain.
    Constant {
        /// The fillet radius.
        radius: PositiveLength,
    },
    /// Constant transverse chord length across the fillet surface.
    Chordal {
        /// Distance between the fillet's two support boundaries.
        chord_length: PositiveLength,
    },
    /// Distinct offsets from the selected edge along its two support faces.
    Asymmetric {
        /// Offset on the first support-face side.
        offset_one: PositiveLength,
        /// Offset on the second support-face side.
        offset_two: PositiveLength,
    },
    /// Radius varying along the edge chain per explicit control points.
    Variable {
        /// Radius samples along the edge chain, in chain-parameter order.
        points: VariableRadii,
    },
}

impl RadiusSpec {
    /// Copy admitted fields through the caller's decode context.
    pub fn try_clone_for_decode(
        &self,
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
        operation: &'static str,
    ) -> Result<Self, cadmpeg_core::CodecError> {
        super::decode_clone::CloneForDecode::try_clone_for_decode(self, ctx, operation)
    }

    /// Returns whether the radius law lacks its required dimensions.
    pub const fn is_unresolved(&self) -> bool {
        matches!(self, Self::Unresolved { .. })
    }
}

/// One independently dimensioned group of filleted edges.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct FilletGroup {
    /// Edges sharing this radius law.
    pub edges: EdgeSelection,
    /// Radius assignment along the edges.
    pub radius: RadiusSpec,
    /// Dimensionless tangency weight, when specified.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_tangency_weight"
    )]
    pub tangency_weight: Option<FiniteReal>,
}

/// One full-round fillet group with pairwise disjoint face selections.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct FullRoundFilletGroup {
    #[serde(rename = "center_faces")]
    center: FaceSelection,
    #[serde(rename = "side_one_faces")]
    side_one: FullRoundSideSelection,
    #[serde(rename = "side_two_faces")]
    side_two: FullRoundSideSelection,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct FullRoundFilletGroupWire {
    #[serde(rename = "center_faces")]
    center: FaceSelection,
    #[serde(rename = "side_one_faces")]
    side_one: FullRoundSideSelection,
    #[serde(rename = "side_two_faces")]
    side_two: FullRoundSideSelection,
}

impl FullRoundFilletGroup {
    /// Admit center and side selections with pairwise disjoint membership.
    pub fn new(
        center_faces: FaceSelection,
        side_one_faces: FullRoundSideSelection,
        side_two_faces: FullRoundSideSelection,
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    ) -> Result<Result<Self, &'static str>, cadmpeg_core::decode::ResourceLimit> {
        Self::build(ctx, center_faces, side_one_faces, side_two_faces)
    }

    fn build<S: OverlapAdmission>(
        admission: &S,
        center_faces: FaceSelection,
        side_one_faces: FullRoundSideSelection,
        side_two_faces: FullRoundSideSelection,
    ) -> Result<Result<Self, &'static str>, S::Error> {
        fn explicit(side: &FullRoundSideSelection) -> Option<&FaceSelection> {
            match side {
                FullRoundSideSelection::Explicit(faces) => Some(faces),
                FullRoundSideSelection::Automatic | FullRoundSideSelection::Unresolved => None,
            }
        }
        admission.work(0)?;
        let first = explicit(&side_one_faces);
        let second = explicit(&side_two_faces);
        for (first, second) in [
            Some(&center_faces).zip(first),
            Some(&center_faces).zip(second),
            first.zip(second),
        ]
        .into_iter()
        .flatten()
        {
            if face_selections_overlap(admission, first, second)? {
                return Ok(Err(
                    "center_faces, side_one_faces and side_two_faces must be pairwise disjoint",
                ));
            }
        }
        Ok(Ok(Self {
            center: center_faces,
            side_one: side_one_faces,
            side_two: side_two_faces,
        }))
    }

    /// Return the center-face selection.
    pub fn center_faces(&self) -> &FaceSelection {
        &self.center
    }

    /// Return the first side-face selection.
    pub fn side_one_faces(&self) -> &FullRoundSideSelection {
        &self.side_one
    }

    /// Return the second side-face selection.
    pub fn side_two_faces(&self) -> &FullRoundSideSelection {
        &self.side_two
    }
}

impl<'de> Deserialize<'de> for FullRoundFilletGroup {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let wire = FullRoundFilletGroupWire::deserialize(deserializer)?;
        standard_result(Self::build(
            &super::selection_overlap::StandardAdmission,
            wire.center,
            wire.side_one,
            wire.side_two,
        ))
        .map_err(serde::de::Error::custom)
    }
}

/// One side of a full-round fillet.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum FullRoundSideSelection {
    /// The kernel infers this side from the center-face selection.
    Automatic,
    /// Explicit side-face selection.
    Explicit(FaceSelection),
    /// A side-face selection exists but cannot be resolved.
    Unresolved,
}

/// One independently dimensioned group of chamfered edges.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ChamferGroup {
    /// Edges sharing this dimensional specification.
    pub edges: EdgeSelection,
    /// Dimensional definition applied to the edges.
    pub spec: ChamferSpec,
}

const INVALID_VARIABLE_RADII: &str = "variable radius points require at least two ordered parameters in [0, 1] and nonnegative radii with one positive radius";

/// Which condition refuses a mapped variable-radius law.
#[derive(Debug, Clone, PartialEq)]
pub enum VariableRadiiMapError<E> {
    /// A radius conversion failed.
    Radius(E),
    /// Every mapped radius is zero.
    Admission(&'static str),
}

/// An ordered variable-radius law with at least two samples and a positive radius.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[cfg_attr(feature = "schema", schemars(into = "Vec<VariableRadius>"))]
#[serde(try_from = "Vec<VariableRadius>")]
pub struct VariableRadii(Vec<VariableRadius<Fraction, NonNegativeLength>>);

impl VariableRadii {
    /// Admits finite ordered parameters in [0, 1] and nonnegative radii with one positive radius.
    pub fn new(
        points: Vec<VariableRadius>,
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    ) -> Result<Result<Self, &'static str>, cadmpeg_core::CodecError> {
        admission::finish(Self::build(ctx, points))
    }

    fn build<A: RadiusAdmission>(
        admission: &A,
        points: Vec<VariableRadius>,
    ) -> Result<Self, A::Error> {
        let points = admission.collect(points, |point| {
            let parameter = Fraction::new(point.parameter).ok_or_else(|| admission.invalid())?;
            let radius =
                NonNegativeLength::try_from(point.radius).map_err(|_| admission.invalid())?;
            Ok(VariableRadius { parameter, radius })
        })?;
        Self::build_parts(admission, points)
    }

    /// Builds the law from admitted samples. The sample types state the
    /// parameter range and the radius sign, so only the sample count, one
    /// positive radius and the parameter order are tested.
    pub fn from_parts(
        points: Vec<VariableRadius<Fraction, NonNegativeLength>>,
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    ) -> Result<Result<Self, &'static str>, cadmpeg_core::CodecError> {
        admission::finish(Self::build_parts(ctx, points))
    }

    fn build_parts<A: RadiusAdmission>(
        admission: &A,
        points: Vec<VariableRadius<Fraction, NonNegativeLength>>,
    ) -> Result<Self, A::Error> {
        if points.len() < 2 {
            return Err(admission.invalid());
        }
        let mut positive = false;
        for point in &points {
            admission.work("IR variable radius positivity")?;
            if point.radius.get() > 0.0 {
                positive = true;
                break;
            }
        }
        if !positive {
            return Err(admission.invalid());
        }
        for pair in points.windows(2) {
            admission.work("IR variable radius parameter comparison")?;
            if pair[0].parameter >= pair[1].parameter {
                return Err(admission.invalid());
            }
        }
        Ok(Self(points))
    }

    /// Returns the admitted radius samples in parameter order.
    pub fn as_slice(&self) -> &[VariableRadius<Fraction, NonNegativeLength>] {
        &self.0
    }

    /// The law with every radius replaced by `map` of it, keeping the
    /// parameters.
    ///
    /// The sample count and the parameter order are kept, and each mapped
    /// radius is nonnegative by type, so only the one positive radius is
    /// tested again. The caller admits each conversion before it runs.
    /// Refused candidates are consumed; no sample collection is copied.
    pub fn try_map_radii<E>(
        mut self,
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
        mut map: impl FnMut(NonNegativeLength) -> Result<NonNegativeLength, E>,
    ) -> Result<Result<Self, VariableRadiiMapError<E>>, cadmpeg_core::CodecError> {
        let mut positive = false;
        for point in &mut self.0 {
            ctx.charge_work(1, "IR variable radii scaling work")?;
            point.radius = match map(point.radius) {
                Ok(radius) => radius,
                Err(error) => return Ok(Err(VariableRadiiMapError::Radius(error))),
            };
            positive |= point.radius.get() > 0.0;
        }
        Ok(if positive {
            Ok(self)
        } else {
            Err(VariableRadiiMapError::Admission(INVALID_VARIABLE_RADII))
        })
    }
}

impl TryFrom<Vec<VariableRadius>> for VariableRadii {
    type Error = &'static str;

    fn try_from(points: Vec<VariableRadius>) -> Result<Self, Self::Error> {
        Self::build(&StandardAdmission, points)
    }
}

impl Serialize for VariableRadii {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.0.serialize(serializer)
    }
}

/// Radius at a normalized position along a filleted edge chain.
// A source states a raw parameter and a signed length; `VariableRadii`
// holds the admitted sample, whose parameter is a `Fraction` and whose
// radius is a `NonNegativeLength`.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct VariableRadius<P = f64, L = Length> {
    /// Position in `[0, 1]` along the edge chain.
    pub parameter: P,
    /// Fillet radius at this position.
    pub radius: L,
}

impl VariableRadius<Fraction, NonNegativeLength> {
    /// The sample with a raw parameter and a signed length radius.
    #[must_use]
    pub fn to_raw(&self) -> VariableRadius {
        VariableRadius {
            parameter: self.parameter.get(),
            radius: Length::from(self.radius),
        }
    }
}

/// Identified chamfer form for a chamfer that is not yet dimensioned.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum ChamferForm {
    /// Equal setback distance on both faces.
    Distance,
    /// Independent setback distances on each face.
    TwoDistances,
    /// A setback distance plus an angle from its reference face.
    DistanceAngle,
}

/// Dimensional definition of an edge chamfer.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum ChamferSpec {
    /// The chamfer is not dimensioned; `form` names it when the source identified one.
    Unresolved {
        /// Identified chamfer form, when the source established one.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_chamfer_spec_form"
        )]
        form: Option<ChamferForm>,
    },
    /// Equal setback distance on both faces meeting the edge.
    Distance {
        /// Setback distance from the edge.
        distance: PositiveLength,
    },
    /// Independent setback distances on each face meeting the edge.
    TwoDistances {
        /// Setback distance on the first face.
        first: PositiveLength,
        /// Setback distance on the second face.
        second: PositiveLength,
    },
    /// A setback distance on one face plus an angle from it to the other.
    DistanceAngle {
        /// Setback distance on the reference face.
        distance: PositiveLength,
        /// Chamfer angle measured from the reference face.
        angle: InteriorAngle,
    },
}

impl ChamferSpec {
    /// Returns whether the chamfer form lacks its required dimensions.
    pub const fn is_unresolved(self) -> bool {
        matches!(self, Self::Unresolved { .. })
    }
}

// Each optional key below names itself in whatever it refuses.
cadmpeg_core::named_optional_field!(deserialize_form, RadiusForm, "form");
cadmpeg_core::named_optional_field!(deserialize_tangency_weight, FiniteReal, "tangency_weight");
cadmpeg_core::named_optional_field!(deserialize_chamfer_spec_form, ChamferForm, "form");

mod decode_clone;

#[cfg(test)]
mod tests;

mod identity_rewrite;