cadkit-dgn 0.5.3

Clean-room DGN V7 and V8 reader and seed-based DGN V8 writer.
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
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
//! Seed-based DGN V8 export; unsupported data returns an error.

mod container;
mod encode;
mod named;
mod oleps;
mod polyline;
mod raster;
mod raster_builtin;
mod raster_template;
mod seed_prepare;
mod strip;
mod tables;
mod text;

pub use seed_prepare::{DimensionPolicy, SeedPrepareOptions, V8Seed};
pub use strip::{StripSeedOptions, StripSeedReport, StrippedSeed, strip_seed_v8};

#[cfg(test)]
use crate::native::v8::RawElement;
use crate::{
    le,
    native::v8::{self, AuxRecord, ModelHeader, PageHeader, V8Model},
};
use cadkit_core::{
    Attribute, Document, Entity, EntityKind, Error, GroupKind, LimitKind, Limits, Point3,
    ReadOptions, Result, Value, Vec3,
};
use encode::*;
use flate2::{Compression, write::ZlibEncoder};
use std::{
    collections::{BTreeMap, BTreeSet},
    io::Write,
};
use tables::Tables;

/// Options for DGN V8 export; each call writes a single model.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(default)]
#[non_exhaustive]
pub struct WriteOptions {
    /// Resource limits for input, output, elements, and coordinates.
    pub limits: Limits,
    /// 8-bit code page for text and tags; `None` writes UTF-16LE.
    pub codepage: Option<String>,
    /// Timestamp for new records in milliseconds since the Unix epoch; defaults to zero.
    pub timestamp_ms: f64,
    /// Explicitly allow clearing graphic and control records from a non-empty seed model.
    pub clear_seed_model: bool,
    /// Maximum distance of polygon ring points from the exterior plane, in source
    /// drawing units. Defaults to 0.01 (1 cm for metres), allowing coordinate rounding.
    pub planarity_tolerance: f64,
    /// Preserve unchanged raster attachments from the same seed, including their
    /// opaque control and auxiliary records. Edited attachments are rejected; images
    /// without an id are new attachments cloned from a seed attachment, or from the
    /// built-in group when the seed has none (see [`seed_has_raster_template`]), whatever
    /// this option says.
    pub preserve_seed_rasters: bool,
    /// Keep the seed model's control records (coordinate system, model settings and similar)
    /// with their auxiliary data, byte for byte, except raster control records (kept only
    /// with their unchanged attachment) and records whose dependency linkages name a seed
    /// graphic as a root. Undecoded record bodies are not searched for ids (FORMAT_NOTES,
    /// "Seed stripping").
    pub preserve_seed_controls: bool,
}
impl Default for WriteOptions {
    fn default() -> Self {
        Self {
            limits: Limits::default(),
            codepage: None,
            timestamp_ms: 0.0,
            clear_seed_model: false,
            planarity_tolerance: 0.01,
            preserve_seed_rasters: true,
            preserve_seed_controls: true,
        }
    }
}

impl WriteOptions {
    /// Default export options: UTF-16LE text, zero timestamp, seed rasters and controls kept.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets resource limits for reading the seed and encoding output records.
    #[must_use]
    pub fn with_limits(mut self, limits: Limits) -> Self {
        self.limits = limits;
        self
    }

    /// Sets the 8-bit Windows codepage label (`"windows-1250"`..=`"windows-1258"`), or
    /// `None` for UTF-16LE.
    #[must_use]
    pub fn with_codepage(mut self, codepage: Option<impl Into<String>>) -> Self {
        self.codepage = codepage.map(Into::into);
        self
    }

    /// Sets the modification timestamp in milliseconds since the Unix epoch.
    #[must_use]
    pub fn with_timestamp_ms(mut self, timestamp_ms: f64) -> Self {
        self.timestamp_ms = timestamp_ms;
        self
    }

    /// Sets whether non-empty seed models may have their graphic and control pages cleared.
    #[must_use]
    pub fn with_clear_seed_model(mut self, clear: bool) -> Self {
        self.clear_seed_model = clear;
        self
    }

    /// Sets the planarity tolerance (in drawing units) for polygons with interior holes.
    #[must_use]
    pub fn with_planarity_tolerance(mut self, tolerance: f64) -> Self {
        self.planarity_tolerance = tolerance;
        self
    }

    /// Sets whether unchanged raster attachments from the seed are preserved.
    #[must_use]
    pub fn with_preserve_seed_rasters(mut self, preserve: bool) -> Self {
        self.preserve_seed_rasters = preserve;
        self
    }

    /// Sets whether non-graphic seed control records are preserved byte for byte.
    #[must_use]
    pub fn with_preserve_seed_controls(mut self, preserve: bool) -> Self {
        self.preserve_seed_controls = preserve;
        self
    }
}

/// Repacks a DGN V8 file with a valid CFB directory without altering stream contents.
pub fn repack_v8(seed: &[u8], options: &ReadOptions) -> Result<Vec<u8>> {
    let native = v8::read(seed, options)?;
    if native.models.is_empty() {
        return Err(Error::invalid(0, "DGN seed has no model"));
    }
    container::rewrite(seed, &BTreeMap::new(), options)
}

/// Whether `seed` holds its own raster attachment template: its single model holds at least
/// one complete raster attachment (the records 92, 93, 93, 90, 91 x 5 in the control pages,
/// the frame 94 they point at and its XAttribute 170) that [`write_v8`] clones for every
/// [`EntityKind::Image`] without an id. Without one, `write_v8` clones a built-in group
/// (bitonal display, 200 DPI unless `dgn.raster_dpi` is given) instead. Seeds with several
/// models return `false`, as `write_v8` accepts single-model seeds only. `Err` when the
/// seed is not a readable DGN V8 file.
pub fn seed_has_raster_template(seed: &[u8], options: &ReadOptions) -> Result<bool> {
    let native = v8::read(seed, options)?;
    Ok(match native.models.as_slice() {
        [model] => raster_template::Template::capture(model).is_some(),
        _ => false,
    })
}

/// Format version of new graphic pages: the seed's first page version, else 3.
fn graphic_page_version(model: &V8Model) -> u32 {
    model
        .graphic_pages
        .first()
        .map(|p| p.header.format_version)
        .filter(|v| matches!(v, 2 | 3))
        .unwrap_or(3)
}

fn compressed(bytes: &[u8]) -> Result<Vec<u8>> {
    let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
    encoder.write_all(bytes)?;
    Ok(encoder.finish()?)
}
/// A graphic or control page: the 16-byte header `{record count, version, 0, 0}`, then the
/// zlib-compressed records. A page without records is the header alone, as every empty page
/// of the observed files is (private corpus: 644 graphic and 1,087 dictionary pages).
fn page(records: &[Vec<u8>], version: u32, _number: u32) -> Result<Vec<u8>> {
    let mut out = vec![0; 16];
    u32_at(
        &mut out,
        0,
        u32::try_from(records.len())
            .map_err(|_| Error::limit(LimitKind::Capacity, "DGN page records".into()))?,
    )?;
    u32_at(&mut out, 4, version)?;
    if records.is_empty() {
        return Ok(out);
    }
    let mut data = vec![];
    for b in records {
        data.extend(0u32.to_le_bytes());
        data.extend_from_slice(b);
    }
    out.extend(compressed(&data)?);
    Ok(out)
}

