File: footprint.cpp

package info (click to toggle)
kicad 9.0.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 770,320 kB
  • sloc: cpp: 961,692; ansic: 121,001; xml: 66,428; python: 18,387; sh: 1,010; awk: 301; asm: 292; makefile: 227; javascript: 167; perl: 10
file content (4227 lines) | stat: -rw-r--r-- 130,226 bytes parent folder | download | duplicates (2)
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
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
/*
 * This program source code file is part of KiCad, a free EDA CAD application.
 *
 * Copyright (C) 2017 Jean-Pierre Charras, jp.charras at wanadoo.fr
 * Copyright (C) 2015 SoftPLC Corporation, Dick Hollenbeck <dick@softplc.com>
 * Copyright (C) 2015 Wayne Stambaugh <stambaughw@gmail.com>
 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, you may find one here:
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * or you may search the http://www.gnu.org website for the version 2 license,
 * or you may write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */
#include <magic_enum.hpp>

#include <unordered_set>

#include <bitmaps.h>
#include <board.h>
#include <board_design_settings.h>
#include <confirm.h>
#include <convert_basic_shapes_to_polygon.h>
#include <convert_shape_list_to_polygon.h>
#include <drc/drc_item.h>
#include <embedded_files.h>
#include <font/font.h>
#include <font/outline_font.h>
#include <footprint.h>
#include <geometry/convex_hull.h>
#include <geometry/shape_segment.h>
#include <geometry/shape_simple.h>
#include <i18n_utility.h>
#include <lset.h>
#include <macros.h>
#include <pad.h>
#include <pcb_dimension.h>
#include <pcb_edit_frame.h>
#include <pcb_field.h>
#include <pcb_group.h>
#include <pcb_marker.h>
#include <pcb_reference_image.h>
#include <pcb_textbox.h>
#include <pcb_track.h>
#include <refdes_utils.h>
#include <string_utils.h>
#include <view/view.h>
#include <zone.h>

#include <google/protobuf/any.pb.h>
#include <api/board/board_types.pb.h>
#include <api/api_enums.h>
#include <api/api_utils.h>
#include <api/api_pcb_utils.h>
#include <wx/log.h>


FOOTPRINT::FOOTPRINT( BOARD* parent ) :
        BOARD_ITEM_CONTAINER((BOARD_ITEM*) parent, PCB_FOOTPRINT_T ),
        m_boundingBoxCacheTimeStamp( 0 ),
        m_textExcludedBBoxCacheTimeStamp( 0 ),
        m_hullCacheTimeStamp( 0 ),
        m_initial_comments( nullptr ),
        m_componentClass( nullptr )
{
    m_attributes   = 0;
    m_layer        = F_Cu;
    m_orient       = ANGLE_0;
    m_fpStatus     = FP_PADS_are_LOCKED;
    m_arflag       = 0;
    m_link         = 0;
    m_lastEditTime = 0;
    m_zoneConnection          = ZONE_CONNECTION::INHERITED;
    m_fileFormatVersionAtLoad = 0;
    m_embedFonts = false;

    addMandatoryFields();

    m_3D_Drawings.clear();
}


void FOOTPRINT::addMandatoryFields()
{
    auto addField =
            [this]( int id, PCB_LAYER_ID layer, bool visible )
            {
                PCB_FIELD* field = new PCB_FIELD( this, id );
                field->SetLayer( layer );
                field->SetVisible( visible );
                m_fields.push_back( field );
            };

    // These are the mandatory fields for the editor to work
    addField( REFERENCE_FIELD, F_SilkS, true );
    addField( VALUE_FIELD, F_Fab, true );
    m_fields.push_back( nullptr );  // FOOTPRINT_FIELD
    addField( DATASHEET_FIELD, F_Fab, false );
    addField( DESCRIPTION_FIELD, F_Fab, false );
}


FOOTPRINT::FOOTPRINT( const FOOTPRINT& aFootprint ) :
    BOARD_ITEM_CONTAINER( aFootprint ),
    EMBEDDED_FILES( aFootprint )
{
    m_pos          = aFootprint.m_pos;
    m_fpid         = aFootprint.m_fpid;
    m_attributes   = aFootprint.m_attributes;
    m_fpStatus     = aFootprint.m_fpStatus;
    m_orient       = aFootprint.m_orient;
    m_lastEditTime = aFootprint.m_lastEditTime;
    m_link         = aFootprint.m_link;
    m_path         = aFootprint.m_path;
    m_embedFonts   = aFootprint.m_embedFonts;

    m_cachedBoundingBox              = aFootprint.m_cachedBoundingBox;
    m_boundingBoxCacheTimeStamp      = aFootprint.m_boundingBoxCacheTimeStamp;
    m_cachedTextExcludedBBox         = aFootprint.m_cachedTextExcludedBBox;
    m_textExcludedBBoxCacheTimeStamp = aFootprint.m_textExcludedBBoxCacheTimeStamp;
    m_cachedHull                     = aFootprint.m_cachedHull;
    m_hullCacheTimeStamp             = aFootprint.m_hullCacheTimeStamp;

    m_clearance                      = aFootprint.m_clearance;
    m_solderMaskMargin               = aFootprint.m_solderMaskMargin;
    m_solderPasteMargin              = aFootprint.m_solderPasteMargin;
    m_solderPasteMarginRatio         = aFootprint.m_solderPasteMarginRatio;
    m_zoneConnection                 = aFootprint.m_zoneConnection;
    m_netTiePadGroups                = aFootprint.m_netTiePadGroups;
    m_fileFormatVersionAtLoad        = aFootprint.m_fileFormatVersionAtLoad;

    m_componentClass                 = aFootprint.m_componentClass;

    std::map<BOARD_ITEM*, BOARD_ITEM*> ptrMap;

    for( [[maybe_unused]] int id : MANDATORY_FIELDS )
        m_fields.push_back( nullptr );

    // Copy fields
    for( PCB_FIELD* field : aFootprint.m_fields )
    {
        if( field )
        {
            PCB_FIELD* newField = static_cast<PCB_FIELD*>( field->Clone() );
            ptrMap[field] = newField;
            Add( newField, ADD_MODE::APPEND ); // Append to ensure indexes are identical
        }
        else
        {
            m_fields.push_back( nullptr );
        }
    }

    // Copy pads
    for( PAD* pad : aFootprint.Pads() )
    {
        PAD* newPad = static_cast<PAD*>( pad->Clone() );
        ptrMap[ pad ] = newPad;
        Add( newPad, ADD_MODE::APPEND ); // Append to ensure indexes are identical
    }

    // Copy zones
    for( ZONE* zone : aFootprint.Zones() )
    {
        ZONE* newZone = static_cast<ZONE*>( zone->Clone() );
        ptrMap[ zone ] = newZone;
        Add( newZone, ADD_MODE::APPEND ); // Append to ensure indexes are identical

        // Ensure the net info is OK and especially uses the net info list
        // living in the current board
        // Needed when copying a fp from fp editor that has its own board
        // Must be NETINFO_LIST::ORPHANED_ITEM for a keepout that has no net.
        newZone->SetNetCode( -1 );
    }

    // Copy drawings
    for( BOARD_ITEM* item : aFootprint.GraphicalItems() )
    {
        BOARD_ITEM* newItem = static_cast<BOARD_ITEM*>( item->Clone() );
        ptrMap[ item ] = newItem;
        Add( newItem, ADD_MODE::APPEND ); // Append to ensure indexes are identical
    }

    // Copy groups
    for( PCB_GROUP* group : aFootprint.Groups() )
    {
        PCB_GROUP* newGroup = static_cast<PCB_GROUP*>( group->Clone() );
        ptrMap[ group ] = newGroup;
        Add( newGroup, ADD_MODE::APPEND ); // Append to ensure indexes are identical
    }

    // Rebuild groups
    for( PCB_GROUP* group : aFootprint.Groups() )
    {
        PCB_GROUP* newGroup = static_cast<PCB_GROUP*>( ptrMap[ group ] );

        newGroup->GetItems().clear();

        for( BOARD_ITEM* member : group->GetItems() )
        {
            if( ptrMap.count( member ) )
                newGroup->AddItem( ptrMap[ member ] );
        }
    }

    for( auto& [ name, file ] : aFootprint.EmbeddedFileMap() )
        AddFile( new EMBEDDED_FILES::EMBEDDED_FILE( *file ) );

    // Copy auxiliary data
    m_3D_Drawings   = aFootprint.m_3D_Drawings;
    m_libDescription = aFootprint.m_libDescription;
    m_keywords      = aFootprint.m_keywords;
    m_privateLayers = aFootprint.m_privateLayers;

    m_arflag        = 0;

    m_initial_comments = aFootprint.m_initial_comments ?
                         new wxArrayString( *aFootprint.m_initial_comments ) : nullptr;
}


FOOTPRINT::FOOTPRINT( FOOTPRINT&& aFootprint ) :
    BOARD_ITEM_CONTAINER( aFootprint )
{
    *this = std::move( aFootprint );
}


FOOTPRINT::~FOOTPRINT()
{
    // Untangle group parents before doing any deleting
    for( PCB_GROUP* group : m_groups )
    {
        for( BOARD_ITEM* item : group->GetItems() )
            item->SetParentGroup( nullptr );
    }

    // Clean up the owned elements
    delete m_initial_comments;

    for( PCB_FIELD* f : m_fields )
        delete f;

    m_fields.clear();

    for( PAD* p : m_pads )
        delete p;

    m_pads.clear();

    for( ZONE* zone : m_zones )
        delete zone;

    m_zones.clear();

    for( PCB_GROUP* group : m_groups )
        delete group;

    m_groups.clear();

    for( BOARD_ITEM* d : m_drawings )
        delete d;

    m_drawings.clear();

    if( BOARD* board = GetBoard() )
        board->IncrementTimeStamp();
}


void FOOTPRINT::Serialize( google::protobuf::Any &aContainer ) const
{
    using namespace kiapi::board;
    types::FootprintInstance footprint;

    footprint.mutable_id()->set_value( m_Uuid.AsStdString() );
    footprint.mutable_position()->set_x_nm( GetPosition().x );
    footprint.mutable_position()->set_y_nm( GetPosition().y );
    footprint.mutable_orientation()->set_value_degrees( GetOrientationDegrees() );
    footprint.set_layer( ToProtoEnum<PCB_LAYER_ID, types::BoardLayer>( GetLayer() ) );
    footprint.set_locked( IsLocked() ? kiapi::common::types::LockedState::LS_LOCKED
                                     : kiapi::common::types::LockedState::LS_UNLOCKED );

    google::protobuf::Any buf;
    GetField( REFERENCE_FIELD )->Serialize( buf );
    buf.UnpackTo( footprint.mutable_reference_field() );
    GetField( VALUE_FIELD )->Serialize( buf );
    buf.UnpackTo( footprint.mutable_value_field() );
    GetField( DATASHEET_FIELD )->Serialize( buf );
    buf.UnpackTo( footprint.mutable_datasheet_field() );
    GetField( DESCRIPTION_FIELD )->Serialize( buf );
    buf.UnpackTo( footprint.mutable_description_field() );

    types::FootprintAttributes* attrs = footprint.mutable_attributes();

    attrs->set_not_in_schematic( IsBoardOnly() );
    attrs->set_exclude_from_position_files( IsExcludedFromPosFiles() );
    attrs->set_exclude_from_bill_of_materials( IsExcludedFromBOM() );
    attrs->set_exempt_from_courtyard_requirement( AllowMissingCourtyard() );
    attrs->set_do_not_populate( IsDNP() );

    if( m_attributes & FP_THROUGH_HOLE )
        attrs->set_mounting_style( types::FootprintMountingStyle::FMS_THROUGH_HOLE );
    else if( m_attributes & FP_SMD )
        attrs->set_mounting_style( types::FootprintMountingStyle::FMS_SMD );
    else
        attrs->set_mounting_style( types::FootprintMountingStyle::FMS_UNSPECIFIED );

    types::Footprint* def = footprint.mutable_definition();

    def->mutable_id()->CopyFrom( kiapi::common::LibIdToProto( GetFPID() ) );
    // anchor?
    def->mutable_attributes()->set_description( GetLibDescription().ToStdString() );
    def->mutable_attributes()->set_keywords( GetKeywords().ToStdString() );

    // TODO: serialize library mandatory fields

    types::FootprintDesignRuleOverrides* overrides = def->mutable_overrides();

    if( GetLocalClearance().has_value() )
        overrides->mutable_copper_clearance()->set_value_nm( *GetLocalClearance() );

    if( GetLocalSolderMaskMargin().has_value() )
        overrides->mutable_solder_mask()->mutable_solder_mask_margin()->set_value_nm( *GetLocalSolderMaskMargin() );

    if( GetLocalSolderPasteMargin().has_value() )
        overrides->mutable_solder_paste()->mutable_solder_paste_margin()->set_value_nm( *GetLocalSolderPasteMargin() );

    if( GetLocalSolderPasteMarginRatio().has_value() )
        overrides->mutable_solder_paste()->mutable_solder_paste_margin_ratio()->set_value( *GetLocalSolderPasteMarginRatio() );

    overrides->set_zone_connection(
            ToProtoEnum<ZONE_CONNECTION, types::ZoneConnectionStyle>( GetLocalZoneConnection() ) );

    for( const wxString& group : GetNetTiePadGroups() )
    {
        types::NetTieDefinition* netTie = def->add_net_ties();
        wxStringTokenizer tokenizer( group, " " );

        while( tokenizer.HasMoreTokens() )
            netTie->add_pad_number( tokenizer.GetNextToken().ToStdString() );
    }

    for( PCB_LAYER_ID layer : GetPrivateLayers().Seq() )
        def->add_private_layers( ToProtoEnum<PCB_LAYER_ID, types::BoardLayer>( layer ) );

    for( const PCB_FIELD* item : m_fields )
    {
        if( !item || item->IsMandatory() )
            continue;

        google::protobuf::Any* itemMsg = def->add_items();
        item->Serialize( *itemMsg );
    }

    for( const PAD* item : Pads() )
    {
        google::protobuf::Any* itemMsg = def->add_items();
        item->Serialize( *itemMsg );
    }

    for( const BOARD_ITEM* item : GraphicalItems() )
    {
        google::protobuf::Any* itemMsg = def->add_items();
        item->Serialize( *itemMsg );
    }

    for( const ZONE* item : Zones() )
    {
        google::protobuf::Any* itemMsg = def->add_items();
        item->Serialize( *itemMsg );
    }

    for( const FP_3DMODEL& model : Models() )
    {
        google::protobuf::Any* itemMsg = def->add_items();
        types::Footprint3DModel modelMsg;
        modelMsg.set_filename( model.m_Filename.ToUTF8() );
        kiapi::common::PackVector3D( *modelMsg.mutable_scale(), model.m_Scale );
        kiapi::common::PackVector3D( *modelMsg.mutable_rotation(), model.m_Rotation );
        kiapi::common::PackVector3D( *modelMsg.mutable_offset(), model.m_Offset );
        modelMsg.set_visible( model.m_Show );
        modelMsg.set_opacity( model.m_Opacity );
        itemMsg->PackFrom( modelMsg );
    }

    // Serialized only (can't modify this from the API to change the symbol mapping)
    kiapi::common::PackSheetPath( *footprint.mutable_symbol_path(), m_path );

    aContainer.PackFrom( footprint );
}


