File: AI.cpp

package info (click to toggle)
endless-sky 0.10.16-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 414,608 kB
  • sloc: cpp: 73,435; python: 893; xml: 666; sh: 271; makefile: 28
file content (5130 lines) | stat: -rw-r--r-- 179,770 bytes parent folder | download
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
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
/* AI.cpp
Copyright (c) 2014 by Michael Zahniser

Endless Sky 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 3 of the License, or (at your option) any later version.

Endless Sky 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, see <https://www.gnu.org/licenses/>.
*/

#include "AI.h"

#include "audio/Audio.h"
#include "Command.h"
#include "ConditionsStore.h"
#include "DistanceMap.h"
#include "FighterHitHelper.h"
#include "Flotsam.h"
#include "text/Format.h"
#include "FormationPattern.h"
#include "FormationPositioner.h"
#include "GameData.h"
#include "Gamerules.h"
#include "Government.h"
#include "Hardpoint.h"
#include "JumpType.h"
#include "image/Mask.h"
#include "Messages.h"
#include "Minable.h"
#include "pi.h"
#include "Planet.h"
#include "PlayerInfo.h"
#include "Point.h"
#include "Port.h"
#include "Preferences.h"
#include "Random.h"
#include "RoutePlan.h"
#include "Ship.h"
#include "ship/ShipAICache.h"
#include "ShipEvent.h"
#include "ShipJumpNavigation.h"
#include "StellarObject.h"
#include "System.h"
#include "UI.h"
#include "Weapon.h"
#include "Wormhole.h"

#include <algorithm>
#include <cmath>
#include <limits>
#include <set>
#include <utility>

using namespace std;

namespace {
	// If the player issues any of those commands, then any autopilot actions for the player get cancelled.
	const Command &AutopilotCancelCommands()
	{
		static const Command cancelers(Command::LAND | Command::JUMP | Command::FLEET_JUMP | Command::BOARD
			| Command::AFTERBURNER | Command::BACK | Command::FORWARD | Command::LEFT | Command::RIGHT
			| Command::AUTOSTEER | Command::STOP);

		return cancelers;
	}

	bool NeedsFuel(const Ship &ship)
	{
		return ship.GetSystem() && !ship.IsEnteringHyperspace() && !ship.GetSystem()->HasFuelFor(ship)
				&& ship.NeedsFuel();
	}

	bool NeedsEnergy(const Ship &ship)
	{
		return ship.GetSystem() && !ship.IsEnteringHyperspace() && ship.NeedsEnergy();
	}

	bool IsStranded(const Ship &ship)
	{
		return NeedsFuel(ship) || NeedsEnergy(ship);
	}

	bool CanBoard(const Ship &ship, const Ship &target)
	{
		if(&ship == &target)
			return false;
		if(target.IsDestroyed() || !target.IsTargetable() || target.GetSystem() != ship.GetSystem())
			return false;
		if(IsStranded(target) && !ship.GetGovernment()->IsEnemy(target.GetGovernment()))
			return true;
		return target.IsDisabled();
	}

	// Check if the given ship can "swarm" the targeted ship, e.g. to provide anti-missile cover.
	bool CanSwarm(const Ship &ship, const Ship &target)
	{
		if(target.GetPersonality().IsSwarming() || target.IsHyperspacing())
			return false;
		if(target.GetGovernment()->IsEnemy(ship.GetGovernment()))
			return false;
		if(target.GetSystem() != ship.GetSystem())
			return false;
		return target.IsTargetable();
	}

	double AngleDiff(double a, double b)
	{
		a = abs(a - b);
		return min(a, 360. - a);
	}

	// Determine if all able, non-carried escorts are ready to jump with this
	// ship. Carried escorts are waited for in AI::Step.
	bool EscortsReadyToJump(const Ship &ship)
	{
		bool shipIsYours = ship.IsYours();
		const Government *gov = ship.GetGovernment();
		for(const weak_ptr<Ship> &ptr : ship.GetEscorts())
		{
			shared_ptr<const Ship> escort = ptr.lock();
			// Skip escorts which are not player-owned and not escort mission NPCs.
			if(!escort || (shipIsYours && !escort->IsYours() && (!escort->GetPersonality().IsEscort()
					|| gov->IsEnemy(escort->GetGovernment()))))
				continue;
			if(!escort->IsDisabled() && !escort->CanBeCarried()
					&& escort->GetSystem() == ship.GetSystem()
					&& escort->JumpNavigation().JumpFuel() && !escort->IsReadyToJump(true))
				return false;
		}
		return true;
	}

	bool EscortsReadyToLand(const Ship &ship)
	{
		bool shipIsYours = ship.IsYours();
		const Government *gov = ship.GetGovernment();
		for(const weak_ptr<Ship> &ptr : ship.GetEscorts())
		{
			shared_ptr<const Ship> escort = ptr.lock();
			// Skip escorts which are not player-owned and not escort mission NPCs.
			if(!escort || (shipIsYours && !escort->IsYours() && (!escort->GetPersonality().IsEscort()
				|| gov->IsEnemy(escort->GetGovernment()))))
				continue;
			if(escort->IsDisabled())
				continue;
			if(escort->GetTargetStellar() == ship.GetTargetStellar() && !escort->CanLand())
				return false;
		}
		return true;
	}

	// Determine if the ship has any usable weapons.
	bool IsArmed(const Ship &ship)
	{
		for(const Hardpoint &hardpoint : ship.Weapons())
		{
			const Weapon *weapon = hardpoint.GetOutfit();
			if(weapon && !hardpoint.IsSpecial())
			{
				if(weapon->Ammo() && !ship.OutfitCount(weapon->Ammo()))
					continue;
				return true;
			}
		}
		return false;
	}

	void Deploy(const Ship &ship, bool includingDamaged)
	{
		for(const Ship::Bay &bay : ship.Bays())
			if(bay.ship && (includingDamaged || bay.ship->Health() > .75) &&
					(!bay.ship->IsYours() || bay.ship->HasDeployOrder()))
				bay.ship->SetCommands(Command::DEPLOY);
	}

	// Helper function for selecting the ships for formation commands.
	vector<Ship *> GetShipsForFormationCommand(const PlayerInfo &player)
	{
		// Figure out what ships we are giving orders to.
		vector<Ship *> targetShips;
		auto &selectedShips = player.SelectedShips();
		// If selectedShips is empty, this applies to the whole fleet.
		if(selectedShips.empty())
		{
			auto &playerShips = player.Ships();
			targetShips.reserve(playerShips.size() - 1);
			for(const shared_ptr<Ship> &it : player.Ships())
				if(it.get() != player.Flagship() && !it->IsParked()
						&& !it->IsDestroyed() && !it->IsDisabled())
					targetShips.push_back(it.get());
		}
		else
		{
			targetShips.reserve(selectedShips.size());
			for(const weak_ptr<Ship> &it : selectedShips)
			{
				shared_ptr<Ship> ship = it.lock();
				if(ship)
					targetShips.push_back(ship.get());
			}
		}

		return targetShips;
	}

	// Issue deploy orders for the selected ships (or the full fleet if no ships are selected).
	void IssueDeploy(const PlayerInfo &player)
	{
		// Lay out the rules for what constitutes a deployable ship. (Since player ships are not
		// deleted from memory until the next landing, check both parked and destroyed states.)
		auto isCandidate = [](const shared_ptr<Ship> &ship) -> bool
		{
			return ship->CanBeCarried() && !ship->IsParked() && !ship->IsDestroyed();
		};

		auto toDeploy = vector<Ship *> {};
		auto toRecall = vector<Ship *> {};
		{
			auto maxCount = player.Ships().size() / 2;
			toDeploy.reserve(maxCount);
			toRecall.reserve(maxCount);
		}

		// First, check if the player selected any carried ships.
		for(const weak_ptr<Ship> &it : player.SelectedShips())
		{
			shared_ptr<Ship> ship = it.lock();
			if(ship && ship->IsYours() && isCandidate(ship))
				(ship->HasDeployOrder() ? toRecall : toDeploy).emplace_back(ship.get());
		}
		// If needed, check the player's fleet for deployable ships.
		if(toDeploy.empty() && toRecall.empty())
			for(const shared_ptr<Ship> &ship : player.Ships())
				if(isCandidate(ship) && ship.get() != player.Flagship())
					(ship->HasDeployOrder() ? toRecall : toDeploy).emplace_back(ship.get());

		// If any ships were not yet ordered to deploy, deploy them.
		if(!toDeploy.empty())
		{
			for(Ship *ship : toDeploy)
				ship->SetDeployOrder(true);
			string ship = (toDeploy.size() == 1 ? "ship" : "ships");
			Messages::Add("Deployed " + to_string(toDeploy.size()) + " carried " + ship + ".", Messages::Importance::High);
		}
		// Otherwise, instruct the carried ships to return to their berth.
		else if(!toRecall.empty())
		{
			for(Ship *ship : toRecall)
				ship->SetDeployOrder(false);
			string ship = (toRecall.size() == 1 ? "ship" : "ships");
			Messages::Add("Recalled " + to_string(toRecall.size()) + " carried " + ship + ".", Messages::Importance::High);
		}
	}

	// Check if the ship contains a carried ship that needs to launch.
	bool HasDeployments(const Ship &ship)
	{
		for(const Ship::Bay &bay : ship.Bays())
			if(bay.ship && bay.ship->HasDeployOrder())
				return true;
		return false;
	}

	// Determine if the ship with the given travel plan should refuel in
	// its current system, or if it should keep traveling.
	bool ShouldRefuel(const Ship &ship, const RoutePlan &route)
	{
		// If we can't get to the destination --- no reason to refuel.
		// (though AI may choose to elsewhere)
		if(!route.HasRoute())
			return false;

		// If the ship is full, no refuel.
		if(ship.Fuel() == 1.)
			return false;

		// If the ship has nowhere to refuel, no refuel.
		const System *from = ship.GetSystem();
		if(!from->HasFuelFor(ship))
			return false;

		// If the ship doesn't have fuel, no refuel.
		double fuelCapacity = ship.Attributes().Get("fuel capacity");
		if(!fuelCapacity)
			return false;

		// If the ship has no drive (or doesn't require fuel), no refuel.
		if(!ship.JumpNavigation().JumpFuel())
			return false;

		// Now we know it could refuel. But it could also jump along the route
		// and refuel later. Calculate if it can reach the next refuel.
		double fuel = fuelCapacity * ship.Fuel();
		const vector<pair<const System *, int>> costs = route.FuelCosts();
		for(auto it = costs.rbegin(); it != costs.rend(); ++it)
		{
			// If the next system with fuel is outside the range of this ship, should refuel.
			if(it->first->HasFuelFor(ship))
				return fuel < it->second;
		}

		// If no system on the way has fuel, refuel if needed to get to the destination.
		return fuel < route.RequiredFuel();
	}

	// The health remaining before becoming disabled, at which fighters and
	// other ships consider retreating from battle.
	const double RETREAT_HEALTH = .25;

	bool ShouldFlee(Ship &ship)
	{
		const Personality &personality = ship.GetPersonality();

		if(personality.IsFleeing())
			return true;

		if(personality.IsStaying())
			return false;

		const bool lowHealth = ship.Health() < RETREAT_HEALTH + .25 * personality.IsCoward();
		if(!personality.IsDaring() && lowHealth)
			return true;

		if(ship.GetAICache().NeedsAmmo())
			return true;

		if(personality.IsGetaway() && ship.Cargo().Free() == 0 && !ship.GetParent())
			return true;

		return false;
	}

	bool StayOrLinger(Ship &ship)
	{
		const Personality &personality = ship.GetPersonality();
		if(personality.IsStaying())
			return true;

		const Government *government = ship.GetGovernment();
		shared_ptr<const Ship> parent = ship.GetParent();
		if(parent && government && parent->GetGovernment()->IsEnemy(government))
			return true;

		if(ship.IsFleeing())
			return false;

		// Everything after here is the lingering logic.

		if(!personality.IsLingering())
			return false;
		// NPCs that can follow the player do not linger.
		if(ship.IsSpecial() && !personality.IsUninterested())
			return false;

		const System *system = ship.GetSystem();
		const System *destination = ship.GetTargetSystem();

		// Ships not yet at their destination must go there before they can linger.
		if(destination && destination != system)
			return false;
		// Ship cannot linger any longer in this system.
		if(!system || ship.GetLingerSteps() >= system->MinimumFleetPeriod() / 4)
			return false;

		ship.Linger();
		return true;
	}

	// Constants for the invisible fence timer.
	const int FENCE_DECAY = 4;
	const int FENCE_MAX = 600;

	// An offset to prevent the ship from being not quite over the point to departure.
	const double SAFETY_OFFSET = 1.;

	// The minimum speed advantage a ship has to have to consider running away.
	const double SAFETY_MULTIPLIER = 1.1;

	// If a ship's velocity is below this value, the ship is considered stopped.
	constexpr double VELOCITY_ZERO = .001;
}



AI::AI(PlayerInfo &player, const List<Ship> &ships, const List<Minable> &minables, const List<Flotsam> &flotsam)
	: player(player), ships(ships), minables(minables), flotsam(flotsam)
{
	// Allocate a starting amount of hardpoints for ships.
	firingCommands.SetHardpoints(12);
	RegisterDerivedConditions(player.Conditions());
}



// Fleet commands from the player.
void AI::IssueFormationChange(PlayerInfo &player)
{
	// Figure out what ships we are giving orders to
	vector<Ship *> targetShips = GetShipsForFormationCommand(player);
	if(targetShips.empty())
		return;

	const auto &formationPatterns = GameData::Formations();
	if(formationPatterns.empty())
	{
		Messages::Add("No formations available.", Messages::Importance::High);
		return;
	}

	// First check which and how many formation patterns we have in the current set of selected ships.
	// If there is more than 1 pattern in the selection, then this command will change all selected
	// ships to use the pattern that was found first. If there is only 1 pattern, then this command
	// will change all selected ships to use the next pattern available.
	const FormationPattern *toSet = nullptr;
	bool multiplePatternsSet = false;
	for(Ship *ship : targetShips)
	{
		const FormationPattern *shipsPattern = ship->GetFormationPattern();
		if(shipsPattern)
		{
			if(!toSet)
				toSet = shipsPattern;
			else if(toSet != shipsPattern)
			{
				multiplePatternsSet = true;
				break;
			}
		}
	}

	// Now determine what formation pattern to set.
	if(!toSet)
		// If no pattern was set at all, then we set the first one from the set of formationPatterns.
		toSet = &(formationPatterns.begin()->second);
	else if(!multiplePatternsSet)
	{
		// If only one pattern was found, then select the next pattern (or clear the pattern if there is no next).
		auto it = formationPatterns.find(toSet->TrueName());
		if(it != formationPatterns.end())
			++it;
		toSet = (it == formationPatterns.end() ? nullptr : &(it->second));
	}
	// If more than one formation was found on the ships, then we set the pattern it to the first one found.
	// No code is needed here for this option, since all variables are already set to just apply the change below.

	// Now set the pattern on the selected ships, and tell them to gather.
	for(Ship *ship : targetShips)
	{
		ship->SetFormationPattern(toSet);
		orders[ship].Add(OrderSingle{Orders::Types::GATHER});
		orders[ship].SetTargetShip(player.FlagshipPtr());
	}

	unsigned int count = targetShips.size();
	string message = to_string(count) + (count == 1 ? " ship" : " ships") + " will ";
	message += toSet ? ("assume \"" + toSet->TrueName() + "\" formation.") : "no longer fly in formation.";
	Messages::Add(message, Messages::Importance::Low);
}



void AI::IssueShipTarget(const shared_ptr<Ship> &target)
{
	bool isEnemy = target->GetGovernment()->IsEnemy();
	// TODO: There's an error in the code style checker that flags using {} instead of () below.
	OrderSingle newOrder(isEnemy ?
		target->IsDisabled() ? Orders::Types::FINISH_OFF : Orders::Types::ATTACK
		: Orders::Types::KEEP_STATION);
	newOrder.SetTargetShip(target);
	IssueOrder(newOrder,
		(isEnemy ? "focusing fire on" : "following") + (" \"" + target->GivenName() + "\"."));
}



void AI::IssueAsteroidTarget(const shared_ptr<Minable> &targetAsteroid)
{
	OrderSingle newOrder{Orders::Types::MINE};
	newOrder.SetTargetAsteroid(targetAsteroid);
	IssueOrder(newOrder,
		"focusing fire on " + targetAsteroid->DisplayName() + " " + targetAsteroid->Noun() + ".");
}



void AI::IssueMoveTarget(const Point &target, const System *moveToSystem)
{
	OrderSingle newOrder{Orders::Types::MOVE_TO};
	newOrder.SetTargetPoint(target);
	newOrder.SetTargetSystem(moveToSystem);
	string description = "moving to the given location";
	description += player.GetSystem() == moveToSystem ? "." : (" in the " + moveToSystem->DisplayName() + " system.");
	IssueOrder(newOrder, description);
}



// Commands issued via the keyboard (mostly, to the flagship).
void AI::UpdateKeys(PlayerInfo &player, const Command &activeCommands)
{
	const Ship *flagship = player.Flagship();
	if(!flagship || flagship->IsDestroyed())
		return;

	escortsUseAmmo = Preferences::Has("Escorts expend ammo");
	escortsAreFrugal = Preferences::Has("Escorts use ammo frugally");

	if(!autoPilot.Has(Command::STOP) && activeCommands.Has(Command::STOP)
			&& flagship->Velocity().Length() > VELOCITY_ZERO)
		Messages::Add("Coming to a stop.", Messages::Importance::High);

	autoPilot |= activeCommands;
	if(activeCommands.Has(AutopilotCancelCommands()))
	{
		bool canceled = (autoPilot.Has(Command::JUMP) && !activeCommands.Has(Command::JUMP | Command::FLEET_JUMP));
		canceled |= (autoPilot.Has(Command::STOP) && !activeCommands.Has(Command::STOP));
		canceled |= (autoPilot.Has(Command::LAND) && !activeCommands.Has(Command::LAND));
		canceled |= (autoPilot.Has(Command::BOARD) && !activeCommands.Has(Command::BOARD));
		if(canceled)
			Messages::Add("Disengaging autopilot.", Messages::Importance::High);
		autoPilot.Clear();
	}

	// Only toggle the "cloak" command if one of your ships has a cloaking device.
	if(activeCommands.Has(Command::CLOAK))
		for(const auto &it : player.Ships())
			if(!it->IsParked() && it->CloakingSpeed())
			{
				isCloaking = !isCloaking;
				Messages::Add(isCloaking ? "Engaging cloaking device." : "Disengaging cloaking device."
					, Messages::Importance::High);
				break;
			}

	// Toggle your secondary weapon.
	if(activeCommands.Has(Command::SELECT))
		player.SelectNextSecondary();

	// The commands below here only apply if you have escorts or fighters.
	if(player.Ships().size() < 2)
		return;

	// Toggle the "deploy" command for the fleet or selected ships.
	if(activeCommands.Has(Command::DEPLOY))
		IssueDeploy(player);

	// The gather command controls formation flying when combined with shift.
	const bool shift = activeCommands.Has(Command::SHIFT);
	if(shift && activeCommands.Has(Command::GATHER))
		IssueFormationChange(player);

	shared_ptr<Ship> target = flagship->GetTargetShip();
	shared_ptr<Minable> targetAsteroid = flagship->GetTargetAsteroid();
	if(activeCommands.Has(Command::FIGHT) && target && !target->IsYours() && !shift)
	{
		OrderSingle newOrder{target->IsDisabled() ? Orders::Types::FINISH_OFF : Orders::Types::ATTACK};
		newOrder.SetTargetShip(target);
		IssueOrder(newOrder, "focusing fire on \"" + target->GivenName() + "\".");
	}
	else if(activeCommands.Has(Command::FIGHT) && !shift && targetAsteroid)
		IssueAsteroidTarget(targetAsteroid);
	if(activeCommands.Has(Command::HOLD_FIRE) && !shift)
	{
		OrderSingle newOrder{Orders::Types::HOLD_FIRE};
		IssueOrder(newOrder, "holding fire.");
	}
	if(activeCommands.Has(Command::HOLD_POSITION) && !shift)
	{
		OrderSingle newOrder{Orders::Types::HOLD_POSITION};
		IssueOrder(newOrder, "holding position.");
	}
	if(activeCommands.Has(Command::GATHER) && !shift)
	{
		OrderSingle newOrder{Orders::Types::GATHER};
		newOrder.SetTargetShip(player.FlagshipPtr());
		IssueOrder(newOrder, "gathering around your flagship.");
	}

	// Get rid of any invalid orders. Carried ships will retain orders in case they are deployed.
	for(auto it = orders.begin(); it != orders.end(); )
	{
		it->second.Validate(it->first, flagship->GetSystem());
		if(it->second.Empty())
		{
			it = orders.erase(it);
			continue;
		}
		++it;
	}
}



void AI::UpdateEvents(const list<ShipEvent> &events)
{
	for(const ShipEvent &event : events)
	{
		const auto &target = event.Target();
		if(!target)
			continue;

		if(event.Actor())
		{
			actions[event.Actor()][target] |= event.Type();
			if(event.TargetGovernment())
				notoriety[event.Actor()][event.TargetGovernment()] |= event.Type();
		}

		const auto &actorGovernment = event.ActorGovernment();
		if(actorGovernment)
		{
			governmentActions[actorGovernment][target] |= event.Type();
			if(actorGovernment->IsPlayer() && event.TargetGovernment())
			{
				int &bitmap = playerActions[target];
				int newActions = event.Type() - (event.Type() & bitmap);
				bitmap |= event.Type();
				// If you provoke the same ship twice, it should have an effect both times.
				if(event.Type() & ShipEvent::PROVOKE)
					newActions |= ShipEvent::PROVOKE;
				event.TargetGovernment()->Offend(newActions, target->CrewValue());
			}
		}
	}
}



// Remove records of what happened in the previous system, now that
// the player has entered a new one.
void AI::Clean()
{
	// Records of what various AI ships and factions have done.
	actions.clear();
	notoriety.clear();
	governmentActions.clear();
	scanPermissions.clear();
	playerActions.clear();
	swarmCount.clear();
	fenceCount.clear();
	cargoScans.clear();
	outfitScans.clear();
	scanTime.clear();
	miningAngle.clear();
	miningRadius.clear();
	miningTime.clear();
	appeasementThreshold.clear();
	// Records for formations flying around lead ships and other objects.
	formations.clear();
	// Records that affect the combat behavior of various governments.
	shipStrength.clear();
	enemyStrength.clear();
	allyStrength.clear();
}



// Clear ship orders and assistance requests. These should be done
// when the player lands, but not when they change systems.
void AI::ClearOrders()
{
	helperList.clear();
	orders.clear();
}



