acadrust 0.6.2

A pure Rust library for reading and writing CAD files in DXF format (ASCII and Binary) and DWG format (Binary).
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
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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
//! SAT (Save and Restore) text format writer.
//!
//! Writes a [`SatDocument`] structure back to ACIS SAT text format.

use super::types::*;

/// Writer for ACIS SAT text format.
pub struct SatWriter;

impl SatWriter {
    /// Write a [`SatDocument`] to SAT text format.
    pub fn write(doc: &SatDocument) -> String {
        let completed = doc.completed_for_restore();
        let doc = completed.as_ref().unwrap_or(doc);
        let mut output = String::new();

        // Classic SAT 7.0 uses zero here. Modern SAT exports carry the actual
        // record count; some readers treat zero as empty data.
        let num_records_out = if doc.header.version.major == 7 {
            0
        } else if doc.header.version.major > 7 {
            doc.records.len()
        } else {
            doc.header.num_records
        };
        output.push_str(&format!(
            "{} {} {} {}\n",
            doc.header.version.sat_version_number(),
            num_records_out,
            doc.header.num_bodies,
            u32::from(doc.header.has_history)
        ));

        // Header line 2: product info
        // Header string lengths have no '@', even in SAT 7.0. Only strings
        // inside entity records use the @-prefixed representation.
        output.push_str(&format!(
            "{} {} {} {} {} {}\n",
            doc.header.product_id.len(),
            doc.header.product_id,
            doc.header.product_version.len(),
            doc.header.product_version,
            doc.header.date.len(),
            doc.header.date,
        ));

        // Header line 3: tolerances
        if let Some(resfit) = doc.header.resfit_tolerance {
            output.push_str(&format!(
                "{} {} {}\n",
                format_float(doc.header.spatial_resolution),
                format_float(doc.header.normal_tolerance),
                format_float(resfit),
            ));
        } else {
            output.push_str(&format!(
                "{} {}\n",
                format_float(doc.header.spatial_resolution),
                format_float(doc.header.normal_tolerance),
            ));
        }

        // Entity records
        for record in &doc.records {
            Self::write_record(&mut output, record, &doc.header.version);
        }

        // End marker
        output.push_str("End-of-ACIS-data\n");

        output
    }

    /// Write a single entity record.
    fn write_record(output: &mut String, record: &SatRecord, version: &SatVersion) {
        // Transform has attribute/id fields but no pattern pointer.
        if record.entity_type == "transform" {
            output.push_str(&format!("transform {}", record.attribute));
            if version.major >= 7 {
                output.push_str(&format!(" {}", record.subtype_id));
            }
            for token in record
                .tokens
                .iter()
                .skip_while(|token| matches!(token, SatToken::Pointer(_)))
            {
                output.push(' ');
                Self::write_token(output, token, version);
            }
            output.push_str(" #\n");
            return;
        }
        // Entity type (no explicit index prefix — ACIS 7.0+ doesn't use them in DXF)
        output.push_str(&record.entity_type);
        output.push(' ');

        // Attribute pointer
        output.push_str(&format!("{}", record.attribute));

        // Subtype/ID field (only present in ACIS 7.0+ / SAT version 700+)
        if version.major >= 7 {
            output.push_str(&format!(" {}", record.subtype_id));
        }

        // Determine which token index to skip for pre-7.0 output.
        // The parser inserts a synthetic sentinel $-1 to normalize v400
        // records to v700 layout; the writer must strip it when producing
        // v400 output.
        let skip_index: Option<usize> = if version.major < 7 {
            match base_entity_type(&record.entity_type) {
                "lump" => Some(1),
                "shell" => Some(2),
                "body" | "subshell" | "wire" | "face" | "loop" | "vertex" | "coedge" | "edge"
                | "point" | "transform" | "surface" | "curve" | "pcurve" => Some(0),
                _ => None,
            }
        } else {
            None
        };

        // Remaining tokens
        for (i, token) in record.tokens.iter().enumerate() {
            if Some(i) == skip_index {
                continue; // skip the synthetic sentinel
            }
            // SAT 4.0 edges have no parameter pair or trailing tolerance
            // descriptor: $start $end $coedge $curve sense.
            if version.major < 7
                && base_entity_type(&record.entity_type) == "edge"
                && (i == 2 || i == 4 || i >= 8)
            {
                continue;
            }
            output.push(' ');
            Self::write_token(output, token, version);
        }

        // Record terminator
        output.push_str(" #\n");
    }

    /// Write a single token.
    fn write_token(output: &mut String, token: &SatToken, version: &SatVersion) {
        match token {
            SatToken::String(s) => {
                if version.has_counted_strings() {
                    output.push_str(&format!("@{} {}", s.len(), s));
                } else {
                    output.push_str(&format!("{} {}", s.len(), s));
                }
            }
            SatToken::Float(v) => {
                output.push_str(&format_float(*v));
            }
            SatToken::Position(x, y, z) => {
                output.push_str(&format_float(*x));
                output.push(' ');
                output.push_str(&format_float(*y));
                output.push(' ');
                output.push_str(&format_float(*z));
            }
            SatToken::True => output.push('T'),
            SatToken::False => output.push('F'),
            _ => {
                output.push_str(&format!("{}", token));
            }
        }
    }
}

