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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
// SPDX-License-Identifier: Apache-2.0
//! Build B-rep topology and geometry from a framed SAB record table.
//!
//! [`decode_with_purpose`] follows the topology chain from bodies through
//! vertices and points. It creates analytic carriers for planes, cylinders,
//! cones, spheres, tori, lines, circles, and ellipses. [`crate::nurbs`]
//! supplies cached NURBS surfaces, 3D curves, and pcurves for spline and
//! procedural records.
//!
//! Faces retain their loops and trims when a referenced surface has no decoded
//! shape; a decoded construction produces a [`SurfaceGeometry::Procedural`]
//! carrier, while an undecoded record produces `SurfaceGeometry::Solved(SolvedSurfaceGeometry::Unknown)`
//! linked to the corresponding [`UnknownRecord`]. Edges retain vertices and
//! parameter ranges when their 3D curve carrier is unavailable. [`Stats`]
//! records these transfer losses for the decode report.
//!
//! ASM model-space lengths become millimetres. Unit vectors, ratios, angles,
//! knots, weights, and UV parameters keep their native scale.

pub mod annotations;
pub mod attributes;
pub mod emit;
pub mod geometry;
pub mod key_maps;
pub mod records;
pub mod stats;
use stats::Stats;
mod topology;
pub mod transfer;

use crate::asm_header;
use crate::ids::IdFormat;
use crate::nurbs;
use crate::nurbs::proc_curve::ProceduralCurveConstruction;
use crate::nurbs::proc_surface::DecodedProceduralSurface;
use crate::sab::Record;
use cadmpeg_ir::attributes::{AttributeTarget, SourceAttribute};
use cadmpeg_ir::geometry::{
    pcurve::{Pcurve, PcurveGeometry},
    Curve, CurveGeometry, ProceduralCurve, ProceduralSurface, Surface, SurfaceGeometry,
};
use cadmpeg_ir::ids::Identity;
use cadmpeg_ir::ids::{CurveId, SurfaceId};
use cadmpeg_ir::topology::{Body, Coedge, Edge, Face, Loop, Point, Region, Shell, Vertex};
use cadmpeg_ir::unknown::UnknownRecord;
use serde::{Deserialize, Serialize};
use serde_value::Value;
use std::collections::{HashMap, HashSet};