fn validate_doc_and_options(doc: &Document, options: &WriteOptions) -> Result<()> {
    cadkit_core::export::validate_limits(doc, &options.limits)?;
    if doc
        .units
        .meters_per_unit
        .is_some_and(|v| !v.is_finite() || v <= 0.0)
    {
        return Err(Error::invalid(0, "invalid source unit scale"));
    }
    if !options.timestamp_ms.is_finite() {
        return Err(Error::invalid(0, "DGN timestamp must be finite"));
    }
    if !options.planarity_tolerance.is_finite() || options.planarity_tolerance <= 0.0 {
        return Err(Error::invalid(
            0,
            "DGN planarity tolerance must be finite and positive",
        ));
    }
    if doc.models.len() != 1 {
        return Err(Error::Unsupported(
            "DGN writer requires exactly one source model".into(),
        ));
    }
    Ok(())
}

/// Writes the single design model of a neutral document into a matching DGN V8 seed.
/// Source units and 2D/3D dimension must match the seed's master units and dimension; Z coordinates and attributes are never silently dropped.
pub fn write_v8(doc: &Document, seed: &[u8], options: &WriteOptions) -> Result<Vec<u8>> {
    validate_doc_and_options(doc, options)?;
    let read = {
        let mut new_options = ReadOptions::default()
            .with_limits(options.limits)
            .with_keep_raw(true);
        new_options.fallback_codepage = options.codepage.clone();
        new_options
    };
    let parsed_seed = V8Seed::parse(seed, &read)?;
    write_v8_with_seed(doc, &parsed_seed, options)
}

/// Writes the single design model of `doc` into a pre-parsed [`V8Seed`], avoiding repeated
/// CFB and zlib decompression of the seed when exporting multiple documents.
pub fn write_v8_with_seed(
    doc: &Document,
    seed: &V8Seed,
    options: &WriteOptions,
) -> Result<Vec<u8>> {
    validate_doc_and_options(doc, options)?;
    if seed.bytes.len() as u64 > options.limits.max_input_bytes {
        return Err(Error::limit(
            LimitKind::InputBytes,
            "DGN seed input bytes".into(),
        ));
    }
    let read = {
        let mut new_options = ReadOptions::default()
            .with_limits(options.limits)
            .with_keep_raw(true);
        new_options.fallback_codepage = options.codepage.clone();
        new_options
    };
    let native = &seed.native;
    let model = seed.model()?;
    let header = seed
        .model_header()
        .ok_or_else(|| Error::invalid(0, "missing seed model header"))?;
    let source = doc
        .models
        .first()
        .ok_or_else(|| Error::invalid(0, "missing source model"))?;
    if source.kind != cadkit_core::ModelKind::Model {
        return Err(Error::Unsupported(
            "DGN writer accepts design models only".into(),
        ));
    }
    if source.is_3d != header.is_3d {
        return Err(Error::invalid(0, "source and seed model dimensions differ"));
    }
    if let (Some(source), Some(target)) = (doc.units.meters_per_unit(), header.master.meters())
        && (!source.is_finite() || (source - target).abs() > target.abs() * 1e-12)
    {
        return Err(Error::invalid(
            0,
            "source and seed units differ; convert coordinates explicitly",
        ));
    }
    if seed.nonempty && !options.clear_seed_model {
        return Err(Error::Unsupported(
            "nonempty seed requires clear_seed_model=true".into(),
        ));
    }
    let max_id = seed.max_id;
    let mut effective_options = options.clone();
    if effective_options.timestamp_ms == 0.0 {
        effective_options.timestamp_ms = seed.seed_timestamp_ms;
    }
    let options = &effective_options;
    let rasters = raster::Preserved::prepare(doc, &seed.bytes, model, &read, options)?;
    let mut tables = Tables::new(&native.named_pages, max_id, &read)?;
    tables.observe_model_fonts(
        model
            .graphic_pages
            .iter()
            .chain(&model.control_pages)
            .flat_map(|p| &p.elements),
        &read,
    );
    let mut state = State {
        tables,
        model: header,
        options,
        wide_tags: wide_integer_tags(&source.entities),
        layers: &doc.layers,
        rasters: &rasters,
        records: vec![],
        tags: vec![],
        new_controls: vec![],
        new_xattributes: vec![],
        work: 0,
        vertices: 0,
        bytes: rasters.bytes,
    };
    for layer in &doc.layers {
        state
            .tables
            .level(Some(&layer.name), options.timestamp_ms)?;
    }
    for entity in &source.entities {
        state.entity(entity, 0, false)?;
    }
    state.records.append(&mut state.tags);
    let new_controls = std::mem::take(&mut state.new_controls);
    let new_xattributes = std::mem::take(&mut state.new_xattributes);
    let records = state.records;
    let named = state.tables.finish(options.timestamp_ms)?;
    let max_id = records
        .iter()
        .chain(named.iter().map(|r| &r.bytes))
        .filter_map(|r| le::u64_at(r, 16))
        .max()
        .unwrap_or(max_id)
        .max(max_id);
    let mut replacements = BTreeMap::new();
    for stream in &native.streams {
        let model_stream = stream
            .path
            .starts_with(&format!("Dgn-Md/{}/Dgn^G/", model.storage))
            || stream
                .path
                .starts_with(&format!("Dgn-Md/{}/Dgn^C/", model.storage))
            || stream
                .path
                .starts_with(&format!("Dgn-Md/{}/Dgn^GA/", model.storage))
            || stream
                .path
                .starts_with(&format!("Dgn-Md/{}/Dgn^CA/", model.storage));
        // Dictionary pages are kept and only rewritten where they change (`named`).
        if model_stream {
            replacements.insert(stream.path.clone(), None);
        }
    }
    let version = graphic_page_version(model);
    let record_pages = put_pages(
        &mut replacements,
        &format!("Dgn-Md/{}/Dgn^G", model.storage),
        &records,
        version,
        options.limits.max_decompressed_bytes,
    )?;
    let control_pages = rasters.write_auxiliary(&mut replacements, &new_controls)?;
    if let Some(template) = rasters
        .template
        .as_ref()
        .filter(|_| !new_xattributes.is_empty())
    {
        // An XAttribute sits in the auxiliary page numbered like the graphic page of its
        // element, as in every observed attachment.
        let mut pages: BTreeMap<u32, Vec<AuxRecord>> = BTreeMap::new();
        for (index, record) in new_xattributes {
            let number = record_pages
                .get(index)
                .copied()
                .ok_or_else(|| Error::invalid(0, "raster frame record outside the pages"))?;
            pages.entry(number).or_default().push(record);
        }
        let mut last = 0;
        for (number, records) in &pages {
            let header = PageHeader {
                record_count: 0,
                format_version: template.aux_version,
                page_number: 0,
                population: 0,
            };
            replacements.insert(
                format!("Dgn-Md/{}/Dgn^GA/${number}", model.storage),
                Some(raster::aux_page(records, header)?),
            );
            last = *number;
        }
        // `^AH` is at least the highest page number in every observed file; the next free
        // number is the most common value.
        replacements.insert(
            format!("Dgn-Md/{}/Dgn^GA/^AH", model.storage),
            Some(last.saturating_add(1).to_le_bytes().to_vec()),
        );
    }
    if rasters.keep_control_counter {
        // Every control auxiliary page is retained as is; so is its page counter.
        replacements.remove(&format!("Dgn-Md/{}/Dgn^CA/^AH", model.storage));
    }
    named::write(
        &mut replacements,
        &native.named_pages,
        &native.named_aux,
        &named,
        options.limits.max_decompressed_bytes,
    )?;
    let mut mh = header.raw.clone();
    let mut low = [i64::MAX; 3];
    let mut high = [i64::MIN; 3];
    for b in &records {
        let [record_low, record_high] = absolute_range(b)?;
        for ((lo, hi), (record_lo, record_hi)) in low
            .iter_mut()
            .zip(high.iter_mut())
            .zip(record_low.into_iter().zip(record_high))
        {
            *lo = (*lo).min(record_lo);
            *hi = (*hi).max(record_hi);
        }
    }
    if records.is_empty() {
        low = [0; 3];
        high = [0; 3];
    }
    for (i, n) in low.into_iter().chain(high).enumerate() {
        put(&mut mh, 0x90 + i * 8, &n.to_le_bytes())?;
    }
    let mut full_header = seed.mh_prefix.clone();
    // The first prefix dword equals the number of graphic and control pages that hold
    // records in 552 of 567 private files and all 3 public V8 files; the other 15 lie
    // between that number and the page count (FORMAT_NOTES, "Model header"). The other
    // prefix bytes keep the seed's values.
    if full_header.len() >= 4 {
        let graphic_pages = if records.is_empty() {
            0
        } else {
            record_pages.last().copied().unwrap_or(0)
        };
        u32_at(
            &mut full_header,
            0,
            graphic_pages.saturating_add(control_pages),
        )?;
    }
    full_header.extend(mh);
    replacements.insert(seed.mh_path.clone(), Some(compressed(&full_header)?));
    let mut data = seed.header_data.clone();
    u64_at(&mut data, 0x128, max_id)?;
    // Keep the seed header's timestamp and revision fields until their layout is verified across more samples.
    let mut h = seed.header_prefix.to_vec();
    h.extend(compressed(&data)?);
    replacements.insert("Dgn~H".into(), Some(h));
    container::rewrite(&seed.bytes, &replacements, &read)
}