/// Format a float value for SAT output, preserving precision.
///
/// Uses scientific notation (e.g. `9.9999999999999995e-007`) for very
/// small or very large values, matching the ACIS convention.
fn format_float(v: f64) -> String {
    if v == 0.0 {
        // A negative zero keeps its sign, as the reference application writes it.
        if v.is_sign_negative() { "-0" } else { "0" }.to_string()
    } else if v.fract() == 0.0 && v.abs() < 1e15 && !v.is_infinite() && !v.is_nan() {
        format!("{}", v as i64)
    } else if v.abs() < 1e-3 || v.abs() >= 1e15 {
        // Scientific notation with 3-digit exponent to match ACIS convention.
        // Rust's {:e} gives e.g. "1e-6"; we need "1e-006".
        let s = format!("{:e}", v);
        // Parse exponent part and reformat with 3-digit exponent
        if let Some(pos) = s.find('e') {
            let mantissa = &s[..pos];
            let exp_str = &s[pos + 1..];
            let exp: i32 = exp_str.parse().unwrap_or(0);
            // Trim trailing zeros from mantissa (keep at least one digit
            // after decimal point if present), but strip the point
            // entirely if there is no fractional part.
            let mantissa = if mantissa.contains('.') {
                let trimmed = mantissa.trim_end_matches('0');
                let trimmed = trimmed.trim_end_matches('.');
                trimmed
            } else {
                mantissa
            };
            if exp < 0 {
                format!("{}e-{:03}", mantissa, -exp)
            } else {
                format!("{}e+{:03}", mantissa, exp)
            }
        } else {
            s
        }
    } else {
        // Use full precision
        format!("{}", v)
    }
}

// ============================================================================
// Builder helpers
// ============================================================================

impl SatDocument {
    /// Create a new SAT document for a simple body with ACIS 7.0 format.
    ///
    /// Sets up the `body` record at index 0 (no asmheader needed for DXF SAT).
    pub fn new_body() -> Self {
        let mut doc = Self::new();
        doc.header.num_bodies = 1;

        // Add body (index 0 — SAT in DXF does not use asmheader)
        let mut body = SatRecord::new(0, "body");
        body.attribute = SatPointer::NULL;
        body.tokens.push(SatToken::Pointer(SatPointer::NULL)); // next_body
        body.tokens.push(SatToken::Pointer(SatPointer::NULL)); // lump
        body.tokens.push(SatToken::Pointer(SatPointer::NULL)); // wire
        body.tokens.push(SatToken::Pointer(SatPointer::NULL)); // transform
        doc.records.push(body);

        doc.header.num_records = doc.records.len();
        doc
    }

    /// Add a transform record and return its index.
    pub fn add_transform(
        &mut self,
        rotation: [[f64; 3]; 3],
        translation: [f64; 3],
        scale: f64,
    ) -> i32 {
        let index = self.records.len() as i32;
        let mut record = SatRecord::new(index, "transform");
        record.attribute = SatPointer::NULL;
        record.tokens.push(SatToken::Pointer(SatPointer::NULL)); // v700 unknown (always $-1)

        // 3x3 rotation matrix
        for row in &rotation {
            for &val in row {
                record.tokens.push(SatToken::Float(val));
            }
        }

        // Translation
        for &val in &translation {
            record.tokens.push(SatToken::Float(val));
        }

        // Scale
        record.tokens.push(SatToken::Float(scale));
        record
            .tokens
            .extend(transform_flags(rotation, scale).map(|flag| SatToken::Ident(flag.into())));

        self.records.push(record);
        self.header.num_records = self.records.len();
        index
    }

    /// Add a point record and return its index.
    pub fn add_point(&mut self, x: f64, y: f64, z: f64) -> i32 {
        let index = self.records.len() as i32;
        let mut record = SatRecord::new(index, "point");
        record.attribute = SatPointer::NULL;
        record.tokens.push(SatToken::Pointer(SatPointer::NULL)); // v700 unknown (always $-1)
        record.tokens.push(SatToken::Float(x));
        record.tokens.push(SatToken::Float(y));
        record.tokens.push(SatToken::Float(z));
        self.records.push(record);
        self.header.num_records = self.records.len();
        index
    }

    /// Add a plane-surface record and return its index.
    pub fn add_plane_surface(&mut self, root: [f64; 3], normal: [f64; 3], u_dir: [f64; 3]) -> i32 {
        let index = self.records.len() as i32;
        let mut record = SatRecord::new(index, "plane-surface");
        record.attribute = SatPointer::NULL;
        record.tokens.push(SatToken::Pointer(SatPointer::NULL)); // v700 unknown (always $-1)
        for &v in &root {
            record.tokens.push(SatToken::Float(v));
        }
        for &v in &normal {
            record.tokens.push(SatToken::Float(v));
        }
        for &v in &u_dir {
            record.tokens.push(SatToken::Float(v));
        }
        record.tokens.push(SatToken::Ident("forward_v".to_string()));
        record.tokens.push(SatToken::Ident("I".to_string()));
        record.tokens.push(SatToken::Ident("I".to_string()));
        record.tokens.push(SatToken::Ident("I".to_string()));
        record.tokens.push(SatToken::Ident("I".to_string()));
        self.records.push(record);
        self.header.num_records = self.records.len();
        index
    }