use self::annotations::{emit_annotation_records, AnnotationRecord};
use self::attributes::attribute_owner;
use self::emit::{
    count_other_records, emit_attributes, emit_carrier_records, emit_coedges, emit_containers,
    emit_edges, emit_faces, emit_loops, emit_passthrough_unknowns, emit_pcurves, emit_points,
    emit_vertices, CoedgeDecodeInputs, ContainerInputs, CurveSenseRefs,
};
use self::geometry::{
    attach_point_edge_carriers, clamp_edge_ranges_to_carrier_domains, classify_body_kinds,
    collapsed_edges,
};
use self::records::{
    BodyNativeKey, EdgeContinuity, EdgeOwnership, FaceNativeKey, FaceSidedness,
    MeshSurfaceSentinel, TolerantCoedgeParameters, TolerantEdgeTail, TolerantVertexTail,
    TransformHints, VertexOwnership, WireTopology,
};
use self::topology::{
    classify_edge_curve_senses, collect_wire_topology, decode_analytic_carriers,
    keep_faces_and_carriers, walk_reachable_topology, TopologyContext,
};
/// The decoded ASM B-rep graph plus loss accounting. Every field is a fact
/// of the ASM stream, independent of the format that references the stream.
#[derive(Default, Serialize)]
pub struct AsmBrep {
    /// Bodies.
    pub bodies: Vec<Body>,
    /// Regions.
    pub regions: Vec<Region>,
    /// Shells.
    pub shells: Vec<Shell>,
    /// Faces.
    pub faces: Vec<Face>,
    /// Loops.
    pub loops: Vec<Loop>,
    /// Coedges.
    pub coedges: Vec<Coedge>,
    /// Edges.
    pub edges: Vec<Edge>,
    /// Vertices.
    pub vertices: Vec<Vertex>,
    /// Points.
    pub points: Vec<Point>,
    /// Analytic surface carriers.
    pub surfaces: Vec<Surface>,
    /// Analytic curve carriers.
    pub curves: Vec<Curve>,
    /// Parameter-space curve carriers.
    pub pcurves: Vec<Pcurve>,
    /// Native procedural definitions for solved surface carriers.
    pub procedural_surfaces: Vec<(SurfaceId, ProceduralSurface)>,
    /// Native procedural definitions for solved curve caches.
    pub procedural_curves: Vec<(CurveId, ProceduralCurve)>,
    /// Kernel continuity classifications stored on solved edges.
    pub edge_continuities: Vec<EdgeContinuity>,
    /// Native owner-coedge selectors stored on solved edges.
    pub edge_ownerships: Vec<EdgeOwnership>,
    /// Native owner-edge and endpoint-slot fields stored on solved vertices.
    pub vertex_ownerships: Vec<VertexOwnership>,
    /// Native sidedness fields stored on solved faces.
    pub face_sidedness: Vec<FaceSidedness>,
    /// Native Design-join key field for every emitted face, including null keys.
    pub face_native_keys: Vec<FaceNativeKey>,
    /// Native parameter intervals stored on tolerant coedges.
    pub tolerant_coedge_parameters: Vec<TolerantCoedgeParameters>,
    /// Native trailing fields stored on tolerant edges.
    pub tolerant_edge_tails: Vec<TolerantEdgeTail>,
    /// Native trailing fields stored on tolerant vertices.
    pub tolerant_vertex_tails: Vec<TolerantVertexTail>,
    /// Zero-payload mesh-surface records used by emitted faces.
    pub mesh_surface_sentinels: Vec<MeshSurfaceSentinel>,
    /// Native rotation/reflection/shear classifications stored on transforms.
    pub transform_hints: Vec<TransformHints>,
    /// Native Design-join key field for every emitted body, including null keys.
    pub body_native_keys: Vec<BodyNativeKey>,
    /// Native wire records projected onto solved shells.
    pub wire_topologies: Vec<WireTopology>,
    /// Linked source-native attributes.
    pub attributes: Vec<SourceAttribute>,
    /// Undecoded carrier records preserved verbatim.
    pub unknowns: Vec<UnknownRecord>,
    /// Loss accounting for the report.
    pub stats: Stats,
    /// Source locations for emitted B-rep and synthetic child records.
    #[serde(skip)]
    pub annotation_records: Vec<AnnotationRecord>,
}

/// Flat wire shape of [`AsmBrep`].
///
/// The read names every key of the document object in one struct and refuses
/// any other. The join maps are not on the wire: they are projections of the
/// key records, derived on read through [`key_maps`].
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct AsmBrepWire {
    bodies: Vec<Body>,
    regions: Vec<Region>,
    shells: Vec<Shell>,
    faces: Vec<Face>,
    loops: Vec<Loop>,
    coedges: Vec<Coedge>,
    edges: Vec<Edge>,
    vertices: Vec<Vertex>,
    points: Vec<Point>,
    surfaces: Vec<Surface>,
    curves: Vec<Curve>,
    pcurves: Vec<Pcurve>,
    procedural_surfaces: Vec<(SurfaceId, ProceduralSurface)>,
    procedural_curves: Vec<(CurveId, ProceduralCurve)>,
    edge_continuities: Vec<EdgeContinuity>,
    edge_ownerships: Vec<EdgeOwnership>,
    vertex_ownerships: Vec<VertexOwnership>,
    face_sidedness: Vec<FaceSidedness>,
    face_native_keys: Vec<FaceNativeKey>,
    tolerant_coedge_parameters: Vec<TolerantCoedgeParameters>,
    tolerant_edge_tails: Vec<TolerantEdgeTail>,
    tolerant_vertex_tails: Vec<TolerantVertexTail>,
    mesh_surface_sentinels: Vec<MeshSurfaceSentinel>,
    transform_hints: Vec<TransformHints>,
    body_native_keys: Vec<BodyNativeKey>,
    wire_topologies: Vec<WireTopology>,
    attributes: Vec<SourceAttribute>,
    unknowns: Vec<UnknownRecord>,
    stats: Stats,
}

