draftwright 0.6.0-alpha.3

Dimensioned engineering drawings from STEP, with SVG, PDF and editable DXF output.
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
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
//! Feature control frames, datum feature symbols and labels: the part's AP242 PMI as
//! [`crate::pmi_lowering`] lowers it, placed beside its view and drawn (draftwright's
//! `annotations/_gdt.py` `render_gdt`, and `build123d_drafting`'s `FeatureControlFrame`,
//! `DatumFeature`, `TextBlock` and `Leader`).
//!
//! - **A feature control frame** is laid out as a CAD system lays out a native TOLERANCE, in
//!   QCAD's `gdt` and `Standard` fonts (haecceity's `cad_control_frame`): text 2.5 mm tall, cells
//!   two text heights (5 mm) tall and each as wide as its ink plus a text height, the
//!   characteristic's symbol in the first, the zone's `⌀` or `S⌀`, the magnitude and the
//!   material condition's ringed letter in the second, one cell per datum letter after. Its
//!   leader runs straight from
//!   its site into its strip, with an arrowhead at the site, a shelf of 2 mm, and the frame hung
//!   from the shelf's end (draftwright's `Leader` with a callout), the all-around circle or the
//!   all-over double circle at the bend.
//! - **A datum feature symbol** is drawn as ISO 5459 and ASME Y14.5 draw it: a filled triangle
//!   whose base sits on the datum's surface at its site, a line along the outward normal to a
//!   frame two text heights (5 mm) tall, and as wide unless the letters need more, holding the
//!   letter in the same font. draftwright hangs its `DatumFeature`
//!   glyph (triangle, line and frame together) off an arrowed leader's shelf instead, so its
//!   triangle sits beside the frame in mid-air, not on the surface.
//! - **A surface texture symbol** (a face's AP242 surface texture) is ISO 1302's graphical
//!   symbol, as the default finish beside the title block draws it, standing on its leader's
//!   shelf, its parameters (`Ra 0.8`) under the bar: its leader runs from a proven site on its
//!   face's edge line along the face's outward normal, as a datum's does, with an arrowhead at
//!   the site (draftwright's `Finish`, a `SurfaceFinish` glyph on a `Leader`, which only
//!   draftwright's face-finish lowering for one external cylinder makes). A cylinder with no
//!   proven silhouette is reached head-on instead, its leader ending in a dot inside the
//!   outline (ISO 128-22).
//! - **A label** (a surface or common label: `A`, `F1.1`, `2X R`) is its text at the
//!   dimensions' text height, unframed, hung from a leader as a frame is (draftwright's `Note`,
//!   a `TextBlock` callout on a `Leader`).
//!
//! **Placement** (additive to the dimensions' and leaders'): the layout reserves each item's
//! lowering strip ([`demand`], [`crate::layout::Strips::reserve_gdt`]). Automatic datums first
//! try compact tiers between their face and the first dimension lane, retaining the triangle,
//! shaft, frame and normal clearances. Only after these choices are exhausted do they try the
//! existing tiers beyond the dimensions. Cylinder sites are proved on either trimmed-face
//! silhouette; planar symbols may stand on a drawn face extension beyond either end of the
//! view outline. Constrained planar datums precede cylinders. At equal clearance and crossing
//! counts automatic datums prefer shorter leaders; original site order breaks remaining ties.
//! Filled triangles reserve clearance alongside the letter boxes, and final-plan lint rejects
//! touching or overlapping datum triangles. A plane's finish keeps its outward side; a
//! cylinder's tries compact tiers in its own strip, then the other proven silhouette only when
//! its own has no place clear of every label and line; its leader keeps a text height from
//! any line it runs alongside, and the finish with fewest sites in a strip is placed first. Frames and labels can retry the other
//! strips (`_gdt_retry_sides`).
//!
//! All glyphs share the same obstacle grade: clearance from labels, views, sheet furniture and
//! reserved-area boundaries, followed by the count of leader crossings with dimension lines,
//! extension lines, arrow shafts and other leaders (the collision reporter's `lines_meet`,
//! including collinear travel). Only the all-zero grade ends the search immediately. Within
//! equal clearances, fewer crossings win. When the original arrangement separates datum
//! triangles, a new arrangement must not introduce any annotation contact (unique unordered
//! pairs, independent of reporting direction). An original arrangement with touching triangles
//! is already illegal: repair may trade soft contacts for fewer symbol overlaps, retaining
//! all findings. Joint attachment reservations are used only when ordinary placement cannot
//! separate the triangles. Later frames must not be displaced merely to clear
//! an earlier leader in an already legal arrangement. Unavoidable collisions are
//! retained and reported (Policy B). Explicit placement intents retain their strip/tier rules.
//! If the full rearrangement introduces contact, the datum changes are also tried alone.
//! Pins and canonical hand placements take precedence over automatic compact placement.
//!
//! Each item's text layer is its compartments as the plan states them (`⌖`, `⌀0.05Ⓜ`, `A`, …),
//! one invisible run over each, so the PDF and SVG can be searched and lint reads it. The ink of
//! //! the symbols and of a frame's text is strokes and arcs in the SVG and PDF, drawn with the text
//! pen ([`crate::output::TEXT_PEN`], [`crate::output::Item::FrameText`]); the DXF writes each
//! frame as one native TOLERANCE with the gdt font's symbols instead, from [`frame`], and the
//! same size, since its style's DIMTXT is the frame text's height. A character the CAD fonts lack
//! is left out of the frame's ink and reported ([`frame_missing`]); a label's text is drawn as
//! the file states it, a character the font lacks as its missing-glyph box (as draftwright's
//! FreeType draws it).

use std::collections::{BTreeMap, BTreeSet};

use serde::{Deserialize, Serialize};

use super::placement::{self, Frame, Page, boxes_overlap, crosses};
use super::{ARROW, ARROW_HALF, FONT, P2, Placed, PlannedDimension, TEXT, font};
use crate::items::{Op, State};
use crate::model::{Analysis, PlannedSheet, PlannedView, Problem, Spec};
use crate::output::{Annotation, Curve, HAlign, Item, TextRun, VAlign};
use crate::pmi_lowering::{Glyph, Lowered};
use crate::text::Segment;

/// A feature control frame or datum feature symbol the sheet will carry.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PlannedGdt {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub from_spec: Vec<String>,
    /// `pmi:<identity>`, the record's semantic identity ([`crate::pmi::identity`]), never its
    /// Part 21 instance (that is `source`).
    pub id: String,
    /// `control_frame`, `datum_feature` or `label`.
    pub kind: String,
    pub view: String,
    /// Its strip: `above`, `below`, `left` or `right` of the view.
    pub side: String,
    /// The PMI record it draws (`Record::source_id`).
    pub source: String,
    /// The drawing's faces it applies to.
    pub faces: Vec<usize>,
    /// What it states, compartment by compartment, as its text runs: the characteristic's
    /// symbol, the zone, magnitude and material condition, then each datum letter; or a datum's
    /// letter.
    pub cells: Vec<String>,
    /// `all_around` or `all_over`, drawn at the leader's bend.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub modifiers: Vec<String>,
    /// What it states as one line ([`crate::items::frame_label`]).
    pub label: String,
    pub default: bool,
    pub basis: String,
    /// What became of it: shown, or why not ([`crate::items::State`]).
    pub state: crate::items::State,
    /// Its ink on the page; absent when it cannot be drawn, and a problem says why.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub placed: Option<GdtPlaced>,
}

/// A frame's or symbol's ink, mm on the page.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GdtPlaced {
    /// Where it attaches: the leader's arrowhead or the triangle's base.
    pub tip: P2,
    /// Its leader's lines: a frame's shaft and shelf, a symbol's line to its frame.
    pub lines: Vec<[P2; 2]>,
    /// Arrowheads, `[tip, tail]`.
    pub arrows: Vec<[P2; 2]>,
    /// The frame's box.
    pub label_box: [f64; 4],
    /// The glyph's straight strokes: the frame's rules and dividers, the symbols' lines and, in
    /// a CAD-font frame, from index `frame_strokes` on, the strokes of its text.
    pub strokes: Vec<[P2; 2]>,
    /// How many of the first `strokes` are lines of the glyph itself; the rest are text drawn
    /// with the text pen ([`haecceity::presentation::gdt::TEXT_PEN`]). All of them in a glyph
    /// that has no CAD-font text.
    #[serde(default = "all_strokes", skip_serializing_if = "is_all_strokes")]
    pub frame_strokes: usize,
    /// Its circles and arcs, `[cx, cy, r, from, to]` (degrees anticlockwise). In a CAD-font
    /// control frame the text's arcs come first and the all-around and all-over rings last.
    pub arcs: Vec<[f64; 5]>,
    /// Filled outlines: a datum's triangle.
    pub fills: Vec<Vec<P2>>,
    /// Letters and numbers drawn from the font, each centred on its point.
    pub letters: Vec<GdtText>,
    /// The text layer: each compartment's run, centred on its cell.
    pub runs: Vec<GdtText>,
}

fn all_strokes() -> usize {
    usize::MAX
}