    /// Add a straight-curve record and return its index.
    pub fn add_straight_curve(&mut self, root: [f64; 3], direction: [f64; 3]) -> i32 {
        let index = self.records.len() as i32;
        let mut record = SatRecord::new(index, "straight-curve");
        record.attribute = SatPointer::NULL;
        record.tokens.push(SatToken::Pointer(SatPointer::NULL)); // v700 unknown (always $-1)
        for &v in &root {
            record.tokens.push(SatToken::Float(v));
        }
        for &v in &direction {
            record.tokens.push(SatToken::Float(v));
        }
        record.tokens.push(SatToken::Ident("I".to_string()));
        record.tokens.push(SatToken::Ident("I".to_string()));
        self.records.push(record);
        self.header.num_records = self.records.len();
        index
    }

    /// Add a cone-surface record and return its index.
    ///
    /// For a cylinder, use `cos_half_angle = 1.0` and `sin_half_angle = 0.0`.
    pub fn add_cone_surface(
        &mut self,
        center: [f64; 3],
        axis: [f64; 3],
        major_axis: [f64; 3],
        ratio: f64,
        cos_half_angle: f64,
        sin_half_angle: f64,
    ) -> i32 {
        let index = self.records.len() as i32;
        let mut record = SatRecord::new(index, "cone-surface");
        record.attribute = SatPointer::NULL;
        record.tokens.push(SatToken::Pointer(SatPointer::NULL)); // v700 unknown (always $-1)
        for &v in &center {
            record.tokens.push(SatToken::Float(v));
        }
        for &v in &axis {
            record.tokens.push(SatToken::Float(v));
        }
        for &v in &major_axis {
            record.tokens.push(SatToken::Float(v));
        }
        record.tokens.push(SatToken::Float(ratio));
        // Spline/law continuation parameters (always I I for simple surfaces)
        record.tokens.push(SatToken::Ident("I".to_string()));
        record.tokens.push(SatToken::Ident("I".to_string()));
        // Half-angle: ACIS stores sine first, then cosine
        record.tokens.push(SatToken::Float(sin_half_angle));
        record.tokens.push(SatToken::Float(cos_half_angle));
        // Radius at reference cross-section = |major_axis|
        let radius = (major_axis[0] * major_axis[0]
            + major_axis[1] * major_axis[1]
            + major_axis[2] * major_axis[2])
            .sqrt();
        record.tokens.push(SatToken::Float(radius));
        // cone-surface uses `forward` (not `forward_v` like plane/sphere)
        record.tokens.push(SatToken::Ident("forward".to_string()));
        record.tokens.push(SatToken::Ident("I".to_string()));
        record.tokens.push(SatToken::Ident("I".to_string()));
        record.tokens.push(SatToken::Ident("I".to_string()));
        record.tokens.push(SatToken::Ident("I".to_string()));
        self.records.push(record);
        self.header.num_records = self.records.len();
        index
    }

    /// Add a sphere-surface record and return its index.
    pub fn add_sphere_surface(
        &mut self,
        center: [f64; 3],
        radius: f64,
        u_dir: [f64; 3],
        pole: [f64; 3],
    ) -> i32 {
        let index = self.records.len() as i32;
        let mut record = SatRecord::new(index, "sphere-surface");
        record.attribute = SatPointer::NULL;
        record.tokens.push(SatToken::Pointer(SatPointer::NULL)); // v700 unknown (always $-1)
        for &v in &center {
            record.tokens.push(SatToken::Float(v));
        }
        record.tokens.push(SatToken::Float(radius));
        for &v in &u_dir {
            record.tokens.push(SatToken::Float(v));
        }
        for &v in &pole {
            record.tokens.push(SatToken::Float(v));
        }
        record.tokens.push(SatToken::Ident("forward_v".to_string()));
        record.tokens.push(SatToken::Ident("I".to_string()));
        record.tokens.push(SatToken::Ident("I".to_string()));
        record.tokens.push(SatToken::Ident("I".to_string()));
        record.tokens.push(SatToken::Ident("I".to_string()));
        self.records.push(record);
        self.header.num_records = self.records.len();
        index
    }

    /// Add a torus-surface record and return its index.
    pub fn add_torus_surface(
        &mut self,
        center: [f64; 3],
        normal: [f64; 3],
        major_radius: f64,
        minor_radius: f64,
        u_dir: [f64; 3],
    ) -> i32 {
        let index = self.records.len() as i32;
        let mut record = SatRecord::new(index, "torus-surface");
        record.attribute = SatPointer::NULL;
        record.tokens.push(SatToken::Pointer(SatPointer::NULL)); // v700 unknown (always $-1)
        for &v in &center {
            record.tokens.push(SatToken::Float(v));
        }
        for &v in &normal {
            record.tokens.push(SatToken::Float(v));
        }
        record.tokens.push(SatToken::Float(major_radius));
        record.tokens.push(SatToken::Float(minor_radius));
        for &v in &u_dir {
            record.tokens.push(SatToken::Float(v));
        }
        record.tokens.push(SatToken::Ident("forward_v".to_string()));
        record.tokens.push(SatToken::Ident("I".to_string()));
        record.tokens.push(SatToken::Ident("I".to_string()));
        record.tokens.push(SatToken::Ident("I".to_string()));
        record.tokens.push(SatToken::Ident("I".to_string()));
        self.records.push(record);
        self.header.num_records = self.records.len();
        index
    }

