cadmpeg-asm 0.6.5

Parse and write Autodesk Shape Manager record streams.
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
// SPDX-License-Identifier: Apache-2.0
//! Decode source attribute chains into typed attribute values, colors, names,
//! and transforms.

use crate::ids::{brep_id, IdFormat};
use crate::nurbs::reader::LEN_TO_MM;
use crate::sab::{Record, Token};
use cadmpeg_ir::attributes::{AttributeTarget, AttributeValue, SourceAttribute};
use cadmpeg_ir::ids::{AttributeId, Identity, IdentityComponent, UnknownId};
use cadmpeg_ir::topology::Color;
use std::collections::{hash_map::RandomState, HashMap, HashSet};

/// Follow `entity`'s attribute chain, emitting each record not yet in
/// `emitted` as a [`SourceAttribute`] bound to `target`.
pub fn collect_attributes(
    entity: &Record,
    target: &AttributeTarget,
    by_index: &HashMap<i64, &Record, RandomState>,
    emitted: &mut HashSet<i64, RandomState>,
    out: &mut Vec<SourceAttribute>,
    format: IdFormat,
) -> Result<(), cadmpeg_core::CodecError> {
    let mut current = entity.ref_at(0);
    let mut chain = HashSet::new();
    while let Some(index) = current {
        if !chain.insert(index) {
            break;
        }
        let Some(record) = by_index.get(&index) else {
            break;
        };
        if emitted.insert(index) {
            out.push(source_attribute(record, target.clone(), format)?);
        }
        current = attribute_next(record);
    }
    Ok(())
}

fn is_integer(token: Option<&Token>) -> bool {
    matches!(
        token,
        Some(Token::Char(_) | Token::Short(_) | Token::Long(_) | Token::Enum(_) | Token::Int64(_))
    )
}

#[derive(Clone, Copy)]
enum AttributeBase {
    Current,
    Legacy,
    Compact,
}

impl AttributeBase {
    fn next(self) -> usize {
        match self {
            Self::Current => 2,
            Self::Legacy => 1,
            Self::Compact => 0,
        }
    }

    fn owner(self) -> Option<usize> {
        match self {
            Self::Current => Some(4),
            Self::Legacy => Some(3),
            Self::Compact => None,
        }
    }

    fn payload(self) -> usize {
        match self {
            Self::Current => 5,
            Self::Legacy => 4,
            Self::Compact => 1,
        }
    }
}

fn attribute_base(record: &Record) -> Option<AttributeBase> {
    let current = matches!(
        (
            record.chunk(0),
            record.chunk(2),
            record.chunk(3),
            record.chunk(4),
        ),
        (
            Some(Token::Ref(_)),
            Some(Token::Ref(_)),
            Some(Token::Ref(_)),
            Some(Token::Ref(_)),
        )
    ) && is_integer(record.chunk(1));
    if current {
        return Some(AttributeBase::Current);
    }
    let legacy = matches!(
        (
            record.chunk(0),
            record.chunk(1),
            record.chunk(2),
            record.chunk(3),
        ),
        (
            Some(Token::Ref(_)),
            Some(Token::Ref(_)),
            Some(Token::Ref(_)),
            Some(Token::Ref(_)),
        )
    );
    if legacy {
        return Some(AttributeBase::Legacy);
    }
    matches!(record.chunk(0), Some(Token::Ref(_))).then_some(AttributeBase::Compact)
}

/// The next record in an attribute chain.
///
/// A current ASM attribute starts with `reserved, marker, next, previous,
/// owner`; a legacy attribute omits `marker`. Source-less streams written by
/// older cadmpeg versions used a compact record whose first field was `next`;
/// retain read compatibility with all three forms.
pub fn attribute_next(record: &Record) -> Option<i64> {
    record.ref_at(attribute_base(record)?.next())
}

/// The topology or parent-attribute owner of a current or legacy attribute.
pub fn attribute_owner(record: &Record) -> Option<i64> {
    record.ref_at(attribute_base(record)?.owner()?)
}

