ezdwg-core 0.22.0

Pure Rust DWG reader and native AC1015 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
use crate::bit::{BitReader, Endian};
use crate::core::error::{DwgError, ErrorKind};
use crate::core::result::Result;
use crate::entities::common::parse_common_entity_header_r14_with_handle;
use crate::entities::common::{
    parse_common_entity_handles, parse_common_entity_header, parse_common_entity_header_r2007,
    parse_common_entity_header_r2010, parse_common_entity_header_r2013,
    parse_common_entity_layer_handle, CommonEntityHeader,
};

/// How string fields (pattern name, gradient name) are stored in the data stream.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HatchStringMode {
    /// R2000-R2004: TV strings inline in the data stream.
    InlineTv,
    /// TU strings inline (only used as a legacy fallback candidate).
    InlineTu,
    /// R2007+: strings live in the object's separate string stream, so they
    /// consume no bits in the data stream.
    StringStream,
}

#[derive(Debug, Clone)]
pub struct HatchPath {
    pub closed: bool,
    /// The boundary as closed points, with arcs, ellipses and splines flattened.
    pub points: Vec<(f64, f64)>,
    /// The boundary before flattening.
    pub boundary: HatchBoundary,
}

/// A hatch boundary before flattening: a polyline (vertices with their bulges)
/// or a list of edges.
#[derive(Debug, Clone, PartialEq)]
pub enum HatchBoundary {
    Polyline {
        closed: bool,
        vertices: Vec<(f64, f64)>,
        /// Empty when the polyline stores no bulges.
        bulges: Vec<f64>,
    },
    Edges(Vec<HatchEdge>),
}

/// One edge of an edge-defined hatch boundary. Angles are in radians.
#[derive(Debug, Clone, PartialEq)]
pub enum HatchEdge {
    Line {
        start: (f64, f64),
        end: (f64, f64),
    },
    Arc {
        center: (f64, f64),
        radius: f64,
        start_angle: f64,
        end_angle: f64,
        counter_clockwise: bool,
    },
    Ellipse {
        center: (f64, f64),
        major_axis: (f64, f64),
        ratio: f64,
        start_angle: f64,
        end_angle: f64,
        counter_clockwise: bool,
    },
    /// A spline edge as stored, independently of its sampled display points.
    Spline {
        degree: u32,
        rational: bool,
        periodic: bool,
        knots: Vec<f64>,
        control_points: Vec<(f64, f64)>,
        weights: Vec<f64>,
        fit_points: Vec<(f64, f64)>,
        start_tangent: Option<(f64, f64)>,
        end_tangent: Option<(f64, f64)>,
    },
}

/// One family of parallel pattern lines of a pattern-filled hatch.
///
/// The line `k` of the family runs through `base + k * offset` at `angle`
/// (radians); `dashes` is its dash pattern (positive = dash, negative = gap,
/// empty = continuous). The values are stored already rotated and scaled.
#[derive(Debug, Clone, PartialEq)]
pub struct HatchPatternLine {
    pub angle: f64,
    pub base: (f64, f64),
    pub offset: (f64, f64),
    pub dashes: Vec<f64>,
}

/// Pattern definition of a pattern-filled hatch.
#[derive(Debug, Clone, PartialEq)]
pub struct HatchPattern {
    /// Pattern angle in radians (DXF group 52).
    pub angle: f64,
    /// Pattern scale or spacing (DXF group 41).
    pub scale: f64,
    /// Double hatch flag (DXF group 77).
    pub double: bool,
    pub lines: Vec<HatchPatternLine>,
}

#[derive(Debug, Clone)]
pub struct HatchEntity {
    pub handle: u64,
    pub color_index: Option<u16>,
    pub true_color: Option<u32>,
    pub layer_handle: u64,
    pub name: String,
    pub solid_fill: bool,
    pub associative: bool,
    pub elevation: f64,
    pub extrusion: (f64, f64, f64),
    pub paths: Vec<HatchPath>,
    /// Only for pattern fills whose definition could be read.
    pub pattern: Option<HatchPattern>,
}

pub fn decode_hatch(reader: &mut BitReader<'_>) -> Result<HatchEntity> {
    let header = parse_common_entity_header(reader)?;
    decode_hatch_with_header(reader, header, false, false, false, false, false)
}

/// R13/R14: the body is the one of R2000 (no gradient data); only the common
/// entity data differs.
pub fn decode_hatch_r14(reader: &mut BitReader<'_>, object_handle: u64) -> Result<HatchEntity> {
    let header = parse_common_entity_header_r14_with_handle(reader, object_handle)?;
    decode_hatch_with_header(reader, header, true, false, false, false, false)
}

pub fn decode_hatch_r2004(reader: &mut BitReader<'_>) -> Result<HatchEntity> {
    let header = parse_common_entity_header(reader)?;
    decode_hatch_with_header(reader, header, false, false, true, false, false)
}

pub fn decode_hatch_r2007(reader: &mut BitReader<'_>) -> Result<HatchEntity> {
    decode_hatch_with_header_start_candidates(
        reader,
        parse_common_entity_header_r2007,
        true,
        true,
        true,
        true,
        false,
    )
}

pub fn decode_hatch_r2010(
    reader: &mut BitReader<'_>,
    object_data_end_bit: u32,
    object_handle: u64,
) -> Result<HatchEntity> {
    decode_hatch_with_header_start_candidates(
        reader,
        |attempt_reader| {
            let mut header = parse_common_entity_header_r2010(attempt_reader, object_data_end_bit)?;
            header.handle = object_handle;
            Ok(header)
        },
        true,
        true,
        true,
        true,
        true,
    )
}

pub fn decode_hatch_r2013(
    reader: &mut BitReader<'_>,
    object_data_end_bit: u32,
    object_handle: u64,
) -> Result<HatchEntity> {
    decode_hatch_with_header_start_candidates(
        reader,
        |attempt_reader| {
            let mut header = parse_common_entity_header_r2013(attempt_reader, object_data_end_bit)?;
            header.handle = object_handle;
            Ok(header)
        },
        true,
        true,
        true,
        true,
        true,
    )
}