    /// Add an ellipse-curve record and return its index.
    pub fn add_ellipse_curve(
        &mut self,
        center: [f64; 3],
        normal: [f64; 3],
        major_axis: [f64; 3],
        ratio: f64,
    ) -> i32 {
        let index = self.records.len() as i32;
        let mut record = SatRecord::new(index, "ellipse-curve");
        record.attribute = SatPointer::NULL;
        record.tokens.push(SatToken::Pointer(SatPointer::NULL)); // v700 unknown (always $-1)
        for &v in &center {
            record.tokens.push(SatToken::Float(v));
        }
        for &v in &normal {
            record.tokens.push(SatToken::Float(v));
        }
        for &v in &major_axis {
            record.tokens.push(SatToken::Float(v));
        }
        record.tokens.push(SatToken::Float(ratio));
        record.tokens.push(SatToken::Ident("I".to_string()));
        record.tokens.push(SatToken::Ident("I".to_string()));
        self.records.push(record);
        self.header.num_records = self.records.len();
        index
    }

    /// Add an exact 3-D NURBS curve carried by an `exactcur` record.
    #[allow(clippy::too_many_arguments)]
    pub fn add_spline_curve(
        &mut self,
        rational: bool,
        degree: i32,
        closed: bool,
        knots: &[(f64, i32)],
        control: &[[f64; 3]],
        weights: Option<&[f64]>,
        fit_tol: f64,
    ) -> i32 {
        let index = self.records.len() as i32;
        let mut record = SatRecord::new(index, "intcurve-curve");
        record.attribute = SatPointer::NULL;
        let id = |value: &str| SatToken::Ident(value.to_string());

        record.tokens.push(SatToken::Pointer(SatPointer::NULL));
        record.tokens.push(id("forward"));
        record.tokens.push(id("{"));
        record.tokens.push(id("exactcur"));
        record.tokens.push(SatToken::Enum("full".to_string()));
        record
            .tokens
            .push(id(if rational { "nurbs" } else { "nubs" }));
        record.tokens.push(SatToken::Integer(degree as i64));
        record.tokens.push(SatToken::Enum(
            if closed { "closed" } else { "open" }.to_string(),
        ));
        record.tokens.push(SatToken::Integer(knots.len() as i64));
        for (position, &(knot, multiplicity)) in knots.iter().enumerate() {
            record.tokens.push(SatToken::Float(knot));
            let implicit = i32::from(position == 0 || position + 1 == knots.len());
            record
                .tokens
                .push(SatToken::Integer((multiplicity - implicit) as i64));
        }
        for (position, point) in control.iter().enumerate() {
            record.tokens.push(SatToken::Float(point[0]));
            record.tokens.push(SatToken::Float(point[1]));
            record.tokens.push(SatToken::Float(point[2]));
            if rational {
                record.tokens.push(SatToken::Float(
                    weights
                        .and_then(|values| values.get(position))
                        .copied()
                        .unwrap_or(1.0),
                ));
            }
        }
        record.tokens.push(SatToken::Float(fit_tol));
        record.tokens.extend([
            id("null_surface"),
            id("null_surface"),
            id("nullbs"),
            id("nullbs"),
            id("I"),
            id("I"),
        ]);
        record.tokens.extend([
            SatToken::Integer(0),
            SatToken::Integer(0),
            SatToken::Integer(0),
            id("F"),
            SatToken::Float(1.0),
            id("F"),
            SatToken::Float(0.0),
        ]);
        record.tokens.push(id("}"));
        record.tokens.push(id("I"));
        record.tokens.push(id("I"));

        self.records.push(record);
        self.header.num_records = self.records.len();
        index
    }