/// The numeric record-index key of an attribute id
/// (`<format>:brep:attribute#<index>`), used to key records derived from that
/// attribute.
pub fn attribute_key(attribute: &SourceAttribute) -> &str {
    attribute
        .id
        .as_str()
        .rsplit('#')
        .next()
        .unwrap_or(attribute.id.as_str())
}

/// Serialize one attribute record's value chunks as a [`SourceAttribute`]
/// bound to `target`. A NaN or infinite number refuses the record.
pub fn source_attribute(
    record: &Record,
    target: AttributeTarget,
    format: IdFormat,
) -> Result<SourceAttribute, cadmpeg_core::CodecError> {
    // Chunks, not raw tokens: the serialized value list is defined over the
    // value tokens, and a payload identifier names an embedded construction
    // rather than carrying an attribute value.
    let mut values = Vec::new();
    for token in record.chunks() {
        let value = attribute_value(token, format).ok_or_else(|| {
            cadmpeg_core::CodecError::malformed(format_args!(
                "attribute record {} ({}) holds a non-finite number",
                record.index, record.name
            ))
        })?;
        values.push(value);
    }
    Ok(SourceAttribute {
        id: brep_id!(format, AttributeId, "attribute", record.index),
        target,
        name: record.name.clone(),
        values,
    })
}

/// The attribute value one token carries, or `None` for a number that is not
/// finite.
fn attribute_value(token: &Token, format: IdFormat) -> Option<AttributeValue> {
    Some(match token {
        Token::Char(value) => AttributeValue::Integer(i64::from(*value)),
        Token::Short(value) => AttributeValue::Integer(i64::from(*value)),
        Token::Long(value) | Token::Enum(value) | Token::Int64(value) => {
            AttributeValue::Integer(*value)
        }
        Token::Float(value) => AttributeValue::float(f64::from(*value))?,
        Token::Double(value) => AttributeValue::float(*value)?,
        Token::Str(value) => AttributeValue::String(value.to_owned()),
        Token::True => AttributeValue::Boolean(true),
        Token::False => AttributeValue::Boolean(false),
        Token::Ref(value) => {
            AttributeValue::Reference(brep_id!(format, Identity, "entity", value).into_string())
        }
        Token::SubtypeOpen => AttributeValue::String("subtype_open".into()),
        Token::SubtypeClose => AttributeValue::String("subtype_close".into()),
        Token::Position(value) | Token::Vector3(value) => AttributeValue::vector(*value)?,
        Token::Vector2(value) => AttributeValue::vector(*value)?,
        Token::Ident(value) | Token::SubIdent(value) => AttributeValue::String(value.to_owned()),
    })
}

/// Decode a native transform record into an IR affine transform, scaling the
/// translation into millimetres.
pub fn decode_transform(
    record: &Record,
    header_scale: f64,
) -> Option<cadmpeg_ir::transform::Transform> {
    let mut vectors = record.tokens.iter().filter_map(|token| match token {
        Token::Position(value) | Token::Vector3(value) => Some(*value),
        _ => None,
    });
    let scale = record
        .tokens
        .iter()
        .filter_map(|token| match token {
            Token::Double(value) => Some(*value),
            _ => None,
        })
        .next_back()?;
    let (Some(x), Some(y), Some(z), Some(translation), None) = (
        vectors.next(),
        vectors.next(),
        vectors.next(),
        vectors.next(),
        vectors.next(),
    ) else {
        return None;
    };
    // The attribute stores a homogeneous scale in the `w` slot. Only the
    // unscaled spelling maps to an affine transform.
    if scale != 1.0 {
        return None;
    }
    cadmpeg_ir::transform::Transform::affine([
        [x[0], y[0], z[0], translation[0] * header_scale * LEN_TO_MM],
        [x[1], y[1], z[1], translation[1] * header_scale * LEN_TO_MM],
        [x[2], y[2], z[2], translation[2] * header_scale * LEN_TO_MM],
    ])
}

/// Storage form and payload-field location of an exact direct-color attribute.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DirectColorCarrier {
    /// Three normalized f64 channel fields.
    NormalizedRgb {
        /// Payload-field indices of red, green, and blue.
        fields: [usize; 3],
    },
    /// One Autodesk method-and-color packed integer field.
    AutodeskTrueColor {
        /// Payload-field index of the packed integer.
        field: usize,
    },
    /// One decimal-text packed RGB field.
    DecimalRgb {
        /// Payload-field index of the decimal text.
        field: usize,
    },
}