void AI::Step(Command &activeCommands)
{
	// First, figure out the comparative strengths of the present governments.
	const System *playerSystem = player.GetSystem();
	map<const Government *, int64_t> strength;
	UpdateStrengths(strength, playerSystem);
	CacheShipLists();

	// Update the counts of how long ships have been outside the "invisible fence."
	// If a ship ceases to exist, this also ensures that it will be removed from
	// the fence count map after a few seconds.
	for(auto it = fenceCount.begin(); it != fenceCount.end(); )
	{
		it->second -= FENCE_DECAY;
		if(it->second < 0)
			it = fenceCount.erase(it);
		else
			++it;
	}
	for(const auto &it : ships)
	{
		const System *system = it->GetActualSystem();
		if(system && it->Position().Length() >= system->InvisibleFenceRadius())
		{
			int &value = fenceCount[&*it];
			value = min(FENCE_MAX, value + FENCE_DECAY + 1);
		}
	}

	// Allow all formation-positioners to handle their internal administration to
	// prepare for the next cycle.
	for(auto &bodyIt : formations)
		for(auto &positionerIt : bodyIt.second)
			positionerIt.second.Step();

	const Ship *flagship = player.Flagship();
	step = (step + 1) & 31;
	int targetTurn = 0;
	int minerCount = 0;
	const int maxMinerCount = minables.empty() ? 0 : 9;
	bool opportunisticEscorts = !Preferences::Has("Turrets focus fire");
	bool fightersRetreat = Preferences::Has("Damaged fighters retreat");
	const int npcMaxMiningTime = GameData::GetGamerules().NPCMaxMiningTime();
	for(const auto &it : ships)
	{
		// A destroyed ship can't do anything.
		if(it->IsDestroyed())
			continue;
		// Skip any carried fighters or drones that are somehow in the list.
		if(!it->GetSystem())
			continue;

		if(it.get() == flagship)
		{
			// Player cannot do anything if the flagship is landing.
			if(!flagship->IsLanding())
				MovePlayer(*it, activeCommands);
			continue;
		}

		const Government *gov = it->GetGovernment();
		const Personality &personality = it->GetPersonality();
		double healthRemaining = it->Health();
		bool isPresent = (it->GetSystem() == playerSystem);
		bool isStranded = IsStranded(*it);
		bool thisIsLaunching = (isPresent && HasDeployments(*it));
		if(isStranded || it->IsDisabled())
		{
			// Attempt to find a friendly ship to render assistance.
			if(!it->GetPersonality().IsDerelict())
				AskForHelp(*it, isStranded, flagship);

			if(it->IsDisabled())
			{
				// Ships other than escorts should deploy fighters if disabled.
				if(!it->IsYours() || thisIsLaunching)
				{
					it->SetCommands(Command::DEPLOY);
					Deploy(*it, !(it->IsYours() && fightersRetreat));
				}
				// Avoid jettisoning cargo as soon as this ship is repaired.
				if(personality.IsAppeasing())
				{
					double health = .5 * it->Shields() + it->Hull();
					double &threshold = appeasementThreshold[it.get()];
					threshold = max((1. - health) + .1, threshold);
				}
				continue;
			}
		}
		// Overheated ships are effectively disabled, and cannot fire, cloak, etc.
		if(it->IsOverheated())
			continue;

		Command command;
		firingCommands.SetHardpoints(it->Weapons().size());
		if(it->IsYours())
		{
			if(it->HasBays() && thisIsLaunching)
			{
				// If this is a carrier, launch whichever of its fighters are at
				// good enough health to survive a fight.
				command |= Command::DEPLOY;
				Deploy(*it, !fightersRetreat);
			}
			if(isCloaking)
				command |= Command::CLOAK;
		}

		// Cloak if the AI considers it appropriate.
		if(!it->IsYours() || !isCloaking)
			if(DoCloak(*it, command))
			{
				// The ship chose to retreat from its target, e.g. to repair.
				it->SetCommands(command);
				continue;
			}

		shared_ptr<Ship> parent = it->GetParent();
		if(parent && parent->IsDestroyed())
		{
			// An NPC that loses its fleet leader should attempt to
			// follow that leader's parent. For most mission NPCs,
			// this is the player. Any regular NPCs and mission NPCs
			// with "personality uninterested" become independent.
			parent = parent->GetParent();
			it->SetParent(parent);
		}

		// Pick a target and automatically fire weapons.
		shared_ptr<Ship> target = it->GetTargetShip();
		shared_ptr<Minable> targetAsteroid = it->GetTargetAsteroid();
		shared_ptr<Flotsam> targetFlotsam = it->GetTargetFlotsam();
		if(isPresent && it->IsYours() && targetFlotsam && FollowOrders(*it, command))
			continue;
		// Determine if this ship was trying to scan its previous target. If so, keep
		// track of this ship's scan time and count.
		if(isPresent && !it->IsYours())
		{
			// Assume that if the target is friendly, not disabled, of a different
			// government to this ship, and this ship has scanning capabilities
			// then it was attempting to scan the target. This isn't a perfect
			// assumption, but should be good enough for now.
			bool cargoScan = it->Attributes().Get("cargo scan power");
			bool outfitScan = it->Attributes().Get("outfit scan power");
			if((cargoScan || outfitScan) && target && !target->IsDisabled()
				&& !target->GetGovernment()->IsEnemy(gov) && target->GetGovernment() != gov)
			{
				++scanTime[&*it];
				if(it->CargoScanFraction() == 1.)
					cargoScans[&*it].insert(&*target);
				if(it->OutfitScanFraction() == 1.)
					outfitScans[&*it].insert(&*target);
			}
		}
		if(isPresent && !personality.IsSwarming())
		{
			// Each ship only switches targets twice a second, so that it can
			// focus on damaging one particular ship.
			targetTurn = (targetTurn + 1) & 31;
			if(targetTurn == step || !target || target->IsDestroyed() || (target->IsDisabled() &&
					(personality.Disables() || (!FighterHitHelper::IsValidTarget(target.get()) && !personality.IsVindictive())))
					|| (target->IsFleeing() && personality.IsMerciful()) || !target->IsTargetable())
			{
				target = FindTarget(*it);
				it->SetTargetShip(target);
			}
		}
		if(isPresent)
		{
			AimTurrets(*it, firingCommands, it->IsYours() ? opportunisticEscorts : personality.IsOpportunistic());
			if(targetAsteroid)
				AutoFire(*it, firingCommands, *targetAsteroid);
			else
				AutoFire(*it, firingCommands);
		}

		// If this ship is hyperspacing, or in the act of
		// launching or landing, it can't do anything else.
		if(it->IsHyperspacing() || it->Zoom() < 1.)
		{
			it->SetCommands(command);
			it->SetCommands(firingCommands);
			continue;
		}

		// Run away if your hostile target is not disabled
		// and you are either badly damaged or have run out of ammo.
		// Player ships never stop targeting hostiles, while hostile mission NPCs will
		// do so only if they are allowed to leave.
		const bool shouldFlee = ShouldFlee(*it);
		if(!it->IsYours() && shouldFlee && target && target->GetGovernment()->IsEnemy(gov) && !target->IsDisabled()
			&& (!it->GetParent() || !it->GetParent()->GetGovernment()->IsEnemy(gov)))
		{
			// Make sure the ship has somewhere to flee to.
			const System *system = it->GetSystem();
			if(it->JumpsRemaining() && (!system->Links().empty() || it->JumpNavigation().HasJumpDrive()))
				target.reset();
			else
				for(const StellarObject &object : system->Objects())
					if(object.HasSprite() && object.HasValidPlanet() && object.GetPlanet()->IsInhabited()
							&& object.GetPlanet()->CanLand(*it))
					{
						target.reset();
						break;
					}

			if(target)
				// This ship has nowhere to flee to: Stop fleeing.
				it->SetFleeing(false);
			else
			{
				// This ship has somewhere to flee to: Remove target and mark this ship as fleeing.
				it->SetTargetShip(target);
				it->SetFleeing();
			}
		}
		else if(it->IsFleeing())
			it->SetFleeing(false);

		// Special actions when a ship is heavily damaged:
		if(healthRemaining < RETREAT_HEALTH + .25)
		{
			// Cowards abandon their fleets.
			if(parent && personality.IsCoward())
			{
				parent.reset();
				it->SetParent(parent);
			}
			// Appeasing ships jettison cargo to distract their pursuers.
			if(personality.IsAppeasing() && it->Cargo().Used())
				DoAppeasing(it, &appeasementThreshold[it.get()]);
		}

		// If recruited to assist a ship, follow through on the commitment
		// instead of ignoring it due to other personality traits.
		shared_ptr<Ship> shipToAssist = it->GetShipToAssist();
		if(shipToAssist)
		{
			if(shipToAssist->IsDestroyed() || shipToAssist->GetSystem() != it->GetSystem()
					|| shipToAssist->IsLanding() || shipToAssist->IsHyperspacing()
					|| shipToAssist->GetGovernment()->IsEnemy(gov)
					|| (!shipToAssist->IsDisabled() && !shipToAssist->NeedsFuel() && !shipToAssist->NeedsEnergy()))
			{
				if(target == shipToAssist)
				{
					target.reset();
					it->SetTargetShip(nullptr);
				}
				shipToAssist.reset();
				it->SetShipToAssist(nullptr);
			}
			else if(!it->IsBoarding())
			{
				MoveTo(*it, command, shipToAssist->Position(), shipToAssist->Velocity(), 40., .8);
				command |= Command::BOARD;
			}

			if(shipToAssist)
			{
				it->SetTargetShip(shipToAssist);
				it->SetCommands(command);
				it->SetCommands(firingCommands);
				continue;
			}
		}

		// This ship may have updated its target ship.
		double targetDistance = numeric_limits<double>::infinity();
		target = it->GetTargetShip();
		if(target)
			targetDistance = target->Position().Distance(it->Position());

		// Special case: if the player's flagship tries to board a ship to
		// refuel it, that escort should hold position for boarding.
		isStranded |= (flagship && it == flagship->GetTargetShip() && CanBoard(*flagship, *it)
			&& autoPilot.Has(Command::BOARD));

		// Stranded ships that have a helper need to stop and be assisted.
		bool strandedWithHelper = isStranded &&
			(HasHelper(*it, NeedsFuel(*it), NeedsEnergy(*it)) || it->GetPersonality().IsDerelict() || it->IsYours());

		// Behave in accordance with personality traits.
		if(isPresent && personality.IsSwarming() && !strandedWithHelper)
		{
			// Swarming ships should not wait for (or be waited for by) any ship.
			if(parent)
			{
				parent.reset();
				it->SetParent(parent);
			}
			// Flock between allied, in-system ships.
			DoSwarming(*it, command, target);
			it->SetCommands(command);
			it->SetCommands(firingCommands);
			continue;
		}

		if(isPresent && personality.IsSecretive())
		{
			if(DoSecretive(*it, command))
			{
				it->SetCommands(command);
				continue;
			}
		}

		// Surveillance NPCs with enforcement authority (or those from
		// missions) should perform scans and surveys of the system.
		if(isPresent && personality.IsSurveillance() && !strandedWithHelper
				&& (scanPermissions[gov] || it->IsSpecial()))
		{
			DoSurveillance(*it, command, target);
			it->SetCommands(command);
			it->SetCommands(firingCommands);
			continue;
		}

		// Ships that harvest flotsam prioritize it over stopping to be refueled.
		if(isPresent && personality.Harvests() && DoHarvesting(*it, command))
		{
			it->SetCommands(command);
			it->SetCommands(firingCommands);
			continue;
		}

		// Attacking a hostile ship, fleeing and stopping to be refueled are more important than mining.
		if(isPresent && personality.IsMining() && !shouldFlee && !target && !strandedWithHelper && maxMinerCount)
		{
			// Miners with free cargo space and available mining time should mine. Mission NPCs
			// should mine even if there are other miners or they have been mining a while.
			if(it->Cargo().Free() >= 5 && IsArmed(*it) && (it->IsSpecial()
					|| (++miningTime[&*it] < npcMaxMiningTime && ++minerCount < maxMinerCount)))
			{
				if(it->HasBays())
				{
					command |= Command::DEPLOY;
					Deploy(*it, false);
				}
				DoMining(*it, command);
				it->SetCommands(command);
				it->SetCommands(firingCommands);
				continue;
			}
			// Fighters and drones should assist their parent's mining operation if they cannot
			// carry ore, and the asteroid is near enough that the parent can harvest the ore.
			if(it->CanBeCarried() && parent && miningTime[parent.get()] < 3601)
			{
				const shared_ptr<Minable> &minable = parent->GetTargetAsteroid();
				if(minable && minable->Position().Distance(parent->Position()) < 600.)
				{
					it->SetTargetAsteroid(minable);
					MoveToAttack(*it, command, *minable);
					AutoFire(*it, firingCommands, *minable);
					it->SetCommands(command);
					it->SetCommands(firingCommands);
					continue;
				}
			}
			it->SetTargetAsteroid(nullptr);
		}

		// Handle carried ships:
		if(it->CanBeCarried())
		{
			// A carried ship must belong to the same government as its parent to dock with it.
			bool hasParent = parent && !parent->IsDestroyed() && parent->GetGovernment() == gov;
			bool inParentSystem = hasParent && parent->GetSystem() == it->GetSystem();
			// NPCs may take 30 seconds or longer to find a new parent. Player
			// owned fighter shouldn't take more than a few seconds.
			bool findNewParent = it->IsYours() ? !Random::Int(30) : !Random::Int(1800);
			bool parentHasSpace = inParentSystem && parent->BaysFree(it->Attributes().Category());
			if(findNewParent && parentHasSpace && it->IsYours())
				parentHasSpace = parent->CanCarry(*it);
			if(!hasParent || (!inParentSystem && !it->JumpNavigation().JumpFuel()) || (!parentHasSpace && findNewParent))
			{
				// Find the possible parents for orphaned fighters and drones.
				auto parentChoices = vector<shared_ptr<Ship>>{};
				parentChoices.reserve(ships.size() * .1);
				auto getParentFrom = [&it, &gov, &parentChoices](const list<shared_ptr<Ship>> &otherShips) -> shared_ptr<Ship>
				{
					for(const auto &other : otherShips)
						if(other->GetGovernment() == gov && other->GetSystem() == it->GetSystem() && !other->CanBeCarried())
						{
							if(!other->IsDisabled() && other->CanCarry(*it))
								return other;
							else
								parentChoices.emplace_back(other);
						}
					return shared_ptr<Ship>();
				};
				// Mission ships should only pick amongst ships from the same mission.
				auto missionIt = it->IsSpecial() && !it->IsYours()
					? find_if(player.Missions().begin(), player.Missions().end(),
						[&it](const Mission &m) { return m.HasShip(it); })
					: player.Missions().end();

				shared_ptr<Ship> newParent;
				if(missionIt != player.Missions().end())
				{
					auto &npcs = missionIt->NPCs();
					for(const auto &npc : npcs)
					{
						// Don't reparent to NPC ships that have not been spawned.
						if(!npc.ShouldSpawn())
							continue;
						newParent = getParentFrom(npc.Ships());
						if(newParent)
							break;
					}
				}
				else
					newParent = getParentFrom(ships);

				// If a new parent was found, then this carried ship should always reparent
				// as a ship of its own government is in-system and has space to carry it.
				if(newParent)
					parent = newParent;
				// Otherwise, if one or more in-system ships of the same government were found,
				// this carried ship should flock with one of them, even if they can't carry it.
				else if(!parentChoices.empty())
					parent = parentChoices[Random::Int(parentChoices.size())];
				// Player-owned carriables that can't be carried and have no ships to flock with
				// should keep their current parent, or if it is destroyed, their parent's parent.
				else if(it->IsYours())
				{
					if(parent && parent->IsDestroyed())
						parent = parent->GetParent();
				}
				// All remaining non-player ships should forget their previous parent entirely.
				else
					parent.reset();

				// Player-owned carriables should defer to player carrier if
				// selected parent can't carry it. This is necessary to prevent
				// fighters from jumping around fleet when there's not enough
				// bays.
				if(it->IsYours() && parent && parent->GetParent() && !parent->CanCarry(*it))
					parent = parent->GetParent();

				if(it->GetParent() != parent)
					it->SetParent(parent);
			}
			// Otherwise, check if this ship wants to return to its parent (e.g. to repair).
			else if(parentHasSpace && ShouldDock(*it, *parent, playerSystem))
			{
				it->SetTargetShip(parent);
				MoveTo(*it, command, parent->Position(), parent->Velocity(), 40., .8);
				command |= Command::BOARD;
				it->SetCommands(command);
				it->SetCommands(firingCommands);
				continue;
			}
			// If we get here, it means that the ship has not decided to return
			// to its mothership. So, it should continue to be deployed.
			command |= Command::DEPLOY;
		}
		// If this ship has decided to recall all of its fighters because combat has ceased,
		// it comes to a stop to facilitate their reboarding process.
		bool mustRecall = false;
		if(!target && it->HasBays() && !(it->IsYours() ?
				thisIsLaunching : it->Commands().Has(Command::DEPLOY)))
			for(const weak_ptr<Ship> &ptr : it->GetEscorts())
			{
				shared_ptr<const Ship> escort = ptr.lock();
				// Note: HasDeployOrder is always `false` for NPC ships, as it is solely used for player ships.
				if(escort && escort->CanBeCarried() && !escort->HasDeployOrder() && escort->GetSystem() == it->GetSystem()
						&& !escort->IsDisabled() && it->BaysFree(escort->Attributes().Category()))
				{
					mustRecall = true;
					break;
				}
			}

		// Construct movement / navigation commands as appropriate for the ship.
		if(mustRecall || (strandedWithHelper && !it->GetPersonality().IsDerelict()))
		{
			// Stopping to let fighters board or to be refueled takes priority
			// even over following orders from the player.
			if(it->Velocity().Length() > VELOCITY_ZERO || !target)
				Stop(*it, command);
			else
			{
				command.SetTurn(TurnToward(*it, TargetAim(*it)));
				it->SetVelocity({0., 0.});
			}
		}
		else if(FollowOrders(*it, command))
		{
			// If this is an escort and it followed orders, its only final task
			// is to convert completed MOVE_TO orders into HOLD_POSITION orders.
			UpdateOrders(*it);
		}
		// Hostile "escorts" (i.e. NPCs that are trailing you) only revert to
		// escort behavior when in a different system from you. Otherwise,
		// the behavior depends on what the parent is doing, whether there
		// are hostile targets nearby, and whether the escort has any
		// immediate needs (like refueling).
		else if(!parent)
			MoveIndependent(*it, command);
		else if(parent->GetSystem() != it->GetSystem())
		{
			if(personality.IsStaying() || !it->Attributes().Get("fuel capacity"))
				MoveIndependent(*it, command);
			else
				MoveEscort(*it, command);
		}
		// From here down, we're only dealing with ships that have a "parent"
		// which is in the same system as them.
		else if(parent->GetGovernment()->IsEnemy(gov))
		{
			// Fight your target, if you have one.
			if(target)
				MoveIndependent(*it, command);
			// Otherwise try to find and fight your parent. If your parent
			// can't be both targeted and pursued, then don't follow them.
			else if(parent->IsTargetable() && CanPursue(*it, *parent))
				MoveEscort(*it, command);
			else
				MoveIndependent(*it, command);
		}
		else if(parent->IsDisabled() && !it->CanBeCarried())
		{
			// Your parent is disabled, and is in this system. If you have enemy
			// targets present, fight them. Otherwise, repair your parent.
			if(target)
				MoveIndependent(*it, command);
			else if(!parent->GetPersonality().IsDerelict())
				it->SetShipToAssist(parent);
			else
				CircleAround(*it, command, *parent);
		}
		else if(personality.IsStaying())
			MoveIndependent(*it, command);
		// This is a friendly escort. If the parent is getting ready to
		// jump, always follow.
		else if(parent->Commands().Has(Command::JUMP) && !strandedWithHelper)
			MoveEscort(*it, command);
		// Timid ships always stay near their parent. Injured player
		// escorts will stay nearby until they have repaired a bit.
		else if((personality.IsTimid() || (it->IsYours() && healthRemaining < RETREAT_HEALTH))
				&& parent->Position().Distance(it->Position()) > 500.)
			MoveEscort(*it, command);
		// Otherwise, attack targets depending on your hunting attribute.
		else if(target && (targetDistance < 2000. || personality.IsHunting()))
			MoveIndependent(*it, command);
		// This ship does not feel like fighting.
		else
			MoveEscort(*it, command);

		// Force ships that are overlapping each other to "scatter":
		DoScatter(*it, command);

		it->SetCommands(command);
		it->SetCommands(firingCommands);
	}
}



void AI::SetMousePosition(Point position)
{
	mousePosition = position;
}



// Get the in-system strength of each government's allies and enemies.
int64_t AI::AllyStrength(const Government *government) const
{
	auto it = allyStrength.find(government);
	return (it == allyStrength.end() ? 0 : it->second);
}



int64_t AI::EnemyStrength(const Government *government) const
{
	auto it = enemyStrength.find(government);
	return (it == enemyStrength.end() ? 0 : it->second);
}



// Find nearest landing location.
const StellarObject *AI::FindLandingLocation(const Ship &ship, const bool refuel)
{
	const StellarObject *target = nullptr;
	const System *system = ship.GetSystem();
	if(system)
	{
		// Determine which, if any, planet with fuel or without fuel is closest.
		double closest = numeric_limits<double>::infinity();
		const Point &p = ship.Position();
		for(const StellarObject &object : system->Objects())
		{
			const Planet *planet = object.GetPlanet();
			if(object.HasSprite() && object.HasValidPlanet() && !planet->IsWormhole()
					&& planet->CanLand(ship) && planet->HasFuelFor(ship) == refuel)
			{
				double distance = p.Distance(object.Position());
				if(distance < closest)
				{
					target = &object;
					closest = distance;
				}
			}
		}
	}
	return target;
}



// Check if the given target can be pursued by this ship.
bool AI::CanPursue(const Ship &ship, const Ship &target) const
{
	// If this ship does not care about the "invisible fence", it can always pursue.
	if(ship.GetPersonality().IsUnconstrained())
		return true;

	// Owned ships ignore fence.
	if(ship.IsYours())
		return true;

	// Check if the target is beyond the "invisible fence" for this system.
	const auto fit = fenceCount.find(&target);
	if(fit == fenceCount.end())
		return true;
	else
		return (fit->second != FENCE_MAX);
}



// Check if the ship is being helped, and if not, ask for help.
void AI::AskForHelp(Ship &ship, bool &isStranded, const Ship *flagship)
{
	bool needsFuel = NeedsFuel(ship);
	bool needsEnergy = NeedsEnergy(ship);
	if(HasHelper(ship, needsFuel, needsEnergy))
		isStranded = true;
	else if(!Random::Int(30))
	{
		const Government *gov = ship.GetGovernment();
		bool hasEnemy = false;

		vector<Ship *> canHelp;
		canHelp.reserve(ships.size());
		for(const auto &helper : ships)
		{
			// Never ask yourself for help.
			if(helper.get() == &ship)
				continue;

			// If any able enemies of this ship are in its system, it cannot call for help.
			const System *system = ship.GetSystem();
			if(helper->GetGovernment()->IsEnemy(gov) && flagship && system == flagship->GetSystem())
			{
				// Disabled, overheated, or otherwise untargetable ships pose no threat.
				bool harmless = helper->IsDisabled() || (helper->IsOverheated() && helper->Heat() >= 1.1)
						|| !helper->IsTargetable();
				hasEnemy |= (system == helper->GetSystem() && !harmless);
				if(hasEnemy)
					break;
			}

			// Check if this ship is logically able to help.
			// If the ship is already assisting someone else, it cannot help this ship.
			if(helper->GetShipToAssist() && helper->GetShipToAssist().get() != &ship)
				continue;
			// If the ship is mining or chasing flotsam, it cannot help this ship.
			if(helper->GetTargetAsteroid() || helper->GetTargetFlotsam())
				continue;
			// Your escorts only help other escorts, and your flagship never helps.
			if((helper->IsYours() && !ship.IsYours()) || helper.get() == flagship)
				continue;
			// Your escorts should not help each other if already under orders.
			auto foundOrders = orders.find(helper.get());
			if(foundOrders != orders.end())
			{
				const OrderSet &helperOrders = foundOrders->second;
				// If your own escorts become disabled, then your mining fleet
				// should prioritize repairing escorts instead of mining or
				// harvesting flotsam.
				if(helper->IsYours() && ship.IsYours()
						&& !(helperOrders.Has(Orders::Types::MINE) || helperOrders.Has(Orders::Types::HARVEST)))
					continue;
			}

			// Check if this ship is physically able to help.
			if(!CanHelp(ship, *helper, needsFuel, needsEnergy))
				continue;

			// Prefer fast ships over slow ones.
			canHelp.insert(canHelp.end(), 1 + .3 * helper->MaxVelocity(), helper.get());
		}

		if(!hasEnemy && !canHelp.empty())
		{
			Ship *helper = canHelp[Random::Int(canHelp.size())];
			helper->SetShipToAssist((&ship)->shared_from_this());
			helperList[&ship] = helper->shared_from_this();
			isStranded = true;
		}
		else
			isStranded = false;
	}
	else
		isStranded = false;
}