bool FOOTPRINT::Deserialize( const google::protobuf::Any &aContainer )
{
    using namespace kiapi::board;
    types::FootprintInstance footprint;

    if( !aContainer.UnpackTo( &footprint ) )
        return false;

    const_cast<KIID&>( m_Uuid ) = KIID( footprint.id().value() );
    SetPosition( VECTOR2I( footprint.position().x_nm(), footprint.position().y_nm() ) );
    SetOrientationDegrees( footprint.orientation().value_degrees() );
    SetLayer( FromProtoEnum<PCB_LAYER_ID, types::BoardLayer>( footprint.layer() ) );
    SetLocked( footprint.locked() == kiapi::common::types::LockedState::LS_LOCKED );

    google::protobuf::Any buf;
    types::Field mandatoryField;

    if( footprint.has_reference_field() )
    {
        mandatoryField = footprint.reference_field();
        mandatoryField.mutable_id()->set_id( REFERENCE_FIELD );
        buf.PackFrom( mandatoryField );
        GetField( REFERENCE_FIELD )->Deserialize( buf );
    }

    if( footprint.has_value_field() )
    {
        mandatoryField = footprint.value_field();
        mandatoryField.mutable_id()->set_id( VALUE_FIELD );
        buf.PackFrom( mandatoryField );
        GetField( VALUE_FIELD )->Deserialize( buf );
    }

    if( footprint.has_datasheet_field() )
    {
        mandatoryField = footprint.datasheet_field();
        mandatoryField.mutable_id()->set_id( DATASHEET_FIELD );
        buf.PackFrom( mandatoryField );
        GetField( DATASHEET_FIELD )->Deserialize( buf );
    }

    if( footprint.has_description_field() )
    {
        mandatoryField = footprint.description_field();
        mandatoryField.mutable_id()->set_id( DESCRIPTION_FIELD );
        buf.PackFrom( mandatoryField );
        GetField( DESCRIPTION_FIELD )->Deserialize( buf );
    }

    m_attributes = 0;

    switch( footprint.attributes().mounting_style() )
    {
    case types::FootprintMountingStyle::FMS_THROUGH_HOLE:
        m_attributes |= FP_THROUGH_HOLE;
        break;

    case types::FootprintMountingStyle::FMS_SMD:
        m_attributes |= FP_SMD;
        break;

    default:
        break;
    }

    SetBoardOnly( footprint.attributes().not_in_schematic() );
    SetExcludedFromBOM( footprint.attributes().exclude_from_bill_of_materials() );
    SetExcludedFromPosFiles( footprint.attributes().exclude_from_position_files() );
    SetAllowMissingCourtyard( footprint.attributes().exempt_from_courtyard_requirement() );
    SetDNP( footprint.attributes().do_not_populate() );

    // Definition
    SetFPID( kiapi::common::LibIdFromProto( footprint.definition().id() ) );
    // TODO: how should anchor be handled?
    SetLibDescription( footprint.definition().attributes().description() );
    SetKeywords( footprint.definition().attributes().keywords() );

    const types::FootprintDesignRuleOverrides& overrides = footprint.overrides();

    if( overrides.has_copper_clearance() )
        SetLocalClearance( overrides.copper_clearance().value_nm() );
    else
        SetLocalClearance( std::nullopt );

    if( overrides.has_solder_mask() && overrides.solder_mask().has_solder_mask_margin() )
        SetLocalSolderMaskMargin( overrides.solder_mask().solder_mask_margin().value_nm() );
    else
        SetLocalSolderMaskMargin( std::nullopt );

    if( overrides.has_solder_paste() )
    {
        const types::SolderPasteOverrides& pasteSettings = overrides.solder_paste();

        if( pasteSettings.has_solder_paste_margin() )
            SetLocalSolderPasteMargin( pasteSettings.solder_paste_margin().value_nm() );
        else
            SetLocalSolderPasteMargin( std::nullopt );

        if( pasteSettings.has_solder_paste_margin_ratio() )
            SetLocalSolderPasteMarginRatio( pasteSettings.solder_paste_margin_ratio().value() );
        else
            SetLocalSolderPasteMarginRatio( std::nullopt );
    }

    SetLocalZoneConnection( FromProtoEnum<ZONE_CONNECTION>( overrides.zone_connection() ) );

    for( const types::NetTieDefinition& netTieMsg : footprint.definition().net_ties() )
    {
        wxString group;

        for( const std::string& pad : netTieMsg.pad_number() )
            group.Append( wxString::Format( wxT( "%s " ), pad ) );

        group.Trim();
        AddNetTiePadGroup( group );
    }

    LSET privateLayers;

    for( int layerMsg : footprint.definition().private_layers() )
    {
        auto layer = static_cast<types::BoardLayer>( layerMsg );
        privateLayers.set( FromProtoEnum<PCB_LAYER_ID, types::BoardLayer>( layer ) );
    }

    SetPrivateLayers( privateLayers );

    // Footprint items
    for( PCB_FIELD* field : m_fields )
    {
        if( field && !field->IsMandatory() )
            Remove( field );
    }

    Pads().clear();
    GraphicalItems().clear();
    Zones().clear();
    Groups().clear();
    Models().clear();

    for( const google::protobuf::Any& itemMsg : footprint.definition().items() )
    {
        std::optional<KICAD_T> type = kiapi::common::TypeNameFromAny( itemMsg );

        if( !type )
        {
            // Bit of a hack here, but eventually 3D models should be promoted to a first-class
            // object, at which point they can get their own serialization
            if( itemMsg.type_url() == "type.googleapis.com/kiapi.board.types.Footprint3DModel" )
            {
                types::Footprint3DModel modelMsg;

                if( !itemMsg.UnpackTo( &modelMsg ) )
                    continue;

                FP_3DMODEL model;

                model.m_Filename = wxString::FromUTF8( modelMsg.filename() );
                model.m_Show = modelMsg.visible();
                model.m_Opacity = modelMsg.opacity();
                model.m_Scale = kiapi::common::UnpackVector3D( modelMsg.scale() );
                model.m_Rotation = kiapi::common::UnpackVector3D( modelMsg.rotation() );
                model.m_Offset = kiapi::common::UnpackVector3D( modelMsg.offset() );

                Models().push_back( model );
            }
            else
            {
                wxLogTrace( traceApi, wxString::Format( wxS( "Attempting to unpack unknown type %s "
                                                             "from footprint message, skipping" ),
                                                        itemMsg.type_url() ) );
            }

            continue;
        }

        std::unique_ptr<BOARD_ITEM> item = CreateItemForType( *type, this );

        if( item && item->Deserialize( itemMsg ) )
            Add( item.release(), ADD_MODE::APPEND );
    }

    return true;
}


PCB_FIELD* FOOTPRINT::GetField( MANDATORY_FIELD_T aFieldType )
{
    PCB_FIELD* field = m_fields[aFieldType];
    wxASSERT_MSG( field, wxT( "Requesting a null field (likely FOOTPRINT)" ) );

    return m_fields[aFieldType];
}


const PCB_FIELD* FOOTPRINT::GetField( MANDATORY_FIELD_T aFieldType ) const
{
    const PCB_FIELD* field = m_fields[aFieldType];
    wxASSERT_MSG( field, wxT( "Requesting a null field (likely FOOTPRINT)" ) );

    return m_fields[aFieldType];
}


PCB_FIELD* FOOTPRINT::GetFieldById( int aFieldId )
{
    for( PCB_FIELD* field : m_fields )
    {
        if( field && field->GetId() == aFieldId )
            return field;
    }

    return nullptr;
}

bool FOOTPRINT::HasFieldByName( const wxString& aFieldName ) const
{
    for( PCB_FIELD* field : m_fields )
    {
        if( field && field->GetCanonicalName() == aFieldName )
            return true;
    }

    return false;
}

PCB_FIELD* FOOTPRINT::GetFieldByName( const wxString& aFieldName )
{
    if( aFieldName.empty() )
        return nullptr;

    for( PCB_FIELD* field : m_fields )
    {
        if( field && field->GetName() == aFieldName )
            return field;
    }

    return nullptr;
}


wxString FOOTPRINT::GetFieldText( const wxString& aFieldName ) const
{
    for( const PCB_FIELD* field : m_fields )
    {
        if( field && ( aFieldName == field->GetName() || aFieldName == field->GetCanonicalName() ) )
            return field->GetText();
    }

    return wxEmptyString;
}


std::vector<PCB_FIELD*> FOOTPRINT::GetFields( bool aVisibleOnly ) const
{
    std::vector<PCB_FIELD*> fields;

    for( PCB_FIELD* field : m_fields )
    {
        // FOOTPRINT field doesn't exist on FOOTPRINT, but it's kept in the m_fields vector
        // for the moment so that the MANDATORY_FIELD ids line up with vector indices.
        // This could be cleaned up by making m_fields a map in the future.
        if( !field || field->GetId() == FOOTPRINT_FIELD )
            continue;

        if( aVisibleOnly )
        {
            if( !field->IsVisible() || field->GetText().IsEmpty() )
                continue;
        }

        fields.push_back( field );
    }

    return fields;
}


void FOOTPRINT::GetFields( std::vector<PCB_FIELD*>& aVector, bool aVisibleOnly ) const
{
    aVector = GetFields( aVisibleOnly );
}


PCB_FIELD* FOOTPRINT::AddField( const PCB_FIELD& aField )
{
    int newNdx = m_fields.size();

    m_fields.push_back( new PCB_FIELD( aField ) );
    return m_fields[newNdx];
}


void FOOTPRINT::RemoveField( const wxString& aFieldName )
{
    for( unsigned i = 0; i < m_fields.size(); ++i )
    {
        if( !m_fields[i] || m_fields[ i ]->IsMandatory() )
            continue;

        if( aFieldName == m_fields[i]->GetName( false ) )
        {
            m_fields.erase( m_fields.begin() + i );
            return;
        }
    }
}


void FOOTPRINT::ApplyDefaultSettings( const BOARD& board, bool aStyleFields, bool aStyleText,
                                      bool aStyleShapes )
{
    if( aStyleFields )
    {
        for( PCB_FIELD* field : m_fields )
        {
            if( field )
                field->StyleFromSettings( board.GetDesignSettings() );
        }
    }

    for( BOARD_ITEM* item : m_drawings )
    {
        switch( item->Type() )
        {
        case PCB_TEXT_T:
        case PCB_TEXTBOX_T:
            if( aStyleText )
                item->StyleFromSettings( board.GetDesignSettings() );

            break;

        case PCB_SHAPE_T:
            if( aStyleShapes && !item->IsOnCopperLayer() )
                item->StyleFromSettings( board.GetDesignSettings() );

            break;

        default:
            break;
        }
    }
}


bool FOOTPRINT::FixUuids()
{
    // replace null UUIDs if any by a valid uuid
    std::vector< BOARD_ITEM* > item_list;

    for( PCB_FIELD* field : m_fields )
    {
        if( field )
            item_list.push_back( field );
    }

    for( PAD* pad : m_pads )
        item_list.push_back( pad );

    for( BOARD_ITEM* gr_item : m_drawings )
        item_list.push_back( gr_item );

    // Note: one cannot fix null UUIDs inside the group, but it should not happen
    // because null uuids can be found in old footprints, therefore without group
    for( PCB_GROUP* group : m_groups )
        item_list.push_back( group );

    // Probably notneeded, because old fp do not have zones. But just in case.
    for( ZONE* zone : m_zones )
        item_list.push_back( zone );

    bool changed = false;

    for( BOARD_ITEM* item : item_list )
    {
        if( item->m_Uuid == niluuid )
        {
            const_cast<KIID&>( item->m_Uuid ) = KIID();
            changed = true;
        }
    }

    return changed;
}


FOOTPRINT& FOOTPRINT::operator=( FOOTPRINT&& aOther )
{
    BOARD_ITEM::operator=( aOther );

    m_pos           = aOther.m_pos;
    m_fpid          = aOther.m_fpid;
    m_attributes    = aOther.m_attributes;
    m_fpStatus      = aOther.m_fpStatus;
    m_orient        = aOther.m_orient;
    m_lastEditTime  = aOther.m_lastEditTime;
    m_link          = aOther.m_link;
    m_path          = aOther.m_path;

    m_cachedBoundingBox              = aOther.m_cachedBoundingBox;
    m_boundingBoxCacheTimeStamp      = aOther.m_boundingBoxCacheTimeStamp;
    m_cachedTextExcludedBBox         = aOther.m_cachedTextExcludedBBox;
    m_textExcludedBBoxCacheTimeStamp = aOther.m_textExcludedBBoxCacheTimeStamp;
    m_cachedHull                     = aOther.m_cachedHull;
    m_hullCacheTimeStamp             = aOther.m_hullCacheTimeStamp;

    m_clearance                      = aOther.m_clearance;
    m_solderMaskMargin               = aOther.m_solderMaskMargin;
    m_solderPasteMargin              = aOther.m_solderPasteMargin;
    m_solderPasteMarginRatio         = aOther.m_solderPasteMarginRatio;
    m_zoneConnection                 = aOther.m_zoneConnection;
    m_netTiePadGroups                = aOther.m_netTiePadGroups;

    m_componentClass                 = aOther.m_componentClass;

    // Move the fields
    m_fields.clear();
    addMandatoryFields();

    for( PCB_FIELD* field : aOther.m_fields )
    {
        if( !field )
            continue;

        if( !field->IsMandatory() )
            Add( field );
        else
            *GetField( static_cast<MANDATORY_FIELD_T>( field->GetId() ) ) = *field;
    }

    // Move the pads
    m_pads.clear();

    for( PAD* pad : aOther.Pads() )
        Add( pad );

    aOther.Pads().clear();

    // Move the zones
    m_zones.clear();

    for( ZONE* item : aOther.Zones() )
    {
        Add( item );

        // Ensure the net info is OK and especially uses the net info list
        // living in the current board
        // Needed when copying a fp from fp editor that has its own board
        // Must be NETINFO_LIST::ORPHANED_ITEM for a keepout that has no net.
        item->SetNetCode( -1 );
    }

    aOther.Zones().clear();

    // Move the drawings
    m_drawings.clear();

    for( BOARD_ITEM* item : aOther.GraphicalItems() )
        Add( item );

    aOther.GraphicalItems().clear();

    // Move the groups
    m_groups.clear();

    for( PCB_GROUP* group : aOther.Groups() )
        Add( group );

    EMBEDDED_FILES::operator=( std::move( aOther ) );

    aOther.Groups().clear();

    // Copy auxiliary data
    m_3D_Drawings      = aOther.m_3D_Drawings;
    m_libDescription   = aOther.m_libDescription;
    m_keywords         = aOther.m_keywords;
    m_privateLayers    = aOther.m_privateLayers;

    m_initial_comments = aOther.m_initial_comments;

    // Clear the other item's containers since this is a move
    aOther.m_fields.clear();
    aOther.Pads().clear();
    aOther.Zones().clear();
    aOther.GraphicalItems().clear();
    aOther.m_initial_comments = nullptr;

    return *this;
}


FOOTPRINT& FOOTPRINT::operator=( const FOOTPRINT& aOther )
{
    BOARD_ITEM::operator=( aOther );

    m_pos           = aOther.m_pos;
    m_fpid          = aOther.m_fpid;
    m_attributes    = aOther.m_attributes;
    m_fpStatus      = aOther.m_fpStatus;
    m_orient        = aOther.m_orient;
    m_lastEditTime  = aOther.m_lastEditTime;
    m_link          = aOther.m_link;
    m_path          = aOther.m_path;

    m_cachedBoundingBox              = aOther.m_cachedBoundingBox;
    m_boundingBoxCacheTimeStamp      = aOther.m_boundingBoxCacheTimeStamp;
    m_cachedTextExcludedBBox         = aOther.m_cachedTextExcludedBBox;
    m_textExcludedBBoxCacheTimeStamp = aOther.m_textExcludedBBoxCacheTimeStamp;
    m_cachedHull                     = aOther.m_cachedHull;
    m_hullCacheTimeStamp             = aOther.m_hullCacheTimeStamp;

    m_clearance                      = aOther.m_clearance;
    m_solderMaskMargin               = aOther.m_solderMaskMargin;
    m_solderPasteMargin              = aOther.m_solderPasteMargin;
    m_solderPasteMarginRatio         = aOther.m_solderPasteMarginRatio;
    m_zoneConnection                 = aOther.m_zoneConnection;
    m_netTiePadGroups                = aOther.m_netTiePadGroups;

    m_componentClass                 = aOther.m_componentClass;

    std::map<BOARD_ITEM*, BOARD_ITEM*> ptrMap;

    // Copy fields
    m_fields.clear();

    for( PCB_FIELD* field : aOther.m_fields )
    {
        if( field )
        {
            PCB_FIELD* newField = new PCB_FIELD( *field );
            ptrMap[field] = newField;
            Add( newField );
        }
        else
        {
            m_fields.push_back( nullptr );
        }
    }

    // Copy pads
    m_pads.clear();

    for( PAD* pad : aOther.Pads() )
    {
        PAD* newPad = new PAD( *pad );
        ptrMap[ pad ] = newPad;
        Add( newPad );
    }

    // Copy zones
    m_zones.clear();

    for( ZONE* zone : aOther.Zones() )
    {
        ZONE* newZone = static_cast<ZONE*>( zone->Clone() );
        ptrMap[ zone ] = newZone;
        Add( newZone );

        // Ensure the net info is OK and especially uses the net info list
        // living in the current board
        // Needed when copying a fp from fp editor that has its own board
        // Must be NETINFO_LIST::ORPHANED_ITEM for a keepout that has no net.
        newZone->SetNetCode( -1 );
    }

    // Copy drawings
    m_drawings.clear();

    for( BOARD_ITEM* item : aOther.GraphicalItems() )
    {
        BOARD_ITEM* newItem = static_cast<BOARD_ITEM*>( item->Clone() );
        ptrMap[ item ] = newItem;
        Add( newItem );
    }

    // Copy groups
    m_groups.clear();

    for( PCB_GROUP* group : aOther.Groups() )
    {
        PCB_GROUP* newGroup = static_cast<PCB_GROUP*>( group->Clone() );
        newGroup->GetItems().clear();

        for( BOARD_ITEM* member : group->GetItems() )
            newGroup->AddItem( ptrMap[ member ] );

        Add( newGroup );
    }

    // Copy auxiliary data
    m_3D_Drawings   = aOther.m_3D_Drawings;
    m_libDescription = aOther.m_libDescription;
    m_keywords      = aOther.m_keywords;
    m_privateLayers = aOther.m_privateLayers;

    m_initial_comments = aOther.m_initial_comments ?
                            new wxArrayString( *aOther.m_initial_comments ) : nullptr;

    EMBEDDED_FILES::operator=( aOther );

    return *this;
}


void FOOTPRINT::CopyFrom( const BOARD_ITEM* aOther )
{
    wxCHECK( aOther && aOther->Type() == PCB_FOOTPRINT_T, /* void */ );
    *this = *static_cast<const FOOTPRINT*>( aOther );

    for( PAD* pad : m_pads )
        pad->SetDirty();
}


void FOOTPRINT::InvalidateGeometryCaches()
{
    m_boundingBoxCacheTimeStamp = 0;
    m_textExcludedBBoxCacheTimeStamp = 0;
    m_hullCacheTimeStamp = 0;

    m_courtyard_cache_back_hash.Clear();
    m_courtyard_cache_front_hash.Clear();
}


bool FOOTPRINT::IsConflicting() const
{
    return HasFlag( COURTYARD_CONFLICT );
}


void FOOTPRINT::GetContextualTextVars( wxArrayString* aVars ) const
{
    aVars->push_back( wxT( "REFERENCE" ) );
    aVars->push_back( wxT( "VALUE" ) );
    aVars->push_back( wxT( "LAYER" ) );
    aVars->push_back( wxT( "FOOTPRINT_LIBRARY" ) );
    aVars->push_back( wxT( "FOOTPRINT_NAME" ) );
    aVars->push_back( wxT( "SHORT_NET_NAME(<pad_number>)" ) );
    aVars->push_back( wxT( "NET_NAME(<pad_number>)" ) );
    aVars->push_back( wxT( "NET_CLASS(<pad_number>)" ) );
    aVars->push_back( wxT( "PIN_NAME(<pad_number>)" ) );
}