fn is_all_strokes(n: &usize) -> bool {
    *n == usize::MAX
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GdtText {
    pub text: String,
    pub at: P2,
    pub size: f64,
}

/// draftwright's draft: the leader's shelf (`pad_around_text`), the frame's metrics
/// (`_gdt_metrics`: cell padding, the zone sign's and the material ring's radii), and the
/// datum symbol's triangle and frame (`DatumFeature`).
/// A datum feature symbol's box side when its letter fits, twice the CAD text height.
const H: f64 = 2.0 * haecceity::presentation::gdt::TEXT_HEIGHT;
pub(super) const SHELF: f64 = 2.0;
pub(super) const TRIANGLE: f64 = 1.4 * TEXT;
const RING: f64 = 0.7 * ARROW;

/// The outer scope ring at the leader bend, shared with the route search.
pub(super) fn ring_radius(modifiers: &[String]) -> f64 {
    if modifiers.iter().any(|m| m == "all_over") {
        1.7 * RING
    } else if modifiers.iter().any(|m| m == "all_around") {
        RING
    } else {
        0.0
    }
}

fn ring_box(bend: P2, radius: f64) -> [f64; 4] {
    [
        bend[0] - radius,
        bend[1] - radius,
        bend[0] + radius,
        bend[1] + radius,
    ]
}
/// The clearance beyond the dimensions, and between tiers.
const CLEAR: f64 = crate::layout::GDT_CLEAR;
const TIERS: usize = 16;

#[derive(Clone)]
struct ScopeRing {
    centre: P2,
    radius: f64,
    leader: Vec<[P2; 2]>,
}

fn reserve_ring(rings: &mut Vec<ScopeRing>, modifiers: &[String], p: &GdtPlaced) {
    let radius = ring_radius(modifiers);
    if radius > 0.0
        && let Some(arc) = p.arcs.last()
    {
        rings.push(ScopeRing {
            centre: [arc[0], arc[1]],
            radius,
            leader: p.lines.clone(),
        });
    }
}

/// Upgrade a transported frame's short shelf without replacing its proven
/// attachment or bend. Scope arcs stay at that bend; only rigid frame ink moves.
fn extend_scope_shelf(p: &mut GdtPlaced, modifiers: &[String]) {
    let radius = ring_radius(modifiers);
    if radius == 0.0 || p.lines.len() != 2 {
        return;
    }
    let [bend, end] = p.lines[1];
    if (end[1] - bend[1]).abs() > 1e-6 {
        return;
    }
    let missing = radius + super::contacts::TEXT_CLEAR - (end[0] - bend[0]).abs();
    if missing <= 1e-9 {
        return;
    }
    let dx = if end[0] >= bend[0] { missing } else { -missing };
    let mut moved = translated(p.clone(), [dx, 0.]);
    moved.tip = p.tip;
    moved.lines.clone_from(&p.lines);
    moved.lines[1][1][0] += dx;
    moved.arrows.clone_from(&p.arrows);
    let rings: usize = modifiers
        .iter()
        .map(|m| if m == "all_over" { 2 } else { 1 })
        .sum();
    let n = p.arcs.len();
    moved.arcs[n - rings..].copy_from_slice(&p.arcs[n - rings..]);
    *p = moved;
}

/// A glyph laid out at its own origin, before it is placed.
#[derive(Default)]
struct Laid {
    strokes: Vec<[P2; 2]>,
    /// How many of the first strokes are lines; the rest are CAD-font text. None: all lines.
    frame_strokes: Option<usize>,
    arcs: Vec<[f64; 5]>,
    letters: Vec<GdtText>,
    runs: Vec<GdtText>,
    size: P2,
}

fn text(s: &str, at: P2, size: f64) -> GdtText {
    GdtText {
        text: s.into(),
        at,
        size,
    }
}

fn circle(c: P2, r: f64) -> [f64; 5] {
    [c[0], c[1], r, 0.0, 360.0]
}

/// The rendered filled arrowhead, shared by scope-bend grading and output.
fn arrow_vertices([tip, tail]: [P2; 2]) -> [P2; 3] {
    let n = [tail[1] - tip[1], tip[0] - tail[0]];
    let k = ARROW_HALF / n[0].hypot(n[1]).max(1e-12);
    [
        tip,
        [tail[0] + k * n[0], tail[1] + k * n[1]],
        [tail[0] - k * n[0], tail[1] - k * n[1]],
    ]
}

/// The width of *s*'s ink at *size* in the sheet's font (IBM Plex Sans Condensed): the width
/// haecceity's shared notation measures cells with, so frames, labels and surface texture
/// symbols are sized for the ink the sheet draws.
fn width(s: &str, size: f64) -> f64 {
    let l = font().text(s, size);
    l.max[0] - l.min[0]
}

/// Frame *p* with the count of the *n* features it applies to (`4×`) over its box at its left end
/// (ISO 1101: the number of features above the tolerance frame), its box grown to hold it. The
/// count is drawn as the frame's text is: strokes and arcs of the CAD font at its text height,
/// the ink starting half a text height in from the box's left edge. A character the CAD font
/// lacks (it has `×` and the digits) is drawn from the sheet's font at the same height.
pub(super) fn with_count(p: &mut GdtPlaced, n: usize) {
    use haecceity::presentation::gdt::{TEXT_HEIGHT, cad_datum_frame, cad_frame_missing};
    let count = format!("{n}×");
    // Final witness repairs can revisit a frame already led to the same group.
    // Its translated glyph already carries the count and reserves its paper.
    if p.runs.iter().any(|run| run.text == count) {
        return;
    }
    let b = p.label_box;
    let pad = 0.6 * TEXT_HEIGHT;
    let base = b[3] + pad;
    let centre = if cad_frame_missing(&count, &[]).is_empty() {
        // The strokes of a datum frame's letter, which the CAD font draws centred on the origin
        // with its baseline half a text height below it, are the count's.
        let laid = cad_datum_frame(&count);
        let text = laid.strokes.get(laid.frame_strokes..).unwrap_or_default();
        let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
        let mut take = |q: P2| {
            for k in 0..2 {
                lo[k] = lo[k].min(q[k]);
                hi[k] = hi[k].max(q[k]);
            }
        };
        text.iter().flatten().for_each(|q| take(*q));
        for a in &laid.arcs {
            for i in 0..=32 {
                let t = (a[3] + (a[4] - a[3]) * f64::from(i) / 32.0).to_radians();
                take([a[0] + a[2] * t.cos(), a[1] + a[2] * t.sin()]);
            }
        }
        let shift = [b[0] + 0.5 * TEXT_HEIGHT - lo[0], base + 0.5 * TEXT_HEIGHT];
        let at = |q: &P2| [q[0] + shift[0], q[1] + shift[1]];
        p.strokes.extend(text.iter().map(|[x, y]| [at(x), at(y)]));
        p.arcs.splice(
            0..0,
            laid.arcs
                .iter()
                .map(|a| [a[0] + shift[0], a[1] + shift[1], a[2], a[3], a[4]]),
        );
        [0.5 * (lo[0] + hi[0]) + shift[0], base + 0.5 * TEXT_HEIGHT]
    } else {
        let w = width(&count, TEXT_HEIGHT);
        let at = [b[0] + 0.5 * TEXT_HEIGHT + 0.5 * w, base + 0.5 * TEXT_HEIGHT];
        p.letters.push(text(&count, at, TEXT_HEIGHT));
        at
    };
    p.runs.insert(0, text(&count, centre, TEXT_HEIGHT));
    p.label_box[3] = base + TEXT_HEIGHT + pad;
}

/// Remove the count added by `with_count`, so a new top row can carry it above
/// the entire stack. The count's strokes are appended and its arcs prepended.
pub(super) fn take_count(g: &mut PlannedGdt) -> Option<usize> {
    let p = g.placed.as_mut()?;
    if p.runs.len() != g.cells.len() + 1 {
        return None;
    }
    let count = &p.runs.first()?.text;
    let n = count.strip_suffix('×')?.parse().ok()?;
    let laid = haecceity::presentation::gdt::cad_datum_frame(count);
    p.strokes
        .truncate(p.strokes.len() - (laid.strokes.len() - laid.frame_strokes));
    p.arcs.drain(..laid.arcs.len());
    p.runs.remove(0);
    p.label_box[3] = p.strokes[..p.frame_strokes]
        .iter()
        .flatten()
        .map(|q| q[1])
        .fold(f64::NEG_INFINITY, f64::max);
    Some(n)
}

/// A feature control frame laid out from its lower left corner (`FeatureControlFrame`):
/// haecceity's CAD-font ISO 1101 frame, sized as a CAD system sizes a native TOLERANCE (text
/// 2.5 mm, box 5 mm), its text strokes and arcs.
fn control_frame(glyph: &Glyph) -> (Laid, Vec<String>) {
    let Glyph::ControlFrame {
        characteristic,
        tolerance,
        zone,
        material,
        datums,
        ..
    } = glyph
    else {
        // Invariant: This branch is reached only for a control-frame annotation.
        unreachable!("a control frame")
    };
    let c = haecceity::presentation::gdt::cad_control_frame(
        characteristic,
        tolerance,
        *zone,
        *material,
        datums,
    );
    let cells = c.cells.clone();
    (laid(c), cells)
}

/// A callout of haecceity's shared notation as this module lays it out.
fn laid(c: haecceity::presentation::Callout) -> Laid {
    let text = |t: haecceity::presentation::Text| GdtText {
        text: t.text,
        at: t.at,
        size: t.size,
    };
    Laid {
        frame_strokes: c.text_symbols.then_some(c.frame_strokes),
        strokes: c.strokes,
        arcs: c.arcs,
        letters: c.letters.into_iter().map(text).collect(),
        runs: c.runs.into_iter().map(text).collect(),
        size: c.size,
    }
}

/// A datum's frame laid out about its centre: haecceity's CAD-font datum feature symbol frame,
/// a box twice the text height on a side, the letter drawn in the frame's font, so its geometry
/// does not depend on the sheet's font.
fn datum_frame(letter: &str) -> Laid {
    laid(haecceity::presentation::gdt::cad_datum_frame(letter))
}

/// A label's text laid out from its lower left corner, a text height tall per line: each line is
/// haecceity's shared label (#258) measured in the sheet's font, its run set unpadded in the
/// label's lines (the lanes and leaders that place a label are this module's).
fn label(s: &str) -> Laid {
    let lines = crate::callouts::prose(s);
    let h = TEXT + (lines.len() - 1) as f64 * crate::callouts::line_spacing();
    let mut laid = Laid::default();
    let mut w: f64 = 0.5 * TEXT;
    for (i, line) in lines.iter().enumerate() {
        let shared = haecceity::presentation::label_with_width(line, &width);
        let line_width = width(line, TEXT);
        w = w.max(line_width);
        let at = [
            line_width / 2.0,
            h - TEXT / 2.0 - i as f64 * crate::callouts::line_spacing(),
        ];
        for run in shared.runs {
            let t = text(&run.text, at, run.size);
            laid.letters.push(t.clone());
            laid.runs.push(t);
        }
    }
    laid.size = [w, h];
    laid
}

/// A numbered triangular flag refers to the text in the existing notes block.
/// Its triangle participates in the ordinary callout collision and routing machinery.
fn flag_note(number: usize) -> Laid {
    let h = 2.5 * TEXT;
    let y = h / 2.0;
    let corners = [[0.0, y], [h, 0.0], [h, h]];
    let number = text(&number.to_string(), [0.68 * h, y], TEXT);
    Laid {
        size: [h, h],
        strokes: (0..3).map(|i| [corners[i], corners[(i + 1) % 3]]).collect(),
        letters: vec![number.clone()],
        runs: vec![number],
        arcs: Vec::new(),
        frame_strokes: None,
    }
}

/// The least gap between a finish's leader or shelf and a dimension or extension line it runs
/// alongside, mm: one text height.
const FINISH_PARALLEL_GAP: f64 = TEXT;

/// Whether segments *a* and *b* are parallel, overlap along their direction by more than
/// 0.5 mm, and lie closer than *gap* across it.
fn runs_alongside(a: [P2; 2], b: [P2; 2], gap: f64) -> bool {
    let d = [a[1][0] - a[0][0], a[1][1] - a[0][1]];
    let e = [b[1][0] - b[0][0], b[1][1] - b[0][1]];
    let (la, lb) = (d[0].hypot(d[1]), e[0].hypot(e[1]));
    if la < 1e-9 || lb < 1e-9 {
        return false;
    }
    let u = [d[0] / la, d[1] / la];
    if (u[0] * e[1] - u[1] * e[0]).abs() / lb > 1e-6 {
        return false;
    }
    let across = ((b[0][0] - a[0][0]) * u[1] - (b[0][1] - a[0][1]) * u[0]).abs();
    let t0 = dot([b[0][0] - a[0][0], b[0][1] - a[0][1]], u);
    let t1 = dot([b[1][0] - a[0][0], b[1][1] - a[0][1]], u);
    let overlap = la.min(t0.max(t1)) - 0f64.max(t0.min(t1));
    across < gap && overlap > 0.5
}

/// The empty margin left of a surface texture symbol's ink, from its origin.
const FINISH_MARGIN: f64 = 0.3 * TEXT;
/// The radius of the dot a leader ends in on a face inside its outline (ISO 128-22).
const DOT: f64 = 0.5;

/// A face's ISO 1302 surface texture symbol laid out from its lower left corner, which is the
/// left end of the reference line it stands on (its leader's shelf), and its parameters, one per
/// line: haecceity's shared symbol (#258), measured in the sheet's font. The short and long legs
/// stand at 60° to a tip on that line (1.4 and 3 text heights tall, as the default finish beside
/// the title block draws them, [`crate::title_block::default_finish`]), with the material removal
/// condition's mark, the bar from the long leg's top, and the parameters under it (ISO 1302's
/// positions a and b). The reference line itself is the leader's ([`candidate`]), as long as the
/// glyph is wide.
fn finish_symbol(
    texture: &haecceity::pmi::SurfaceTexture,
    units: crate::units::Units,
) -> (Laid, Vec<String>) {
    let source = haecceity::presentation::notes::texture_parameters(texture);
    let replacement = |line: &str| {
        if units.is_mm() {
            return line.to_string();
        }
        source.iter().position(|s| s == line).map_or_else(
            || line.to_string(),
            |i| {
                format!(
                    "{} {}",
                    texture.parameters[i].characteristic,
                    units.magnitude(texture.parameters[i].value.mm())
                )
            },
        )
    };
    let mut c = haecceity::presentation::notes::surface_texture_with_width(texture, &|s, size| {
        width(&replacement(s), size)
    });
    if !units.is_mm() {
        for t in c.letters.iter_mut().chain(&mut c.runs) {
            t.text = replacement(&t.text);
        }
        for t in &mut c.cells {
            *t = replacement(t);
        }
    }
    let cells = c.cells.clone();
    (laid(c), cells)
}

/// How an item hangs from its site: a feature control frame or label from its leader's shelf,
/// a datum feature symbol's triangle on its surface, or a surface texture symbol standing on its
/// leader's shelf.
#[derive(Clone, Copy, PartialEq)]
enum Shape {
    Frame,
    Datum,
    Finish,
}

impl Shape {
    fn of(glyph: &Glyph) -> Shape {
        match glyph {
            Glyph::Datum { .. } => Shape::Datum,
            Glyph::Finish { .. } => Shape::Finish,
            Glyph::ControlFrame { .. } | Glyph::Label { .. } | Glyph::FlagNote { .. } => {
                Shape::Frame
            }
        }
    }
}

/// The outward direction of strip *side*.
fn outward(side: &str) -> P2 {
    match side {
        "below" => [0.0, -1.0],
        "above" => [0.0, 1.0],
        "left" => [-1.0, 0.0],
        _ => [1.0, 0.0],
    }
}

fn dot(a: P2, b: P2) -> f64 {
    a[0] * b[0] + a[1] * b[1]
}

/// An item as placed at strip coordinate *pos* (along its strip's outward axis): its leader,
/// frame box and the laid glyph's offset.
#[derive(Clone)]
struct Candidate {
    frame_rule: bool,
    lines: Vec<[P2; 2]>,
    arrows: Vec<[P2; 2]>,
    fills: Vec<Vec<P2>>,
    label_box: [f64; 4],
    /// Where the glyph's origin lands.
    origin: P2,
    elbow: P2,
    ring_radius: f64,
}

impl Candidate {
    /// Grow the shelf by translating the rigid frame. The attachment and bend
    /// stay fixed, so an orthogonal shaft cannot acquire a slope.
    fn with_ring(mut self, radius: f64) -> Self {
        self.ring_radius = radius;
        if radius > 0.0 {
            let shelf = self.lines[1];
            let dir = if shelf[1][0] >= shelf[0][0] {
                1.0
            } else {
                -1.0
            };
            let dx = dir * (radius + super::contacts::TEXT_CLEAR - SHELF).max(0.0);
            self.lines[1][1][0] += dx;
            self.origin[0] += dx;
            self.label_box[0] += dx;
            self.label_box[2] += dx;
        }
        self
    }

    fn move_bend(&mut self, dx: f64) {
        self.elbow[0] += dx;
        self.lines[0][1] = self.elbow;
        self.lines[1][0] = self.elbow;
        for arrow in &mut self.arrows {
            *arrow = placement::arrow(self.lines[0][0], self.elbow);
        }
    }

    fn leader_length(&self) -> f64 {
        self.lines
            .iter()
            .map(|[a, b]| (b[0] - a[0]).hypot(b[1] - a[1]))
            .sum()
    }
}

/// Scope symbols can need a longer shelf to separate leaders with nearby tips.
/// Exhaust these bounded bend positions before displacing the frame to another
/// tier. A collinear shaft/shelf retains its partition rather than scoring it.
fn clear_ring_bend(
    c: Candidate,
    obstacles: &Obstacles<'_>,
    footprints: Option<&super::footprints::Footprints>,
) -> Candidate {
    if c.ring_radius == 0.0 {
        return c;
    }
    if (c.lines[0][0][1] - c.elbow[1]).abs() < 1e-9 || (c.lines[0][0][0] - c.elbow[0]).abs() < 1e-6
    {
        return c;
    }
    // A longer shelf must not buy annotation clearance by sending the shaft
    // through a foreign feature. Use the same footprints as the final audit.
    let feature_contacts = footprints.map_or(0, |f| f.crossing_count(c.lines[0]));
    let preserves_features = |next: &Candidate| {
        footprints.is_none_or(|f| f.crossing_count(next.lines[0]) <= feature_contacts)
    };
    // Moving the bend can put its ring on a witness that the old bend cleared.
    // When the frame itself fits, also try extending the frame end of the shelf
    // by the minimum amount, before sending its leader through the model.
    if obstacles.bounds_grade(&c, c.label_box) <= 1 && obstacles.clearance_grade(&c) == 2 {
        let dir = if c.lines[1][1][0] >= c.elbow[0] {
            1.0
        } else {
            -1.0
        };
        let dx = dir * (c.ring_radius + super::contacts::TEXT_CLEAR - SHELF).max(0.0);
        let mut shifted = c.clone();
        shifted.move_bend(dx);
        shifted.lines[1][1][0] += dx;
        shifted.origin[0] += dx;
        shifted.label_box[0] += dx;
        shifted.label_box[2] += dx;
        if preserves_features(&shifted)
            && obstacles.clearance_grade(&shifted) < obstacles.clearance_grade(&c)
        {
            // This solves the new ring contact while retaining the established
            // shaft through the model; further bend changes are unnecessary.
            return shifted;
        }
    }
    let dir = if c.lines[1][1][0] >= c.elbow[0] {
        1.0
    } else {
        -1.0
    };
    let score = |candidate: &Candidate, best| {
        let mut grade = obstacles.grade(candidate, best);
        let meets =
            |a, b| super::leaders::Line::new(a).meets(b) || super::leaders::Line::new(b).meets(a);
        grade.2 += candidate
            .arrows
            .iter()
            .filter(|arrow| obstacles.lines.iter().any(|line| meets(**arrow, *line)))
            .count();
        grade.2 += obstacles
            .heads
            .iter()
            .map(|head| {
                [
                    head[0],
                    [
                        0.5 * (head[1][0] + head[2][0]),
                        0.5 * (head[1][1] + head[2][1]),
                    ],
                ]
            })
            .filter(|arrow| candidate.lines.iter().any(|line| meets(*arrow, *line)))
            .count();
        grade.2 += candidate
            .arrows
            .iter()
            .copied()
            .map(arrow_vertices)
            .filter(|head| {
                obstacles
                    .heads
                    .iter()
                    .any(|other| polygons_touch(head, other))
            })
            .count();
        grade
    };
    let mut best = c.clone();
    let mut grade = score(&best, None);
    for step in 1..=5 {
        if grade == (0, 0, 0) {
            break;
        }
        let mut next = c.clone();
        next.move_bend(-dir * step as f64 * SHELF);
        if !preserves_features(&next) {
            continue;
        }
        let next_grade = score(&next, Some(grade));
        if next_grade < grade {
            best = next;
            grade = next_grade;
        }
    }
    best
}

fn candidate(shape: Shape, tip: P2, side: &str, pos: f64, size: P2) -> Candidate {
    let d = outward(side);
    let horizontal = d[0] == 0.0;
    if shape == Shape::Finish {
        // The symbol stands on its shelf, which runs from the leader's end under it: above or
        // below the view the shelf is the box's bottom edge (*pos* the box's middle), the
        // leader rising or falling to its left end; beside the view the leader runs straight
        // out to *pos* and on under the symbol, which stands on it. The glyph's ink starts
        // FINISH_MARGIN in from its origin: its box starts there too, so the leader's bend
        // stays that far outside it on every side (lint's leader through text), the box
        // turned to keep the margin toward the bend left of the view.
        let (elbow, x0) = if horizontal {
            ([tip[0], pos - size[1] / 2.0], tip[0])
        } else if d[0] > 0.0 {
            ([pos, tip[1]], pos)
        } else {
            ([pos, tip[1]], pos - size[0] - FINISH_MARGIN)
        };
        let label_box = [
            x0 + FINISH_MARGIN,
            elbow[1],
            x0 + size[0],
            elbow[1] + size[1],
        ];
        let shelf = if elbow[0] > x0 {
            [label_box[0], elbow[1]]
        } else {
            [label_box[2], elbow[1]]
        };
        return Candidate {
            frame_rule: shape == Shape::Frame,
            lines: vec![[tip, elbow], [elbow, shelf]],
            arrows: vec![placement::arrow(tip, elbow)],
            fills: Vec::new(),
            label_box,
            origin: [x0, elbow[1]],
            elbow,
            ring_radius: 0.0,
        };
    }
    if shape == Shape::Datum {
        let centre = if horizontal {
            [tip[0], pos]
        } else {
            [pos, tip[1]]
        };
        let n = [-d[1], d[0]];
        let half = 0.5 * TRIANGLE;
        let apex = [
            tip[0] + d[0] * 0.9 * TRIANGLE,
            tip[1] + d[1] * 0.9 * TRIANGLE,
        ];
        let near = [
            centre[0] - d[0] * 0.5 * size[0],
            centre[1] - d[1] * 0.5 * size[1],
        ];
        return Candidate {
            frame_rule: shape == Shape::Frame,
            lines: vec![[apex, near]],
            arrows: Vec::new(),
            fills: vec![vec![
                [tip[0] + n[0] * half, tip[1] + n[1] * half],
                apex,
                [tip[0] - n[0] * half, tip[1] - n[1] * half],
            ]],
            label_box: [
                centre[0] - 0.5 * size[0],
                centre[1] - 0.5 * size[1],
                centre[0] + 0.5 * size[0],
                centre[1] + 0.5 * size[1],
            ],
            origin: centre,
            elbow: near,
            ring_radius: 0.0,
        };
    }
    let elbow = if horizontal {
        [tip[0], pos]
    } else {
        [pos, tip[1]]
    };
    // The shelf runs on in the leader's direction, to the right of a vertical one.
    let dir = if elbow[0] >= tip[0] { 1.0 } else { -1.0 };
    let end = [elbow[0] + dir * SHELF, elbow[1]];
    let x0 = if dir > 0.0 { end[0] } else { end[0] - size[0] };
    let y0 = elbow[1] - size[1] / 2.0;
    Candidate {
        frame_rule: shape == Shape::Frame,
        lines: vec![[tip, elbow], [elbow, end]],
        arrows: vec![placement::arrow(tip, elbow)],
        fills: Vec::new(),
        label_box: [x0, y0, x0 + size[0], y0 + size[1]],
        origin: [x0, y0],
        elbow,
        ring_radius: 0.0,
    }
}

/// Half a datum frame's extent across its strip and along it (outward from the view): its box is
/// as wide as the letter needs and twice the text height tall, however the strip runs.
fn datum_halves(side: &str, size: P2) -> (f64, f64) {
    if outward(side)[0] == 0.0 {
        (0.5 * size[0], 0.5 * size[1])
    } else {
        (0.5 * size[1], 0.5 * size[0])
    }
}

/// An item's extent across strip *side* from its site, page mm: a frame's or label's leader,
/// shelf and box above or below its view, its box centred on the leader left or right; a datum's
/// frame centred on its line.
fn span(shape: Shape, side: &str, size: P2) -> [f64; 2] {
    if shape == Shape::Datum {
        let (across, _) = datum_halves(side, size);
        [-across, across]
    } else if shape == Shape::Finish {
        // From its leader: rightwards above or below the view, upwards beside it.
        if outward(side)[0] == 0.0 {
            [0.0, size[0]]
        } else {
            [0.0, size[1]]
        }
    } else if outward(side)[0] == 0.0 {
        [0.0, SHELF + size[0]]
    } else {
        [-size[1] / 2.0, size[1] / 2.0]
    }
}

/// The strip coordinate of an item's first tier in *side* of the view whose outline is *o*:
/// beyond the outline and every piece of that view's dimensions (*ink*: lines, arrows and label
/// boxes as their corners) on that side that lies across from it, with room for the leader's
/// arrowhead or the datum's triangle. A dimension elsewhere along the strip does not push it
/// out (draftwright's lateral tier reuse, `_adjust_strip_candidate_labels`): its tier is free
/// there.
fn first_tier(shape: Shape, side: &str, tip: P2, o: [f64; 4], ink: &[[P2; 2]], size: P2) -> f64 {
    let d = outward(side);
    let horizontal = d[0] == 0.0;
    let edge = match side {
        "below" => -o[1],
        "above" => o[3],
        "left" => -o[0],
        _ => o[2],
    };
    let across = |p: P2| if horizontal { p[0] } else { p[1] };
    let [a, b] = span(shape, side, size).map(|v| across(tip) + v);
    let base = ink
        .iter()
        .filter(|[p, q]| {
            let (lo, hi) = (across(*p).min(across(*q)), across(*p).max(across(*q)));
            lo < b + CLEAR && hi > a - CLEAR
        })
        .flat_map(|s| s.iter().map(|q| dot(*q, d)))
        .filter(|v| *v > edge)
        .fold(edge, f64::max);
    let along = dot(tip, d);
    // A surface texture symbol's box starts at its leader's end beside the view, as a frame's
    // would without its shelf, so the same clearances hold.
    let (from_base, from_tip) = if shape == Shape::Datum {
        let (_, along) = datum_halves(side, size);
        (CLEAR + along, 0.9 * TRIANGLE + 0.8 * TEXT + along)
    } else if horizontal {
        (CLEAR + size[1] / 2.0, ARROW + 1.0 + size[1] / 2.0)
    } else {
        (CLEAR, ARROW + 1.0)
    };
    let s = (base + from_base).max(along + from_tip);
    // Back from the outward axis to the page coordinate.
    if d[0] + d[1] < 0.0 { -s } else { s }
}

/// The step between tiers along the strip.
fn step(shape: Shape, side: &str, size: P2) -> f64 {
    let horizontal = outward(side)[0] == 0.0;
    if shape == Shape::Datum {
        2.0 * datum_halves(side, size).1 + CLEAR
    } else if horizontal {
        size[1] + CLEAR
    } else if shape == Shape::Finish {
        size[0] + CLEAR
    } else {
        size[0] + SHELF + CLEAR
    }
}

/// An attachment site, its outward side, and an optional planar face extension.
type Site<'a> = (P2, &'a str, Option<[P2; 2]>);
/// Clearance class, text contacts, then line crossings; winning counts are exact.
type Grade = (u8, usize, usize);
type Choice<'a> = (Grade, &'a str, Candidate, P2, usize);