// Determine if the selected ship is physically able to render assistance.
bool AI::CanHelp(const Ship &ship, const Ship &helper, const bool needsFuel, const bool needsEnergy) const
{
	// A ship being assisted cannot assist.
	if(helperList.find(&helper) != helperList.end())
		return false;

	// Fighters, drones, and disabled / absent ships can't offer assistance.
	if(helper.CanBeCarried() || helper.GetSystem() != ship.GetSystem() ||
			(helper.GetGovernment() != ship.GetGovernment() && helper.CannotAct(Ship::ActionType::COMMUNICATION))
			|| helper.IsOverheated() || helper.IsHyperspacing())
		return false;

	// An enemy cannot provide assistance, and only ships of the same government will repair disabled ships.
	if(helper.GetGovernment()->IsEnemy(ship.GetGovernment())
			|| (ship.IsDisabled() && helper.GetGovernment() != ship.GetGovernment()))
		return false;

	// If the helper has insufficient fuel or energy, it cannot help this ship unless this ship is also disabled.
	if(!ship.IsDisabled() && ((needsFuel && !helper.CanRefuel(ship)) || (needsEnergy && !helper.CanGiveEnergy(ship))))
		return false;

	// For player's escorts, check if the player knows the helper's language.
	if(ship.IsYours() && !helper.GetGovernment()->Language().empty()
			&& !player.Conditions().Get("language: " + helper.GetGovernment()->Language()))
		return false;

	return true;
}



bool AI::HasHelper(const Ship &ship, const bool needsFuel, const bool needsEnergy)
{
	// Do we have an existing ship that was asked to assist?
	if(helperList.find(&ship) != helperList.end())
	{
		shared_ptr<Ship> helper = helperList[&ship].lock();
		if(helper && helper->GetShipToAssist().get() == &ship && CanHelp(ship, *helper, needsFuel, needsEnergy))
			return true;
		else
			helperList.erase(&ship);
	}

	return false;
}



// Pick a new target for the given ship.
shared_ptr<Ship> AI::FindTarget(const Ship &ship) const
{
	// If this ship has no government, it has no enemies.
	shared_ptr<Ship> target;
	const Government *gov = ship.GetGovernment();
	if(!gov || ship.GetPersonality().IsPacifist())
		return FindNonHostileTarget(ship);

	bool isYours = ship.IsYours();
	if(isYours)
	{
		auto it = orders.find(&ship);
		if(it != orders.end())
		{
			if(it->second.Has(Orders::Types::ATTACK) || it->second.Has(Orders::Types::FINISH_OFF))
				return it->second.GetTargetShip();
			if(it->second.Has(Orders::Types::HOLD_FIRE))
				return target;
		}
	}

	// If this ship is not armed, do not make it fight.
	double minRange = numeric_limits<double>::infinity();
	double maxRange = 0.;
	for(const Hardpoint &weapon : ship.Weapons())
		if(weapon.GetOutfit() && !weapon.IsSpecial())
		{
			minRange = min(minRange, weapon.GetOutfit()->Range());
			maxRange = max(maxRange, weapon.GetOutfit()->Range());
		}
	if(!maxRange)
		return FindNonHostileTarget(ship);

	const Personality &person = ship.GetPersonality();
	shared_ptr<Ship> oldTarget = ship.GetTargetShip();
	if(oldTarget && !oldTarget->IsTargetable())
		oldTarget.reset();
	if(oldTarget && person.IsTimid() && oldTarget->IsDisabled()
			&& ship.Position().Distance(oldTarget->Position()) > 1000.)
		oldTarget.reset();
	// Ships with 'plunders' personality always destroy the ships they have boarded
	// unless they also have either or both of the 'disables' or 'merciful' personalities.
	if(oldTarget && person.Plunders() && !person.Disables() && !person.IsMerciful()
			&& oldTarget->IsDisabled() && Has(ship, oldTarget, ShipEvent::BOARD))
		return oldTarget;
	shared_ptr<Ship> parentTarget;
	if(ship.GetParent() && !ship.GetParent()->GetGovernment()->IsEnemy(gov))
		parentTarget = ship.GetParent()->GetTargetShip();
	if(parentTarget && !parentTarget->IsTargetable())
		parentTarget.reset();

	// Find the closest enemy ship (if there is one). If this ship is "hunting,"
	// it will attack any ship in system. Otherwise, if all its weapons have a
	// range higher than 2000, it will engage ships up to 50% beyond its range.
	// If a ship has short range weapons and is not hunting, it will engage any
	// ship that is within 3000 of it.
	double closest = person.IsHunting() ? numeric_limits<double>::infinity() :
		(minRange > 1000.) ? maxRange * 1.5 : 4000.;
	bool hasNemesis = false;
	bool canPlunder = person.Plunders() && ship.Cargo().Free() && !ship.CanBeCarried();
	// Figure out how strong this ship is.
	int64_t maxStrength = 0;
	auto strengthIt = shipStrength.find(&ship);
	if(!person.IsDaring() && strengthIt != shipStrength.end())
		maxStrength = 2 * strengthIt->second;

	// Get a list of all targetable, hostile ships in this system.
	const auto enemies = GetShipsList(ship, true);
	for(const auto &foe : enemies)
	{
		// If this is a "nemesis" ship and it has found one of the player's
		// ships to target, it will only consider the player's owned fleet,
		// or NPCs being escorted by the player.
		const bool isPotentialNemesis = person.IsNemesis()
				&& (foe->IsYours() || foe->GetPersonality().IsEscort());
		if(hasNemesis && !isPotentialNemesis)
			continue;
		if(!CanPursue(ship, *foe))
			continue;

		// Estimate the range a second from now, so ships prefer foes they are approaching.
		double range = (foe->Position() + 60. * foe->Velocity()).Distance(
			ship.Position() + 60. * ship.Velocity());
		// Prefer the previous target, or the parent's target, if they are nearby.
		if(foe == oldTarget.get() || foe == parentTarget.get())
			range -= 500.;

		// Unless this ship is "daring", it should not chase much stronger ships.
		if(maxStrength && range > 1000. && !foe->IsDisabled())
		{
			const auto otherStrengthIt = shipStrength.find(foe);
			if(otherStrengthIt != shipStrength.end() && otherStrengthIt->second > maxStrength)
				continue;
		}

		// Merciful ships do not attack any ships that are trying to escape.
		if(person.IsMerciful() && foe->IsFleeing())
			continue;

		// Ships which only disable never target already-disabled ships.
		if((person.Disables() || (!person.IsNemesis() && foe != oldTarget.get()))
				&& foe->IsDisabled() && (!canPlunder || Has(ship, foe->shared_from_this(), ShipEvent::BOARD)))
			continue;

		// Ships that don't (or can't) plunder strongly prefer active targets.
		if(!canPlunder)
			range += 5000. * foe->IsDisabled();
		// While those that do, do so only if no "live" enemies are nearby.
		else
			range += 2000. * (2 * foe->IsDisabled() - !Has(ship, foe->shared_from_this(), ShipEvent::BOARD));

		// Prefer to go after armed targets, especially if you're not a pirate.
		range += 1000. * (!IsArmed(*foe) * (1 + !person.Plunders()));
		// Targets which have plundered this ship's faction earn extra scorn.
		range -= 1000 * Has(*foe, gov, ShipEvent::BOARD);
		// Focus on nearly dead ships.
		range += 500. * (foe->Shields() + foe->Hull());
		// If a target is extremely overheated, focus on ships that can attack back.
		if(foe->IsOverheated())
			range += 3000. * (foe->Heat() - .9);
		if((isPotentialNemesis && !hasNemesis) || range < closest)
		{
			closest = range;
			target = foe->shared_from_this();
			hasNemesis = isPotentialNemesis;
		}
	}

	// With no hostile targets, NPCs with enforcement authority (and any
	// mission NPCs) should consider friendly targets for surveillance.
	if(!isYours && !target && (ship.IsSpecial() || scanPermissions.at(gov)))
		target = FindNonHostileTarget(ship);

	// Vindictive personalities without in-range hostile targets keep firing at an old
	// target (instead of perhaps moving about and finding one that is still alive).
	if(!target && person.IsVindictive())
	{
		target = ship.GetTargetShip();
		if(target && (target->IsCloaked() || target->GetSystem() != ship.GetSystem()))
			target.reset();
	}

	return target;
}



shared_ptr<Ship> AI::FindNonHostileTarget(const Ship &ship) const
{
	shared_ptr<Ship> target;

	// A ship may only make up to 6 successful scans (3 ships scanned if the ship
	// is using both scanners) and spend up to 2.5 minutes searching for scan targets.
	// After that, stop scanning targets. This is so that scanning ships in high spawn
	// rate systems don't build up over time, as they always have a new ship they
	// can try to scan.
	// Ships with the surveillance personality may make up to 12 successful scans and
	// spend 5 minutes searching.
	bool isSurveillance = ship.GetPersonality().IsSurveillance();
	int maxScanCount = isSurveillance ? 12 : 6;
	int searchTime = isSurveillance ? 9000 : 18000;
	// Ships will stop finding new targets to scan after the above scan time, but
	// may continue to pursue a target that they already started scanning for an
	// additional minute.
	int forfeitTime = searchTime + 3600;

	double cargoScan = ship.Attributes().Get("cargo scan power");
	double outfitScan = ship.Attributes().Get("outfit scan power");
	auto cargoScansIt = cargoScans.find(&ship);
	auto outfitScansIt = outfitScans.find(&ship);
	auto scanTimeIt = scanTime.find(&ship);
	int shipScanCount = cargoScansIt != cargoScans.end() ? cargoScansIt->second.size() : 0;
	shipScanCount += outfitScansIt != outfitScans.end() ? outfitScansIt->second.size() : 0;
	int shipScanTime = scanTimeIt != scanTime.end() ? scanTimeIt->second : 0;
	if((cargoScan || outfitScan) && shipScanCount < maxScanCount && shipScanTime < forfeitTime)
	{
		// If this ship already has a target, and is in the process of scanning it, prioritise that,
		// even if the scan time for this ship has exceeded 2.5 minutes.
		shared_ptr<Ship> oldTarget = ship.GetTargetShip();
		if(oldTarget && !oldTarget->IsTargetable())
			oldTarget.reset();
		if(oldTarget)
		{
			// If this ship started scanning this target then continue to scan it
			// unless it has traveled too far outside of the scan range. Surveillance
			// ships will continue to pursue targets regardless of range.
			bool cargoScanInProgress = ship.CargoScanFraction() > 0. && ship.CargoScanFraction() < 1.;
			bool outfitScanInProgress = ship.OutfitScanFraction() > 0. && ship.OutfitScanFraction() < 1.;
			// Divide the distance by 10,000 to normalize to the scan range that
			// scan power provides.
			double range = isSurveillance ? 0. : oldTarget->Position().DistanceSquared(ship.Position()) * .0001;
			if((cargoScanInProgress && range < 2. * cargoScan)
				|| (outfitScanInProgress && range < 2. * outfitScan))
				target = std::move(oldTarget);
		}
		else if(shipScanTime < searchTime)
		{
			// Don't try chasing targets that are too far away from this ship's scan range.
			// Surveillance ships will still prioritize nearby targets here, but if there
			// is no scan target nearby then they will pick a random target in the system
			// to pursue in DoSurveillance.
			double closest = max(cargoScan, outfitScan) * 2.;
			const Government *gov = ship.GetGovernment();
			for(const auto &it : GetShipsList(ship, false))
				if(it->GetGovernment() != gov)
				{
					auto ptr = it->shared_from_this();
					// Scan friendly ships that are as-yet unscanned by this ship's government.
					if((!cargoScan || Has(gov, ptr, ShipEvent::SCAN_CARGO))
							&& (!outfitScan || Has(gov, ptr, ShipEvent::SCAN_OUTFITS)))
						continue;

					// Divide the distance by 10,000 to normalize to the scan range that
					// scan power provides.
					double range = it->Position().DistanceSquared(ship.Position()) * .0001;
					if(range < closest)
					{
						closest = range;
						target = std::move(ptr);
					}
				}
		}
	}

	return target;
}



// Return a list of all targetable ships in the same system as the player that
// match the desired hostility (i.e. enemy or non-enemy). Does not consider the
// ship's current target, as its inclusion may or may not be desired.
vector<Ship *> AI::GetShipsList(const Ship &ship, bool targetEnemies, double maxRange) const
{
	if(maxRange < 0.)
		maxRange = numeric_limits<double>::infinity();

	auto targets = vector<Ship *>();

	// The cached lists are built each step based on the current ships in the player's system.
	const auto &rosters = targetEnemies ? enemyLists : allyLists;

	const auto it = rosters.find(ship.GetGovernment());
	if(it != rosters.end() && !it->second.empty())
	{
		targets.reserve(it->second.size());

		const System *here = ship.GetSystem();
		const Point &p = ship.Position();
		for(const auto &target : it->second)
			if(target->IsTargetable() && target->GetSystem() == here
					&& !(target->IsHyperspacing() && target->Velocity().Length() > 10.)
					&& p.Distance(target->Position()) < maxRange
					&& (ship.IsYours() || !target->GetPersonality().IsMarked())
					&& (target->IsYours() || !ship.GetPersonality().IsMarked()))
				targets.emplace_back(target);
	}

	return targets;
}



// TODO: This should be const when ships are not added and removed from formations in MoveInFormation
bool AI::FollowOrders(Ship &ship, Command &command)
{
	auto it = orders.find(&ship);
	if(it == orders.end())
		return false;

	const OrderSet &shipOrders = it->second;

	// Ships without an (alive) parent don't follow orders.
	shared_ptr<Ship> parent = ship.GetParent();
	if(!parent)
		return false;
	// If your parent is jumping or absent, that overrides your orders unless
	// your orders are to hold position.
	if(parent && !(shipOrders.Has(Orders::Types::HOLD_POSITION)
		|| shipOrders.Has(Orders::Types::HOLD_ACTIVE) || shipOrders.Has(Orders::Types::MOVE_TO)))
	{
		if(parent->GetSystem() != ship.GetSystem())
			return false;
		if(parent->Commands().Has(Command::JUMP) && ship.JumpsRemaining())
			return false;
	}
	// Do not keep chasing flotsam because another order was given.
	if(ship.GetTargetFlotsam()
		&& (!shipOrders.Has(Orders::Types::HARVEST) || (ship.CanBeCarried() && !ship.HasDeployOrder())))
	{
		ship.SetTargetFlotsam(nullptr);
		return false;
	}

	shared_ptr<Ship> target = shipOrders.GetTargetShip();
	shared_ptr<Minable> targetAsteroid = shipOrders.GetTargetAsteroid();
	const System *targetSystem = shipOrders.GetTargetSystem();
	const Point &targetPoint = shipOrders.GetTargetPoint();
	if(shipOrders.Has(Orders::Types::MOVE_TO) && targetSystem && ship.GetSystem() != targetSystem)
	{
		// The desired position is in a different system. Find the best
		// way to reach that system (via wormhole or jumping). This may
		// result in the ship landing to refuel.
		SelectRoute(ship, targetSystem);

		// Travel there even if your parent is not planning to travel.
		if((ship.GetTargetSystem() && ship.JumpsRemaining()) || ship.GetTargetStellar())
			MoveIndependent(ship, command);
		else
			return false;
	}
	else if((shipOrders.Has(Orders::Types::MOVE_TO) || shipOrders.Has(Orders::Types::HOLD_ACTIVE))
			&& ship.Position().Distance(targetPoint) > 20.)
		MoveTo(ship, command, targetPoint, Point(), 10., .1);
	else if(shipOrders.Has(Orders::Types::HOLD_POSITION) || shipOrders.Has(Orders::Types::HOLD_ACTIVE)
		|| shipOrders.Has(Orders::Types::MOVE_TO))
	{
		if(ship.Velocity().Length() > VELOCITY_ZERO || !ship.GetTargetShip())
			Stop(ship, command);
		else
		{
			command.SetTurn(TurnToward(ship, TargetAim(ship)));
			ship.SetVelocity({0., 0.});
		}
	}
	else if(shipOrders.Has(Orders::Types::MINE) && targetAsteroid)
	{
		ship.SetTargetAsteroid(targetAsteroid);
		// Escorts should chase the player-targeted asteroid.
		MoveToAttack(ship, command, *targetAsteroid);
	}
	else if(shipOrders.Has(Orders::Types::HARVEST))
	{
		if(DoHarvesting(ship, command))
		{
			ship.SetCommands(command);
			ship.SetCommands(firingCommands);
		}
		else
			return false;
	}
	else if(!target)
	{
		// Note: in AI::UpdateKeys() we already made sure that if a set of orders
		// has a target, the target is in-system and targetable. But, to be sure:
		return false;
	}
	else if(shipOrders.Has(Orders::Types::KEEP_STATION))
		KeepStation(ship, command, *target);
	else if(shipOrders.Has(Orders::Types::GATHER))
	{
		if(ship.GetFormationPattern())
			MoveInFormation(ship, command);
		else
			CircleAround(ship, command, *target);
	}
	else
		MoveIndependent(ship, command);

	return true;
}



void AI::MoveInFormation(Ship &ship, Command &command)
{
	shared_ptr<Ship> parent = ship.GetParent();
	if(!parent)
		return;

	const Body *formationLead = parent.get();
	const FormationPattern *pattern = ship.GetFormationPattern();

	// First we retrieve the patterns that are formed around the parent.
	auto &patterns = formations[formationLead];

	// Find the existing FormationPositioner for the pattern, or add one if none exists yet.
	auto insert = patterns.emplace(piecewise_construct,
		forward_as_tuple(pattern),
		forward_as_tuple(formationLead, pattern));

	// Set an iterator to point to the just found or emplaced value.
	auto it = insert.first;

	// Aggressively try to match the position and velocity for the formation position.
	const double POSITION_DEADBAND = ship.Radius() * 1.25;
	constexpr double VELOCITY_DEADBAND = .1;
	bool inPosition = MoveTo(ship, command, it->second.Position(&ship), formationLead->Velocity(), POSITION_DEADBAND,
		VELOCITY_DEADBAND);

	// If we match the position and velocity, then also match the facing angle within some limits.
	constexpr double FACING_TOLERANCE_DEGREES = 3;
	if(inPosition)
	{
		double facingDeltaDegrees = (formationLead->Facing() - ship.Facing()).Degrees();
		if(abs(facingDeltaDegrees) > FACING_TOLERANCE_DEGREES)
			command.SetTurn(facingDeltaDegrees);

		// If the position and velocity matches, smoothly match velocity over multiple frames.
		Point velocityDelta = formationLead->Velocity() - ship.Velocity();
		Point snapAcceleration = velocityDelta.Length() < VELOCITY_ZERO ? velocityDelta : velocityDelta.Unit() * .001;
		if((ship.Velocity() + snapAcceleration).Length() <= ship.MaxVelocity())
			ship.SetVelocity(ship.Velocity() + snapAcceleration);
	}
}



void AI::MoveIndependent(Ship &ship, Command &command) const
{
	double invisibleFenceRadius = ship.GetSystem()->InvisibleFenceRadius();

	shared_ptr<const Ship> target = ship.GetTargetShip();
	// NPCs should not be beyond the "fence" unless their target is
	// fairly close to it (or they are intended to be there).
	if(!ship.IsYours() && !ship.GetPersonality().IsUnconstrained())
	{
		if(target)
		{
			Point extrapolated = target->Position() + 120. * (target->Velocity() - ship.Velocity());
			if(extrapolated.Length() >= invisibleFenceRadius)
			{
				MoveTo(ship, command, Point(), Point(), 40., .8);
				if(ship.Velocity().Dot(ship.Position()) > 0.)
					command |= Command::FORWARD;
				return;
			}
		}
		else if(ship.Position().Length() >= invisibleFenceRadius)
		{
			// This ship should not be beyond the fence.
			MoveTo(ship, command, Point(), Point(), 40, .8);
			return;
		}
	}

	bool friendlyOverride = false;
	bool ignoreTargetShip = false;
	if(ship.IsYours())
	{
		auto it = orders.find(&ship);
		if(it != orders.end())
		{
			if(it->second.Has(Orders::Types::MOVE_TO))
				ignoreTargetShip = (ship.GetTargetSystem() && ship.JumpsRemaining()) || ship.GetTargetStellar();
			else if(it->second.Has(Orders::Types::ATTACK) || it->second.Has(Orders::Types::FINISH_OFF))
				friendlyOverride = it->second.GetTargetShip() == target;
		}
	}
	const Government *gov = ship.GetGovernment();
	if(ignoreTargetShip)
	{
		// Do not move to attack, scan, or assist the target ship.
	}
	else if(target && (gov->IsEnemy(target->GetGovernment()) || friendlyOverride))
	{
		bool shouldBoard = ship.Cargo().Free() && ship.GetPersonality().Plunders();
		bool hasBoarded = Has(ship, target, ShipEvent::BOARD);
		if(shouldBoard && target->IsDisabled() && !hasBoarded)
		{
			if(ship.IsBoarding())
				return;
			MoveTo(ship, command, target->Position(), target->Velocity(), 40., .8);
			command |= Command::BOARD;
		}
		else
			Attack(ship, command, *target);
		return;
	}
	else if(target)
	{
		// An AI ship that is targeting a non-hostile ship should scan it, or move on.
		bool cargoScan = ship.Attributes().Get("cargo scan power");
		bool outfitScan = ship.Attributes().Get("outfit scan power");
		// De-target if the target left my system.
		if(ship.GetSystem() != target->GetSystem())
		{
			target.reset();
			ship.SetTargetShip(nullptr);
		}
		// Detarget if I cannot scan, or if I already scanned the ship.
		else if((!cargoScan || Has(gov, target, ShipEvent::SCAN_CARGO))
				&& (!outfitScan || Has(gov, target, ShipEvent::SCAN_OUTFITS)))
		{
			target.reset();
			ship.SetTargetShip(nullptr);
		}
		// Move to (or near) the ship and scan it.
		else
		{
			if(target->Velocity().Length() > ship.MaxVelocity() * 0.9)
				CircleAround(ship, command, *target);
			else
				MoveTo(ship, command, target->Position(), target->Velocity(), 1., 1.);
			if(!ship.IsYours() && (ship.IsSpecial() || scanPermissions.at(gov)))
				command |= Command::SCAN;
			return;
		}
	}

	// A ship has restricted movement options if it is 'staying', 'lingering', or hostile to its parent.
	const bool shouldStay = StayOrLinger(ship);

	// Ships should choose a random system/planet for travel if they do not
	// already have a system/planet in mind, and are free to move about.
	const System *origin = ship.GetSystem();
	if(!ship.GetTargetSystem() && !ship.GetTargetStellar() && !shouldStay)
	{
		// TODO: This should probably be changed, because JumpsRemaining
		// does not return an accurate number.
		int jumps = ship.JumpsRemaining(false);
		// Each destination system has an average priority of 10.
		// If you only have one jump left, landing should be high priority.
		int planetWeight = jumps ? (1 + 40 / jumps) : 1;

		vector<int> systemWeights;
		int totalWeight = 0;
		const set<const System *> &links = ship.JumpNavigation().HasJumpDrive()
			? origin->JumpNeighbors(ship.JumpNavigation().JumpRange()) : origin->Links();
		if(jumps)
		{
			for(const System *link : links)
			{
				if(ship.IsRestrictedFrom(*link))
				{
					systemWeights.push_back(0);
					continue;
				}
				// Prefer systems in the direction we're facing.
				Point direction = link->Position() - origin->Position();
				int weight = static_cast<int>(
					11. + 10. * ship.Facing().Unit().Dot(direction.Unit()));

				systemWeights.push_back(weight);
				totalWeight += weight;
			}
		}
		int systemTotalWeight = totalWeight;

		// Anywhere you can land that has a port has the same weight. Ships will
		// not land anywhere without a port.
		vector<const StellarObject *> planets;
		for(const StellarObject &object : origin->Objects())
			if(object.HasSprite() && object.HasValidPlanet() && object.GetPlanet()->HasServices()
					&& object.GetPlanet()->CanLand(ship))
			{
				planets.push_back(&object);
				totalWeight += planetWeight;
			}
		// If there are no ports to land on and this ship cannot jump, consider
		// landing on uninhabited planets.
		if(!totalWeight)
			for(const StellarObject &object : origin->Objects())
				if(object.HasSprite() && object.HasValidPlanet() && object.GetPlanet()->CanLand(ship))
				{
					planets.push_back(&object);
					totalWeight += planetWeight;
				}
		if(!totalWeight)
		{
			// If there is nothing this ship can land on, have it just go to the
			// star and hover over it rather than drifting far away.
			if(origin->Objects().empty())
				return;
			totalWeight = 1;
			planets.push_back(&origin->Objects().front());
		}

		set<const System *>::const_iterator it = links.begin();
		int choice = Random::Int(totalWeight);
		if(choice < systemTotalWeight)
		{
			for(unsigned i = 0; i < systemWeights.size(); ++i, ++it)
			{
				choice -= systemWeights[i];
				if(choice < 0)
				{
					ship.SetTargetSystem(*it);
					break;
				}
			}
		}
		else
		{
			choice = (choice - systemTotalWeight) / planetWeight;
			ship.SetTargetStellar(planets[choice]);
		}
	}
	// Choose the best method of reaching the target system, which may mean
	// using a local wormhole rather than jumping. If this ship has chosen
	// to land, this decision will not be altered.
	SelectRoute(ship, ship.GetTargetSystem());

	if(ship.GetTargetSystem())
	{
		PrepareForHyperspace(ship, command);
		// Issuing the JUMP command prompts the escorts to get ready to jump.
		command |= Command::JUMP;
		// Issuing the WAIT command will prevent this parent from jumping.
		// When all its non-carried, in-system escorts that are not disabled and
		// have the ability to jump are ready, the WAIT command will be omitted.
		if(!EscortsReadyToJump(ship))
			command |= Command::WAIT;
	}
	else if(ship.GetTargetStellar())
	{
		MoveToPlanet(ship, command);
		if(!shouldStay && ship.Attributes().Get("fuel capacity") && ship.GetTargetStellar()->HasSprite()
				&& ship.GetTargetStellar()->GetPlanet() && ship.GetTargetStellar()->GetPlanet()->CanLand(ship))
			command |= Command::LAND;
		else if(ship.Position().Distance(ship.GetTargetStellar()->Position()) < 100.)
			ship.SetTargetStellar(nullptr);
	}
	else if(shouldStay && !ship.GetSystem()->Objects().empty())
	{
		unsigned i = Random::Int(origin->Objects().size());
		ship.SetTargetStellar(&origin->Objects()[i]);
	}
	// Nowhere to go, and nothing to do, so stay near the system center.
	else if(shouldStay)
		MoveTo(ship, command, Point(), Point(), 40, 0.8);
}