#[cfg(test)]
mod tests;

/// Writes graphic `records` to pages `{prefix}/$1`, `$2`, ... of at most 256 KiB and returns
/// the page number of every record. Dictionary pages keep the seed's layout instead (`named`).
fn put_pages(
    replacements: &mut BTreeMap<String, Option<Vec<u8>>>,
    prefix: &str,
    records: &[Vec<u8>],
    version: u32,
    max: u64,
) -> Result<Vec<u32>> {
    let total = records
        .iter()
        .try_fold(0u64, |sum, r| sum.checked_add(r.len() as u64 + 4))
        .ok_or_else(|| Error::limit(LimitKind::Output, "DGN output records".into()))?;
    if total > max {
        return Err(Error::limit(LimitKind::Output, "DGN output records".into()));
    }
    let mut first = 0;
    let mut bytes = 0usize;
    let mut number = 1u32;
    let mut numbers = Vec::with_capacity(records.len());
    for (i, r) in records.iter().enumerate() {
        if bytes > 0 && bytes.saturating_add(r.len() + 4) > 256 * 1024 {
            replacements.insert(
                format!("{prefix}/${number}"),
                Some(page(records.get(first..i).unwrap_or(&[]), version, number)?),
            );
            first = i;
            bytes = 0;
            number = number
                .checked_add(1)
                .ok_or_else(|| Error::limit(LimitKind::Capacity, "DGN page count".into()))?;
        }
        bytes = bytes.saturating_add(r.len() + 4);
        numbers.push(number);
    }
    replacements.insert(
        format!("{prefix}/${number}"),
        Some(page(records.get(first..).unwrap_or(&[]), version, number)?),
    );
    Ok(numbers)
}

/// An absent tag set is distinct from every explicitly named tag set.
fn tag_key(a: &Attribute) -> (Option<String>, String) {
    (a.set.clone(), a.tag.clone())
}

/// Tags holding an integer outside the signed 32-bit range of DGN integer tags. A tag
/// definition has one value type, so every value of such a tag is written as a double.
fn wide_integer_tags(entities: &[Entity]) -> BTreeSet<(Option<String>, String)> {
    let mut wide = BTreeSet::new();
    let mut todo: Vec<&Entity> = entities.iter().collect();
    while let Some(e) = todo.pop() {
        for a in &e.attributes {
            if let Value::Int(n) = a.value
                && i32::try_from(n).is_err()
            {
                wide.insert(tag_key(a));
            }
        }
        if let EntityKind::Group { children, .. } = &e.kind {
            todo.extend(children);
        }
    }
    wide
}

/// An integer as a double tag value, refused where the double would not hold it exactly.
fn exact_f64(n: i64) -> Result<f64> {
    const EXACT: u64 = 1 << f64::MANTISSA_DIGITS;
    if n.unsigned_abs() > EXACT {
        return Err(Error::invalid(
            0,
            "DGN integer tag exceeds the exact double range",
        ));
    }
    Ok(n as f64)
}