/// Compact datum tiers, starting with the normal triangle, shaft and frame clearances.
/// Exact obstacle grading rejects any intervening dimension, extension or text. The outer
/// edge must precede the first stroke across the frame's strip, with the usual clearance.
fn inside_tiers(
    side: &str,
    tip: P2,
    outline: [f64; 4],
    size: P2,
    ink: &[[P2; 2]],
    local: bool,
) -> Vec<f64> {
    let d = outward(side);
    let sign = d[0] + d[1];
    // Start at the attachment, not at the far end of the entire view. A shoulder
    // or face extension can have clear paper beside it inside the outline's span.
    // The obstacle grade requires proof of exterior paper within the view's box.
    let (half_across, half_along) = datum_halves(side, size);
    let first = dot(tip, d) + 0.9 * TRIANGLE + 0.8 * TEXT + half_along;
    let across = usize::from(d[0] != 0.0);
    let nearest = ink
        .iter()
        .filter(|[a, b]| {
            a[across].min(b[across]) < tip[across] + half_across + CLEAR
                && a[across].max(b[across]) > tip[across] - half_across - CLEAR
        })
        .flat_map(|l| l.iter().map(|p| dot(*p, d)))
        .filter(|v| *v > dot(tip, d) + 1e-6)
        .fold(f64::INFINITY, f64::min);
    // Keep the original view-boundary grid too. Starting the new grid at a
    // shoulder changes its phase; replacing the old grid would lose clear
    // placements between crowded dimension lanes on unrelated parts.
    let boundary = first_tier(Shape::Datum, side, tip, outline, &[], size) * sign;
    let starts = if local {
        vec![first, boundary]
    } else {
        vec![boundary]
    };
    let mut positions: Vec<_> = starts
        .into_iter()
        .flat_map(|start| {
            (0..TIERS)
                .map(move |k| start + k as f64 * step(Shape::Datum, side, size))
                .take_while(move |p| *p + half_along + CLEAR <= nearest)
                .map(move |p| p * sign)
        })
        .collect();
    positions.sort_by(|a, b| (a * sign).total_cmp(&(b * sign)));
    positions.dedup_by(|a, b| (*a - *b).abs() < 1e-6);
    positions
}

/// Both silhouettes are usable only where the reader proved points on the trimmed face.
/// Keep the original site first, then try the nearest sites in page space.
fn cylinder_sites<'a>(
    analysis: &Analysis,
    item: &'a Lowered,
    frame: &Frame,
    requested: Option<&str>,
) -> Vec<Site<'a>> {
    cylinder_sites_of(analysis, item, frame, requested, false)
}

/// [`cylinder_sites`], from each face's head-on sites when *face_on*
/// ([`crate::pmi::FaceAttachment::face_on`]), else from its silhouette sites.
fn cylinder_sites_of<'a>(
    analysis: &Analysis,
    item: &'a Lowered,
    frame: &Frame,
    requested: Option<&str>,
    face_on: bool,
) -> Vec<Site<'a>> {
    let original = frame.page(item.site);
    let mut sites = Vec::new();
    for face in &item.faces {
        let Some(a) = analysis.face_attachments.get(*face) else {
            continue;
        };
        let Some(axis) = a.exact_axis else {
            continue;
        };
        if a.support.len() != 2 {
            continue;
        }
        let mut centre = item.site;
        for (i, value) in (0..3).filter(|i| *i != axis).zip(&a.support) {
            centre[i] = *value;
        }
        let centre = frame.page(centre);
        let proven = if face_on { &a.face_on } else { &a.sites };
        for p in std::iter::once(item.site)
            .chain(item.alternatives.iter().copied())
            .chain(proven.iter().copied())
        {
            let tip = frame.page(p);
            let side = if outward(item.side)[0] != 0.0 {
                if tip[0] > centre[0] { "right" } else { "left" }
            } else if tip[1] > centre[1] {
                "above"
            } else {
                "below"
            };
            if requested.is_none_or(|s| s == side) {
                sites.push((tip, side, None));
            }
        }
    }
    if sites.is_empty() {
        return vec![(original, item.side, None)];
    }
    sites.sort_by(|a, b| {
        let distance = |p: P2| (p[0] - original[0]).hypot(p[1] - original[1]);
        distance(a.0).total_cmp(&distance(b.0))
    });
    sites.dedup_by(|a, b| a.0 == b.0 && a.1 == b.1);
    sites
}

/// A planar face seen edge-on continues as a straight extension beyond either end of
/// the view. Leave a 1 mm outline gap and carry the line beyond the triangle's full base.
fn plane_extensions<'a>(analysis: &Analysis, item: &'a Lowered, frame: &Frame) -> Vec<Site<'a>> {
    let tip = frame.page(item.site);
    let k = usize::from(outward(item.side)[0] != 0.0);
    let outline = frame.outline();
    let mut bounds = [f64::INFINITY, f64::NEG_INFINITY];
    for f in &item.faces {
        let Some(b) = analysis.face_attachments.get(*f).and_then(|a| a.bounds) else {
            continue;
        };
        for x in [b[0], b[3]] {
            for y in [b[1], b[4]] {
                for z in [b[2], b[5]] {
                    let p = frame.page([x, y, z]);
                    bounds[0] = bounds[0].min(p[k]);
                    bounds[1] = bounds[1].max(p[k]);
                }
            }
        }
    }
    if !bounds.iter().all(|v| v.is_finite()) {
        return Vec::new();
    }
    let mut sites = Vec::new();
    for (end, sign) in [(0, -1.0), (1, 1.0)] {
        // Starting 1 mm past the face must also clear the part's projected envelope.
        if (bounds[end] - outline[k + 2 * end]).abs() > 1.0 {
            continue;
        }
        for n in 0..TIERS {
            let mut at = tip;
            at[k] = outline[k + 2 * end] + sign * (CLEAR + TRIANGLE / 2.0 + n as f64 * (H + CLEAR));
            let mut start = tip;
            start[k] = bounds[end] + sign;
            let mut stop = at;
            stop[k] += sign * (TRIANGLE / 2.0 + CLEAR);
            sites.push((at, item.side, Some([start, stop])));
        }
    }
    sites.sort_by(|a, b| (a.0[k] - tip[k]).abs().total_cmp(&(b.0[k] - tip[k]).abs()));
    sites
}

fn authored(place: Option<&crate::placement_intent::Place>) -> bool {
    place.is_some_and(|p| {
        p.pinned || p.side.is_some() || p.lane.is_some() || p.along.is_some() || p.offset.is_some()
    })
}

fn datum_sites<'a>(
    analysis: &Analysis,
    item: &'a Lowered,
    frame: &Frame,
    constrained: bool,
) -> Vec<Site<'a>> {
    if matches!(&item.glyph, Glyph::Datum { surface, .. } if surface == "cylinder") {
        return cylinder_sites(analysis, item, frame, constrained.then_some(item.side));
    }
    let mut sites: Vec<_> = std::iter::once(item.site)
        .chain(item.alternatives.iter().copied())
        .map(|p| (frame.page(p), item.side, None))
        .collect();
    if !constrained {
        sites.extend(plane_extensions(analysis, item, frame));
    }
    sites
}

/// Reserve distinct proven attachment sites together before greedily placing
/// letter boxes. Three coincident projections may need an earlier triangle to
/// move away from its middle station to leave room for the third. The bounded
/// search concerns filled triangles alone, not combinations of leader tiers.
fn separated_sites(
    analysis: &Analysis,
    spec: &Spec,
    items: &[Lowered],
    frames: &BTreeMap<&str, Frame>,
    page: &Page<'_>,
) -> BTreeMap<String, Vec<P2>> {
    let mut choices = Vec::new();
    for item in items
        .iter()
        .filter(|i| matches!(i.glyph, Glyph::Datum { .. }))
    {
        let entry = spec.annotations.get(&item.id);
        if entry.is_some_and(|p| p.omit) || datum_omission(analysis, spec, item).is_some() {
            continue;
        }
        let intent = entry.and_then(|p| p.place.as_ref());
        // Explicit pins retain their authored positions and are linted as drawn.
        if intent.is_some_and(|p| p.pinned) {
            return BTreeMap::new();
        }
        let Some(frame) = frames.get(item.view) else {
            continue;
        };
        if page.area(item.view).is_none() {
            continue;
        }
        let mut fills = Vec::new();
        for (tip, side, _) in datum_sites(analysis, item, frame, authored(intent)) {
            let d = outward(side);
            let pos = dot(tip, d) + 0.9 * TRIANGLE + 0.8 * TEXT + TEXT;
            let c = candidate(Shape::Datum, tip, side, pos * (d[0] + d[1]), [H, H]);
            // Invariant: The datum-symbol builder always emits its filled triangle.
            let fill = c.fills.into_iter().next().expect("datum triangle");
            let b = fill_box(&fill);
            let paper = page.drawable();
            if b[0] >= paper[0]
                && b[1] >= paper[1]
                && b[2] <= paper[2]
                && b[3] <= paper[3]
                && !fills.contains(&fill)
            {
                fills.push(fill);
            }
        }
        if fills.is_empty() {
            return BTreeMap::new();
        }
        choices.push((item.id.clone(), fills));
    }
    fn choose(
        choices: &[(String, Vec<Vec<P2>>)],
        selected: &mut Vec<Vec<P2>>,
        remaining: &mut usize,
    ) -> bool {
        if selected.len() == choices.len() {
            return true;
        }
        for fill in &choices[selected.len()].1 {
            if *remaining == 0 {
                return false;
            }
            *remaining -= 1;
            if selected
                .iter()
                .any(|previous| polygons_touch(fill, previous))
            {
                continue;
            }
            selected.push(fill.clone());
            if choose(choices, selected, remaining) {
                return true;
            }
            selected.pop();
        }
        false
    }
    let mut selected = Vec::new();
    let mut remaining = 4096;
    if choose(&choices, &mut selected, &mut remaining) {
        choices
            .into_iter()
            .zip(selected)
            .map(|((id, _), fill)| (id, fill))
            .collect()
    } else {
        BTreeMap::new()
    }
}

/// Conservative bounds of a filled datum triangle, including its surface base.
/// Reserve these alongside frames so triangles cannot overlap or touch, even when
/// their leaders and letter boxes are far apart.
fn fill_box(fill: &[P2]) -> [f64; 4] {
    fill.iter().fold(
        [
            f64::INFINITY,
            f64::INFINITY,
            f64::NEG_INFINITY,
            f64::NEG_INFINITY,
        ],
        |b, p| {
            [
                b[0].min(p[0]),
                b[1].min(p[1]),
                b[2].max(p[0]),
                b[3].max(p[1]),
            ]
        },
    )
}

/// Exact separating axes for a disc and a convex filled symbol. Edge normals
/// separate faces; vertex-to-centre axes separate the circle from corners.
fn circle_touches_polygon(centre: P2, radius: f64, polygon: &[P2]) -> bool {
    if polygon.len() < 3 {
        return false;
    }
    let edges = (0..polygon.len()).map(|i| {
        let (a, b) = (polygon[i], polygon[(i + 1) % polygon.len()]);
        [a[1] - b[1], b[0] - a[0]]
    });
    let vertices = polygon.iter().map(|p| [p[0] - centre[0], p[1] - centre[1]]);
    !edges.chain(vertices).any(|axis| {
        let reach = radius * axis[0].hypot(axis[1]);
        let middle = dot(centre, axis);
        let bounds = polygon
            .iter()
            .map(|p| dot(*p, axis))
            .fold([f64::INFINITY, f64::NEG_INFINITY], |b, x| {
                [b[0].min(x), b[1].max(x)]
            });
        bounds[1] < middle - reach || bounds[0] > middle + reach
    })
}

/// What a candidate must stay clear of.
struct Obstacles<'a> {
    page: &'a Page<'a>,
    own: String,
    /// The area reserved for its view and bands.
    area: Option<[f64; 4]>,
    /// Proven exterior paper beside a shoulder inside the whole-view box.
    exterior: Option<(&'a PlannedView, &'a super::interior::Proof)>,
    protect_triangles: bool,
    /// Datum shafts must clear text by the same half millimetre the final contact audit uses.
    label_gap: f64,
    /// A finish's leader and shelf keep this clear of any line they run alongside.
    parallel_gap: Option<f64>,
    triangles: Vec<Vec<P2>>,
    labels: Vec<[f64; 4]>,
    /// Filled scope-symbol discs, independent of label packing.
    rings: Vec<ScopeRing>,
    lines: Vec<[P2; 2]>,
    /// Filled peer arrowheads; scope bends must separate the flares as well as shafts.
    heads: Vec<[P2; 3]>,
    /// Control-frame shafts, independently of ordinary dimension witnesses.
    frame_leaders: Vec<[P2; 2]>,
}

impl Obstacles<'_> {
    /// How well *c* fits, best first: 0 clear of everything and inside its view's reserved area;
    /// 1 clear of everything, past the area; 2 on the sheet and off every label and frame, a line
    /// of it through a label or another view; 3 off every label and frame only; 4 neither;
    /// 5 a filled datum triangle overlaps or touches an earlier triangle.
    /// Within a clearance class, keep frames off existing leaders before counting
    /// line crossings. An unavoidable shaft through one label must not hide an
    /// avoidable frame over another leader (CTC-03's narrower CAD-sized frames).
    /// Datum attachment and common-label placement retain their existing ordering.
    fn grade(&self, c: &Candidate, best: Option<Grade>) -> Grade {
        let (clearance, text, _) = self.text_grade(c);
        // Clearance precedes crossings. A worse clearance, or a crossing count that
        // already ties the best at the same clearance, cannot replace that candidate.
        // Only losing candidates stop early; every saved best has its exact count.
        if best.is_some_and(|b| (clearance, text) > (b.0, b.1)) {
            return (clearance, text, 0);
        }
        let limit = best
            .filter(|b| (b.0, b.1) == (clearance, text))
            .map(|b| b.2);
        if limit == Some(0) {
            return (clearance, text, 0);
        }
        let triangle: Vec<_> = c
            .fills
            .iter()
            .flat_map(|f| (0..f.len()).map(|i| [f[i], f[(i + 1) % f.len()]]))
            .collect();
        let mut crossings = 0;
        for s in c.lines.iter().chain(&triangle) {
            // Every obstacle uses the same candidate segment. Reuse the router's exact
            // crossing/collinearity primitive with its direction computed once.
            let line = super::leaders::Line::new(*s);
            for t in &self.lines {
                if line.meets(*t) {
                    crossings += 1;
                    if limit.is_some_and(|n| crossings >= n) {
                        return (clearance, text, crossings);
                    }
                }
            }
        }
        (clearance, text, crossings)
    }

    fn text_grade(&self, c: &Candidate) -> Grade {
        let clearance = self.clearance_grade(c);
        let contacts = if clearance == 2 && c.frame_rule {
            self.frame_leaders
                .iter()
                .filter(|l| crosses(**l, c.label_box))
                .count()
        } else {
            0
        };
        (clearance, contacts + self.scope_contacts(c), 0)
    }

    // Scope symbols are real obstacles, but clearing one must not introduce a
    // worse frame/label collision. Among equally fitting placements avoid their
    // discs before comparing ordinary line crossings; unavoidable contacts are
    // still reported by the independent ink audit.
    fn scope_contacts(&self, c: &Candidate) -> usize {
        self.rings
            .iter()
            .filter(|ring| {
                let (centre, radius) = (ring.centre, ring.radius);
                let b = super::contacts::clear_box(c.label_box);
                let nearest = [centre[0].clamp(b[0], b[2]), centre[1].clamp(b[1], b[3])];
                (nearest[0] - centre[0]).hypot(nearest[1] - centre[1]) <= radius
                    || (c.ring_radius > 0.0
                        && (c.elbow[0] - centre[0]).hypot(c.elbow[1] - centre[1])
                            <= radius + c.ring_radius + super::contacts::TEXT_CLEAR)
                    || c.fills
                        .iter()
                        .any(|f| circle_touches_polygon(centre, radius, f))
                    || c.arrows
                        .iter()
                        .copied()
                        .map(arrow_vertices)
                        .any(|f| circle_touches_polygon(centre, radius, &f))
                    || c.lines.iter().any(|&[a, b]| {
                        // Ordinary route grading already counts a contact with
                        // this ring owner's shaft or shelf. Do not count the
                        // same owner twice; a chord meeting only the ring is
                        // still a separate obstacle contact.
                        if ring
                            .leader
                            .iter()
                            .any(|&owner| super::leaders::lines_meet([a, b], owner))
                        {
                            return false;
                        }
                        let delta = [b[0] - a[0], b[1] - a[1]];
                        let length2 = delta[0] * delta[0] + delta[1] * delta[1];
                        let t = if length2 > 0.0 {
                            ((centre[0] - a[0]) * delta[0] + (centre[1] - a[1]) * delta[1])
                                / length2
                        } else {
                            0.0
                        }
                        .clamp(0.0, 1.0);
                        (a[0] + t * delta[0] - centre[0]).hypot(a[1] + t * delta[1] - centre[1])
                            <= radius
                    })
            })
            .count()
    }

    fn clearance_grade(&self, c: &Candidate) -> u8 {
        // An incumbent from the historical template may still have the old
        // short shelf. It cannot override a live candidate with a clear ring.
        if c.ring_radius > 0.0
            && !c.lines.get(1).is_some_and(|[bend, end]| {
                *bend == c.elbow
                    && (end[1] - bend[1]).abs() < 1e-9
                    && (end[0] - bend[0]).abs()
                        >= c.ring_radius + super::contacts::TEXT_CLEAR - 1e-9
            })
        {
            return 4;
        }
        let frame = self.bounds_grade(c, c.label_box);
        if c.ring_radius > 0.0 {
            frame.max(self.bounds_grade(c, ring_box(c.elbow, c.ring_radius)))
        } else {
            frame
        }
    }

    fn bounds_grade(&self, c: &Candidate, b: [f64; 4]) -> u8 {
        // Filled symbols take precedence over soft label/leader contacts. In a
        // dense view every label tier may be obstructed, but another proven site
        // can still separate the triangles rather than keeping coincident ink.
        if c.fills
            .iter()
            .any(|f| self.triangles.iter().any(|t| polygons_touch(f, t)))
        {
            return 5;
        }
        let d = self.page.drawable();
        let on_sheet = b[0] >= d[0] && b[1] >= d[1] && b[2] <= d[2] && b[3] <= d[3];
        let grown = [b[0] - 0.5, b[1] - 0.5, b[2] + 0.5, b[3] + 0.5];
        let off_labels = self.labels.iter().all(|l| !boxes_overlap(grown, *l))
            && (!self.protect_triangles
                || c.fills.iter().all(|f| {
                    let b = fill_box(f);
                    let grown = [b[0] - 0.5, b[1] - 0.5, b[2] + 0.5, b[3] + 0.5];
                    self.labels.iter().all(|l| !boxes_overlap(grown, *l))
                }));
        if !off_labels {
            return 4;
        }
        let furniture = on_sheet
            && !boxes_overlap(b, self.page.title_block())
            && self.page.views().iter().all(|(id, v)| {
                if boxes_overlap(b, *v)
                    && *id == self.own
                    && let Some((view, proof)) = self.exterior
                {
                    proof.exterior_clear(view, b, &c.lines, &c.arrows)
                } else {
                    !boxes_overlap(b, *v)
                }
            });
        if !furniture {
            return 3;
        }
        let padded = |b: [f64; 4]| {
            let gap = self.label_gap;
            [b[0] - gap, b[1] - gap, b[2] + gap, b[3] + gap]
        };
        let lines_clear =
            self.page.views().iter().all(|(id, v)| {
                *id == self.own.as_str() || !c.lines.iter().any(|l| crosses(*l, *v))
            }) && !c.lines.iter().any(|l| crosses(*l, self.page.title_block()))
                && !self.lines.iter().any(|l| crosses(*l, padded(b)))
                && !c
                    .lines
                    .iter()
                    .any(|l| self.labels.iter().any(|x| crosses(*l, padded(*x))));
        // A finish's leader run close alongside a dimension or extension line reads as a
        // doubled line: as bad as a line through a label.
        let alongside = self.parallel_gap.is_some_and(|gap| {
            c.lines
                .iter()
                .any(|l| self.lines.iter().any(|t| runs_alongside(*l, *t, gap)))
        });
        if !lines_clear || alongside {
            return 2;
        }
        let inside = |q: &P2, a: [f64; 4]| {
            q[0] >= a[0] - 1e-6 && q[0] <= a[2] + 1e-6 && q[1] >= a[1] - 1e-6 && q[1] <= a[3] + 1e-6
        };
        let within = self.area.is_none_or(|a| {
            c.lines.iter().flatten().all(|q| inside(q, a))
                && [[b[0], b[1]], [b[2], b[3]]].iter().all(|q| inside(q, a))
        });
        if within { 0 } else { 1 }
    }
}