void AI::MoveWithParent(Ship &ship, Command &command, const Ship &parent)
{
	if(ship.GetFormationPattern())
		MoveInFormation(ship, command);
	else
		KeepStation(ship, command, parent);
}



// TODO: Function should be const, but formation flying needed write access to the FormationPositioner.
void AI::MoveEscort(Ship &ship, Command &command)
{
	const Ship &parent = *ship.GetParent();
	const System *currentSystem = ship.GetSystem();
	bool hasFuelCapacity = ship.Attributes().Get("fuel capacity");
	bool needsFuel = ship.NeedsFuel();
	bool isStaying = ship.GetPersonality().IsStaying() || !hasFuelCapacity;
	bool parentIsHere = (currentSystem == parent.GetSystem());
	// Check if the parent already landed, or has a target planet that is in the parent's system.
	const Planet *parentPlanet = (parent.GetPlanet() ? parent.GetPlanet() :
		(parent.GetTargetStellar() ? parent.GetTargetStellar()->GetPlanet() : nullptr));
	bool planetIsHere = (parentPlanet && parentPlanet->IsInSystem(parent.GetSystem()));
	bool systemHasFuel = hasFuelCapacity && currentSystem->HasFuelFor(ship);

	if(parent.Cloaking() == 1 && (ship.GetGovernment() != parent.GetGovernment()))
	{
		if(parent.GetGovernment() && parent.GetGovernment()->IsPlayer() &&
			ship.GetPersonality().IsEscort() && !ship.GetPersonality().IsUninterested())
		{
			// NPCs with the "escort" personality that are not uninterested
			// act as if they were escorts, following the cloaked flagship.
		}
		else
		{
			MoveIndependent(ship, command);
			return;
		}
	}

	// Non-staying escorts should route to their parent ship's system if not already in it.
	if(!parentIsHere && !isStaying)
	{
		if(ship.GetTargetStellar())
		{
			// An escort with an out-of-system parent only lands to
			// refuel or use a wormhole to route toward the parent.
			const Planet *targetPlanet = ship.GetTargetStellar()->GetPlanet();
			if(!targetPlanet || !targetPlanet->CanLand(ship)
					|| !ship.GetTargetStellar()->HasSprite()
					|| (!targetPlanet->IsWormhole() && ship.Fuel() == 1.))
				ship.SetTargetStellar(nullptr);
		}

		// If the ship has no destination or the destination is unreachable, route to the parent's system.
		if(!ship.GetTargetStellar() && (!ship.GetTargetSystem() || !ship.JumpNavigation().JumpFuel(ship.GetTargetSystem())))
		{
			// Route to the parent ship's system and check whether
			// the ship should land (refuel or wormhole) or jump.
			SelectRoute(ship, parent.GetSystem());
		}

		// Perform the action that this ship previously decided on.
		if(ship.GetTargetStellar())
		{
			MoveToPlanet(ship, command);
			command |= Command::LAND;
		}
		else if(ship.GetTargetSystem() && ship.JumpsRemaining())
		{
			PrepareForHyperspace(ship, command);
			command |= Command::JUMP;
			// If this ship is a parent to members of its fleet,
			// it should wait for them before jumping.
			if(!EscortsReadyToJump(ship))
				command |= Command::WAIT;
		}
		else if(systemHasFuel && ship.Fuel() < 1.)
			// Refuel so that when the parent returns, this ship is ready to rendezvous with it.
			Refuel(ship, command);
		else
			// This ship has no route to the parent's system, so park at the system's center.
			MoveTo(ship, command, Point(), Point(), 40., 0.1);
	}
	// If the parent is in-system and planning to jump, non-staying escorts should follow suit.
	else if(parent.Commands().Has(Command::JUMP) && parent.GetTargetSystem() && !isStaying)
	{
		if(parent.GetTargetSystem() != ship.GetTargetSystem())
			SelectRoute(ship, parent.GetTargetSystem());

		if(ship.GetTargetSystem())
		{
			PrepareForHyperspace(ship, command);
			command |= Command::JUMP;
			if(!(parent.IsEnteringHyperspace() || parent.IsReadyToJump()) || !EscortsReadyToJump(ship))
				command |= Command::WAIT;
		}
		else if(needsFuel && systemHasFuel)
			Refuel(ship, command);
		else if(ship.GetTargetStellar())
		{
			MoveToPlanet(ship, command);
			if(parent.IsEnteringHyperspace())
				command |= Command::LAND;
		}
		else if(needsFuel)
			// Return to the system center to maximize solar collection rate.
			MoveTo(ship, command, Point(), Point(), 40., 0.1);
		else
			// This ship has no route to the parent's destination system, so protect it until it jumps away.
			KeepStation(ship, command, parent);
	}
	// If an escort is out of fuel, they should refuel without waiting for the
	// "parent" to land (because the parent may not be planning on landing).
	else if(systemHasFuel && needsFuel)
		Refuel(ship, command);
	else if((parent.Commands().Has(Command::LAND) || parent.IsLanding()) && parentIsHere && planetIsHere)
	{
		if(parentPlanet->CanLand(ship))
		{
			ship.SetTargetSystem(nullptr);
			ship.SetTargetStellar(parent.GetTargetStellar());
			if(parent.IsLanding())
			{
				MoveToPlanet(ship, command);
				command |= Command::LAND;
			}
			else
				MoveWithParent(ship, command, parent);
		}
		else if(parentPlanet->IsWormhole())
		{
			const auto *wormhole = parentPlanet->GetWormhole();
			SelectRoute(ship, &wormhole->WormholeDestination(*currentSystem));

			if(ship.GetTargetSystem())
			{
				PrepareForHyperspace(ship, command);
				if(parent.IsLanding())
					command |= Command::JUMP;
			}
			else if(ship.GetTargetStellar())
			{
				MoveToPlanet(ship, command);
				if(parent.IsLanding())
					command |= Command::LAND;
			}
			else if(needsFuel)
				// Return to the system center to maximize solar collection rate.
				MoveTo(ship, command, Point(), Point(), 40., 0.1);
			else
				// This ship has no route to the parent's destination system, so protect it until it jumps away.
				MoveWithParent(ship, command, parent);
		}
		else
			MoveWithParent(ship, command, parent);
	}
	else if(parent.Commands().Has(Command::BOARD) && parent.GetTargetShip().get() == &ship)
		Stop(ship, command, .2);
	else
		MoveWithParent(ship, command, parent);
}



// Prefer your parent's target planet for refueling, but if it and your current
// target planet can't fuel you, try to find one that can.
void AI::Refuel(Ship &ship, Command &command)
{
	const StellarObject *parentTarget = (ship.GetParent() ? ship.GetParent()->GetTargetStellar() : nullptr);
	if(CanRefuel(ship, parentTarget))
		ship.SetTargetStellar(parentTarget);
	else if(!CanRefuel(ship, ship.GetTargetStellar()))
		ship.SetTargetStellar(FindLandingLocation(ship));

	if(ship.GetTargetStellar())
	{
		MoveToPlanet(ship, command);
		command |= Command::LAND;
	}
}



bool AI::CanRefuel(const Ship &ship, const StellarObject *target)
{
	if(!target)
		return false;

	const Planet *planet = target->GetPlanet();
	if(!planet)
		return false;

	if(!planet->IsInSystem(ship.GetSystem()))
		return false;

	if(!planet->HasFuelFor(ship))
		return false;

	return true;
}



// Set the ship's target system or planet in order to reach the
// next desired system. Will target a landable planet to refuel.
// If the ship is an escort it will only use routes known to the player.
void AI::SelectRoute(Ship &ship, const System *targetSystem) const
{
	const System *from = ship.GetSystem();
	if(from == targetSystem || !targetSystem)
		return;
	RoutePlan route(ship, *targetSystem, ship.IsYours() ? &player : nullptr);
	if(ShouldRefuel(ship, route))
	{
		// There is at least one planet that can refuel the ship.
		ship.SetTargetStellar(AI::FindLandingLocation(ship));
		return;
	}
	const System *nextSystem = route.FirstStep();
	// The destination may be accessible by both jump and wormhole.
	// Prefer wormhole travel in these cases, to conserve fuel.
	if(nextSystem)
		for(const StellarObject &object : from->Objects())
		{
			if(!object.HasSprite() || !object.HasValidPlanet())
				continue;

			const Planet &planet = *object.GetPlanet();
			if(planet.IsWormhole() && planet.IsAccessible(&ship)
				&& &planet.GetWormhole()->WormholeDestination(*from) == nextSystem)
			{
				ship.SetTargetStellar(&object);
				ship.SetTargetSystem(nullptr);
				return;
			}
		}
	// Either there is no viable wormhole route to this system, or
	// the target system cannot be reached.
	ship.SetTargetSystem(nextSystem);
	ship.SetTargetStellar(nullptr);
}



// Determine if a carried ship meets any of the criteria for returning to its parent.
bool AI::ShouldDock(const Ship &ship, const Ship &parent, const System *playerSystem) const
{
	// If your parent is disabled, you should not attempt to board it.
	// (Doing so during combat will likely lead to its destruction.)
	if(parent.IsDisabled())
		return false;

	// A player-owned carried ship should return to its carrier when the player
	// has ordered it to "no longer deploy" or when it is not in the current system.
	// A non-player-owned carried ship should retreat if its parent is calling it back.
	if(ship.IsYours())
	{
		if(!ship.HasDeployOrder() || ship.GetSystem() != playerSystem)
			return true;
	}
	else if(!parent.Commands().Has(Command::DEPLOY))
		return true;

	// If a carried ship has repair abilities, avoid having it get stuck oscillating between
	// retreating and attacking when at exactly 50% health by adding hysteresis to the check.
	double minHealth = RETREAT_HEALTH + .25 + .25 * !ship.Commands().Has(Command::DEPLOY);
	if(ship.Health() < minHealth && (!ship.IsYours() || Preferences::Has("Damaged fighters retreat")))
		return true;

	// If a fighter is armed with only ammo-using weapons, but no longer has the ammunition
	// needed to use them, it should dock if the parent can supply that ammo.
	auto requiredAmmo = set<const Outfit *>{};
	for(const Hardpoint &hardpoint : ship.Weapons())
	{
		const Weapon *weapon = hardpoint.GetOutfit();
		if(weapon && !hardpoint.IsSpecial())
		{
			const Outfit *ammo = weapon->Ammo();
			if(!ammo || ship.OutfitCount(ammo))
			{
				// This fighter has at least one usable weapon, and
				// thus does not need to dock to continue fighting.
				requiredAmmo.clear();
				break;
			}
			else if(parent.OutfitCount(ammo))
				requiredAmmo.insert(ammo);
		}
	}
	if(!requiredAmmo.empty())
		return true;

	// If a carried ship has fuel capacity but is very low, it should return if
	// the parent can refuel it.
	double maxFuel = ship.Attributes().Get("fuel capacity");
	if(maxFuel && ship.Fuel() < .005 && parent.JumpNavigation().JumpFuel() < parent.Fuel() *
			parent.Attributes().Get("fuel capacity") - maxFuel)
		return true;

	// NPC ships should always transfer cargo. Player ships should only
	// transfer cargo if the player has the AI preference set for it.
	if(!ship.IsYours() || Preferences::Has("Fighters transfer cargo"))
	{
		// If an out-of-combat carried ship is carrying a significant cargo
		// load and can transfer some of it to the parent, it should do so.
		bool hasEnemy = ship.GetTargetShip() && ship.GetTargetShip()->GetGovernment()->IsEnemy(ship.GetGovernment());
		if(!hasEnemy && parent.Cargo().Free())
		{
			const CargoHold &cargo = ship.Cargo();
			// Mining ships only mine while they have 5 or more free space. While mining, carried ships
			// do not consider docking unless their parent is far from a targetable asteroid.
			if(!cargo.IsEmpty() && cargo.Size() && cargo.Free() < 5)
				return true;
		}
	}

	return false;
}



double AI::TurnBackward(const Ship &ship)
{
	return TurnToward(ship, -ship.Velocity());
}



// Determine the value to use in Command::SetTurn() to turn the ship towards the desired facing.
// "precision" is an optional argument corresponding to a value of the dot product of the current and target facing
// vectors above which no turning should be attempting, to reduce constant, minute corrections.
double AI::TurnToward(const Ship &ship, const Point &vector, const double precision)
{
	Point facing = ship.Facing().Unit();
	double cross = vector.Cross(facing);

	double dot = vector.Dot(facing);
	if(dot > 0.)
	{
		// Is the facing direction aligned with the target direction with sufficient precision?
		// The maximum angle between the two directions is given by: arccos(sqrt(precision)).
		bool close = false;
		if(precision < 1. && precision > 0. && dot * dot >= precision * vector.LengthSquared())
			close = true;
		double angle = asin(min(1., max(-1., cross / vector.Length()))) * TO_DEG;
		// Is the angle between the facing and target direction smaller than
		// the angle the ship can turn through in one step?
		if(fabs(angle) < ship.TurnRate())
		{
			// If the ship is within one step of the target direction,
			// and the facing is already sufficiently aligned with the target direction,
			// don't turn any further.
			if(close)
				return 0.;
			return -angle / ship.TurnRate();
		}
	}

	bool left = cross < 0.;
	return left - !left;
}



bool AI::MoveToPlanet(const Ship &ship, Command &command, double cruiseSpeed)
{
	if(!ship.GetTargetStellar())
		return false;

	const Point &target = ship.GetTargetStellar()->Position();
	return MoveTo(ship, command, target, Point(), ship.GetTargetStellar()->Radius(), 1., cruiseSpeed);
}



// Instead of moving to a point with a fixed location, move to a moving point (Ship = position + velocity)
bool AI::MoveTo(const Ship &ship, Command &command, const Point &targetPosition,
	const Point &targetVelocity, double radius, double slow, double cruiseSpeed)
{
	const Point &position = ship.Position();
	const Point &velocity = ship.Velocity();
	const Angle &angle = ship.Facing();
	Point dp = targetPosition - position;
	Point dv = targetVelocity - velocity;

	double speed = dv.Length();

	bool isClose = (dp.Length() < radius);
	if(isClose && speed < slow)
		return true;

	bool shouldReverse = false;
	dp = targetPosition - StoppingPoint(ship, targetVelocity, shouldReverse);

	// Calculate target vector required to get where we want to be.
	Point tv = dp;
	bool hasCruiseSpeed = (cruiseSpeed > 0.);
	if(hasCruiseSpeed)
	{
		// The ship prefers a velocity at cruise-speed towards the target, so we need
		// to compare this preferred velocity to the current velocity and apply the
		// delta to get to the preferred velocity.
		tv = (dp.Unit() * cruiseSpeed) - velocity;
		// If we are moving close to our preferred velocity, then face towards the target.
		if(tv.LengthSquared() < .01)
			tv = dp;
	}

	bool isFacing = (tv.Unit().Dot(angle.Unit()) > .95);
	if(!isClose || (!isFacing && !shouldReverse))
		command.SetTurn(TurnToward(ship, tv));

	// Drag is not applied when not thrusting, so stop thrusting when close to max speed
	// to save energy. Work with a slightly lower maximum velocity to avoid border cases.
	// In order for a ship to use their afterburner, they must also have the forward
	// command active. Therefore, if this ship should use its afterburner, use the
	// max velocity with afterburner thrust included.
	double maxVelocity = ship.MaxVelocity(ShouldUseAfterburner(ship)) * .99;
	if(isFacing && (velocity.LengthSquared() <= maxVelocity * maxVelocity
			|| dp.Unit().Dot(velocity.Unit()) < .95))
	{
		// We set full forward power when we don't have a cruise-speed, when we are below
		// cruise-speed or when we need to do course corrections.
		bool movingTowardsTarget = (velocity.Unit().Dot(dp.Unit()) > .95);
		if(!hasCruiseSpeed || !movingTowardsTarget || velocity.Length() < cruiseSpeed)
			command |= Command::FORWARD;
	}
	else if(shouldReverse)
	{
		command.SetTurn(TurnToward(ship, velocity));
		command |= Command::BACK;
	}

	return false;
}



bool AI::Stop(const Ship &ship, Command &command, double maxSpeed, const Point &direction)
{
	const Point &velocity = ship.Velocity();
	const Angle &angle = ship.Facing();

	double speed = velocity.Length();

	// If asked for a complete stop, the ship needs to be going much slower.
	if(speed <= (maxSpeed ? maxSpeed : VELOCITY_ZERO))
		return true;
	if(!maxSpeed)
		command |= Command::STOP;

	// If you're moving slow enough that one frame of acceleration could bring
	// you to a stop, make sure you're pointed perfectly in the right direction.
	// This is a fudge factor for how straight you must be facing: it increases
	// from 0.8 when it will take many frames to stop, to nearly 1 when it will
	// take less than 1 frame to stop.
	double stopTime = speed / ship.Acceleration();
	double limit = .8 + .2 / (1. + stopTime * stopTime * stopTime * .001);

	// If you have a reverse thruster, figure out whether using it is faster
	// than turning around and using your main thruster.
	if(ship.Attributes().Get("reverse thrust"))
	{
		// Figure out your stopping time using your main engine:
		double degreesToTurn = TO_DEG * acos(min(1., max(-1., -velocity.Unit().Dot(angle.Unit()))));
		double forwardTime = degreesToTurn / ship.TurnRate();
		forwardTime += stopTime;

		// Figure out your reverse thruster stopping time:
		double reverseTime = (180. - degreesToTurn) / ship.TurnRate();
		reverseTime += speed / ship.ReverseAcceleration();

		// If you want to end up facing a specific direction, add the extra turning time.
		if(direction)
		{
			// Time to turn from facing backwards to target:
			double degreesFromBackwards = TO_DEG * acos(min(1., max(-1., direction.Unit().Dot(-velocity.Unit()))));
			double turnFromBackwardsTime = degreesFromBackwards / ship.TurnRate();
			forwardTime += turnFromBackwardsTime;

			// Time to turn from facing forwards to target:
			double degreesFromForward = TO_DEG * acos(min(1., max(-1., direction.Unit().Dot(angle.Unit()))));
			double turnFromForwardTime = degreesFromForward / ship.TurnRate();
			reverseTime += turnFromForwardTime;
		}

		if(reverseTime < forwardTime)
		{
			command.SetTurn(TurnToward(ship, velocity));
			if(velocity.Unit().Dot(angle.Unit()) > limit)
				command |= Command::BACK;
			return false;
		}
	}

	command.SetTurn(TurnBackward(ship));
	if(velocity.Unit().Dot(angle.Unit()) < -limit)
		command |= Command::FORWARD;

	return false;
}



void AI::PrepareForHyperspace(const Ship &ship, Command &command)
{
	bool hasHyperdrive = ship.JumpNavigation().HasHyperdrive();
	double scramThreshold = ship.Attributes().Get("scram drive");
	bool hasJumpDrive = ship.JumpNavigation().HasJumpDrive();
	if(!hasHyperdrive && !hasJumpDrive)
		return;

	bool isJump = (ship.JumpNavigation().GetCheapestJumpType(ship.GetTargetSystem()).first == JumpType::JUMP_DRIVE);

	Point direction = ship.GetTargetSystem()->Position() - ship.GetSystem()->Position();
	double departure = isJump ?
		ship.GetSystem()->JumpDepartureDistance() :
		ship.GetSystem()->HyperDepartureDistance();
	double squaredDeparture = departure * departure + SAFETY_OFFSET;
	if(ship.Position().LengthSquared() < squaredDeparture)
	{
		Point closestDeparturePoint = ship.Position().Unit() * (departure + SAFETY_OFFSET);
		MoveTo(ship, command, closestDeparturePoint, Point(), 0., 0.);
	}
	else if(!isJump && scramThreshold)
	{
		direction = direction.Unit();
		Point normal(-direction.Y(), direction.X());

		double deviation = ship.Velocity().Dot(normal);
		if(fabs(deviation) > scramThreshold)
		{
			// Need to maneuver; not ready to jump
			if((ship.Facing().Unit().Dot(normal) < 0) == (deviation < 0))
				// Thrusting from this angle is counterproductive
				direction = -deviation * normal;
			else
			{
				command |= Command::FORWARD;

				// How much correction will be applied to deviation by thrusting
				// as I turn back toward the jump direction.
				double turnRateRadians = ship.TurnRate() * TO_RAD;
				double cos = ship.Facing().Unit().Dot(direction);
				// integral(t*sin(r*x), angle/r, 0) = t/r * (1 - cos(angle)), so:
				double correctionWhileTurning = fabs(1 - cos) * ship.Acceleration() / turnRateRadians;
				// (Note that this will always underestimate because thrust happens before turn)

				if(fabs(deviation) - correctionWhileTurning > scramThreshold)
					// Want to thrust from an even sharper angle
					direction = -deviation * normal;
			}
		}
		command.SetTurn(TurnToward(ship, direction));
	}
	// If we're a jump drive, just stop.
	else if(isJump)
		Stop(ship, command, ship.Attributes().Get("jump speed"));
	// Else stop in the fastest way to end facing in the right direction
	else if(Stop(ship, command, ship.Attributes().Get("jump speed"), direction))
		command.SetTurn(TurnToward(ship, direction));
}