    /// Add an exact NURBS `spline-surface` record and return its index.
    ///
    /// Emits the ACIS 7 `exactsur` form used for a free-form (non-analytic)
    /// surface — a `bs3_surface` with a fit tolerance:
    /// Input knot runs include the complete clamped endpoint multiplicities;
    /// ACIS omits one endpoint repetition on each end of each axis.
    ///
    /// * `rational` — `false` = `nubs` (control points are x y z); `true` =
    ///   `nurbs` (each control point carries a trailing weight).
    /// * `u_knots` / `v_knots` — the distinct knot values paired with their
    ///   multiplicity.
    /// * `control` — the control net in **v-major** order (all `u` for the first
    ///   `v`, then the next `v`, …), `[x, y, z]`; `weights` (rational only) is a
    ///   parallel array with one weight per control point.
    ///
    /// The control-net dimension must satisfy
    /// `num_ctrl_u = Σ(u multiplicities) − (deg_u + 1)` and likewise for `v`, or
    /// the surface is geometrically inconsistent. `u_closed` / `v_closed` select
    /// the `open`/`closed` closure identifier (periodic is not emitted here).
    #[allow(clippy::too_many_arguments)]
    pub fn add_spline_surface(
        &mut self,
        rev_v: bool,
        rational: bool,
        deg_u: i32,
        deg_v: i32,
        u_closed: bool,
        v_closed: bool,
        u_knots: &[(f64, i32)],
        v_knots: &[(f64, i32)],
        control: &[[f64; 3]],
        weights: Option<&[f64]>,
        fit_tol: f64,
    ) -> i32 {
        let index = self.records.len() as i32;
        let mut record = SatRecord::new(index, "spline-surface");
        record.attribute = SatPointer::NULL;
        let id = |s: &str| SatToken::Ident(s.to_string());

        record.tokens.push(SatToken::Pointer(SatPointer::NULL)); // v700 sentinel
        record
            .tokens
            .push(id(if rev_v { "reversed" } else { "forward" }));
        record.tokens.push(id("{"));
        record.tokens.push(id("exactsur"));
        record.tokens.push(SatToken::Enum("full".to_string()));
        record
            .tokens
            .push(id(if rational { "nurbs" } else { "nubs" }));
        record.tokens.push(SatToken::Integer(deg_u as i64));
        record.tokens.push(SatToken::Integer(deg_v as i64));
        if rational {
            record.tokens.push(id("both"));
        }
        record.tokens.push(SatToken::Enum(
            if u_closed { "closed" } else { "open" }.to_string(),
        ));
        record.tokens.push(SatToken::Enum(
            if v_closed { "closed" } else { "open" }.to_string(),
        ));
        record.tokens.push(SatToken::Enum("none".to_string()));
        record.tokens.push(SatToken::Enum("none".to_string()));
        record.tokens.push(SatToken::Integer(u_knots.len() as i64));
        record.tokens.push(SatToken::Integer(v_knots.len() as i64));
        for (position, &(knot, mult)) in u_knots.iter().enumerate() {
            record.tokens.push(SatToken::Float(knot));
            let implicit = i32::from(position == 0 || position + 1 == u_knots.len());
            record
                .tokens
                .push(SatToken::Integer((mult - implicit) as i64));
        }
        for (position, &(knot, mult)) in v_knots.iter().enumerate() {
            record.tokens.push(SatToken::Float(knot));
            let implicit = i32::from(position == 0 || position + 1 == v_knots.len());
            record
                .tokens
                .push(SatToken::Integer((mult - implicit) as i64));
        }
        for (i, p) in control.iter().enumerate() {
            record.tokens.push(SatToken::Float(p[0]));
            record.tokens.push(SatToken::Float(p[1]));
            record.tokens.push(SatToken::Float(p[2]));
            if rational {
                let w = weights.and_then(|w| w.get(i)).copied().unwrap_or(1.0);
                record.tokens.push(SatToken::Float(w));
            }
        }
        record.tokens.push(SatToken::Float(fit_tol));
        // Empty U/V discontinuity lists, then the exact surface's native bounds.
        record.tokens.extend((0..6).map(|_| SatToken::Integer(0)));
        record.tokens.extend((0..4).map(|_| id("I")));
        record.tokens.push(id("}"));
        record.tokens.push(id("I"));
        record.tokens.push(id("I"));
        record.tokens.push(id("I"));
        record.tokens.push(id("I"));

        self.records.push(record);
        self.header.num_records = self.records.len();
        index
    }

    /// Add an ACIS 7 explicit pcurve on an existing analytic or spline surface.
    /// Knot parameters must already match the owning edge. The final pair
    /// are UV offsets, not an active parameter interval.
    #[allow(clippy::too_many_arguments)]
    pub fn add_pcurve(
        &mut self,
        rational: bool,
        degree: i32,
        closed: bool,
        knots: &[(f64, i32)],
        control: &[[f64; 2]],
        weights: Option<&[f64]>,
        fit_tol: f64,
        support_surface: i32,
        offsets: (f64, f64),
    ) -> i32 {
        let support = self
            .record(support_surface as usize)
            .expect("pcurve support surface");
        let id = |value: &str| SatToken::Ident(value.to_string());
        let support_tokens = match support.entity_type.as_str() {
            "spline-surface" => {
                let start = support
                    .tokens
                    .iter()
                    .position(|token| token.as_ident() == Some("{"))
                    .expect("spline support subtype");
                let end = support
                    .tokens
                    .iter()
                    .rposition(|token| token.as_ident() == Some("}"))
                    .expect("spline support subtype end");
                let subtype_index =
                    if support.tokens.get(start + 1).and_then(SatToken::as_ident) == Some("ref") {
                        support.tokens[start + 2]
                            .as_integer()
                            .expect("spline support subtype reference")
                    } else {
                        self.records
                            .iter()
                            .take(support_surface as usize)
                            .map(|record| {
                                record
                                    .tokens
                                    .windows(2)
                                    .filter(|pair| {
                                        pair[0].as_ident() == Some("{")
                                            && pair[1].as_ident() != Some("ref")
                                    })
                                    .count()
                            })
                            .sum::<usize>() as i64
                    };
                let mut tokens = vec![
                    id("spline"),
                    support.tokens[1].clone(),
                    id("{"),
                    id("ref"),
                    SatToken::Integer(subtype_index),
                    id("}"),
                ];
                tokens.extend_from_slice(&support.tokens[end + 1..]);
                tokens
            }
            "plane-surface" | "cone-surface" | "sphere-surface" | "torus-surface" => {
                // An explicit pcurve embeds the surface geometry, without the
                // SURFACE entity's common pointer. Analytic surfaces have no
                // spline subtype to reference; retain their native frame,
                // radii, parameter sense and bounded intervals verbatim.
                let name = support.entity_type.strip_suffix("-surface").unwrap();
                let mut tokens = vec![id(name)];
                tokens.extend_from_slice(&support.tokens[1..]);
                // Kernel-built surfaces gain their parameter sense and
                // interval markers only when the document is completed;
                // the embedded copy needs them now.
                tokens.extend(SatDocument::missing_tail(support).unwrap_or_default());
                tokens
            }
            _ => panic!(
                "unsupported pcurve support surface: {}",
                support.entity_type
            ),
        };
        let index = self.records.len() as i32;
        let mut record = SatRecord::new(index, "pcurve");
        record.attribute = SatPointer::NULL;
        let id = |value: &str| SatToken::Ident(value.to_string());

        record.tokens.push(SatToken::Pointer(SatPointer::NULL));
        record.tokens.push(SatToken::Integer(0));
        record.tokens.push(id("forward"));
        record.tokens.push(id("{"));
        record.tokens.push(id("exppc"));
        record
            .tokens
            .push(id(if rational { "nurbs" } else { "nubs" }));
        record.tokens.push(SatToken::Integer(degree as i64));
        record.tokens.push(SatToken::Enum(
            if closed { "closed" } else { "open" }.to_string(),
        ));
        record.tokens.push(SatToken::Integer(knots.len() as i64));
        for (position, &(knot, multiplicity)) in knots.iter().enumerate() {
            record.tokens.push(SatToken::Float(knot));
            let implicit = i32::from(position == 0 || position + 1 == knots.len());
            record
                .tokens
                .push(SatToken::Integer((multiplicity - implicit) as i64));
        }
        for (position, point) in control.iter().enumerate() {
            record.tokens.push(SatToken::Float(point[0]));
            record.tokens.push(SatToken::Float(point[1]));
            if rational {
                record.tokens.push(SatToken::Float(
                    weights
                        .and_then(|values| values.get(position))
                        .copied()
                        .unwrap_or(1.0),
                ));
            }
        }
        record.tokens.push(SatToken::Float(fit_tol));
        record.tokens.extend(support_tokens);
        record.tokens.push(id("}"));
        record.tokens.push(SatToken::Float(offsets.0));
        record.tokens.push(SatToken::Float(offsets.1));

        self.records.push(record);
        self.header.num_records = self.records.len();
        index
    }