impl<'de> Deserialize<'de> for AsmBrep {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let wire = AsmBrepWire::deserialize(deserializer)?;
        Ok(Self {
            bodies: wire.bodies,
            regions: wire.regions,
            shells: wire.shells,
            faces: wire.faces,
            loops: wire.loops,
            coedges: wire.coedges,
            edges: wire.edges,
            vertices: wire.vertices,
            points: wire.points,
            surfaces: wire.surfaces,
            curves: wire.curves,
            pcurves: wire.pcurves,
            procedural_surfaces: wire.procedural_surfaces,
            procedural_curves: wire.procedural_curves,
            edge_continuities: wire.edge_continuities,
            edge_ownerships: wire.edge_ownerships,
            vertex_ownerships: wire.vertex_ownerships,
            face_sidedness: wire.face_sidedness,
            face_native_keys: wire.face_native_keys,
            tolerant_coedge_parameters: wire.tolerant_coedge_parameters,
            tolerant_edge_tails: wire.tolerant_edge_tails,
            tolerant_vertex_tails: wire.tolerant_vertex_tails,
            mesh_surface_sentinels: wire.mesh_surface_sentinels,
            transform_hints: wire.transform_hints,
            body_native_keys: wire.body_native_keys,
            wire_topologies: wire.wire_topologies,
            attributes: wire.attributes,
            unknowns: wire.unknowns,
            stats: wire.stats,
            annotation_records: Vec::new(),
        })
    }
}

impl AsmBrep {
    /// Append a disjoint, already-qualified ASM graph.
    pub fn append(&mut self, mut other: Self) {
        macro_rules! append_vecs {
            ($($field:ident),+ $(,)?) => {
                $((self.$field).append(&mut other.$field);)+
            };
        }
        append_vecs!(
            bodies,
            regions,
            shells,
            faces,
            loops,
            coedges,
            edges,
            vertices,
            points,
            surfaces,
            curves,
            pcurves,
            procedural_surfaces,
            procedural_curves,
            edge_continuities,
            edge_ownerships,
            vertex_ownerships,
            face_sidedness,
            face_native_keys,
            tolerant_coedge_parameters,
            tolerant_edge_tails,
            tolerant_vertex_tails,
            mesh_surface_sentinels,
            transform_hints,
            body_native_keys,
            wire_topologies,
            attributes,
            unknowns,
            annotation_records,
        );
        self.stats.merge(other.stats);
    }
}

/// Collect every `id` field value in a serialized value tree.
pub fn collect_owned_ids(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    value: &Value,
    out: &mut HashSet<String, std::collections::hash_map::RandomState>,
) -> Result<(), cadmpeg_core::CodecError> {
    let _depth = ctx.enter_nested("collect ASM owned ids")?;
    match value {
        Value::Map(fields) => {
            if let Some(id) = fields
                .iter()
                .find(|(key, _)| matches!(key, Value::String(name) if name == "id"))
                .map(|(_, value)| value)
                .and_then(value_string)
            {
                out.insert(id.to_owned());
            }
            for (key, value) in fields {
                collect_owned_ids(ctx, key, out)?;
                collect_owned_ids(ctx, value, out)?;
            }
        }
        Value::Seq(items) => {
            for item in items {
                collect_owned_ids(ctx, item, out)?;
            }
        }
        Value::Option(Some(value)) | Value::Newtype(value) => collect_owned_ids(ctx, value, out)?,
        _ => {}
    }
    Ok(())
}

/// The string payload of a serialized value, unwrapping newtype layers.
pub fn value_string(value: &Value) -> Option<&str> {
    match value {
        Value::String(value) => Some(value),
        Value::Newtype(value) => value_string(value),
        _ => None,
    }
}