void AI::CircleAround(const Ship &ship, Command &command, const Body &target)
{
	Point direction = target.Position() - ship.Position();
	command.SetTurn(TurnToward(ship, direction));

	double length = direction.Length();
	if(length > 200. && ship.Facing().Unit().Dot(direction) >= 0.)
	{
		command |= Command::FORWARD;

		// If the ship is far away enough the ship should use the afterburner.
		if(length > 750. && ShouldUseAfterburner(ship))
			command |= Command::AFTERBURNER;
	}
}



void AI::Swarm(const Ship &ship, Command &command, const Body &target)
{
	Point direction = target.Position() - ship.Position();
	double maxSpeed = ship.MaxVelocity();
	double rendezvousTime = RendezvousTime(direction, target.Velocity(), maxSpeed);
	if(std::isnan(rendezvousTime) || rendezvousTime > 600.)
		rendezvousTime = 600.;
	direction += rendezvousTime * target.Velocity();
	MoveTo(ship, command, target.Position() + direction, .5 * maxSpeed * direction.Unit(), 50., 2.);
}



void AI::KeepStation(const Ship &ship, Command &command, const Body &target)
{
	// Constants:
	static const double MAX_TIME = 600.;
	static const double LEAD_TIME = 500.;
	static const double POSITION_DEADBAND = 200.;
	static const double VELOCITY_DEADBAND = 1.5;
	static const double TIME_DEADBAND = 120.;
	static const double THRUST_DEADBAND = .5;

	// Current properties of the two ships:
	double maxV = ship.MaxVelocity();
	double accel = ship.Acceleration();
	double turn = ship.TurnRate();
	double mass = ship.InertialMass();
	Point unit = ship.Facing().Unit();
	double currentAngle = ship.Facing().Degrees();
	// This is where we want to be relative to where we are now:
	Point velocityDelta = target.Velocity() - ship.Velocity();
	Point positionDelta = target.Position() + LEAD_TIME * velocityDelta - ship.Position();
	double positionSize = positionDelta.Length();
	double positionWeight = positionSize / (positionSize + POSITION_DEADBAND);
	// This is how fast we want to be going relative to how fast we're going now:
	velocityDelta -= unit * VELOCITY_DEADBAND;
	double velocitySize = velocityDelta.Length();
	double velocityWeight = velocitySize / (velocitySize + VELOCITY_DEADBAND);

	// Time it will take (roughly) to move to the target ship:
	double positionTime = RendezvousTime(positionDelta, target.Velocity(), maxV);
	if(std::isnan(positionTime) || positionTime > MAX_TIME)
		positionTime = MAX_TIME;
	Point rendezvous = positionDelta + target.Velocity() * positionTime;
	double positionAngle = Angle(rendezvous).Degrees();
	positionTime += AngleDiff(currentAngle, positionAngle) / turn;
	positionTime += (rendezvous.Unit() * maxV - ship.Velocity()).Length() / accel;
	// If you are very close, stop trying to adjust:
	positionTime *= positionWeight * positionWeight;

	// Time it will take (roughly) to adjust your velocity to match the target:
	double velocityTime = velocityDelta.Length() / accel;
	double velocityAngle = Angle(velocityDelta).Degrees();
	velocityTime += AngleDiff(currentAngle, velocityAngle) / turn;
	// If you are very close, stop trying to adjust:
	velocityTime *= velocityWeight * velocityWeight;

	// Focus on matching position or velocity depending on which will take longer.
	double totalTime = positionTime + velocityTime + TIME_DEADBAND;
	positionWeight = positionTime / totalTime;
	velocityWeight = velocityTime / totalTime;
	double facingWeight = TIME_DEADBAND / totalTime;

	// Determine the angle we want to face, interpolating smoothly between three options.
	Point facingGoal = rendezvous.Unit() * positionWeight
		+ velocityDelta.Unit() * velocityWeight
		+ target.Facing().Unit() * facingWeight;
	double targetAngle = Angle(facingGoal).Degrees() - currentAngle;
	if(abs(targetAngle) > 180.)
		targetAngle += (targetAngle < 0. ? 360. : -360.);
	// Avoid "turn jitter" when position & velocity are well-matched.
	bool changedDirection = (signbit(ship.Commands().Turn()) != signbit(targetAngle));
	double targetTurn = abs(targetAngle / turn);
	double lastTurn = abs(ship.Commands().Turn());
	if(lastTurn && (changedDirection || (lastTurn < 1. && targetTurn > lastTurn)))
	{
		// Keep the desired turn direction, but damp the per-frame turn rate increase.
		double dampedTurn = (changedDirection ? 0. : lastTurn) + min(.025, targetTurn);
		command.SetTurn(copysign(dampedTurn, targetAngle));
	}
	else if(targetTurn < 1.)
		command.SetTurn(copysign(targetTurn, targetAngle));
	else
		command.SetTurn(targetAngle);

	// Determine whether to apply thrust.
	Point drag = ship.Velocity() * ship.DragForce();
	if(ship.Attributes().Get("reverse thrust"))
	{
		// Don't take drag into account when reverse thrusting, because this
		// estimate of how it will be applied can be quite inaccurate.
		Point a = (unit * (-ship.Attributes().Get("reverse thrust") / mass)).Unit();
		double direction = positionWeight * positionDelta.Dot(a) / POSITION_DEADBAND
			+ velocityWeight * velocityDelta.Dot(a) / VELOCITY_DEADBAND;
		if(direction > THRUST_DEADBAND)
		{
			command |= Command::BACK;
			return;
		}
	}
	Point a = (unit * accel - drag).Unit();
	double direction = positionWeight * positionDelta.Dot(a) / POSITION_DEADBAND
		+ velocityWeight * velocityDelta.Dot(a) / VELOCITY_DEADBAND;
	if(direction > THRUST_DEADBAND)
		command |= Command::FORWARD;
}



void AI::Attack(const Ship &ship, Command &command, const Ship &target)
{
	// Deploy any fighters you are carrying.
	if(!ship.IsYours() && ship.HasBays())
	{
		command |= Command::DEPLOY;
		Deploy(ship, false);
	}
	// Ramming AI doesn't take weapon range or self-damage into account, instead opting to bum-rush the target.
	if(ship.GetPersonality().IsRamming())
	{
		MoveToAttack(ship, command, target);
		return;
	}

	// Check if this ship is fast enough to keep distance from target.
	// Have a 10% minimum to avoid ships getting in a chase loop.
	const bool isAbleToRun = target.MaxVelocity() * SAFETY_MULTIPLIER < ship.MaxVelocity();

	const ShipAICache &shipAICache = ship.GetAICache();
	const bool useArtilleryAI = shipAICache.IsArtilleryAI() && isAbleToRun;
	const double shortestRange = shipAICache.ShortestRange();
	const double shortestArtillery = shipAICache.ShortestArtillery();
	double minSafeDistance = isAbleToRun ? shipAICache.MinSafeDistance() : 0.;

	const double totalRadius = ship.Radius() + target.Radius();
	const Point direction = target.Position() - ship.Position();
	// Average distance from this ship's weapons to the enemy ship.
	const double weaponDistanceFromTarget = direction.Length() - totalRadius / 3.;

	// If this ship has mostly long-range weapons, or some weapons have a
	// blast radius, it should keep some distance instead of closing in.
	// If a weapon has blast radius, some leeway helps avoid getting hurt.
	if(minSafeDistance || (useArtilleryAI && shortestRange < weaponDistanceFromTarget))
	{
		minSafeDistance = 1.25 * minSafeDistance + totalRadius;

		double approachSpeed = (ship.Velocity() - target.Velocity()).Dot(direction.Unit());
		double slowdownDistance = 0.;
		// If this ship can use reverse thrusters, consider doing so.
		double reverseSpeed = ship.MaxReverseVelocity();
		bool useReverse = reverseSpeed && (reverseSpeed >= min(target.MaxVelocity(), ship.MaxVelocity())
				|| target.Velocity().Dot(-direction.Unit()) <= reverseSpeed);
		slowdownDistance = approachSpeed * approachSpeed / (useReverse ?
			ship.ReverseAcceleration() : (ship.Acceleration() + 160. / ship.TurnRate())) / 2.;

		// If we're too close, run away.
		if(direction.Length() <
				max(minSafeDistance + max(slowdownDistance, 0.), useArtilleryAI * .75 * shortestArtillery))
		{
			if(useReverse)
			{
				command.SetTurn(TurnToward(ship, direction));
				if(ship.Facing().Unit().Dot(direction) >= 0.)
					command |= Command::BACK;
			}
			else
			{
				command.SetTurn(TurnToward(ship, -direction));
				if(ship.Facing().Unit().Dot(direction) <= 0.)
					command |= Command::FORWARD;
			}
		}
		else
		{
			// This isn't perfect, but it works well enough.
			if((useArtilleryAI && (approachSpeed > 0. && weaponDistanceFromTarget < shortestArtillery * .9)) ||
					weaponDistanceFromTarget < shortestRange * .75)
				AimToAttack(ship, command, target);
			else
				MoveToAttack(ship, command, target);
		}
	}
	// Fire if we can or move closer to use all weapons.
	else
		if(weaponDistanceFromTarget < shortestRange * .75)
			AimToAttack(ship, command, target);
		else
			MoveToAttack(ship, command, target);
}



void AI::AimToAttack(const Ship &ship, Command &command, const Body &target)
{
	command.SetTurn(TurnToward(ship, TargetAim(ship, target)));
}



void AI::MoveToAttack(const Ship &ship, Command &command, const Body &target)
{
	Point direction = target.Position() - ship.Position();

	// First of all, aim in the direction that will hit this target.
	AimToAttack(ship, command, target);

	// Calculate this ship's "turning radius"; that is, the smallest circle it
	// can make while at its current speed.
	double stepsInFullTurn = 360. / ship.TurnRate();
	double circumference = stepsInFullTurn * ship.Velocity().Length();
	double diameter = max(200., circumference / PI);

	const auto facing = ship.Facing().Unit().Dot(direction.Unit());
	// If the ship has reverse thrusters and the target is behind it, we can
	// use them to reach the target more quickly.
	if(facing < -.75 && ship.Attributes().Get("reverse thrust"))
		command |= Command::BACK;
	// Only apply thrust if either:
	// This ship is within 90 degrees of facing towards its target and far enough away not to overshoot
	// if it accelerates while needing to turn further, or:
	// This ship is moving away from its target but facing mostly towards it.
	else if((facing >= 0. && direction.Length() > diameter)
			|| (ship.Velocity().Dot(direction) < 0. && facing >= .9))
	{
		command |= Command::FORWARD;
		// Use afterburner, if applicable.
		if(direction.Length() > 600. && ShouldUseAfterburner(ship))
			command |= Command::AFTERBURNER;
	}
}



void AI::PickUp(const Ship &ship, Command &command, const Body &target)
{
	// Figure out the target's velocity relative to the ship.
	Point p = target.Position() - ship.Position();
	Point v = target.Velocity() - ship.Velocity();
	double vMax = ship.MaxVelocity();

	// Estimate where the target will be by the time we reach it.
	double time = RendezvousTime(p, v, vMax);
	if(std::isnan(time))
		time = p.Length() / vMax;
	double degreesToTurn = TO_DEG * acos(min(1., max(-1., p.Unit().Dot(ship.Facing().Unit()))));
	time += degreesToTurn / ship.TurnRate();
	p += v * time;

	// Move toward the target.
	command.SetTurn(TurnToward(ship, p));
	double dp = p.Unit().Dot(ship.Facing().Unit());
	if(dp > .7)
		command |= Command::FORWARD;

	// Use the afterburner if it will not cause you to miss your target.
	double squareDistance = p.LengthSquared();
	if(command.Has(Command::FORWARD) && ShouldUseAfterburner(ship))
		if(dp > max(.9, min(.9999, 1. - squareDistance / 10000000.)))
			command |= Command::AFTERBURNER;
}



// Determine if using an afterburner does not use up reserve fuel, cause undue
// energy strain, or undue thermal loads if almost overheated.
bool AI::ShouldUseAfterburner(const Ship &ship)
{
	if(!ship.Attributes().Get("afterburner thrust"))
		return false;

	double fuel = ship.Fuel() * ship.Attributes().Get("fuel capacity");
	double neededFuel = ship.Attributes().Get("afterburner fuel");
	double energy = ship.Energy() * ship.Attributes().Get("energy capacity");
	double neededEnergy = ship.Attributes().Get("afterburner energy");
	if(energy == 0.)
		energy = ship.Attributes().Get("energy generation")
				+ 0.2 * ship.Attributes().Get("solar collection")
				- ship.Attributes().Get("energy consumption");
	double outputHeat = ship.Attributes().Get("afterburner heat") / (100 * ship.Mass());
	if((!neededFuel || fuel - neededFuel > ship.JumpNavigation().JumpFuel())
			&& (!neededEnergy || neededEnergy / energy < 0.25)
			&& (!outputHeat || ship.Heat() + outputHeat < .9))
		return true;

	return false;
}



// "Appeasing" ships will dump cargo after being injured, if they are being targeted.
void AI::DoAppeasing(const shared_ptr<Ship> &ship, double *threshold) const
{
	double health = .5 * ship->Shields() + ship->Hull();
	if(1. - health <= *threshold)
		return;

	const auto enemies = GetShipsList(*ship, true);
	if(none_of(enemies.begin(), enemies.end(), [&ship](const Ship *foe) noexcept -> bool
			{ return !foe->IsDisabled() && foe->GetTargetShip() == ship; }))
		return;

	int toDump = 11 + (1. - health) * .5 * ship->Cargo().Size();
	for(auto &&commodity : ship->Cargo().Commodities())
		if(commodity.second && toDump > 0)
		{
			int dumped = min(commodity.second, toDump);
			ship->Jettison(commodity.first, dumped, true);
			toDump -= dumped;
		}

	*threshold = (1. - health) + .1;

	if(ship->GetPersonality().IsMute())
		return;
	const Government *government = ship->GetGovernment();
	const string &language = government->Language();
	if(language.empty() || player.Conditions().Get("language: " + language))
		Messages::Add(government->DisplayName() + " " + ship->Noun() + " \"" + ship->GivenName()
			+ "\": Please, just take my cargo and leave me alone.", Messages::Importance::Low);

}



// Find a target ship to flock around at high speed.
void AI::DoSwarming(Ship &ship, Command &command, shared_ptr<Ship> &target)
{
	// Find a new ship to target on average every 10 seconds, or if the current target
	// is no longer eligible. If landing, release the old target so others can swarm it.
	if(ship.IsLanding() || !target || !CanSwarm(ship, *target) || !Random::Int(600))
	{
		if(target)
		{
			// Allow another swarming ship to consider the target.
			auto sit = swarmCount.find(target.get());
			if(sit != swarmCount.end() && sit->second > 0)
				--sit->second;
			// Release the current target.
			target.reset();
			ship.SetTargetShip(target);
		}
		// If here just because we are about to land, do not seek a new target.
		if(ship.IsLanding())
			return;

		int lowestCount = 7;
		// Consider swarming around non-hostile ships in the same system.
		const auto others = GetShipsList(ship, false);
		for(auto *other : others)
			if(!other->GetPersonality().IsSwarming())
			{
				// Prefer to swarm ships that are not already being heavily swarmed.
				int count = swarmCount[other] + Random::Int(4);
				if(count < lowestCount)
				{
					target = other->shared_from_this();
					lowestCount = count;
				}
			}
		ship.SetTargetShip(target);
		if(target)
			++swarmCount[target.get()];
	}
	// If a friendly ship to flock with was not found, return to an available planet.
	if(target)
		Swarm(ship, command, *target);
	else if(ship.Zoom() == 1.)
		Refuel(ship, command);
}



void AI::DoSurveillance(Ship &ship, Command &command, shared_ptr<Ship> &target) const
{
	const bool isStaying = ship.GetPersonality().IsStaying();
	// Since DoSurveillance is called after target-seeking and firing, if this
	// ship has a target, that target is guaranteed to be targetable.
	if(target && (target->GetSystem() != ship.GetSystem() || target->IsEnteringHyperspace()))
	{
		target.reset();
		ship.SetTargetShip(target);
	}
	// If you have a hostile target, pursuing and destroying it has priority.
	if(target && ship.GetGovernment()->IsEnemy(target->GetGovernment()))
	{
		// Automatic aiming and firing already occurred.
		MoveIndependent(ship, command);
		return;
	}

	// Choose a surveillance behavior.
	if(ship.GetTargetSystem())
	{
		// Unload surveillance drones in this system before leaving.
		if(!isStaying)
		{
			PrepareForHyperspace(ship, command);
			command |= Command::JUMP;
		}
		if(ship.HasBays())
		{
			command |= Command::DEPLOY;
			Deploy(ship, false);
		}
	}
	else if(ship.GetTargetStellar())
	{
		// Approach the planet and "land" on it (i.e. scan it).
		MoveToPlanet(ship, command);
		double atmosphereScan = ship.Attributes().Get("atmosphere scan");
		double distance = ship.Position().Distance(ship.GetTargetStellar()->Position());
		if(distance < atmosphereScan && !Random::Int(100))
			ship.SetTargetStellar(nullptr);
		else if(!isStaying)
			command |= Command::LAND;
	}
	else if(target)
	{
		// Approach and scan the targeted, friendly ship's cargo or outfits.
		bool cargoScan = ship.Attributes().Get("cargo scan power");
		bool outfitScan = ship.Attributes().Get("outfit scan power");
		// If the pointer to the target ship exists, it is targetable and in-system.
		const Government *gov = ship.GetGovernment();
		bool mustScanCargo = cargoScan && !Has(gov, target, ShipEvent::SCAN_CARGO);
		bool mustScanOutfits = outfitScan && !Has(gov, target, ShipEvent::SCAN_OUTFITS);
		if(!mustScanCargo && !mustScanOutfits)
			ship.SetTargetShip(shared_ptr<Ship>());
		else
		{
			if(target->Velocity().Length() > ship.MaxVelocity() * 0.9)
				CircleAround(ship, command, *target);
			else
				MoveTo(ship, command, target->Position(), target->Velocity(), 1., 1.);
			command |= Command::SCAN;
		}
	}
	else
	{
		const System *system = ship.GetSystem();
		const Government *gov = ship.GetGovernment();

		// Consider scanning any non-hostile ship in this system that your government hasn't scanned.
		// A surveillance ship may only make up to 12 successful scans (6 ships scanned
		// if the ship is using both scanners) and spend up to 5 minutes searching for
		// scan targets. After that, stop scanning ship targets. This is so that scanning
		// ships in high spawn rate systems don't build up over time, as they always have
		// a new ship they can try to scan.
		vector<Ship *> targetShips;
		bool cargoScan = ship.Attributes().Get("cargo scan power");
		bool outfitScan = ship.Attributes().Get("outfit scan power");
		auto cargoScansIt = cargoScans.find(&ship);
		auto outfitScansIt = outfitScans.find(&ship);
		auto scanTimeIt = scanTime.find(&ship);
		int shipScanCount = cargoScansIt != cargoScans.end() ? cargoScansIt->second.size() : 0;
		shipScanCount += outfitScansIt != outfitScans.end() ? outfitScansIt->second.size() : 0;
		int shipScanTime = scanTimeIt != scanTime.end() ? scanTimeIt->second : 0;
		if((cargoScan || outfitScan) && shipScanCount < 12 && shipScanTime < 18000)
		{
			for(const auto &it : GetShipsList(ship, false))
				if(it->GetGovernment() != gov)
				{
					auto ptr = it->shared_from_this();
					if((!cargoScan || Has(gov, ptr, ShipEvent::SCAN_CARGO))
							&& (!outfitScan || Has(gov, ptr, ShipEvent::SCAN_OUTFITS)))
						continue;

					if(it->IsTargetable())
						targetShips.emplace_back(it);
				}
		}

		// Consider scanning any planetary object in the system, if able.
		vector<const StellarObject *> targetPlanets;
		double atmosphereScan = ship.Attributes().Get("atmosphere scan");
		if(atmosphereScan)
			for(const StellarObject &object : system->Objects())
				if(object.HasSprite() && !object.IsStar() && !object.IsStation())
					targetPlanets.push_back(&object);

		// If this ship can jump away, consider traveling to a nearby system.
		vector<const System *> targetSystems;
		// TODO: These ships cannot travel through wormholes?
		if(ship.JumpsRemaining(false))
		{
			const auto &links = ship.JumpNavigation().HasJumpDrive() ?
				system->JumpNeighbors(ship.JumpNavigation().JumpRange()) : system->Links();
			for(const System *link : links)
				if(!ship.IsRestrictedFrom(*link))
					targetSystems.push_back(link);
		}

		unsigned total = targetShips.size() + targetPlanets.size() + targetSystems.size();
		// If there is nothing for this ship to scan, have it patrol the entire system
		// instead of drifting or stopping.
		if(!total)
		{
			DoPatrol(ship, command);
			return;
		}
		// Pick one of the valid surveillance targets at random to focus on.
		unsigned index = Random::Int(total);
		if(index < targetShips.size())
			ship.SetTargetShip(targetShips[index]->shared_from_this());
		else
		{
			index -= targetShips.size();
			if(index < targetPlanets.size())
				ship.SetTargetStellar(targetPlanets[index]);
			else
				ship.SetTargetSystem(targetSystems[index - targetPlanets.size()]);
		}
	}
}



void AI::DoMining(Ship &ship, Command &command)
{
	// This function is only called for ships that are in the player's system.
	// Update the radius that the ship is searching for asteroids at.
	bool isNew = !miningAngle.contains(&ship);
	Angle &angle = miningAngle[&ship];
	if(isNew)
	{
		angle = Angle::Random();
		miningRadius[&ship] = ship.GetSystem()->AsteroidBeltRadius();
	}
	angle += Angle::Random(1.) - Angle::Random(1.);
	double radius = miningRadius[&ship] * pow(2., angle.Unit().X());

	shared_ptr<Minable> target = ship.GetTargetAsteroid();
	if(!target || target->Velocity().Length() > ship.MaxVelocity())
	{
		for(const shared_ptr<Minable> &minable : minables)
		{
			Point offset = minable->Position() - ship.Position();
			// Target only nearby minables that are within 45deg of the current heading
			// and not moving faster than the ship can catch.
			if(offset.Length() < 800. && offset.Unit().Dot(ship.Facing().Unit()) > .7
					&& minable->Velocity().Dot(offset.Unit()) < ship.MaxVelocity())
			{
				target = minable;
				ship.SetTargetAsteroid(target);
				break;
			}
		}
	}
	if(target)
	{
		// If the asteroid has moved well out of reach, stop tracking it.
		if(target->Position().Distance(ship.Position()) > 1600.)
			ship.SetTargetAsteroid(nullptr);
		else
		{
			MoveToAttack(ship, command, *target);
			AutoFire(ship, firingCommands, *target);
			return;
		}
	}

	Point heading = Angle(30.).Rotate(ship.Position().Unit() * radius) - ship.Position();
	command.SetTurn(TurnToward(ship, heading));
	if(ship.Velocity().Dot(heading.Unit()) < .7 * ship.MaxVelocity())
		command |= Command::FORWARD;
}