struct State<'a> {
    tables: Tables,
    model: &'a ModelHeader,
    options: &'a WriteOptions,
    /// Tags written as doubles; see [`wide_integer_tags`].
    wide_tags: BTreeSet<(Option<String>, String)>,
    layers: &'a [cadkit_core::Layer],
    rasters: &'a raster::Preserved,
    records: Vec<Vec<u8>>,
    tags: Vec<Vec<u8>>,
    /// Control records of new raster attachments, in stored order.
    new_controls: Vec<Vec<u8>>,
    /// XAttributes of new raster frames with the index of the frame in `records`.
    new_xattributes: Vec<(usize, AuxRecord)>,
    work: u64,
    vertices: u64,
    bytes: u64,
}
impl State<'_> {
    #[allow(clippy::too_many_arguments)]
    fn header(
        &self,
        kind: u32,
        size: usize,
        id: u64,
        level: u32,
        time: f64,
        entity: &Entity,
        three: bool,
    ) -> Result<Vec<u8>> {
        let weight = self.lineweight(entity)?;
        let mut b = encode::header(kind, size, id, level, time, entity, three, weight)?;
        if !entity.props.contains_key("dgn.color_index") {
            use cadkit_core::Color;
            let layer = self
                .layers
                .iter()
                .find(|l| Some(l.name.as_str()) == entity.layer.as_deref());
            // A ByLayer entity takes the layer's palette index first, as it takes the layer's
            // `dgn.weight`: a layer read from a 240-byte level entry carries the level's
            // color index, which then survives a seed palette that repeats or lacks its RGB.
            let layer_index = match layer.and_then(|l| l.props.get("dgn.color_index")) {
                Some(Value::Int(n)) => u8::try_from(*n).ok(),
                _ => None,
            };
            let color = match (entity.color, layer_index) {
                (Color::ByLayer, Some(index)) => {
                    u32_at(&mut b, 0x34, u32::from(index))?;
                    Color::ByLayer
                }
                (Color::ByLayer, None) => layer.map_or(Color::ByLayer, |l| l.color),
                (color, _) => color,
            };
            let rgb = match color {
                Color::Aci { index } => {
                    let &(r, g, b) = cadkit_core::aci::TABLE
                        .get(usize::from(index))
                        .ok_or_else(|| Error::invalid(0, "ACI index"))?;
                    Some([r, g, b])
                }
                Color::Rgb { r, g, b } => Some([r, g, b]),
                Color::ByLayer => None,
                Color::ByBlock => {
                    return Err(Error::Unsupported(
                        "resolve ByBlock color before DGN export".into(),
                    ));
                }
            };
            if let Some(rgb) = rgb {
                let index =
                    crate::palette::exact_index(&self.tables.palette, rgb).ok_or_else(|| {
                        Error::Unsupported(
                        "RGB color is absent from seed palette; provide dgn.color_index explicitly"
                            .into(),
                    )
                    })?;
                u32_at(&mut b, 0x34, u32::from(index))?;
            }
        }
        if entity.linetype.as_deref().is_some_and(|s| {
            !s.eq_ignore_ascii_case("continuous") && !s.eq_ignore_ascii_case("bylayer")
        }) && !entity.props.contains_key("dgn.style")
        {
            return Err(Error::Unsupported(
                "custom linetype requires seed dgn.style index".into(),
            ));
        }
        Ok(b)
    }

    fn lineweight(&self, entity: &Entity) -> Result<u32> {
        // `element`: an element may hold `BY_LEVEL` as read; a level cannot take its weight
        // from itself.
        fn native(props: &cadkit_core::Props, element: bool) -> Result<Option<u32>> {
            match props.get("dgn.weight") {
                Some(Value::Int(n)) => {
                    let weight = u32::try_from(*n)
                        .map_err(|_| Error::invalid(0, "DGN weight must be a nonnegative index"))?;
                    if weight > 31 && !(element && weight == BY_LEVEL) {
                        return Err(Error::Unsupported("DGN lineweight indexes above 31".into()));
                    }
                    Ok(Some(weight))
                }
                Some(_) => Err(Error::invalid(0, "DGN weight must be an integer index")),
                None => Ok(None),
            }
        }
        if let Some(weight) = native(&entity.props, true)? {
            return Ok(weight);
        }
        let weight = if entity.lineweight == cadkit_core::Lineweight::ByLayer {
            match self
                .layers
                .iter()
                .find(|layer| Some(layer.name.as_str()) == entity.layer.as_deref())
            {
                Some(layer) => {
                    if let Some(weight) = native(&layer.props, false)? {
                        return Ok(weight);
                    }
                    layer.lineweight
                }
                None => cadkit_core::Lineweight::Default,
            }
        } else {
            entity.lineweight
        };
        match weight {
            cadkit_core::Lineweight::Millimeters(_) => Err(Error::Unsupported(
                "DGN lineweight needs an explicit entity/layer dgn.weight index; millimeter mapping is display-dependent".into(),
            )),
            cadkit_core::Lineweight::ByBlock => Err(Error::Unsupported(
                "resolve ByBlock lineweight before DGN export".into(),
            )),
            cadkit_core::Lineweight::Default | cadkit_core::Lineweight::ByLayer => Ok(0),
        }
    }

    fn add(&mut self, b: Vec<u8>, tag: bool) -> Result<()> {
        self.bytes = self.bytes.saturating_add(b.len() as u64);
        let new_rasters = self
            .new_controls
            .len()
            .saturating_add(self.new_xattributes.len()) as u64;
        if self.bytes > self.options.limits.max_decompressed_bytes
            || (self.records.len().saturating_add(self.tags.len()) as u64)
                .saturating_add(self.rasters.objects)
                .saturating_add(new_rasters)
                >= self.options.limits.max_objects
        {
            return Err(Error::limit(
                LimitKind::Objects,
                "DGN output record budget".into(),
            ));
        }
        if tag {
            self.tags.push(b);
        } else {
            self.records.push(b);
        }
        Ok(())
    }
    fn entity(&mut self, e: &Entity, depth: u32, component: bool) -> Result<()> {
        if depth >= self.options.limits.max_depth || self.work >= self.options.limits.max_objects {
            return Err(Error::limit(
                LimitKind::Objects,
                "DGN output depth/objects".into(),
            ));
        }
        self.work += 1;
        let level = self
            .tables
            .level(e.layer.as_deref(), self.options.timestamp_ms)?;
        if matches!(e.kind, EntityKind::Image { .. }) {
            if e.id.is_none() {
                return self.new_raster(e, level, component);
            }
            let (id, record) = self.rasters.frame(e, component)?;
            self.add(record, false)?;
            return self.attributes(e, id, level);
        }
        if matches!(&e.kind, EntityKind::Unknown { type_name } if type_name == "dgn.type_37") {
            if e.attributes.len() != 1 {
                return Err(Error::invalid(
                    0,
                    "standalone DGN tag requires exactly one attribute",
                ));
            }
            return self.write_attributes(e, None, level);
        }
        let id = self.tables.id()?;
        let three = self.model.is_3d;
        let psize = if three { 24 } else { 16 };
        let flags = if component { 0x4000_0000 } else { 0 };
        let mut links = vec![];
        let mut b = match &e.kind {
            EntityKind::Point { position } => {
                let p = coordinate(*position, self.model)?;
                let mut b = self.header(
                    3 | flags,
                    0x68 + psize * 2,
                    id,
                    level,
                    self.options.timestamp_ms,
                    e,
                    three,
                )?;
                point(&mut b, 0x68, p, three)?;
                point(&mut b, 0x68 + psize, p, three)?;
                range(&mut b, &[p, p])?;
                b
            }
            EntityKind::Line { start, end } => {
                let p = coordinate(*start, self.model)?;
                let q = coordinate(*end, self.model)?;
                let mut b = self.header(
                    3 | flags,
                    0x68 + psize * 2,
                    id,
                    level,
                    self.options.timestamp_ms,
                    e,
                    three,
                )?;
                point(&mut b, 0x68, p, three)?;
                point(&mut b, 0x68 + psize, q, three)?;
                range(&mut b, &[p, q])?;
                b
            }
            EntityKind::Polyline {
                vertices,
                closed,
                normal,
            } => {
                if vertices
                    .iter()
                    .any(|v| v.start_width != 0.0 || v.end_width != 0.0)
                {
                    return Err(Error::Unsupported(
                        "DGN polyline widths require explicit conversion".into(),
                    ));
                }
                if vertices.iter().any(|v| v.bulge != 0.0) {
                    let children = polyline::segments(e, vertices, *closed, *normal)?;
                    self.group(
                        e,
                        id,
                        level,
                        flags,
                        depth,
                        &children,
                        if *closed {
                            GroupKind::ComplexShape
                        } else {
                            GroupKind::ComplexChain
                        },
                        None,
                    )?;
                    self.attributes(e, id, level)?;
                    return Ok(());
                }
                self.points(
                    e,
                    id,
                    level,
                    flags,
                    &vertices.iter().map(|v| v.position).collect::<Vec<_>>(),
                    *closed,
                )?
            }
            EntityKind::Face { points, .. } => self.points(e, id, level, flags, points, true)?,
            EntityKind::Polygon {
                exterior,
                interiors,
            } => {
                cadkit_core::polygon::validate(
                    exterior,
                    interiors,
                    self.options.planarity_tolerance,
                    1e-6,
                    &mut 20_000_000,
                )?;
                if interiors.is_empty() {
                    self.points(e, id, level, flags, exterior, true)?
                } else {
                    let mut children = vec![];
                    for (i, ring) in std::iter::once(exterior)
                        .chain(interiors.iter())
                        .enumerate()
                    {
                        let mut child = Entity::new(EntityKind::Point {
                            position: Point3::default(),
                        });
                        copy_symbology(e, &mut child);
                        child.kind = EntityKind::Polyline {
                            vertices: ring.iter().copied().map(cadkit_core::Vertex::at).collect(),
                            closed: true,
                            normal: Vec3::Z,
                        };
                        if i > 0 {
                            child.props.insert("dgn.hole".into(), Value::Bool(true));
                        }
                        children.push(child);
                    }
                    self.group(e, id, level, flags, depth, &children, GroupKind::Cell, None)?;
                    self.attributes(e, id, level)?;
                    return Ok(());
                }
            }
            EntityKind::Group {
                children,
                group_kind,
                name,
                ..
            } => {
                self.group(
                    e,
                    id,
                    level,
                    flags,
                    depth,
                    children,
                    *group_kind,
                    name.as_deref(),
                )?;
                self.attributes(e, id, level)?;
                return Ok(());
            }
            EntityKind::Mesh { vertices, faces } => {
                let mut children = vec![];
                for face in faces {
                    let mut points = vec![];
                    for &i in face {
                        points.push(
                            *vertices.get(i as usize).ok_or_else(|| {
                                Error::invalid(0, "mesh index outside vertex array")
                            })?,
                        );
                    }
                    let mut child = Entity::new(EntityKind::Face {
                        points,
                        filled: true,
                    });
                    copy_symbology(e, &mut child);
                    children.push(child);
                }
                self.group(e, id, level, flags, depth, &children, GroupKind::Cell, None)?;
                self.attributes(e, id, level)?;
                return Ok(());
            }
            EntityKind::Circle {
                center,
                radius,
                normal,
            } => {
                if normal.normalized().is_none() {
                    return Err(Error::invalid(0, "invalid normal"));
                }
                let (x, y, n) = cadkit_core::geom_ops::arbitrary_axes(*normal);
                self.ellipse(
                    e, id, level, flags, *center, *radius, *radius, x, y, n, None,
                )?
            }
            EntityKind::Arc {
                center,
                radius,
                normal,
                start_angle,
                end_angle,
            } => {
                if normal.normalized().is_none() {
                    return Err(Error::invalid(0, "invalid normal"));
                }
                let (x, mut y, mut n) = cadkit_core::geom_ops::arbitrary_axes(*normal);
                let mut start = *start_angle;
                let mut sweep = cadkit_core::geom_ops::ccw_sweep(*start_angle, *end_angle);
                // A clockwise XY arc is represented by -Z in the neutral model.
                // V8 2D stores the same curve with a signed sweep and +Z axes.
                if !three && n.z < -0.999999 {
                    y = y.scaled(-1.0);
                    n = n.scaled(-1.0);
                    start = -start;
                    sweep = -sweep;
                }
                self.ellipse(
                    e,
                    id,
                    level,
                    flags,
                    *center,
                    *radius,
                    *radius,
                    x,
                    y,
                    n,
                    Some((start, sweep)),
                )?
            }
            EntityKind::Ellipse {
                center,
                major_axis,
                ratio,
                start_param,
                end_param,
                normal,
            } => {
                let n = normal
                    .normalized()
                    .ok_or_else(|| Error::invalid(0, "zero ellipse normal"))?;
                let x = major_axis
                    .normalized()
                    .ok_or_else(|| Error::invalid(0, "zero ellipse axis"))?;
                if n.dot(x).abs() > 1e-9 {
                    return Err(Error::invalid(0, "ellipse major axis is not in plane"));
                }
                let y = n.cross(x);
                let a = major_axis.length();
                let arc = ((*end_param - *start_param - std::f64::consts::TAU).abs() > 1e-12)
                    .then_some((*start_param, *end_param - *start_param));
                self.ellipse(e, id, level, flags, *center, a, a * ratio, x, y, n, arc)?
            }
            EntityKind::Text {
                position,
                height,
                rotation: angle,
                width_factor,
                oblique,
                value,
                style,
                halign,
                valign,
                normal,
                end_point,
            } => {
                if *oblique != 0.0 || end_point.is_some() {
                    return Err(Error::Unsupported(
                        "DGN text oblique and fit/aligned endpoints require explicit conversion"
                            .into(),
                    ));
                }
                if !height.is_finite()
                    || *height <= 0.0
                    || !width_factor.is_finite()
                    || *width_factor <= 0.0
                    || normal.normalized().is_none()
                {
                    return Err(Error::invalid(0, "invalid text dimensions or normal"));
                }
                let font = self.tables.font(e, style.as_deref())?;
                let (justification, fx, fy) = text::justification(e, *halign, *valign)?;
                let length = text::length(e, value, *height * *width_factor, fx)?;
                let (x, y, n) = cadkit_core::geom_ops::arbitrary_axes(*normal);
                let a = x.scaled(angle.cos()).plus(y.scaled(angle.sin()));
                let c = x.scaled(-angle.sin()).plus(y.scaled(angle.cos()));
                // The neutral point is the justification anchor; DGN stores the
                // lower-left baseline origin. Preserve the measured advance so
                // center/right text is not positioned from a font-width guess.
                let shift = a.scaled(fx * length).plus(c.scaled(fy * *height));
                let origin = coordinate(
                    Point3::new(
                        position.x - shift.x,
                        position.y - shift.y,
                        position.z - shift.z,
                    ),
                    self.model,
                )?;
                let value = self.text(value, false)?;
                let offset = if three { 0xca } else { 0xaa };
                let mut b = self.header(
                    17 | flags,
                    offset + value.len(),
                    id,
                    level,
                    self.options.timestamp_ms,
                    e,
                    three,
                )?;
                u32_at(&mut b, 0x68, font)?;
                put(&mut b, 0x6c, &justification.to_le_bytes())?;
                put(
                    &mut b,
                    0x6e,
                    &u16::try_from(value.len())
                        .map_err(|_| Error::limit(LimitKind::Capacity, "DGN text length".into()))?
                        .to_le_bytes(),
                )?;
                f64_at(
                    &mut b,
                    0x70,
                    height * width_factor * self.model.uor_per_master / 0.006,
                )?;
                f64_at(&mut b, 0x78, height * self.model.uor_per_master / 0.006)?;
                f64_at(&mut b, 0x80, length * self.model.uor_per_master)?;
                f64_at(&mut b, 0x88, height * self.model.uor_per_master)?;
                rotation(&mut b, 0x90, a, c, n, three)?;
                point(&mut b, if three { 0xb0 } else { 0x98 }, origin, three)?;
                put(&mut b, offset, &value)?;
                text::range(
                    &mut b,
                    origin,
                    a,
                    c,
                    length * self.model.uor_per_master,
                    height * self.model.uor_per_master,
                )?;
                links.extend(self.codepage_link()?);
                b
            }
            EntityKind::Spline {
                degree,
                knots,
                control_points,
                weights,
                fit_points,
                closed,
            } => {
                let sampled = if !control_points.is_empty() {
                    cadkit_core::geom_ops::nurbs_flatten(
                        *degree,
                        knots,
                        control_points,
                        weights,
                        16,
                    )
                } else if !fit_points.is_empty() {
                    match cadkit_core::geom_ops::interpolate_fit_points(fit_points, *closed) {
                        Some((deg, k, ctrl)) => {
                            cadkit_core::geom_ops::nurbs_flatten(deg, &k, &ctrl, &[], 16)
                        }
                        None => fit_points.clone(),
                    }
                } else {
                    return Err(Error::invalid(0, "empty spline cannot be written to DGN"));
                };
                if let [only] = sampled.as_slice() {
                    let p = coordinate(*only, self.model)?;
                    let mut b = self.header(
                        3 | flags,
                        0x68 + psize * 2,
                        id,
                        level,
                        self.options.timestamp_ms,
                        e,
                        three,
                    )?;
                    point(&mut b, 0x68, p, three)?;
                    point(&mut b, 0x68 + psize, p, three)?;
                    range(&mut b, &[p, p])?;
                    b
                } else {
                    let close_shape = *closed && sampled.len() >= 3;
                    self.points(e, id, level, flags, &sampled, close_shape)?
                }
            }
            other => {
                return Err(Error::Unsupported(format!(
                    "DGN V8 writer: {} requires explicit conversion",
                    other.type_name()
                )));
            }
        };
        // Carry an explicit hole flag from source props onto newly written geometry.
        if matches!(e.props.get("dgn.hole"), Some(Value::Bool(true))) {
            let props = le::u32_at(&b, 0x28).unwrap_or(0) | 0x8000;
            u32_at(&mut b, 0x28, props)?;
        }
        self.add(finish(b, &links)?, false)?;
        self.attributes(e, id, level)
    }
    /// A new raster attachment cloned from the seed template (see `raster_template`).
    fn new_raster(&mut self, e: &Entity, level: u32, component: bool) -> Result<()> {
        if component {
            return Err(Error::Unsupported(
                "new DGN raster attachments cannot be complex group components".into(),
            ));
        }
        let template = self
            .rasters
            .template
            .as_ref()
            .ok_or_else(|| Error::invalid(0, "raster template missing for a new attachment"))?;
        let mut ids = [0u64; 10];
        for id in &mut ids {
            *id = self.tables.id()?;
        }
        let group = template.instantiate(e, ids, level, self.model, self.options.timestamp_ms)?;
        let extra = group
            .controls
            .iter()
            .map(|c| c.len() as u64)
            .sum::<u64>()
            .saturating_add(group.xattribute.payload.len() as u64 + 28);
        self.bytes = self.bytes.saturating_add(extra);
        let index = self.records.len();
        self.new_controls.extend(group.controls);
        self.new_xattributes.push((index, group.xattribute));
        self.add(group.frame, false)?;
        self.attributes(e, group.frame_id, level)
    }
    fn points(
        &mut self,
        e: &Entity,
        id: u64,
        level: u32,
        flags: u32,
        points: &[Point3],
        closed: bool,
    ) -> Result<Vec<u8>> {
        if points.len() < if closed { 3 } else { 2 } {
            return Err(Error::invalid(0, "too few DGN vertices"));
        }
        let count = points.len() + usize::from(closed && points.first() != points.last());
        self.vertices = self.vertices.saturating_add(count as u64);
        if count as u64 > u64::from(self.options.limits.max_vertices)
            || self.vertices > self.options.limits.max_total_vertices
        {
            return Err(Error::limit(
                LimitKind::TotalVertices,
                "DGN output vertices".into(),
            ));
        }
        let mut coordinates: Vec<_> = points
            .iter()
            .map(|p| coordinate(*p, self.model))
            .collect::<Result<_>>()?;
        if count > points.len()
            && let Some(first) = coordinates.first().copied()
        {
            coordinates.push(first);
        }
        let size = if self.model.is_3d { 24 } else { 16 };
        let mut b = self.header(
            if closed { 6 } else { 4 } | flags,
            0x70 + count * size,
            id,
            level,
            self.options.timestamp_ms,
            e,
            self.model.is_3d,
        )?;
        u32_at(&mut b, 0x68, count as u32)?;
        for (i, p) in coordinates.iter().enumerate() {
            point(&mut b, 0x70 + i * size, *p, self.model.is_3d)?;
        }
        range(&mut b, &coordinates)?;
        Ok(b)
    }
    #[allow(clippy::too_many_arguments)]
    fn ellipse(
        &mut self,
        e: &Entity,
        id: u64,
        level: u32,
        flags: u32,
        center: Point3,
        a: f64,
        b: f64,
        x: Vec3,
        y: Vec3,
        n: Vec3,
        arc: Option<(f64, f64)>,
    ) -> Result<Vec<u8>> {
        if !(a > 0.0 && b > 0.0 && a.is_finite() && b.is_finite()) {
            return Err(Error::invalid(0, "invalid DGN ellipse radii"));
        }
        let three = self.model.is_3d;
        let p = coordinate(center, self.model)?;
        let (axes, rot, origin, size) = if arc.is_some() {
            (
                0x78,
                0x88,
                if three { 0xa8 } else { 0x90 },
                if three { 0xc0 } else { 0xa0 },
            )
        } else {
            (
                0x68,
                0x78,
                if three { 0x98 } else { 0x80 },
                if three { 0xb0 } else { 0x90 },
            )
        };
        let mut out = self.header(
            if arc.is_some() { 16 } else { 15 } | flags,
            size,
            id,
            level,
            self.options.timestamp_ms,
            e,
            three,
        )?;
        if let Some((start, sweep)) = arc {
            f64_at(&mut out, 0x68, start)?;
            f64_at(&mut out, 0x70, sweep)?;
        }
        f64_at(&mut out, axes, a * self.model.uor_per_master)?;
        f64_at(&mut out, axes + 8, b * self.model.uor_per_master)?;
        rotation(&mut out, rot, x, y, n, three)?;
        point(&mut out, origin, p, three)?;
        let bounds = [
            Point3::new(
                center.x - (a * x.x).hypot(b * y.x),
                center.y - (a * x.y).hypot(b * y.y),
                center.z - (a * x.z).hypot(b * y.z),
            ),
            Point3::new(
                center.x + (a * x.x).hypot(b * y.x),
                center.y + (a * x.y).hypot(b * y.y),
                center.z + (a * x.z).hypot(b * y.z),
            ),
        ];
        range(
            &mut out,
            &[
                coordinate(bounds[0], self.model)?,
                coordinate(bounds[1], self.model)?,
            ],
        )?;
        Ok(out)
    }
    #[allow(clippy::too_many_arguments)]
    fn group(
        &mut self,
        e: &Entity,
        id: u64,
        level: u32,
        flags: u32,
        depth: u32,
        children: &[Entity],
        kind: GroupKind,
        name: Option<&str>,
    ) -> Result<()> {
        if children.len() as u64 > self.options.limits.max_objects {
            return Err(Error::limit(
                LimitKind::Objects,
                "DGN group children".into(),
            ));
        }
        let cell = !matches!(kind, GroupKind::ComplexChain | GroupKind::ComplexShape);
        let t = if cell {
            2
        } else if kind == GroupKind::ComplexShape {
            14
        } else {
            12
        };
        let size = if cell {
            if self.model.is_3d { 0x100 } else { 0xc0 }
        } else {
            0x70
        };
        let mut b = self.header(
            t | flags | 0x2000_0000,
            size,
            id,
            level,
            self.options.timestamp_ms,
            e,
            self.model.is_3d,
        )?;
        u32_at(&mut b, 0x68, children.len() as u32)?;
        if cell {
            // MicroStation and ODA cells both carry 1 here (test_dgnv8.dgn).
            u32_at(&mut b, 0x6c, 1)?;
            let off = if self.model.is_3d { 0xa0 } else { 0x90 };
            let width = if self.model.is_3d { 3 } else { 2 };
            for i in 0..width {
                f64_at(&mut b, off + 8 * (i * width + i), 1.0)?;
            }
        }
        let links = if let Some(name) = name {
            string_link(1, name)?
        } else {
            vec![]
        };
        let index = self.records.len();
        self.add(finish(b, &links)?, false)?;
        let first = self.records.len();
        for child in children {
            self.entity(child, depth + 1, true)?;
        }
        let mut low = [i64::MAX; 3];
        let mut high = [i64::MIN; 3];
        for child in self.records.get(first..).unwrap_or(&[]) {
            let [child_low, child_high] = absolute_range(child)?;
            for axis in 0..3 {
                if let (Some(lo), Some(hi), Some(cl), Some(ch)) = (
                    low.get_mut(axis),
                    high.get_mut(axis),
                    child_low.get(axis),
                    child_high.get(axis),
                ) {
                    *lo = (*lo).min(*cl);
                    *hi = (*hi).max(*ch);
                }
            }
        }
        if children.is_empty() || self.records.len() == first {
            low = [0; 3];
            high = [0; 3];
        }
        if let Some(parent) = self.records.get_mut(index) {
            put_range(parent, low, high)?;
            if cell {
                // The cell body repeats the bounds as absolute corners (ODA writes them so;
                // the header keeps low corner + extent like every graphic record).
                point(parent, 0x70, low.map(|v| v as f64), self.model.is_3d)?;
                point(
                    parent,
                    if self.model.is_3d { 0x88 } else { 0x80 },
                    high.map(|v| v as f64),
                    self.model.is_3d,
                )?;
            }
        }
        Ok(())
    }
    /// String payload in the selected encoding. Text elements store the characters only
    /// (their length field counts no terminator); tag values end with a NUL that the
    /// value length includes, as MicroStation writes them (FORMAT_NOTES, "Strings").
    fn text(&self, value: &str, terminated: bool) -> Result<Vec<u8>> {
        if value.len() as u64 > u64::from(self.options.limits.max_string_bytes)
            || value.contains('\0')
        {
            return Err(Error::limit(
                LimitKind::StringBytes,
                "DGN string bytes/NUL".into(),
            ));
        }
        if let Some(label) = &self.options.codepage {
            let enc = encoding_rs::Encoding::for_label(label.as_bytes())
                .ok_or_else(|| Error::Unsupported("unknown DGN codepage".into()))?;
            let (bytes, _, errors) = enc.encode(value);
            if errors {
                return Err(Error::Unsupported(
                    "text cannot be represented in selected DGN codepage".into(),
                ));
            }
            let mut bytes = bytes.into_owned();
            if terminated {
                bytes.push(0);
            }
            Ok(bytes)
        } else if terminated {
            utf16(value)
        } else {
            utf16_unterminated(value)
        }
    }
    /// Code page linkage of 8-bit text elements, byte for byte as MicroStation writes it
    /// (`07 10 d4 80 00 02 ..` + code page at `+12`).
    fn codepage_link(&self) -> Result<Vec<u8>> {
        let Some(label) = &self.options.codepage else {
            return Ok(vec![]);
        };
        let number = label
            .strip_prefix("windows-")
            .and_then(|s| s.parse::<u32>().ok())
            .filter(|n| (1250..=1258).contains(n))
            .ok_or_else(|| {
                Error::Unsupported("DGN writer codepage must be windows-1250..1258".into())
            })?;
        let mut b = vec![0; 16];
        put(&mut b, 0, &[7, 0x10])?;
        put(&mut b, 2, &0x80d4u16.to_le_bytes())?;
        put(&mut b, 5, &[2])?;
        u32_at(&mut b, 12, number)?;
        Ok(b)
    }
    fn attributes(&mut self, e: &Entity, target: u64, level: u32) -> Result<()> {
        self.write_attributes(e, Some(target), level)
    }
    fn write_attributes(&mut self, e: &Entity, target: Option<u64>, level: u32) -> Result<()> {
        for a in &e.attributes {
            let widened;
            let a = match a.value {
                Value::Int(n) if self.wide_tags.contains(&tag_key(a)) => {
                    widened = {
                        let mut attribute = a.clone();
                        attribute.value = Value::Float(exact_f64(n)?);
                        attribute
                    };
                    &widened
                }
                _ => a,
            };
            let (set, index, kind) = self.tables.tag(a)?;
            let id = self.tables.id()?;
            let value = match &a.value {
                Value::Text(s) => self.text(s, true)?,
                Value::Int(n) => i32::try_from(*n)
                    .map_err(|_| Error::invalid(0, "DGN integer tag exceeds i32"))?
                    .to_le_bytes()
                    .to_vec(),
                Value::Float(n) if n.is_finite() => n.to_le_bytes().to_vec(),
                _ => return Err(Error::Unsupported("DGN tag type".into())),
            };
            // A tag element sits on its own level when the attribute names one.
            let level = match a.layer.as_deref() {
                Some(name) => self.tables.level(Some(name), self.options.timestamp_ms)?,
                None => level,
            };
            let symbology = attribute_symbology(e, a);
            // MicroStation leaves 10 bytes between the value and the linkages.
            let mut b = self.header(
                37,
                0x14a + value.len(),
                id,
                level,
                self.options.timestamp_ms,
                &symbology,
                self.model.is_3d,
            )?;
            let flags = le::u32_at(&b, 0x28).unwrap_or(0) | if a.invisible { 0x80 } else { 0 };
            u32_at(&mut b, 0x28, flags)?;
            // Observed constants: 3 and 3 on hidden tags, 3 and 11 on displayed ones.
            put(&mut b, 0x98, &3u16.to_le_bytes())?;
            put(
                &mut b,
                0x9a,
                &(if a.invisible { 3u16 } else { 11u16 }).to_le_bytes(),
            )?;
            put(&mut b, 0xd0, &index.to_le_bytes())?;
            put(&mut b, 0xd2, &kind.to_le_bytes())?;
            u32_at(
                &mut b,
                0x138,
                u32::try_from(value.len())
                    .map_err(|_| Error::limit(LimitKind::Capacity, "DGN tag value".into()))?,
            )?;
            put(&mut b, 0x140, &value)?;
            match &a.display {
                Some(display) => self.tag_display(&mut b, e, a, display)?,
                None => {
                    let p = coordinate(a.position.unwrap_or(Point3::default()), self.model)?;
                    point(&mut b, 0xa0, p, true)?;
                    // MicroStation leaves the range of a tag it does not draw empty.
                    put_range(&mut b, [0; 3], [0; 3])?;
                }
            }
            let mut links = dependency(0x2717, set)?;
            if let Some(target) = target {
                links.extend(tag_target_dependency(target)?);
            }
            self.add(finish_aligned(b, &links, 2)?, target.is_some())?;
        }
        Ok(())
    }

    /// Presentation of a displayed tag, laid out as MicroStation 8.11 writes it: the
    /// origin is the owner's first vertex and the offset leads to the text anchor; the
    /// size, font, justification and quaternion follow the text element conventions.
    fn tag_display(
        &self,
        b: &mut [u8],
        owner: &Entity,
        a: &Attribute,
        display: &cadkit_core::AttributeDisplay,
    ) -> Result<()> {
        let anchor = a
            .position
            .ok_or_else(|| Error::invalid(0, "displayed DGN tag needs a position"))?;
        if !(display.height.is_finite()
            && display.height > 0.0
            && display.width.is_finite()
            && display.width > 0.0
            && display.rotation.is_finite())
        {
            return Err(Error::invalid(0, "invalid DGN tag text size or rotation"));
        }
        let uor = self.model.uor_per_master;
        let p = coordinate(anchor, self.model)?;
        let origin = coordinate(first_vertex(owner).unwrap_or(anchor), self.model)?;
        point(b, 0xa0, origin, true)?;
        point(
            b,
            0xb8,
            [p[0] - origin[0], p[1] - origin[1], p[2] - origin[2]],
            true,
        )?;
        if !a.invisible {
            u32_at(b, 0xd4, 0x0200_0000)?;
        }
        f64_at(b, 0xf0, display.width * uor / 0.006)?;
        f64_at(b, 0xf8, display.height * uor / 0.006)?;
        // A 2D tag stores its angle in the first double, as 2D text does (issue #29;
        // MicroStation's unrotated 2D tags hold zeros). A 3D tag stores a quaternion:
        // unrotated (-1, 0, 0, 0), otherwise the text convention (w, 0, 0, z) with
        // z = sin(-θ/2), see native::element::Rotation::matrix.
        let q = if !self.model.is_3d {
            [display.rotation, 0.0, 0.0, 0.0]
        } else if display.rotation == 0.0 {
            [-1.0, 0.0, 0.0, 0.0]
        } else {
            let half = display.rotation / 2.0;
            [half.cos(), 0.0, 0.0, (-half).sin()]
        };
        for (i, v) in q.into_iter().enumerate() {
            f64_at(b, 0x100 + 8 * i, v)?;
        }
        u32_at(
            b,
            0x12c,
            self.tables.tag_font(&a.props, display.style.as_deref())?,
        )?;
        let (code, fx, fy) = text::justification_code(&a.props, display.halign, display.valign)?;
        u32_at(b, 0x130, u32::from(code))?;
        if a.invisible {
            return put_range(b, [0; 3], [0; 3]);
        }
        // Range: the text box around the anchor, `2h` high as MicroStation stores it.
        let length = match a.props.get("dgn.text_length") {
            Some(Value::Float(v)) if v.is_finite() && *v > 0.0 => *v,
            _ => display.width * value_chars(&a.value) as f64,
        } * uor;
        let height = display.height * uor;
        let (sin, cos) = display.rotation.sin_cos();
        let corners: Vec<[f64; 3]> = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)]
            .into_iter()
            .map(|(u, v)| {
                let dx = (u - fx) * length;
                let dy = (v * 2.0 - fy * 2.0) * height;
                [p[0] + dx * cos - dy * sin, p[1] + dx * sin + dy * cos, p[2]]
            })
            .collect();
        range(b, &corners)
    }
}