/// The strips a feature control frame tries after its own (`_gdt_retry_sides`).
fn retries(side: &str) -> [&'static str; 3] {
    match side {
        "above" => ["below", "right", "left"],
        "below" => ["above", "right", "left"],
        "left" => ["right", "above", "below"],
        _ => ["left", "above", "below"],
    }
}

/// The principal views' towards-the-viewer and up directions, third angle (`model::VIEWS`).
const PRINCIPALS: [(&str, [f64; 3], [f64; 3]); 3] = [
    ("front", [0.0, -1.0, 0.0], [0.0, 0.0, 1.0]),
    ("plan", [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]),
    ("side", [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]),
];

/// The part's lowered PMI as the layout reserves room for it ([`crate::layout::Gdt`],
/// [`crate::layout::Strips::reserve_gdt`]), *shown* saying which principal views the sheet
/// carries: each item's strip as lowering chose it, its site across the strip, and its glyph's
/// extents as [`plan`] places it (the leader and shelf of a frame or label, a datum's frame
/// centred on its line), with the room [`first_tier`] leaves for the arrowhead or triangle.
pub fn demand(analysis: &Analysis, shown: &dyn Fn(&str) -> bool) -> Vec<crate::layout::Gdt> {
    demand_with_spec(analysis, &Spec::default(), shown)
}

pub(crate) fn demand_with_spec(
    analysis: &Analysis,
    spec: &Spec,
    shown: &dyn Fn(&str) -> bool,
) -> Vec<crate::layout::Gdt> {
    let (mut items, _) = crate::pmi_lowering::lower_in(analysis, shown, spec.units);
    if items
        .iter()
        .any(|i| matches!(i.glyph, Glyph::FlagNote { .. }))
    {
        // The exact same reconciled list reserves and numbers the notes block. A feature
        // whose leader cannot be lowered still has its text there, without a dangling flag.
        let (requirements, _) = crate::pmi_lowering::sheet_requirements(analysis);
        let (notes, inactive, _) = crate::notes::reconcile(&requirements, analysis, spec);
        for item in &mut items {
            if let Glyph::FlagNote { number, .. } = &mut item.glyph {
                let id = inactive
                    .iter()
                    .find(|n| n.id == item.id)
                    .and_then(|n| {
                        if let crate::items::State::Covered { by } = &n.state {
                            Some(by.as_str())
                        } else {
                            None
                        }
                    })
                    .unwrap_or(&item.id);
                *number = notes.iter().position(|n| n.id == id).map_or(0, |i| i + 1);
            }
        }
        items.retain(|i| !matches!(i.glyph, Glyph::FlagNote { number: 0, .. }));
    }
    // Invariant: plan_with validates these same annotation texts before demand and placement.
    crate::label_text::annotations(&mut items, spec).expect("validated annotation wording");
    if spec.sheet.uncited_datums != Some(true) || spec.annotations.values().any(|a| a.omit) {
        items.retain(|item| datum_omission(analysis, spec, item).is_none());
    }
    let frames: BTreeMap<&str, Frame> = PRINCIPALS
        .iter()
        .map(|(name, toward, up)| (*name, Frame::looking(analysis, *toward, *up, [0.0; 2], 1.0)))
        .collect();
    items
        .iter()
        .map(|item| {
            let shape = Shape::of(&item.glyph);
            let datum = shape == Shape::Datum;
            let size = match &item.glyph {
                Glyph::Datum { letter, .. } => datum_frame(letter).size,
                Glyph::Label { text } => label(text).size,
                Glyph::FlagNote { number, .. } => flag_note(*number).size,
                Glyph::Finish { texture, .. } => finish_symbol(texture, spec.units).0.size,
                g => control_frame(g).0.size,
            };
            let horizontal = outward(item.side)[0] == 0.0;
            let f = &frames[item.view];
            let p = f.page(item.site);
            let o = f.outline();
            let depth = if datum {
                2.0 * datum_halves(item.side, size).1
            } else if horizontal {
                size[1]
            } else if shape == Shape::Finish {
                size[0]
            } else {
                SHELF + size[0]
            };
            crate::layout::Gdt {
                view: item.view,
                side: item.side,
                at: if horizontal { p[0] } else { p[1] },
                span: span(shape, item.side, size),
                ends: if horizontal {
                    [o[0], o[2]]
                } else {
                    [o[1], o[3]]
                },
                depth,
                lead: if datum {
                    0.9 * TRIANGLE + 0.8 * TEXT
                } else {
                    ARROW + 1.0
                },
            }
        })
        .collect()
}