bool AI::DoHarvesting(Ship &ship, Command &command) const
{
	// If the ship has no target to pick up, do nothing.
	shared_ptr<Flotsam> target = ship.GetTargetFlotsam();
	// Don't try to chase flotsam that are already being pulled toward the ship by a tractor beam.
	const set<const Flotsam *> &avoid = ship.GetTractorFlotsam();
	if(target && (!ship.CanPickUp(*target) || avoid.contains(target.get())))
	{
		target.reset();
		ship.SetTargetFlotsam(target);
	}
	if(!target)
	{
		// Only check for new targets every 10 frames, on average.
		if(Random::Int(10))
			return false;

		// Don't chase anything that will take more than 10 seconds to reach.
		double bestTime = 600.;
		for(const shared_ptr<Flotsam> &it : flotsam)
		{
			if(!ship.CanPickUp(*it) || avoid.contains(it.get()))
				continue;
			// Only pick up flotsam that is nearby and that you are facing toward. Player escorts should
			// always attempt to pick up nearby flotsams when they are given a harvest order, and so ignore
			// the facing angle check.
			Point p = it->Position() - ship.Position();
			double range = p.Length();
			// Player ships do not have a restricted field of view so that they target flotsam behind them.
			if(range > 800. || (range > 100. && p.Unit().Dot(ship.Facing().Unit()) < .9 && !ship.IsYours()))
				continue;

			// Estimate how long it would take to intercept this flotsam.
			Point v = it->Velocity() - ship.Velocity();
			double vMax = ship.MaxVelocity();
			double time = RendezvousTime(p, v, vMax);
			if(std::isnan(time))
				continue;

			double degreesToTurn = TO_DEG * acos(min(1., max(-1., p.Unit().Dot(ship.Facing().Unit()))));
			time += degreesToTurn / ship.TurnRate();
			if(time < bestTime)
			{
				bestTime = time;
				target = it;
			}
		}
		if(!target)
			return false;

		ship.SetTargetFlotsam(target);
	}
	// Deploy any carried ships to improve maneuverability.
	if(ship.HasBays())
	{
		command |= Command::DEPLOY;
		Deploy(ship, false);
	}

	PickUp(ship, command, *target);
	return true;
}



// Check if this ship should cloak. Returns true if this ship decided to run away while cloaking.
bool AI::DoCloak(const Ship &ship, Command &command) const
{
	if(ship.GetPersonality().IsDecloaked())
		return false;
	double cloakingSpeed = ship.CloakingSpeed();
	if(!cloakingSpeed)
		return false;
	// Never cloak if it will cause you to be stranded.
	const Outfit &attributes = ship.Attributes();
	double cloakingFuel = attributes.Get("cloaking fuel");
	double fuelCost = cloakingFuel
		+ attributes.Get("fuel consumption") - attributes.Get("fuel generation");
	if(cloakingFuel && !attributes.Get("ramscoop"))
	{
		double fuel = ship.Fuel() * attributes.Get("fuel capacity");
		int steps = ceil((1. - ship.Cloaking()) / cloakingSpeed);
		// Only cloak if you will be able to fully cloak and also maintain it
		// for as long as it will take you to reach full cloak.
		fuel -= fuelCost * (1 + 2 * steps);
		if(fuel < ship.JumpNavigation().JumpFuel())
			return false;
	}

	// If your parent has chosen to cloak, cloak and rendezvous with them.
	const shared_ptr<const Ship> &parent = ship.GetParent();
	bool shouldCloakWithParent = false;
	if(parent && parent->GetGovernment() && parent->Commands().Has(Command::CLOAK)
			&& parent->GetSystem() == ship.GetSystem())
	{
		const Government *parentGovernment = parent->GetGovernment();
		bool isPlayer = parentGovernment->IsPlayer();
		if(isPlayer && ship.GetGovernment() == parentGovernment)
			shouldCloakWithParent = true;
		else if(isPlayer && ship.GetPersonality().IsEscort() && !ship.GetPersonality().IsUninterested())
			shouldCloakWithParent = true;
		else if(!isPlayer && !parent->GetGovernment()->IsEnemy(ship.GetGovernment()))
			shouldCloakWithParent = true;
	}
	if(shouldCloakWithParent)
	{
		command |= Command::CLOAK;
		KeepStation(ship, command, *parent);
		return true;
	}

	// Otherwise, always cloak if you are in imminent danger.
	static const double MAX_RANGE = 10000.;
	double range = MAX_RANGE;
	const Ship *nearestEnemy = nullptr;
	// Find the nearest targetable, in-system enemy that could attack this ship.
	const auto enemies = GetShipsList(ship, true);
	for(const auto &foe : enemies)
		if(!foe->IsDisabled())
		{
			double distance = ship.Position().Distance(foe->Position());
			if(distance < range)
			{
				range = distance;
				nearestEnemy = foe;
			}
		}

	// If this ship has started cloaking, it must get at least 40% repaired
	// or 40% farther away before it begins decloaking again.
	double hysteresis = ship.Commands().Has(Command::CLOAK) ? .4 : 0.;
	// If cloaking costs nothing, and no one has asked you for help, cloak at will.
	// Player ships should never cloak automatically if they are not in danger.
	bool cloakFreely = (fuelCost <= 0.) && !ship.GetShipToAssist() && !ship.IsYours();
	// If this ship is injured and can repair those injuries while cloaked,
	// then it should cloak while under threat.
	bool canRecoverShieldsCloaked = false;
	bool canRecoverHullCloaked = false;
	if(attributes.Get("cloaked regen multiplier") > -1.)
	{
		if(attributes.Get("shield generation") > 0.)
			canRecoverShieldsCloaked = true;
		else if(attributes.Get("cloaking shield delay") < 1. && attributes.Get("delayed shield generation") > 0.)
			canRecoverShieldsCloaked = true;
	}
	if(attributes.Get("cloaked repair multiplier") > -1.)
	{
		if(attributes.Get("hull repair rate") > 0.)
			canRecoverHullCloaked = true;
		else if(attributes.Get("cloaking repair delay") < 1. && attributes.Get("delayed hull repair") > 0.)
			canRecoverHullCloaked = true;
	}
	bool cloakToRepair = (ship.Health() < RETREAT_HEALTH + hysteresis)
			&& ((ship.Shields() < 1. && canRecoverShieldsCloaked)
			|| (ship.Hull() < 1. && canRecoverHullCloaked));
	if(cloakToRepair && (cloakFreely || range < 2000. * (1. + hysteresis)))
	{
		command |= Command::CLOAK;
		// Move away from the nearest enemy.
		if(nearestEnemy)
		{
			Point safety;
			// TODO: This could use an "Avoid" method, to account for other in-system hazards.
			// Simple approximation: move equally away from both the system center and the
			// nearest enemy, until the constrainment boundary is reached.
			if(ship.GetPersonality().IsUnconstrained() || !fenceCount.contains(&ship))
				safety = 2 * ship.Position().Unit() - nearestEnemy->Position().Unit();
			else
				safety = -ship.Position().Unit();

			safety *= ship.MaxVelocity();
			MoveTo(ship, command, ship.Position() + safety, safety, 1., .8);
			return true;
		}
	}
	// Choose to cloak if there are no enemies nearby and cloaking is sensible.
	if(range == MAX_RANGE && cloakFreely && !ship.GetTargetShip())
		command |= Command::CLOAK;

	return false;
}



void AI::DoPatrol(Ship &ship, Command &command) const
{
	double radius = ship.GetSystem()->ExtraHyperArrivalDistance();
	if(radius == 0.)
		radius = 500.;

	// The ship is outside of the effective range of the system,
	// so we turn it around.
	if(ship.Position().LengthSquared() > radius * radius)
	{
		// Allow ships to land after a while, otherwise they would continue to accumulate in the system.
		if(!ship.GetPersonality().IsStaying() && !Random::Int(10000))
		{
			vector<const StellarObject *> landingTargets;
			for(const StellarObject &object : ship.GetSystem()->Objects())
				if(object.HasSprite() && object.GetPlanet() && object.GetPlanet()->CanLand(ship))
					landingTargets.push_back(&object);
			if(!landingTargets.empty())
			{
				ship.SetTargetStellar(landingTargets[Random::Int(landingTargets.size())]);
				MoveToPlanet(ship, command);
				command |= Command::LAND;
				return;
			}
		}
		// Hacky way of differentiating ship behaviour without additional storage,
		// while keeping it consistent for each ship. TODO: change when Ship::SetTargetLocation exists.
		// This uses the pointer of the ship to choose a pseudo-random angle and instructs it to
		// patrol the system in a criss-crossing pattern, where each turn is this specific angle.
		intptr_t seed = reinterpret_cast<intptr_t>(&ship);
		int behaviour = abs(seed % 23);
		Angle delta = Angle(360. / (behaviour / 2. + 2.) * (behaviour % 2 ? -1. : 1.));
		Angle target = Angle(ship.Position()) + delta;
		MoveTo(ship, command, target.Unit() * radius / 2, Point(), 10., 1.);
	}
	// Otherwise, keep going forward.
	else
	{
		const Point targetVelocity = ship.Facing().Unit() * (ship.MaxVelocity() + 1);
		const Point targetPosition = ship.Position() + targetVelocity;
		MoveTo(ship, command, targetPosition, targetVelocity, 10., 1.);
	}
}



void AI::DoScatter(const Ship &ship, Command &command) const
{
	if(!command.Has(Command::FORWARD) && !command.Has(Command::BACK))
		return;

	double flip = command.Has(Command::BACK) ? -1 : 1;
	double turnRate = ship.TurnRate();
	double acceleration = ship.Acceleration();
	// TODO: If there are many ships, use CollisionSet::Circle or another
	// suitable method to limit which ships are checked.
	for(const shared_ptr<Ship> &other : ships)
	{
		// Do not scatter away from yourself, or ships in other systems.
		if(other.get() == &ship || other->GetSystem() != ship.GetSystem())
			continue;

		// Check for any ships that have nearly the same movement profile as
		// this ship and are in nearly the same location.
		Point offset = other->Position() - ship.Position();
		if(offset.LengthSquared() > 400.)
			continue;
		if(fabs(other->TurnRate() / turnRate - 1.) > .05)
			continue;
		if(fabs(other->Acceleration() / acceleration - 1.) > .05)
			continue;

		// We are too close to this ship. Turn away from it if we aren't already facing away.
		if(fabs(other->Facing().Unit().Dot(ship.Facing().Unit())) > 0.99) // 0.99 => 8 degrees
			command.SetTurn(flip * offset.Cross(ship.Facing().Unit()) > 0. ? 1. : -1.);
		return;
	}
}



bool AI::DoSecretive(Ship &ship, Command &command) const
{
	shared_ptr<Ship> scanningShip;
	// Figure out if any ship is currently scanning us. If that is the case, move away from it.
	for(auto &otherShip : GetShipsList(ship, false))
		if(!ship.GetGovernment()->Trusts(otherShip->GetGovernment()) &&
				otherShip->Commands().Has(Command::SCAN) &&
				otherShip->GetTargetShip() == ship.shared_from_this() &&
				!otherShip->IsDisabled() && !otherShip->IsDestroyed())
			scanningShip = make_shared<Ship>(*otherShip);

	if(scanningShip)
	{
		Point scanningPos = scanningShip->Position();
		Point pos = ship.Position();

		double cargoDistance = scanningShip->Attributes().Get("cargo scan power");
		double outfitDistance = scanningShip->Attributes().Get("outfit scan power");

		double maxScanRange = max(cargoDistance, outfitDistance);
		double distance = scanningPos.DistanceSquared(pos) * .0001;

		// If it can scan us we need to evade.
		if(distance < maxScanRange)
		{
			Point away;
			if(ship.GetPersonality().IsUnconstrained() || !fenceCount.contains(&ship))
				away = pos - scanningPos;
			else
				away = -pos;
			away *= ship.MaxVelocity();
			MoveTo(ship, command, pos + away, away, 1., 1.);
			return true;
		}
	}
	return false;
}



// Instead of coming to a full stop, adjust to a target velocity vector
Point AI::StoppingPoint(const Ship &ship, const Point &targetVelocity, bool &shouldReverse)
{
	Point position = ship.Position();
	Point velocity = ship.Velocity() - targetVelocity;
	Angle angle = ship.Facing();
	double acceleration = ship.CrewAcceleration();
	double turnRate = ship.CrewTurnRate();
	shouldReverse = false;

	// If I were to turn around and stop now the relative movement, where would that put me?
	double v = velocity.Length();
	if(!v)
		return position;
	// It makes no sense to calculate a stopping point for a ship entering hyperspace.
	if(ship.IsHyperspacing())
	{
		if(ship.IsUsingJumpDrive() || ship.IsEnteringHyperspace())
			return position;

		double maxVelocity = ship.MaxVelocity();
		double jumpTime = (v - maxVelocity) / 2.;
		position += velocity.Unit() * (jumpTime * (v + maxVelocity) * .5);
		v = maxVelocity;
	}

	// This assumes you're facing exactly the wrong way.
	double degreesToTurn = TO_DEG * acos(min(1., max(-1., -velocity.Unit().Dot(angle.Unit()))));
	double stopDistance = v * (degreesToTurn / turnRate);
	// Sum of: v + (v - a) + (v - 2a) + ... + 0.
	// The number of terms will be v / a.
	// The average term's value will be v / 2. So:
	stopDistance += .5 * v * v / acceleration;

	if(ship.Attributes().Get("reverse thrust"))
	{
		// Figure out your reverse thruster stopping distance:
		double reverseAcceleration = ship.Attributes().Get("reverse thrust") / ship.InertialMass();
		double reverseDistance = v * (180. - degreesToTurn) / turnRate;
		reverseDistance += .5 * v * v / reverseAcceleration;

		if(reverseDistance < stopDistance)
		{
			shouldReverse = true;
			stopDistance = reverseDistance;
		}
	}

	return position + stopDistance * velocity.Unit();
}



// Get a vector giving the direction this ship should aim in in order to do
// maximum damaged to a target at the given position with its non-turret,
// non-homing weapons. If the ship has no non-homing weapons, this just
// returns the direction to the target.
Point AI::TargetAim(const Ship &ship)
{
	shared_ptr<const Ship> target = ship.GetTargetShip();
	if(target)
		return TargetAim(ship, *target);

	shared_ptr<const Minable> targetAsteroid = ship.GetTargetAsteroid();
	if(targetAsteroid)
		return TargetAim(ship, *targetAsteroid);

	return Point();
}



Point AI::TargetAim(const Ship &ship, const Body &target)
{
	Point result;
	for(const Hardpoint &hardpoint : ship.Weapons())
	{
		const Weapon *weapon = hardpoint.GetOutfit();
		if(!weapon || hardpoint.IsHoming() || hardpoint.IsTurret())
			continue;

		Point start = ship.Position() + ship.Facing().Rotate(hardpoint.GetPoint());
		Point p = target.Position() - start + ship.GetPersonality().Confusion();
		Point v = target.Velocity() - ship.Velocity();
		double steps = RendezvousTime(p, v, weapon->WeightedVelocity() + .5 * weapon->RandomVelocity());
		if(std::isnan(steps))
			continue;

		steps = min(steps, weapon->TotalLifetime());
		p += steps * v;

		double damage = weapon->ShieldDamage() + weapon->HullDamage();
		result += p.Unit() * abs(damage);
	}

	return result ? result : target.Position() - ship.Position();
}



// Aim the given ship's turrets.
void AI::AimTurrets(const Ship &ship, FireCommand &command, bool opportunistic,
		const optional<Point> &targetOverride) const
{
	// (Position, Velocity) pairs of the targets.
	vector<pair<Point, Point>> targets;
	if(!targetOverride)
	{
		// First, get the set of potential hostile ships.
		vector<const Body *> targetBodies;
		const Ship *currentTarget = ship.GetTargetShip().get();
		if(opportunistic || !currentTarget || !currentTarget->IsTargetable())
		{
			// Find the maximum range of any of this ship's turrets.
			double maxRange = 0.;
			for(const Hardpoint &weapon : ship.Weapons())
				if(weapon.CanAim(ship))
					maxRange = max(maxRange, weapon.GetOutfit()->Range());
			// If this ship has no turrets, bail out.
			if(!maxRange)
				return;
			// Extend the weapon range slightly to account for velocity differences.
			maxRange *= 1.5;

			// Now, find all enemy ships within that radius.
			auto enemies = GetShipsList(ship, true, maxRange);
			// Convert the shared_ptr<Ship> into const Body *, to allow aiming turrets
			// at a targeted asteroid. Skip disabled ships, which pose no threat.
			for(auto &&foe : enemies)
				if(!foe->IsDisabled())
					targetBodies.emplace_back(foe);
			// Even if the ship's current target ship is beyond maxRange,
			// or is already disabled, consider aiming at it.
			if(currentTarget && currentTarget->IsTargetable()
					&& find(targetBodies.cbegin(), targetBodies.cend(), currentTarget) == targetBodies.cend())
				targetBodies.push_back(currentTarget);
		}
		else
			targetBodies.push_back(currentTarget);
		// If this ship is mining, consider aiming at its target asteroid.
		if(ship.GetTargetAsteroid())
			targetBodies.push_back(ship.GetTargetAsteroid().get());

		// If there are no targets to aim at, opportunistic turrets should sweep
		// back and forth at random, with the sweep centered on the "outward-facing"
		// angle. Focused turrets should just point forward.
		if(targetBodies.empty() && !opportunistic)
		{
			for(const Hardpoint &hardpoint : ship.Weapons())
				if(hardpoint.CanAim(ship))
				{
					// Get the index of this weapon.
					int index = &hardpoint - &ship.Weapons().front();
					double offset = (hardpoint.GetIdleAngle() - hardpoint.GetAngle()).Degrees();
					command.SetAim(index, offset / hardpoint.TurnRate(ship));
				}
			return;
		}
		if(targetBodies.empty())
		{
			for(const Hardpoint &hardpoint : ship.Weapons())
				if(hardpoint.CanAim(ship))
				{
					// Get the index of this weapon.
					int index = &hardpoint - &ship.Weapons().front();
					// First, check if this turret is currently in motion. If not,
					// it only has a small chance of beginning to move.
					double previous = ship.FiringCommands().Aim(index);
					if(!previous && Random::Int(60))
						continue;

					// Sweep between the min and max arc.
					Angle centerAngle = Angle(hardpoint.GetIdleAngle());
					const Angle minArc = hardpoint.GetMinArc();
					const Angle maxArc = hardpoint.GetMaxArc();
					const double arcMiddleDegrees = (minArc.AbsDegrees() + maxArc.AbsDegrees()) / 2.;
					double bias = (centerAngle - hardpoint.GetAngle()).Degrees() / min(arcMiddleDegrees, 180.);
					double acceleration = Random::Real() - Random::Real() + bias;
					command.SetAim(index, previous + .1 * acceleration);
				}
			return;
		}

		targets.reserve(targetBodies.size());
		for(auto body : targetBodies)
			targets.emplace_back(body->Position(), body->Velocity());
	}
	else
		targets.emplace_back(*targetOverride + ship.Position(), ship.Velocity());
	// Each hardpoint should aim at the target that it is "closest" to hitting.
	for(const Hardpoint &hardpoint : ship.Weapons())
		if(hardpoint.CanAim(ship))
		{
			// This is where this projectile fires from. Add some randomness
			// based on how skilled the pilot is.
			Point start = ship.Position() + ship.Facing().Rotate(hardpoint.GetPoint());
			start += ship.GetPersonality().Confusion();
			// Get the turret's current facing, in absolute coordinates:
			Angle aim = ship.Facing() + hardpoint.GetAngle();
			// Get this projectile's average velocity.
			const Weapon *weapon = hardpoint.GetOutfit();
			double vp = weapon->WeightedVelocity() + .5 * weapon->RandomVelocity();
			// Loop through each body this hardpoint could shoot at. Find the
			// one that is the "best" in terms of how many frames it will take
			// to aim at it and for a projectile to hit it.
			double bestScore = numeric_limits<double>::infinity();
			double bestAngle = 0.;
			for(auto [p, v] : targets)
			{
				p -= start;

				// Only take the ship's velocity into account if this weapon
				// does not have its own acceleration.
				if(!weapon->Acceleration())
					v -= ship.Velocity();
				// By the time this action is performed, the target will
				// have moved forward one time step.
				p += v;

				double rendezvousTime = numeric_limits<double>::quiet_NaN();
				double distance = p.Length();
				// Beam weapons hit instantaneously if they are in range.
				bool isInstantaneous = weapon->TotalLifetime() == 1.;
				if(isInstantaneous && distance < vp)
					rendezvousTime = 0.;
				else
				{
					// Find out how long it would take for this projectile to reach the target.
					if(!isInstantaneous)
						rendezvousTime = RendezvousTime(p, v, vp);

					// If there is no intersection (i.e. the turret is not facing the target),
					// consider this target "out-of-range" but still targetable.
					if(std::isnan(rendezvousTime))
						rendezvousTime = max(distance / (vp ? vp : 1.), 2 * weapon->TotalLifetime());

					// Determine where the target will be at that point.
					p += v * rendezvousTime;

					// All bodies within weapons range have the same basic
					// weight. Outside that range, give them lower priority.
					rendezvousTime = max(0., rendezvousTime - weapon->TotalLifetime());
				}

				// Determine how much the turret must turn to face that vector.
				double degrees = 0.;
				Angle angleToPoint = Angle(p);
				if(hardpoint.IsOmnidirectional())
					degrees = (angleToPoint - aim).Degrees();
				else
				{
					// For turret with limited arc, determine the turn up to the nearest arc limit.
					// Also reduce priority of target if it's not within the firing arc.
					const Angle facing = ship.Facing();
					const Angle minArc = hardpoint.GetMinArc() + facing;
					const Angle maxArc = hardpoint.GetMaxArc() + facing;
					if(!angleToPoint.IsInRange(minArc, maxArc))
					{
						// Decrease the priority of the target.
						rendezvousTime += 2. * weapon->TotalLifetime();

						// Point to the nearer edge of the arc.
						const double minDegree = (minArc - angleToPoint).Degrees();
						const double maxDegree = (maxArc - angleToPoint).Degrees();
						if(fabs(minDegree) < fabs(maxDegree))
							angleToPoint = minArc;
						else
							angleToPoint = maxArc;
					}
					degrees = (angleToPoint - minArc).AbsDegrees() - (aim - minArc).AbsDegrees();
				}
				double turnTime = fabs(degrees) / hardpoint.TurnRate(ship);
				// Always prefer targets that you are able to hit.
				double score = turnTime + (180. / hardpoint.TurnRate(ship)) * rendezvousTime;
				if(score < bestScore)
				{
					bestScore = score;
					bestAngle = degrees;
				}
			}
			if(bestAngle)
			{
				// Get the index of this weapon.
				int index = &hardpoint - &ship.Weapons().front();
				command.SetAim(index, bestAngle / hardpoint.TurnRate(ship));
			}
		}
}