/// Build the undirected id-adjacency of every entity in the top-level
/// sequences of a serialized value tree.
pub fn collect_entity_adjacency(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    value: &Value,
    owned: &HashSet<String, std::collections::hash_map::RandomState>,
    out: &mut HashMap<
        String,
        HashSet<String, std::collections::hash_map::RandomState>,
        std::collections::hash_map::RandomState,
    >,
) -> Result<(), cadmpeg_core::CodecError> {
    let Value::Map(fields) = value else {
        return Ok(());
    };
    for value in fields.values() {
        let Value::Seq(items) = value else {
            continue;
        };
        for item in items {
            let Some(id) = entity_id(item) else {
                continue;
            };
            let mut references = HashSet::new();
            collect_references(ctx, item, owned, &mut references)?;
            references.remove(id);
            for reference in references {
                insert_adjacency(out, id, &reference);
                insert_adjacency(out, &reference, id);
            }
        }
    }
    Ok(())
}

fn insert_adjacency(out: &mut HashMap<String, HashSet<String>>, owner: &str, reference: &str) {
    out.entry(owner.to_owned())
        .or_default()
        .insert(reference.to_owned());
}

/// The `id` field of a serialized entity map.
pub fn entity_id(value: &Value) -> Option<&str> {
    let Value::Map(fields) = value else {
        return None;
    };
    fields
        .iter()
        .find(|(key, _)| matches!(key, Value::String(name) if name == "id"))
        .map(|(_, value)| value)
        .and_then(value_string)
}

/// Collect every string in a serialized value tree that names an owned id.
pub fn collect_references(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    value: &Value,
    owned: &HashSet<String, std::collections::hash_map::RandomState>,
    out: &mut HashSet<String, std::collections::hash_map::RandomState>,
) -> Result<(), cadmpeg_core::CodecError> {
    let _depth = ctx.enter_nested("collect ASM references")?;
    match value {
        Value::String(id) if owned.contains(id) => {
            out.insert(id.to_owned());
        }
        Value::Seq(items) => {
            for item in items {
                collect_references(ctx, item, owned, out)?;
            }
        }
        Value::Map(fields) => {
            for (key, value) in fields {
                collect_references(ctx, key, owned, out)?;
                collect_references(ctx, value, owned, out)?;
            }
        }
        Value::Option(Some(value)) | Value::Newtype(value) => {
            collect_references(ctx, value, owned, out)?;
        }
        _ => {}
    }
    Ok(())
}

/// Retain only entities with a reachable `id` in the top-level sequences of a
/// serialized value tree.
pub fn retain_root_entities(
    value: &mut Value,
    reachable: &HashSet<String, std::collections::hash_map::RandomState>,
) {
    let Value::Map(fields) = value else {
        return;
    };
    for value in fields.values_mut() {
        if let Value::Seq(items) = value {
            items.retain(|item| entity_id(item).is_none_or(|id| reachable.contains(id)));
        }
    }
}

/// Rewrite every string in a serialized value tree through `replacements`.
pub fn remap_owned_ids(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    value: &mut Value,
    replacements: &HashMap<String, String, std::collections::hash_map::RandomState>,
) -> Result<(), cadmpeg_core::CodecError> {
    let _depth = ctx.enter_nested("remap ASM owned ids")?;
    match value {
        Value::String(id) => {
            if let Some(replacement) = replacements.get(id) {
                *id = replacement.to_owned();
            }
        }
        Value::Seq(items) => {
            for item in items {
                remap_owned_ids(ctx, item, replacements)?;
            }
        }
        Value::Map(fields) => {
            let entries = std::mem::take(fields);
            for (mut key, mut item) in entries {
                remap_owned_ids(ctx, &mut key, replacements)?;
                remap_owned_ids(ctx, &mut item, replacements)?;
                fields.insert(key, item);
            }
        }
        Value::Option(Some(value)) | Value::Newtype(value) => {
            remap_owned_ids(ctx, value, replacements)?;
        }
        _ => {}
    }
    Ok(())
}