/// The part's PMI lowered and placed around *views* on *sheet*, after the dimensions *dims*:
/// the items, and the problems met (lowering's, and what the placed items collide with). An
/// item whose view *spec* omits is fixed by restoring it.
pub fn plan(
    analysis: &Analysis,
    spec: &Spec,
    sheet: &PlannedSheet,
    views: &[PlannedView],
    dims: &[PlannedDimension],
) -> (Vec<PlannedGdt>, Vec<Problem>) {
    plan_anchored(
        analysis,
        spec,
        sheet,
        views,
        dims,
        None,
        &super::footprints::Cache::default(),
    )
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn plan_anchored(
    analysis: &Analysis,
    spec: &Spec,
    sheet: &PlannedSheet,
    views: &[PlannedView],
    dims: &[PlannedDimension],
    canonical: Option<&crate::model::Plan>,
    cache: &super::footprints::Cache,
) -> (Vec<PlannedGdt>, Vec<Problem>) {
    let reference = crate::decision_overrides::placement_reference(spec);
    let canonical = canonical.or(reference.as_deref());
    // A complete existing layout is also a candidate. Greedy improvements must not buy
    // fewer crossings by displacing later frames into text, other views or unreserved space.
    // Compare unique unordered pairs, since leader crossings can be reported both ways.
    let seed = plan_search(
        analysis,
        spec,
        sheet,
        views,
        dims,
        canonical,
        cache,
        Search::Seed,
        None,
    )
    // Invariant: The seed call supplies no incumbent bound, so search always returns its candidate.
    .expect("the seed search is never pruned");
    let contacts = |problems: &[Problem]| {
        problems
            .iter()
            .filter(|p| p.code.starts_with("annotation_") || p.code == "datum_symbol_overlap")
            .map(|p| {
                let mut pair = p.subjects.clone();
                pair.sort_unstable();
                (p.code.clone(), pair)
            })
            .collect::<std::collections::BTreeSet<_>>()
    };
    let before = contacts(&seed.1);
    let overlap_count = |problems: &[Problem]| {
        problems
            .iter()
            .filter(|p| p.code == "datum_symbol_overlap")
            .count()
    };
    let seed_overlaps = overlap_count(&seed.1);
    // Without datums, only the added dimension arrow shafts can change the datum-only
    // pass's clearance grading. If every seed label clears them, the same first-best
    // choice survives at each step; the pass would reproduce the seed.
    let datum_search_can_change = seed.0.iter().any(|g| g.kind == "datum_feature")
        || dims.iter().filter_map(|d| d.placed.as_ref()).any(|d| {
            d.arrows.iter().any(|a| {
                seed.0
                    .iter()
                    .filter_map(|g| g.placed.as_ref())
                    .any(|g| crosses(*a, g.label_box))
            })
        });
    if seed.0.iter().all(|g| g.placed.is_none()) {
        return seed;
    }
    // Preserve the actual old arrangement as the contact reference. Triangle
    // reservations belong to the corrective searches, never to that seed.
    // An already illegal seed needs symbol separation before soft contacts:
    // try ordinary placement first, reserving sites jointly only if it cannot
    // separate the triangles. Keep every resulting warning visible.
    // Keep the previous complete compact arrangement as a candidate too.
    // Its triangles are checked independently: an already legal, clearer
    // drawing must not be lost when the new attachment choices are expanded.
    let searches = [
        Search::Baseline,
        Search::All,
        Search::Datums,
        Search::Separate,
    ];
    let score = |candidate: &(Vec<PlannedGdt>, Vec<Problem>)| {
        let datums: BTreeSet<_> = candidate
            .0
            .iter()
            .filter(|g| g.kind == "datum_feature")
            .map(|g| &g.id)
            .collect();
        (
            overlap_count(&candidate.1),
            candidate
                .1
                .iter()
                .filter(|p| {
                    p.code == "annotation_leader_crossing"
                        && p.subjects.iter().any(|id| datums.contains(id))
                })
                .count(),
            contacts(&candidate.1).len(),
        )
    };
    let datum_length = |candidate: &(Vec<PlannedGdt>, Vec<Problem>)| -> f64 {
        candidate
            .0
            .iter()
            .filter(|g| g.kind == "datum_feature")
            .filter_map(|g| g.placed.as_ref())
            .flat_map(|p| &p.lines)
            .map(|[a, b]| (b[0] - a[0]).hypot(b[1] - a[1]))
            .sum()
    };
    let mut best_score = score(&seed);
    let mut best_length = datum_length(&seed);
    let mut best = seed;
    let mut original = true;
    for search in searches {
        if search == Search::Separate && (seed_overlaps == 0 || best_score.0 == 0) {
            continue;
        }
        if search == Search::Datums && !datum_search_can_change {
            continue;
        }
        if let Some(compact) = plan_search(
            analysis,
            spec,
            sheet,
            views,
            dims,
            canonical,
            cache,
            search,
            (seed_overlaps == 0).then_some(&before),
        ) && (contacts(&compact.1).is_subset(&before)
            || overlap_count(&compact.1) < seed_overlaps)
        {
            let grade = score(&compact);
            let length = datum_length(&compact);
            if grade < best_score
                || (grade == best_score && (original || length < best_length - 1e-6))
            {
                best = compact;
                best_score = grade;
                best_length = length;
                original = false;
            }
            // Try the datum-only arrangement too if a legal full arrangement
            // still crosses dimensions. Keep the shortest equally clear arrangement, and
            // stop once the datum symbols and their leaders are both clear. The
            // boundary-only baseline must still compete with the local search:
            // equal contacts do not justify retaining a much longer leader.
            if (search != Search::Baseline || best_length <= 1e-6)
                && best_score.0 == 0
                && best_score.1 == 0
            {
                return best;
            }
        }
    }
    // Keep the existing search loop unchanged for cited-only drawings. Only new,
    // uncited output with remaining contacts needs exact narrow-gap trials.
    if (best_score.0 != 0 || best_score.1 != 0)
        && matches!(&analysis.pmi, Some(crate::pmi::Reading::Read(report)) if report.records.iter().any(|r| r.category == crate::pmi::Category::Datum && !report.records.iter().any(|t| t.category == crate::pmi::Category::GeometricTolerance && t.datum_refs.iter().any(|d| d.trim() == r.label.trim()))))
        && let Some(candidate) = plan_search(
            analysis,
            spec,
            sheet,
            views,
            dims,
            canonical,
            cache,
            Search::Uncited,
            (seed_overlaps == 0).then_some(&before),
        )
        && (contacts(&candidate.1).is_subset(&before)
            || overlap_count(&candidate.1) < seed_overlaps)
    {
        let grade = score(&candidate);
        if grade < best_score
            || (grade == best_score && datum_length(&candidate) < best_length - 1e-6)
        {
            return candidate;
        }
    }
    best
}

pub(super) fn translated(mut p: GdtPlaced, delta: P2) -> GdtPlaced {
    use crate::placement_intent::{move_box, move_point};
    move_point(&mut p.tip, delta);
    move_box(&mut p.label_box, delta);
    for line in p
        .lines
        .iter_mut()
        .chain(&mut p.arrows)
        .chain(&mut p.strokes)
    {
        for q in line {
            move_point(q, delta);
        }
    }
    for arc in &mut p.arcs {
        if delta != [0.0, 0.0] {
            arc[0] += delta[0];
            arc[1] += delta[1];
        }
    }
    for fill in &mut p.fills {
        for q in fill {
            move_point(q, delta);
        }
    }
    for t in p.letters.iter_mut().chain(&mut p.runs) {
        move_point(&mut t.at, delta);
    }
    p
}

#[derive(Clone, Copy, PartialEq)]
enum Search {
    Seed,
    Datums,
    All,
    Separate,
    Baseline,
    Uncited,
}

#[allow(clippy::too_many_arguments)]
fn plan_search(
    analysis: &Analysis,
    spec: &Spec,
    sheet: &PlannedSheet,
    views: &[PlannedView],
    dims: &[PlannedDimension],
    canonical: Option<&crate::model::Plan>,
    cache: &super::footprints::Cache,
    search: Search,
    allowed: Option<&BTreeSet<(String, Vec<String>)>>,
) -> Option<(Vec<PlannedGdt>, Vec<Problem>)> {
    let compact = search != Search::Seed;
    let protect = compact && search != Search::Baseline;
    let recess_frames = dims.iter().any(|d| {
        d.measurements
            .iter()
            .any(|m| m.feature.starts_with("f:section_recess:"))
    });
    let shown = |name: &str| views.iter().any(|v| v.id == format!("v:{name}"));
    let (mut items, mut problems) = crate::pmi_lowering::lower_in(analysis, &shown, spec.units);
    // The exact same reconciled list reserves and numbers the notes block. A feature
    // whose leader cannot be lowered still has its text there, without a dangling flag.
    let (requirements, _) = crate::pmi_lowering::sheet_requirements(analysis);
    let (notes, inactive, _) = crate::notes::reconcile(&requirements, analysis, spec);
    for item in &mut items {
        if let Glyph::FlagNote { number, .. } = &mut item.glyph {
            let id = inactive
                .iter()
                .find(|n| n.id == item.id)
                .and_then(|n| {
                    if let crate::items::State::Covered { by } = &n.state {
                        Some(by.as_str())
                    } else {
                        None
                    }
                })
                .unwrap_or(&item.id);
            *number = notes.iter().position(|n| n.id == id).map_or(0, |i| i + 1);
        }
    }
    items.retain(|i| !matches!(i.glyph, Glyph::FlagNote { number: 0, .. }));
    // Invariant: plan_with validates these same annotation texts before demand and placement.
    crate::label_text::annotations(&mut items, spec).expect("validated annotation wording");
    if items.is_empty() {
        return Some((Vec::new(), problems));
    }
    let frames: BTreeMap<&str, Frame> = views
        .iter()
        .filter_map(|v| {
            let name = v.id.strip_prefix("v:")?;
            ["front", "plan", "side"]
                .contains(&name)
                .then(|| (name, Frame::new(analysis, v)))
        })
        .collect();
    let page = Page::new(analysis, sheet, views);
    let on_sheet = |view: &str| {
        views
            .iter()
            .find(|v| v.id == view)
            .map_or(sheet.number == 1, |v| v.sheet == sheet.number)
    };
    for item in &mut items {
        if let Some(p) = spec
            .annotations
            .get(&item.id)
            .and_then(|a| a.place.as_ref())
            .filter(|p| !super::hole_marks::pinned_on_mark(analysis, item, p))
        {
            if let Some(v) = p.view.as_deref() {
                item.view = match v {
                    "plan" => "plan",
                    "side" => "side",
                    _ => "front",
                };
            }
            if let Some(side) = p.side {
                item.side = side.name();
            } else if matches!(item.glyph, Glyph::Datum { .. } | Glyph::Finish { .. })
                && let Some(crate::pmi::Reading::Read(report)) = &analysis.pmi
                && let Some(record) = report.records.iter().find(|r| r.source_id == item.source)
                && let Some((_, sides)) = placement_choices(item, record, views)
                    .into_iter()
                    .find(|(view, _)| *view == item.view)
            {
                item.side = sides[0];
            }
        }
    }
    // Each site's position across its strip.
    let across = |i: &Lowered| -> f64 {
        frames.get(i.view).map_or(0.0, |f| {
            let p = f.page(i.site);
            if outward(i.side)[0] == 0.0 {
                p[0]
            } else {
                p[1]
            }
        })
    };
    // A frame above or below its view runs right of its leader, so the rightmost leader takes
    // the nearest tier and no shaft runs through a frame placed before it. Leaders that stand
    // together keep the reading's order (its sources, as text), as before items were named by
    // their identity.
    // A plane has one outward side; a cylinder can try both silhouettes. Place
    // the constrained planar datum first in the compact search so a movable
    // cylinder does not consume its only clear shoulder band.
    items.sort_by(|a, b| {
        let order = if outward(a.side)[0] == 0.0 {
            across(b).total_cmp(&across(a))
        } else {
            across(a).total_cmp(&across(b))
        };
        (
            !spec
                .annotations
                .get(&a.id)
                .and_then(|a| a.place.as_ref())
                .is_some_and(|p| p.pinned),
            a.view,
            protect && !matches!(&a.glyph, Glyph::Datum { surface, .. } if surface == "plane"),
            a.side,
            finish_freedom(a),
        )
            .cmp(&(
                !spec
                    .annotations
                    .get(&b.id)
                    .and_then(|a| a.place.as_ref())
                    .is_some_and(|p| p.pinned),
                b.view,
                protect && !matches!(&b.glyph, Glyph::Datum { surface, .. } if surface == "plane"),
                b.side,
                finish_freedom(b),
            ))
            .then(order)
            .then(a.source.cmp(&b.source))
    });
    let mut labels: Vec<[f64; 4]> = dims
        .iter()
        .filter_map(|d| d.placed.as_ref().map(|p| p.label_box))
        .collect();
    let mut rings = Vec::new();
    let mut lines: Vec<[P2; 2]> = dims
        .iter()
        .filter_map(|d| d.placed.as_ref())
        .flat_map(|p| {
            p.lines
                .iter()
                .chain(p.arrows.iter().filter(|_| compact))
                .copied()
        })
        .collect();
    let mut heads: Vec<_> = dims
        .iter()
        .filter_map(|d| d.placed.as_ref())
        .flat_map(|p| p.arrows.iter().copied().map(arrow_vertices))
        .collect();
    let control_ids: BTreeSet<_> = items
        .iter()
        .filter(|i| matches!(i.glyph, Glyph::ControlFrame { .. }))
        .map(|i| i.id.clone())
        .collect();
    let mut frame_leaders: Vec<_> = dims
        .iter()
        .filter(|d| control_ids.contains(&d.id))
        .filter_map(|d| d.placed.as_ref())
        .flat_map(|p| p.lines.iter().copied())
        .collect();
    let exterior = if protect && items.iter().any(|i| matches!(i.glyph, Glyph::Datum { .. })) {
        super::interior::exterior_proofs(analysis, views)
    } else {
        BTreeMap::new()
    };
    let mut reservations = if search == Search::Separate {
        separated_sites(analysis, spec, &items, &frames, &page)
    } else {
        BTreeMap::new()
    };
    let mut out = Vec::new();
    let mut triangles = Vec::new();
    for item in items {
        reservations.remove(&item.id);
        let shape = Shape::of(&item.glyph);
        let datum = shape == Shape::Datum;
        let (laid, cells) = match &item.glyph {
            Glyph::Datum { letter, .. } => (datum_frame(letter), vec![letter.clone()]),
            Glyph::Label { text } => (label(text), vec![text.clone()]),
            Glyph::FlagNote { number, .. } => (flag_note(*number), vec![number.to_string()]),
            Glyph::Finish { texture, .. } => finish_symbol(texture, spec.units),
            g => control_frame(g),
        };
        let modifiers: Vec<String> = match &item.glyph {
            Glyph::ControlFrame {
                all_around,
                all_over,
                ..
            } => [("all_around", *all_around), ("all_over", *all_over)]
                .into_iter()
                .filter(|(_, on)| *on)
                .map(|(m, _)| m.to_string())
                .collect(),
            Glyph::Datum { .. }
            | Glyph::Label { .. }
            | Glyph::FlagNote { .. }
            | Glyph::Finish { .. } => Vec::new(),
        };
        let mut planned = PlannedGdt {
            from_spec: if spec
                .annotations
                .get(&item.id)
                .is_some_and(|a| a.text.is_some())
            {
                vec!["text".into()]
            } else {
                Vec::new()
            },
            id: item.id.clone(),
            kind: match item.glyph {
                Glyph::Datum { .. } => "datum_feature",
                Glyph::Label { .. } | Glyph::FlagNote { .. } => "label",
                Glyph::ControlFrame { .. } => "control_frame",
                Glyph::Finish { .. } => "surface_finish",
            }
            .into(),
            view: format!("v:{}", item.view),
            side: item.side.into(),
            source: item.source.clone(),
            faces: item.faces.clone(),
            label: crate::items::frame_label(&cells),
            cells,
            modifiers,
            // A datum or control the Spec authors is never a default ([`crate::spec_gdt`]).
            default: !spec.annotations.contains_key(&item.id)
                && !item.source.starts_with(crate::spec_gdt::SOURCE_PREFIX),
            basis: item.basis.clone(),
            // Shown once placed; else its view is not drawn.
            state: State::not_drawable("pmi_not_drawn"),
            placed: None,
        };
        if let Some(reason) = datum_omission(analysis, spec, &item) {
            planned.basis += &format!("; {reason}");
            if reason == crate::spec_gdt::UNCITED_DATUM {
                planned.state = State::not_drawable("datum_not_drawn");
                problems.push(Problem {
                    id: format!("p:datum_not_drawn:{}", item.id),
                    code: "datum_not_drawn".into(),
                    severity: "info".into(),
                    message: format!(
                        "Datum {} is declared but not drawn: no control frame cites it and no dimension measures from it. Set sheet/uncited_datums to true to draw every declared datum.",
                        planned.label
                    ),
                    subjects: vec![item.id.clone()],
                    ..Default::default()
                });
            } else {
                planned.state = State::OmittedByUser;
            }
            out.push(planned);
            continue;
        }
        if spec.annotations.get(&item.id).is_some_and(|a| a.omit) {
            planned.state = State::OmittedByUser;
            planned.basis += "; omitted by the spec";
            out.push(planned);
            continue;
        }
        let intent = spec
            .annotations
            .get(&item.id)
            .and_then(|a| a.place.as_ref());
        let authored = authored(intent);
        if intent.is_some() {
            planned.basis += "; placed relative to its anchor by the spec";
        }
        let Some(frame) = frames.get(item.view) else {
            problems.push(Problem {
                id: format!("p:pmi_not_drawn:{}", item.id),
                code: "pmi_not_drawn".into(),
                severity: "warning".into(),
                message: format!(
                    "{} is drawn in the {} view, which is not on the sheet; it stays in the plan undrawn. Restore the view (remove views/{}/omit).",
                    crate::wording::capital(&crate::wording::item(
                        &item.id,
                        "",
                        &planned.cells.join(" ")
                    )),
                    item.view,
                    item.view
                ),
                subjects: vec![item.id.clone()],
                fix: if spec.views.get(item.view).is_some_and(|v| v.omit) {
                    vec![Op::remove(format!("views/{}/omit", item.view))]
                } else {
                    Vec::new()
                },
                ..Default::default()
            });
            out.push(planned);
            continue;
        };
        if intent.is_some_and(crate::placement_intent::automatic_pin)
            && let Some(base) = canonical
            && let Some(g) = base.gdt.iter().find(|g| {
                g.id == item.id && (g.view == planned.view || super::hole_marks::attached(g))
            })
            && let Some(delta) = crate::placement_intent::anchor_delta(base, views, &g.view)
            && let Some(mut p) = g.placed.clone()
        {
            p = translated(p, delta);
            extend_scope_shelf(&mut p, &g.modifiers);
            labels.push(p.label_box);
            reserve_ring(&mut rings, &planned.modifiers, &p);
            if protect {
                labels.extend(p.fills.iter().map(|f| fill_box(f)));
                triangles.extend(p.fills.iter().cloned());
            }
            lines.extend(p.lines.iter().copied());
            heads.extend(p.arrows.iter().copied().map(arrow_vertices));
            if matches!(item.glyph, Glyph::ControlFrame { .. }) {
                frame_leaders.extend(p.lines.iter().copied());
            }
            planned.side = g.side.clone();
            planned.view.clone_from(&g.view);
            if super::hole_marks::attached(g) {
                planned.basis.clone_from(&g.basis);
            }
            planned.state = State::Shown;
            planned.placed = Some(p);
            out.push(planned);
            continue;
        }
        let own = format!("v:{}", item.view);
        let ink: Vec<[P2; 2]> = dims
            .iter()
            .filter(|d| d.view == own)
            .filter_map(|d| d.placed.as_ref())
            .flat_map(|p| {
                let b = p.label_box;
                p.lines
                    .iter()
                    .chain(&p.arrows)
                    .copied()
                    .chain([[[b[0], b[1]], [b[2], b[3]]]])
                    .collect::<Vec<_>>()
            })
            .collect();
        let obstacles = Obstacles {
            page: &page,
            own: own.clone(),
            area: page.area(item.view),
            exterior: datum
                .then(|| {
                    views
                        .iter()
                        .find(|v| v.id == own)
                        .and_then(|v| exterior.get(&v.id).map(|proof| (v, proof.as_ref())))
                })
                .flatten(),
            protect_triangles: protect,
            label_gap: if datum {
                super::contacts::TEXT_CLEAR
            } else {
                0.0
            },
            parallel_gap: (shape == Shape::Finish).then_some(FINISH_PARALLEL_GAP),
            triangles: triangles
                .iter()
                .chain(reservations.values())
                .cloned()
                .collect(),
            labels: labels.clone(),
            rings: rings.clone(),
            lines: lines.clone(),
            heads: heads.clone(),
            frame_leaders: frame_leaders.clone(),
        };
        let scope_footprints = (ring_radius(&planned.modifiers) > 0.0)
            .then(|| {
                views
                    .iter()
                    .find(|v| v.id == own)
                    .map(|v| cache.get(analysis, v))
            })
            .flatten();
        let sides: Vec<&str> = if shape != Shape::Frame || intent.is_some_and(|p| p.side.is_some())
        {
            vec![item.side]
        } else {
            std::iter::once(item.side)
                .chain(retries(item.side))
                .collect()
        };
        let mut sites: Vec<Site<'_>> = std::iter::once(item.site)
            .chain(item.alternatives.iter().copied())
            .map(|s| (frame.page(s), item.side, None))
            .collect();
        if compact && datum {
            sites = datum_sites(analysis, &item, frame, authored);
        }
        // A cylinder's finish may stand at any proven site on either silhouette (or, head-on,
        // either half of the face), each in the strip it faces: its own strip's first, the
        // other's only when they find no clear place; only the authored strip's when the Spec
        // names one. A dot reads on blank face: sites clear of the view's projected edges and
        // silhouettes (hidden ones too) by a millimetre past the dot come first in each strip.
        let face_on = matches!(item.glyph, Glyph::Finish { face_on: true, .. });
        let cylinder_finish =
            matches!(&item.glyph, Glyph::Finish { surface, .. } if surface == "cylinder");
        if cylinder_finish {
            let requested = intent.and_then(|p| p.side).map(|s| s.name());
            sites = cylinder_sites_of(analysis, &item, frame, requested, face_on);
            let proofs = if face_on {
                super::interior::exterior_proofs(analysis, views)
            } else {
                BTreeMap::new()
            };
            let view = views.iter().find(|v| v.id == own);
            let blank = |p: P2| match (view, proofs.get(&own)) {
                (Some(v), Some(proof)) => proof.point_clear(v, p, DOT + 1.0),
                _ => true,
            };
            sites.sort_by_key(|s| (s.1 != item.side, !blank(s.0)));
        }
        let tiers = |side: &str, tip: P2| {
            let pinned = intent.is_some_and(|p| p.pinned);
            let first = first_tier(
                shape,
                side,
                tip,
                frame.outline(),
                if pinned { &[] } else { &ink },
                laid.size,
            );
            let d = outward(side);
            let sign = if d[0] + d[1] < 0.0 { -1.0 } else { 1.0 };
            let step = step(shape, side, laid.size);
            let lane = intent.and_then(|p| p.lane).unwrap_or(0);
            let count = if intent.is_some_and(|p| p.pinned) {
                1
            } else {
                TIERS
            };
            (0..count)
                .map(move |k| first + sign * (k + lane) as f64 * step)
                .collect::<Vec<_>>()
        };
        // The best grade, then the shortest automatic datum leader; remaining
        // ties keep the original site, strip and tier order.
        let mut best: Option<Choice<'_>> = None;
        let mut ring_best: Option<Choice<'_>> = None;
        let tier_ink: &[[P2; 2]] = if search == Search::Uncited { &[] } else { &ink };
        // Exhaust the compact, face-to-first-lane choices before trying any outer tier.
        // A cylinder's finish exhausts its own strip (compact tiers, then outer ones) before the
        // other silhouette's, which it tries only when its own has no place clear of every label
        // and line: a place past the reserved area, uncrossed, still keeps its strip.
        let passes: &[(bool, Option<bool>)] = if cylinder_finish {
            &[
                (true, Some(true)),
                (false, Some(true)),
                (true, Some(false)),
                (false, Some(false)),
            ]
        } else {
            &[(true, None), (false, None)]
        };
        'search: for &(inside, own_strip) in passes {
            if own_strip == Some(false)
                && best
                    .as_ref()
                    .is_some_and(|b: &Choice<'_>| b.0.0 <= 1 && b.0.1 == 0)
            {
                break;
            }
            if inside
                && (!compact
                    || !(datum || shape == Shape::Finish || recess_frames && shape == Shape::Frame)
                    || authored)
            {
                continue;
            }
            for (n, (tip, site_side, extension)) in sites.iter().enumerate() {
                if own_strip.is_some_and(|own| (*site_side == item.side) != own) {
                    continue;
                }
                let choices = if datum || cylinder_finish {
                    vec![*site_side]
                } else {
                    sides.clone()
                };
                for side in choices {
                    let positions = if inside && datum {
                        // The uncited fallback lets exact obstacle grading test a narrow
                        // shoulder gap that the conservative first-stroke band rejects.
                        // All original sites and tiers are reused; crossings still lose.
                        inside_tiers(side, *tip, frame.outline(), laid.size, tier_ink, protect)
                    } else if inside {
                        // Frame ink can fit between the face and the first
                        // dimension lane too. Exact obstacle grading, including
                        // every label and witness, still decides whether it fits.
                        let d = outward(side);
                        let sign = d[0] + d[1];
                        let first = first_tier(shape, side, *tip, frame.outline(), &[], laid.size);
                        let outer =
                            first_tier(shape, side, *tip, frame.outline(), &ink, laid.size) * sign;
                        (0..TIERS)
                            .map(|k| first + sign * k as f64 * step(shape, side, laid.size))
                            .take_while(|p| p * sign < outer - 1e-6)
                            .collect()
                    } else {
                        tiers(side, *tip)
                    };
                    for pos in positions {
                        let mut anchor = *tip;
                        if let Some(along) = intent.and_then(|p| p.along) {
                            let o = frame.outline();
                            let k = usize::from(outward(side)[0] != 0.0);
                            anchor[k] = o[k] + along.fraction() * (o[k + 2] - o[k]);
                        }
                        let mut c = candidate(shape, anchor, side, pos, laid.size)
                            .with_ring(ring_radius(&planned.modifiers));
                        c.frame_rule = matches!(item.glyph, Glyph::ControlFrame { .. });
                        if datum && intent.and_then(|p| p.along).is_some() {
                            for fill in &mut c.fills {
                                for q in fill {
                                    q[0] += tip[0] - anchor[0];
                                    q[1] += tip[1] - anchor[1];
                                }
                            }
                        }
                        if intent.and_then(|p| p.along).is_some() {
                            if let Some(line) = c.lines.first_mut() {
                                line[0] = if datum {
                                    [
                                        line[0][0] + tip[0] - anchor[0],
                                        line[0][1] + tip[1] - anchor[1],
                                    ]
                                } else {
                                    *tip
                                };
                            }
                            for a in &mut c.arrows {
                                *a = placement::arrow(*tip, c.elbow);
                            }
                        }
                        if datum && intent.and_then(|p| p.along).is_some() {
                            let [apex, near] = c.lines[0];
                            let u = outward(side);
                            let lateral = (near[0] - apex[0]) * u[1] - (near[1] - apex[1]) * u[0];
                            if lateral.abs() > 1e-6 {
                                let reach = dot([near[0] - apex[0], near[1] - apex[1]], u);
                                let stub = [
                                    apex[0] + u[0] * (0.8 * TEXT).min(reach / 2.),
                                    apex[1] + u[1] * (0.8 * TEXT).min(reach / 2.),
                                ];
                                c.lines = vec![[apex, stub], [stub, near]];
                            }
                        }
                        if let Some(line) = extension {
                            c.lines.push(*line);
                        }
                        if face_on {
                            // Inside the outline the leader ends in a dot on the face.
                            c.arrows.clear();
                            c.fills = vec![dot_at(c.lines[0][0])];
                        }
                        if c.ring_radius > 0.0 && !intent.is_some_and(|p| p.pinned) {
                            let expanded =
                                clear_ring_bend(c.clone(), &obstacles, scope_footprints.as_deref());
                            let grade = if matches!(search, Search::All | Search::Baseline) {
                                obstacles.grade(&expanded, None)
                            } else {
                                obstacles.text_grade(&expanded)
                            };
                            if ring_best.as_ref().is_none_or(|b| grade < b.0) {
                                ring_best = Some((grade, side, expanded, *tip, n));
                            }
                        }
                        let compact_datum = protect && datum && !authored;
                        let shorter = compact_datum
                            && best
                                .as_ref()
                                .is_some_and(|b| c.leader_length() < b.2.leader_length() - 1e-6);
                        let g = if intent.is_some_and(|p| p.pinned) {
                            (0, 0, 0)
                        } else if matches!(search, Search::All | Search::Baseline)
                            || (compact && datum)
                        {
                            // A shorter equal-grade datum can now win the tie, so
                            // its crossings must be exact rather than pruned at a tie.
                            obstacles.grade(
                                &c,
                                if shorter {
                                    None
                                } else {
                                    best.as_ref().map(|b| b.0)
                                },
                            )
                        } else {
                            obstacles.text_grade(&c)
                        };
                        if best
                            .as_ref()
                            .is_none_or(|b| g < b.0 || (shorter && g == b.0))
                        {
                            // The normal shaft clearance is the shortest possible
                            // datum leader. A longer clear route must still try other
                            // proven face sites before it can win on site order alone.
                            let shortest = c.leader_length() <= 0.8 * TEXT + 1e-6;
                            best = Some((g, side, c, *tip, n));
                            if g == (0, 0, 0) && (!compact_datum || shortest) {
                                break 'search;
                            }
                        }
                    }
                }
            }
        }
        // Exhaust ordinary shelves on every strip before accepting an expanded
        // bend. An equally clear longer shelf must not preempt a proven exit on
        // a later strip and displace its neighbouring callouts.
        if let Some(expanded) = ring_best
            && best.as_ref().is_none_or(|b| expanded.0 < b.0)
        {
            best = Some(expanded);
        }
        // A dimension placement does not evict clear, unchanged GD&T ink merely
        // because another greedy search finds a shorter leader. Compare its
        // transported incumbent using the same exact obstacle grading.
        if intent.is_none()
            && !crate::placement_intent::has_pins(spec)
            && let Some(base) = canonical
            && let Some(g) = base.gdt.iter().find(|g| {
                g.id == item.id
                    && g.view == planned.view
                    && g.cells == planned.cells
                    && !super::hole_marks::attached(g)
            })
            && base.views.iter().any(|old| {
                old.id == g.view
                    && views.iter().any(|v| {
                        v.id == old.id
                            && v.scale == old.scale
                            && v.direction == old.direction
                            && v.up == old.up
                    })
            })
            && let Some(delta) = crate::placement_intent::anchor_delta(base, views, &g.view)
            && let Some(p) = g.placed.clone()
        {
            let mut p = translated(p, delta);
            extend_scope_shelf(&mut p, &g.modifiers);
            let candidate = Candidate {
                frame_rule: matches!(item.glyph, Glyph::ControlFrame { .. }),
                lines: p.lines.clone(),
                arrows: p.arrows.clone(),
                fills: p.fills.clone(),
                label_box: p.label_box,
                origin: [0.; 2],
                elbow: p.lines.first().map_or([0.; 2], |l| l[1]),
                ring_radius: ring_radius(&g.modifiers),
            };
            let grade = obstacles.grade(&candidate, None);
            if grade.0 <= 1
                && grade.1 == 0
                && grade.2 == 0
                && best
                    .as_ref()
                    .is_none_or(|b| grade <= obstacles.grade(&b.2, None))
            {
                labels.push(p.label_box);
                reserve_ring(&mut rings, &g.modifiers, &p);
                if protect {
                    labels.extend(p.fills.iter().map(|f| fill_box(f)));
                    triangles.extend(p.fills.iter().cloned());
                }
                lines.extend(p.lines.iter().copied());
                heads.extend(p.arrows.iter().copied().map(arrow_vertices));
                if matches!(item.glyph, Glyph::ControlFrame { .. }) {
                    frame_leaders.extend(p.lines.iter().copied());
                }
                planned.side.clone_from(&g.side);
                planned.state = State::Shown;
                planned.placed = Some(p);
                out.push(planned);
                continue;
            }
        }
        // Invariant: The finite tier loop always evaluates its first candidate without pruning.
        let (_, side, chosen, tip, alternative) = best.expect("a tier");
        if sites[alternative].2.is_some() {
            planned.basis += "; on an extension of its planar face beyond the view outline";
        } else if alternative > 0 {
            planned.basis +=
                "; at another proven site on its face, as the first has no clear place";
        }
        if side != item.side {
            planned.basis += &format!(
                "; its {} strip has no clear place, so it stands {side} the view",
                item.side
            );
            planned.side = side.into();
        }
        let shift = |p: P2| [p[0] + chosen.origin[0], p[1] + chosen.origin[1]];
        let moved = |t: &GdtText| GdtText {
            text: t.text.clone(),
            at: shift(t.at),
            size: t.size,
        };
        let mut arcs: Vec<[f64; 5]> = laid
            .arcs
            .iter()
            .map(|a| {
                let c = shift([a[0], a[1]]);
                [c[0], c[1], a[2], a[3], a[4]]
            })
            .collect();
        for m in &planned.modifiers {
            arcs.push(circle(chosen.elbow, RING));
            if m == "all_over" {
                arcs.push(circle(chosen.elbow, 1.7 * RING));
            }
        }
        labels.push(chosen.label_box);
        if chosen.ring_radius > 0.0 {
            rings.push(ScopeRing {
                centre: chosen.elbow,
                radius: chosen.ring_radius,
                leader: chosen.lines.clone(),
            });
        }
        if protect {
            labels.extend(chosen.fills.iter().map(|f| fill_box(f)));
            triangles.extend(chosen.fills.iter().cloned());
        }
        lines.extend(chosen.lines.iter().copied());
        heads.extend(chosen.arrows.iter().copied().map(arrow_vertices));
        if chosen.frame_rule {
            frame_leaders.extend(chosen.lines.iter().copied());
        }
        planned.state = State::Shown;
        planned.placed = Some(GdtPlaced {
            tip,
            lines: chosen.lines,
            arrows: chosen.arrows,
            label_box: chosen.label_box,
            strokes: laid
                .strokes
                .iter()
                .map(|[a, b]| [shift(*a), shift(*b)])
                .collect(),
            frame_strokes: laid.frame_strokes.unwrap_or(usize::MAX),
            arcs,
            fills: chosen.fills,
            letters: laid.letters.iter().map(moved).collect(),
            runs: laid.runs.iter().map(moved).collect(),
        });
        // This contact cannot be undone by placing later items. Stop a search that the
        // complete-arrangement guard would reject, before searching the remaining items.
        if let Some(allowed) = allowed.filter(|_| on_sheet(&planned.view)) {
            // Invariant: The preceding placement assignment set planned.placed to Some.
            let p = planned.placed.as_ref().expect("just placed");
            for (id, lines, arrows) in dims
                .iter()
                .filter(|d| on_sheet(&d.view))
                .filter_map(|d| d.placed.as_ref().map(|p| (&d.id, &p.lines, &p.arrows)))
                .chain(
                    out.iter()
                        .filter(|g: &&PlannedGdt| on_sheet(&g.view))
                        .filter_map(|g| g.placed.as_ref().map(|p| (&g.id, &p.lines, &p.arrows))),
                )
            {
                if *id == planned.id {
                    continue;
                }
                let mut pair = vec![planned.id.clone(), id.clone()];
                pair.sort_unstable();
                if !allowed.contains(&("annotation_leader_crossing".into(), pair))
                    && p.lines.iter().any(|s| {
                        lines
                            .iter()
                            .chain(arrows)
                            .any(|t| super::leaders::lines_meet(*s, *t))
                    })
                {
                    return None;
                }
            }
        }
        out.push(planned);
    }
    out.sort_by(|a, b| a.id.cmp(&b.id));
    // What the placed items collide with, as the dimensions' collisions are judged; the
    // dimensions' own are reported by them.
    let mut all: Vec<PlannedDimension> = dims.to_vec();
    all.extend(out.iter().filter_map(proxy));
    problems.extend(
        placement::collisions_cached(analysis, &all, sheet, views, cache)
            .into_iter()
            .filter(|p| p.subjects.iter().any(|s| s.starts_with("pmi:"))),
    );
    problems.extend(symbol_collisions(out.iter().filter(|g| on_sheet(&g.view))));
    Some((out, problems))
}

/// Datum *letter*'s symbol with its triangle's base centred at *tip* and its line running out
/// toward *side*, its frame in tier *tier* (0 nearest, as [`first_tier`] spaces it from a tip).
pub(super) fn datum_at(letter: &str, tip: P2, side: &str, tier: usize) -> GdtPlaced {
    let d = outward(side);
    let laid = datum_frame(letter);
    let size = laid.size;
    let reach = 0.9 * TRIANGLE
        + 0.8 * TEXT
        + datum_halves(side, size).1
        + tier as f64 * step(Shape::Datum, side, size);
    let pos = dot(tip, d) + reach;
    let c = candidate(
        Shape::Datum,
        tip,
        side,
        if d[0] + d[1] < 0.0 { -pos } else { pos },
        size,
    );
    let shift = |p: P2| [p[0] + c.origin[0], p[1] + c.origin[1]];
    let moved = |t: &GdtText| GdtText {
        text: t.text.clone(),
        at: shift(t.at),
        size: t.size,
    };
    GdtPlaced {
        tip,
        lines: c.lines,
        arrows: c.arrows,
        label_box: c.label_box,
        strokes: laid
            .strokes
            .iter()
            .map(|[a, b]| [shift(*a), shift(*b)])
            .collect(),
        frame_strokes: laid.frame_strokes.unwrap_or(usize::MAX),
        arcs: laid
            .arcs
            .iter()
            .map(|a| {
                let c = shift([a[0], a[1]]);
                [c[0], c[1], a[2], a[3], a[4]]
            })
            .collect(),
        fills: c.fills,
        letters: laid.letters.iter().map(moved).collect(),
        runs: laid.runs.iter().map(moved).collect(),
    }
}

/// How free a surface finish is to move along its strip: its count of other proven sites there
/// (none for anything else). In one strip the finish with fewest places is placed first, so a
/// narrow face (a flange) keeps its only site before a long one takes the paper beside it.
fn finish_freedom(item: &Lowered) -> (bool, usize) {
    match item.glyph {
        Glyph::Finish { .. } => (true, item.alternatives.len()),
        _ => (false, 0),
    }
}

/// The filled dot a leader ends in at *c*, as a polygon.
fn dot_at(c: P2) -> Vec<P2> {
    (0..12)
        .map(|i| {
            let a = f64::from(i) * std::f64::consts::PI / 6.0;
            [c[0] + DOT * a.cos(), c[1] + DOT * a.sin()]
        })
        .collect()
}

/// Datum triangles must not overlap or even touch. Separating-axis testing also
/// detects containment; leader intersections and letter boxes cannot see it.
fn polygons_touch(a: &[P2], b: &[P2]) -> bool {
    if a.len() < 3 || b.len() < 3 {
        return false;
    }
    ![a, b].iter().any(|polygon| {
        (0..polygon.len()).any(|i| {
            let (p, q) = (polygon[i], polygon[(i + 1) % polygon.len()]);
            let normal = [p[1] - q[1], q[0] - p[0]];
            let interval = |points: &[P2]| {
                points
                    .iter()
                    .map(|p| dot(*p, normal))
                    .fold([f64::INFINITY, f64::NEG_INFINITY], |r, x| {
                        [r[0].min(x), r[1].max(x)]
                    })
            };
            let (a, b) = (interval(a), interval(b));
            a[1] < b[0] - 1e-9 || b[1] < a[0] - 1e-9
        })
    })
}

/// A drawn frame citing a datum whose symbol the drawing does not show (#224): the frame cannot
/// be read without it, so each such frame is said once, naming the datums it lacks
/// (`frame_datum_not_drawn`, a warning). Why each datum is missing is its own problem
/// (`pmi_not_lowered`, `pmi_not_drawn`, an omission). Replaces any earlier statement.
pub(crate) fn cited_undrawn(plan: &mut crate::model::Plan) {
    plan.problems.retain(|p| p.code != "frame_datum_not_drawn");
    let drawn: BTreeSet<&str> = plan
        .gdt
        .iter()
        .filter(|g| g.kind == "datum_feature" && g.state == State::Shown)
        .filter_map(|g| g.cells.first().map(String::as_str))
        .collect();
    let mut found = Vec::new();
    for g in plan
        .gdt
        .iter()
        .filter(|g| g.kind == "control_frame" && g.state == State::Shown)
    {
        let mut missing: Vec<&str> = g
            .cells
            .iter()
            .skip(2)
            .map(String::as_str)
            .filter(|d| !drawn.contains(d))
            .collect();
        missing.dedup();
        if missing.is_empty() {
            continue;
        }
        found.push(Problem {
            id: format!("p:frame_datum_not_drawn:{}", g.id),
            code: "frame_datum_not_drawn".into(),
            severity: "warning".into(),
            message: format!(
                "The feature control frame {} cites datum{} {} that the drawing does not show, so it cannot be read in full. Draw the datum{} (see why {} not drawn) or review the frame manually.",
                g.label,
                if missing.len() > 1 { "s" } else { "" },
                missing.join(", "),
                if missing.len() > 1 { "s" } else { "" },
                if missing.len() > 1 { "they are" } else { "it is" },
            ),
            subjects: vec![g.id.clone()],
            refs: missing.iter().map(|d| format!("datum {d}")).collect(),
            ..Default::default()
        });
    }
    plan.problems.extend(found);
    plan.status = crate::completeness::status(&plan.problems);
}

/// Independent final-plan lint, including pinned and unavoidable placements.
pub fn symbol_collisions<'a>(items: impl IntoIterator<Item = &'a PlannedGdt>) -> Vec<Problem> {
    let datums: Vec<_> = items
        .into_iter()
        .filter(|g| g.kind == "datum_feature")
        .filter_map(|g| g.placed.as_ref().map(|p| (g, p)))
        .collect();
    let mut problems = Vec::new();
    for (i, (a, pa)) in datums.iter().enumerate() {
        for (b, pb) in &datums[i + 1..] {
            if pa
                .fills
                .iter()
                .any(|fa| pb.fills.iter().any(|fb| polygons_touch(fa, fb)))
            {
                problems.push(Problem {
                    id: format!("p:datum_symbol_overlap:{}|{}", a.id, b.id),
                    code: "datum_symbol_overlap".into(),
                    severity: "error".into(),
                    message: format!("The filled triangles of datum feature symbols {} and {} overlap or touch; move their attachments apart.", a.label, b.label),
                    subjects: vec![a.id.clone(), b.id.clone()],
                    ..Default::default()
                });
            }
        }
    }
    problems
}