bool FOOTPRINT::ResolveTextVar( wxString* token, int aDepth ) const
{
    if( GetBoard() && GetBoard()->GetBoardUse() == BOARD_USE::FPHOLDER )
        return false;

    if( token->IsSameAs( wxT( "REFERENCE" ) ) )
    {
        *token = Reference().GetShownText( false, aDepth + 1 );
        return true;
    }
    else if( token->IsSameAs( wxT( "VALUE" ) ) )
    {
        *token = Value().GetShownText( false, aDepth + 1 );
        return true;
    }
    else if( token->IsSameAs( wxT( "LAYER" ) ) )
    {
        *token = GetLayerName();
        return true;
    }
    else if( token->IsSameAs( wxT( "FOOTPRINT_LIBRARY" ) ) )
    {
        *token = m_fpid.GetUniStringLibNickname();
        return true;
    }
    else if( token->IsSameAs( wxT( "FOOTPRINT_NAME" ) ) )
    {
        *token = m_fpid.GetUniStringLibItemName();
        return true;
    }
    else if( token->StartsWith( wxT( "SHORT_NET_NAME(" ) )
                 || token->StartsWith( wxT( "NET_NAME(" ) )
                 || token->StartsWith( wxT( "NET_CLASS(" ) )
                 || token->StartsWith( wxT( "PIN_NAME(" ) ) )
    {
        wxString padNumber = token->AfterFirst( '(' );
        padNumber = padNumber.BeforeLast( ')' );

        for( PAD* pad : Pads() )
        {
            if( pad->GetNumber() == padNumber )
            {
                if( token->StartsWith( wxT( "SHORT_NET_NAME" ) ) )
                    *token = pad->GetShortNetname();
                else if( token->StartsWith( wxT( "NET_NAME" ) ) )
                    *token = pad->GetNetname();
                else if( token->StartsWith( wxT( "NET_CLASS" ) ) )
                    *token = pad->GetNetClassName();
                else
                    *token = pad->GetPinFunction();

                return true;
            }
        }
    }
    else if( HasFieldByName( *token ) )
    {
        *token = GetFieldText( *token );
        return true;
    }

    if( GetBoard() && GetBoard()->ResolveTextVar( token, aDepth + 1 ) )
        return true;

    return false;
}


void FOOTPRINT::ClearAllNets()
{
    // Force the ORPHANED dummy net info for all pads.
    // ORPHANED dummy net does not depend on a board
    for( PAD* pad : m_pads )
        pad->SetNetCode( NETINFO_LIST::ORPHANED );
}


void FOOTPRINT::Add( BOARD_ITEM* aBoardItem, ADD_MODE aMode, bool aSkipConnectivity )
{
    switch( aBoardItem->Type() )
    {
    case PCB_FIELD_T:
    {
        PCB_FIELD* field = static_cast<PCB_FIELD*>( aBoardItem );

        if( field->IsMandatory() )
        {
            wxASSERT( m_fields.size() >= MANDATORY_FIELD_COUNT
                        && m_fields[ field->GetId() ] == nullptr );

            m_fields[ field->GetId() ] = field;
        }
        else
        {
            m_fields.push_back( static_cast<PCB_FIELD*>( aBoardItem ) );
        }

        break;
    }

    case PCB_TEXT_T:
    case PCB_DIM_ALIGNED_T:
    case PCB_DIM_LEADER_T:
    case PCB_DIM_CENTER_T:
    case PCB_DIM_RADIAL_T:
    case PCB_DIM_ORTHOGONAL_T:
    case PCB_SHAPE_T:
    case PCB_TEXTBOX_T:
    case PCB_TABLE_T:
    case PCB_REFERENCE_IMAGE_T:
        if( aMode == ADD_MODE::APPEND )
            m_drawings.push_back( aBoardItem );
        else
            m_drawings.push_front( aBoardItem );

        break;

    case PCB_PAD_T:
        if( aMode == ADD_MODE::APPEND )
            m_pads.push_back( static_cast<PAD*>( aBoardItem ) );
        else
            m_pads.push_front( static_cast<PAD*>( aBoardItem ) );

        break;

    case PCB_ZONE_T:
        if( aMode == ADD_MODE::APPEND )
            m_zones.push_back( static_cast<ZONE*>( aBoardItem ) );
        else
            m_zones.insert( m_zones.begin(), static_cast<ZONE*>( aBoardItem ) );

        break;

    case PCB_GROUP_T:
        if( aMode == ADD_MODE::APPEND )
            m_groups.push_back( static_cast<PCB_GROUP*>( aBoardItem ) );
        else
            m_groups.insert( m_groups.begin(), static_cast<PCB_GROUP*>( aBoardItem ) );

        break;

    default:
    {
        wxString msg;
        msg.Printf( wxT( "FOOTPRINT::Add() needs work: BOARD_ITEM type (%d) not handled" ),
                    aBoardItem->Type() );
        wxFAIL_MSG( msg );

        return;
    }
    }

    aBoardItem->ClearEditFlags();
    aBoardItem->SetParent( this );
}


void FOOTPRINT::Remove( BOARD_ITEM* aBoardItem, REMOVE_MODE aMode )
{
    switch( aBoardItem->Type() )
    {
    case PCB_FIELD_T:
    {
        PCB_FIELD* field = static_cast<PCB_FIELD*>( aBoardItem );

        if( field->IsMandatory() )
        {
            m_fields[ field->GetId() ] = nullptr;
        }
        else
        {
            for( auto it = m_fields.begin(); it != m_fields.end(); ++it )
            {
                if( *it == field )
                {
                    m_fields.erase( it );
                    break;
                }
            }
        }

        break;
    }

    case PCB_TEXT_T:
    case PCB_DIM_ALIGNED_T:
    case PCB_DIM_CENTER_T:
    case PCB_DIM_ORTHOGONAL_T:
    case PCB_DIM_RADIAL_T:
    case PCB_DIM_LEADER_T:
    case PCB_SHAPE_T:
    case PCB_TEXTBOX_T:
    case PCB_TABLE_T:
    case PCB_REFERENCE_IMAGE_T:
        for( auto it = m_drawings.begin(); it != m_drawings.end(); ++it )
        {
            if( *it == aBoardItem )
            {
                m_drawings.erase( it );
                break;
            }
        }

        break;

    case PCB_PAD_T:
        for( auto it = m_pads.begin(); it != m_pads.end(); ++it )
        {
            if( *it == static_cast<PAD*>( aBoardItem ) )
            {
                m_pads.erase( it );
                break;
            }
        }

        break;

    case PCB_ZONE_T:
        for( auto it = m_zones.begin(); it != m_zones.end(); ++it )
        {
            if( *it == static_cast<ZONE*>( aBoardItem ) )
            {
                m_zones.erase( it );
                break;
            }
        }

        break;

    case PCB_GROUP_T:
        for( auto it = m_groups.begin(); it != m_groups.end(); ++it )
        {
            if( *it == static_cast<PCB_GROUP*>( aBoardItem ) )
            {
                m_groups.erase( it );
                break;
            }
        }

        break;

    default:
    {
        wxString msg;
        msg.Printf( wxT( "FOOTPRINT::Remove() needs work: BOARD_ITEM type (%d) not handled" ),
                    aBoardItem->Type() );
        wxFAIL_MSG( msg );
    }
    }

    aBoardItem->SetFlags( STRUCT_DELETED );

    PCB_GROUP* parentGroup = aBoardItem->GetParentGroup();

    if( parentGroup && !( parentGroup->GetFlags() & STRUCT_DELETED ) )
        parentGroup->RemoveItem( aBoardItem );
}


double FOOTPRINT::GetArea( int aPadding ) const
{
    BOX2I bbox = GetBoundingBox( false );

    double w = std::abs( static_cast<double>( bbox.GetWidth() ) ) + aPadding;
    double h = std::abs( static_cast<double>( bbox.GetHeight() ) ) + aPadding;
    return w * h;
}


int FOOTPRINT::GetLikelyAttribute() const
{
    int smd_count = 0;
    int tht_count = 0;

    for( PAD* pad : m_pads )
    {
        switch( pad->GetProperty() )
        {
        case PAD_PROP::FIDUCIAL_GLBL:
        case PAD_PROP::FIDUCIAL_LOCAL:
            continue;

        case PAD_PROP::HEATSINK:
        case PAD_PROP::CASTELLATED:
        case PAD_PROP::MECHANICAL:
            continue;

        case PAD_PROP::NONE:
        case PAD_PROP::BGA:
        case PAD_PROP::TESTPOINT:
            break;
        }

        switch( pad->GetAttribute() )
        {
        case PAD_ATTRIB::PTH:
            tht_count++;
            break;

        case PAD_ATTRIB::SMD:
            if( pad->IsOnCopperLayer() )
                smd_count++;

            break;

        default:
            break;
        }
    }

    // Footprints with plated through-hole pads should usually be marked through hole even if they
    // also have SMD because they might not be auto-placed.  Exceptions to this might be shielded
    if( tht_count > 0 )
        return FP_THROUGH_HOLE;

    if( smd_count > 0 )
        return FP_SMD;

    return 0;
}


wxString FOOTPRINT::GetTypeName() const
{
    if( ( m_attributes & FP_SMD ) == FP_SMD )
        return _( "SMD" );

    if( ( m_attributes & FP_THROUGH_HOLE ) == FP_THROUGH_HOLE )
        return _( "Through hole" );

    return _( "Other" );
}


BOX2I FOOTPRINT::GetFpPadsLocalBbox() const
{
    BOX2I bbox;

    // We want the bounding box of the footprint pads at rot 0, not flipped
    // Create such a image:
    FOOTPRINT dummy( *this );

    dummy.SetPosition( VECTOR2I( 0, 0 ) );
    dummy.SetOrientation( ANGLE_0 );

    if( dummy.IsFlipped() )
        dummy.Flip( VECTOR2I( 0, 0 ), FLIP_DIRECTION::TOP_BOTTOM );

    for( PAD* pad : dummy.Pads() )
        bbox.Merge( pad->GetBoundingBox() );

    // Remove the parent and the group from the dummy footprint before deletion
    dummy.SetParent( nullptr );
    dummy.SetParentGroup( nullptr );

    return bbox;
}


bool FOOTPRINT::TextOnly() const
{
    for( BOARD_ITEM* item : m_drawings )
    {
        if( m_privateLayers.test( item->GetLayer() ) )
            continue;

        if( item->Type() != PCB_FIELD_T && item->Type() != PCB_TEXT_T )
            return false;
    }

    return true;
}


const BOX2I FOOTPRINT::GetBoundingBox() const
{
    return GetBoundingBox( true );
}


const BOX2I FOOTPRINT::GetBoundingBox( bool aIncludeText ) const
{
    const BOARD* board = GetBoard();

    if( board )
    {
        if( aIncludeText )
        {
            if( m_boundingBoxCacheTimeStamp >= board->GetTimeStamp() )
                return m_cachedBoundingBox;
        }
        else
        {
            if( m_textExcludedBBoxCacheTimeStamp >= board->GetTimeStamp() )
                return m_cachedTextExcludedBBox;
        }
    }

    std::vector<PCB_TEXT*> texts;
    bool                   isFPEdit = board && board->IsFootprintHolder();

    BOX2I bbox( m_pos );
    bbox.Inflate( pcbIUScale.mmToIU( 0.25 ) );   // Give a min size to the bbox

    // Calculate the footprint side
    PCB_LAYER_ID footprintSide = GetSide();

    for( BOARD_ITEM* item : m_drawings )
    {
        if( m_privateLayers.test( item->GetLayer() ) && !isFPEdit )
            continue;

        // We want the bitmap bounding box just in the footprint editor
        // so it will start with the correct initial zoom
        if( item->Type() == PCB_REFERENCE_IMAGE_T && !isFPEdit )
            continue;

        // Handle text separately
        if( item->Type() == PCB_TEXT_T )
        {
            texts.push_back( static_cast<PCB_TEXT*>( item ) );
            continue;
        }

        // If we're not including text then drop annotations as well -- unless, of course, it's
        // an unsided footprint -- in which case it's likely to be nothing *but* annotations.
        if( !aIncludeText && footprintSide != UNDEFINED_LAYER )
        {
            if( BaseType( item->Type() ) == PCB_DIMENSION_T )
                continue;

            if( item->GetLayer() == Cmts_User || item->GetLayer() == Dwgs_User
                || item->GetLayer() == Eco1_User || item->GetLayer() == Eco2_User )
            {
                continue;
            }
        }

        bbox.Merge( item->GetBoundingBox() );
    }

    for( PCB_FIELD* field : m_fields )
    {
        // Reference and value get their own processing
        if( field && !field->IsReference() && !field->IsValue() )
            texts.push_back( field );
    }

    for( PAD* pad : m_pads )
        bbox.Merge( pad->GetBoundingBox() );

    for( ZONE* zone : m_zones )
        bbox.Merge( zone->GetBoundingBox() );

    bool noDrawItems = ( m_drawings.empty() && m_pads.empty() && m_zones.empty() );

    // Groups do not contribute to the rect, only their members
    if( aIncludeText || noDrawItems )
    {
        // Only PCB_TEXT and PCB_FIELD items are independently selectable; PCB_TEXTBOX items go
        // in with other graphic items above.
        for( PCB_TEXT* text : texts )
        {
            if( !isFPEdit && m_privateLayers.test( text->GetLayer() ) )
                continue;

            if( text->Type() == PCB_FIELD_T && !text->IsVisible() )
                continue;

            bbox.Merge( text->GetBoundingBox() );
        }

        // This can be further optimized when aIncludeInvisibleText is true, but currently
        // leaving this as is until it's determined there is a noticeable speed hit.
        bool   valueLayerIsVisible = true;
        bool   refLayerIsVisible   = true;

        if( board )
        {
            // The first "&&" conditional handles the user turning layers off as well as layers
            // not being present in the current PCB stackup.  Values, references, and all
            // footprint text can also be turned off via the GAL meta-layers, so the 2nd and
            // 3rd "&&" conditionals handle that.
            valueLayerIsVisible = board->IsLayerVisible( Value().GetLayer() )
                                  && board->IsElementVisible( LAYER_FP_VALUES )
                                  && board->IsElementVisible( LAYER_FP_TEXT );

            refLayerIsVisible = board->IsLayerVisible( Reference().GetLayer() )
                                && board->IsElementVisible( LAYER_FP_REFERENCES )
                                && board->IsElementVisible( LAYER_FP_TEXT );
        }


        if( ( Value().IsVisible() && valueLayerIsVisible ) || noDrawItems )
        {
            bbox.Merge( Value().GetBoundingBox() );
        }

        if( ( Reference().IsVisible() && refLayerIsVisible ) || noDrawItems )
        {
            bbox.Merge( Reference().GetBoundingBox() );
        }
    }

    if( board )
    {
        if( aIncludeText || noDrawItems )
        {
            m_boundingBoxCacheTimeStamp = board->GetTimeStamp();
            m_cachedBoundingBox = bbox;
        }
        else
        {
            m_textExcludedBBoxCacheTimeStamp = board->GetTimeStamp();
            m_cachedTextExcludedBBox = bbox;
        }
    }

    return bbox;
}


const BOX2I FOOTPRINT::GetLayerBoundingBox( LSET aLayers ) const
{
    std::vector<PCB_TEXT*> texts;
    const BOARD* board = GetBoard();
    bool         isFPEdit = board && board->IsFootprintHolder();

    // Start with an uninitialized bounding box
    BOX2I bbox;

    for( BOARD_ITEM* item : m_drawings )
    {
        if( m_privateLayers.test( item->GetLayer() ) && !isFPEdit )
            continue;

        if( ( aLayers & item->GetLayerSet() ).none() )
            continue;

        // We want the bitmap bounding box just in the footprint editor
        // so it will start with the correct initial zoom
        if( item->Type() == PCB_REFERENCE_IMAGE_T && !isFPEdit )
            continue;

        bbox.Merge( item->GetBoundingBox() );
    }

    for( PAD* pad : m_pads )
    {
        if( ( aLayers & pad->GetLayerSet() ).none() )
            continue;

        bbox.Merge( pad->GetBoundingBox() );
    }

    for( ZONE* zone : m_zones )
    {
        if( ( aLayers & zone->GetLayerSet() ).none() )
            continue;

        bbox.Merge( zone->GetBoundingBox() );
    }

    return bbox;
}