    /// Add a vertex record and return its index.
    pub fn add_vertex(&mut self, edge: SatPointer, point: SatPointer) -> i32 {
        let index = self.records.len() as i32;
        let mut record = SatRecord::new(index, "vertex");
        record.attribute = SatPointer::NULL;
        record.tokens.push(SatToken::Pointer(SatPointer::NULL)); // v700 unknown (always $-1)
        record.tokens.push(SatToken::Pointer(edge));
        record.tokens.push(SatToken::Pointer(point));
        self.records.push(record);
        self.header.num_records = self.records.len();
        index
    }

    /// Add an edge record and return its index.
    ///
    /// The v700 edge format:
    /// `edge $attr -1 $-1 $start_v start_param $end_v end_param $coedge $curve sense @7 unknown`
    pub fn add_edge(
        &mut self,
        start_vertex: SatPointer,
        start_param: f64,
        end_vertex: SatPointer,
        end_param: f64,
        coedge: SatPointer,
        curve: SatPointer,
        sense: Sense,
    ) -> i32 {
        let index = self.records.len() as i32;
        let mut record = SatRecord::new(index, "edge");
        record.attribute = SatPointer::NULL;
        record.tokens.push(SatToken::Pointer(SatPointer::NULL)); // v700 unknown (always $-1)
        record.tokens.push(SatToken::Pointer(start_vertex));
        record.tokens.push(SatToken::Float(start_param));
        record.tokens.push(SatToken::Pointer(end_vertex));
        record.tokens.push(SatToken::Float(end_param));
        record.tokens.push(SatToken::Pointer(coedge));
        record.tokens.push(SatToken::Pointer(curve));
        record
            .tokens
            .push(SatToken::Enum(sense.as_str().to_string()));
        record.tokens.push(SatToken::String("unknown".to_string()));
        self.records.push(record);
        self.header.num_records = self.records.len();
        index
    }

    /// Add a coedge record and return its index.
    pub fn add_coedge(
        &mut self,
        next: SatPointer,
        prev: SatPointer,
        partner: SatPointer,
        edge: SatPointer,
        sense: Sense,
        owner_loop: SatPointer,
    ) -> i32 {
        let index = self.records.len() as i32;
        let mut record = SatRecord::new(index, "coedge");
        record.attribute = SatPointer::NULL;
        record.tokens.push(SatToken::Pointer(SatPointer::NULL)); // v700 unknown (always $-1)
        record.tokens.push(SatToken::Pointer(next));
        record.tokens.push(SatToken::Pointer(prev));
        record.tokens.push(SatToken::Pointer(partner));
        record.tokens.push(SatToken::Pointer(edge));
        record
            .tokens
            .push(SatToken::Enum(sense.as_str().to_string()));
        record.tokens.push(SatToken::Pointer(owner_loop));
        record.tokens.push(SatToken::Pointer(SatPointer::NULL)); // pcurve (always $-1)
        self.records.push(record);
        self.header.num_records = self.records.len();
        index
    }

    /// Add a loop record and return its index.
    pub fn add_loop(
        &mut self,
        next_loop: SatPointer,
        first_coedge: SatPointer,
        face: SatPointer,
    ) -> i32 {
        let index = self.records.len() as i32;
        let mut record = SatRecord::new(index, "loop");
        record.attribute = SatPointer::NULL;
        record.tokens.push(SatToken::Pointer(SatPointer::NULL)); // unknown (always $-1)
        record.tokens.push(SatToken::Pointer(next_loop));
        record.tokens.push(SatToken::Pointer(first_coedge));
        record.tokens.push(SatToken::Pointer(face));
        self.records.push(record);
        self.header.num_records = self.records.len();
        index
    }