/// Symbology a component written for `parent` inherits (polygon rings, mesh faces): level,
/// colour, line style and weight, visibility and the native DGN indexes.
fn copy_symbology(parent: &Entity, child: &mut Entity) {
    child.layer = parent.layer.clone();
    child.color = parent.color;
    child.linetype = parent.linetype.clone();
    child.lineweight = parent.lineweight;
    child.visible = parent.visible;
    for key in ["dgn.color_index", "dgn.style", "dgn.weight"] {
        if let Some(value) = parent.props.get(key) {
            child.props.insert(key.into(), value.clone());
        }
    }
}

/// First defining point of an entity, where MicroStation anchors a tag attached to it.
fn first_vertex(e: &Entity) -> Option<Point3> {
    match &e.kind {
        EntityKind::Polyline { vertices, .. } => vertices.first().map(|v| v.position),
        EntityKind::Polygon { exterior, .. } => exterior.first().copied(),
        EntityKind::Face { points, .. } => points.first().copied(),
        EntityKind::Line { start, .. } => Some(*start),
        EntityKind::Point { position } | EntityKind::Text { position, .. } => Some(*position),
        EntityKind::Circle { center, .. }
        | EntityKind::Arc { center, .. }
        | EntityKind::Ellipse { center, .. } => Some(*center),
        EntityKind::Spline {
            control_points,
            fit_points,
            ..
        } => control_points
            .first()
            .or_else(|| fit_points.first())
            .copied(),
        _ => None,
    }
}