/// A decoded exact direct-color attribute and the carrier that supplied it.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DirectAttributeColor {
    /// Opaque neutral RGB color.
    pub color: Color,
    /// Native payload form and field location.
    pub carrier: DirectColorCarrier,
}

fn packed_u32(value: i64) -> Option<u32> {
    u32::try_from(value)
        .ok()
        .or_else(|| i32::try_from(value).ok().map(i32::cast_unsigned))
}

fn packed_rgb(packed: u32) -> Option<Color> {
    let red = u8::try_from((packed >> 16) & 0xff).ok()?;
    let green = u8::try_from((packed >> 8) & 0xff).ok()?;
    let blue = u8::try_from(packed & 0xff).ok()?;
    Some(Color::from_rgba8(red, green, blue, 255))
}

/// Decode one well-formed exact direct-color attribute.
///
/// Palette, material-library, inherited truecolor, and malformed records do
/// not define a neutral RGB color.
fn direct_attribute_color(record: &Record) -> Option<DirectAttributeColor> {
    let payload = attribute_base(record)?.payload();
    match record.name.as_str() {
        "rgb_color-st-attrib" => {
            let mut channels = record.chunks().enumerate().skip(payload).filter_map(
                |(field, token)| match token {
                    Token::Double(value) => Some((field, *value)),
                    _ => None,
                },
            );
            let channels = [
                channels.next(),
                channels.next(),
                channels.next(),
                channels.next(),
                channels.next(),
            ];
            let [(r_field, r), (g_field, g), (b_field, b)] = match channels {
                [Some(red), Some(green), Some(blue), None, None] => [red, green, blue],
                [Some(red), Some(green), Some(blue), Some((_, 1.0)), None] => [red, green, blue],
                _ => return None,
            };
            if ![r, g, b]
                .into_iter()
                .all(|value| (0.0..=1.0).contains(&value))
            {
                return None;
            }
            Some(DirectAttributeColor {
                color: Color::new(
                    cadmpeg_core::convert::f32_from_f64(r)?,
                    cadmpeg_core::convert::f32_from_f64(g)?,
                    cadmpeg_core::convert::f32_from_f64(b)?,
                    1.0,
                )?,
                carrier: DirectColorCarrier::NormalizedRgb {
                    fields: [r_field, g_field, b_field],
                },
            })
        }
        "truecolor-adesk-attrib" => {
            let (field, packed) = record
                .chunks()
                .enumerate()
                .skip(payload)
                .filter_map(|(field, token)| match token {
                    Token::Int64(value) | Token::Long(value) => Some((field, *value)),
                    _ => None,
                })
                .last()?;
            let packed = packed_u32(packed)?;
            // AcCmColor stores its color method in the high byte. Only
            // kByColor carries self-contained RGB channels.
            if packed >> 24 != 0xc2 {
                return None;
            }
            Some(DirectAttributeColor {
                color: packed_rgb(packed)?,
                carrier: DirectColorCarrier::AutodeskTrueColor { field },
            })
        }
        "entatt_color-bt-attrib" => {
            let (field, text) = record
                .chunks()
                .enumerate()
                .skip(payload)
                .filter_map(|(field, token)| match token {
                    Token::Str(value) => Some((field, value.as_str())),
                    _ => None,
                })
                .last()?;
            if text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) {
                return None;
            }
            let packed = text
                .parse::<u32>()
                .ok()
                .filter(|value| *value <= 0xff_ffff)?;
            Some(DirectAttributeColor {
                color: packed_rgb(packed)?,
                carrier: DirectColorCarrier::DecimalRgb { field },
            })
        }
        _ => None,
    }
}

/// The first well-formed exact direct-color carrier on an attribute chain.
pub fn attribute_chain_color_carrier<'a>(
    entity: &Record,
    max_steps: usize,
    mut by_index: impl FnMut(i64) -> Option<&'a Record>,
) -> Option<(&'a Record, DirectAttributeColor)> {
    let mut current = entity.ref_at(0)?;
    for _ in 0..max_steps {
        let record = by_index(current)?;
        if let Some(color) = direct_attribute_color(record) {
            return Some((record, color));
        }
        current = attribute_next(record)?;
    }
    None
}