SHAPE_POLY_SET FOOTPRINT::GetBoundingHull() const
{
    const BOARD* board = GetBoard();
    bool         isFPEdit = board && board->IsFootprintHolder();

    if( board )
    {
        if( m_hullCacheTimeStamp >= board->GetTimeStamp() )
            return m_cachedHull;
    }

    SHAPE_POLY_SET rawPolys;
    SHAPE_POLY_SET hull;

    for( BOARD_ITEM* item : m_drawings )
    {
        if( !isFPEdit && m_privateLayers.test( item->GetLayer() ) )
            continue;

        if( item->Type() != PCB_FIELD_T && item->Type() != PCB_REFERENCE_IMAGE_T )
        {
            item->TransformShapeToPolygon( rawPolys, UNDEFINED_LAYER, 0, ARC_LOW_DEF,
                                           ERROR_OUTSIDE );
        }

        // We intentionally exclude footprint fields from the bounding hull.
    }

    for( PAD* pad : m_pads )
    {
        pad->Padstack().ForEachUniqueLayer(
            [&]( PCB_LAYER_ID aLayer )
            {
                pad->TransformShapeToPolygon( rawPolys, aLayer, 0, ARC_LOW_DEF, ERROR_OUTSIDE );
            } );

        // In case hole is larger than pad
        pad->TransformHoleToPolygon( rawPolys, 0, ARC_LOW_DEF, ERROR_OUTSIDE );
    }

    for( ZONE* zone : m_zones )
    {
        for( PCB_LAYER_ID layer : zone->GetLayerSet().Seq() )
        {
            const SHAPE_POLY_SET& layerPoly = *zone->GetFilledPolysList( layer );

            for( int ii = 0; ii < layerPoly.OutlineCount(); ii++ )
            {
                const SHAPE_LINE_CHAIN& poly = layerPoly.COutline( ii );
                rawPolys.AddOutline( poly );
            }
        }
    }

    // If there are some graphic items, build the actual hull.
    // However if no items, create a minimal polygon (can happen if a footprint
    // is created with no item: it contains only 2 texts.
    if( rawPolys.OutlineCount() == 0 || rawPolys.FullPointCount() < 3 )
    {
        // generate a small dummy rectangular outline around the anchor
        const int halfsize = pcbIUScale.mmToIU( 1.0 );

        rawPolys.NewOutline();

        // add a square:
        rawPolys.Append( GetPosition().x - halfsize,  GetPosition().y - halfsize );
        rawPolys.Append( GetPosition().x + halfsize,  GetPosition().y - halfsize );
        rawPolys.Append( GetPosition().x + halfsize,  GetPosition().y + halfsize );
        rawPolys.Append( GetPosition().x - halfsize,  GetPosition().y + halfsize );
    }

    std::vector<VECTOR2I> convex_hull;
    BuildConvexHull( convex_hull, rawPolys );

    m_cachedHull.RemoveAllContours();
    m_cachedHull.NewOutline();

    for( const VECTOR2I& pt : convex_hull )
        m_cachedHull.Append( pt );

    if( board )
        m_hullCacheTimeStamp = board->GetTimeStamp();

    return m_cachedHull;
}


void FOOTPRINT::GetMsgPanelInfo( EDA_DRAW_FRAME* aFrame, std::vector<MSG_PANEL_ITEM>& aList )
{
    wxString msg, msg2;

    // Don't use GetShownText(); we want to see the variable references here
    aList.emplace_back( UnescapeString( Reference().GetText() ),
                        UnescapeString( Value().GetText() ) );

    if( aFrame->IsType( FRAME_FOOTPRINT_VIEWER )
        || aFrame->IsType( FRAME_FOOTPRINT_CHOOSER )
        || aFrame->IsType( FRAME_FOOTPRINT_EDITOR ) )
    {
        size_t     padCount = GetPadCount( DO_NOT_INCLUDE_NPTH );

        aList.emplace_back( _( "Library" ), GetFPID().GetLibNickname().wx_str() );

        aList.emplace_back( _( "Footprint Name" ), GetFPID().GetLibItemName().wx_str() );

        aList.emplace_back( _( "Pads" ), wxString::Format( wxT( "%zu" ), padCount ) );

        aList.emplace_back( wxString::Format( _( "Doc: %s" ), GetLibDescription() ),
                            wxString::Format( _( "Keywords: %s" ), GetKeywords() ) );

        return;
    }

    // aFrame is the board editor:

    switch( GetSide() )
    {
    case F_Cu: aList.emplace_back( _( "Board Side" ), _( "Front" ) );          break;
    case B_Cu: aList.emplace_back( _( "Board Side" ), _( "Back (Flipped)" ) ); break;
    default:   /* unsided: user-layers only, etc. */                           break;
    }

    auto addToken = []( wxString* aStr, const wxString& aAttr )
                    {
                        if( !aStr->IsEmpty() )
                            *aStr += wxT( ", " );

                        *aStr += aAttr;
                    };

    wxString status;
    wxString attrs;

    if( IsLocked() )
        addToken( &status, _( "Locked" ) );

    if( m_fpStatus & FP_is_PLACED )
        addToken( &status, _( "autoplaced" ) );

    if( m_attributes & FP_BOARD_ONLY )
        addToken( &attrs, _( "not in schematic" ) );

    if( m_attributes & FP_EXCLUDE_FROM_POS_FILES )
        addToken( &attrs, _( "exclude from pos files" ) );

    if( m_attributes & FP_EXCLUDE_FROM_BOM )
        addToken( &attrs, _( "exclude from BOM" ) );

    if( m_attributes & FP_DNP )
        addToken( &attrs, _( "DNP" ) );

    aList.emplace_back( _( "Status: " ) + status, _( "Attributes:" ) + wxS( " " ) + attrs );

    aList.emplace_back( _( "Rotation" ), wxString::Format( wxT( "%.4g" ),
                                                           GetOrientation().AsDegrees() ) );

    if( m_componentClass )
    {
        aList.emplace_back( _( "Component Class" ), m_componentClass->GetName() );
    }

    msg.Printf( _( "Footprint: %s" ), m_fpid.GetUniStringLibId() );
    msg2.Printf( _( "3D-Shape: %s" ), m_3D_Drawings.empty() ? _( "<none>" )
                                                            : m_3D_Drawings.front().m_Filename );
    aList.emplace_back( msg, msg2 );

    msg.Printf( _( "Doc: %s" ), m_libDescription );
    msg2.Printf( _( "Keywords: %s" ), m_keywords );
    aList.emplace_back( msg, msg2 );
}


PCB_LAYER_ID FOOTPRINT::GetSide() const
{
    if( const BOARD* board = GetBoard() )
    {
        if( board->IsFootprintHolder() )
            return UNDEFINED_LAYER;
    }

    // Test pads first; they're the most likely to return a quick answer.
    for( PAD* pad : m_pads )
    {
        if( ( LSET::SideSpecificMask() & pad->GetLayerSet() ).any() )
            return GetLayer();
    }

    for( BOARD_ITEM* item : m_drawings )
    {
        if( LSET::SideSpecificMask().test( item->GetLayer() ) )
            return GetLayer();
    }

    for( ZONE* zone : m_zones )
    {
        if( ( LSET::SideSpecificMask() & zone->GetLayerSet() ).any() )
            return GetLayer();
    }

    return UNDEFINED_LAYER;
}


bool FOOTPRINT::IsOnLayer( PCB_LAYER_ID aLayer ) const
{
    // If we have any pads, fall back on normal checking
    for( PAD* pad : m_pads )
    {
        if( pad->IsOnLayer( aLayer ) )
            return true;
    }

    for( ZONE* zone : m_zones )
    {
        if( zone->IsOnLayer( aLayer ) )
            return true;
    }

    for( PCB_FIELD* field : m_fields )
    {
        if( field && field->IsOnLayer( aLayer ) )
            return true;
    }

    for( BOARD_ITEM* item : m_drawings )
    {
        if( item->IsOnLayer( aLayer ) )
            return true;
    }

    return false;
}


bool FOOTPRINT::HitTestOnLayer( const VECTOR2I& aPosition, PCB_LAYER_ID aLayer, int aAccuracy ) const
{
    for( PAD* pad : m_pads )
    {
        if( pad->IsOnLayer( aLayer ) && pad->HitTest( aPosition, aAccuracy ) )
            return true;
    }

    for( ZONE* zone : m_zones )
    {
        if( zone->IsOnLayer( aLayer ) && zone->HitTest( aPosition, aAccuracy ) )
            return true;
    }

    for( BOARD_ITEM* item : m_drawings )
    {
        if( item->Type() != PCB_TEXT_T && item->IsOnLayer( aLayer )
            && item->HitTest( aPosition, aAccuracy ) )
        {
            return true;
        }
    }

    return false;
}


bool FOOTPRINT::HitTestOnLayer( const BOX2I& aRect, bool aContained, PCB_LAYER_ID aLayer, int aAccuracy ) const
{
    std::vector<BOARD_ITEM*> items;

    for( PAD* pad : m_pads )
    {
        if( pad->IsOnLayer( aLayer ) )
            items.push_back( pad );
    }

    for( ZONE* zone : m_zones )
    {
        if( zone->IsOnLayer( aLayer ) )
            items.push_back( zone );
    }

    for( BOARD_ITEM* item : m_drawings )
    {
        if( item->Type() != PCB_TEXT_T && item->IsOnLayer( aLayer ) )
            items.push_back( item );
    }

    // If we require the elements to be contained in the rect and any of them are not,
    // we can return false;
    // Conversely, if we just require any of the elements to have a hit, we can return true
    // when the first one is found.
    for( BOARD_ITEM* item : items )
    {
        if( !aContained && item->HitTest( aRect, aContained, aAccuracy ) )
            return true;
        else if( aContained && !item->HitTest( aRect, aContained, aAccuracy ) )
            return false;
    }

    // If we didn't exit in the loop, that means that we did not return false for aContained or
    // we did not return true for !aContained.  So we can just return the bool with a test of
    // whether there were any elements or not.
    return !items.empty() && aContained;
}


bool FOOTPRINT::HitTest( const VECTOR2I& aPosition, int aAccuracy ) const
{
    BOX2I rect = GetBoundingBox( false );
    return rect.Inflate( aAccuracy ).Contains( aPosition );
}


bool FOOTPRINT::HitTestAccurate( const VECTOR2I& aPosition, int aAccuracy ) const
{
    return GetBoundingHull().Collide( aPosition, aAccuracy );
}


bool FOOTPRINT::HitTest( const BOX2I& aRect, bool aContained, int aAccuracy ) const
{
    BOX2I arect = aRect;
    arect.Inflate( aAccuracy );

    if( aContained )
    {
        return arect.Contains( GetBoundingBox( false ) );
    }
    else
    {
        // If the rect does not intersect the bounding box, skip any tests
        if( !aRect.Intersects( GetBoundingBox( false ) ) )
            return false;

        // If there are no pads, zones, or drawings, allow intersection with text
        if( m_pads.empty() && m_zones.empty() && m_drawings.empty() )
            return GetBoundingBox( true ).Intersects( arect );

        // Determine if any elements in the FOOTPRINT intersect the rect
        for( PAD* pad : m_pads )
        {
            if( pad->HitTest( arect, false, 0 ) )
                return true;
        }

        for( ZONE* zone : m_zones )
        {
            if( zone->HitTest( arect, false, 0 ) )
                return true;
        }

        // PCB fields are selectable on their own, so they don't get tested

        for( BOARD_ITEM* item : m_drawings )
        {
            // Text items are selectable on their own, and are therefore excluded from this
            // test.  TextBox items are NOT selectable on their own, and so MUST be included
            // here. Bitmaps aren't selectable since they aren't displayed.
            if( item->Type() != PCB_TEXT_T && item->HitTest( arect, false, 0 ) )
                return true;
        }

        // Groups are not hit-tested; only their members

        // No items were hit
        return false;
    }
}


PAD* FOOTPRINT::FindPadByNumber( const wxString& aPadNumber, PAD* aSearchAfterMe ) const
{
    bool can_select = aSearchAfterMe ? false : true;

    for( PAD* pad : m_pads )
    {
        if( !can_select && pad == aSearchAfterMe )
        {
            can_select = true;
            continue;
        }

        if( can_select && pad->GetNumber() == aPadNumber )
            return pad;
    }

    return nullptr;
}


PAD* FOOTPRINT::GetPad( const VECTOR2I& aPosition, LSET aLayerMask )
{
    for( PAD* pad : m_pads )
    {
        // ... and on the correct layer.
        if( !( pad->GetLayerSet() & aLayerMask ).any() )
            continue;

        if( pad->HitTest( aPosition ) )
            return pad;
    }

    return nullptr;
}


std::vector<const PAD*> FOOTPRINT::GetPads( const wxString& aPadNumber, const PAD* aIgnore ) const
{
    std::vector<const PAD*> retv;

    for( const PAD* pad : m_pads )
    {
        if( ( aIgnore && aIgnore == pad ) || ( pad->GetNumber() != aPadNumber ) )
            continue;

        retv.push_back( pad );
    }

    return retv;
}


unsigned FOOTPRINT::GetPadCount( INCLUDE_NPTH_T aIncludeNPTH ) const
{
    if( aIncludeNPTH )
        return m_pads.size();

    unsigned cnt = 0;

    for( PAD* pad : m_pads )
    {
        if( pad->GetAttribute() == PAD_ATTRIB::NPTH )
            continue;

        cnt++;
    }

    return cnt;
}


std::set<wxString> FOOTPRINT::GetUniquePadNumbers( INCLUDE_NPTH_T aIncludeNPTH ) const
{
    std::set<wxString> usedNumbers;

    // Create a set of used pad numbers
    for( PAD* pad : m_pads )
    {
        // Skip pads not on copper layers (used to build complex
        // solder paste shapes for instance)
        if( ( pad->GetLayerSet() & LSET::AllCuMask() ).none() )
            continue;

        // Skip pads with no name, because they are usually "mechanical"
        // pads, not "electrical" pads
        if( pad->GetNumber().IsEmpty() )
            continue;

        if( !aIncludeNPTH )
        {
            // skip NPTH
            if( pad->GetAttribute() == PAD_ATTRIB::NPTH )
                continue;
        }

        usedNumbers.insert( pad->GetNumber() );
    }

    return usedNumbers;
}


unsigned FOOTPRINT::GetUniquePadCount( INCLUDE_NPTH_T aIncludeNPTH ) const
{
    return GetUniquePadNumbers( aIncludeNPTH ).size();
}


void FOOTPRINT::Add3DModel( FP_3DMODEL* a3DModel )
{
    if( nullptr == a3DModel )
        return;

    if( !a3DModel->m_Filename.empty() )
        m_3D_Drawings.push_back( *a3DModel );
}


// see footprint.h
INSPECT_RESULT FOOTPRINT::Visit( INSPECTOR inspector, void* testData,
                                 const std::vector<KICAD_T>& aScanTypes )
{
#if 0 && defined(DEBUG)
    std::cout << GetClass().mb_str() << ' ';
#endif

    bool drawingsScanned = false;

    for( KICAD_T scanType : aScanTypes )
    {
        switch( scanType )
        {
        case PCB_FOOTPRINT_T:
            if( inspector( this, testData ) == INSPECT_RESULT::QUIT )
                return INSPECT_RESULT::QUIT;

            break;

        case PCB_PAD_T:
            if( IterateForward<PAD*>( m_pads, inspector, testData, { scanType } )
                    == INSPECT_RESULT::QUIT )
            {
                return INSPECT_RESULT::QUIT;
            }

            break;

        case PCB_ZONE_T:
            if( IterateForward<ZONE*>( m_zones, inspector, testData, { scanType } )
                    == INSPECT_RESULT::QUIT )
            {
                return INSPECT_RESULT::QUIT;
            }

            break;

        case PCB_FIELD_T:
            if( IterateForward<PCB_FIELD*>( m_fields, inspector, testData, { scanType } )
                == INSPECT_RESULT::QUIT )
            {
                return INSPECT_RESULT::QUIT;
            }

            break;

        case PCB_TEXT_T:
        case PCB_DIM_ALIGNED_T:
        case PCB_DIM_LEADER_T:
        case PCB_DIM_CENTER_T:
        case PCB_DIM_RADIAL_T:
        case PCB_DIM_ORTHOGONAL_T:
        case PCB_SHAPE_T:
        case PCB_TEXTBOX_T:
        case PCB_TABLE_T:
        case PCB_TABLECELL_T:
            if( !drawingsScanned )
            {
                if( IterateForward<BOARD_ITEM*>( m_drawings, inspector, testData, aScanTypes )
                        == INSPECT_RESULT::QUIT )
                {
                    return INSPECT_RESULT::QUIT;
                }

                drawingsScanned = true;
            }

            break;

        case PCB_GROUP_T:
            if( IterateForward<PCB_GROUP*>( m_groups, inspector, testData, { scanType } )
                    == INSPECT_RESULT::QUIT )
            {
                return INSPECT_RESULT::QUIT;
            }

            break;

        default:
            break;
        }
    }

    return INSPECT_RESULT::CONTINUE;
}


wxString FOOTPRINT::GetItemDescription( UNITS_PROVIDER* aUnitsProvider, bool aFull ) const
{
    wxString reference = GetReference();

    if( reference.IsEmpty() )
        reference = _( "<no reference designator>" );

    return wxString::Format( _( "Footprint %s" ), reference );
}


BITMAPS FOOTPRINT::GetMenuImage() const
{
    return BITMAPS::module;
}


EDA_ITEM* FOOTPRINT::Clone() const
{
    return new FOOTPRINT( *this );
}


void FOOTPRINT::RunOnChildren( const std::function<void ( BOARD_ITEM* )>& aFunction ) const
{
    try
    {
        for( PCB_FIELD* field : m_fields )
        {
            if( field )
                aFunction( field );
        }

        for( PAD* pad : m_pads )
            aFunction( pad );

        for( ZONE* zone : m_zones )
            aFunction( zone );

        for( PCB_GROUP* group : m_groups )
            aFunction( group );

        for( BOARD_ITEM* drawing : m_drawings )
            aFunction( drawing );
    }
    catch( std::bad_function_call& )
    {
        wxFAIL_MSG( wxT( "Error running FOOTPRINT::RunOnChildren" ) );
    }
}


void FOOTPRINT::RunOnDescendants( const std::function<void( BOARD_ITEM* )>& aFunction,
                                  int aDepth ) const
{
    // Avoid freezes with infinite recursion
    if( aDepth > 20 )
        return;

    try
    {
        for( PCB_FIELD* field : m_fields )
        {
            if( field )
                aFunction( field );
        }

        for( PAD* pad : m_pads )
            aFunction( pad );

        for( ZONE* zone : m_zones )
            aFunction( zone  );

        for( PCB_GROUP* group : m_groups )
            aFunction( group );

        for( BOARD_ITEM* drawing : m_drawings )
        {
            aFunction( drawing );
            drawing->RunOnDescendants( aFunction, aDepth + 1 );
        }
    }
    catch( std::bad_function_call& )
    {
        wxFAIL_MSG( wxT( "Error running FOOTPRINT::RunOnDescendants" ) );
    }
}