fn decode_hatch_with_header_start_candidates<F>(
    reader: &mut BitReader<'_>,
    mut parse_header: F,
    allow_handle_decode_failure: bool,
    r2007_layer_only: bool,
    has_gradient_payload: bool,
    use_unicode_text: bool,
    spline_fit_points: bool,
) -> Result<HatchEntity>
where
    F: FnMut(&mut BitReader<'_>) -> Result<CommonEntityHeader>,
{
    let start = reader.get_pos();
    let align_candidates = if start.1 == 0 {
        [false, false]
    } else {
        [false, true]
    };
    let mut first_err: Option<DwgError> = None;
    let mut best: Option<(i32, BitReader<'_>, HatchEntity)> = None;

    for align_after_prefix in align_candidates {
        if align_after_prefix && start.1 == 0 {
            continue;
        }
        let mut attempt_reader = reader.clone();
        if align_after_prefix {
            attempt_reader.align_byte();
        }
        let header = match parse_header(&mut attempt_reader) {
            Ok(header) => header,
            Err(err) => {
                if first_err.is_none() {
                    first_err = Some(err);
                }
                continue;
            }
        };
        match decode_hatch_with_header(
            &mut attempt_reader,
            header,
            allow_handle_decode_failure,
            r2007_layer_only,
            has_gradient_payload,
            use_unicode_text,
            spline_fit_points,
        ) {
            Ok(entity) => {
                let score = score_hatch_candidate(&entity);
                match &best {
                    Some((best_score, ..)) if score <= *best_score => {}
                    _ => best = Some((score, attempt_reader, entity)),
                }
            }
            Err(err) => {
                if first_err.is_none() {
                    first_err = Some(err);
                }
            }
        }
    }

    if let Some((_score, chosen_reader, entity)) = best {
        *reader = chosen_reader;
        return Ok(entity);
    }

    Err(first_err.unwrap_or_else(|| {
        DwgError::new(
            ErrorKind::Format,
            "failed to decode HATCH header-alignment candidates",
        )
    }))
}

fn decode_hatch_with_header(
    reader: &mut BitReader<'_>,
    header: CommonEntityHeader,
    allow_handle_decode_failure: bool,
    r2007_layer_only: bool,
    has_gradient_payload: bool,
    use_unicode_text: bool,
    spline_fit_points: bool,
) -> Result<HatchEntity> {
    let base_reader = reader.clone();
    if !has_gradient_payload {
        return decode_hatch_body(
            reader,
            header,
            allow_handle_decode_failure,
            r2007_layer_only,
            false,
            if use_unicode_text {
                HatchStringMode::StringStream
            } else {
                HatchStringMode::InlineTv
            },
            spline_fit_points,
        );
    }

    let mut first_err: Option<DwgError> = None;
    let mut best: Option<(i32, BitReader<'_>, HatchEntity)> = None;

    let debug = std::env::var("EZDWG_DEBUG_HATCH")
        .ok()
        .and_then(|value| value.parse::<u64>().ok())
        .is_some_and(|handle| handle == header.handle);
    // R2007+ keeps TV/TU strings in the string stream: the data stream has no
    // string bits at all. Older heuristics tried inline TU/TV first, which
    // misaligned every field after the gradient/pattern name; keep them only as
    // fallbacks for odd writers.
    let string_modes: &[HatchStringMode] = if use_unicode_text {
        &[
            HatchStringMode::StringStream,
            HatchStringMode::InlineTu,
            HatchStringMode::InlineTv,
        ]
    } else {
        &[HatchStringMode::InlineTv, HatchStringMode::InlineTu]
    };
    for skip_gradient in [true, false] {
        for string_mode in string_modes.iter().copied() {
            let string_is_unicode = string_mode;
            let mut attempt_reader = reader.clone();
            match decode_hatch_body(
                &mut attempt_reader,
                header.clone(),
                allow_handle_decode_failure,
                r2007_layer_only,
                skip_gradient,
                string_mode,
                spline_fit_points,
            ) {
                Ok(entity) => {
                    let mut score = score_hatch_candidate(&entity);
                    if use_unicode_text && string_mode == HatchStringMode::StringStream {
                        // The spec-conformant layout for R2007+; inline-string
                        // candidates only exist as a fallback for odd writers.
                        score += 5;
                    }
                    if debug {
                        eprintln!(
                            "[hatch debug] handle={} skip_gradient={skip_gradient} strings={string_is_unicode:?} OK score={score} name={:?} paths={:?} solid={} extrusion={:?}",
                            header.handle,
                            entity.name,
                            entity.paths.iter().map(|p| p.points.len()).collect::<Vec<_>>(),
                            entity.solid_fill,
                            entity.extrusion
                        );
                    }
                    match &best {
                        Some((best_score, ..)) if score <= *best_score => {}
                        _ => best = Some((score, attempt_reader, entity)),
                    }
                }
                Err(err) => {
                    if debug {
                        eprintln!(
                            "[hatch debug] handle={} skip_gradient={skip_gradient} strings={string_is_unicode:?} ERR {err}",
                            header.handle
                        );
                    }
                    if first_err.is_none() {
                        first_err = Some(err);
                    }
                }
            }
        }
    }

    if let Ok((candidate_reader, entity)) = decode_hatch_with_polyline_path_scan(
        &base_reader,
        &header,
        allow_handle_decode_failure,
        r2007_layer_only,
    ) {
        let score = score_hatch_candidate(&entity);
        if debug {
            eprintln!(
                "[hatch debug] handle={} scan-fallback score={score} paths={:?}",
                header.handle,
                entity
                    .paths
                    .iter()
                    .map(|p| p.points.len())
                    .collect::<Vec<_>>()
            );
        }
        match &best {
            Some((best_score, ..)) if score <= *best_score => {}
            _ => best = Some((score, candidate_reader, entity)),
        }
    }

    if let Some((score, chosen_reader, entity)) = best {
        if score > HATCH_CANDIDATE_REJECT {
            *reader = chosen_reader;
            return Ok(entity);
        }
        // Every candidate was garbage (no boundary): report a failure instead of
        // an entity with an empty or shifted boundary and a corrupt pattern name.
        return Err(first_err.unwrap_or_else(|| {
            DwgError::new(
                ErrorKind::Format,
                "failed to decode HATCH: no candidate has a usable boundary",
            )
        }));
    }

    Err(first_err.unwrap_or_else(|| {
        DwgError::new(
            ErrorKind::Format,
            "failed to decode HATCH with all candidates",
        )
    }))
}

fn decode_hatch_with_polyline_path_scan<'a>(
    base_reader: &BitReader<'a>,
    header: &CommonEntityHeader,
    allow_handle_decode_failure: bool,
    r2007_layer_only: bool,
) -> Result<(BitReader<'a>, HatchEntity)> {
    let body_start_bit = base_reader.tell_bits().min(u64::from(u32::MAX)) as u32;
    let total_bits = base_reader.total_bits().min(u64::from(u32::MAX)) as u32;
    let search_end_bit = header.obj_size.min(total_bits);
    if search_end_bit <= body_start_bit.saturating_add(96) {
        return Err(DwgError::new(
            ErrorKind::Format,
            "HATCH scan fallback has no room for path data",
        ));
    }

    let max_start_bit = search_end_bit
        .saturating_sub(96)
        .min(body_start_bit.saturating_add(2048));
    let mut best: Option<(i32, BitReader<'_>, HatchEntity)> = None;

    for start_bit in body_start_bit..=max_start_bit {
        let mut attempt_reader = base_reader.clone();
        attempt_reader.set_bit_pos(start_bit);
        let Ok(paths) = scan_hatch_polyline_paths(&mut attempt_reader, search_end_bit) else {
            continue;
        };

        let solid_fill = hatch_flag_bit_before(base_reader, start_bit, 2).unwrap_or(false);
        let associative = hatch_flag_bit_before(base_reader, start_bit, 1).unwrap_or(false);

        let mut handle_reader = attempt_reader.clone();
        handle_reader.set_bit_pos(header.obj_size);
        let layer_handle = match if r2007_layer_only {
            parse_common_entity_layer_handle(&mut handle_reader, header)
        } else {
            parse_common_entity_handles(&mut handle_reader, header)
                .map(|common_handles| common_handles.layer)
        } {
            Ok(layer_handle) => layer_handle,
            Err(err)
                if allow_handle_decode_failure
                    && matches!(
                        err.kind,
                        ErrorKind::Format | ErrorKind::Decode | ErrorKind::Io
                    ) =>
            {
                0
            }
            Err(err) => return Err(err),
        };

        let entity = HatchEntity {
            handle: header.handle,
            color_index: header.color.index,
            true_color: header.color.true_color,
            layer_handle,
            name: String::new(),
            solid_fill,
            associative,
            elevation: 0.0,
            extrusion: (0.0, 0.0, 1.0),
            paths,
            pattern: None,
        };

        let start_penalty =
            i32::try_from(start_bit.saturating_sub(body_start_bit) / 8).unwrap_or(0);
        let score = score_hatch_candidate(&entity).saturating_sub(start_penalty);
        match &best {
            Some((best_score, ..)) if score <= *best_score => {}
            _ => best = Some((score, handle_reader, entity)),
        }
    }

    best.map(|(_, reader, entity)| (reader, entity))
        .ok_or_else(|| {
            DwgError::new(
                ErrorKind::Format,
                "failed to recover HATCH polyline paths by scanning",
            )
        })
}

fn decode_hatch_body(
    reader: &mut BitReader<'_>,
    header: CommonEntityHeader,
    allow_handle_decode_failure: bool,
    r2007_layer_only: bool,
    skip_gradient: bool,
    string_mode: HatchStringMode,
    spline_fit_points: bool,
) -> Result<HatchEntity> {
    let debug = std::env::var("EZDWG_DEBUG_HATCH")
        .ok()
        .and_then(|value| value.parse::<u64>().ok())
        .is_some_and(|handle| handle == header.handle);
    if debug {
        eprintln!(
            "[hatch trace] body start bit={} obj_size={}",
            reader.tell_bits(),
            header.obj_size
        );
    }
    if skip_gradient {
        skip_gradient_payload(reader, string_mode)?;
        if debug {
            eprintln!("[hatch trace] after gradient bit={}", reader.tell_bits());
        }
    }

    let elevation = reader.read_bd()?;
    let extrusion = reader.read_3bd()?;
    let name = read_hatch_string(reader, string_mode)?;
    let solid_fill = reader.read_b()? != 0;
    let associative = reader.read_b()? != 0;

    let num_paths = bounded_count(reader.read_bl()?, "hatch paths")?;
    if debug {
        eprintln!(
            "[hatch trace] elev={elevation} ext={extrusion:?} name={name:?} solid={solid_fill} assoc={associative} num_paths={num_paths} bit={}",
            reader.tell_bits()
        );
    }
    let mut paths = Vec::with_capacity(num_paths.min(4096));
    let mut any_path_uses_pixel_size = false;
    let mut tessellated_points: usize = 0;

    for _ in 0..num_paths {
        let path_flag = reader.read_bl()?;
        any_path_uses_pixel_size |= (path_flag & 0x04) != 0;
        if debug {
            eprintln!(
                "[hatch trace] path flag={path_flag:#x} bit={}",
                reader.tell_bits()
            );
        }

        if (path_flag & 0x02) == 0 {
            let num_segments = bounded_count(reader.read_bl()?, "hatch edge path segments")?;
            let mut path_points: Vec<(f64, f64)> = Vec::new();
            let mut edges: Vec<HatchEdge> = Vec::new();
            for _ in 0..num_segments {
                let segment_type = reader.read_rc()?;
                if debug {
                    eprintln!(
                        "[hatch trace]  seg type={segment_type} of {num_segments} bit={}",
                        reader.tell_bits()
                    );
                }
                match segment_type {
                    1 => {
                        let start = read_point2rd(reader)?;
                        let end = read_point2rd(reader)?;
                        require_plausible_hatch_point(start, "line edge start")?;
                        require_plausible_hatch_point(end, "line edge end")?;
                        append_segment_points(&mut path_points, &[start, end]);
                        charge_hatch_points(&mut tessellated_points, 2)?;
                        edges.push(HatchEdge::Line { start, end });
                    }
                    2 => {
                        let center = read_point2rd(reader)?;
                        let radius = reader.read_bd()?;
                        let start_angle = reader.read_bd()?;
                        let end_angle = reader.read_bd()?;
                        let is_ccw = reader.read_b()? != 0;
                        require_plausible_hatch_point(center, "arc edge center")?;
                        require_plausible_hatch_length(radius, "arc edge radius")?;
                        require_plausible_hatch_scalar(start_angle, "arc edge start angle")?;
                        require_plausible_hatch_scalar(end_angle, "arc edge end angle")?;
                        let segment =
                            circular_arc_points(center, radius, start_angle, end_angle, is_ccw, 64);
                        charge_hatch_points(&mut tessellated_points, segment.len())?;
                        append_segment_points(&mut path_points, &segment);
                        edges.push(HatchEdge::Arc {
                            center,
                            radius,
                            start_angle,
                            end_angle,
                            counter_clockwise: is_ccw,
                        });
                    }
                    3 => {
                        let center = read_point2rd(reader)?;
                        let major_endpoint = read_point2rd(reader)?;
                        let ratio = reader.read_bd()?;
                        let start_angle = reader.read_bd()?;
                        let end_angle = reader.read_bd()?;
                        let is_ccw = reader.read_b()? != 0;
                        require_plausible_hatch_point(center, "ellipse edge center")?;
                        require_plausible_hatch_point(
                            major_endpoint,
                            "ellipse edge major endpoint",
                        )?;
                        require_plausible_hatch_scalar(ratio, "ellipse edge ratio")?;
                        require_plausible_hatch_scalar(start_angle, "ellipse edge start angle")?;
                        require_plausible_hatch_scalar(end_angle, "ellipse edge end angle")?;
                        let segment = elliptical_arc_points(
                            center,
                            major_endpoint,
                            ratio,
                            start_angle,
                            end_angle,
                            is_ccw,
                            96,
                        );
                        charge_hatch_points(&mut tessellated_points, segment.len())?;
                        append_segment_points(&mut path_points, &segment);
                        edges.push(HatchEdge::Ellipse {
                            center,
                            major_axis: major_endpoint,
                            ratio,
                            start_angle,
                            end_angle,
                            counter_clockwise: is_ccw,
                        });
                    }
                    4 => {
                        let (segment, edge) = read_spline_edge(reader, spline_fit_points, debug)?;
                        charge_hatch_points(&mut tessellated_points, segment.len())?;
                        append_segment_points(&mut path_points, &segment);
                        edges.push(edge);
                    }
                    _ => {
                        return Err(DwgError::new(
                            ErrorKind::Format,
                            format!("unsupported HATCH edge segment type: {segment_type}"),
                        ));
                    }
                }
            }
            let _num_boundary_obj_handles = reader.read_bl()?;
            close_path_if_needed(&mut path_points);
            paths.push(HatchPath {
                closed: true,
                points: path_points,
                boundary: HatchBoundary::Edges(edges),
            });
            continue;
        }

        let bulges_present = reader.read_b()? != 0;
        let closed = reader.read_b()? != 0;
        let num_vertices = bounded_count(reader.read_bl()?, "hatch polyline vertices")?;
        charge_hatch_points(&mut tessellated_points, num_vertices)?;
        // バルジは頂点ごとに最大64点へ増幅される。中間バッファの瞬間確保も
        // 抑えるため、バルジ付きは頂点数自体を実務上十分な範囲に制限する
        if bulges_present && num_vertices > 65_536 {
            return Err(DwgError::new(
                ErrorKind::Format,
                format!("hatch bulge polyline vertex count is too large: {num_vertices}"),
            ));
        }
        let mut vertices: Vec<(f64, f64)> = Vec::with_capacity(num_vertices.min(65_536));
        let mut bulges: Vec<f64> = Vec::with_capacity(if bulges_present {
            num_vertices.min(65_536)
        } else {
            0
        });
        for _ in 0..num_vertices {
            let point = read_point2rd(reader)?;
            require_plausible_hatch_point(point, "polyline vertex")?;
            vertices.push(point);
            if bulges_present {
                let bulge = reader.read_bd()?;
                require_plausible_hatch_scalar(bulge, "polyline bulge")?;
                bulges.push(bulge);
            }
        }
        let _num_boundary_obj_handles = reader.read_bl()?;

        let boundary = HatchBoundary::Polyline {
            closed,
            vertices: vertices.clone(),
            bulges: bulges.clone(),
        };
        let mut points = if bulges_present {
            polyline_with_bulges_points(&vertices, &bulges, closed, 64)
        } else {
            vertices
        };
        // 増幅後の実点数で課金(読み取り時に頂点数分は課金済み)
        charge_hatch_points(
            &mut tessellated_points,
            points.len().saturating_sub(num_vertices),
        )?;
        if closed {
            close_path_if_needed(&mut points);
        }
        paths.push(HatchPath {
            closed,
            points,
            boundary,
        });
    }

    let pattern = match read_hatch_definition_payload(reader, solid_fill, any_path_uses_pixel_size)
    {
        Ok(pattern) => pattern,
        Err(err)
            if matches!(
                err.kind,
                ErrorKind::Format | ErrorKind::Decode | ErrorKind::Io
            ) =>
        {
            None
        }
        Err(err) => return Err(err),
    };

    // Handles are stored in the handle stream at obj_size bit offset.
    reader.set_bit_pos(header.obj_size);
    let layer_handle = match if r2007_layer_only {
        parse_common_entity_layer_handle(reader, &header)
    } else {
        parse_common_entity_handles(reader, &header).map(|common_handles| common_handles.layer)
    } {
        Ok(layer_handle) => layer_handle,
        Err(err)
            if allow_handle_decode_failure
                && matches!(
                    err.kind,
                    ErrorKind::Format | ErrorKind::Decode | ErrorKind::Io
                ) =>
        {
            0
        }
        Err(err) => return Err(err),
    };

    Ok(HatchEntity {
        handle: header.handle,
        color_index: header.color.index,
        true_color: header.color.true_color,
        layer_handle,
        name,
        solid_fill,
        associative,
        elevation,
        extrusion,
        paths,
        pattern,
    })
}

fn scan_hatch_polyline_paths(
    reader: &mut BitReader<'_>,
    search_end_bit: u32,
) -> Result<Vec<HatchPath>> {
    let num_paths = bounded_count(reader.read_bl()?, "hatch paths")?;
    if !(1..=32).contains(&num_paths) {
        return Err(DwgError::new(
            ErrorKind::Format,
            format!("unsupported scanned HATCH path count: {num_paths}"),
        ));
    }

    let mut paths = Vec::with_capacity(num_paths);
    for _ in 0..num_paths {
        let path_flag = reader.read_bl()?;
        if path_flag > 0x1F || (path_flag & 0x02) == 0 {
            return Err(DwgError::new(
                ErrorKind::Format,
                format!("unsupported scanned HATCH path flag: {path_flag}"),
            ));
        }

        let bulges_present = reader.read_b()? != 0;
        let closed = reader.read_b()? != 0;
        let num_vertices = bounded_count(reader.read_bl()?, "hatch polyline vertices")?;
        if !(3..=4096).contains(&num_vertices) {
            return Err(DwgError::new(
                ErrorKind::Format,
                format!("unsupported scanned HATCH vertex count: {num_vertices}"),
            ));
        }

        let mut vertices: Vec<(f64, f64)> = Vec::with_capacity(num_vertices);
        let mut bulges: Vec<f64> = Vec::with_capacity(num_vertices);
        for _ in 0..num_vertices {
            let point = read_point2rd(reader)?;
            if !is_plausible_hatch_point(point) {
                return Err(DwgError::new(
                    ErrorKind::Format,
                    format!(
                        "implausible scanned HATCH point: ({}, {})",
                        point.0, point.1
                    ),
                ));
            }
            vertices.push(point);
            if bulges_present {
                let bulge = reader.read_bd()?;
                if !bulge.is_finite() || bulge.abs() > 1.0e6 {
                    return Err(DwgError::new(
                        ErrorKind::Format,
                        format!("implausible scanned HATCH bulge: {bulge}"),
                    ));
                }
                bulges.push(bulge);
            }
        }
        let _num_boundary_obj_handles = reader.read_bl()?;

        if reader.tell_bits() > u64::from(search_end_bit) {
            return Err(DwgError::new(
                ErrorKind::Format,
                "scanned HATCH path exceeds object data boundary",
            ));
        }

        let boundary = HatchBoundary::Polyline {
            closed,
            vertices: vertices.clone(),
            bulges: bulges.clone(),
        };
        let mut points = if bulges_present {
            polyline_with_bulges_points(&vertices, &bulges, closed, 64)
        } else {
            vertices
        };
        if closed {
            close_path_if_needed(&mut points);
        }
        if points.len() < 3 {
            return Err(DwgError::new(
                ErrorKind::Format,
                "scanned HATCH path is too short",
            ));
        }
        paths.push(HatchPath {
            closed,
            points,
            boundary,
        });
    }

    Ok(paths)
}

/// Score below which a candidate is a misaligned read, not a hatch.
const HATCH_CANDIDATE_REJECT: i32 = i32::MIN / 8;

fn score_hatch_candidate(entity: &HatchEntity) -> i32 {
    let mut score = 0i32;
    if !entity.name.is_empty() {
        score += 8;
    }
    // Without a single usable boundary the candidate read the wrong bits (every
    // real hatch has a boundary with at least three points).
    if entity.paths.is_empty() || entity.paths.iter().all(|path| path.points.len() < 3) {
        return i32::MIN / 4;
    }
    score += (entity.paths.len().min(32) as i32) * 4;
    // A boundary needs at least three points; empty/degenerate paths are a strong
    // sign of a misaligned candidate (they used to outscore real geometry).
    for path in &entity.paths {
        if path.points.len() >= 3 {
            score += 3;
        } else {
            score -= 8;
        }
        if path.closed {
            score += 2;
        }
        for (x, y) in &path.points {
            if !x.is_finite() || !y.is_finite() {
                return i32::MIN / 4;
            }
            if x.abs() > HATCH_COORDINATE_LIMIT || y.abs() > HATCH_COORDINATE_LIMIT {
                return i32::MIN / 4;
            }
        }
    }
    // Extrusion is (0, 0, ±1) for virtually every 2D hatch; a zero vector means
    // the fields were read from the wrong bit offset.
    let (ex, ey, ez) = entity.extrusion;
    let extrusion_len = (ex * ex + ey * ey + ez * ez).sqrt();
    if !extrusion_len.is_finite() || extrusion_len < 0.5 {
        score -= 10;
    } else if (extrusion_len - 1.0).abs() < 1e-6 {
        score += 6;
    }
    score
}

fn hatch_flag_bit_before(base_reader: &BitReader<'_>, start_bit: u32, offset: u32) -> Option<bool> {
    if start_bit < offset {
        return None;
    }
    let bit_pos = start_bit.saturating_sub(offset);
    if u64::from(bit_pos) >= base_reader.total_bits() {
        return None;
    }
    let mut reader = base_reader.clone();
    reader.set_bit_pos(bit_pos);
    reader.read_b().ok().map(|bit| bit != 0)
}

fn require_plausible_hatch_point(point: (f64, f64), context: &str) -> Result<()> {
    if is_plausible_hatch_point(point) {
        return Ok(());
    }
    Err(DwgError::new(
        ErrorKind::Format,
        format!("implausible HATCH {context}: ({}, {})", point.0, point.1),
    ))
}

/// A length (a radius) can be as large as a coordinate.
fn require_plausible_hatch_length(value: f64, context: &str) -> Result<()> {
    if value.is_finite() && value.abs() <= HATCH_COORDINATE_LIMIT {
        return Ok(());
    }
    Err(DwgError::new(
        ErrorKind::Format,
        format!("implausible HATCH {context}: {value}"),
    ))
}

fn require_plausible_hatch_scalar(value: f64, context: &str) -> Result<()> {
    if value.is_finite() && value.abs() <= 1.0e8 {
        return Ok(());
    }
    Err(DwgError::new(
        ErrorKind::Format,
        format!("implausible HATCH {context}: {value}"),
    ))
}

/// Largest coordinate a boundary point of a HATCH is taken at its word for.
///
/// A drawing in a national grid drawn in millimetres reaches 1.5e8 (150 km from
/// the origin of the zone); at 1e8 the fills of such a drawing were refused as
/// implausible. Bytes read at a wrong bit offset mostly come out far outside
/// this range.
const HATCH_COORDINATE_LIMIT: f64 = 1.0e12;

fn is_plausible_hatch_point(point: (f64, f64)) -> bool {
    point.0.is_finite()
        && point.1.is_finite()
        && point.0.abs() <= HATCH_COORDINATE_LIMIT
        && point.1.abs() <= HATCH_COORDINATE_LIMIT
}

/// A tangent component is 0 or a sane magnitude; the bytes of a following edge
/// or path read as doubles come out as denormals or astronomically large.
fn is_plausible_tangent_component(value: f64) -> bool {
    value.is_finite() && (value == 0.0 || (1.0e-9..=1.0e8).contains(&value.abs()))
}

fn read_hatch_string(reader: &mut BitReader<'_>, mode: HatchStringMode) -> Result<String> {
    match mode {
        HatchStringMode::InlineTv => reader.read_tv(),
        HatchStringMode::InlineTu => reader.read_tu(),
        HatchStringMode::StringStream => Ok(String::new()),
    }
}

fn skip_gradient_payload(reader: &mut BitReader<'_>, string_mode: HatchStringMode) -> Result<()> {
    let _is_gradient = reader.read_bl()?;
    let _reserved = reader.read_bl()?;
    let _gradient_angle = reader.read_bd()?;
    let _gradient_shift = reader.read_bd()?;
    let _single_color = reader.read_bl()?;
    let _gradient_tint = reader.read_bd()?;
    let num_colors = bounded_count(reader.read_bl()?, "hatch gradient colors")?;
    for _ in 0..num_colors {
        let _unknown_double = reader.read_bd()?;
        let _unknown_short = reader.read_bs()?;
        let _rgb_color = reader.read_bl()?;
        let _ignored_color_byte = reader.read_rc()?;
    }
    let _gradient_name = read_hatch_string(reader, string_mode)?;
    Ok(())
}

/// Reads the hatch style, the pattern definition of a pattern fill and the seed points.
///
/// Returns the pattern definition when the fill is not solid and its values are usable.
fn read_hatch_definition_payload(
    reader: &mut BitReader<'_>,
    solid_fill: bool,
    any_path_uses_pixel_size: bool,
) -> Result<Option<HatchPattern>> {
    let _style = reader.read_bs()?;
    let _pattern_type = reader.read_bs()?;

    let mut pattern = None;
    if !solid_fill {
        let angle = reader.read_bd()?;
        let scale = reader.read_bd()?;
        let double = reader.read_b()? != 0;
        let num_def_lines =
            bounded_count(reader.read_bs()? as u32, "hatch pattern definition lines")?;
        let mut lines = Vec::with_capacity(num_def_lines.min(64));
        for _ in 0..num_def_lines {
            let line_angle = reader.read_bd()?;
            let base = (reader.read_bd()?, reader.read_bd()?);
            let offset = (reader.read_bd()?, reader.read_bd()?);
            let num_dashes = bounded_count(reader.read_bs()? as u32, "hatch pattern dashes")?;
            let mut dashes = Vec::with_capacity(num_dashes.min(64));
            for _ in 0..num_dashes {
                dashes.push(reader.read_bd()?);
            }
            lines.push(HatchPatternLine {
                angle: line_angle,
                base,
                offset,
                dashes,
            });
        }
        let usable = angle.is_finite()
            && scale.is_finite()
            && lines.iter().all(|line| {
                line.angle.is_finite()
                    && line.base.0.is_finite()
                    && line.base.1.is_finite()
                    && line.offset.0.is_finite()
                    && line.offset.1.is_finite()
                    && line.dashes.iter().all(|dash| dash.is_finite())
            });
        if usable {
            pattern = Some(HatchPattern {
                angle,
                scale,
                double,
                lines,
            });
        }
    }

    let num_seed_points = if any_path_uses_pixel_size {
        let _pixel_size = reader.read_bd()?;
        bounded_count(reader.read_bl()?, "hatch seed points")?
    } else {
        0usize
    };
    for _ in 0..num_seed_points {
        let _seed = read_point2rd(reader)?;
    }
    Ok(pattern)
}

fn read_point2rd(reader: &mut BitReader<'_>) -> Result<(f64, f64)> {
    Ok((
        reader.read_rd(Endian::Little)?,
        reader.read_rd(Endian::Little)?,
    ))
}

fn append_segment_points(points: &mut Vec<(f64, f64)>, segment: &[(f64, f64)]) {
    if segment.is_empty() {
        return;
    }
    if points.is_empty() {
        points.extend_from_slice(segment);
        return;
    }
    let mut start = 0usize;
    if points_equal_2d(*points.last().unwrap(), segment[0]) {
        start = 1;
    }
    points.extend_from_slice(&segment[start..]);
}

fn close_path_if_needed(points: &mut Vec<(f64, f64)>) {
    if points.len() <= 1 {
        return;
    }
    let first = points[0];
    let last = *points.last().unwrap();
    if !points_equal_2d(first, last) {
        points.push(first);
    }
}

/// Read a HATCH spline boundary edge, retaining its definition and sampled points.
///
/// Layout (ODA spec, edge type 4): BL degree, B rational, B periodic,
/// BL knot count, BL control point count, BD knots, 2RD control points
/// (each followed by BD weight when rational); R2010+ append BL fit-point
/// count, 2RD fit points and the 2RD start/end tangents.
///
/// The specification lists the tangent pair unconditionally, but AutoCAD 2018
/// drawings seen in production store it only together with fit points: a
/// spline edge with zero fit points is followed directly by the next edge or
/// path. Reading 32 bytes of tangents there shifted every following field, so
/// the tangents are consumed only when fit points exist or when the next 4
/// doubles look like a tangent pair.
fn read_spline_edge(
    reader: &mut BitReader<'_>,
    has_fit_points: bool,
    debug: bool,
) -> Result<(Vec<(f64, f64)>, HatchEdge)> {
    let degree = bounded_count(reader.read_bl()?, "hatch spline degree")?;
    if degree > 25 {
        return Err(DwgError::new(
            ErrorKind::Format,
            format!("hatch spline degree is implausible: {degree}"),
        ));
    }
    let rational = reader.read_b()? != 0;
    let periodic = reader.read_b()? != 0;
    let num_knots = bounded_count(reader.read_bl()?, "hatch spline knots")?;
    let num_control = bounded_count(reader.read_bl()?, "hatch spline control points")?;
    if debug {
        eprintln!(
            "[hatch trace]   spline degree={degree} rational={rational} knots={num_knots} ctl={num_control} bit={}",
            reader.tell_bits()
        );
    }
    let mut knots = Vec::with_capacity(num_knots.min(4096));
    for _ in 0..num_knots {
        knots.push(reader.read_bd()?);
    }
    let mut control = Vec::with_capacity(num_control.min(4096));
    let mut weights = Vec::with_capacity(if rational { num_control.min(4096) } else { 0 });
    for _ in 0..num_control {
        control.push(read_point2rd(reader)?);
        if rational {
            weights.push(reader.read_bd()?);
        }
    }
    let mut fit_points = Vec::new();
    let mut start_tangent = None;
    let mut end_tangent = None;
    if has_fit_points {
        let num_fit = bounded_count(reader.read_bl()?, "hatch spline fit points")?;
        for _ in 0..num_fit {
            fit_points.push(read_point2rd(reader)?);
        }
        let tangents_present = if num_fit > 0 {
            true
        } else {
            let mut probe = reader.clone();
            (0..4).all(|_| {
                probe
                    .read_rd(Endian::Little)
                    .map(is_plausible_tangent_component)
                    .unwrap_or(false)
            })
        };
        if tangents_present {
            start_tangent = Some(read_point2rd(reader)?);
            end_tangent = Some(read_point2rd(reader)?);
        }
        if debug {
            eprintln!(
                "[hatch trace]   spline num_fit={num_fit} tangents_present={tangents_present} bit={}",
                reader.tell_bits()
            );
        }
    }
    let points = if control.len() >= 2 {
        sample_bspline(&control, &weights, &knots, degree)
    } else {
        None
    }
    .unwrap_or_else(|| {
        if fit_points.len() >= 2 {
            fit_points.clone()
        } else {
            control.clone()
        }
    });
    Ok((
        points,
        HatchEdge::Spline {
            degree: degree as u32,
            rational,
            periodic,
            knots,
            control_points: control,
            weights,
            fit_points,
            start_tangent,
            end_tangent,
        },
    ))
}

/// Uniform parameter sampling of a (rational) B-spline with Cox-de Boor basis.
fn sample_bspline(
    control: &[(f64, f64)],
    weights: &[f64],
    knots: &[f64],
    degree: usize,
) -> Option<Vec<(f64, f64)>> {
    let n = control.len();
    let degree = degree.min(n.saturating_sub(1)).max(1);
    let owned_knots: Vec<f64>;
    let knots = if knots.len() == n + degree + 1 && knots.windows(2).all(|w| w[0] <= w[1]) {
        knots
    } else {
        // Clamped uniform knot vector as a fallback for damaged knot data.
        let mut generated = vec![0.0; degree + 1];
        let interior = n - degree - 1;
        for index in 1..=interior {
            generated.push(index as f64 / (interior + 1) as f64);
        }
        generated.extend(std::iter::repeat(1.0).take(degree + 1));
        owned_knots = generated;
        &owned_knots
    };
    let start = knots[degree];
    let end = knots[n];
    if !(end > start) || !start.is_finite() || !end.is_finite() {
        return None;
    }
    let use_weights = weights.len() == n && weights.iter().all(|w| w.is_finite() && *w > 0.0);
    let samples = (n * 8).clamp(16, 256);
    let mut basis = vec![0.0f64; n];
    let mut points = Vec::with_capacity(samples + 1);
    for sample in 0..=samples {
        let t = if sample == samples {
            end
        } else {
            start + (end - start) * sample as f64 / samples as f64
        };
        bspline_basis(t, degree, knots, n, end, &mut basis);
        let mut x = 0.0;
        let mut y = 0.0;
        let mut denominator = 0.0;
        for (index, point) in control.iter().enumerate() {
            let weight = if use_weights { weights[index] } else { 1.0 };
            let factor = basis[index] * weight;
            x += factor * point.0;
            y += factor * point.1;
            denominator += factor;
        }
        if denominator.abs() < 1e-15 || !x.is_finite() || !y.is_finite() {
            continue;
        }
        points.push((x / denominator, y / denominator));
    }
    (points.len() >= 2).then_some(points)
}

fn bspline_basis(t: f64, degree: usize, knots: &[f64], n: usize, end: f64, out: &mut [f64]) {
    // Degree-0 basis: 1 on the half-open span containing t (closed at the end).
    let span_count = knots.len() - 1;
    let mut current = vec![0.0f64; span_count];
    for index in 0..span_count {
        let in_span = if t >= end {
            knots[index] < end && knots[index + 1] >= end
        } else {
            knots[index] <= t && t < knots[index + 1]
        };
        if in_span {
            current[index] = 1.0;
        }
    }
    for level in 1..=degree {
        let width = span_count - level;
        let mut next = vec![0.0f64; width];
        for index in 0..width {
            let left_den = knots[index + level] - knots[index];
            let right_den = knots[index + level + 1] - knots[index + 1];
            let mut value = 0.0;
            if left_den > 0.0 {
                value += (t - knots[index]) / left_den * current[index];
            }
            if right_den > 0.0 {
                value += (knots[index + level + 1] - t) / right_den * current[index + 1];
            }
            next[index] = value;
        }
        current = next;
    }
    for (index, slot) in out.iter_mut().enumerate().take(n) {
        *slot = current.get(index).copied().unwrap_or(0.0);
    }
}

fn circular_arc_points(
    center: (f64, f64),
    radius: f64,
    start_angle: f64,
    end_angle: f64,
    is_ccw: bool,
    arc_segments: usize,
) -> Vec<(f64, f64)> {
    if radius.abs() <= 1.0e-12 {
        return vec![];
    }
    let sweep = normalized_sweep(start_angle, end_angle, is_ccw);
    let segs = ((sweep.abs() / std::f64::consts::TAU) * (arc_segments.max(8) as f64)).ceil();
    let segments = segs.max(2.0) as usize;
    let mut out = Vec::with_capacity(segments + 1);
    for i in 0..=segments {
        let t = (i as f64) / (segments as f64);
        let angle = start_angle + sweep * t;
        out.push((
            center.0 + radius * angle.cos(),
            center.1 + radius * angle.sin(),
        ));
    }
    out
}

fn elliptical_arc_points(
    center: (f64, f64),
    major_endpoint: (f64, f64),
    ratio: f64,
    start_angle: f64,
    end_angle: f64,
    is_ccw: bool,
    arc_segments: usize,
) -> Vec<(f64, f64)> {
    let mx = major_endpoint.0;
    let my = major_endpoint.1;
    if mx.abs() <= 1.0e-12 && my.abs() <= 1.0e-12 {
        return vec![];
    }
    let vx = -my * ratio;
    let vy = mx * ratio;
    let sweep = normalized_sweep(start_angle, end_angle, is_ccw);
    let segs = ((sweep.abs() / std::f64::consts::TAU) * (arc_segments.max(16) as f64)).ceil();
    let segments = segs.max(4.0) as usize;
    let mut out = Vec::with_capacity(segments + 1);
    for i in 0..=segments {
        let t = (i as f64) / (segments as f64);
        let angle = start_angle + sweep * t;
        let c = angle.cos();
        let s = angle.sin();
        out.push((center.0 + mx * c + vx * s, center.1 + my * c + vy * s));
    }
    out
}

fn polyline_with_bulges_points(
    points: &[(f64, f64)],
    bulges: &[f64],
    closed: bool,
    arc_segments: usize,
) -> Vec<(f64, f64)> {
    if points.len() <= 1 {
        return points.to_vec();
    }
    let mut bulge_values = vec![0.0f64; points.len()];
    for (idx, bulge) in bulges.iter().enumerate().take(points.len()) {
        bulge_values[idx] = *bulge;
    }

    let seg_count = if closed {
        points.len()
    } else {
        points.len().saturating_sub(1)
    };
    let mut out: Vec<(f64, f64)> = Vec::new();
    for idx in 0..seg_count {
        let start = points[idx];
        let end = points[(idx + 1) % points.len()];
        let bulge = bulge_values[idx];
        let segment = bulge_segment_points(start, end, bulge, arc_segments);
        append_segment_points(&mut out, &segment);
    }
    out
}

fn bulge_segment_points(
    start: (f64, f64),
    end: (f64, f64),
    bulge: f64,
    arc_segments: usize,
) -> Vec<(f64, f64)> {
    if bulge.abs() <= 1.0e-12 {
        return vec![start, end];
    }

    let dx = end.0 - start.0;
    let dy = end.1 - start.1;
    let chord = (dx * dx + dy * dy).sqrt();
    if chord <= 1.0e-12 {
        return vec![start, end];
    }

    let theta = 4.0 * bulge.atan();
    if theta.abs() <= 1.0e-12 {
        return vec![start, end];
    }

    let normal = (-dy / chord, dx / chord);
    let center_offset = chord * (1.0 - bulge * bulge) / (4.0 * bulge);
    let mid = ((start.0 + end.0) * 0.5, (start.1 + end.1) * 0.5);
    let center = (
        mid.0 + normal.0 * center_offset,
        mid.1 + normal.1 * center_offset,
    );
    let radius = ((start.0 - center.0).powi(2) + (start.1 - center.1).powi(2)).sqrt();
    if radius <= 1.0e-12 {
        return vec![start, end];
    }

    let start_angle = (start.1 - center.1).atan2(start.0 - center.0);
    let segs = ((theta.abs() / std::f64::consts::TAU) * (arc_segments.max(8) as f64)).ceil();
    let segments = segs.max(2.0) as usize;
    let mut out = Vec::with_capacity(segments + 1);
    for i in 0..=segments {
        let t = (i as f64) / (segments as f64);
        let angle = start_angle + theta * t;
        out.push((
            center.0 + radius * angle.cos(),
            center.1 + radius * angle.sin(),
        ));
    }
    if let Some(first) = out.first_mut() {
        *first = start;
    }
    if let Some(last) = out.last_mut() {
        *last = end;
    }
    out
}

fn normalized_sweep(start_angle: f64, end_angle: f64, is_ccw: bool) -> f64 {
    let mut sweep = end_angle - start_angle;
    if is_ccw {
        if sweep < 0.0 {
            sweep += std::f64::consts::TAU;
        }
    } else if sweep > 0.0 {
        sweep -= std::f64::consts::TAU;
    }
    sweep
}

fn points_equal_2d(a: (f64, f64), b: (f64, f64)) -> bool {
    (a.0 - b.0).abs() <= 1.0e-9 && (a.1 - b.1).abs() <= 1.0e-9
}

/// 1つのHATCHが展開してよいテッセレーション点数の上限。実務図面のハッチは
/// 数千点で足りる。壊れた境界データは円弧セグメント1個あたり64点(楕円96点)に
/// 増幅されるため、カウント上限(bounded_count)だけでは数GBに膨らみうる。
const MAX_HATCH_TESSELLATION_POINTS: usize = 262_144;

fn charge_hatch_points(total: &mut usize, additional: usize) -> Result<()> {
    *total = total.saturating_add(additional);
    if *total > MAX_HATCH_TESSELLATION_POINTS {
        return Err(DwgError::new(
            ErrorKind::Format,
            format!("hatch tessellation exceeds {MAX_HATCH_TESSELLATION_POINTS} points"),
        ));
    }
    Ok(())
}

fn bounded_count(raw: u32, label: &str) -> Result<usize> {
    let count = raw as usize;
    if count > 1_000_000 {
        return Err(DwgError::new(
            ErrorKind::Format,
            format!("{} count is too large: {}", label, count),
        ));
    }
    Ok(count)
}

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

    #[test]
    fn bspline_sampler_reproduces_a_polyline_for_degree_one() {
        let control = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)];
        let knots = [0.0, 0.0, 0.5, 1.0, 1.0];
        let points = sample_bspline(&control, &[], &knots, 1).expect("sampled");
        assert_eq!(points.first().copied(), Some((0.0, 0.0)));
        let last = points.last().copied().unwrap();
        assert!((last.0 - 10.0).abs() < 1e-9 && (last.1 - 10.0).abs() < 1e-9);
        // The midpoint of the parameter range is the corner of the polyline.
        let mid = points[points.len() / 2];
        assert!((mid.0 - 10.0).abs() < 1e-6 && mid.1.abs() < 1e-6, "{mid:?}");
    }

    #[test]
    fn bspline_sampler_interpolates_clamped_endpoints_and_falls_back_on_bad_knots() {
        let control = [(0.0, 0.0), (5.0, 10.0), (10.0, 0.0)];
        // Wrong knot count: a clamped uniform vector is generated instead.
        let points = sample_bspline(&control, &[], &[0.0, 1.0], 2).expect("sampled");
        assert_eq!(points.first().copied(), Some((0.0, 0.0)));
        let last = points.last().copied().unwrap();
        assert!((last.0 - 10.0).abs() < 1e-9 && last.1.abs() < 1e-9);
        // A quadratic Bezier peaks at y = 5 in the middle.
        let peak = points.iter().map(|p| p.1).fold(f64::MIN, f64::max);
        assert!((peak - 5.0).abs() < 1e-3, "{peak}");
    }

    #[test]
    fn hatch_scores_prefer_real_boundaries_over_empty_paths() {
        let real = HatchEntity {
            handle: 1,
            color_index: None,
            true_color: None,
            layer_handle: 0,
            name: String::new(),
            solid_fill: true,
            associative: false,
            elevation: 0.0,
            extrusion: (0.0, 0.0, 1.0),
            paths: vec![HatchPath {
                closed: true,
                points: vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)],
                boundary: HatchBoundary::Edges(Vec::new()),
            }],
            pattern: None,
        };
        let garbage = HatchEntity {
            extrusion: (0.0, 0.0, 0.0),
            paths: vec![
                HatchPath {
                    closed: true,
                    points: Vec::new(),
                    boundary: HatchBoundary::Edges(Vec::new()),
                },
                HatchPath {
                    closed: true,
                    points: Vec::new(),
                    boundary: HatchBoundary::Edges(Vec::new()),
                },
            ],
            ..real.clone()
        };
        assert!(score_hatch_candidate(&real) > score_hatch_candidate(&garbage));
        // Garbage is rejected outright: no boundary with three points means the bits
        // were read from the wrong offset (2026-10-28, R2018 production files).
        assert!(score_hatch_candidate(&garbage) <= HATCH_CANDIDATE_REJECT);
        assert!(score_hatch_candidate(&real) > HATCH_CANDIDATE_REJECT);
    }

    /// degree 1, two control points, R2010+ fit-point count 0.
    fn write_spline_edge_without_fit_points(writer: &mut BitWriter) {
        writer.write_bl(1).unwrap(); // degree
        writer.write_b(0).unwrap(); // rational
        writer.write_b(0).unwrap(); // periodic
        writer.write_bl(4).unwrap(); // knots
        writer.write_bl(2).unwrap(); // control points
        for knot in [0.0, 0.0, 1.0, 1.0] {
            writer.write_bd(knot).unwrap();
        }
        for (x, y) in [(0.0, 0.0), (10.0, 0.0)] {
            writer.write_rd(Endian::Little, x).unwrap();
            writer.write_rd(Endian::Little, y).unwrap();
        }
        writer.write_bl(0).unwrap(); // fit points (R2010+)
    }

    #[test]
    fn spline_edge_without_fit_points_does_not_eat_the_next_edge_as_tangents() {
        // AutoCAD 2018 files store no start/end tangents when a spline edge has no fit
        // points; the next edge (type 1 = line) follows directly.
        let mut writer = BitWriter::new();
        write_spline_edge_without_fit_points(&mut writer);
        writer.write_rc(1).unwrap();
        writer.write_rd(Endian::Little, 10.0).unwrap();
        writer.write_rd(Endian::Little, 0.0).unwrap();
        writer.write_rd(Endian::Little, 10.0).unwrap();
        writer.write_rd(Endian::Little, 5.0).unwrap();
        let bytes = writer.into_bytes();
        let mut reader = BitReader::new(&bytes);
        let (points, edge) = read_spline_edge(&mut reader, true, false).expect("spline edge");
        assert_eq!(points.first().copied(), Some((0.0, 0.0)));
        assert!(matches!(
            edge,
            HatchEdge::Spline {
                start_tangent: None,
                end_tangent: None,
                ..
            }
        ));
        assert_eq!(
            reader.read_rc().unwrap(),
            1,
            "next edge type follows the spline edge"
        );
        assert_eq!(reader.read_rd(Endian::Little).unwrap(), 10.0);
    }

    #[test]
    fn spline_edge_without_fit_points_still_consumes_a_real_tangent_pair() {
        // Writers that follow the specification literally store the tangents anyway.
        let mut writer = BitWriter::new();
        write_spline_edge_without_fit_points(&mut writer);
        for value in [1.0, 0.0, 0.0, 1.0] {
            writer.write_rd(Endian::Little, value).unwrap();
        }
        writer.write_rc(2).unwrap();
        let bytes = writer.into_bytes();
        let mut reader = BitReader::new(&bytes);
        let (_, edge) = read_spline_edge(&mut reader, true, false).expect("spline edge");
        assert!(matches!(
            edge,
            HatchEdge::Spline {
                start_tangent: Some((1.0, 0.0)),
                end_tangent: Some((0.0, 1.0)),
                ..
            }
        ));
        assert_eq!(reader.read_rc().unwrap(), 2, "tangent pair was consumed");
    }

    #[test]
    fn spline_edge_with_fit_points_reads_fit_points_and_tangents() {
        let mut writer = BitWriter::new();
        writer.write_bl(1).unwrap();
        writer.write_b(0).unwrap();
        writer.write_b(0).unwrap();
        writer.write_bl(4).unwrap();
        writer.write_bl(2).unwrap();
        for knot in [0.0, 0.0, 1.0, 1.0] {
            writer.write_bd(knot).unwrap();
        }
        for (x, y) in [(0.0, 0.0), (10.0, 0.0)] {
            writer.write_rd(Endian::Little, x).unwrap();
            writer.write_rd(Endian::Little, y).unwrap();
        }
        writer.write_bl(1).unwrap(); // one fit point
        writer.write_rd(Endian::Little, 5.0).unwrap();
        writer.write_rd(Endian::Little, 0.0).unwrap();
        for value in [1.0, 0.0, 1.0, 0.0] {
            writer.write_rd(Endian::Little, value).unwrap(); // tangents
        }
        writer.write_rc(3).unwrap();
        let bytes = writer.into_bytes();
        let mut reader = BitReader::new(&bytes);
        let (_, edge) = read_spline_edge(&mut reader, true, false).expect("spline edge");
        let HatchEdge::Spline {
            fit_points,
            start_tangent,
            end_tangent,
            ..
        } = edge
        else {
            panic!("spline definition");
        };
        assert_eq!(fit_points, vec![(5.0, 0.0)]);
        assert_eq!(start_tangent, Some((1.0, 0.0)));
        assert_eq!(end_tangent, Some((1.0, 0.0)));
        assert_eq!(reader.read_rc().unwrap(), 3);
    }
}