// Fire whichever of the given ship's weapons can hit a hostile target.
void AI::AutoFire(const Ship &ship, FireCommand &command, bool secondary, bool isFlagship) const
{
	const Personality &person = ship.GetPersonality();
	if(person.IsPacifist() || ship.CannotAct(Ship::ActionType::FIRE))
		return;

	bool beFrugal = (ship.IsYours() && !escortsUseAmmo);
	if(person.IsFrugal() || (ship.IsYours() && escortsAreFrugal && escortsUseAmmo))
	{
		// The frugal personality is only active when ships have more than a certain fraction of their total health,
		// and are not outgunned. The default threshold is 75%.
		beFrugal = (ship.Health() > GameData::GetGamerules().UniversalFrugalThreshold());
		if(beFrugal)
		{
			auto ait = allyStrength.find(ship.GetGovernment());
			auto eit = enemyStrength.find(ship.GetGovernment());
			if(ait != allyStrength.end() && eit != enemyStrength.end() && ait->second < eit->second)
				beFrugal = false;
		}
	}

	// Special case: your target is not your enemy. Do not fire, because you do
	// not want to risk damaging that target. Ships will target friendly ships
	// while assisting and performing surveillance.
	shared_ptr<Ship> currentTarget = ship.GetTargetShip();
	const Government *gov = ship.GetGovernment();
	bool friendlyOverride = false;
	bool disabledOverride = false;
	if(ship.IsYours())
	{
		auto it = orders.find(&ship);
		if(it != orders.end())
		{
			if(it->second.Has(Orders::Types::HOLD_FIRE))
				return;
			if(it->second.GetTargetShip() == currentTarget)
			{
				disabledOverride = it->second.Has(Orders::Types::FINISH_OFF);
				friendlyOverride = disabledOverride || it->second.Has(Orders::Types::ATTACK);
			}
		}
	}
	bool currentIsEnemy = currentTarget
		&& currentTarget->GetGovernment()->IsEnemy(gov)
		&& currentTarget->GetSystem() == ship.GetSystem();
	if(currentTarget && !(currentIsEnemy || friendlyOverride))
		currentTarget.reset();

	// Only fire on disabled targets if you don't want to plunder them.
	bool plunders = (person.Plunders() && ship.Cargo().Free());
	bool disables = person.Disables();

	// Don't use weapons with firing force if you are preparing to jump.
	bool isWaitingToJump = ship.Commands().Has(Command::JUMP | Command::WAIT);

	// Find the longest range of any of your non-homing weapons. Homing weapons
	// that don't consume ammo may also fire in non-homing mode.
	double maxRange = 0.;
	for(const Hardpoint &weapon : ship.Weapons())
		if(weapon.IsReady()
				&& !(!currentTarget && weapon.IsHoming() && weapon.GetOutfit()->Ammo())
				&& !(!secondary && weapon.GetOutfit()->Icon())
				&& !(beFrugal && weapon.GetOutfit()->Ammo())
				&& !(isWaitingToJump && weapon.GetOutfit()->FiringForce()))
			maxRange = max(maxRange, weapon.GetOutfit()->Range());
	// Extend the weapon range slightly to account for velocity differences.
	maxRange *= 1.5;

	// Find all enemy ships within range of at least one weapon.
	auto enemies = GetShipsList(ship, true, maxRange);
	// Consider the current target if it is not already considered (i.e. it
	// is a friendly ship and this is a player ship ordered to attack it).
	if(currentTarget && currentTarget->IsTargetable()
			&& find(enemies.cbegin(), enemies.cend(), currentTarget.get()) == enemies.cend())
		enemies.push_back(currentTarget.get());

	int index = -1;
	for(const Hardpoint &hardpoint : ship.Weapons())
	{
		++index;
		// Skip weapons that are not ready to fire.
		if(!hardpoint.IsReady())
			continue;

		// Skip weapons omitted by the "Automatic firing" preference.
		if(isFlagship)
		{
			const Preferences::AutoFire autoFireMode = Preferences::GetAutoFire();
			if(autoFireMode == Preferences::AutoFire::GUNS_ONLY && hardpoint.IsTurret())
				continue;
			if(autoFireMode == Preferences::AutoFire::TURRETS_ONLY && !hardpoint.IsTurret())
				continue;
		}

		const Weapon *weapon = hardpoint.GetOutfit();
		// Don't expend ammo for homing weapons that have no target selected.
		if(!currentTarget && weapon->Homing() && weapon->Ammo())
			continue;
		// Don't fire secondary weapons if told not to.
		if(!secondary && weapon->Icon())
			continue;
		// Don't expend ammo if trying to be frugal.
		if(beFrugal && weapon->Ammo())
			continue;
		// Don't use weapons with firing force if you are preparing to jump.
		if(isWaitingToJump && weapon->FiringForce())
			continue;

		// Special case: if the weapon uses fuel, be careful not to spend so much
		// fuel that you cannot leave the system if necessary.
		if(weapon->FiringFuel())
		{
			double fuel = ship.Fuel() * ship.Attributes().Get("fuel capacity");
			fuel -= weapon->FiringFuel();
			// If the ship is not ever leaving this system, it does not need to
			// reserve any fuel.
			bool isStaying = person.IsStaying();
			if(!secondary || fuel < (isStaying ? 0. : ship.JumpNavigation().JumpFuel()))
				continue;
		}
		// Figure out where this weapon will fire from, but add some randomness
		// depending on how accurate this ship's pilot is.
		Point start = ship.Position() + ship.Facing().Rotate(hardpoint.GetPoint());
		start += person.Confusion();

		double vp = weapon->WeightedVelocity() + .5 * weapon->RandomVelocity();
		double lifetime = weapon->TotalLifetime();

		// Homing weapons revert to "dumb firing" if they have no target.
		if(weapon->Homing() && currentTarget)
		{
			// NPCs shoot ships that they just plundered.
			bool hasBoarded = !ship.IsYours() && Has(ship, currentTarget, ShipEvent::BOARD);
			if(currentTarget->IsDisabled() && (disables || (plunders && !hasBoarded)) && !disabledOverride)
				continue;
			// Don't fire secondary weapons at targets that have started jumping.
			if(weapon->Icon() && currentTarget->IsEnteringHyperspace())
				continue;

			// For homing weapons, don't take the velocity of the ship firing it
			// into account, because the projectile will settle into a velocity
			// that depends on its own acceleration and drag.
			Point p = currentTarget->Position() - start;
			Point v = currentTarget->Velocity();
			// By the time this action is performed, the ships will have moved
			// forward one time step.
			p += v;

			// If this weapon has a blast radius, don't fire it if the target is
			// so close that you'll be hit by the blast. Weapons using proximity
			// triggers will explode sooner, so a larger separation is needed.
			if(!weapon->IsSafe() && p.Length() <= (weapon->BlastRadius() + weapon->TriggerRadius()))
				continue;

			// Calculate how long it will take the projectile to reach its target.
			double steps = RendezvousTime(p, v, vp);
			if(!std::isnan(steps) && steps <= lifetime)
			{
				command.SetFire(index);
				continue;
			}
			continue;
		}
		// For non-homing weapons:
		for(const auto &target : enemies)
		{
			// NPCs shoot ships that they just plundered.
			bool hasBoarded = !ship.IsYours() && Has(ship, target->shared_from_this(), ShipEvent::BOARD);
			if(target->IsDisabled() && (disables || (plunders && !hasBoarded)) && !disabledOverride)
				continue;
			// Merciful ships let fleeing ships go.
			if(target->IsFleeing() && person.IsMerciful())
				continue;
			// Don't hit ships that cannot be hit without targeting
			if(target != currentTarget.get() && !FighterHitHelper::IsValidTarget(target))
				continue;

			Point p = target->Position() - start;
			Point v = target->Velocity();
			// Only take the ship's velocity into account if this weapon
			// does not have its own acceleration.
			if(!weapon->Acceleration())
				v -= ship.Velocity();
			// By the time this action is performed, the ships will have moved
			// forward one time step.
			p += v;

			// Non-homing weapons may have a blast radius or proximity trigger.
			// Do not fire this weapon if we will be caught in the blast.
			if(!weapon->IsSafe() && p.Length() <= (weapon->BlastRadius() + weapon->TriggerRadius()))
				continue;

			// Get the vector the weapon will travel along.
			v = (ship.Facing() + hardpoint.GetAngle()).Unit() * vp - v;
			// Extrapolate over the lifetime of the projectile.
			v *= lifetime;

			const Mask &mask = target->GetMask(step);
			if(mask.Collide(-p, v, target->Facing()) < 1.)
			{
				command.SetFire(index);
				break;
			}
		}
	}
}



void AI::AutoFire(const Ship &ship, FireCommand &command, const Body &target) const
{
	int index = -1;
	for(const Hardpoint &hardpoint : ship.Weapons())
	{
		++index;
		// Only auto-fire primary weapons that take no ammunition.
		if(!hardpoint.IsReady() || hardpoint.GetOutfit()->Icon() || hardpoint.GetOutfit()->Ammo())
			continue;

		// Figure out where this weapon will fire from, but add some randomness
		// depending on how accurate this ship's pilot is.
		Point start = ship.Position() + ship.Facing().Rotate(hardpoint.GetPoint());
		start += ship.GetPersonality().Confusion();

		const Weapon *weapon = hardpoint.GetOutfit();
		double vp = weapon->WeightedVelocity() + .5 * weapon->RandomVelocity();
		double lifetime = weapon->TotalLifetime();

		Point p = target.Position() - start;
		Point v = target.Velocity();
		// Only take the ship's velocity into account if this weapon
		// does not have its own acceleration.
		if(!weapon->Acceleration())
			v -= ship.Velocity();
		// By the time this action is performed, the ships will have moved
		// forward one time step.
		p += v;

		// Get the vector the weapon will travel along.
		v = (ship.Facing() + hardpoint.GetAngle()).Unit() * vp - v;
		// Extrapolate over the lifetime of the projectile.
		v *= lifetime;

		const Mask &mask = target.GetMask(step);
		if(mask.Collide(-p, v, target.Facing()) < 1.)
			command.SetFire(index);
	}
}



// Get the amount of time it would take the given weapon to reach the given
// target, assuming it can be fired in any direction (i.e. turreted). For
// non-turreted weapons this can be used to calculate the ideal direction to
// point the ship in.
double AI::RendezvousTime(const Point &p, const Point &v, double vp)
{
	// How many steps will it take this projectile
	// to intersect the target?
	// (p.x + v.x*t)^2 + (p.y + v.y*t)^2 = vp^2*t^2
	// p.x^2 + 2*p.x*v.x*t + v.x^2*t^2
	//    + p.y^2 + 2*p.y*v.y*t + v.y^2t^2
	//    - vp^2*t^2 = 0
	// (v.x^2 + v.y^2 - vp^2) * t^2
	//    + (2 * (p.x * v.x + p.y * v.y)) * t
	//    + (p.x^2 + p.y^2) = 0
	double a = v.Dot(v) - vp * vp;
	double b = 2. * p.Dot(v);
	double c = p.Dot(p);
	double discriminant = b * b - 4 * a * c;
	if(discriminant < 0.)
		return numeric_limits<double>::quiet_NaN();

	discriminant = sqrt(discriminant);

	// The solutions are b +- discriminant.
	// But it's not a solution if it's negative.
	double r1 = (-b + discriminant) / (2. * a);
	double r2 = (-b - discriminant) / (2. * a);
	if(r1 >= 0. && r2 >= 0.)
		return min(r1, r2);
	else if(r1 >= 0. || r2 >= 0.)
		return max(r1, r2);

	return numeric_limits<double>::quiet_NaN();
}



// Searches every asteroid within the ship scan limit and returns either the
// asteroid closest to the ship or the asteroid of highest value in range, depending
// on the player's preferences.
bool AI::TargetMinable(Ship &ship) const
{
	double scanRangeMetric = 10000. * ship.Attributes().Get("asteroid scan power");
	if(!scanRangeMetric)
		return false;
	const bool findClosest = Preferences::Has("Target asteroid based on");
	auto bestMinable = ship.GetTargetAsteroid();
	double bestScore = findClosest ? numeric_limits<double>::max() : 0.;
	auto GetDistanceMetric = [&ship](const Minable &minable) -> double {
		return ship.Position().DistanceSquared(minable.Position());
	};
	if(bestMinable)
	{
		if(findClosest)
			bestScore = GetDistanceMetric(*bestMinable);
		else
			bestScore = bestMinable->GetValue();
	}
	auto MinableStrategy = [&findClosest, &bestMinable, &bestScore, &GetDistanceMetric]()
			-> function<void(const shared_ptr<Minable> &)>
	{
		if(findClosest)
			return [&bestMinable, &bestScore, &GetDistanceMetric]
					(const shared_ptr<Minable> &minable) -> void {
				double newScore = GetDistanceMetric(*minable);
				if(newScore < bestScore || (newScore == bestScore && minable->GetValue() > bestMinable->GetValue()))
				{
					bestScore = newScore;
					bestMinable = minable;
				}
			};
		else
			return [&bestMinable, &bestScore, &GetDistanceMetric]
					(const shared_ptr<Minable> &minable) -> void {
				double newScore = minable->GetValue();
				if(newScore > bestScore || (newScore == bestScore
						&& GetDistanceMetric(*minable) < GetDistanceMetric(*bestMinable)))
				{
					bestScore = newScore;
					bestMinable = minable;
				}
			};
	};
	auto UpdateBestMinable = MinableStrategy();
	for(auto &&minable : minables)
	{
		if(GetDistanceMetric(*minable) > scanRangeMetric)
			continue;
		if(bestMinable)
			UpdateBestMinable(minable);
		else
			bestMinable = minable;
	}
	if(bestMinable)
		ship.SetTargetAsteroid(bestMinable);
	return static_cast<bool>(ship.GetTargetAsteroid());
}