fn count_kind(counts: &mut std::collections::BTreeMap<String, usize>, kind: &str) {
    *counts.entry(kind.to_owned()).or_insert(0) += 1;
}

// ---- geometry carrier decode -------------------------------------------------

/// Formats the stable IR id for the entity emitted from record `index`.
pub fn id(format: IdFormat, index: i64) -> Identity {
    format.brep_identity(&cadmpeg_ir::identity_component!("entity"), index)
}

/// Construction and fit metadata separated from the cache geometry.
enum ProceduralCurveSource {
    Cached {
        construction: Box<ProceduralCurveConstruction>,
        cache_fit_tolerance: Option<f64>,
        parsed_domain: Option<[f64; 2]>,
    },
    Cacheless(Box<cadmpeg_ir::geometry::ProceduralCurveDefinition>),
}

#[derive(Clone, Copy, PartialEq, Eq, Hash)]
struct PcurveRecordIndex(i64);

#[derive(Clone, Copy, PartialEq, Eq, Hash)]
struct CoedgeRecordIndex(i64);

/// Decoded carrier geometry keyed by `RecordTable` index. The reachability and
/// emit passes read decoded shapes from here and consume them (`remove`) as the
/// owning surface or curve record is emitted.
#[derive(Default)]
struct Carriers {
    /// Source record indices of synthetic procedural support surfaces.
    procedural_support_sources: Vec<(i64, SurfaceId)>,
    /// Source record indices of synthetic procedural surface curves.
    procedural_curve_child_sources: Vec<(i64, CurveId)>,
    surface_geo: HashMap<i64, SurfaceGeometry>,
    procedural_surface_defs: HashMap<i64, DecodedProceduralSurface>,
    curve_geo: HashMap<i64, CurveGeometry>,
    procedural_curve_defs: HashMap<i64, ProceduralCurveSource>,
    pcurve_geo: HashMap<PcurveRecordIndex, PcurveGeometry>,
    pcurve_parameter_ranges: HashMap<CoedgeRecordIndex, [f64; 2]>,
}

/// Record indices reached from kept faces by the shell/loop/coedge walk,
/// grouped by entity kind. Every emit pass filters `records` against these
/// sets so only reachable entities appear in the output.
#[derive(Default)]
pub struct Reachable {
    /// Face slots admitted by the face pass.
    pub faces: HashSet<i64>,
    loops: HashSet<i64>,
    coedges: HashSet<i64>,
    edges: HashSet<i64>,
    vertices: HashSet<i64>,
    points: HashSet<i64>,
    surfaces: HashSet<i64>,
    curves: HashSet<i64>,
    pcurves: HashSet<i64>,
    unknown_surface_records: HashSet<i64>,
    cached_unknown_procedural_surfaces: HashSet<i64>,
    undecoded_carriers: HashSet<i64>,
}

/// Wire-edge and free-vertex reachability collected per shell during the
/// topology walk, consumed when emitting shell containers.
#[derive(Default)]
pub struct WireShellTopology {
    wire_edges_by_shell: HashMap<i64, Vec<i64>>,
    free_vertices_by_shell: HashMap<i64, Vec<i64>>,
    saved_free_edges: Vec<i64>,
}

/// Which outputs a decode materializes.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum DecodePurpose {
    /// Transfer complete neutral geometry and retained native records.
    Model,
    /// Transfer stable topology plus measurements used by history binding.
    History,
}

/// Decode a framed active slice into the ASM B-rep graph.
///
/// `stream` names the source ZIP entry for provenance. Ids are minted as
/// `<format>:brep:entity#<record-index>`, unique across the `RecordTable`.
/// [`DecodePurpose::History`] skips free-form carrier shapes because
/// historical binding consumes stable record identities, not control data.
pub fn decode_with_purpose(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    records: &[Record],
    bytes: &[u8],
    stream: &str,
    format: IdFormat,
    purpose: DecodePurpose,
) -> Result<AsmBrep, cadmpeg_core::CodecError> {
    let header = asm_header::parse(bytes).map(|header| header.metadata);
    decode_with_header(
        ctx,
        records,
        bytes,
        header.as_ref(),
        stream,
        format,
        purpose,
    )
}