std::vector<int> FOOTPRINT::ViewGetLayers() const
{
    std::vector<int> layers;

    layers.reserve( 6 );
    layers.push_back( LAYER_ANCHOR );

    switch( m_layer )
    {
    default:
        wxASSERT_MSG( false, wxT( "Illegal layer" ) );   // do you really have footprints placed
                                                         // on other layers?
        KI_FALLTHROUGH;

    case F_Cu:
        layers.push_back( LAYER_FOOTPRINTS_FR );
        break;

    case B_Cu:
        layers.push_back( LAYER_FOOTPRINTS_BK );
        break;
    }

    if( IsLocked() )
        layers.push_back( LAYER_LOCKED_ITEM_SHADOW );

    if( IsConflicting() )
        layers.push_back( LAYER_CONFLICTS_SHADOW );

    // If there are no pads, and only drawings on a silkscreen layer, then report the silkscreen
    // layer as well so that the component can be edited with the silkscreen layer
    bool f_silk = false, b_silk = false, non_silk = false;

    for( BOARD_ITEM* item : m_drawings )
    {
        if( item->GetLayer() == F_SilkS )
            f_silk = true;
        else if( item->GetLayer() == B_SilkS )
            b_silk = true;
        else
            non_silk = true;
    }

    if( ( f_silk || b_silk ) && !non_silk && m_pads.empty() )
    {
        if( f_silk )
            layers.push_back( F_SilkS );

        if( b_silk )
            layers.push_back( B_SilkS );
    }

    return layers;
}


double FOOTPRINT::ViewGetLOD( int aLayer, const KIGFX::VIEW* aView ) const
{
    if( aLayer == LAYER_LOCKED_ITEM_SHADOW )
    {
        // The locked shadow shape is shown only if the footprint itself is visible
        if( ( m_layer == F_Cu ) && aView->IsLayerVisible( LAYER_FOOTPRINTS_FR ) )
            return LOD_SHOW;

        if( ( m_layer == B_Cu ) && aView->IsLayerVisible( LAYER_FOOTPRINTS_BK ) )
            return LOD_SHOW;

        return LOD_HIDE;
    }

    if( aLayer == LAYER_CONFLICTS_SHADOW && IsConflicting() )
    {
        // The locked shadow shape is shown only if the footprint itself is visible
        if( ( m_layer == F_Cu ) && aView->IsLayerVisible( LAYER_FOOTPRINTS_FR ) )
            return LOD_SHOW;

        if( ( m_layer == B_Cu ) && aView->IsLayerVisible( LAYER_FOOTPRINTS_BK ) )
            return LOD_SHOW;

        return LOD_HIDE;
    }

    int layer = ( m_layer == F_Cu ) ? LAYER_FOOTPRINTS_FR :
                ( m_layer == B_Cu ) ? LAYER_FOOTPRINTS_BK : LAYER_ANCHOR;

    // Currently this is only pertinent for the anchor layer; everything else is drawn from the
    // children.
    // The "good" value is experimentally chosen.
    constexpr double MINIMAL_ZOOM_LEVEL_FOR_VISIBILITY = 1.5;

    if( aView->IsLayerVisible( layer ) )
        return MINIMAL_ZOOM_LEVEL_FOR_VISIBILITY;

    return LOD_HIDE;
}


const BOX2I FOOTPRINT::ViewBBox() const
{
    BOX2I area = GetBoundingBox( true );

    // Inflate in case clearance lines are drawn around pads, etc.
    if( const BOARD* board = GetBoard() )
    {
        int biggest_clearance = board->GetMaxClearanceValue();
        area.Inflate( biggest_clearance );
    }

    return area;
}


bool FOOTPRINT::IsLibNameValid( const wxString & aName )
{
    const wxChar * invalids = StringLibNameInvalidChars( false );

    if( aName.find_first_of( invalids ) != std::string::npos )
        return false;

    return true;
}


const wxChar* FOOTPRINT::StringLibNameInvalidChars( bool aUserReadable )
{
    // This list of characters is also duplicated in validators.cpp and
    // lib_id.cpp
    // TODO: Unify forbidden character lists - Warning, invalid filename characters are not the same
    // as invalid LIB_ID characters.  We will need to separate the FP filenames from FP names before this
    // can be unified
    static const wxChar invalidChars[] = wxT("%$<>\t\n\r\"\\/:");
    static const wxChar invalidCharsReadable[] = wxT("% $ < > 'tab' 'return' 'line feed' \\ \" / :");

    if( aUserReadable )
        return invalidCharsReadable;
    else
        return invalidChars;
}


void FOOTPRINT::Move( const VECTOR2I& aMoveVector )
{
    if( aMoveVector.x == 0 && aMoveVector.y == 0 )
        return;

    VECTOR2I newpos = m_pos + aMoveVector;
    SetPosition( newpos );
}


void FOOTPRINT::Rotate( const VECTOR2I& aRotCentre, const EDA_ANGLE& aAngle )
{
    if( aAngle == ANGLE_0 )
        return;

    EDA_ANGLE orientation = GetOrientation();
    EDA_ANGLE newOrientation = orientation + aAngle;
    VECTOR2I  newpos = m_pos;
    RotatePoint( newpos, aRotCentre, aAngle );
    SetPosition( newpos );
    SetOrientation( newOrientation );

    for( PCB_FIELD* field : m_fields )
    {
        if( field )
            field->KeepUpright();
    }

    for( BOARD_ITEM* item : m_drawings )
    {
        if( item->Type() == PCB_TEXT_T )
            static_cast<PCB_TEXT*>( item )->KeepUpright();
    }
}


void FOOTPRINT::SetLayerAndFlip( PCB_LAYER_ID aLayer )
{
    wxASSERT( aLayer == F_Cu || aLayer == B_Cu );

    if( aLayer != GetLayer() )
        Flip( GetPosition(), FLIP_DIRECTION::LEFT_RIGHT );
}


void FOOTPRINT::Flip( const VECTOR2I& aCentre, FLIP_DIRECTION aFlipDirection )
{
    // Move footprint to its final position:
    VECTOR2I finalPos = m_pos;

    // Now Flip the footprint.
    // Flipping a footprint is a specific transform: it is not mirrored like a text.
    // We have to change the side, and ensure the footprint rotation is modified according to the
    // transform, because this parameter is used in pick and place files, and when updating the
    // footprint from library.
    // When flipped around the X axis (Y coordinates changed) orientation is negated
    // When flipped around the Y axis (X coordinates changed) orientation is 180 - old orient.
    // Because it is specific to a footprint, we flip around the X axis, and after rotate 180 deg

    MIRROR( finalPos.y, aCentre.y );     /// Mirror the Y position (around the X axis)

    SetPosition( finalPos );

    // Flip layer
    BOARD_ITEM::SetLayer( GetBoard()->FlipLayer( GetLayer() ) );

    // Calculate the new orientation, and then clear it for pad flipping.
    EDA_ANGLE newOrientation = -m_orient;
    newOrientation.Normalize180();
    m_orient = ANGLE_0;

    // Mirror fields to other side of board.
    for( PCB_FIELD* field : m_fields )
    {
        if( field )
            field->Flip( m_pos, FLIP_DIRECTION::TOP_BOTTOM );
    }

    // Mirror pads to other side of board.
    for( PAD* pad : m_pads )
        pad->Flip( m_pos, FLIP_DIRECTION::TOP_BOTTOM );

    // Now set the new orientation.
    m_orient = newOrientation;

    // Mirror zones to other side of board.
    for( ZONE* zone : m_zones )
        zone->Flip( m_pos, FLIP_DIRECTION::TOP_BOTTOM );

    // Reverse mirror footprint graphics and texts.
    for( BOARD_ITEM* item : m_drawings )
        item->Flip( m_pos, FLIP_DIRECTION::TOP_BOTTOM );

    // Now rotate 180 deg if required
    if( aFlipDirection == FLIP_DIRECTION::LEFT_RIGHT )
        Rotate( aCentre, ANGLE_180 );

    m_boundingBoxCacheTimeStamp = 0;
    m_textExcludedBBoxCacheTimeStamp = 0;

    m_cachedHull.Mirror( m_pos, aFlipDirection );

    // The courtyard caches must be rebuilt after geometry change
    BuildCourtyardCaches();
}


void FOOTPRINT::SetPosition( const VECTOR2I& aPos )
{
    VECTOR2I delta = aPos - m_pos;

    m_pos += delta;

    for( PCB_FIELD* field : m_fields )
    {
        if( field )
            field->EDA_TEXT::Offset( delta );
    }

    for( PAD* pad : m_pads )
        pad->SetPosition( pad->GetPosition() + delta );

    for( ZONE* zone : m_zones )
        zone->Move( delta );

    for( BOARD_ITEM* item : m_drawings )
        item->Move( delta );

    m_cachedBoundingBox.Move( delta );
    m_cachedTextExcludedBBox.Move( delta );
    m_cachedHull.Move( delta );

    // The geometry work has been conserved by using Move(). But the hashes
    // need to be updated, otherwise the cached polygons will still be rebuild.
    m_courtyard_cache_back.Move( delta );
    m_courtyard_cache_back_hash = m_courtyard_cache_back.GetHash();
    m_courtyard_cache_front.Move( delta );
    m_courtyard_cache_front_hash = m_courtyard_cache_front.GetHash();
}


void FOOTPRINT::MoveAnchorPosition( const VECTOR2I& aMoveVector )
{
    /*
     * Move the reference point of the footprint
     * the footprints elements (pads, outlines, edges .. ) are moved
     * but:
     * - the footprint position is not modified.
     * - the relative (local) coordinates of these items are modified
     * - Draw coordinates are updated
     */

    // Update (move) the relative coordinates relative to the new anchor point.
    VECTOR2I moveVector = aMoveVector;
    RotatePoint( moveVector, -GetOrientation() );

    // Update field local coordinates
    for( PCB_FIELD* field : m_fields )
    {
        if( field )
            field->Move( moveVector );
    }

    // Update the pad local coordinates.
    for( PAD* pad : m_pads )
        pad->Move( moveVector );

    // Update the draw element coordinates.
    for( BOARD_ITEM* item : GraphicalItems() )
        item->Move( moveVector );

    // Update the keepout zones
    for( ZONE* zone : Zones() )
        zone->Move( moveVector );

    // Update the 3D models
    for( FP_3DMODEL& model : Models() )
    {
        model.m_Offset.x += pcbIUScale.IUTomm( moveVector.x );
        model.m_Offset.y -= pcbIUScale.IUTomm( moveVector.y );
    }

    m_cachedBoundingBox.Move( moveVector );
    m_cachedTextExcludedBBox.Move( moveVector );
    m_cachedHull.Move( moveVector );

    // The geometry work have been conserved by using Move(). But the hashes
    // need to be updated, otherwise the cached polygons will still be rebuild.
    m_courtyard_cache_back.Move( moveVector );
    m_courtyard_cache_back_hash = m_courtyard_cache_back.GetHash();
    m_courtyard_cache_front.Move( moveVector );
    m_courtyard_cache_front_hash = m_courtyard_cache_front.GetHash();
}


void FOOTPRINT::SetOrientation( const EDA_ANGLE& aNewAngle )
{
    EDA_ANGLE angleChange = aNewAngle - m_orient;  // change in rotation

    m_orient = aNewAngle;
    m_orient.Normalize180();

    for( PCB_FIELD* field : m_fields )
    {
        if( field )
            field->Rotate( GetPosition(), angleChange );
    }

    for( PAD* pad : m_pads )
        pad->Rotate( GetPosition(), angleChange );

    for( ZONE* zone : m_zones )
        zone->Rotate( GetPosition(), angleChange );

    for( BOARD_ITEM* item : m_drawings )
        item->Rotate( GetPosition(), angleChange );

    m_boundingBoxCacheTimeStamp = 0;
    m_textExcludedBBoxCacheTimeStamp = 0;
    m_hullCacheTimeStamp = 0;

    // The courtyard caches need to be rebuilt, as the geometry has changed
    BuildCourtyardCaches();
}


BOARD_ITEM* FOOTPRINT::Duplicate() const
{
    FOOTPRINT* dupe = static_cast<FOOTPRINT*>( BOARD_ITEM::Duplicate() );

    dupe->RunOnDescendants( [&]( BOARD_ITEM* child )
                            {
                                const_cast<KIID&>( child->m_Uuid ) = KIID();
                            });

    return dupe;
}


BOARD_ITEM* FOOTPRINT::DuplicateItem( const BOARD_ITEM* aItem, bool aAddToFootprint )
{
    BOARD_ITEM* new_item = nullptr;

    switch( aItem->Type() )
    {
    case PCB_PAD_T:
    {
        PAD* new_pad = new PAD( *static_cast<const PAD*>( aItem ) );
        const_cast<KIID&>( new_pad->m_Uuid ) = KIID();

        if( aAddToFootprint )
            m_pads.push_back( new_pad );

        new_item = new_pad;
        break;
    }

    case PCB_ZONE_T:
    {
        ZONE* new_zone = new ZONE( *static_cast<const ZONE*>( aItem ) );
        const_cast<KIID&>( new_zone->m_Uuid ) = KIID();

        if( aAddToFootprint )
            m_zones.push_back( new_zone );

        new_item = new_zone;
        break;
    }

    case PCB_FIELD_T:
    case PCB_TEXT_T:
    {
        PCB_TEXT* new_text = new PCB_TEXT( *static_cast<const PCB_TEXT*>( aItem ) );
        const_cast<KIID&>( new_text->m_Uuid ) = KIID();

        if( aItem->Type() == PCB_FIELD_T )
        {
            switch( static_cast<const PCB_FIELD*>( aItem )->GetId() )
            {
            case REFERENCE_FIELD: new_text->SetText( wxT( "${REFERENCE}" ) ); break;

            case VALUE_FIELD: new_text->SetText( wxT( "${VALUE}" ) ); break;

            case DATASHEET_FIELD: new_text->SetText( wxT( "${DATASHEET}" ) ); break;
            }
        }

        if( aAddToFootprint )
            Add( new_text );

        new_item = new_text;
        break;
    }

    case PCB_SHAPE_T:
    {
        PCB_SHAPE* new_shape = new PCB_SHAPE( *static_cast<const PCB_SHAPE*>( aItem ) );
        const_cast<KIID&>( new_shape->m_Uuid ) = KIID();

        if( aAddToFootprint )
            Add( new_shape );

        new_item = new_shape;
        break;
    }

    case PCB_TEXTBOX_T:
    {
        PCB_TEXTBOX* new_textbox = new PCB_TEXTBOX( *static_cast<const PCB_TEXTBOX*>( aItem ) );
        const_cast<KIID&>( new_textbox->m_Uuid ) = KIID();

        if( aAddToFootprint )
            Add( new_textbox );

        new_item = new_textbox;
        break;
    }

    case PCB_DIM_ALIGNED_T:
    case PCB_DIM_LEADER_T:
    case PCB_DIM_CENTER_T:
    case PCB_DIM_RADIAL_T:
    case PCB_DIM_ORTHOGONAL_T:
    {
        PCB_DIMENSION_BASE* dimension = static_cast<PCB_DIMENSION_BASE*>( aItem->Duplicate() );

        if( aAddToFootprint )
            Add( dimension );

        new_item = dimension;
        break;
    }

    case PCB_GROUP_T:
    {
        PCB_GROUP* group = static_cast<const PCB_GROUP*>( aItem )->DeepDuplicate();

        if( aAddToFootprint )
        {
            group->RunOnDescendants(
                    [&]( BOARD_ITEM* aCurrItem )
                    {
                        Add( aCurrItem );
                    } );

            Add( group );
        }

        new_item = group;
        break;
    }

    case PCB_FOOTPRINT_T:
        // Ignore the footprint itself
        break;

    default:
        // Un-handled item for duplication
        wxFAIL_MSG( wxT( "Duplication not supported for items of class " ) + aItem->GetClass() );
        break;
    }

    return new_item;
}


wxString FOOTPRINT::GetNextPadNumber( const wxString& aLastPadNumber ) const
{
    std::set<wxString> usedNumbers;

    // Create a set of used pad numbers
    for( PAD* pad : m_pads )
        usedNumbers.insert( pad->GetNumber() );

    // Pad numbers aren't technically reference designators, but the formatting is close enough
    // for these to give us what we need.
    wxString prefix = UTIL::GetRefDesPrefix( aLastPadNumber );
    int      num = GetTrailingInt( aLastPadNumber );

    while( usedNumbers.count( wxString::Format( wxT( "%s%d" ), prefix, num ) ) )
        num++;

    return wxString::Format( wxT( "%s%d" ), prefix, num );
}


void FOOTPRINT::AutoPositionFields()
{
    // Auto-position reference and value
    BOX2I bbox = GetBoundingBox( false );
    bbox.Inflate( pcbIUScale.mmToIU( 0.2 ) ); // Gap between graphics and text

    if( Reference().GetPosition() == VECTOR2I( 0, 0 ) )
    {
        Reference().SetHorizJustify( GR_TEXT_H_ALIGN_CENTER );
        Reference().SetVertJustify( GR_TEXT_V_ALIGN_CENTER );
        Reference().SetTextAngle( ANGLE_0 );

        Reference().SetX( bbox.GetCenter().x );
        Reference().SetY( bbox.GetTop() - Reference().GetTextSize().y / 2 );
    }

    if( Value().GetPosition() == VECTOR2I( 0, 0 ) )
    {
        Value().SetHorizJustify( GR_TEXT_H_ALIGN_CENTER );
        Value().SetVertJustify( GR_TEXT_V_ALIGN_CENTER );
        Value().SetTextAngle( ANGLE_0 );

        Value().SetX( bbox.GetCenter().x );
        Value().SetY( bbox.GetBottom() + Value().GetTextSize().y / 2 );
    }
}