/// A placed item as the dimensions' collision checks see it: a callout whose leader is its
/// lines and whose label is its frame.
pub fn proxy(g: &PlannedGdt) -> Option<PlannedDimension> {
    let p = g.placed.as_ref()?;
    Some(PlannedDimension {
        callout_offset: None,
        reference: false,
        determined_by: Vec::new(),
        region: None,
        id: g.id.clone(),
        kind: "callout".into(),
        view: g.view.clone(),
        value: 0.0,
        label: g.cells.join(" "),
        terms: g.cells.clone(),
        measurements: Vec::new(),
        default: true,
        from_spec: Vec::new(),
        basis: g.basis.clone(),
        state: State::Shown,
        placed: Some(Placed {
            lines: p.lines.clone(),
            arrows: p.arrows.clone(),
            label_at: [p.label_box[0], p.label_box[1]],
            rotation: 0.0,
            label_box: p.label_box,
        }),
    })
}

/// Complete scope-symbol ink for contact/overlap audits. Route consumers use
/// `proxy` so that its two leader segments retain their shaft/shelf semantics.
pub(crate) fn contact_proxy(g: &PlannedGdt) -> Option<PlannedDimension> {
    let mut d = proxy(g)?;
    let p = g.placed.as_ref()?;
    let rings = ring_arcs(g);
    let arcs = &p.arcs[p.arcs.len() - rings..];
    let ink = crate::centrelines::LineWork {
        id: g.id.clone(),
        kind: "symbol".into(),
        curves: arcs
            .iter()
            .map(|a| Curve::Conic {
                centre: [a[0], a[1]],
                radii: [a[2]; 2],
                x_axis: [1., 0.],
                y_axis: [0., 1.],
                t0: a[3].to_radians(),
                t1: a[4].to_radians(),
            })
            .collect(),
        centre: None,
        radial: false,
        global_axis: false,
        overrun: 0.,
    };
    d.placed
        .as_mut()?
        .lines
        .extend(crate::centrelines::segments(&ink));
    Some(d)
}

/// The default surface finish's symbol beside the title block (*r*) as the placed items'
/// collision checks and the blocks placed after it see it: its strokes as lines, its whole box
/// as its label.
pub fn finish_proxy(r: &crate::pmi_lowering::PlannedRequirement) -> Option<PlannedDimension> {
    let p = r.placed.as_ref()?;
    Some(PlannedDimension {
        callout_offset: None,
        reference: false,
        determined_by: Vec::new(),
        region: None,
        id: r.id.clone(),
        kind: "symbol".into(),
        view: String::new(),
        value: 0.0,
        label: r.text.clone(),
        terms: vec![r.text.clone()],
        measurements: Vec::new(),
        default: true,
        from_spec: Vec::new(),
        basis: r.basis.clone(),
        state: State::Shown,
        placed: Some(Placed {
            lines: p.strokes.clone(),
            arrows: Vec::new(),
            label_at: [p.glyph[0], p.glyph[1]],
            rotation: 0.0,
            label_box: p.glyph,
        }),
    })
}

/// What the default surface finish's symbol (*r*) collides with among the placed *items* (the
/// dimensions, frames and labels), judged as their collisions are.
pub fn finish_collisions(
    analysis: &Analysis,
    sheet: &PlannedSheet,
    views: &[PlannedView],
    items: &[PlannedDimension],
    r: &crate::pmi_lowering::PlannedRequirement,
) -> Vec<Problem> {
    finish_collisions_cached(
        analysis,
        sheet,
        views,
        items,
        r,
        &super::footprints::Cache::default(),
    )
}

pub(crate) fn finish_collisions_cached(
    analysis: &Analysis,
    sheet: &PlannedSheet,
    views: &[PlannedView],
    items: &[PlannedDimension],
    r: &crate::pmi_lowering::PlannedRequirement,
    cache: &super::footprints::Cache,
) -> Vec<Problem> {
    if sheet.number != 1 {
        return Vec::new();
    }
    let Some(proxy) = finish_proxy(r) else {
        return Vec::new();
    };
    let mut all = items.to_vec();
    all.push(proxy);
    // It stands in the band the title block's reservation keeps above the grid, as the scale
    // note does, so the reservation is not an obstacle to it.
    placement::collisions_cached(analysis, &all, sheet, views, cache)
        .into_iter()
        .filter(|q| q.subjects.contains(&r.id) && q.code != "annotation_over_title_block")
        .collect()
}

/// Draws a planned item into *items* (the dims layer) and its runs into *text*, from the plan
/// alone; returns its annotation for lint (no measurement claims: a frame states the source's
/// requirement, not a measurement of the part).
pub fn render(
    g: &PlannedGdt,
    items: &mut Vec<Item>,
    text: &mut Vec<TextRun>,
) -> Option<Annotation> {
    // An omitted datum, or one not drawn by default because nothing cites or measures from it,
    // is suppressed by policy: recorded, not missing ink.
    if g.kind == "datum_feature"
        && (g.state == State::OmittedByUser || g.state == State::not_drawable("datum_not_drawn"))
    {
        return Some(Annotation {
            name: format!("suppressed:{}", g.id),
            view: Some(g.view.clone()),
            ..Default::default()
        });
    }
    let p = g.placed.as_ref()?;
    let first = text.len();
    for [a, b] in &p.lines {
        items.push(Item::Edge(Curve::Line(*a, *b)));
    }
    // A CAD-font frame's text is strokes and arcs after its lines, each tied to the run of the
    // compartment it sits in and drawn with the text pen.
    let run_of = text_run_of(p, g.cells.len(), first);
    for (i, [a, b]) in p.strokes.iter().enumerate() {
        items.push(if i < p.frame_strokes {
            Item::Edge(Curve::Line(*a, *b))
        } else {
            Item::FrameText(
                Curve::Line(*a, *b),
                run_of([0, 1].map(|k| 0.5 * (a[k] + b[k]))),
            )
        });
    }
    for &arrow in &p.arrows {
        let [tip, b1, b2] = arrow_vertices(arrow);
        items.push(Item::Face(vec![vec![
            Curve::Line(tip, b1),
            Curve::Line(b1, b2),
            Curve::Line(b2, tip),
        ]]));
    }
    for f in &p.fills {
        let wire: Vec<Curve> = (0..f.len())
            .map(|i| Curve::Line(f[i], f[(i + 1) % f.len()]))
            .collect();
        items.push(Item::Face(vec![wire]));
    }
    let text_arcs = if p.frame_strokes == usize::MAX {
        0
    } else {
        p.arcs.len().saturating_sub(ring_arcs(g))
    };
    for (i, a) in p.arcs.iter().enumerate() {
        let curve = Curve::Conic {
            centre: [a[0], a[1]],
            radii: [a[2], a[2]],
            x_axis: [1.0, 0.0],
            y_axis: [0.0, 1.0],
            t0: a[3].to_radians(),
            t1: a[4].to_radians(),
        };
        items.push(if i < text_arcs {
            Item::FrameText(curve, run_of([a[0], a[1]]))
        } else {
            Item::Edge(curve)
        });
    }
    let f = font();
    for l in &p.letters {
        let laid = f.text(&l.text, l.size);
        let shift = |q: P2| [q[0] + l.at[0], q[1] + l.at[1]];
        let wires: Vec<Vec<Curve>> = laid
            .contours
            .iter()
            .filter(|c| !c.is_empty())
            .map(|c| {
                c.iter()
                    .map(|s| match *s {
                        Segment::Line(a, b) => Curve::Line(shift(a), shift(b)),
                        Segment::Quad(a, b, c) => {
                            Curve::Beziers(vec![vec![shift(a), shift(b), shift(c)]])
                        }
                        Segment::Cubic(a, b, c, d) => {
                            Curve::Beziers(vec![vec![shift(a), shift(b), shift(c), shift(d)]])
                        }
                    })
                    .collect()
            })
            .collect();
        if !wires.is_empty() {
            let run = p
                .runs
                .iter()
                .enumerate()
                .min_by(|(_, a), (_, b)| {
                    let distance = |r: &GdtText| (r.at[0] - l.at[0]).hypot(r.at[1] - l.at[1]);
                    distance(a).total_cmp(&distance(b))
                })
                .map_or(first, |(i, _)| first + i);
            items.push(Item::Glyph(wires, run));
        }
    }
    for r in &p.runs {
        text.push(TextRun {
            text: r.text.clone(),
            at: r.at,
            size: r.size,
            rotation: 0.0,
            font: FONT.into(),
            h_align: HAlign::Center,
            v_align: VAlign::Middle,
        });
    }
    Some(Annotation {
        approved_claims: Vec::new(),
        approved_text: None,
        coordinate_origin: None,
        satisfies: Vec::new(),
        name: g.id.clone(),
        view: Some(g.view.clone()),
        runs: (first..text.len()).collect(),
        claims: Vec::new(),
    })
}