/// Character count of a displayed tag value, for its estimated text length.
fn value_chars(v: &Value) -> usize {
    match v {
        Value::Text(s) => s.chars().count(),
        Value::Int(n) => n.to_string().len(),
        Value::Float(f) => format!("{f}").len(),
        _ => 0,
    }
    .max(1)
}

/// Symbology of a tag element: the attribute's own DGN indexes first, then its typed
/// `color` / `lineweight` (resolved like an entity's: seed palette, `dgn.weight` rules),
/// then the owner's indexes and values.
fn attribute_symbology(owner: &Entity, a: &Attribute) -> Entity {
    let mut s = Entity::new(EntityKind::Point {
        position: Point3::default(),
    });
    s.layer = a.layer.clone().or_else(|| owner.layer.clone());
    s.color = a.color.unwrap_or(owner.color);
    s.linetype = owner.linetype.clone();
    s.lineweight = a.lineweight.unwrap_or(owner.lineweight);
    // The tag's hidden bit is the attribute's own (`a.invisible`); a hidden owner does not
    // hide a displayed tag of it.
    s.visible = true;
    for (key, typed) in [
        ("dgn.color_index", a.color.is_some()),
        ("dgn.weight", a.lineweight.is_some()),
        ("dgn.style", false),
    ] {
        let inherited = if typed { None } else { owner.props.get(key) };
        if let Some(v) = a.props.get(key).or(inherited) {
            s.props.insert(key.into(), v.clone());
        }
    }
    for key in ["dgn.graphic_group", "dgn.properties", "dgn.type_flags"] {
        if let Some(v) = a.props.get(key) {
            s.props.insert(key.into(), v.clone());
        }
    }
    s
}