void FOOTPRINT::IncrementReference( int aDelta )
{
    const wxString& refdes = GetReference();

    SetReference( wxString::Format( wxT( "%s%i" ),
                                    UTIL::GetRefDesPrefix( refdes ),
                                    GetTrailingInt( refdes ) + aDelta ) );
}


// Calculate the area of a PolySet, polygons with hole are allowed.
static double polygonArea( SHAPE_POLY_SET& aPolySet )
{
    // Ensure all outlines are closed, before calculating the SHAPE_POLY_SET area
    for( int ii = 0; ii < aPolySet.OutlineCount(); ii++ )
    {
        SHAPE_LINE_CHAIN& outline = aPolySet.Outline( ii );
        outline.SetClosed( true );

        for( int jj = 0; jj < aPolySet.HoleCount( ii ); jj++ )
            aPolySet.Hole( ii, jj ).SetClosed( true );
    }

    return aPolySet.Area();
}


double FOOTPRINT::GetCoverageArea( const BOARD_ITEM* aItem, const GENERAL_COLLECTOR& aCollector  )
{
    int            textMargin = aCollector.GetGuide()->Accuracy();
    SHAPE_POLY_SET poly;

    if( aItem->Type() == PCB_MARKER_T )
    {
        const PCB_MARKER* marker = static_cast<const PCB_MARKER*>( aItem );
        SHAPE_LINE_CHAIN  markerShape;

        marker->ShapeToPolygon( markerShape );
        return markerShape.Area();
    }
    else if( aItem->Type() == PCB_GROUP_T || aItem->Type() == PCB_GENERATOR_T )
    {
        double combinedArea = 0.0;

        for( BOARD_ITEM* member : static_cast<const PCB_GROUP*>( aItem )->GetItems() )
            combinedArea += GetCoverageArea( member, aCollector );

        return combinedArea;
    }
    if( aItem->Type() == PCB_FOOTPRINT_T )
    {
        const FOOTPRINT* footprint = static_cast<const FOOTPRINT*>( aItem );

        poly = footprint->GetBoundingHull();
    }
    else if( aItem->Type() == PCB_FIELD_T || aItem->Type() == PCB_TEXT_T )
    {
        const PCB_TEXT* text = static_cast<const PCB_TEXT*>( aItem );

        text->TransformTextToPolySet( poly, textMargin, ARC_LOW_DEF, ERROR_INSIDE );
    }
    else if( aItem->Type() == PCB_TEXTBOX_T )
    {
        const PCB_TEXTBOX* tb = static_cast<const PCB_TEXTBOX*>( aItem );

        tb->TransformTextToPolySet( poly, textMargin, ARC_LOW_DEF, ERROR_INSIDE );
    }
    else if( aItem->Type() == PCB_SHAPE_T )
    {
        // Approximate "linear" shapes with just their width squared, as we don't want to consider
        // a linear shape as being much bigger than another for purposes of selection filtering
        // just because it happens to be really long.

        const PCB_SHAPE* shape = static_cast<const PCB_SHAPE*>( aItem );

        switch( shape->GetShape() )
        {
        case SHAPE_T::SEGMENT:
        case SHAPE_T::ARC:
        case SHAPE_T::BEZIER:
            return shape->GetWidth() * shape->GetWidth();

        case SHAPE_T::RECTANGLE:
        case SHAPE_T::CIRCLE:
        case SHAPE_T::POLY:
        {
            if( !shape->IsFilled() )
                return shape->GetWidth() * shape->GetWidth();

            KI_FALLTHROUGH;
        }

        default:
            shape->TransformShapeToPolygon( poly, UNDEFINED_LAYER, 0, ARC_LOW_DEF, ERROR_OUTSIDE );
        }
    }
    else if( aItem->Type() == PCB_TRACE_T || aItem->Type() == PCB_ARC_T )
    {
        double width = static_cast<const PCB_TRACK*>( aItem )->GetWidth();
        return width * width;
    }
    else if( aItem->Type() == PCB_PAD_T )
    {
        static_cast<const PAD*>( aItem )->Padstack().ForEachUniqueLayer(
            [&]( PCB_LAYER_ID aLayer )
            {
                SHAPE_POLY_SET padPoly;
                aItem->TransformShapeToPolygon( padPoly, aLayer, 0, ARC_LOW_DEF, ERROR_OUTSIDE );
                poly.BooleanAdd( padPoly );
            } );
    }
    else
    {
        aItem->TransformShapeToPolygon( poly, UNDEFINED_LAYER, 0, ARC_LOW_DEF, ERROR_OUTSIDE );
    }

    return polygonArea( poly );
}


double FOOTPRINT::CoverageRatio( const GENERAL_COLLECTOR& aCollector ) const
{
    int textMargin = aCollector.GetGuide()->Accuracy();

    SHAPE_POLY_SET footprintRegion( GetBoundingHull() );
    SHAPE_POLY_SET coveredRegion;

    TransformPadsToPolySet( coveredRegion, UNDEFINED_LAYER, 0, ARC_LOW_DEF, ERROR_OUTSIDE );

    TransformFPShapesToPolySet( coveredRegion, UNDEFINED_LAYER, textMargin, ARC_LOW_DEF,
                                ERROR_OUTSIDE,
                                true,  /* include text */
                                false, /* include shapes */
                                false  /* include private items */ );

    for( int i = 0; i < aCollector.GetCount(); ++i )
    {
        const BOARD_ITEM* item = aCollector[i];

        switch( item->Type() )
        {
        case PCB_FIELD_T:
        case PCB_TEXT_T:
        case PCB_TEXTBOX_T:
        case PCB_SHAPE_T:
        case PCB_TRACE_T:
        case PCB_ARC_T:
        case PCB_VIA_T:
            if( item->GetParent() != this )
            {
                item->TransformShapeToPolygon( coveredRegion, UNDEFINED_LAYER, 0, ARC_LOW_DEF,
                                               ERROR_OUTSIDE );
            }
            break;

        case PCB_FOOTPRINT_T:
            if( item != this )
            {
                const FOOTPRINT* footprint = static_cast<const FOOTPRINT*>( item );
                coveredRegion.AddOutline( footprint->GetBoundingHull().Outline( 0 ) );
            }
            break;

        default:
            break;
        }
    }

    coveredRegion.BooleanIntersection( footprintRegion );

    double footprintRegionArea = polygonArea( footprintRegion );
    double uncoveredRegionArea = footprintRegionArea - polygonArea( coveredRegion );
    double coveredArea = footprintRegionArea - uncoveredRegionArea;
    double ratio = ( coveredArea / footprintRegionArea );

    // Test for negative ratio (should not occur).
    // better to be conservative (this will result in the disambiguate dialog)
    if( ratio < 0.0 )
        return 1.0;

    return std::min( ratio, 1.0 );
}


std::shared_ptr<SHAPE> FOOTPRINT::GetEffectiveShape( PCB_LAYER_ID aLayer, FLASHING aFlash ) const
{
    std::shared_ptr<SHAPE_COMPOUND> shape = std::make_shared<SHAPE_COMPOUND>();

    // There are several possible interpretations here:
    // 1) the bounding box (without or without invisible items)
    // 2) just the pads and "edges" (ie: non-text graphic items)
    // 3) the courtyard

    // We'll go with (2) for now, unless the caller is clearly looking for (3)

    if( aLayer == F_CrtYd || aLayer == B_CrtYd )
    {
        const SHAPE_POLY_SET& courtyard = GetCourtyard( aLayer );

        if( courtyard.OutlineCount() == 0 )    // malformed/empty polygon
            return shape;

        shape->AddShape( new SHAPE_SIMPLE( courtyard.COutline( 0 ) ) );
    }
    else
    {
        for( PAD* pad : Pads() )
            shape->AddShape( pad->GetEffectiveShape( aLayer, aFlash )->Clone() );

        for( BOARD_ITEM* item : GraphicalItems() )
        {
            if( item->Type() == PCB_SHAPE_T )
                shape->AddShape( item->GetEffectiveShape( aLayer, aFlash )->Clone() );
        }
    }

    return shape;
}


const SHAPE_POLY_SET& FOOTPRINT::GetCourtyard( PCB_LAYER_ID aLayer ) const
{
    std::lock_guard<std::mutex> lock( m_courtyard_cache_mutex );

    if( m_courtyard_cache_front_hash != m_courtyard_cache_front.GetHash()
        || m_courtyard_cache_back_hash != m_courtyard_cache_back.GetHash() )
    {
        const_cast<FOOTPRINT*>(this)->BuildCourtyardCaches();
    }

    return GetCachedCourtyard( aLayer );
}


const SHAPE_POLY_SET& FOOTPRINT::GetCachedCourtyard( PCB_LAYER_ID aLayer ) const
{
    if( IsBackLayer( aLayer ) )
        return m_courtyard_cache_back;
    else
        return m_courtyard_cache_front;
}


void FOOTPRINT::BuildCourtyardCaches( OUTLINE_ERROR_HANDLER* aErrorHandler )
{
    m_courtyard_cache_front.RemoveAllContours();
    m_courtyard_cache_back.RemoveAllContours();
    ClearFlags( MALFORMED_COURTYARDS );

    // Build the courtyard area from graphic items on the courtyard.
    // Only PCB_SHAPE_T have meaning, graphic texts are ignored.
    // Collect items:
    std::vector<PCB_SHAPE*> list_front;
    std::vector<PCB_SHAPE*> list_back;
    std::map<int, int>      front_width_histogram;
    std::map<int, int>      back_width_histogram;

    for( BOARD_ITEM* item : GraphicalItems() )
    {
        if( item->GetLayer() == B_CrtYd && item->Type() == PCB_SHAPE_T )
        {
            PCB_SHAPE* shape = static_cast<PCB_SHAPE*>( item );
            list_back.push_back( shape );
            back_width_histogram[ shape->GetStroke().GetWidth() ]++;
        }

        if( item->GetLayer() == F_CrtYd && item->Type() == PCB_SHAPE_T )
        {
            PCB_SHAPE* shape = static_cast<PCB_SHAPE*>( item );
            list_front.push_back( shape );
            front_width_histogram[ shape->GetStroke().GetWidth() ]++;
        }
    }

    if( !list_front.size() && !list_back.size() )
        return;

    int maxError = pcbIUScale.mmToIU( 0.005 );        // max error for polygonization
    int chainingEpsilon = pcbIUScale.mmToIU( 0.02 );  // max dist from one endPt to next startPt

    if( ConvertOutlineToPolygon( list_front, m_courtyard_cache_front, maxError, chainingEpsilon,
                                 true, aErrorHandler ) )
    {
        int width = 0;

        // Touching courtyards, or courtyards -at- the clearance distance are legal.
        // Use maxError here because that is the allowed deviation when transforming arcs/circles to
        // polygons.
        m_courtyard_cache_front.Inflate( -maxError, CORNER_STRATEGY::CHAMFER_ACUTE_CORNERS, maxError );

        m_courtyard_cache_front.CacheTriangulation( false );
        auto max = std::max_element( front_width_histogram.begin(), front_width_histogram.end(),
                                     []( const std::pair<int, int>& a, const std::pair<int, int>& b )
                                     {
                                         return a.second < b.second;
                                     } );

        if( max != front_width_histogram.end() )
            width = max->first;

        if( width == 0 )
            width = pcbIUScale.mmToIU( DEFAULT_COURTYARD_WIDTH );

        if( m_courtyard_cache_front.OutlineCount() > 0 )
            m_courtyard_cache_front.Outline( 0 ).SetWidth( width );
    }
    else
    {
        SetFlags( MALFORMED_F_COURTYARD );
    }

    if( ConvertOutlineToPolygon( list_back, m_courtyard_cache_back, maxError, chainingEpsilon, true,
                                 aErrorHandler ) )
    {
        int width = 0;

        // Touching courtyards, or courtyards -at- the clearance distance are legal.
        m_courtyard_cache_back.Inflate( -maxError, CORNER_STRATEGY::CHAMFER_ACUTE_CORNERS, maxError );

        m_courtyard_cache_back.CacheTriangulation( false );
        auto max = std::max_element( back_width_histogram.begin(), back_width_histogram.end(),
                                     []( const std::pair<int, int>& a, const std::pair<int, int>& b )
                                     {
                                         return a.second < b.second;
                                     } );

        if( max != back_width_histogram.end() )
            width = max->first;

        if( width == 0 )
            width = pcbIUScale.mmToIU( DEFAULT_COURTYARD_WIDTH );

        if( m_courtyard_cache_back.OutlineCount() > 0 )
            m_courtyard_cache_back.Outline( 0 ).SetWidth( width );
    }
    else
    {
        SetFlags( MALFORMED_B_COURTYARD );
    }

    m_courtyard_cache_front_hash = m_courtyard_cache_front.GetHash();
    m_courtyard_cache_back_hash = m_courtyard_cache_back.GetHash();
}


void FOOTPRINT::BuildNetTieCache()
{
    m_netTieCache.clear();
    std::map<wxString, int> map = MapPadNumbersToNetTieGroups();
    std::map<PCB_LAYER_ID, std::vector<PCB_SHAPE*>> layer_shapes;

    std::for_each( m_drawings.begin(), m_drawings.end(),
                   [&]( BOARD_ITEM* item )
                   {
                       if( item->Type() != PCB_SHAPE_T )
                           return;

                       for( PCB_LAYER_ID layer : item->GetLayerSet() )
                           layer_shapes[layer].push_back( static_cast<PCB_SHAPE*>( item ) );
                   } );

    for( size_t ii = 0; ii < m_pads.size(); ++ii )
    {
        PAD* pad = m_pads[ ii ];
        bool has_nettie = false;

        auto it = map.find( pad->GetNumber() );

        if( it == map.end() || it->second < 0 )
            continue;

        for( size_t jj = ii + 1; jj < m_pads.size(); ++jj )
        {
            PAD* other = m_pads[ jj ];

            auto it2 = map.find( other->GetNumber() );

            if( it2 == map.end() || it2->second < 0 )
                continue;

            if( it2->second == it->second )
            {
                m_netTieCache[pad].insert( pad->GetNetCode() );
                m_netTieCache[pad].insert( other->GetNetCode() );
                m_netTieCache[other].insert( other->GetNetCode() );
                m_netTieCache[other].insert( pad->GetNetCode() );
                has_nettie = true;
            }
        }

        if( !has_nettie )
            continue;

        for( auto& [ layer, shapes ] : layer_shapes )
        {
            auto pad_shape = pad->GetEffectiveShape( layer );

            for( auto other_shape : shapes )
            {
                auto shape = other_shape->GetEffectiveShape( layer );

                if( pad_shape->Collide( shape.get() ) )
                {
                    std::set<int>& nettie = m_netTieCache[pad];
                    m_netTieCache[other_shape].insert( nettie.begin(), nettie.end() );
                }
            }
        }
    }
}


std::map<wxString, int> FOOTPRINT::MapPadNumbersToNetTieGroups() const
{
    std::map<wxString, int> padNumberToGroupIdxMap;

    for( const PAD* pad : m_pads )
        padNumberToGroupIdxMap[ pad->GetNumber() ] = -1;

    auto processPad =
            [&]( wxString aPad, int aGroup )
            {
                aPad.Trim( true ).Trim( false );

                if( !aPad.IsEmpty() )
                    padNumberToGroupIdxMap[ aPad ] = aGroup;
            };

    for( int ii = 0; ii < (int) m_netTiePadGroups.size(); ++ii )
    {
        wxString group( m_netTiePadGroups[ ii ] );
        bool esc = false;
        wxString pad;

        for( wxUniCharRef ch : group )
        {
            if( esc )
            {
                esc = false;
                pad.Append( ch );
                continue;
            }

            switch( static_cast<unsigned char>( ch ) )
            {
            case '\\':
                esc = true;
                break;

            case ',':
                processPad( pad, ii );
                pad.Clear();
                break;

            default:
                pad.Append( ch );
                break;
            }
        }

        processPad( pad, ii );
    }

    return padNumberToGroupIdxMap;
}


std::vector<PAD*> FOOTPRINT::GetNetTiePads( PAD* aPad ) const
{
    // First build a map from pad numbers to allowed-shorting-group indexes.  This ends up being
    // something like O(3n), but it still beats O(n^2) for large numbers of pads.

    std::map<wxString, int> padToNetTieGroupMap = MapPadNumbersToNetTieGroups();
    int                     groupIdx = padToNetTieGroupMap[ aPad->GetNumber() ];
    std::vector<PAD*>       otherPads;

    if( groupIdx >= 0 )
    {
        for( PAD* pad : m_pads )
        {
            if( padToNetTieGroupMap[ pad->GetNumber() ] == groupIdx )
                otherPads.push_back( pad );
        }
    }

    return otherPads;
}


void FOOTPRINT::CheckFootprintAttributes( const std::function<void( const wxString& )>& aErrorHandler )
{
    int likelyAttr = ( GetLikelyAttribute() & ( FP_SMD | FP_THROUGH_HOLE ) );
    int setAttr = ( GetAttributes() & ( FP_SMD | FP_THROUGH_HOLE ) );

    if( setAttr && likelyAttr && setAttr != likelyAttr )
    {
        wxString msg;

        switch( likelyAttr )
        {
        case FP_THROUGH_HOLE:
            msg.Printf( _( "(expected 'Through hole'; actual '%s')" ), GetTypeName() );
            break;
        case FP_SMD:
            msg.Printf( _( "(expected 'SMD'; actual '%s')" ), GetTypeName() );
            break;
        }

        if( aErrorHandler )
            (aErrorHandler)( msg );
    }
}