/// The characters of a placed frame's text that neither CAD font draws
/// (`haecceity::presentation::gdt::cad_frame_missing`), as the frame leaves them out of its ink:
/// in its tolerance cell without the zone sign and material letter the cell adds, and in its
/// datum cells; for a datum symbol, its letter.
pub(crate) fn frame_missing(g: &PlannedGdt) -> Vec<char> {
    use haecceity::presentation::gdt::cad_frame_missing;
    match (g.kind.as_str(), g.cells.as_slice()) {
        ("control_frame", [_, tolerance, datums @ ..]) => {
            let value = tolerance.trim_start_matches("S⌀").trim_start_matches('⌀');
            let value = value.trim_end_matches(['Ⓜ', 'Ⓛ']);
            cad_frame_missing(value, datums)
        }
        ("datum_feature", [letter]) => cad_frame_missing(letter, &[]),
        _ => Vec::new(),
    }
}

/// How many circles the leader's bend scope symbols add to the end of a frame's arcs.
fn ring_arcs(g: &PlannedGdt) -> usize {
    g.modifiers
        .iter()
        .map(|m| if m == "all_over" { 2 } else { 1 })
        .sum()
}

/// The index, in the text run list that [`render`] builds from *first*, of the run whose
/// compartment a point of *p*'s text falls in: a point above the frame's box is the count's, a
/// point in the box is its cell's by the frame's dividers.
fn text_run_of(p: &GdtPlaced, cells: usize, first: usize) -> impl Fn(P2) -> usize {
    let lines = &p.strokes[..p.frame_strokes.min(p.strokes.len())];
    let top = lines
        .iter()
        .flatten()
        .map(|q| q[1])
        .fold(f64::NEG_INFINITY, f64::max);
    let mut dividers: Vec<f64> = lines
        .iter()
        .filter(|[a, b]| a[0] == b[0])
        .map(|[a, _]| a[0])
        .collect();
    dividers.sort_by(f64::total_cmp);
    dividers.dedup();
    let lead = p.runs.len().saturating_sub(cells);
    let last = p.runs.len().saturating_sub(1);
    move |q| {
        if lead > 0 && q[1] > top {
            return first;
        }
        let cell = dividers.iter().filter(|x| **x < q[0]).count().max(1) - 1;
        first + (lead + cell).min(last)
    }
}

/// What [`render`] drew of a placed feature control frame that is the frame itself, for the
/// DXF's one native frame entity to stand in for: the box, dividers and symbol strokes, the
/// zone and material rings (the laid ink), and the compartments' runs. The leader's lines,
/// arrowheads and fills, the all-around and all-over rings at its bend, and the count over the
/// box are not. Item offsets follow [`render`]'s push order; the rings are the last arcs, as
/// the callout routes count them.
///
/// Every placed control frame has a frame: it needs only its box strokes to locate it. That its
/// runs end in its cells and that it has the arcs its rings count on are what [`render`] builds,
/// so they are asserted, not tested for.
pub(crate) fn frame(g: &PlannedGdt) -> Option<crate::dxf_output::Frame> {
    let p = g.placed.as_ref().filter(|_| g.kind == "control_frame")?;
    let lead = p.runs.len().saturating_sub(g.cells.len());
    debug_assert!(
        p.runs.len() >= g.cells.len()
            && p.runs[lead..]
                .iter()
                .zip(&g.cells)
                .all(|(r, c)| r.text == *c),
        "{}: runs are not the cells",
        g.id
    );
    let rings = ring_arcs(g);
    debug_assert!(p.arcs.len() >= rings, "{}: fewer arcs than rings", g.id);
    let own_arcs = p.arcs.len().saturating_sub(rings);
    let first = p.lines.len();
    let arcs = first + p.strokes.len() + p.arrows.len() + p.fills.len();
    // The box alone: the count above it and the text in it are not its extent.
    let lines = &p.strokes[..p.frame_strokes.min(p.strokes.len())];
    let (x0, y0, y1) = lines.iter().flatten().fold(
        (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY),
        |(x, a, b), q| (x.min(q[0]), a.min(q[1]), b.max(q[1])),
    );
    x0.is_finite().then(|| crate::dxf_output::Frame {
        cells: g.cells.clone(),
        at: [x0, 0.5 * (y0 + y1)],
        ink: vec![first..first + p.strokes.len(), arcs..arcs + own_arcs],
        lead,
    })
}

fn placement_choices(
    item: &Lowered,
    record: &crate::pmi::Record,
    views: &[PlannedView],
) -> Vec<(&'static str, Vec<&'static str>)> {
    views
        .iter()
        .filter_map(|view| {
            let name = match view.id.as_str() {
                "v:front" => "front",
                "v:plan" => "plan",
                "v:side" => "side",
                _ => return None,
            };
            match &item.glyph {
                Glyph::Label { .. }
                    if record
                        .geometry
                        .as_ref()
                        .is_some_and(|g| !g.sites.is_empty()) =>
                {
                    Some((name, vec!["above", "below", "left", "right"]))
                }
                Glyph::ControlFrame { .. } | Glyph::Label { .. } | Glyph::FlagNote { .. } => {
                    (name == item.view).then(|| (name, vec!["above", "below", "left", "right"]))
                }
                Glyph::Datum { surface, .. } | Glyph::Finish { surface, .. }
                    if surface == "plane" =>
                {
                    let normal = record.geometry.as_ref()?.normal?;
                    let dot: f64 = normal.iter().zip(view.direction).map(|(a, b)| a * b).sum();
                    if dot.abs() > 1e-6 {
                        return None;
                    }
                    let projected = haecceity::hlr::View::new(view.direction, view.up)?.map(normal);
                    let side = if projected[0].abs() > 0.9 {
                        if projected[0] > 0.0 { "right" } else { "left" }
                    } else if projected[1].abs() > 0.9 {
                        if projected[1] > 0.0 { "above" } else { "below" }
                    } else {
                        return None;
                    };
                    Some((name, vec![side]))
                }
                // A cylinder's finish may stand on either side its record proves a site on.
                Glyph::Finish { .. } if name == item.view => {
                    let mut sides = vec![item.side];
                    if let Some(other) = other_finish_side(item, record) {
                        sides.push(other);
                    }
                    Some((name, sides))
                }
                Glyph::Datum { .. } | Glyph::Finish { .. } => {
                    (name == item.view).then(|| (name, vec![item.side]))
                }
            }
        })
        .collect()
}

/// The strip opposite a cylinder finish's own (*item*) when its record proves a site there: one
/// whose coordinate across the strip differs from its lowered site's (the silhouettes, or the
/// head-on sites either side of the axis, each share theirs).
fn other_finish_side(item: &Lowered, record: &crate::pmi::Record) -> Option<&'static str> {
    let Glyph::Finish { surface, .. } = &item.glyph else {
        return None;
    };
    if surface != "cylinder" {
        return None;
    }
    let beside = outward(item.side)[0] != 0.0;
    // The model axis across the strip in the view: front x | z, plan x | y, side y | z.
    let across = match (item.view, beside) {
        ("side", true) => 1,
        (_, true) => 0,
        ("plan", false) => 1,
        (_, false) => 2,
    };
    let g = record.geometry.as_ref()?;
    g.sites
        .iter()
        .chain(&g.alternatives)
        .any(|p| (p[across] - item.site[across]).abs() > 1e-6)
        .then_some(match item.side {
            "left" => "right",
            "right" => "left",
            "above" => "below",
            _ => "above",
        })
}

/// Authored carriers must prove the attachment before placement.
pub(crate) fn validate_placements(
    analysis: &Analysis,
    spec: &Spec,
    views: &[PlannedView],
) -> Result<(), crate::model::Invalid> {
    if spec.annotations.is_empty() {
        return Ok(());
    }
    let shown = |name: &str| views.iter().any(|v| v.id == format!("v:{name}"));
    let (items, _) = crate::pmi_lowering::lower_in(analysis, &shown, spec.units);
    let all: Vec<_> = PRINCIPALS
        .iter()
        .map(|(name, direction, up)| PlannedView {
            detail: None,
            sheet: 1,
            scale_note: None,
            xref: None,
            id: format!("v:{name}"),
            direction: *direction,
            up: *up,
            at: [0.0; 2],
            scale: 1.0,
            area: [0.0; 4],
            default: true,
            basis: String::new(),
            state: State::Shown,
            cut: None,
            half_section: None,
            broken: None,
            line_work: Vec::new(),
            line_style: Default::default(),
            from_spec: Vec::new(),
        })
        .collect();
    let Some(crate::pmi::Reading::Read(report)) = &analysis.pmi else {
        return Ok(());
    };
    for item in items {
        let Some(entry) = spec.annotations.get(&item.id).filter(|e| !e.omit) else {
            continue;
        };
        let Some(place) = entry
            .place
            .as_ref()
            .filter(|p| !super::hole_marks::pinned_on_mark(analysis, &item, p))
        else {
            continue;
        };
        let Some(record) = report.records.iter().find(|r| r.source_id == item.source) else {
            continue;
        };
        let choices = placement_choices(&item, record, &all);
        let view = place.view.as_deref().unwrap_or(item.view);
        let Some((_, sides)) = choices.iter().find(|(name, _)| *name == view) else {
            return Err(crate::model::Invalid {
                path: None,
                also: Vec::new(),
                message: format!(
                    "{} cannot attach in the {view} view; choose a compatible view.",
                    record.label
                ),
                choices: choices.iter().map(|(name, _)| name.to_string()).collect(),
            });
        };
        // A finish stands only beside a silhouette (or half face) it proves a site on.
        if let (Glyph::Finish { .. }, Some(side)) = (&item.glyph, place.side)
            && view == item.view
            && !sides.contains(&side.name())
        {
            return Err(crate::model::Invalid {
                path: None,
                also: Vec::new(),
                message: format!(
                    "{} has no proven site {} the {view} view; choose a side it attaches on.",
                    record.label,
                    side.name()
                ),
                choices: sides.iter().map(|s| s.to_string()).collect(),
            });
        }
    }
    Ok(())
}

pub fn placement_options(
    analysis: &Analysis,
    views: &[PlannedView],
) -> BTreeMap<String, serde_json::Value> {
    let (items, _) = crate::pmi_lowering::lower(analysis, &|name| {
        views.iter().any(|view| view.id == format!("v:{name}"))
    });
    let identities = match analysis.pmi.as_ref() {
        Some(crate::pmi::Reading::Read(report)) => report.identities(),
        _ => return BTreeMap::new(),
    };
    items
        .into_iter()
        .filter_map(|item| {
            let Some(crate::pmi::Reading::Read(report)) = &analysis.pmi else {
                return None;
            };
            let record = report.records.iter().find(|r| r.source_id == item.source)?;
            let id = identities.id(&record.source_id).ok()?;
            let choices = placement_choices(&item, record, views)
                .into_iter()
                .map(|(view, sides)| serde_json::json!({"view": view, "sides": sides}))
                .collect::<Vec<_>>();
            Some((
                id.to_string(),
                serde_json::json!({"label": record.label, "views": choices}),
            ))
        })
        .collect()
}

/// Straight, short normal routes precede one-bend routes with a square stub.
/// The triangle and any reader-proven face extension stay fixed. No automatic
/// oblique departure is generated, even when every candidate retains a contact.
pub(super) fn normal_routes(g: &PlannedGdt, bends: bool) -> Vec<Placed> {
    let Some(p) = &g.placed else {
        return Vec::new();
    };
    let Some(&[apex, near]) = p.lines.first() else {
        return Vec::new();
    };
    let Some(triangle) = p.fills.first().filter(|f| f.len() == 3) else {
        return Vec::new();
    };
    let base = [
        (triangle[0][0] + triangle[2][0]) / 2.,
        (triangle[0][1] + triangle[2][1]) / 2.,
    ];
    let v = [triangle[1][0] - base[0], triangle[1][1] - base[1]];
    let n = v[0].hypot(v[1]);
    if n <= 1e-9 {
        return Vec::new();
    }
    let u = v.map(|x| x / n);
    let old = (near[0] - apex[0]).hypot(near[1] - apex[1]);
    let mut routes = Vec::new();
    for i in 0..64 {
        let length = 0.8 * TEXT + f64::from(i);
        if length > old + 1e-6 {
            break;
        }
        let end = [apex[0] + u[0] * length, apex[1] + u[1] * length];
        let delta = [end[0] - near[0], end[1] - near[1]];
        let Some(mut q) = proxy(g).and_then(|q| q.placed) else {
            break;
        };
        q.lines[0][1] = end;
        for k in 0..4 {
            q.label_box[k] += delta[k % 2];
        }
        q.label_at = [q.label_box[0], q.label_box[1]];
        routes.push(q);
    }
    // A lateral frame can escape an occupied normal corridor after a square stub.
    // Try the shorter normal tiers first; retain all face-extension strokes.
    if !bends {
        return routes;
    }
    let straight = routes.clone();
    for q in straight.iter().take(8) {
        for offset in [-8., 8., -16., 16.] {
            let delta = [-u[1] * offset, u[0] * offset];
            let mut bent = q.clone();
            let end = [q.lines[0][1][0] + delta[0], q.lines[0][1][1] + delta[1]];
            let stub = [apex[0] + u[0] * 0.8 * TEXT, apex[1] + u[1] * 0.8 * TEXT];
            if (end[0] - stub[0]) * u[0] + (end[1] - stub[1]) * u[1] <= 1e-6 {
                continue;
            }
            bent.lines[0] = [apex, stub];
            bent.lines.insert(1, [stub, end]);
            for k in 0..4 {
                bent.label_box[k] += delta[k % 2];
            }
            bent.label_at = [bent.label_box[0], bent.label_box[1]];
            routes.push(bent);
        }
    }
    routes
}