void AI::MovePlayer(Ship &ship, Command &activeCommands)
{
	Command command;
	firingCommands.SetHardpoints(ship.Weapons().size());

	bool shift = activeCommands.Has(Command::SHIFT);

	bool isWormhole = false;
	if(player.HasTravelPlan())
	{
		// Determine if the player is jumping to their target system or landing on a wormhole.
		const System *system = player.TravelPlan().back();
		for(const StellarObject &object : ship.GetSystem()->Objects())
			if(object.HasSprite() && object.HasValidPlanet() && object.GetPlanet()->IsWormhole()
				&& object.GetPlanet()->IsAccessible(&ship) && player.HasVisited(*object.GetPlanet())
				&& player.CanView(*system))
			{
				const auto *wormhole = object.GetPlanet()->GetWormhole();
				if(&wormhole->WormholeDestination(*ship.GetSystem()) != system)
					continue;

				isWormhole = true;
				if(!ship.GetTargetStellar() || autoPilot.Has(Command::JUMP))
					ship.SetTargetStellar(&object);
				break;
			}
		if(!isWormhole)
			ship.SetTargetSystem(system);
	}

	if(ship.IsEnteringHyperspace() && !ship.IsHyperspacing())
	{
		// Check if there's a particular planet there we want to visit.
		const System *system = ship.GetTargetSystem();
		set<const Planet *> destinations;
		Date deadline;
		const Planet *bestDestination = nullptr;
		size_t missions = 0;
		for(const Mission &mission : player.Missions())
		{
			// Don't include invisible and failed missions in the check.
			if(!mission.IsVisible() || mission.IsFailed())
				continue;

			// If the accessible destination of a mission is in this system, and you've been
			// to all waypoints and stopovers (i.e. could complete it), consider landing on it.
			if(mission.Stopovers().empty() && mission.Waypoints().empty()
					&& mission.Destination()->IsInSystem(system)
					&& mission.Destination()->IsAccessible(&ship))
			{
				destinations.insert(mission.Destination());
				++missions;
				// If this mission has a deadline, check if it is the soonest
				// deadline. If so, this should be your ship's destination.
				if(!deadline || (mission.Deadline() && mission.Deadline() < deadline))
				{
					deadline = mission.Deadline();
					bestDestination = mission.Destination();
				}
			}
			// Also check for stopovers in the destination system.
			for(const Planet *planet : mission.Stopovers())
				if(planet->IsInSystem(system) && planet->IsAccessible(&ship))
				{
					destinations.insert(planet);
					++missions;
					if(!bestDestination)
						bestDestination = planet;
				}
		}

		// Inform the player of any destinations in the system they are jumping to.
		if(!destinations.empty() && Preferences::GetNotificationSetting() != Preferences::NotificationSetting::OFF)
		{
			string message = "Note: you have ";
			message += (missions == 1 ? "a mission that requires" : "missions that require");
			message += " landing on ";
			message += Format::List<set, const Planet *>(destinations,
				[](const Planet *const &planet)
				{
					return planet->DisplayName();
				});
			message += " in the system you are jumping to.";
			Messages::Add(message, Messages::Importance::Info);

			if(Preferences::GetNotificationSetting() == Preferences::NotificationSetting::BOTH)
				UI::PlaySound(UI::UISound::FAILURE);
		}
		// If any destination was found, find the corresponding stellar object
		// and set it as your ship's target planet.
		if(bestDestination)
			ship.SetTargetStellar(system->FindStellar(bestDestination));
	}

	if(activeCommands.Has(Command::NEAREST))
	{
		// Find the nearest enemy ship to the flagship. If `Shift` is held, consider friendly ships too.
		double closest = numeric_limits<double>::infinity();
		bool foundActive = false;
		bool found = false;
		for(const shared_ptr<Ship> &other : ships)
			if(other.get() != &ship && other->IsTargetable())
			{
				bool enemy = other->GetGovernment()->IsEnemy(ship.GetGovernment());
				// Do not let "target nearest" select a friendly ship, so that
				// if the player is repeatedly targeting nearest to, say, target
				// a bunch of fighters, they won't start firing on friendly
				// ships as soon as the last one is gone.
				if((!enemy && !shift) || other->IsYours())
					continue;

				// Sort ships by active or disabled:
				// Prefer targeting an active ship over a disabled one
				bool active = !other->IsDisabled();

				double d = other->Position().Distance(ship.Position());

				if((!foundActive && active) || (foundActive == active && d < closest))
				{
					ship.SetTargetShip(other);
					closest = d;
					foundActive = active;
					found = true;
				}
			}
		// If no ship was found, look for nearby asteroids.
		if(!found)
			TargetMinable(ship);
		else
			UI::PlaySound(UI::UISound::TARGET);
	}
	else if(activeCommands.Has(Command::TARGET))
	{
		// Find the "next" ship to target. Holding `Shift` will cycle through escorts.
		shared_ptr<const Ship> target = ship.GetTargetShip();
		// Whether the next eligible ship should be targeted.
		bool selectNext = !target || !target->IsTargetable();
		for(const shared_ptr<Ship> &other : ships)
		{
			// Do not target yourself.
			if(other.get() == &ship)
				continue;
			// The default behavior is to ignore your fleet and any friendly escorts.
			bool isPlayer = other->IsYours() || (other->GetPersonality().IsEscort()
					&& !other->GetGovernment()->IsEnemy());
			if(other == target)
				selectNext = true;
			else if(selectNext && isPlayer == shift && other->IsTargetable())
			{
				ship.SetTargetShip(other);
				if(isPlayer)
					player.SelectShip(other.get(), false);
				selectNext = false;
				break;
			}
		}
		if(selectNext)
		{
			ship.SetTargetShip(shared_ptr<Ship>());
			player.SelectShip(nullptr, false);
		}
		else
			UI::PlaySound(UI::UISound::TARGET);
	}
	else if(activeCommands.Has(Command::BOARD))
	{
		// Determine the player's boarding target based on their current target and their boarding preference. They may
		// press BOARD repeatedly to cycle between ships, or use SHIFT to prioritize repairing their owned escorts.
		shared_ptr<Ship> target = ship.GetTargetShip();
		if(target && !CanBoard(ship, *target))
			target.reset();
		if(!target || activeCommands.Has(Command::WAIT) || (shift && !target->IsYours()))
		{
			if(shift)
				ship.SetTargetShip(shared_ptr<Ship>());

			const auto boardingPriority = Preferences::GetBoardingPriority();
			auto strategy = [&]() noexcept -> function<double(const Ship &)>
			{
				Point current = ship.Position();
				switch(boardingPriority)
				{
					case Preferences::BoardingPriority::VALUE:
						return [this, &ship](const Ship &other) noexcept -> double
						{
							// Use the exact cost if the ship was scanned, otherwise use an estimation.
							return this->Has(ship, other.shared_from_this(), ShipEvent::SCAN_OUTFITS) ?
								other.Cost() : (other.ChassisCost() * 2.);
						};
					case Preferences::BoardingPriority::MIXED:
						return [this, &ship, current](const Ship &other) noexcept -> double
						{
							double cost = this->Has(ship, other.shared_from_this(), ShipEvent::SCAN_OUTFITS) ?
								other.Cost() : (other.ChassisCost() * 2.);
							// Even if we divide by 0, doubles can contain and handle infinity,
							// and we should definitely board that one then.
							return cost * cost / (current.DistanceSquared(other.Position()) + 0.1);
						};
					case Preferences::BoardingPriority::PROXIMITY:
					default:
						return [current](const Ship &other) noexcept -> double
						{
							return current.DistanceSquared(other.Position());
						};
				}
			}();

			using ShipValue = pair<Ship *, double>;
			auto options = vector<ShipValue>{};
			if(shift)
			{
				const auto &owned = governmentRosters[ship.GetGovernment()];
				options.reserve(owned.size());
				for(auto &&escort : owned)
					if(CanBoard(ship, *escort))
						options.emplace_back(escort, strategy(*escort));
			}
			else
			{
				auto ships = GetShipsList(ship, true);
				options.reserve(ships.size());
				// The current target is not considered by GetShipsList.
				if(target)
					options.emplace_back(target.get(), strategy(*target));

				// First check if we can board enemy ships, then allies.
				for(auto &&enemy : ships)
					if(CanBoard(ship, *enemy))
						options.emplace_back(enemy, strategy(*enemy));
				if(options.empty())
				{
					ships = GetShipsList(ship, false);
					options.reserve(ships.size());
					for(auto &&ally : ships)
						if(CanBoard(ship, *ally))
							options.emplace_back(ally, strategy(*ally));
				}
			}

			if(options.empty())
				activeCommands.Clear(Command::BOARD);
			else
			{
				// Sort the list of options in increasing order of desirability.
				sort(options.begin(), options.end(),
					[&ship, boardingPriority](const ShipValue &lhs, const ShipValue &rhs)
					{
						if(boardingPriority == Preferences::BoardingPriority::PROXIMITY)
							return lhs.second > rhs.second;

						// If their cost is the same, prefer the closest ship.
						return (boardingPriority == Preferences::BoardingPriority::VALUE && lhs.second == rhs.second)
							? lhs.first->Position().DistanceSquared(ship.Position()) >
								rhs.first->Position().DistanceSquared(ship.Position())
							: lhs.second < rhs.second;
					}
				);

				// Pick the (next) most desirable option.
				auto it = !target ? options.end() : find_if(options.begin(), options.end(),
					[&target](const ShipValue &lhs) noexcept -> bool { return lhs.first == target.get(); });
				if(it == options.begin())
					it = options.end();
				ship.SetTargetShip((--it)->first->shared_from_this());
				UI::PlaySound(UI::UISound::TARGET);
			}
		}
	}
	// Player cannot attempt to land while departing from a planet.
	else if(activeCommands.Has(Command::LAND) && !ship.IsEnteringHyperspace() && ship.Zoom() == 1.)
	{
		// Track all possible landable objects in the current system.
		auto landables = vector<const StellarObject *>{};

		string message;
		const bool isMovingSlowly = (ship.Velocity().Length() < (MIN_LANDING_VELOCITY / 60.));
		const StellarObject *potentialTarget = nullptr;
		for(const StellarObject &object : ship.GetSystem()->Objects())
		{
			if(!object.HasSprite())
				continue;

			// If the player is moving slowly over an object, then the player is considering landing there.
			// The target object might not be able to be landed on, for example an enemy planet or a star.
			const bool isTryingLanding = (ship.Position().Distance(object.Position()) < object.Radius() && isMovingSlowly);
			if(object.HasValidPlanet() && object.GetPlanet()->IsAccessible(&ship) && object.IsVisible(ship.Position()))
			{
				landables.emplace_back(&object);
				if(isTryingLanding)
					potentialTarget = &object;
			}
			else if(isTryingLanding)
				message = object.LandingMessage();
		}

		const StellarObject *target = ship.GetTargetStellar();
		// Require that the player's planetary target is one of the current system's planets.
		auto landIt = find(landables.cbegin(), landables.cend(), target);
		if(landIt == landables.cend())
			target = nullptr;

		// Consider the potential target as a landing target first.
		if(!target && potentialTarget)
		{
			target = potentialTarget;
			ship.SetTargetStellar(potentialTarget);
		}

		// If the player has a target in mind already, don't emit an error if the player
		// is hovering above a star or inaccessible planet.
		if(target)
			message.clear();
		else if(!message.empty())
			UI::PlaySound(UI::UISound::FAILURE);

		Messages::Importance messageImportance = Messages::Importance::High;

		if(target && (ship.Zoom() < 1. || ship.Position().Distance(target->Position()) < target->Radius()))
		{
			// Special case: if there are two planets in system and you have one
			// selected, then press "land" again, do not toggle to the other if
			// you are within landing range of the one you have selected.
		}
		else if(message.empty() && target && activeCommands.Has(Command::WAIT))
		{
			// Select the next landable in the list after the currently selected object.
			if(++landIt == landables.cend())
				landIt = landables.cbegin();
			const StellarObject *next = *landIt;
			ship.SetTargetStellar(next);

			if(!next->GetPlanet()->CanLand())
			{
				message = "The authorities on this " + next->GetPlanet()->Noun() +
					" refuse to clear you to land here.";
				messageImportance = Messages::Importance::Highest;
				UI::PlaySound(UI::UISound::FAILURE);
			}
			else if(next != target)
				message = "Switching landing targets. Now landing on " + next->DisplayName() + ".";
		}
		else if(message.empty())
		{
			// This is the first press, or it has been long enough since the last press,
			// so land on the nearest eligible planet. Prefer inhabited ones with fuel.
			set<string> types;
			if(!target && !landables.empty())
			{
				if(landables.size() == 1)
					ship.SetTargetStellar(landables.front());
				else
				{
					double closest = numeric_limits<double>::infinity();
					for(const auto &object : landables)
					{
						double distance = ship.Position().Distance(object->Position());
						const Planet *planet = object->GetPlanet();
						types.insert(planet->Noun());
						if((!planet->CanLand() || !planet->GetPort().CanRecharge(Port::RechargeType::Fuel))
								&& !planet->IsWormhole())
							distance += 10000.;

						if(distance < closest)
						{
							ship.SetTargetStellar(object);
							closest = distance;
						}
					}
				}
				target = ship.GetTargetStellar();
			}

			if(!target)
			{
				message = "There are no planets in this system that you can land on.";
				messageImportance = Messages::Importance::Highest;
				UI::PlaySound(UI::UISound::FAILURE);
			}
			else if(!target->GetPlanet()->CanLand())
			{
				message = "The authorities on this " + target->GetPlanet()->Noun() +
					" refuse to clear you to land here.";
				messageImportance = Messages::Importance::Highest;
				UI::PlaySound(UI::UISound::FAILURE);
			}
			else if(!types.empty())
			{
				message = "You can land on more than one ";
				set<string>::const_iterator it = types.begin();
				message += *it++;
				if(it != types.end())
				{
					set<string>::const_iterator last = --types.end();
					if(it != last)
						message += ',';
					while(it != last)
						message += ' ' + *it++ + ',';
					message += " or " + *it;
				}
				message += " in this system. Landing on " + target->DisplayName() + ".";
			}
			else
				message = "Landing on " + target->DisplayName() + ".";
		}
		if(!message.empty())
			Messages::Add(message, messageImportance);
	}
	else if(activeCommands.Has(Command::JUMP | Command::FLEET_JUMP))
	{
		if(player.TravelPlan().empty() && !isWormhole)
		{
			double bestMatch = -2.;
			const auto &links = (ship.JumpNavigation().HasJumpDrive() ?
				ship.GetSystem()->JumpNeighbors(ship.JumpNavigation().JumpRange()) : ship.GetSystem()->Links());
			for(const System *link : links)
			{
				// Not all systems in range are necessarily visible. Don't allow
				// jumping to systems which haven't been seen.
				if(!player.HasSeen(*link))
					continue;

				Point direction = link->Position() - ship.GetSystem()->Position();
				double match = ship.Facing().Unit().Dot(direction.Unit());
				if(match > bestMatch)
				{
					bestMatch = match;
					ship.SetTargetSystem(link);
				}
			}
		}
		else if(isWormhole)
		{
			// The player is guaranteed to have a travel plan for isWormhole to be true.
			Messages::Add("Landing on a local wormhole to navigate to the "
					+ player.TravelPlan().back()->DisplayName() + " system.", Messages::Importance::High);
		}
		if(ship.GetTargetSystem() && !isWormhole)
		{
			string name = "selected star";
			if(player.KnowsName(*ship.GetTargetSystem()))
				name = ship.GetTargetSystem()->DisplayName();

			if(activeCommands.Has(Command::FLEET_JUMP))
			{
				// Note: also has command JUMP on only the first call.
				if(activeCommands.Has(Command::JUMP))
					Messages::Add("Engaging fleet autopilot to jump to the " + name + " system."
						" Your fleet will jump when ready.", Messages::Importance::High);
			}
			else
				Messages::Add("Engaging autopilot to jump to the " + name + " system.", Messages::Importance::High);
		}
	}
	else if(activeCommands.Has(Command::SCAN))
		command |= Command::SCAN;
	else if(activeCommands.Has(Command::HARVEST))
	{
		OrderSingle newOrder{Orders::Types::HARVEST};
		IssueOrder(newOrder, "preparing to harvest.");
	}
	else if(activeCommands.Has(Command::NEAREST_ASTEROID))
	{
		TargetMinable(ship);
	}

	const shared_ptr<const Ship> target = ship.GetTargetShip();
	auto targetOverride = Preferences::Has("Aim turrets with mouse") ^ activeCommands.Has(Command::AIM_TURRET_HOLD)
		? optional(mousePosition) : nullopt;
	AimTurrets(ship, firingCommands, !Preferences::Has("Turrets focus fire"), targetOverride);
	if(Preferences::GetAutoFire() != Preferences::AutoFire::OFF && !ship.IsBoarding()
			&& !(autoPilot | activeCommands).Has(Command::LAND | Command::JUMP | Command::FLEET_JUMP | Command::BOARD)
			&& (!target || target->GetGovernment()->IsEnemy()))
		AutoFire(ship, firingCommands, false, true);

	const bool mouseTurning = activeCommands.Has(Command::MOUSE_TURNING_HOLD);
	if(mouseTurning && !ship.IsBoarding() && (!ship.IsReversing() || ship.Attributes().Get("reverse thrust")))
		command.SetTurn(TurnToward(ship, mousePosition));

	if(activeCommands)
	{
		if(activeCommands.Has(Command::FORWARD))
			command |= Command::FORWARD;
		if(activeCommands.Has(Command::RIGHT | Command::LEFT) && !mouseTurning)
			command.SetTurn(activeCommands.Has(Command::RIGHT) - activeCommands.Has(Command::LEFT));
		if(activeCommands.Has(Command::BACK))
		{
			if(!activeCommands.Has(Command::FORWARD) && ship.Attributes().Get("reverse thrust"))
				command |= Command::BACK;
			else if(!activeCommands.Has(Command::RIGHT | Command::LEFT | Command::AUTOSTEER))
				command.SetTurn(TurnBackward(ship));
		}

		if(activeCommands.Has(Command::PRIMARY))
		{
			int index = 0;
			for(const Hardpoint &hardpoint : ship.Weapons())
			{
				if(hardpoint.IsReady() && !hardpoint.GetOutfit()->Icon())
					firingCommands.SetFire(index);
				++index;
			}
		}
		if(activeCommands.Has(Command::SECONDARY))
		{
			int index = 0;
			const auto &playerSelectedWeapons = player.SelectedSecondaryWeapons();
			for(const Hardpoint &hardpoint : ship.Weapons())
			{
				if(hardpoint.IsReady() && (playerSelectedWeapons.find(hardpoint.GetOutfit()) != playerSelectedWeapons.end()))
					firingCommands.SetFire(index);
				++index;
			}
		}
		if(activeCommands.Has(Command::AFTERBURNER))
			command |= Command::AFTERBURNER;

		if(activeCommands.Has(AutopilotCancelCommands()))
			autoPilot = activeCommands;
	}
	bool shouldAutoAim = false;
	bool isFiring = activeCommands.Has(Command::PRIMARY) || activeCommands.Has(Command::SECONDARY);
	if(activeCommands.Has(Command::AUTOSTEER) && !command.Turn() && !ship.IsBoarding()
			&& !autoPilot.Has(Command::LAND | Command::JUMP | Command::FLEET_JUMP | Command::BOARD))
	{
		if(target && target->GetSystem() == ship.GetSystem() && target->IsTargetable())
			command.SetTurn(TurnToward(ship, TargetAim(ship)));
		else if(ship.GetTargetAsteroid())
			command.SetTurn(TurnToward(ship, TargetAim(ship, *ship.GetTargetAsteroid())));
		else if(ship.GetTargetStellar())
			command.SetTurn(TurnToward(ship, ship.GetTargetStellar()->Position() - ship.Position()));
	}
	else if((Preferences::GetAutoAim() == Preferences::AutoAim::ALWAYS_ON
			|| (Preferences::GetAutoAim() == Preferences::AutoAim::WHEN_FIRING && isFiring))
			&& !command.Turn() && !ship.IsBoarding()
			&& ((target && target->GetSystem() == ship.GetSystem() && target->IsTargetable()) || ship.GetTargetAsteroid())
			&& !autoPilot.Has(Command::LAND | Command::JUMP | Command::FLEET_JUMP | Command::BOARD))
	{
		// Check if this ship has any forward-facing weapons.
		for(const Hardpoint &weapon : ship.Weapons())
			if(!weapon.CanAim(ship) && !weapon.IsTurret() && weapon.GetOutfit())
			{
				shouldAutoAim = true;
				break;
			}
	}
	if(shouldAutoAim)
	{
		Point pos = (target ? target->Position() : ship.GetTargetAsteroid()->Position());
		if((pos - ship.Position()).Unit().Dot(ship.Facing().Unit()) >= .8)
			command.SetTurn(TurnToward(ship, TargetAim(ship)));
	}

	if(autoPilot.Has(Command::JUMP | Command::FLEET_JUMP) && !(player.HasTravelPlan() || ship.GetTargetSystem()))
	{
		// The player completed their travel plan, which may have indicated a destination within the final system.
		autoPilot.Clear(Command::JUMP | Command::FLEET_JUMP);
		const Planet *planet = player.TravelDestination();
		if(planet && planet->IsInSystem(ship.GetSystem()) && planet->IsAccessible(&ship))
		{
			Messages::Add("Autopilot: landing on " + planet->DisplayName() + ".", Messages::Importance::High);
			autoPilot |= Command::LAND;
			ship.SetTargetStellar(ship.GetSystem()->FindStellar(planet));
		}
	}

	// Clear autopilot actions if actions can't be performed.
	if(autoPilot.Has(Command::LAND) && !ship.GetTargetStellar())
		autoPilot.Clear(Command::LAND);
	if(autoPilot.Has(Command::JUMP | Command::FLEET_JUMP) && !(ship.GetTargetSystem() || isWormhole))
		autoPilot.Clear(Command::JUMP | Command::FLEET_JUMP);
	if(autoPilot.Has(Command::BOARD) && !(ship.GetTargetShip() && CanBoard(ship, *ship.GetTargetShip())))
		autoPilot.Clear(Command::BOARD);

	if(autoPilot.Has(Command::LAND) || (autoPilot.Has(Command::JUMP | Command::FLEET_JUMP) && isWormhole))
	{
		if(activeCommands.Has(Command::WAIT) || (autoPilot.Has(Command::FLEET_JUMP) && !EscortsReadyToLand(ship)))
			command |= Command::WAIT;

		if(ship.GetPlanet())
			autoPilot.Clear(Command::LAND | Command::JUMP | Command::FLEET_JUMP);
		else
		{
			MoveToPlanet(ship, command);
			command |= Command::LAND;
		}
	}
	else if(autoPilot.Has(Command::STOP))
	{
		// STOP is automatically cleared once the ship has stopped.
		if(Stop(ship, command))
			autoPilot.Clear(Command::STOP);
	}
	else if(autoPilot.Has(Command::JUMP | Command::FLEET_JUMP) && !ship.IsEnteringHyperspace())
	{
		if(!ship.JumpNavigation().HasHyperdrive() && !ship.JumpNavigation().HasJumpDrive())
		{
			Messages::Add("You do not have a hyperdrive installed.", Messages::Importance::Highest);
			autoPilot.Clear();
			UI::PlaySound(UI::UISound::FAILURE);
		}
		else if(!ship.JumpNavigation().JumpFuel(ship.GetTargetSystem()))
		{
			Messages::Add("You cannot jump to the selected system.", Messages::Importance::Highest);
			autoPilot.Clear();
			UI::PlaySound(UI::UISound::FAILURE);
		}
		else if(!ship.JumpsRemaining() && !ship.IsEnteringHyperspace())
		{
			Messages::Add("You do not have enough fuel to make a hyperspace jump.", Messages::Importance::Highest);
			autoPilot.Clear();
			UI::PlaySound(UI::UISound::FAILURE);
		}
		else if(ship.IsLanding())
		{
			Messages::Add("You cannot jump while landing.", Messages::Importance::Highest);
			autoPilot.Clear(Command::JUMP);
			UI::PlaySound(UI::UISound::FAILURE);
		}
		else
		{
			PrepareForHyperspace(ship, command);
			command |= Command::JUMP;

			// Don't jump yet if the player is holding jump key or fleet jump is active and
			// escorts are not ready to jump yet.
			if(activeCommands.Has(Command::WAIT) || (autoPilot.Has(Command::FLEET_JUMP) && !EscortsReadyToJump(ship)))
				command |= Command::WAIT;
		}
	}
	else if(autoPilot.Has(Command::BOARD))
	{
		if(!CanBoard(ship, *target))
			autoPilot.Clear(Command::BOARD);
		else
		{
			MoveTo(ship, command, target->Position(), target->Velocity(), 40., .8);
			command |= Command::BOARD;
		}
	}

	if(ship.HasBays() && HasDeployments(ship))
	{
		command |= Command::DEPLOY;
		Deploy(ship, !Preferences::Has("Damaged fighters retreat"));
	}
	if(isCloaking)
		command |= Command::CLOAK;

	ship.SetCommands(command);
	ship.SetCommands(firingCommands);
}



void AI::DisengageAutopilot()
{
	Messages::Add("Disengaging autopilot.", Messages::Importance::High);
	autoPilot.Clear();
}



bool AI::Has(const Ship &ship, const weak_ptr<const Ship> &other, int type) const
{
	auto sit = actions.find(ship.shared_from_this());
	if(sit == actions.end())
		return false;

	auto oit = sit->second.find(other);
	if(oit == sit->second.end())
		return false;

	return (oit->second & type);
}



bool AI::Has(const Government *government, const weak_ptr<const Ship> &other, int type) const
{
	auto git = governmentActions.find(government);
	if(git == governmentActions.end())
		return false;

	auto oit = git->second.find(other);
	if(oit == git->second.end())
		return false;

	return (oit->second & type);
}



// True if the ship has committed the action against that government. For
// example, if the player boarded any ship belonging to that government.
bool AI::Has(const Ship &ship, const Government *government, int type) const
{
	auto sit = notoriety.find(ship.shared_from_this());
	if(sit == notoriety.end())
		return false;

	auto git = sit->second.find(government);
	if(git == sit->second.end())
		return false;

	return (git->second & type);
}



void AI::UpdateStrengths(map<const Government *, int64_t> &strength, const System *playerSystem)
{
	// Tally the strength of a government by the strength of its present and able ships.
	governmentRosters.clear();
	for(const auto &it : ships)
		if(it->GetGovernment() && it->GetSystem() == playerSystem)
		{
			governmentRosters[it->GetGovernment()].emplace_back(it.get());
			if(!it->IsDisabled())
				strength[it->GetGovernment()] += it->Strength();
		}

	// Strengths of enemies and allies are rebuilt every step.
	enemyStrength.clear();
	allyStrength.clear();
	for(const auto &gov : strength)
	{
		set<const Government *> allies;
		for(const auto &enemy : strength)
			if(enemy.first->IsEnemy(gov.first))
			{
				// "Know your enemies."
				enemyStrength[gov.first] += enemy.second;
				for(const auto &ally : strength)
					if(ally.first->IsEnemy(enemy.first) && !allies.contains(ally.first))
					{
						// "The enemy of my enemy is my friend."
						allyStrength[gov.first] += ally.second;
						allies.insert(ally.first);
					}
			}
	}

	// Ships with nearby allies consider their allies' strength as well as their own.
	for(const auto &it : ships)
	{
		const Government *gov = it->GetGovernment();

		// Check if this ship's government has the authority to enforce scans & fines in this system.
		if(!scanPermissions.contains(gov))
			scanPermissions.emplace(gov, gov && gov->CanEnforce(playerSystem));

		// Only have ships update their strength estimate once per second on average.
		if(!gov || it->GetSystem() != playerSystem || it->IsDisabled() || Random::Int(60))
			continue;

		int64_t &myStrength = shipStrength[it.get()];
		for(const auto &allies : governmentRosters)
		{
			// If this is not an allied government, its ships will not assist this ship when attacked.
			if(allies.first->AttitudeToward(gov) <= 0.)
				continue;
			for(const auto &ally : allies.second)
				if(!ally->IsDisabled() && ally->Position().Distance(it->Position()) < 2000.)
					myStrength += ally->Strength();
		}
	}
}



// Cache various lists of all targetable ships in the player's system for this Step.
void AI::CacheShipLists()
{
	allyLists.clear();
	enemyLists.clear();
	for(const auto &git : governmentRosters)
	{
		allyLists.emplace(git.first, vector<Ship *>());
		allyLists.at(git.first).reserve(ships.size());
		enemyLists.emplace(git.first, vector<Ship *>());
		enemyLists.at(git.first).reserve(ships.size());
		for(const auto &oit : governmentRosters)
		{
			auto &list = git.first->IsEnemy(oit.first)
					? enemyLists[git.first] : allyLists[git.first];
			list.insert(list.end(), oit.second.begin(), oit.second.end());
		}
	}
}



void AI::RegisterDerivedConditions(ConditionsStore &conditions)
{
	// Special conditions about system hostility.
	conditions["government strength: "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		const Government *gov = GameData::Governments().Get(ce.NameWithoutPrefix());
		int64_t strength = 0;
		for(const Ship *ship : governmentRosters[gov])
			if(ship)
				strength += ship->Strength();
		return strength;
	});
	conditions["ally strength"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		return allyStrength[GameData::PlayerGovernment()];
	});
	conditions["enemy strength"].ProvideNamed([this](const ConditionEntry &ce) -> int64_t {
		return enemyStrength[GameData::PlayerGovernment()];
	});
	conditions["ally strength: "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		const Government *gov = GameData::Governments().Get(ce.NameWithoutPrefix());
		return gov ? allyStrength[gov] : 0.;
	});
	conditions["enemy strength: "].ProvidePrefixed([this](const ConditionEntry &ce) -> int64_t {
		const Government *gov = GameData::Governments().Get(ce.NameWithoutPrefix());
		return gov ? enemyStrength[gov] : 0.;
	});
}



void AI::IssueOrder(const OrderSingle &newOrder, const string &description)
{
	// Figure out what ships we are giving orders to.
	string who;
	vector<const Ship *> ships;
	size_t destroyedCount = 0;
	// A "hold fire" order can used on the flagship to temporarily block autofire.
	// Other orders can be issued only to escorts.
	bool includeFlagship = newOrder.type == Orders::Types::HOLD_FIRE;
	if(player.SelectedShips().empty())
	{
		for(const shared_ptr<Ship> &it : player.Ships())
			if((includeFlagship || it.get() != player.Flagship()) && !it->IsParked())
			{
				if(it->IsDestroyed())
					++destroyedCount;
				else
					ships.push_back(it.get());
			}
		who = (ships.empty() ? destroyedCount : ships.size()) > 1
			? "Your fleet is " : includeFlagship ? "Your flagship is " : "Your escort is ";
	}
	else
	{
		for(const weak_ptr<Ship> &it : player.SelectedShips())
		{
			shared_ptr<Ship> ship = it.lock();
			if(!ship)
				continue;
			if(ship->IsDestroyed())
				++destroyedCount;
			else
				ships.push_back(ship.get());
		}
		who = (ships.empty() ? destroyedCount : ships.size()) > 1
			? "The selected escorts are " : "The selected escort is ";
	}
	if(ships.empty())
	{
		if(destroyedCount)
			Messages::Add(who + "destroyed and unable to execute your orders.",
				Messages::Importance::High);
		return;
	}

	Point centerOfGravity;
	bool isMoveOrder = newOrder.type == Orders::Types::MOVE_TO;
	int squadCount = 0;
	if(isMoveOrder)
	{
		for(const Ship *ship : ships)
			if(ship->GetSystem() && !ship->IsDisabled())
			{
				centerOfGravity += ship->Position();
				++squadCount;
			}
		if(squadCount > 1)
			centerOfGravity /= squadCount;
	}
	// If this is a move command, make sure the fleet is bunched together
	// enough that each ship takes up no more than about 30,000 square pixels.
	double maxSquadOffset = sqrt(10000. * squadCount);

	const Ship *flagship = player.Flagship();
	const Ship *newTargetShip = newOrder.GetTargetShip().get();
	// A target is valid if we have no target, or when the target is in the
	// same system as the flagship.
	bool isValidTarget = !newTargetShip || newOrder.GetTargetAsteroid()
		|| (flagship && newTargetShip->GetSystem() == flagship->GetSystem());

	// Now, go through all the given ships and add the new order to their sets.
	// But, if it turns out that they already had the given order,
	// this order will be cleared instead. The only command that does not
	// toggle is a move command; it always counts as a new command.
	bool hasMismatch = isMoveOrder;
	bool gaveOrder = false;
	bool alreadyHarvesting = false;
	if(isValidTarget)
	{
		for(const Ship *ship : ships)
		{
			// Never issue orders to a ship to target itself.
			if(ship == newTargetShip)
				continue;

			gaveOrder = true;
			hasMismatch |= !orders.contains(ship);

			OrderSet &existing = orders[ship];
			existing.Add(newOrder, &hasMismatch, &alreadyHarvesting);

			if(isMoveOrder)
			{
				// In a move order, rather than commanding every ship to move to the
				// same point, they move as a mass so their center of gravity is
				// that point but their relative positions are unchanged.
				Point offset = ship->Position() - centerOfGravity;
				if(offset.Length() > maxSquadOffset)
					offset = offset.Unit() * maxSquadOffset;
				existing.SetTargetPoint(existing.GetTargetPoint() + offset);
			}
			else if(existing.Has(Orders::Types::HOLD_POSITION))
			{
				bool shouldReverse = false;
				// Set the point this ship will "guard," so it can return
				// to it if knocked away by projectiles / explosions.
				existing.SetTargetPoint(StoppingPoint(*ship, Point(), shouldReverse));
			}
		}
		if(!gaveOrder)
			return;
	}

	if(alreadyHarvesting)
		return;
	else if(hasMismatch)
		Messages::Add(who + description, Messages::Importance::High);
	else
	{
		if(!isValidTarget)
			Messages::Add(who + "unable to and no longer " + description, Messages::Importance::High);
		else
			Messages::Add(who + "no longer " + description, Messages::Importance::High);

		// Clear any orders that are now empty.
		for(const Ship *ship : ships)
		{
			auto it = orders.find(ship);
			if(it != orders.end() && it->second.Empty())
				orders.erase(it);
		}
	}
}



// Change the ship's order based on its current fulfillment of the order.
void AI::UpdateOrders(const Ship &ship)
{
	// This should only be called for ships with orders that can be carried out.
	auto it = orders.find(&ship);
	if(it == orders.end())
		return;

	it->second.Update(ship);
}