void FOOTPRINT::CheckPads( UNITS_PROVIDER* aUnitsProvider,
                           const std::function<void( const PAD*, int,
                                                     const wxString& )>& aErrorHandler )
{
    if( aErrorHandler == nullptr )
        return;

    for( PAD* pad: Pads() )
    {
        pad->CheckPad( aUnitsProvider, false,
                [&]( int errorCode, const wxString& msg )
                {
                    aErrorHandler( pad, errorCode, msg );
                } );
    }
}


void FOOTPRINT::CheckShortingPads( const std::function<void( const PAD*, const PAD*,
                                                             int aErrorCode,
                                                             const VECTOR2I& )>& aErrorHandler )
{
    std::unordered_map<PTR_PTR_CACHE_KEY, int> checkedPairs;

    for( PAD* pad : Pads() )
    {
        std::vector<PAD*> netTiePads = GetNetTiePads( pad );

        for( PAD* other : Pads() )
        {
            if( other == pad )
                continue;

            // store canonical order so we don't collide in both directions (a:b and b:a)
            PAD* a = pad;
            PAD* b = other;

            if( static_cast<void*>( a ) > static_cast<void*>( b ) )
                std::swap( a, b );

            if( checkedPairs.find( { a, b } ) == checkedPairs.end() )
            {
                checkedPairs[ { a, b } ] = 1;

                if( pad->HasDrilledHole() && other->HasDrilledHole() )
                {
                    VECTOR2I pos = pad->GetPosition();

                    if( pad->GetPosition() == other->GetPosition() )
                    {
                        aErrorHandler( pad, other, DRCE_DRILLED_HOLES_COLOCATED, pos );
                    }
                    else
                    {
                        std::shared_ptr<SHAPE_SEGMENT> holeA = pad->GetEffectiveHoleShape();
                        std::shared_ptr<SHAPE_SEGMENT> holeB = other->GetEffectiveHoleShape();

                        if( holeA->Collide( holeB->GetSeg(), 0 ) )
                            aErrorHandler( pad, other, DRCE_DRILLED_HOLES_TOO_CLOSE, pos );
                    }
                }

                if( pad->SameLogicalPadAs( other ) || alg::contains( netTiePads, other ) )
                    continue;

                if( !( ( pad->GetLayerSet() & other->GetLayerSet() ) & LSET::AllCuMask() ).any() )
                    continue;

                if( pad->GetBoundingBox().Intersects( other->GetBoundingBox() ) )
                {
                    VECTOR2I pos;

                    for( PCB_LAYER_ID l : pad->Padstack().RelevantShapeLayers( other->Padstack() ) )
                    {
                        SHAPE*   padShape = pad->GetEffectiveShape( l ).get();
                        SHAPE*   otherShape = other->GetEffectiveShape( l ).get();

                        if( padShape->Collide( otherShape, 0, nullptr, &pos ) )
                            aErrorHandler( pad, other, DRCE_SHORTING_ITEMS, pos );
                    }
                }
            }
        }
    }
}


void FOOTPRINT::CheckNetTies( const std::function<void( const BOARD_ITEM* aItem,
                                                        const BOARD_ITEM* bItem,
                                                        const BOARD_ITEM* cItem,
                                                        const VECTOR2I& )>& aErrorHandler )
{
    // First build a map from pad numbers to allowed-shorting-group indexes.  This ends up being
    // something like O(3n), but it still beats O(n^2) for large numbers of pads.

    std::map<wxString, int> padNumberToGroupIdxMap = MapPadNumbersToNetTieGroups();

    // Now collect all the footprint items which are on copper layers

    std::vector<BOARD_ITEM*> copperItems;

    for( BOARD_ITEM* item : m_drawings )
    {
        if( item->IsOnCopperLayer() )
            copperItems.push_back( item );

        item->RunOnDescendants(
                [&]( BOARD_ITEM* descendent )
                {
                    if( descendent->IsOnCopperLayer() )
                        copperItems.push_back( descendent );
                } );
    }

    for( ZONE* zone : m_zones )
    {
        if( !zone->GetIsRuleArea() && zone->IsOnCopperLayer() )
            copperItems.push_back( zone );
    }

    for( PCB_FIELD* field : m_fields )
    {
        if( field && field->IsOnCopperLayer() )
            copperItems.push_back( field );
    }

    for( PCB_LAYER_ID layer : { F_Cu, In1_Cu, B_Cu } )
    {
        // Next, build a polygon-set for the copper on this layer.  We don't really care about
        // nets here, we just want to end up with a set of outlines describing the distinct
        // copper polygons of the footprint.

        SHAPE_POLY_SET                         copperOutlines;
        std::map<int, std::vector<const PAD*>> outlineIdxToPadsMap;

        for( BOARD_ITEM* item : copperItems )
        {
            if( item->IsOnLayer( layer ) )
            {
                item->TransformShapeToPolygon( copperOutlines, layer, 0, ARC_HIGH_DEF,
                                               ERROR_OUTSIDE );
            }
        }

        copperOutlines.Simplify();

        // Index each pad to the outline in the set that it is part of.

        for( const PAD* pad : m_pads )
        {
            for( int ii = 0; ii < copperOutlines.OutlineCount(); ++ii )
            {
                if( pad->GetEffectiveShape( layer )->Collide( &copperOutlines.Outline( ii ), 0 ) )
                    outlineIdxToPadsMap[ ii ].emplace_back( pad );
            }
        }

        // Finally, ensure that each outline which contains multiple pads has all its pads
        // listed in an allowed-shorting group.

        for( const auto& [ outlineIdx, pads ] : outlineIdxToPadsMap )
        {
            if( pads.size() > 1 )
            {
                const PAD* firstPad = pads[0];
                int        firstGroupIdx = padNumberToGroupIdxMap[ firstPad->GetNumber() ];

                for( size_t ii = 1; ii < pads.size(); ++ii )
                {
                    const PAD* thisPad = pads[ii];
                    int        thisGroupIdx = padNumberToGroupIdxMap[ thisPad->GetNumber() ];

                    if( thisGroupIdx < 0 || thisGroupIdx != firstGroupIdx )
                    {
                        BOARD_ITEM* shortingItem = nullptr;
                        VECTOR2I    pos = ( firstPad->GetPosition() + thisPad->GetPosition() ) / 2;

                        pos = copperOutlines.Outline( outlineIdx ).NearestPoint( pos );

                        for( BOARD_ITEM* item : copperItems )
                        {
                            if( item->HitTest( pos, 1 ) )
                            {
                                shortingItem = item;
                                break;
                            }
                        }

                        if( shortingItem )
                            aErrorHandler( shortingItem, firstPad, thisPad, pos );
                        else
                            aErrorHandler( firstPad, thisPad, nullptr, pos );
                    }
                }
            }
        }
    }
}


void FOOTPRINT::CheckNetTiePadGroups( const std::function<void( const wxString& )>& aErrorHandler )
{
    std::set<wxString> padNumbers;
    wxString           msg;

    for( const auto& [ padNumber, _ ] : MapPadNumbersToNetTieGroups() )
    {
        const PAD* pad = FindPadByNumber( padNumber );

        if( !pad )
        {
            msg.Printf( _( "(net-tie pad group contains unknown pad number %s)" ), padNumber );
            aErrorHandler( msg );
        }
        else if( !padNumbers.insert( pad->GetNumber() ).second )
        {
            msg.Printf( _( "(pad %s appears in more than one net-tie pad group)" ), padNumber );
            aErrorHandler( msg );
        }
    }
}


void FOOTPRINT::CheckClippedSilk( const std::function<void( BOARD_ITEM* aItemA,
                                                            BOARD_ITEM* aItemB,
                                                            const VECTOR2I& aPt )>& aErrorHandler )
{
    auto checkColliding =
            [&]( BOARD_ITEM* item, BOARD_ITEM* other )
            {
                for( PCB_LAYER_ID silk : { F_SilkS, B_SilkS } )
                {
                    PCB_LAYER_ID mask = silk == F_SilkS ? F_Mask : B_Mask;

                    if( !item->IsOnLayer( silk ) || !other->IsOnLayer( mask ) )
                        continue;

                    std::shared_ptr<SHAPE> itemShape = item->GetEffectiveShape( silk );
                    std::shared_ptr<SHAPE> otherShape = other->GetEffectiveShape( mask );
                    int                    actual;
                    VECTOR2I               pos;

                    if( itemShape->Collide( otherShape.get(), 0, &actual, &pos ) )
                        aErrorHandler( item, other, pos );
                }
            };

    for( BOARD_ITEM* item : m_drawings )
    {
        for( BOARD_ITEM* other : m_drawings )
        {
            if( other != item )
                checkColliding( item, other );
        }

        for( PAD* pad : m_pads )
            checkColliding( item, pad );
    }
}


void FOOTPRINT::swapData( BOARD_ITEM* aImage )
{
    wxASSERT( aImage->Type() == PCB_FOOTPRINT_T );

    FOOTPRINT* image = static_cast<FOOTPRINT*>( aImage );

    std::swap( *this, *image );

    RunOnChildren(
            [&]( BOARD_ITEM* child )
            {
                child->SetParent( this );
            } );

    image->RunOnChildren(
            [&]( BOARD_ITEM* child )
            {
                child->SetParent( image );
            } );
}


bool FOOTPRINT::HasThroughHolePads() const
{
    for( PAD* pad : Pads() )
    {
        if( pad->GetAttribute() != PAD_ATTRIB::SMD )
            return true;
    }

    return false;
}


bool FOOTPRINT::operator==( const BOARD_ITEM& aOther ) const
{
    if( aOther.Type() != PCB_FOOTPRINT_T )
        return false;

    const FOOTPRINT& other = static_cast<const FOOTPRINT&>( aOther );

    return *this == other;
}


bool FOOTPRINT::operator==( const FOOTPRINT& aOther ) const
{
    if( m_pads.size() != aOther.m_pads.size() )
        return false;

    for( size_t ii = 0; ii < m_pads.size(); ++ii )
    {
        if( !( *m_pads[ii] == *aOther.m_pads[ii] ) )
            return false;
    }

    if( m_drawings.size() != aOther.m_drawings.size() )
        return false;

    for( size_t ii = 0; ii < m_drawings.size(); ++ii )
    {
        if( !( *m_drawings[ii] == *aOther.m_drawings[ii] ) )
            return false;
    }

    if( m_zones.size() != aOther.m_zones.size() )
        return false;

    for( size_t ii = 0; ii < m_zones.size(); ++ii )
    {
        if( !( *m_zones[ii] == *aOther.m_zones[ii] ) )
            return false;
    }

    if( m_fields.size() != aOther.m_fields.size() )
        return false;

    for( size_t ii = 0; ii < m_fields.size(); ++ii )
    {
        if( m_fields[ii] )
        {
            if( !( *m_fields[ii] == *aOther.m_fields[ii] ) )
                return false;
        }
    }

    return true;
}


double FOOTPRINT::Similarity( const BOARD_ITEM& aOther ) const
{
    if( aOther.Type() != PCB_FOOTPRINT_T )
        return 0.0;

    const FOOTPRINT& other = static_cast<const FOOTPRINT&>( aOther );

    double similarity = 1.0;

    for( const PAD* pad : m_pads)
    {
        const PAD* otherPad = other.FindPadByNumber( pad->GetNumber() );

        if( !otherPad )
            continue;

        similarity *= pad->Similarity( *otherPad );
    }

    return similarity;
}


bool FOOTPRINT::cmp_drawings::operator()( const BOARD_ITEM* itemA, const BOARD_ITEM* itemB ) const
{
    if( itemA->Type() != itemB->Type() )
        return itemA->Type() < itemB->Type();

    if( itemA->GetLayer() != itemB->GetLayer() )
        return itemA->GetLayer() < itemB->GetLayer();

    if( itemA->Type() == PCB_SHAPE_T )
    {
        const PCB_SHAPE* dwgA = static_cast<const PCB_SHAPE*>( itemA );
        const PCB_SHAPE* dwgB = static_cast<const PCB_SHAPE*>( itemB );

        if( dwgA->GetShape() != dwgB->GetShape() )
            return dwgA->GetShape() < dwgB->GetShape();

        // GetStart() and GetEnd() have no meaning with polygons.
        // We cannot use them for sorting polygons
        if( dwgA->GetShape() != SHAPE_T::POLY )
        {
            if( dwgA->GetStart().x != dwgB->GetStart().x )
                return dwgA->GetStart().x < dwgB->GetStart().x;
            if( dwgA->GetStart().y != dwgB->GetStart().y )
                return dwgA->GetStart().y < dwgB->GetStart().y;

            if( dwgA->GetEnd().x != dwgB->GetEnd().x )
                return dwgA->GetEnd().x < dwgB->GetEnd().x;
            if( dwgA->GetEnd().y != dwgB->GetEnd().y )
                return dwgA->GetEnd().y < dwgB->GetEnd().y;
        }

        if( dwgA->GetShape() == SHAPE_T::ARC )
        {
            if( dwgA->GetCenter().x != dwgB->GetCenter().x )
                return dwgA->GetCenter().x < dwgB->GetCenter().x;
            if( dwgA->GetCenter().y != dwgB->GetCenter().y )
                return dwgA->GetCenter().y < dwgB->GetCenter().y;
        }
        else if( dwgA->GetShape() == SHAPE_T::BEZIER )
        {
            if( dwgA->GetBezierC1().x != dwgB->GetBezierC1().x )
                return dwgA->GetBezierC1().x < dwgB->GetBezierC1().x;
            if( dwgA->GetBezierC1().y != dwgB->GetBezierC1().y )
                return dwgA->GetBezierC1().y < dwgB->GetBezierC1().y;

            if( dwgA->GetBezierC2().x != dwgB->GetBezierC2().x )
                return dwgA->GetBezierC2().x < dwgB->GetBezierC2().x;
            if( dwgA->GetBezierC2().y != dwgB->GetBezierC2().y )
                return dwgA->GetBezierC2().y < dwgB->GetBezierC2().y;
        }
        else if( dwgA->GetShape() == SHAPE_T::POLY )
        {
            if( dwgA->GetPolyShape().TotalVertices() != dwgB->GetPolyShape().TotalVertices() )
                return dwgA->GetPolyShape().TotalVertices() < dwgB->GetPolyShape().TotalVertices();

            for( int ii = 0; ii < dwgA->GetPolyShape().TotalVertices(); ++ii )
            {
                if( dwgA->GetPolyShape().CVertex( ii ).x != dwgB->GetPolyShape().CVertex( ii ).x )
                    return dwgA->GetPolyShape().CVertex( ii ).x
                           < dwgB->GetPolyShape().CVertex( ii ).x;
                if( dwgA->GetPolyShape().CVertex( ii ).y != dwgB->GetPolyShape().CVertex( ii ).y )
                    return dwgA->GetPolyShape().CVertex( ii ).y
                           < dwgB->GetPolyShape().CVertex( ii ).y;
            }
        }

        if( dwgA->GetWidth() != dwgB->GetWidth() )
            return dwgA->GetWidth() < dwgB->GetWidth();
    }

    if( itemA->m_Uuid != itemB->m_Uuid )
        return itemA->m_Uuid < itemB->m_Uuid;

    return itemA < itemB;
}


bool FOOTPRINT::cmp_pads::operator()( const PAD* aFirst, const PAD* aSecond ) const
{
    if( aFirst->GetNumber() != aSecond->GetNumber() )
        return StrNumCmp( aFirst->GetNumber(), aSecond->GetNumber() ) < 0;

    if( aFirst->GetFPRelativePosition().x != aSecond->GetFPRelativePosition().x )
        return aFirst->GetFPRelativePosition().x < aSecond->GetFPRelativePosition().x;
    if( aFirst->GetFPRelativePosition().y != aSecond->GetFPRelativePosition().y )
        return aFirst->GetFPRelativePosition().y < aSecond->GetFPRelativePosition().y;

    std::optional<bool> padCopperMatches;

    // Pick the "most complex" padstack to iterate
    const PAD* checkPad = aFirst;

    if( aSecond->Padstack().Mode() == PADSTACK::MODE::CUSTOM
        || ( aSecond->Padstack().Mode() == PADSTACK::MODE::FRONT_INNER_BACK &&
             aFirst->Padstack().Mode() == PADSTACK::MODE::NORMAL ) )
    {
        checkPad = aSecond;
    }

    checkPad->Padstack().ForEachUniqueLayer(
        [&]( PCB_LAYER_ID aLayer )
        {
            if( aFirst->GetSize( aLayer ).x != aSecond->GetSize( aLayer ).x )
                padCopperMatches = aFirst->GetSize( aLayer ).x < aSecond->GetSize( aLayer ).x;
            else if( aFirst->GetSize( aLayer ).y != aSecond->GetSize( aLayer ).y )
                padCopperMatches = aFirst->GetSize( aLayer ).y < aSecond->GetSize( aLayer ).y;
            else if( aFirst->GetShape( aLayer ) != aSecond->GetShape( aLayer ) )
                padCopperMatches = aFirst->GetShape( aLayer ) < aSecond->GetShape( aLayer );
        } );

    if( padCopperMatches.has_value() )
        return *padCopperMatches;

    if( aFirst->GetLayerSet().Seq() != aSecond->GetLayerSet().Seq() )
        return aFirst->GetLayerSet().Seq() < aSecond->GetLayerSet().Seq();

    if( aFirst->m_Uuid != aSecond->m_Uuid )
        return aFirst->m_Uuid < aSecond->m_Uuid;

    return aFirst < aSecond;
}