/// Explicit datum visibility intent, shared by strip demand and symbol placement.
fn datum_omission(analysis: &Analysis, spec: &Spec, item: &Lowered) -> Option<&'static str> {
    if !matches!(item.glyph, Glyph::Datum { .. })
        || (spec.sheet.uncited_datums == Some(true)
            && !spec.annotations.get(&item.id).is_some_and(|a| a.omit))
    {
        return None;
    }
    let Some(crate::pmi::Reading::Read(report)) = &analysis.pmi else {
        return None;
    };
    report
        .records
        .iter()
        .find(|r| r.source_id == item.source)
        .and_then(|r| {
            let origins = super::pmi_policy::origin_datums(analysis, spec);
            crate::spec_gdt::datum_omission(spec, report, r, &origins)
        })
}

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

    #[test]
    fn scope_rings_have_a_clear_shelf_on_every_strip_and_reserve_their_ink() {
        let analysis: Analysis = serde_json::from_value(serde_json::json!({
            "schema": crate::model::ANALYSIS_SCHEMA,
            "binding":{"source_sha256":"", "part":"plate", "face_count":0, "loader":"test"},
            "envelope":[[0,0,0],[100,60,10]], "iso_bounds":[0,0,100,60]
        }))
        .unwrap();
        let plan = crate::model::plan(&analysis, &Spec::default()).unwrap();
        let page = Page::new(&analysis, &plan.sheet, &[]);
        for modifier in ["all_around", "all_over"] {
            let radius = ring_radius(&[modifier.into()]);
            for side in ["above", "below", "left", "right"] {
                let c = candidate(
                    Shape::Frame,
                    [80., 80.],
                    side,
                    if matches!(side, "below" | "left") {
                        60.
                    } else {
                        100.
                    },
                    [20., 5.],
                )
                .with_ring(radius);
                let original = candidate(
                    Shape::Frame,
                    [80., 80.],
                    side,
                    if matches!(side, "below" | "left") {
                        60.
                    } else {
                        100.
                    },
                    [20., 5.],
                );
                assert_eq!(c.elbow, original.elbow);
                assert_eq!(c.lines[0], original.lines[0]);
                let direction = if side == "left" { -1. } else { 1. };
                assert!(
                    (c.label_box[0]
                        - original.label_box[0]
                        - direction * (radius + super::super::contacts::TEXT_CLEAR - SHELF))
                        .abs()
                        < 1e-9
                );
                assert_eq!(c.lines[0][1], c.elbow);
                assert_eq!(c.arrows, [placement::arrow(c.lines[0][0], c.elbow)]);
                let [a, b] = c.lines[1];
                assert!((b[0] - a[0]).abs() >= radius + super::super::contacts::TEXT_CLEAR - 1e-9);
                assert!(!boxes_overlap(c.label_box, ring_box(c.elbow, radius)));
                let mut obstacles = Obstacles {
                    page: &page,
                    own: "v:front".into(),
                    area: None,
                    exterior: None,
                    protect_triangles: false,
                    label_gap: 0.,
                    parallel_gap: None,
                    triangles: Vec::new(),
                    labels: Vec::new(),
                    rings: Vec::new(),
                    lines: Vec::new(),
                    heads: Vec::new(),
                    frame_leaders: Vec::new(),
                };
                assert_eq!(obstacles.clearance_grade(&c), 0);
                let mut legacy = candidate(
                    Shape::Frame,
                    [80., 80.],
                    side,
                    if matches!(side, "below" | "left") {
                        60.
                    } else {
                        100.
                    },
                    [20., 5.],
                );
                legacy.ring_radius = radius;
                assert_eq!(obstacles.clearance_grade(&legacy), 4);
                // This label touches only the ring, away from the frame and shaft.
                let ring = ring_box(c.elbow, radius);
                obstacles
                    .labels
                    .push([ring[0], ring[3] - 0.25, ring[0] + 0.25, ring[3]]);
                assert_eq!(obstacles.clearance_grade(&c), 4);
                obstacles.labels.clear();
                obstacles
                    .lines
                    .push([[ring[0], ring[3] - 0.25], [ring[2], ring[3] - 0.25]]);
                assert_eq!(obstacles.clearance_grade(&c), 2);
            }
        }
        let c = candidate(Shape::Frame, [80., 80.], "above", 100., [20., 5.]).with_ring(RING);
        let obstacles = Obstacles {
            page: &page,
            own: "v:front".into(),
            area: None,
            exterior: None,
            protect_triangles: false,
            label_gap: 0.,
            parallel_gap: None,
            triangles: Vec::new(),
            labels: Vec::new(),
            rings: Vec::new(),
            lines: vec![[[80., 80.75], [80., 87.25]]],
            heads: vec![arrow_vertices(placement::arrow([80., 80.75], [80., 87.25]))],
            frame_leaders: Vec::new(),
        };
        assert!(obstacles.grade(&c, None).2 > 0);
        assert_eq!(
            clear_ring_bend(c.clone(), &obstacles, None).lines[0],
            c.lines[0]
        );
        let mut c = c;
        c.move_bend(-0.39);
        let next = clear_ring_bend(c.clone(), &obstacles, None);
        assert_eq!(next.label_box, c.label_box);
        assert_eq!(next.origin, c.origin);
        assert_eq!(next.lines[0][0], c.lines[0][0]);
        assert_eq!(obstacles.grade(&next, None), (0, 0, 0));
        assert!(!polygons_touch(
            &arrow_vertices(next.arrows[0]),
            &obstacles.heads[0]
        ));
        let shaft = obstacles.lines[0];
        assert!(!super::super::leaders::Line::new(shaft).meets(next.arrows[0]));
        assert!(!super::super::leaders::Line::new(next.arrows[0]).meets(shaft));
        let peer_arrow = placement::arrow([80., 80.75], [80., 87.25]);
        assert!(!super::super::leaders::Line::new(peer_arrow).meets(next.lines[0]));
        assert!(!super::super::leaders::Line::new(next.lines[0]).meets(peer_arrow));
        assert!(next.lines[1][1][0] - next.elbow[0] > c.lines[1][1][0] - c.elbow[0]);
        let c = candidate(Shape::Frame, [80., 80.], "above", 100., [20., 5.]).with_ring(RING);
        let mut witness = obstacles;
        witness.heads.clear();
        let mut c = c;
        c.move_bend(-0.39);
        witness.lines = vec![[[77.9, 98.2], [77.9, 101.8]]];
        assert_eq!(witness.bounds_grade(&c, c.label_box), 0);
        assert_eq!(witness.clearance_grade(&c), 2);
        let next = clear_ring_bend(c.clone(), &witness, None);
        assert_eq!(witness.grade(&next, None), (0, 0, 0));
        assert!((next.elbow[0] - 80.).abs() < 1e-9);
        assert!(
            (next.label_box[0]
                - c.label_box[0]
                - (RING + super::super::contacts::TEXT_CLEAR - SHELF))
                .abs()
                < 1e-9
        );
        assert!(
            (next.lines[1][1][0] - next.elbow[0] - (c.lines[1][1][0] - c.elbow[0])).abs() < 1e-9
        );
    }

    #[test]
    fn later_frame_avoids_reserved_ring_and_audit_sees_an_unavoidable_contact() {
        let analysis: Analysis = serde_json::from_value(serde_json::json!({
            "schema": crate::model::ANALYSIS_SCHEMA,
            "binding":{"source_sha256":"", "part":"plate", "face_count":0, "loader":"test"},
            "envelope":[[0,0,0],[100,60,10]], "iso_bounds":[0,0,100,60]
        }))
        .unwrap();
        let mut plan = crate::model::plan(&analysis, &Spec::default()).unwrap();
        let page = Page::new(&analysis, &plan.sheet, &[]);
        let frame = |id: &str, c: &Candidate, modifiers: Vec<String>| PlannedGdt {
            from_spec: Vec::new(),
            id: id.into(),
            kind: "control_frame".into(),
            view: "v:front".into(),
            side: "above".into(),
            source: id.into(),
            faces: vec![1],
            cells: vec!["⌓".into(), "0.1".into()],
            modifiers: modifiers.clone(),
            label: "⌓ 0.1".into(),
            default: true,
            basis: String::new(),
            state: State::Shown,
            placed: Some(GdtPlaced {
                tip: c.lines[0][0],
                lines: c.lines.clone(),
                arrows: c.arrows.clone(),
                label_box: c.label_box,
                strokes: Vec::new(),
                frame_strokes: 0,
                arcs: if modifiers.is_empty() {
                    Vec::new()
                } else {
                    vec![circle(c.elbow, RING), circle(c.elbow, 1.7 * RING)]
                },
                fills: Vec::new(),
                letters: Vec::new(),
                runs: Vec::new(),
            }),
        };
        let legacy = candidate(Shape::Frame, [80., 80.], "above", 100., [20., 5.]);
        let mut inherited = frame("pmi:legacy", &legacy, vec!["all_over".into()]);
        let p = inherited.placed.as_mut().unwrap();
        let old = p.clone();
        extend_scope_shelf(p, &inherited.modifiers);
        assert_eq!(p.lines[0], old.lines[0]);
        assert_eq!(p.arcs, old.arcs);
        assert!(
            (p.lines[1][1][0] - p.lines[1][0][0] - 1.7 * RING - super::super::contacts::TEXT_CLEAR)
                .abs()
                < 1e-9
        );
        let first =
            candidate(Shape::Frame, [80., 80.], "above", 100., [20., 5.]).with_ring(1.7 * RING);
        let first = frame("pmi:first", &first, vec!["all_over".into()]);
        let natural = candidate(Shape::Frame, [68., 80.], "above", 100., [8., 2.]);
        let mut obstacles = Obstacles {
            page: &page,
            own: "v:front".into(),
            area: None,
            exterior: None,
            protect_triangles: false,
            label_gap: 0.,
            parallel_gap: None,
            triangles: Vec::new(),
            labels: vec![first.placed.as_ref().unwrap().label_box],
            rings: Vec::new(),
            lines: first.placed.as_ref().unwrap().lines.clone(),
            heads: Vec::new(),
            frame_leaders: Vec::new(),
        };
        assert_eq!(obstacles.clearance_grade(&natural), 0);
        reserve_ring(
            &mut obstacles.rings,
            &first.modifiers,
            first.placed.as_ref().unwrap(),
        );
        assert_eq!(obstacles.text_grade(&natural), (0, 1, 0));
        let mut filled = natural.clone();
        filled.label_box = [40., 40., 42., 42.];
        filled.fills = vec![vec![[76.5, 99.5], [78., 99.5], [78., 100.5]]];
        assert_eq!(obstacles.text_grade(&filled), (0, 1, 0));
        let chord = candidate(Shape::Frame, [78., 80.], "above", 107., [8., 2.]);
        assert_eq!(obstacles.scope_contacts(&chord), 1);
        let shared_shaft = candidate(Shape::Frame, [80., 80.], "above", 107., [8., 2.]);
        assert_eq!(obstacles.scope_contacts(&shared_shaft), 0);
        assert!(obstacles.grade(&shared_shaft, None).2 > 0);
        // An unrelated line ending at the same bend is not the ring's owner.
        obstacles.lines.push([[80., 100.], [76., 100.]]);
        assert_eq!(obstacles.scope_contacts(&chord), 1);
        obstacles.lines.pop();
        let clear = candidate(Shape::Frame, [68., 80.], "above", 107., [8., 2.]);
        assert_eq!(obstacles.grade(&clear, None), (0, 0, 0));
        assert!(obstacles.grade(&clear, None) < obstacles.grade(&natural, None));
        // The first frame's label and leader are clear. Only its ring enters
        // the second frame; both proxy consumers must receive that printed ink.
        assert!(contact_proxy(&first).unwrap().placed.unwrap().lines.len() > 2);
        plan.dimensions.clear();
        plan.gdt = vec![first, frame("pmi:second", &natural, Vec::new())];
        let contact = |p: &Problem| {
            p.code == "annotation_ink_overlap" && p.subjects == ["pmi:first", "pmi:second"]
        };
        assert!(crate::dims::recheck(&analysis, &plan).iter().any(contact));
        crate::dims::contacts::report(&analysis, &mut plan);
        crate::dims::contacts::report(&analysis, &mut plan);
        assert_eq!(plan.problems.iter().filter(|p| contact(p)).count(), 1);
        plan.gdt[1] = frame("pmi:second", &clear, Vec::new());
        assert!(!crate::dims::recheck(&analysis, &plan).iter().any(contact));
        crate::dims::contacts::report(&analysis, &mut plan);
        assert!(!plan.problems.iter().any(contact));
    }

    #[test]
    fn datum_route_inventory_tries_straight_before_square_stub_bends() {
        let a = crate::model::analyse_native(
            &std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("tests/fixtures/samples/cnc-review-spindle.step.gz"),
        )
        .unwrap()
        .1;
        let p = crate::model::plan(&a, &Spec::default()).unwrap();
        let g = p
            .gdt
            .iter()
            .find(|g| {
                g.kind == "datum_feature" && g.placed.as_ref().is_some_and(|p| p.lines.len() == 1)
            })
            .unwrap();
        // Make a deliberately long normal route so the inventory has both tiers
        // and bends to exercise (the real spindle is already at minimum reach).
        let mut g = g.clone();
        let u = outward(&g.side);
        let placed = g.placed.as_mut().unwrap();
        for (k, value) in u.into_iter().enumerate() {
            placed.lines[0][1][k] += 20. * value;
            placed.label_box[k] += 20. * value;
            placed.label_box[k + 2] += 20. * value;
        }
        let placed = g.placed.as_ref().unwrap();
        let triangle = &placed.fills[0];
        let base = [
            triangle[2][0] - triangle[0][0],
            triangle[2][1] - triangle[0][1],
        ];
        let routes = normal_routes(&g, true);
        assert!(!routes.is_empty());
        let mut bent = false;
        for route in routes {
            let [a, b] = route.lines[0];
            assert_eq!(a, placed.lines[0][0], "the triangle stays fixed");
            assert!(dot(base, [b[0] - a[0], b[1] - a[1]]).abs() < 1e-8);
            if route.lines.len() == 2 {
                bent = true;
                assert!(((b[0] - a[0]).hypot(b[1] - a[1]) - 0.8 * TEXT).abs() < 1e-8);
                assert_eq!(b, route.lines[1][0]);
            } else {
                assert!(!bent, "straight routes precede every bend");
            }
        }
        assert!(bent, "a blocked normal corridor has one-bend alternatives");
    }

    #[test]
    fn a_turned_shoulder_has_clear_exterior_paper_at_its_upper_site() {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/pmi/step/GRM-03_thumbwheel_drive_screw_AP242_PMI.step.gz");
        let (_, mut analysis) = crate::model::analyse_native(&path).unwrap();
        // Keep a frame citation here to exercise existing cited-datum placement
        // alongside the separate regressions for uncited author declarations.
        if let Some(crate::pmi::Reading::Read(report)) = &mut analysis.pmi {
            let mut control = report
                .records
                .iter()
                .find(|r| r.category == crate::pmi::Category::Datum && r.label == "B")
                .unwrap()
                .clone();
            control.category = crate::pmi::Category::GeometricTolerance;
            control.source_id = "geometric_tolerance:placement-test".into();
            control.kind = "perpendicularity".into();
            control.value = Some(0.1);
            control.label = "⟂ 0.1 B".into();
            control.datum_refs = vec!["B".into()];
            report.records.push(control);
        }
        let view: PlannedView = serde_json::from_value(serde_json::json!({
            "id": "v:front", "direction": [0,-1,0], "up": [0,0,1],
            "at": [0,0], "scale": 5, "area": [-500,-500,500,500],
            "state": {"kind":"shown"}, "default": true, "basis": "test"
        }))
        .unwrap();
        let (items, _) = crate::pmi_lowering::lower(&analysis, &|_| true);
        let item = items
            .iter()
            .find(|i| matches!(&i.glyph, Glyph::Datum { letter, .. } if letter == "B"))
            .unwrap();
        let frame = Frame::new(&analysis, &view);
        let tip = std::iter::once(item.site)
            .chain(item.alternatives.iter().copied())
            .map(|p| frame.page(p))
            .max_by(|a, b| a[1].total_cmp(&b[1]))
            .unwrap();
        let c = candidate(
            Shape::Datum,
            tip,
            "right",
            tip[0] + 0.9 * TRIANGLE + 0.8 * TEXT + TEXT,
            [H, H],
        );
        assert!(
            !crate::dims::interior::proofs(&analysis, std::slice::from_ref(&view))
                .contains_key(&view.id),
            "ordinary dimension routing retains its planar-face requirement"
        );
        let proofs = crate::dims::interior::exterior_proofs(&analysis, std::slice::from_ref(&view));
        let proof = proofs
            .get(&view.id)
            .expect("turned side view has exterior proof");
        assert!(
            proof.exterior_clear(&view, c.label_box, &c.lines, &c.arrows),
            "tip {tip:?}, box {:?}, lines {:?}",
            c.label_box,
            c.lines
        );
    }

    #[test]
    fn datum_triangle_contact_detects_containment_and_touch_but_not_empty_corners() {
        let a = [[0.0, 0.0], [4.0, 0.0], [0.0, 4.0]];
        for b in [
            a,
            [[0.5, 0.5], [1.0, 0.5], [0.5, 1.0]],
            [[4.0, 0.0], [5.0, 0.0], [4.0, 1.0]],
        ] {
            assert!(polygons_touch(&a, &b));
            assert!(polygons_touch(&b, &a));
        }
        let clear = [[3.0, 3.0], [4.0, 3.0], [3.0, 4.0]];
        assert!(boxes_overlap(fill_box(&a), fill_box(&clear)));
        assert!(!polygons_touch(&a, &clear));
    }

    #[test]
    fn filled_datum_triangles_reserve_clearance_even_with_separate_boxes() {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/samples/cnc-review-spindle.step.gz");
        let (_, analysis) = crate::model::analyse_native(&path).unwrap();
        let plan = crate::model::plan_recovered(&analysis, &Spec::default()).unwrap();
        let page = Page::new(&analysis, &plan.sheet, &plan.views);
        let first = candidate(Shape::Datum, [30.0, 180.0], "right", 50.0, [H, H]);
        let obstacles = Obstacles {
            page: &page,
            own: "v:front".into(),
            area: None,
            exterior: None,
            protect_triangles: true,
            label_gap: 0.5,
            parallel_gap: None,
            triangles: first.fills.clone(),
            labels: std::iter::once(first.label_box)
                .chain(first.fills.iter().map(|f| fill_box(f)))
                .collect(),
            rings: Vec::new(),
            lines: first.lines.clone(),
            heads: Vec::new(),
            frame_leaders: Vec::new(),
        };
        // The letter boxes and shafts are disjoint in every case. Identical,
        // overlapping and just-touching triangles must still be rejected.
        for offset in [0.0, TRIANGLE / 2.0, TRIANGLE] {
            let next = candidate(Shape::Datum, [30.0, 180.0 + offset], "right", 75.0, [H, H]);
            assert!(!boxes_overlap(first.label_box, next.label_box));
            assert_eq!(obstacles.clearance_grade(&next), 5, "offset {offset}");
        }
        let clear = candidate(
            Shape::Datum,
            [30.0, 180.0 + TRIANGLE + 1.0],
            "right",
            75.0,
            [H, H],
        );
        assert!(obstacles.clearance_grade(&clear) < 4);
    }

    #[test]
    fn a_datum_shaft_reserves_the_reporters_text_clearance() {
        let analysis: Analysis = serde_json::from_value(serde_json::json!({
            "schema": crate::model::ANALYSIS_SCHEMA,
            "binding":{"source_sha256":"", "part":"plate", "face_count":0, "loader":"test"},
            "envelope":[[0,0,0],[100,60,10]], "iso_bounds":[0,0,100,60]
        }))
        .unwrap();
        let plan = crate::model::plan(&analysis, &Spec::default()).unwrap();
        let page = Page::new(&analysis, &plan.sheet, &[]);
        let c = candidate(Shape::Datum, [30.0, 180.0], "right", 50.0, [H, H]);
        let mut obstacles = Obstacles {
            page: &page,
            own: "v:front".into(),
            area: None,
            exterior: None,
            protect_triangles: true,
            label_gap: 0.5,
            parallel_gap: None,
            triangles: Vec::new(),
            labels: vec![[40.0, 180.25, 45.0, 185.25]],
            rings: Vec::new(),
            lines: Vec::new(),
            heads: Vec::new(),
            frame_leaders: Vec::new(),
        };
        // The shaft misses the box, but its 0.25 mm gap reads as touching text.
        assert_eq!(obstacles.clearance_grade(&c), 2);
        obstacles.labels[0] = [40.0, 180.75, 45.0, 185.75];
        assert_eq!(obstacles.clearance_grade(&c), 0);
        // Existing dimension ink must also keep this gap from a new letter box.
        obstacles.labels.clear();
        obstacles.lines = vec![[[48.0, 182.75], [52.0, 182.75]]];
        assert_eq!(obstacles.clearance_grade(&c), 2);
    }

    #[test]
    fn an_unavoidable_text_contact_does_not_hide_another_frames_leader() {
        let analysis: Analysis = serde_json::from_value(serde_json::json!({
            "schema": crate::model::ANALYSIS_SCHEMA,
            "binding":{"source_sha256":"", "part":"plate", "face_count":0, "loader":"test"},
            "envelope":[[0,0,0],[100,60,10]], "iso_bounds":[0,0,100,60]
        }))
        .unwrap();
        let plan = crate::model::plan(&analysis, &Spec::default()).unwrap();
        let page = Page::new(&analysis, &plan.sheet, &[]);
        let right = candidate(Shape::Frame, [88., 100.], "below", 45., [29.5, 5.]);
        let obstacles = Obstacles {
            page: &page,
            own: "v:front".into(),
            area: None,
            exterior: None,
            protect_triangles: false,
            label_gap: 0.,
            parallel_gap: None,
            triangles: Vec::new(),
            // Both left-hand tiers cross this label on their way from the face.
            labels: vec![[57., 80., 59., 85.], right.label_box],
            rings: Vec::new(),
            heads: Vec::new(),
            frame_leaders: right.lines.clone(),
            lines: right.lines,
        };
        let beside = candidate(Shape::Frame, [58., 100.], "below", 47.5, [29.4, 5.]);
        let below = candidate(Shape::Frame, [58., 100.], "below", 38.5, [29.4, 5.]);
        assert_eq!(obstacles.clearance_grade(&beside), 2);
        assert_eq!(obstacles.clearance_grade(&below), 2);
        assert!(obstacles.text_grade(&below) < obstacles.text_grade(&beside));
        assert!(obstacles.grade(&below, None) < obstacles.grade(&beside, None));
    }

    #[test]
    fn planar_extensions_require_the_face_to_reach_the_outline() {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/samples/cnc-review-spindle.step.gz");
        let (_, mut analysis) = crate::model::analyse_native(&path).unwrap();
        let (items, _) = crate::pmi_lowering::lower(&analysis, &|_| true);
        let item = items
            .iter()
            .find(|i| matches!(&i.glyph, Glyph::Datum { letter, .. } if letter == "A"))
            .unwrap();
        let frame = Frame::looking(&analysis, [0.0, -1.0, 0.0], [0.0, 0.0, 1.0], [0.0; 2], 1.0);
        assert!(!plane_extensions(&analysis, item, &frame).is_empty());
        // Inset both ends of this edge-on face while keeping the view outline fixed.
        for face in &item.faces {
            let bounds = analysis.face_attachments[*face].bounds.as_mut().unwrap();
            bounds[0] = analysis.envelope[0][0] + 2.0;
            bounds[3] = analysis.envelope[1][0] - 2.0;
        }
        assert!(plane_extensions(&analysis, item, &frame).is_empty());
        // The guard is directional: reaching only the right outline offers only that end.
        for face in &item.faces {
            analysis.face_attachments[*face].bounds.as_mut().unwrap()[3] = analysis.envelope[1][0];
        }
        let sites = plane_extensions(&analysis, item, &frame);
        assert!(!sites.is_empty());
        assert!(sites.iter().all(|s| s.0[0] > frame.outline()[2]));
    }
}