/// The first well-formed exact direct color on `entity`'s attribute chain.
pub fn attribute_chain_color(
    entity: &Record,
    by_index: &HashMap<i64, &Record, RandomState>,
) -> Option<Color> {
    attribute_chain_color_carrier(entity, by_index.len(), |index| {
        by_index.get(&index).copied()
    })
    .map(|(_, decoded)| decoded.color)
}

/// The first non-empty name attribute on `entity`'s attribute chain.
pub fn attribute_chain_name(
    entity: &Record,
    by_index: &HashMap<i64, &Record, RandomState>,
) -> Option<String> {
    attribute_chain_name_text(entity, by_index).map(str::to_owned)
}

/// The first non-empty name attribute on `entity`'s attribute chain, borrowed
/// from the record that holds it.
pub(crate) fn attribute_chain_name_text<'a>(
    entity: &Record,
    by_index: &HashMap<i64, &'a Record, RandomState>,
) -> Option<&'a str> {
    let mut current = entity.ref_at(0)?;
    for _ in 0..by_index.len() {
        let record: &'a Record = by_index.get(&current)?;
        if record.name == "string_attrib-name_attrib-gen-attrib" {
            let mut values = record.tokens.iter().filter_map(|token| match token {
                Token::Str(value) => Some(value.as_str()),
                _ => None,
            });
            let mut previous = None;
            let mut last = None;
            for value in &mut values {
                previous = last;
                last = Some(value);
            }
            if let (Some("name"), Some(value)) = (previous, last) {
                if !value.is_empty() {
                    return Some(value);
                }
            }
        }
        let next = attribute_next(record)?;
        current = next;
    }
    None
}

/// The `UnknownId` for a preserved carrier record. Shared by the passthrough
/// `UnknownRecord` and any `SurfaceGeometry::Solved(SolvedSurfaceGeometry::Unknown)` that links to it, so the
/// reference resolves under validation.
pub fn unknown_record_id(
    rec: &Record,
    format: IdFormat,
) -> Result<UnknownId, cadmpeg_core::CodecError> {
    // The record-table index remains its identity when the source name has
    // no leading component. Keep the source spelling in the retained bytes.
    let head = if rec.head().is_empty() {
        "untyped-record"
    } else {
        rec.head()
    };
    let name = head.to_owned();
    let kind = IdentityComponent::try_new(name).map_err(|error| {
        cadmpeg_core::CodecError::malformed(format_args!(
            "invalid ASM source identity component: {error}"
        ))
    })?;
    Ok(UnknownId::from(format.try_brep_identity(&kind, rec.index)?))
}

#[cfg(test)]
mod tests {
    use super::decode_transform;
    use crate::sab::{Record, Token};

    fn transform_record(scale: f64, x: [f64; 3]) -> Record {
        Record {
            index: 0,
            name: "transform".into(),
            tokens: std::sync::Arc::from([
                Token::Vector3(x),
                Token::Vector3([0.0, 1.0, 0.0]),
                Token::Vector3([0.0, 0.0, 1.0]),
                Token::Position([0.0, 0.0, 0.0]),
                Token::Double(scale),
            ]),
            offset: 0,
            len: 0,
        }
    }

    #[test]
    fn transform_decode_propagates_affine_constructor_rejection() {
        let identity = transform_record(1.0, [1.0, 0.0, 0.0]);
        assert_eq!(
            decode_transform(&identity, 1.0),
            Some(cadmpeg_ir::transform::Transform::identity())
        );
        for scale in [0.0, 2.0, f64::NAN, f64::INFINITY] {
            assert!(decode_transform(&transform_record(scale, [1.0, 0.0, 0.0]), 1.0).is_none());
        }
        assert!(decode_transform(&transform_record(1.0, [f64::NAN, 0.0, 0.0]), 1.0).is_none());
        assert!(decode_transform(&identity, f64::INFINITY).is_none());
    }
}