#if 0
bool FOOTPRINT::cmp_padstack::operator()( const PAD* aFirst, const PAD* aSecond ) const
{
    if( aFirst->GetSize().x != aSecond->GetSize().x )
        return aFirst->GetSize().x < aSecond->GetSize().x;
    if( aFirst->GetSize().y != aSecond->GetSize().y )
        return aFirst->GetSize().y < aSecond->GetSize().y;

    if( aFirst->GetShape() != aSecond->GetShape() )
        return aFirst->GetShape() < aSecond->GetShape();

    if( aFirst->GetLayerSet().Seq() != aSecond->GetLayerSet().Seq() )
        return aFirst->GetLayerSet().Seq() < aSecond->GetLayerSet().Seq();

    if( aFirst->GetDrillSizeX() != aSecond->GetDrillSizeX() )
        return aFirst->GetDrillSizeX() < aSecond->GetDrillSizeX();

    if( aFirst->GetDrillSizeY() != aSecond->GetDrillSizeY() )
        return aFirst->GetDrillSizeY() < aSecond->GetDrillSizeY();

    if( aFirst->GetDrillShape() != aSecond->GetDrillShape() )
        return aFirst->GetDrillShape() < aSecond->GetDrillShape();

    if( aFirst->GetAttribute() != aSecond->GetAttribute() )
        return aFirst->GetAttribute() < aSecond->GetAttribute();

    if( aFirst->GetOrientation() != aSecond->GetOrientation() )
        return aFirst->GetOrientation() < aSecond->GetOrientation();

    if( aFirst->GetSolderMaskExpansion() != aSecond->GetSolderMaskExpansion() )
        return aFirst->GetSolderMaskExpansion() < aSecond->GetSolderMaskExpansion();

    if( aFirst->GetSolderPasteMargin() != aSecond->GetSolderPasteMargin() )
        return aFirst->GetSolderPasteMargin() < aSecond->GetSolderPasteMargin();

    if( aFirst->GetLocalSolderMaskMargin() != aSecond->GetLocalSolderMaskMargin() )
        return aFirst->GetLocalSolderMaskMargin() < aSecond->GetLocalSolderMaskMargin();

    const std::shared_ptr<SHAPE_POLY_SET>& firstShape = aFirst->GetEffectivePolygon( ERROR_INSIDE );
    const std::shared_ptr<SHAPE_POLY_SET>& secondShape = aSecond->GetEffectivePolygon( ERROR_INSIDE );

    if( firstShape->VertexCount() != secondShape->VertexCount() )
        return firstShape->VertexCount() < secondShape->VertexCount();

    for( int ii = 0; ii < firstShape->VertexCount(); ++ii )
    {
        if( firstShape->CVertex( ii ).x != secondShape->CVertex( ii ).x )
            return firstShape->CVertex( ii ).x < secondShape->CVertex( ii ).x;
        if( firstShape->CVertex( ii ).y != secondShape->CVertex( ii ).y )
            return firstShape->CVertex( ii ).y < secondShape->CVertex( ii ).y;
    }

    return false;
}
#endif


bool FOOTPRINT::cmp_zones::operator()( const ZONE* aFirst, const ZONE* aSecond ) const
{
    if( aFirst->GetAssignedPriority() != aSecond->GetAssignedPriority() )
        return aFirst->GetAssignedPriority() < aSecond->GetAssignedPriority();

    if( aFirst->GetLayerSet().Seq() != aSecond->GetLayerSet().Seq() )
        return aFirst->GetLayerSet().Seq() < aSecond->GetLayerSet().Seq();

    if( aFirst->Outline()->TotalVertices() != aSecond->Outline()->TotalVertices() )
        return aFirst->Outline()->TotalVertices() < aSecond->Outline()->TotalVertices();

    for( int ii = 0; ii < aFirst->Outline()->TotalVertices(); ++ii )
    {
        if( aFirst->Outline()->CVertex( ii ).x != aSecond->Outline()->CVertex( ii ).x )
            return aFirst->Outline()->CVertex( ii ).x < aSecond->Outline()->CVertex( ii ).x;
        if( aFirst->Outline()->CVertex( ii ).y != aSecond->Outline()->CVertex( ii ).y )
            return aFirst->Outline()->CVertex( ii ).y < aSecond->Outline()->CVertex( ii ).y;
    }

    if( aFirst->m_Uuid != aSecond->m_Uuid )
        return aFirst->m_Uuid < aSecond->m_Uuid;

    return aFirst < aSecond;
}


void FOOTPRINT::TransformPadsToPolySet( SHAPE_POLY_SET& aBuffer, PCB_LAYER_ID aLayer,
                                        int aClearance, int aMaxError, ERROR_LOC aErrorLoc,
                                        bool aSkipNPTHPadsWihNoCopper ) const
{
    auto processPad =
        [&]( const PAD* pad, PCB_LAYER_ID padLayer )
        {
            VECTOR2I clearance( aClearance, aClearance );

            switch( aLayer )
            {
            case F_Mask:
            case B_Mask:
                clearance.x += pad->GetSolderMaskExpansion( padLayer );
                clearance.y += pad->GetSolderMaskExpansion( padLayer );
                break;

            case F_Paste:
            case B_Paste:
                clearance += pad->GetSolderPasteMargin( padLayer );
                break;

            default:
                break;
            }

            // Our standard TransformShapeToPolygon() routines can't handle differing x:y clearance
            // values (which get generated when a relative paste margin is used with an oblong pad).
            // So we apply this huge hack and fake a larger pad to run the transform on.
            // Of course being a hack it falls down when dealing with custom shape pads (where the
            // size is only the size of the anchor), so for those we punt and just use clearance.x.

            if( ( clearance.x < 0 || clearance.x != clearance.y )
                    && pad->GetShape( padLayer ) != PAD_SHAPE::CUSTOM )
            {
                VECTOR2I dummySize = pad->GetSize( padLayer ) + clearance + clearance;

                if( dummySize.x <= 0 || dummySize.y <= 0 )
                    return;

                PAD dummy( *pad );
                dummy.SetSize( padLayer, dummySize );
                dummy.TransformShapeToPolygon( aBuffer, padLayer, 0, aMaxError, aErrorLoc );
            }
            else
            {
                pad->TransformShapeToPolygon( aBuffer, padLayer, clearance.x, aMaxError,
                                              aErrorLoc );
            }
        };

    for( const PAD* pad : m_pads )
    {
        if( !pad->FlashLayer( aLayer ) )
            continue;

        if( aLayer == UNDEFINED_LAYER )
        {
            pad->Padstack().ForEachUniqueLayer(
                    [&]( PCB_LAYER_ID l )
                    {
                        processPad( pad, l );
                    } );
        }
        else
        {
            processPad( pad, aLayer );
        }
    }
}


void FOOTPRINT::TransformFPShapesToPolySet( SHAPE_POLY_SET& aBuffer, PCB_LAYER_ID aLayer,
                                            int aClearance, int aError, ERROR_LOC aErrorLoc,
                                            bool aIncludeText, bool aIncludeShapes,
                                            bool aIncludePrivateItems ) const
{
    for( BOARD_ITEM* item : GraphicalItems() )
    {
        if( GetPrivateLayers().test( item->GetLayer() ) && !aIncludePrivateItems )
            continue;

        if( item->Type() == PCB_TEXT_T && aIncludeText )
        {
            PCB_TEXT* text = static_cast<PCB_TEXT*>( item );

            if( aLayer != UNDEFINED_LAYER && text->GetLayer() == aLayer )
                text->TransformTextToPolySet( aBuffer, aClearance, aError, aErrorLoc );
        }

        if( item->Type() == PCB_TEXTBOX_T && aIncludeText )
        {
            PCB_TEXTBOX* textbox = static_cast<PCB_TEXTBOX*>( item );

            if( aLayer != UNDEFINED_LAYER && textbox->GetLayer() == aLayer )
            {
                // border
                if( textbox->IsBorderEnabled() )
                {
                    textbox->PCB_SHAPE::TransformShapeToPolygon( aBuffer, aLayer, 0, aError,
                                                                 aErrorLoc );
                }

                // text
                textbox->TransformTextToPolySet( aBuffer, 0, aError, aErrorLoc );
            }
        }

        if( item->Type() == PCB_SHAPE_T && aIncludeShapes )
        {
            const PCB_SHAPE* outline = static_cast<PCB_SHAPE*>( item );

            if( aLayer != UNDEFINED_LAYER && outline->GetLayer() == aLayer )
                outline->TransformShapeToPolygon( aBuffer, aLayer, 0, aError, aErrorLoc );
        }
    }

    if( aIncludeText )
    {
        for( const PCB_FIELD* field : m_fields )
        {
            if( field && field->GetLayer() == aLayer && field->IsVisible() )
                field->TransformTextToPolySet( aBuffer, aClearance, aError, aErrorLoc );
        }
    }
}


std::set<KIFONT::OUTLINE_FONT*> FOOTPRINT::GetFonts() const
{
    using OUTLINE_FONT = KIFONT::OUTLINE_FONT;
    using EMBEDDING_PERMISSION = OUTLINE_FONT::EMBEDDING_PERMISSION;

    std::set<OUTLINE_FONT*> fonts;

    for( BOARD_ITEM* item : GraphicalItems() )
    {
        if( auto* text = dynamic_cast<EDA_TEXT*>( item ) )
        {
            if( auto* font = text->GetFont(); font && !font->IsStroke() )
            {
                auto* outline = static_cast<OUTLINE_FONT*>( font );
                auto permission = outline->GetEmbeddingPermission();

                if( permission == EMBEDDING_PERMISSION::EDITABLE
                    || permission == EMBEDDING_PERMISSION::INSTALLABLE )
                {
                    fonts.insert( outline );
                }
            }
        }
    }

    return fonts;
}


void FOOTPRINT::EmbedFonts()
{
    std::set<KIFONT::OUTLINE_FONT*> fonts = GetFonts();

    for( auto* font : fonts )
    {
        auto file = GetEmbeddedFiles()->AddFile( font->GetFileName(), false );
        file->type = EMBEDDED_FILES::EMBEDDED_FILE::FILE_TYPE::FONT;
    }
}


wxString FOOTPRINT::GetComponentClassAsString() const
{
    if( m_componentClass )
    {
        return m_componentClass->GetFullName();
    }

    return wxEmptyString;
}


void FOOTPRINT::ResolveComponentClassNames(
        BOARD* aBoard, const std::unordered_set<wxString>& aComponentClassNames )
{
    const COMPONENT_CLASS* componentClass =
            aBoard->GetComponentClassManager().GetEffectiveComponentClass( aComponentClassNames );
    SetComponentClass( componentClass );
}


static struct FOOTPRINT_DESC
{
    FOOTPRINT_DESC()
    {
        ENUM_MAP<ZONE_CONNECTION>& zcMap = ENUM_MAP<ZONE_CONNECTION>::Instance();

        if( zcMap.Choices().GetCount() == 0 )
        {
            zcMap.Undefined( ZONE_CONNECTION::INHERITED );
            zcMap.Map( ZONE_CONNECTION::INHERITED, _HKI( "Inherited" ) )
                 .Map( ZONE_CONNECTION::NONE, _HKI( "None" ) )
                 .Map( ZONE_CONNECTION::THERMAL, _HKI( "Thermal reliefs" ) )
                 .Map( ZONE_CONNECTION::FULL, _HKI( "Solid" ) )
                 .Map( ZONE_CONNECTION::THT_THERMAL, _HKI( "Thermal reliefs for PTH" ) );
        }

        ENUM_MAP<PCB_LAYER_ID>& layerEnum = ENUM_MAP<PCB_LAYER_ID>::Instance();

        if( layerEnum.Choices().GetCount() == 0 )
        {
            layerEnum.Undefined( UNDEFINED_LAYER );

            for( PCB_LAYER_ID layer : LSET::AllLayersMask().Seq() )
                layerEnum.Map( layer, LSET::Name( layer ) );
        }

        wxPGChoices fpLayers;       // footprints might be placed only on F.Cu & B.Cu
        fpLayers.Add( LSET::Name( F_Cu ), F_Cu );
        fpLayers.Add( LSET::Name( B_Cu ), B_Cu );

        PROPERTY_MANAGER& propMgr = PROPERTY_MANAGER::Instance();
        REGISTER_TYPE( FOOTPRINT );
        propMgr.AddTypeCast( new TYPE_CAST<FOOTPRINT, BOARD_ITEM> );
        propMgr.AddTypeCast( new TYPE_CAST<FOOTPRINT, BOARD_ITEM_CONTAINER> );
        propMgr.InheritsAfter( TYPE_HASH( FOOTPRINT ), TYPE_HASH( BOARD_ITEM ) );
        propMgr.InheritsAfter( TYPE_HASH( FOOTPRINT ), TYPE_HASH( BOARD_ITEM_CONTAINER ) );

        auto layer = new PROPERTY_ENUM<FOOTPRINT, PCB_LAYER_ID>( _HKI( "Layer" ),
                    &FOOTPRINT::SetLayerAndFlip, &FOOTPRINT::GetLayer );
        layer->SetChoices( fpLayers );
        propMgr.ReplaceProperty( TYPE_HASH( BOARD_ITEM ), _HKI( "Layer" ), layer );

        propMgr.AddProperty( new PROPERTY<FOOTPRINT, double>( _HKI( "Orientation" ),
                    &FOOTPRINT::SetOrientationDegrees, &FOOTPRINT::GetOrientationDegrees,
                    PROPERTY_DISPLAY::PT_DEGREE ) );

        const wxString groupFields = _HKI( "Fields" );

        propMgr.AddProperty( new PROPERTY<FOOTPRINT, wxString>( _HKI( "Reference" ),
                    &FOOTPRINT::SetReference, &FOOTPRINT::GetReferenceAsString ),
                    groupFields );
        propMgr.AddProperty( new PROPERTY<FOOTPRINT, wxString>( _HKI( "Value" ),
                    &FOOTPRINT::SetValue, &FOOTPRINT::GetValueAsString ),
                    groupFields );

        propMgr.AddProperty( new PROPERTY<FOOTPRINT, wxString>( _HKI( "Library Link" ),
                    NO_SETTER( FOOTPRINT, wxString ), &FOOTPRINT::GetFPIDAsString ),
                    groupFields );
        propMgr.AddProperty( new PROPERTY<FOOTPRINT, wxString>( _HKI( "Library Description" ),
                    NO_SETTER( FOOTPRINT, wxString ), &FOOTPRINT::GetLibDescription ),
                    groupFields );
        propMgr.AddProperty( new PROPERTY<FOOTPRINT, wxString>( _HKI( "Keywords" ),
                    NO_SETTER( FOOTPRINT, wxString ), &FOOTPRINT::GetKeywords ),
                    groupFields );

        // Note: Also used by DRC engine
        propMgr.AddProperty( new PROPERTY<FOOTPRINT, wxString>(
                                     _HKI( "Component Class" ), NO_SETTER( FOOTPRINT, wxString ),
                                     &FOOTPRINT::GetComponentClassAsString ), groupFields )
                .SetIsHiddenFromLibraryEditors();

        const wxString groupAttributes = _HKI( "Attributes" );

        propMgr.AddProperty( new PROPERTY<FOOTPRINT, bool>( _HKI( "Not in Schematic" ),
                    &FOOTPRINT::SetBoardOnly, &FOOTPRINT::IsBoardOnly ), groupAttributes );
        propMgr.AddProperty( new PROPERTY<FOOTPRINT, bool>( _HKI( "Exclude From Position Files" ),
                    &FOOTPRINT::SetExcludedFromPosFiles, &FOOTPRINT::IsExcludedFromPosFiles ),
                    groupAttributes );
        propMgr.AddProperty( new PROPERTY<FOOTPRINT, bool>( _HKI( "Exclude From Bill of Materials" ),
                    &FOOTPRINT::SetExcludedFromBOM, &FOOTPRINT::IsExcludedFromBOM ),
                    groupAttributes );
        propMgr.AddProperty( new PROPERTY<FOOTPRINT, bool>( _HKI( "Do not Populate" ),
                    &FOOTPRINT::SetDNP, &FOOTPRINT::IsDNP ),
                    groupAttributes );

        const wxString groupOverrides = _HKI( "Overrides" );

        propMgr.AddProperty( new PROPERTY<FOOTPRINT, bool>(
                    _HKI( "Exempt From Courtyard Requirement" ),
                    &FOOTPRINT::SetAllowMissingCourtyard, &FOOTPRINT::AllowMissingCourtyard ),
                    groupOverrides );
        propMgr.AddProperty( new PROPERTY<FOOTPRINT, std::optional<int>>(
                    _HKI( "Clearance Override" ),
                    &FOOTPRINT::SetLocalClearance, &FOOTPRINT::GetLocalClearance,
                    PROPERTY_DISPLAY::PT_SIZE ),
                    groupOverrides );
        propMgr.AddProperty( new PROPERTY<FOOTPRINT, std::optional<int>>(
                    _HKI( "Solderpaste Margin Override" ),
                    &FOOTPRINT::SetLocalSolderPasteMargin, &FOOTPRINT::GetLocalSolderPasteMargin,
                    PROPERTY_DISPLAY::PT_SIZE ),
                    groupOverrides );
        propMgr.AddProperty( new PROPERTY<FOOTPRINT, std::optional<double>>(
                    _HKI( "Solderpaste Margin Ratio Override" ),
                    &FOOTPRINT::SetLocalSolderPasteMarginRatio,
                    &FOOTPRINT::GetLocalSolderPasteMarginRatio,
                    PROPERTY_DISPLAY::PT_RATIO ),
                    groupOverrides );
        propMgr.AddProperty( new PROPERTY_ENUM<FOOTPRINT, ZONE_CONNECTION>(
                    _HKI( "Zone Connection Style" ),
                    &FOOTPRINT::SetLocalZoneConnection, &FOOTPRINT::GetLocalZoneConnection ),
                    groupOverrides );
    }
} _FOOTPRINT_DESC;