    /// Add a face record and return its index.
    pub fn add_face(
        &mut self,
        next_face: SatPointer,
        first_loop: SatPointer,
        shell: SatPointer,
        surface: SatPointer,
        sense: Sense,
        sidedness: Sidedness,
    ) -> i32 {
        let index = self.records.len() as i32;
        let mut record = SatRecord::new(index, "face");
        record.attribute = SatPointer::NULL;
        record.tokens.push(SatToken::Pointer(SatPointer::NULL)); // unknown (always $-1)
        record.tokens.push(SatToken::Pointer(next_face));
        record.tokens.push(SatToken::Pointer(first_loop));
        record.tokens.push(SatToken::Pointer(shell));
        record.tokens.push(SatToken::Pointer(SatPointer::NULL)); // subshell
        record.tokens.push(SatToken::Pointer(surface));
        record
            .tokens
            .push(SatToken::Enum(sense.as_str().to_string()));
        record
            .tokens
            .push(SatToken::Enum(sidedness.as_str().to_string()));
        self.records.push(record);
        self.header.num_records = self.records.len();
        index
    }

    /// Add a shell record and return its index.
    pub fn add_shell(&mut self, first_face: SatPointer, lump: SatPointer) -> i32 {
        let index = self.records.len() as i32;
        let mut record = SatRecord::new(index, "shell");
        record.attribute = SatPointer::NULL;
        record.tokens.push(SatToken::Pointer(SatPointer::NULL)); // pattern
        record.tokens.push(SatToken::Pointer(SatPointer::NULL)); // next_shell
        record.tokens.push(SatToken::Pointer(SatPointer::NULL)); // subshell
        record.tokens.push(SatToken::Pointer(first_face));
        record.tokens.push(SatToken::Pointer(SatPointer::NULL)); // wire
        record.tokens.push(SatToken::Pointer(lump));
        self.records.push(record);
        self.header.num_records = self.records.len();
        index
    }