/// Decode a framed slice whose header the caller supplies.
///
/// The text encoding ([`crate::sat`]) carries the same header fields in ASCII
/// header lines rather than the binary layout, so its caller parses them and
/// passes the result here. `bytes` remains the source byte image: unknown
/// records retain their byte extents from it.
pub fn decode_with_header(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    records: &[Record],
    bytes: &[u8],
    header: Option<&crate::kernel_header::KernelHeader>,
    stream: &str,
    format: IdFormat,
    purpose: DecodePurpose,
) -> Result<AsmBrep, cadmpeg_core::CodecError> {
    let token_table = nurbs::toks::SubtypeTable::from_records(records)
        .with_save_format_version(header.and_then(|header| header.save_format_version));
    decode_with_table(
        ctx,
        records,
        bytes,
        (header, &token_table),
        stream,
        format,
        purpose,
    )
}

/// Decode a History subset with the complete state's subtype numbering.
/// The supplied table must carry the stream's save format version.
pub fn decode_history_with_subtypes(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    records: &[Record],
    bytes: &[u8],
    format: IdFormat,
    subtypes: &nurbs::toks::SubtypeTable,
) -> Result<AsmBrep, cadmpeg_core::CodecError> {
    let header = asm_header::parse(bytes).map(|header| header.metadata);
    decode_with_table(
        ctx,
        records,
        bytes,
        (header.as_ref(), subtypes),
        "history",
        format,
        DecodePurpose::History,
    )
}

fn decode_with_table(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    records: &[Record],
    bytes: &[u8],
    tables: (
        Option<&crate::kernel_header::KernelHeader>,
        &nurbs::toks::SubtypeTable,
    ),
    stream: &str,
    format: IdFormat,
    purpose: DecodePurpose,
) -> Result<AsmBrep, cadmpeg_core::CodecError> {
    let (header, token_table) = tables;
    let mut out = AsmBrep::default();

    // Index records by RecordTable index (== position for a framed slice).
    let mut by_index: HashMap<i64, &Record> = HashMap::new();

    for record in records {
        by_index.insert(
            i64::try_from(record.index).map_err(|_| {
                cadmpeg_core::CodecError::malformed("ASM record index exceeds the i64 range")
            })?,
            record,
        );
    }
    nurbs::toks::admit_subtype_references(ctx, records, token_table)?;
    let save_format_major = header.and_then(crate::kernel_header::KernelHeader::save_format_major);
    let saved_entity_limit = header
        .and_then(|header| header.entity_count)
        .and_then(|count| i64::try_from(count).ok());
    let header_scale = header.and_then(|header| header.scale).unwrap_or(1.0);

    let (mut carriers, inward_normal_surfaces) = decode_analytic_carriers(records)?;
    let mut reach = Reachable::default();

    let topology_context = TopologyContext {
        ctx,
        by_index: &by_index,
        token_table,
        purpose,
        format,
    };
    keep_faces_and_carriers(
        topology_context,
        &mut out,
        records,
        &mut carriers,
        &mut reach,
    )?;
    walk_reachable_topology(topology_context, &mut out, &mut carriers, &mut reach)?;
    let wire = collect_wire_topology(
        topology_context,
        &mut out,
        records,
        saved_entity_limit,
        &mut carriers,
        &mut reach,
    )?;

    let (reversed_curve_refs, forward_curve_refs) = classify_edge_curve_senses(records, &reach)?;

    emit_carrier_records(
        &mut out,
        records,
        &mut carriers,
        &reach,
        CurveSenseRefs {
            reversed_curve_refs: &reversed_curve_refs,
            forward_curve_refs: &forward_curve_refs,
        },
        format,
    )?;
    emit_pcurves(&mut out, records, &mut carriers, &reach, format)?;
    emit_points(&mut out, records, &reach, format)?;
    emit_vertices(&mut out, records, &by_index, &reach, format)?;
    emit_edges(
        &mut out,
        records,
        &by_index,
        &reach,
        CurveSenseRefs {
            reversed_curve_refs: &reversed_curve_refs,
            forward_curve_refs: &forward_curve_refs,
        },
        format,
    )?;
    emit_coedges(
        &mut out,
        records,
        CoedgeDecodeInputs {
            token_table,
            save_format_major,
        },
        &carriers,
        &reach,
        format,
    )?;
    emit_loops(&mut out, records, &by_index, &reach, format)?;
    emit_faces(
        ctx,
        &mut out,
        records,
        &by_index,
        &reach,
        &inward_normal_surfaces,
        format,
    )?;
    emit_containers(
        ctx,
        &mut out,
        ContainerInputs {
            records,
            bytes,
            by_index: &by_index,
            reach: &reach,
            wire: &wire,
            stream,
            header_scale,
            format,
        },
    )?;
    let emitted_attributes = emit_attributes(&mut out, records, &by_index, &reach, format)?;
    if purpose == DecodePurpose::Model {
        emit_passthrough_unknowns(ctx, &mut out, records, bytes, &reach, format)?;
        count_other_records(&mut out, records, &reach, &emitted_attributes)?;
        emit_annotation_records(ctx, &mut out, records, &by_index, &carriers, stream, format)?;

        attach_point_edge_carriers(&mut out, records, format);
        let collapsed = collapsed_edges(records, &by_index, &reach.edges, format)?;
        classify_body_kinds(&mut out, &collapsed);
        clamp_edge_ranges_to_carrier_domains(&mut out)?;
    }

    Ok(out)
}

fn inherited_attribute_target(
    mut owner: i64,
    by_index: &HashMap<i64, &Record>,
    targets: &HashMap<i64, AttributeTarget>,
) -> Option<AttributeTarget> {
    for _ in 0..=by_index.len() {
        if let Some(target) = targets.get(&owner) {
            return Some(target.clone());
        }
        let attribute = by_index.get(&owner)?;
        if !attribute.name.ends_with("-attrib") {
            return None;
        }
        owner = attribute_owner(attribute)?;
    }
    None
}

#[cfg(test)]
mod tests;

mod identity_rewrite;

#[cfg(test)]
mod supplied_subtype_tests {
    #[test]
    fn history_subset_admits_references_against_supplied_table() {
        use crate::sab::{Record, Token};
        use cadmpeg_core::decode::{DecodeArena, DecodeContext, DecodePolicy};
        let definition: std::sync::Arc<[Token]> = vec![
            Token::SubtypeOpen,
            Token::Ident("example".into()),
            Token::SubtypeClose,
        ]
        .into();
        let table = crate::nurbs::toks::SubtypeTable::from_definitions(vec![(definition, 0)]);
        let records = [Record {
            index: 1,
            name: "unused".into(),
            offset: 0,
            len: 0,
            tokens: vec![
                Token::SubtypeOpen,
                Token::Ident("ref".into()),
                Token::Long(0),
                Token::SubtypeClose,
            ]
            .into(),
        }];
        let arena = DecodeArena::new();
        let mut policy = DecodePolicy::service();
        policy.limits.max_recursion_depth = 0;
        let (ctx, _) = DecodeContext::from_root_bytes(&[], &arena, &policy).unwrap();
        assert!(super::decode_history_with_subtypes(
            &ctx,
            &records,
            &[],
            crate::ids::IdFormat::from_literal("f3d").unwrap(),
            &table
        )
        .is_err());
        assert!(super::decode_with_purpose(
            &ctx,
            &records,
            &[],
            "history",
            crate::ids::IdFormat::from_literal("f3d").unwrap(),
            super::DecodePurpose::History
        )
        .is_ok());
    }
}