    /// Add a lump record and return its index.
    pub fn add_lump(&mut self, shell: SatPointer, body: SatPointer) -> i32 {
        let index = self.records.len() as i32;
        let mut record = SatRecord::new(index, "lump");
        record.attribute = SatPointer::NULL;
        record.tokens.push(SatToken::Pointer(SatPointer::NULL)); // pattern
        record.tokens.push(SatToken::Pointer(SatPointer::NULL)); // next_lump
        record.tokens.push(SatToken::Pointer(shell));
        record.tokens.push(SatToken::Pointer(body));
        self.records.push(record);
        self.header.num_records = self.records.len();
        index
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_write_empty_body() {
        let doc = SatDocument::new_body();
        let output = doc.to_sat_string();

        assert!(output.contains("700"));
        assert!(output.contains("body"));
        assert!(output.contains("End-of-ACIS-data"));
    }

    #[test]
    fn test_roundtrip_simple() {
        let original = "700 0 1 0\n\
            @8 acadrust @8 ACIS 7.0 @24 Thu Jan 01 00:00:00 2023\n\
            1e-06 9.9999999999999995e-07\n\
            -0 asmheader $-1 -1 @12 700 7 0 0 @5 ACIS @3 7.0 @24 Thu Jan 01 00:00:00 2023 #\n\
            -1 body $-1 $-1 $-1 $-1 #\n\
            End-of-ACIS-data\n";

        let doc = SatDocument::parse(original).unwrap();
        let output = doc.to_sat_string();

        // Parse the output again
        let doc2 = SatDocument::parse(&output).unwrap();
        assert_eq!(doc.records.len(), doc2.records.len());
        assert_eq!(doc.header.version, doc2.header.version);

        for (r1, r2) in doc.records.iter().zip(doc2.records.iter()) {
            assert_eq!(r1.entity_type, r2.entity_type);
            assert_eq!(r1.index, r2.index);
        }
    }

    #[test]
    fn test_roundtrip_v400() {
        let original = "400 0 1 0\n\
            8 acadrust 8 ACIS 4.0 24 Thu Jan 01 00:00:00 2023\n\
            1e-06 9.9999999999999995e-07\n\
            body $-1 $1 $-1 $-1 #\n\
            lump $-1 $-1 $2 $0 #\n\
            shell $-1 $-1 $-1 $3 $-1 $1 #\n\
            End-of-ACIS-data\n";

        let doc = SatDocument::parse(original).unwrap();
        assert_eq!(doc.header.version, SatVersion::new(4, 0, 0));

        let output = doc.to_sat_string();
        let doc2 = SatDocument::parse(&output).unwrap();
        assert_eq!(doc.records.len(), doc2.records.len());
    }

    #[test]
    fn test_write_with_geometry() {
        let mut doc = SatDocument::new_body();

        // Add a plane surface
        let plane_idx = doc.add_plane_surface([0.0, 0.0, 5.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]);

        let output = doc.to_sat_string();
        assert!(output.contains("plane-surface"));

        // Parse back and verify
        let doc2 = SatDocument::parse(&output).unwrap();
        let planes = doc2.records_of_type("plane-surface");
        assert_eq!(planes.len(), 1);
        let plane = SatPlaneSurface::from_record(planes[0]).unwrap();
        assert_eq!(plane.root_point(), (0.0, 0.0, 5.0));
        assert_eq!(plane.normal(), (0.0, 0.0, 1.0));

        assert!(plane_idx >= 0);
    }

    #[test]
    fn test_build_topology() {
        let mut doc = SatDocument::new_body();
        let body_idx = 0; // body is at index 0

        // Build minimal topology
        let point_idx = doc.add_point(1.0, 2.0, 3.0);
        let vertex_idx = doc.add_vertex(SatPointer::NULL, SatPointer::new(point_idx));
        let surface_idx = doc.add_plane_surface([0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]);

        let output = doc.to_sat_string();
        assert!(output.contains("point"));
        assert!(output.contains("vertex"));
        assert!(output.contains("plane-surface"));

        // Verify indices
        assert!(vertex_idx > point_idx);
        assert!(surface_idx > vertex_idx);
        assert!(body_idx >= 0);
    }

    #[test]
    fn test_float_formatting() {
        assert_eq!(format_float(0.0), "0");
        assert_eq!(format_float(1.0), "1");
        assert_eq!(format_float(-5.0), "-5");
        assert_eq!(format_float(1e-06), "1e-006");
    }

    #[test]
    fn test_add_sphere_surface() {
        let mut doc = SatDocument::new_body();
        let idx = doc.add_sphere_surface([0.0, 0.0, 0.0], 5.0, [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]);

        let output = doc.to_sat_string();
        assert!(output.contains("sphere-surface"));

        let doc2 = SatDocument::parse(&output).unwrap();
        let spheres = doc2.records_of_type("sphere-surface");
        assert_eq!(spheres.len(), 1);
        let sphere = SatSphereSurface::from_record(spheres[0]).unwrap();
        assert_eq!(sphere.center(), (0.0, 0.0, 0.0));
        assert_eq!(sphere.radius(), 5.0);

        assert!(idx >= 0);
    }

    #[test]
    fn test_cone_surface_accessor_positions() {
        let mut doc = SatDocument::new_body();
        let _idx = doc.add_cone_surface(
            [1.0, 2.0, 3.0], // center
            [0.0, 0.0, 1.0], // axis
            [5.0, 0.0, 0.0], // major_axis (radius = 5)
            1.0,             // ratio
            1.0,             // cos_half_angle (cylinder)
            0.0,             // sin_half_angle (cylinder)
        );

        // Roundtrip through SAT text
        let output = doc.to_sat_string();
        let doc2 = SatDocument::parse(&output).unwrap();
        let cones = doc2.records_of_type("cone-surface");
        assert_eq!(cones.len(), 1);
        let cone = SatConeSurface::from_record(cones[0]).unwrap();
        assert_eq!(cone.center(), (1.0, 2.0, 3.0));
        assert_eq!(cone.axis(), (0.0, 0.0, 1.0));
        assert_eq!(cone.major_axis(), (5.0, 0.0, 0.0));
        assert_eq!(cone.ratio(), 1.0);
        assert!(
            (cone.sin_half_angle() - 0.0).abs() < 1e-10,
            "sin should be 0.0 for cylinder, got {}",
            cone.sin_half_angle()
        );
        assert!(
            (cone.cos_half_angle() - 1.0).abs() < 1e-10,
            "cos should be 1.0 for cylinder, got {}",
            cone.cos_half_angle()
        );
        assert!(
            (cone.radius() - 5.0).abs() < 1e-10,
            "radius should be 5.0, got {}",
            cone.radius()
        );
    }

    #[test]
    fn test_cone_surface_accessor_with_cone_angles() {
        let mut doc = SatDocument::new_body();
        let sin_val: f64 = 30.0_f64.to_radians().sin(); // ~0.5
        let cos_val: f64 = 30.0_f64.to_radians().cos(); // ~0.866
        let _idx = doc.add_cone_surface(
            [0.0, 0.0, 0.0],
            [0.0, 0.0, 1.0],
            [3.0, 0.0, 0.0],
            1.0,
            cos_val,
            sin_val,
        );

        let output = doc.to_sat_string();
        let doc2 = SatDocument::parse(&output).unwrap();
        let cones = doc2.records_of_type("cone-surface");
        let cone = SatConeSurface::from_record(cones[0]).unwrap();
        assert!(
            (cone.sin_half_angle() - sin_val).abs() < 1e-10,
            "sin mismatch: {} vs {}",
            cone.sin_half_angle(),
            sin_val
        );
        assert!(
            (cone.cos_half_angle() - cos_val).abs() < 1e-10,
            "cos mismatch: {} vs {}",
            cone.cos_half_angle(),
            cos_val
        );
    }

    #[test]
    fn spline_surface_emits_valid_sat() {
        // Bilinear (degree 1×1) exact spline surface — a flat quad expressed as
        // a NURBS. Knot vectors [0,0,1,1] each → 2×2 control net.
        let mut doc = SatDocument::new_body();
        let u_knots = [(0.0, 2), (1.0, 2)];
        let v_knots = [(0.0, 2), (1.0, 2)];
        let control = [
            [0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [0.0, 1.0, 0.0],
            [1.0, 1.0, 0.0],
        ];
        let idx = doc.add_spline_surface(
            false, false, 1, 1, false, false, &u_knots, &v_knots, &control, None, 1e-6,
        );
        assert!(idx > 0);

        // Round-trip through the SAT text parser and validate.
        let output = doc.to_sat_string();
        let re = SatDocument::parse(&output).expect("emitted spline-surface must re-parse");
        let sp = re
            .records_of_type("spline-surface")
            .into_iter()
            .next()
            .expect("spline-surface present after re-parse");
        // deg_u, deg_v tokens.
        assert!(matches!(sp.tokens.get(6), Some(SatToken::Integer(1))));
        assert!(matches!(sp.tokens.get(7), Some(SatToken::Integer(1))));
        assert!(
            re.validate().is_empty(),
            "spline-surface failed validation: {:?}",
            re.validate()
        );
    }
}