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
|
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// The copyright to the contents herein is the property of Valve, L.L.C.
// The contents may be used and/or copied only with the written permission of
// Valve, L.L.C., or in accordance with the terms and conditions stipulated in
// the agreement/contract under which the contents have been supplied.
//
// Purpose: Basic BOT handling.
//
// $Workfile: $
// $Date: $
//
//-----------------------------------------------------------------------------
// $Log: $
//
// $NoKeywords: $
//=============================================================================
#include "cbase.h"
#include "player.h"
#include "tf_player.h"
#include "tf_gamerules.h"
#include "in_buttons.h"
#include "movehelper_server.h"
#include "tf_playerclass_shared.h"
#include "datacache/imdlcache.h"
#include "serverbenchmark_base.h"
#include "econ_entity_creation.h"
#include "nav_mesh.h"
#include "nav_pathfind.h"
#include "tf_team.h"
#include "tf_obj.h"
#include "player.h"
#ifdef STAGING_ONLY
#include "econ_item_system.h"
#endif // STAGING_ONLY
void InitBotTrig( void );
void ClientPutInServer( edict_t *pEdict, const char *playername );
void Bot_Think( CTFPlayer *pBot );
ConVar bot_debug( "bot_debug", "0", FCVAR_CHEAT, "Bot debugging." );
#define DbgBotMsg( pszMsg ) \
do \
{ \
if ( bot_debug.GetBool() ) \
DevMsg( "[Bot] %s", static_cast<const char *>(pszMsg) ); \
} while (0)
ConVar bot_forcefireweapon( "bot_forcefireweapon", "", 0, "Force bots with the specified weapon to fire." );
ConVar bot_forceattack( "bot_forceattack", "0", 0, "When on, all bots fire their guns." );
ConVar bot_forceattack2( "bot_forceattack2", "0", 0, "When firing, use attack2." );
ConVar bot_forceattack_down( "bot_forceattack_down", "1", 0, "When firing, don't tap fire, hold it down." );
ConVar bot_changeclass( "bot_changeclass", "0", 0, "Force all bots to change to the specified class." );
ConVar bot_dontmove( "bot_dontmove", "0", FCVAR_CHEAT );
ConVar bot_saveme( "bot_saveme", "0", FCVAR_CHEAT );
static ConVar bot_mimic_inverse( "bot_mimic_inverse", "0", 0, "Bot uses usercmd of player by index." );
static ConVar bot_mimic_yaw_offset( "bot_mimic_yaw_offset", "180", 0, "Offsets the bot yaw." );
ConVar bot_selectweaponslot( "bot_selectweaponslot", "-1", FCVAR_CHEAT, "set to weapon slot that bot should switch to." );
ConVar bot_randomnames( "bot_randomnames", "0", FCVAR_CHEAT );
ConVar bot_jump( "bot_jump", "0", FCVAR_CHEAT, "Force all bots to repeatedly jump." );
ConVar bot_crouch( "bot_crouch", "0", FCVAR_CHEAT, "Force all bots to crouch." );
ConVar bot_nav_turnspeed( "bot_nav_turnspeed", "5", FCVAR_CHEAT, "Rate at which bots turn to face their targets." );
ConVar bot_nav_wpdistance( "bot_nav_wpdistance", "16", FCVAR_CHEAT, "Distance to a waypoint within which a bot considers as having reached it." );
ConVar bot_nav_wpdeceldistance( "bot_nav_wpdeceldistance", "128", FCVAR_CHEAT, "Distance to a waypoint to which a bot starts to decelerate to reach it." );
ConVar bot_nav_simplifypaths( "bot_nav_simplifypaths", "1", FCVAR_CHEAT, "If set, bots will skip waypoints if they already see the waypoint post." );
ConVar bot_nav_useoffsetpaths( "bot_nav_useoffsetpaths", "1", FCVAR_CHEAT, "If set, bots will generate waypoints on both sides of portals between waypoints when building paths." );
ConVar bot_nav_offsetpathinset( "bot_nav_offsetpathinset", "20", FCVAR_CHEAT, "Distance into an area that waypoints should be generated when pathfinding through portals." );
ConVar bot_nav_usefeelers( "bot_nav_usefeelers", "1", FCVAR_CHEAT, "If set, bots will extend feelers to their sides to find & avoid upcoming collisions." );
ConVar bot_nav_recomputetime( "bot_nav_recomputetime", "0.5", FCVAR_CHEAT, "Delay before bots recompute their path to targets that have moved when moving to them." );
ConVar bot_com_meleerange( "bot_com_meleerange", "80", FCVAR_CHEAT, "Distance to a target that a melee bot wants to be within to attack." );
ConVar bot_com_wpnrange( "bot_com_wpnrange", "400", FCVAR_CHEAT, "Distance to a target that a ranged bot wants to be within to attack." );
ConVar bot_com_viewrange( "bot_com_viewrange", "2000", FCVAR_CHEAT, "Distance within which bots looking for any enemies will find them." );
extern ConVar bot_mimic;
extern ConVar sv_usercmd_custom_random_seed;
// Utility function to get the specified bot from the command arguments
void GetBotsFromCommand( const CCommand &args, int iArgsRequired, const char *pszUsage, CUtlVector< CTFPlayer* > *botVector )
{
if ( !botVector)
return;
if ( args.ArgC() < iArgsRequired )
{
Msg( "Too few parameters. %s\n", pszUsage );
return;
}
const char *pszBotName = args[1];
if ( FStrEq( pszBotName, "all" ) )
{
CUtlVector< CTFPlayer* > playerVector;
CollectPlayers( &playerVector );
for ( int i=0; i<playerVector.Count(); ++i )
{
if ( playerVector[i]->IsFakeClient() )
{
botVector->AddToTail( playerVector[i] );
}
}
return;
}
// get the bot's player object
CTFPlayer *pBot = ToTFPlayer( UTIL_PlayerByName( pszBotName ) );
if ( !pBot || !pBot->IsFakeClient() )
{
Msg( "No bot with name %s\n", args[1] );
return;
}
botVector->AddToTail( pBot );
}
static int BotNumber = 1;
static int g_iNextBotTeam = -1;
static int g_iNextBotClass = -1;
//===================================================================================================================
// Purpose: Mapmaker bot control entity. Used by mapmakers to add & script bot behaviors.
class CTFBotController : public CPointEntity
{
DECLARE_CLASS( CTFBotController, CPointEntity );
public:
DECLARE_DATADESC();
// Input.
void InputCreateBot( inputdata_t &inputdata );
void InputRespawnBot( inputdata_t &inputdata );
void InputBotAddCommandMoveToEntity( inputdata_t &inputdata );
void InputBotAddCommandAttackEntity( inputdata_t &inputdata );
void InputBotAddCommandSwitchWeapon( inputdata_t &inputdata );
void InputBotAddCommandDefend( inputdata_t &inputdata );
void InputBotSetIgnoreHumans( inputdata_t &inputdata );
void InputBotPreventMovement( inputdata_t &inputdata );
void InputBotClearQueue( inputdata_t &inputdata );
public:
COutputEvent m_outputOnCommandFinished; // Fired when the entity is done respawning the players.
CHandle<CTFPlayer> m_hBot;
string_t m_iszBotName;
int m_iBotClass;
};
enum botcommands_t
{
BC_NONE,
BC_MOVETO_ENTITY,
BC_MOVETO_POINT,
BC_ATTACK,
BC_SWITCH_WEAPON,
BC_DEFEND,
};
typedef struct botdata_t
{
CHandle<CTFPlayer> m_hBot;
bool backwards;
float nextturntime;
bool lastturntoright;
float nextstrafetime;
float sidemove;
QAngle forwardAngle;
QAngle lastAngles;
float m_flJoinTeamTime;
int m_WantedTeam;
int m_WantedClass;
bool m_bChoseWeapon;
bool m_bWasDead;
float m_flDeadTime;
//------------------------------------------------------
// Input into the next command
unsigned short buttons;
//------------------------------------------------------
// Base thinking
void Bot_AliveThink( QAngle *vecAngles, Vector *vecMove );
void Bot_AliveWeaponThink( QAngle *vecAngles, Vector *vecMove );
void Bot_AliveMovementThink( QAngle *vecAngles, Vector *vecMove );
void Bot_AliveMovementThink_ExtendFeelers( QAngle *vecAngles, Vector *vecMove, Vector *vecCurVelocity );
void Bot_DeadThink( QAngle *vecAngles, Vector *vecMove );
void Bot_ItemTestingThink( QAngle *vecAngles, Vector *vecMove );
//------------------------------------------------------
// Navigation
bool FindPathTo( Vector vecTarget );
bool ComputePathPositions( void );
bool UpdatePath( void );
void AdvancePath( void )
{
m_iPathIndex++;
if ( m_iPathIndex >= m_iPathLength )
{
if ( RunningMovementCommand() )
{
// We're not done if we're moving to an entity
if ( !CommandHasATarget() && ShouldFinishCommandOnArrival() )
{
ResetPath();
FinishCommand();
}
else
{
// We finished our path, so find another one.
m_flRecomputePathAt = 0;
if ( !UpdatePath() )
{
FinishCommand();
}
}
}
}
}
bool HasPath( void )
{
return (m_iPathLength > 0);
}
void ResetPath( void )
{
m_iPathIndex = 0;
m_iPathLength = 0;
}
Vector m_vecFaceToTarget;
enum { MAX_PATH_LENGTH = 256 };
struct ConnectInfo
{
CNavArea *area; ///< the area along the path
NavTraverseType how; ///< how to enter this area from the previous one
Vector pos; ///< our movement goal position at this point in the path
float flOffset;
};
ConnectInfo m_path[MAX_PATH_LENGTH];
int m_iPathLength;
int m_iPathIndex;
CNavArea *m_lastKnownArea;
float m_flRecomputePathAt;
Vector m_vecLastPathTarget;
//------------------------------------------------------
// Sensing
void SetIgnoreHumans( bool bIgnore ) { m_bIgnoreHumans = bIgnore; }
void SetFrozen( bool bFrozen ) { if ( bFrozen ) m_hBot->AddEFlags( EFL_BOT_FROZEN ); else m_hBot->RemoveEFlags( EFL_BOT_FROZEN ); }
bool FindEnemyTarget( void );
bool ValidTargetPlayer( CTFPlayer *pPlayer, const Vector &vecStart, const Vector &vecEnd );
bool ValidTargetObject( CBaseObject *pObject, const Vector &vecStart, const Vector &vecEnd );
EHANDLE m_hEnemy;
bool m_bIgnoreHumans;
//------------------------------------------------------
// Command Queue
void UpdatePlanForCommand( void );
void StartNewCommand( void );
void FinishCommand( void );
void RunAttackPlan( void );
void RunDefendPlan( void );
void AddAttackCommand( CBaseEntity *pTarget );
void AddMoveToCommand( CBaseEntity *pTarget, Vector vecTarget );
void AddSwitchWeaponCommand( int iSlot );
void AddDefendCommand( float flRange );
void ClearQueue( void );
bool RunningMovementCommand( void );
bool CommandHasATarget( void );
bool ShouldFinishCommandOnArrival( void );
CBaseEntity *GetCommandTarget( void ) { return m_Commands.Count() ? m_Commands[0].pTarget : NULL; }
Vector GetCommandPosition( void ) { return m_Commands.Count() ? m_Commands[0].vecTarget : vec3_origin; }
struct CommandInfo
{
botcommands_t iCommand;
EHANDLE pTarget;
Vector vecTarget;
float flData;
};
CUtlVector<CommandInfo> m_Commands;
bool m_bStartedCommand;
CHandle<CTFBotController> m_hBotController;
} botdata_t;
static botdata_t g_BotData[ MAX_PLAYERS ];
inline botdata_t *BotData( CBasePlayer *pBot )
{
return &g_BotData[ pBot->entindex() - 1 ];
}
//-----------------------------------------------------------------------------
// Purpose: Create a new Bot and put it in the game.
// Output : Pointer to the new Bot, or NULL if there's no free clients.
//-----------------------------------------------------------------------------
CBasePlayer *BotPutInServer( bool bTargetDummy, bool bFrozen, int iTeam, int iClass, const char *pszCustomName )
{
InitBotTrig();
g_iNextBotTeam = iTeam;
g_iNextBotClass = iClass;
char botname[ 64 ];
if ( pszCustomName && pszCustomName[0] )
{
Q_strncpy( botname, pszCustomName, sizeof( botname ) );
}
else if ( bot_randomnames.GetBool() )
{
switch( g_pServerBenchmark->RandomInt(0,5) )
{
case 0: Q_snprintf( botname, sizeof( botname ), "Bot" ); break;
case 1: Q_snprintf( botname, sizeof( botname ), "This is a medium Bot" ); break;
case 2: Q_snprintf( botname, sizeof( botname ), "This is a super long bot name that is too long for the game to allow" ); break;
case 3: Q_snprintf( botname, sizeof( botname ), "Another bot" ); break;
case 4: Q_snprintf( botname, sizeof( botname ), "Yet more Bot names, medium sized" ); break;
default: Q_snprintf( botname, sizeof( botname ), "B" ); break;
}
}
else
{
Q_snprintf( botname, sizeof( botname ), "Bot%02i", BotNumber );
}
edict_t *pEdict = engine->CreateFakeClient( botname );
if (!pEdict)
{
Msg( "Failed to create Bot.\n");
return NULL;
}
// Allocate a CBasePlayer for the bot, and call spawn
//ClientPutInServer( pEdict, botname );
CTFPlayer *pPlayer = ((CTFPlayer *)CBaseEntity::Instance( pEdict ));
pPlayer->ClearFlags();
pPlayer->AddFlag( FL_CLIENT | FL_FAKECLIENT );
pPlayer->SetPlayerType( CTFPlayer::TEMP_BOT );
if ( bFrozen )
{
pPlayer->AddEFlags( EFL_BOT_FROZEN );
}
if ( bTargetDummy )
{
pPlayer->SetTargetDummy();
}
BotNumber++;
botdata_t *pBot = BotData(pPlayer);
pBot->m_hBot = pPlayer;
pBot->m_bWasDead = false;
pBot->m_WantedTeam = iTeam;
pBot->m_WantedClass = iClass;
pBot->m_bChoseWeapon = false;
pBot->m_flJoinTeamTime = gpGlobals->curtime + 0.3;
pBot->m_vecFaceToTarget.Zero();
pBot->m_lastKnownArea = NULL;
pBot->m_flRecomputePathAt = 0;
pBot->ResetPath();
pBot->m_bIgnoreHumans = false;
pBot->m_bStartedCommand = false;
return pPlayer;
}
//-----------------------------------------------------------------------------------------------------
CON_COMMAND_F( bot_kick, "Remove a bot by name, or an entire team (\"red\" or \"blue\"), or all bots (\"all\").", FCVAR_CHEAT )
{
// Listenserver host or rcon access only!
if ( !UTIL_IsCommandIssuedByServerAdmin() )
return;
if ( args.ArgC() != 2 )
{
DevMsg( "%s <bot name>, \"red\", \"blue\", or \"all\"\n", args.Arg(0) );
return;
}
for( int i = 1; i <= gpGlobals->maxClients; ++i )
{
CBasePlayer *player = static_cast<CBasePlayer *>( UTIL_PlayerByIndex( i ) );
if ( !player )
continue;
if ( FNullEnt( player->edict() ) )
continue;
if ( player->GetFlags() & FL_FAKECLIENT )
{
if ( FStrEq( args.Arg( 1 ), "all" ) ||
FStrEq( args.Arg( 1 ), player->GetPlayerName() ) ||
( FStrEq( args.Arg( 1 ), "red" ) && player->GetTeamNumber() == TF_TEAM_RED ) ||
( FStrEq( args.Arg( 1 ), "blue" ) && player->GetTeamNumber() == TF_TEAM_BLUE ) )
{
engine->ServerCommand( UTIL_VarArgs( "kickid %d\n", player->GetUserID() ) );
}
}
}
}
// Handler for the "bot" command.
CON_COMMAND_F( bot, "Add a bot.", FCVAR_NONE )
{
// Listenserver host or rcon access only!
if ( !UTIL_IsCommandIssuedByServerAdmin() )
return;
// Allow bots in item testing mode
if ( !sv_cheats->GetBool() && !TFGameRules()->IsInItemTestingMode() )
return;
//CDODPlayer *pPlayer = CDODPlayer::Instance( UTIL_GetCommandClientIndex() );
// The bot command uses switches like command-line switches.
// -count <count> tells how many bots to spawn.
// -team <index> selects the bot's team. Default is -1 which chooses randomly.
// Note: if you do -team !, then it
// -class <index> selects the bot's class. Default is -1 which chooses randomly.
// -frozen prevents the bots from running around when they spawn in.
// -name sets the bot's name
// -targetdummy sets their health to 1,000,000. Useful for testing damage via hud_damagemeter.
// -teleport teleports the bot to the location the player is pointing at
// Look at -count.
int count = args.FindArgInt( "-count", 1 );
count = clamp( count, 1, 16 );
if ( args.FindArg( "-all" ) )
{
count = 9;
}
// Look at -frozen.
bool bFrozen = !!args.FindArg( "-frozen" );
bool bTargetDummy = !!args.FindArg( "-targetdummy" );
bool bTeleport = !!args.FindArg( "-teleport" );
// Ok, spawn all the bots.
while ( --count >= 0 )
{
// What class do they want?
int iClass = g_pServerBenchmark->RandomInt( 1, TF_CLASS_COUNT-2 ); // -2 so we skip the Civilian class
char const *pVal = args.FindArg( "-class" );
if ( pVal )
{
for ( int i=1; i < TF_CLASS_COUNT_ALL; i++ )
{
if ( !Q_stricmp(pVal, g_aPlayerClassNames_NonLocalized[i] ) )
{
iClass = i;
break;
}
}
}
if ( args.FindArg( "-all" ) )
{
iClass = 9 - count ;
}
int iTeam = TEAM_UNASSIGNED;
pVal = args.FindArg( "-team" );
if ( pVal )
{
if ( stricmp( pVal, "red" ) == 0 )
{
iTeam = TF_TEAM_RED;
}
else if ( stricmp( pVal, "spectator" ) == 0 )
{
iTeam = TEAM_SPECTATOR;
}
else if ( stricmp( pVal, "random" ) == 0 )
{
iTeam = g_pServerBenchmark->RandomInt( 0, 100 ) < 50 ? TF_TEAM_BLUE : TF_TEAM_RED;
}
else
{
iTeam = TF_TEAM_BLUE;
}
}
char const *pName = args.FindArg( "-name" );
CBasePlayer *pTemp = BotPutInServer( bTargetDummy, bFrozen, iTeam, iClass, pName );
if ( bTeleport && pTemp )
{
CTFPlayer *pBot = ToTFPlayer( pTemp );
CBasePlayer *pPlayer = UTIL_GetCommandClient();
if ( pPlayer && pBot )
{
trace_t tr;
Vector forward;
pPlayer->EyeVectors( &forward );
UTIL_TraceLine( pPlayer->EyePosition(),
pPlayer->EyePosition() + forward * MAX_TRACE_LENGTH,MASK_NPCSOLID,
pPlayer, COLLISION_GROUP_NONE, &tr );
if ( tr.fraction != 1.0 )
{
botdata_t *pBotData = BotData( pBot );
if ( pBotData )
{
pBotData->m_flJoinTeamTime = gpGlobals->curtime - 0.1;
}
const char *pszTeam = "auto";
switch ( pBotData->m_WantedTeam )
{
case TF_TEAM_RED:
pszTeam = "red";
break;
case TF_TEAM_BLUE:
pszTeam = "blue";
break;
case TEAM_SPECTATOR:
pszTeam = "spectator";
break;
default:
pszTeam = "auto";
break;
}
pBot->HandleCommand_JoinTeam( pszTeam );
const char *pszClassname = ( pBotData->m_WantedClass == TF_CLASS_RANDOM ) ? "random" : GetPlayerClassData( pBotData->m_WantedClass )->m_szClassName;
pBot->HandleCommand_JoinClass( pszClassname );
pBot->ForceRespawn();
pBot->Teleport( &tr.endpos, NULL, NULL );
}
}
}
}
}
//-----------------------------------------------------------------------------------------------------
CON_COMMAND_F( bot_hurt, "Hurt a bot by team, or all bots (\"all\").", FCVAR_GAMEDLL )
{
// Listenserver host or rcon access only!
if ( !UTIL_IsCommandIssuedByServerAdmin() )
return;
if ( args.ArgC() < 2 )
{
DevMsg( "%s (-team <red/blue/all>>) (-name <name>) (-damage <int>) (-burn)\n", args.Arg(0) );
return;
}
int nDamage = 50;
const char* pszDamage = args.FindArg( "-damage" );
if( pszDamage )
{
nDamage = atoi(pszDamage);
}
bool bBurn = args.FindArg( "-burn" ) != nullptr;
// Figure out which team if specified
int iTeam = TEAM_UNASSIGNED;
const char* pVal = args.FindArg( "-team" );
if ( pVal )
{
if ( stricmp( pVal, "red" ) == 0 )
{
iTeam = TF_TEAM_RED;
}
else if ( stricmp( pVal, "blue" ) == 0 )
{
iTeam = TF_TEAM_BLUE;
}
else if ( stricmp( pVal, "all" ) == 0 )
{
iTeam = TEAM_ANY;
}
else
{
iTeam = TEAM_ANY;
}
}
// Get the name if the put one in
pVal = args.FindArg( "-name" );
const char *pPlayerName = "";
if( pVal )
{
pPlayerName = pVal;
}
for( int i=1; i<=gpGlobals->maxClients; ++i )
{
CBasePlayer *player = static_cast<CBasePlayer *>( UTIL_PlayerByIndex( i ) );
if ( !player )
continue;
if ( FNullEnt( player->edict() ) )
continue;
if ( player->GetFlags() & FL_FAKECLIENT )
{
if ( iTeam == TEAM_ANY ||
FStrEq( pPlayerName, player->GetPlayerName() ) ||
( player->GetTeamNumber() == iTeam ) ||
( player->GetTeamNumber() == iTeam ) )
{
player->m_iHealth -= nDamage;
if ( bBurn )
{
CTFPlayer *pBot = ToTFPlayer( player );
pBot->m_Shared.Burn( nullptr, nullptr, 10.0f );
}
}
}
}
}
inline bool isTempBot( CTFPlayer* pPlayer )
{
return ( pPlayer && ( pPlayer->GetFlags() & FL_FAKECLIENT ) && pPlayer->GetPlayerType() == CTFPlayer::TEMP_BOT );
}
//-----------------------------------------------------------------------------
// Purpose: Run through all the Bots in the game and let them think.
//-----------------------------------------------------------------------------
void Bot_RunAll( void )
{
for ( int i = 1; i <= gpGlobals->maxClients; i++ )
{
CTFPlayer *pPlayer = ToTFPlayer( UTIL_PlayerByIndex( i ) );
if ( isTempBot( pPlayer ) && pPlayer->MyNextBotPointer() == NULL )
{
Bot_Think( pPlayer );
}
}
}
bool RunMimicCommand( CUserCmd& cmd )
{
if ( bot_mimic.GetInt() <= 0 )
return false;
if ( bot_mimic.GetInt() > gpGlobals->maxClients )
return false;
CBasePlayer *pPlayer = UTIL_PlayerByIndex( bot_mimic.GetInt() );
if ( !pPlayer )
return false;
if ( !pPlayer->GetLastUserCommand() )
return false;
cmd = *pPlayer->GetLastUserCommand();
cmd.viewangles[YAW] += bot_mimic_yaw_offset.GetFloat();
if ( bot_mimic_inverse.GetBool() )
{
cmd.forwardmove *= -1;
cmd.sidemove *= -1;
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Simulates a single frame of movement for a player
// Input : *fakeclient -
// *viewangles -
// forwardmove -
// sidemove -
// upmove -
// buttons -
// impulse -
// msec -
// Output : virtual void
//-----------------------------------------------------------------------------
static void RunPlayerMove( CTFPlayer *fakeclient, const QAngle& viewangles, float forwardmove, float sidemove, float upmove, unsigned short buttons, byte impulse, float frametime )
{
if ( !fakeclient )
return;
CUserCmd cmd;
// Store off the globals.. they're gonna get whacked
float flOldFrametime = gpGlobals->frametime;
float flOldCurtime = gpGlobals->curtime;
float flTimeBase = gpGlobals->curtime + gpGlobals->frametime - frametime;
fakeclient->SetTimeBase( flTimeBase );
Q_memset( &cmd, 0, sizeof( cmd ) );
if ( !RunMimicCommand( cmd ) )
{
VectorCopy( viewangles, cmd.viewangles );
cmd.forwardmove = forwardmove;
cmd.sidemove = sidemove;
cmd.upmove = upmove;
cmd.buttons = buttons;
cmd.impulse = impulse;
cmd.random_seed = g_pServerBenchmark->RandomInt( 0, 0x7fffffff );
if ( sv_usercmd_custom_random_seed.GetBool() )
{
float fltTimeNow = float( Plat_FloatTime() * 1000.0 );
cmd.server_random_seed = *reinterpret_cast<int*>( (char*)&fltTimeNow );
}
else
{
cmd.server_random_seed = cmd.random_seed;
}
}
if ( bot_dontmove.GetBool() )
{
cmd.forwardmove = 0;
cmd.sidemove = 0;
cmd.upmove = 0;
}
else
{
float flStunAmount = fakeclient->m_Shared.GetAmountStunned( TF_STUN_MOVEMENT );
if ( flStunAmount )
{
cmd.forwardmove *= (1.0 - flStunAmount);
cmd.sidemove *= (1.0 - flStunAmount);
}
}
if ( fakeclient->m_Shared.IsControlStunned() || fakeclient->m_Shared.IsLoserStateStunned() )
{
cmd.weaponselect = 0;
cmd.buttons = 0;
if ( fakeclient->m_Shared.IsControlStunned() )
{
cmd.forwardmove = 0;
cmd.sidemove = 0;
cmd.upmove = 0;
}
}
MoveHelperServer()->SetHost( fakeclient );
fakeclient->PlayerRunCommand( &cmd, MoveHelperServer() );
// save off the last good usercmd
fakeclient->SetLastUserCommand( cmd );
// Clear out any fixangle that has been set
fakeclient->pl.fixangle = FIXANGLE_NONE;
// Restore the globals..
gpGlobals->frametime = flOldFrametime;
gpGlobals->curtime = flOldCurtime;
}
//-----------------------------------------------------------------------------
// Purpose: Run this Bot's AI for one frame.
//-----------------------------------------------------------------------------
void Bot_Think( CTFPlayer *pBot )
{
// Make sure we stay being a bot
pBot->AddFlag( FL_FAKECLIENT );
botdata_t *botdata = BotData(pBot);
Vector vecMove( 0, 0, 0 );
byte impulse = 0;
float frametime = gpGlobals->frametime;
QAngle vecViewAngles = pBot->EyeAngles();
botdata->buttons = 0;
MDLCACHE_CRITICAL_SECTION();
// Create some random values
if ( pBot->GetTeamNumber() == TEAM_UNASSIGNED && gpGlobals->curtime > botdata->m_flJoinTeamTime )
{
const char *pszTeam = NULL;
switch ( botdata->m_WantedTeam )
{
case TF_TEAM_RED:
pszTeam = "red";
break;
case TF_TEAM_BLUE:
pszTeam = "blue";
break;
case TEAM_SPECTATOR:
pszTeam = "spectator";
break;
default:
pszTeam = "auto";
break;
}
pBot->HandleCommand_JoinTeam( pszTeam );
}
else if ( pBot->GetTeamNumber() != TEAM_UNASSIGNED && pBot->GetPlayerClass()->IsClass( TF_CLASS_UNDEFINED ) )
{
// If they're on a team but haven't picked a class, choose a random class..
const char *pszClassname = ( botdata->m_WantedClass == TF_CLASS_RANDOM ) ? "random" : GetPlayerClassData( botdata->m_WantedClass )->m_szClassName;
pBot->HandleCommand_JoinClass( pszClassname );
}
else if ( pBot->IsAlive() && (pBot->GetSolid() == SOLID_BBOX) )
{
botdata->Bot_AliveThink( &vecViewAngles, &vecMove );
}
else
{
botdata->Bot_DeadThink( &vecViewAngles, &vecMove );
}
RunPlayerMove( pBot, vecViewAngles, vecMove[0], vecMove[1], vecMove[2], botdata->buttons, impulse, frametime );
}
//-----------------------------------------------------------------------------
// Purpose: Handle the Bot AI for a live bot
//-----------------------------------------------------------------------------
void botdata_t::Bot_AliveThink( QAngle *vecAngles, Vector *vecMove )
{
trace_t trace;
m_bWasDead = false;
// In item testing mode, we run custom logic
if ( TFGameRules()->IsInItemTestingMode() )
{
Bot_ItemTestingThink( vecAngles, vecMove );
return;
}
UpdatePlanForCommand();
Bot_AliveMovementThink( vecAngles, vecMove );
Bot_AliveWeaponThink( vecAngles, vecMove );
// Miscellaneous
if ( bot_saveme.GetInt() > 0 )
{
m_hBot->SaveMe();
bot_saveme.SetValue( bot_saveme.GetInt() - 1 );
}
}
//-----------------------------------------------------------------------------
// Purpose: Handle movement
//-----------------------------------------------------------------------------
void botdata_t::Bot_AliveMovementThink( QAngle *vecAngles, Vector *vecMove )
{
if ( m_hBot->IsEFlagSet(EFL_BOT_FROZEN) )
{
(*vecMove)[0] = 0;
(*vecMove)[1] = 0;
(*vecMove)[2] = 0;
return;
}
if ( bot_jump.GetBool() && m_hBot->GetFlags() & FL_ONGROUND )
{
buttons |= IN_JUMP;
}
if ( bot_crouch.GetBool() )
{
buttons |= IN_DUCK;
}
// If we don't have a faceto target, but we're moving to a waypoint, look at that.
Vector vecFaceTo = m_vecFaceToTarget;
if ( vecFaceTo == vec3_origin )
{
if ( m_hEnemy )
{
vecFaceTo = m_hEnemy->EyePosition();
}
else if ( GetCommandTarget() )
{
vecFaceTo = GetCommandTarget()->EyePosition();
}
else if ( HasPath() )
{
vecFaceTo = m_path[ m_iPathIndex ].pos;
vecFaceTo[2] = m_hBot->EyePosition()[2];
}
}
// Should we face something?
if ( vecFaceTo != vec3_origin )
{
Vector vecViewTarget = (vecFaceTo - m_hBot->EyePosition());
VectorNormalize(vecViewTarget);
QAngle vecTargetViewAngles;
VectorAngles( vecViewTarget, Vector(0,0,1), vecTargetViewAngles );
(*vecAngles)[YAW] = ApproachAngle( vecTargetViewAngles[YAW], (*vecAngles)[YAW], bot_nav_turnspeed.GetFloat() );
}
// Are we moving to a waypoint?
if ( HasPath() )
{
m_lastKnownArea = TheNavMesh->GetNavArea( m_hBot->GetAbsOrigin() );
if ( !UpdatePath() )
{
FinishCommand();
return;
}
if ( !m_Commands.Count() )
return;
float flDistance = bot_nav_wpdistance.GetFloat();
CBaseEntity *pTargetEnt = m_Commands[0].pTarget;
// We might run into our target entity earlier.
if ( CommandHasATarget() && ShouldFinishCommandOnArrival() )
{
float flEntDistance = pTargetEnt->BoundingRadius() + flDistance;
flEntDistance *= flEntDistance;
if ( (pTargetEnt->GetAbsOrigin() - m_hBot->GetAbsOrigin()).Length2DSqr() < flEntDistance )
{
ResetPath();
FinishCommand();
return;
}
}
// Have we reached the next waypoint?
flDistance *= flDistance;
if ( (m_path[ m_iPathIndex ].pos - m_hBot->GetAbsOrigin()).Length2DSqr() < flDistance )
{
AdvancePath();
}
else if ( bot_nav_simplifypaths.GetBool() )
{
// If we can see our next waypoint already, stop moving to this one
while ( m_iPathLength >= (m_iPathIndex+1) &&
m_iPathIndex < (m_iPathLength - 1) &&
m_hBot->FVisible( m_path[ m_iPathIndex+1 ].pos ) )
{
AdvancePath();
}
}
if ( bot_debug.GetInt() == 1 )
{
for ( int i = 0; i < m_iPathLength-1; i++ )
{
NDebugOverlay::Line( m_path[i].pos, m_path[i+1].pos, 0, i == m_iPathIndex ? 255 : 64, 0, true, 0.1 );
NDebugOverlay::Box( m_path[i].pos, -Vector(3,3,3), Vector(3,3,3), 0, i == m_iPathIndex ? 255 : 64, 0, 0, 0.1 );
}
}
Vector vecTarget = m_path[ m_iPathIndex ].pos;
Vector vecDesiredVelocity = (vecTarget - m_hBot->GetAbsOrigin());
if ( bot_nav_usefeelers.GetBool() && m_iPathIndex < (m_iPathLength - 1) )
{
Bot_AliveMovementThink_ExtendFeelers( vecAngles, vecMove, &vecDesiredVelocity );
}
flDistance = VectorNormalize( vecDesiredVelocity );
// If we're approaching our last waypoint, decelerate to the point.
if ( m_iPathLength == 1 )
{
float flDecelDistance = bot_nav_wpdeceldistance.GetFloat();
float flSpeed = MIN( m_hBot->MaxSpeed() * (flDistance / flDecelDistance), m_hBot->MaxSpeed() );
vecDesiredVelocity *= flSpeed;
}
else
{
vecDesiredVelocity *= m_hBot->MaxSpeed();
}
if ( bot_debug.GetInt() == 10 )
{
NDebugOverlay::HorzArrow( m_hBot->GetAbsOrigin(), m_hBot->GetAbsOrigin() + vecDesiredVelocity, 3, 255, 0, 0, 0, true, 0.1 );
}
// Convert the velocity into forward/sidemove
Vector vecForward, vecRight;
AngleVectors( *vecAngles, &vecForward, &vecRight, NULL );
(*vecMove)[0] = DotProduct( vecForward, vecDesiredVelocity );
(*vecMove)[1] = DotProduct( vecRight, vecDesiredVelocity );
}
}
//------------------------------------------------------------------------------------------------------------
#define COS_TABLE_SIZE 256
static float cosTable[ COS_TABLE_SIZE ];
static bool bBotTrigInitted = false;
void InitBotTrig( void )
{
if ( bBotTrigInitted )
return;
bBotTrigInitted = true;
for( int i=0; i<COS_TABLE_SIZE; ++i )
{
float angle = (float)(2.0f * M_PI * i / (float)(COS_TABLE_SIZE-1));
cosTable[i] = (float)cos( angle );
}
}
float BotCOS( float angle )
{
angle = AngleNormalizePositive( angle );
int i = (int)( angle * (COS_TABLE_SIZE-1) / 360.0f );
return cosTable[i];
}
float BotSIN( float angle )
{
angle = AngleNormalizePositive( angle - 90 );
int i = (int)( angle * (COS_TABLE_SIZE-1) / 360.0f );
return cosTable[i];
}
// Find "simple" ground height, treating current nav area as part of the floor
bool GetSimpleGroundHeightWithFloor( CNavArea *pArea, const Vector &pos, float *height, Vector *normal )
{
if (TheNavMesh->GetSimpleGroundHeight( pos, height, normal ))
{
// our current nav area also serves as a ground polygon
if ( pArea && pArea->IsOverlapping( pos ))
{
*height = MAX( (*height), pArea->GetZ( pos ) );
}
return true;
}
return false;
}
//--------------------------------------------------------------------------------------------------------------
// Purpose: Fire feelers out to either side and steer to avoid collisions
//--------------------------------------------------------------------------------------------------------------
void botdata_t::Bot_AliveMovementThink_ExtendFeelers( QAngle *vecAngles, Vector *vecMove, Vector *vecCurVelocity )
{
VectorNormalize( *vecCurVelocity );
float flForwardAngle = UTIL_VecToYaw( *vecCurVelocity );
Vector dir( BotCOS( flForwardAngle ), BotSIN( flForwardAngle ), 0.0f );
Vector lat( -dir.y, dir.x, 0.0f );
const float feelerOffset = 20.0f;
const float feelerLengthRun = 50.0f; // 100 - too long for tight hallways (cs_747)
const float feelerHeight = StepHeight + 0.1f; // if obstacle is lower than StepHeight, we'll walk right over it
// Feelers must follow floor slope
float ground;
Vector normal;
Vector eye = m_hBot->EyePosition();
if (GetSimpleGroundHeightWithFloor( m_lastKnownArea, eye, &ground, &normal ) == false)
return;
// get forward vector along floor
dir = CrossProduct( lat, normal );
// correct the sideways vector
lat = CrossProduct( dir, normal );
Vector feet = m_hBot->GetAbsOrigin();
feet.z += feelerHeight;
Vector from = feet + feelerOffset * lat;
Vector to = from + feelerLengthRun * dir;
bool leftClear = IsWalkableTraceLineClear( from, to, WALK_THRU_DOORS | WALK_THRU_BREAKABLES );
if ( bot_debug.GetInt() == 3 )
{
NDebugOverlay::Line( from, to, leftClear ? 0 : 255, leftClear ? 255 : 0, 0, true, 0.1 );
}
from = feet - feelerOffset * lat;
to = from + feelerLengthRun * dir;
bool rightClear = IsWalkableTraceLineClear( from, to, WALK_THRU_DOORS | WALK_THRU_BREAKABLES );
if ( bot_debug.GetInt() == 3 )
{
NDebugOverlay::Line( from, to, rightClear ? 0 : 255, rightClear ? 255 : 0, 0, true, 0.1 );
}
Vector vecDebug;
if ( bot_debug.GetInt() == 3 && (!leftClear || !rightClear) )
{
vecDebug = (*vecCurVelocity * 100);
NDebugOverlay::Line( m_hBot->GetAbsOrigin(), m_hBot->GetAbsOrigin() + vecDebug, 0, 0, 255, true, 0.1 );
}
const float avoidRange = 300.0f; // 50, 300
if (!rightClear)
{
if (leftClear)
{
// right hit, left clear - veer left
*vecCurVelocity = (*vecCurVelocity * avoidRange) + avoidRange * lat;
}
}
else if (!leftClear)
{
// right clear, left hit - veer right
*vecCurVelocity = (*vecCurVelocity * avoidRange) - avoidRange * lat;
}
if ( bot_debug.GetInt() == 3 && (!leftClear || !rightClear) )
{
vecDebug = (*vecCurVelocity);
VectorNormalize( vecDebug );
vecDebug *= 100;
NDebugOverlay::Line( m_hBot->GetAbsOrigin(), m_hBot->GetAbsOrigin() + vecDebug, 64, 64, 255, true, 0.1 );
}
}
//-----------------------------------------------------------------------------
// Purpose: Handle weapon switching / firing
//-----------------------------------------------------------------------------
void botdata_t::Bot_AliveWeaponThink( QAngle *vecAngles, Vector *vecMove )
{
if ( bot_selectweaponslot.GetInt() >= 0 )
{
int slot = bot_selectweaponslot.GetInt();
CBaseCombatWeapon *pWpn = m_hBot->Weapon_GetSlot( slot );
if ( pWpn )
{
m_hBot->Weapon_Switch( pWpn );
}
bot_selectweaponslot.SetValue( -1 );
}
const char *pszWeapon = bot_forcefireweapon.GetString();
if ( (pszWeapon && pszWeapon[0]) || g_pServerBenchmark->IsBenchmarkRunning() )
{
// If bots are being forced to fire a weapon, see if I have it
// Manually look through weapons to ignore subtype
CBaseCombatWeapon *pWeapon = NULL;
if ( g_pServerBenchmark->IsBenchmarkRunning() )
{
if ( !m_bChoseWeapon )
{
m_bChoseWeapon = true;
// Choose any weapon out of the available ones.
CUtlVector<CBaseCombatWeapon*> weapons;
for (int i=0;i<MAX_WEAPONS;i++)
{
if ( m_hBot->GetWeapon(i) )
{
weapons.AddToTail( m_hBot->GetWeapon( i ) );
}
}
if ( weapons.Count() > 0 )
{
pWeapon = weapons[ g_pServerBenchmark->RandomInt( 0, weapons.Count() - 1 ) ];
}
}
}
else
{
// Look for a specific weapon name here.
for (int i=0;i<MAX_WEAPONS;i++)
{
if ( m_hBot->GetWeapon(i) && FClassnameIs( m_hBot->GetWeapon(i), pszWeapon ) )
{
pWeapon = m_hBot->GetWeapon(i);
break;
}
}
}
if ( pWeapon )
{
// Switch to it if we don't have it out
CBaseCombatWeapon *pActiveWeapon = m_hBot->GetActiveWeapon();
// Switch?
if ( pActiveWeapon != pWeapon )
{
m_hBot->Weapon_Switch( pWeapon );
}
else
{
// Start firing
// Some weapons require releases, so randomise firing
if ( bot_forceattack_down.GetBool() || (g_pServerBenchmark->RandomFloat(0.0,1.0) > 0.5) )
{
buttons |= IN_ATTACK;
}
if ( bot_forceattack2.GetBool() )
{
buttons |= IN_ATTACK2;
}
}
}
}
if ( bot_forceattack.GetInt() )
{
if ( bot_forceattack_down.GetBool() || (g_pServerBenchmark->RandomFloat(0.0,1.0) > 0.5) )
{
buttons |= bot_forceattack2.GetBool() ? IN_ATTACK2 : IN_ATTACK;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Handle the Bot AI for a dead bot
//-----------------------------------------------------------------------------
void botdata_t::Bot_DeadThink( QAngle *vecAngles, Vector *vecMove )
{
// Wait for Reinforcement wave
if ( !m_hBot->IsAlive() )
{
if ( m_bWasDead )
{
// Wait for a few seconds before respawning.
if ( gpGlobals->curtime - m_flDeadTime > 3 )
{
// Respawn the bot
buttons |= IN_JUMP;
}
}
else
{
// Start a timer to respawn them in a few seconds.
m_bWasDead = true;
m_flDeadTime = gpGlobals->curtime;
}
}
}
//------------------------------------------------------------------------------
// Purpose: sends the specified command from a bot
//------------------------------------------------------------------------------
void cc_bot_sendcommand( const CCommand &args )
{
CUtlVector< CTFPlayer* > botVector;
GetBotsFromCommand( args, 3, "Usage: bot_command <bot name> <command string...>", &botVector );
if ( botVector.IsEmpty() )
return;
const char *commandline = args.GetCommandString();
// find the rest of the command line past the bot index
commandline = strstr( commandline, args[2] );
Assert( commandline );
int iSize = Q_strlen(commandline) + 1;
char *pBuf = (char *)malloc(iSize);
Q_snprintf( pBuf, iSize, "%s", commandline );
if ( pBuf[iSize-2] == '"' )
{
pBuf[iSize-2] = '\0';
}
// make a command object with the intended command line
CCommand command;
command.Tokenize( pBuf );
// send the command
FOR_EACH_VEC( botVector, i )
{
TFGameRules()->ClientCommand( botVector[i], command );
}
}
static ConCommand bot_sendcommand( "bot_command", cc_bot_sendcommand, "<bot id> <command string...>. Sends specified command on behalf of specified bot", FCVAR_CHEAT );
//------------------------------------------------------------------------------
// Purpose: Kill the specified bot
//------------------------------------------------------------------------------
void cc_bot_kill( const CCommand &args )
{
CUtlVector< CTFPlayer* > botVector;
GetBotsFromCommand( args, 2, "Usage: bot_kill <bot name>", &botVector );
if ( botVector.IsEmpty() )
return;
FOR_EACH_VEC( botVector, i )
{
botVector[i]->CommitSuicide();
}
}
static ConCommand bot_kill( "bot_kill", cc_bot_kill, "Kills a bot. Usage: bot_kill <bot name>", FCVAR_CHEAT );
//------------------------------------------------------------------------------
// Purpose: Force all bots to swap teams
//------------------------------------------------------------------------------
CON_COMMAND_F( bot_changeteams, "Make all bots change teams", FCVAR_CHEAT )
{
for ( int i = 1; i <= gpGlobals->maxClients; i++ )
{
CTFPlayer *pPlayer = ToTFPlayer( UTIL_PlayerByIndex( i ) );
if ( isTempBot( pPlayer ) )
{
int iTeam = pPlayer->GetTeamNumber();
if ( TF_TEAM_BLUE == iTeam || TF_TEAM_RED == iTeam )
{
// toggle team between red & blue
pPlayer->ChangeTeam( TF_TEAM_BLUE + TF_TEAM_RED - iTeam );
}
}
}
}
//------------------------------------------------------------------------------
// Purpose: Refill all bot ammo counts
//------------------------------------------------------------------------------
CON_COMMAND_F( bot_refill, "Refill all bot ammo counts", FCVAR_CHEAT )
{
for ( int i = 1; i <= gpGlobals->maxClients; i++ )
{
CTFPlayer *pPlayer = ToTFPlayer( UTIL_PlayerByIndex( i ) );
if ( isTempBot( pPlayer ) )
{
pPlayer->GiveAmmo( 1000, TF_AMMO_PRIMARY );
pPlayer->GiveAmmo( 1000, TF_AMMO_SECONDARY );
pPlayer->GiveAmmo( 1000, TF_AMMO_METAL );
pPlayer->TakeHealth( 999, DMG_GENERIC );
}
}
}
//------------------------------------------------------------------------------
// Purpose: Deliver lethal damage from the player to the specified bot
//------------------------------------------------------------------------------
CON_COMMAND_F( bot_whack, "Deliver lethal damage from player to specified bot. Usage: bot_whack <bot name>", FCVAR_CHEAT )
{
CUtlVector< CTFPlayer* > botVector;
GetBotsFromCommand( args, 2, "Usage: bot_whack <bot name>", &botVector );
if ( botVector.IsEmpty() )
return;
CTFPlayer *pTFPlayer = ToTFPlayer( UTIL_GetCommandClient() );
FOR_EACH_VEC( botVector, i )
{
CTakeDamageInfo info( botVector[i], pTFPlayer, 1000, DMG_BULLET );
info.SetInflictor( pTFPlayer->GetActiveTFWeapon() );
botVector[i]->TakeDamage( info );
}
}
//------------------------------------------------------------------------------
// Purpose: Force the specified bot to teleport to the specified position
//------------------------------------------------------------------------------
CON_COMMAND_F( bot_teleport, "Teleport the specified bot to the specified position & angles.\n\tFormat: bot_teleport <bot name> <X> <Y> <Z> <Pitch> <Yaw> <Roll>", FCVAR_CHEAT )
{
CUtlVector< CTFPlayer* > botVector;
GetBotsFromCommand( args, 8, "Usage: bot_teleport <bot name> <X> <Y> <Z> <Pitch> <Yaw> <Roll>", &botVector );
if ( botVector.IsEmpty() )
return;
Vector vecPos( atof(args[2]), atof(args[3]), atof(args[4]) );
QAngle vecAng( atof(args[5]), atof(args[6]), atof(args[7]) );
FOR_EACH_VEC( botVector, i )
{
botVector[i]->Teleport( &vecPos, &vecAng, NULL );
}
}
//------------------------------------------------------------------------------
// Purpose: Force the specified bot to create & equip an item
//------------------------------------------------------------------------------
void BotGenerateAndWearItem( CTFPlayer *pBot, const char *itemName )
{
if ( !pBot )
return;
CItemSelectionCriteria criteria;
criteria.SetItemLevel( AE_USE_SCRIPT_VALUE );
criteria.SetQuality( AE_USE_SCRIPT_VALUE );
criteria.BAddCondition( "name", k_EOperator_String_EQ, itemName, true );
CBaseEntity *pItem = ItemGeneration()->GenerateRandomItem( &criteria, pBot->GetAbsOrigin(), vec3_angle );
if ( pItem )
{
// If it's a weapon, remove the current one, and give us this one.
CBaseEntity *pExisting = pBot->Weapon_OwnsThisType(pItem->GetClassname());
if ( pExisting )
{
CBaseCombatWeapon *pWpn = dynamic_cast<CBaseCombatWeapon *>(pExisting);
pBot->Weapon_Detach( pWpn );
UTIL_Remove( pExisting );
}
// Fake global id
static int s_nFakeID = 1;
static_cast<CEconEntity*>(pItem)->GetAttributeContainer()->GetItem()->SetItemID( s_nFakeID++ );
DispatchSpawn( pItem );
static_cast<CEconEntity*>(pItem)->GiveTo( pBot );
pBot->PostInventoryApplication();
}
else
{
#ifdef STAGING_ONLY
extern ConVar tf_bot_use_items;
if ( !tf_bot_use_items.GetInt() )
#endif
{
Msg( "Failed to create an item named %s\n", itemName );
}
}
}
void BotGenerateAndWearItem( CTFPlayer *pBot, CEconItemView *pItem )
{
int iClass = pBot->GetPlayerClass()->GetClassIndex();
int iItemSlot = pItem->GetStaticData()->GetLoadoutSlot( iClass );
CTFWeaponBase *pWeapon = dynamic_cast<CTFWeaponBase*>( pBot->GetEntityForLoadoutSlot( iItemSlot ) );
// we need to force translating the name here.
// GiveNamedItem will not translate if we force creating the item
const char *pTranslatedWeaponName = TranslateWeaponEntForClass( pItem->GetStaticData()->GetItemClass(), iClass );
CTFWeaponBase *pNewItem = dynamic_cast<CTFWeaponBase*>( pBot->GiveNamedItem( pTranslatedWeaponName, 0, pItem, true ) );
if ( pNewItem )
{
CTFWeaponBuilder *pBuilder = dynamic_cast<CTFWeaponBuilder*>( (CBaseEntity*)pNewItem );
if ( pBuilder )
{
pBuilder->SetSubType( pBot->GetPlayerClass()->GetData()->m_aBuildable[0] );
}
// make sure we removed our current weapon
if ( pWeapon )
{
pBot->Weapon_Detach( pWeapon );
UTIL_Remove( pWeapon );
}
pNewItem->MarkAttachedEntityAsValidated();
pNewItem->GiveTo( pBot );
}
else
{
BotGenerateAndWearItem( pBot, pItem->GetItemDefinition()->GetDefinitionName() );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void BotMirrorPlayerClassAndItems( CTFPlayer *pBot, CTFPlayer *pPlayer )
{
if ( !pBot || !pPlayer )
return;
// Force them to be our class
if ( pPlayer->GetPlayerClass()->GetClassIndex() != pBot->GetPlayerClass()->GetClassIndex() )
{
pBot->AllowInstantSpawn();
pBot->HandleCommand_JoinClass( pPlayer->GetPlayerClass()->GetName() );
}
int nLastSlot = LOADOUT_POSITION_MISC2;
#ifdef STAGING_ONLY
//nLastSlot = LOADOUT_POSITION_MISC10;
#endif // STAGING_ONLY
pBot->RemoveAllItems( false );
for ( int i = 0; i <= nLastSlot; ++i )
{
CEconItemView *pPlayerItem = pPlayer->GetLoadoutItem( pPlayer->GetPlayerClass()->GetClassIndex(), i );
if ( !pPlayerItem )
continue;
BotGenerateAndWearItem( pBot, pPlayerItem );
}
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
CON_COMMAND_F( bot_mirror, "Forces the specified bot to be the same class, and use the same items, as you.", FCVAR_CHEAT )
{
CTFPlayer *pTFPlayer = ToTFPlayer( UTIL_GetCommandClient() );
if ( !pTFPlayer )
return;
CUtlVector< CTFPlayer* > botVector;
GetBotsFromCommand( args, 2, "Usage: bot_mirror <bot name>, or bot_mirror all", &botVector );
FOR_EACH_VEC( botVector, i )
{
BotMirrorPlayerClassAndItems( botVector[i], pTFPlayer );
}
}
#ifdef STAGING_ONLY
//------------------------------------------------------------------------------
// Purpose: Force the specified bot to create & equip an item
//------------------------------------------------------------------------------
void cc_bot_equip( const CCommand &args )
{
CUtlVector< CTFPlayer* > botVector;
GetBotsFromCommand( args, 3, "Usage: bot_equip <bot name> <item name>", &botVector );
FOR_EACH_VEC( botVector, i )
{
BotGenerateAndWearItem( botVector[i], args[2] );
}
}
static ConCommand bot_equip("bot_equip", cc_bot_equip, "Generate an item and have the bot equip it.\n\tFormat: bot_equip <bot name> <item name>", FCVAR_CHEAT );
//------------------------------------------------------------------------------
// Purpose: Force the specified bot to disguise themselves. Needed because the disguise command is clientside.
//------------------------------------------------------------------------------
void cc_bot_disguise( const CCommand &args )
{
CUtlVector< CTFPlayer* > botVector;
GetBotsFromCommand( args, 4, "Usage: bot_disguise <bot name> <team> <class>", &botVector );
FOR_EACH_VEC( botVector, i )
{
if ( botVector[i]->CanDisguise() )
{
// intercepting the team value and reassigning what gets passed into Disguise()
// because the team numbers in the client menu don't match the #define values for the teams
botVector[i]->m_Shared.Disguise( Q_atoi( args[2] ), Q_atoi( args[3] ) );
}
}
}
static ConCommand bot_disguise("bot_disguise", cc_bot_disguise, "Force the specified bot to disguise themselves.\n\tFormat: bot_disguise <bot name> <team> <class>", FCVAR_CHEAT );
//------------------------------------------------------------------------------
// Purpose: Force the specified bot to taunt with specific taunt name
//------------------------------------------------------------------------------
void cc_bot_taunt( const CCommand &args )
{
CUtlVector< CTFPlayer* > botVector;
GetBotsFromCommand( args, 3, "Usage: bot_taunt <bot name> <taunt_name>", &botVector );
if ( botVector.IsEmpty() )
return;
const char *pszTauntName = args.ArgS() + V_strlen( args[1] ) + 1;
CEconItemDefinition *pItemDef = ItemSystem()->GetStaticDataForItemByName( pszTauntName );
if ( !pItemDef )
{
Msg( "bot_taunt: failed to find taunt name <%s>\n", pszTauntName );
return;
}
static CEconItemView item;
item.SetItemDefIndex( pItemDef->GetDefinitionIndex() );
item.SetItemQuality( pItemDef->GetQuality() );
item.SetInitialized( true );
FOR_EACH_VEC( botVector, i )
{
botVector[i]->PlayTauntSceneFromItem( &item );
}
}
static ConCommand bot_taunt("bot_taunt", cc_bot_taunt, "Force the specified bot to taunt with specific taunt name.\n\tFormat: bot_taunt <bot name> <taunt_name>", FCVAR_CHEAT );
#endif // STAGING_ONLY
//------------------------------------------------------------------------------
// Purpose: Force the specified bot to select a weapon in the specified slot
//------------------------------------------------------------------------------
CON_COMMAND_F( cc_bot_selectweapon, "Force a bot to select a weapon in a slot. Usage: bot_selectweapon <bot name> <weapon slot>", FCVAR_CHEAT )
{
CUtlVector< CTFPlayer* > botVector;
GetBotsFromCommand( args, 3, "Usage: bot_selectweapon <bot name> <weapon slot>", &botVector );
if ( botVector.IsEmpty() )
return;
int slot = atoi( args[2] );
FOR_EACH_VEC( botVector, i )
{
CBaseCombatWeapon *pWpn = botVector[i]->Weapon_GetSlot( slot );
if ( pWpn )
{
botVector[i]->Weapon_Switch( pWpn );
}
}
}
//------------------------------------------------------------------------------
// Purpose: Force the specified bot to drop all his gear.
//------------------------------------------------------------------------------
CON_COMMAND_F( bot_drop, "Force the specified bot to drop his active weapon. Usage: bot_drop <bot name>", FCVAR_CHEAT )
{
CUtlVector< CTFPlayer* > botVector;
GetBotsFromCommand( args, 2, "Usage: bot_drop <bot name>", &botVector );
FOR_EACH_VEC( botVector, i )
{
CBaseCombatWeapon* pWpn = botVector[i]->GetActiveWeapon();
if ( pWpn )
{
UTIL_Remove( pWpn );
}
}
}
//------------------------------------------------------------------------------
// Purpose: Force the specified bot to move to the point under your crosshair
//------------------------------------------------------------------------------
CON_COMMAND_F( bot_moveto, "Force the specified bot to move to the point under your crosshair. Usage: bot_moveto <bot name>", FCVAR_CHEAT )
{
CUtlVector< CTFPlayer* > botVector;
GetBotsFromCommand( args, 2, "Usage: bot_moveto <bot name>", &botVector );
if ( botVector.IsEmpty() )
return;
CBasePlayer *pPlayer = UTIL_GetCommandClient();
trace_t tr;
Vector forward;
pPlayer->EyeVectors( &forward );
UTIL_TraceLine( pPlayer->EyePosition(), pPlayer->EyePosition() + forward * MAX_TRACE_LENGTH,MASK_SOLID, pPlayer, COLLISION_GROUP_NONE, &tr );
if ( tr.fraction != 1.0 )
{
FOR_EACH_VEC( botVector, i )
{
botdata_t *botdata = BotData( botVector[i] );
botdata->FindPathTo( tr.endpos );
}
}
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
bool botdata_t::FindPathTo( Vector vecTarget )
{
m_flRecomputePathAt = gpGlobals->curtime + bot_nav_recomputetime.GetFloat();
m_vecLastPathTarget = vecTarget;
ShortestPathCost cost;
CNavArea *pCurrentArea = TheNavMesh->GetNavArea( m_hBot->GetAbsOrigin() );
if ( !pCurrentArea )
{
Warning( "Bot '%s' not on the nav mesh.\n", m_hBot->GetPlayerName() );
return false;
}
CNavArea *pTargetArea = TheNavMesh->GetNavArea( vecTarget );
if ( !pTargetArea )
{
Warning( "Bot '%s' tried to move to a point that isn't on the nav mesh (%.2f %.2f %.2f).\n", m_hBot->GetPlayerName(), vecTarget.x, vecTarget.y, vecTarget.z );
return false;
}
// If the path stays within a single area, build a single waypoint and we're done.
if ( pTargetArea == pCurrentArea )
{
m_path[0].pos = vecTarget;
m_path[0].area = pCurrentArea;
m_path[0].how = NUM_TRAVERSE_TYPES;
m_iPathLength = 1;
m_iPathIndex = 0;
return true;
}
if ( NavAreaBuildPath( pCurrentArea, pTargetArea, &vecTarget, cost ) == false )
{
Warning( "Bot '%s' couldn't find a path from nav mesh %d to nav mesh %d.\n", m_hBot->GetPlayerName(), pCurrentArea->GetID(), pTargetArea->GetID() );
return false;
}
m_iPathIndex = 0;
// Count the number of areas in the path
int count = 0;
CNavArea *area;
for( area = pTargetArea; area; area = area->GetParent() )
{
++count;
}
bool bUseOffsetPaths = bot_nav_useoffsetpaths.GetBool();
if ( bUseOffsetPaths )
{
count = (count * 2) - 1;
}
m_iPathLength = count;
// Move the areas into our path
for( area = pTargetArea; count && area; area = area->GetParent() )
{
--count;
m_path[ count ].area = area;
m_path[ count ].how = area->GetParentHow();
m_path[ count ].flOffset = bUseOffsetPaths ? -bot_nav_offsetpathinset.GetFloat() : 0;
if ( bUseOffsetPaths && count >= 1 )
{
--count;
m_path[ count ].area = m_path[ count+1 ].area;
m_path[ count ].how = m_path[ count+1 ].how;
m_path[ count ].flOffset = m_path[ count+1 ].flOffset * -1;
}
}
if ( !ComputePathPositions() )
{
ResetPath();
return false;
}
// append path end position
m_path[ m_iPathLength ].area = pTargetArea;
m_path[ m_iPathLength ].pos = vecTarget;
m_path[ m_iPathLength ].how = NUM_TRAVERSE_TYPES;
m_path[ m_iPathLength ].flOffset = 0;
++m_iPathLength;
return true;
}
//------------------------------------------------------------------------------
// Purpose: Given a path of areas, compute waypoints along the path
//------------------------------------------------------------------------------
bool botdata_t::ComputePathPositions( void )
{
if (m_iPathLength == 0)
return false;
m_path[0].pos = m_hBot->GetAbsOrigin();//m_path[0].area->GetCenter();
m_path[0].how = NUM_TRAVERSE_TYPES;
for( int i=1; i<m_iPathLength; ++i )
{
const ConnectInfo *from = &m_path[ i-1 ];
ConnectInfo *to = &m_path[ i ];
Vector vecFrom = from->pos;
if ( to->flOffset < 0 && i >= 2 )
{
from = &m_path[ i-2 ];
}
from->area->ComputeClosestPointInPortal( to->area, (NavDirType)to->how, from->pos, &to->pos );
to->pos.z = from->area->GetZ( to->pos );
if ( to->flOffset )
{
// Create a waypoint just inside our current area
AddDirectionVector( &to->pos, (NavDirType)to->how, -to->flOffset );
}
if ( bot_debug.GetInt() == 2 )
{
NDebugOverlay::HorzArrow( vecFrom, to->pos, 3, 0, 96, 0, 0, true, 10.0 );
}
}
return true;
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
bool botdata_t::UpdatePath( void )
{
// If we're going to an entity, make sure it hasn't moved.
if ( CommandHasATarget() )
{
if ( m_flRecomputePathAt < gpGlobals->curtime && m_Commands[0].pTarget )
{
Vector vecNewTarget = m_Commands[0].pTarget->GetAbsOrigin();
if ( (m_vecLastPathTarget - vecNewTarget).LengthSqr() > (50 * 50) )
return FindPathTo( vecNewTarget );
}
}
return true;
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void botdata_t::UpdatePlanForCommand( void )
{
if ( !m_Commands.Count() )
return;
if ( !m_bStartedCommand )
{
StartNewCommand();
m_bStartedCommand = true;
}
switch ( m_Commands[0].iCommand )
{
case BC_ATTACK:
{
RunAttackPlan();
}
break;
case BC_MOVETO_ENTITY:
{
if ( !HasPath() )
{
if ( FindPathTo( m_Commands[0].pTarget->GetAbsOrigin() ) == false )
{
FinishCommand();
}
}
}
break;
case BC_MOVETO_POINT:
{
if ( !HasPath() )
{
if ( FindPathTo( GetCommandPosition() ) == false )
{
FinishCommand();
}
}
}
break;
case BC_SWITCH_WEAPON:
{
CBaseCombatWeapon *pWpn = m_hBot->Weapon_GetSlot( (int)m_Commands[0].flData );
if ( pWpn )
{
m_hBot->Weapon_Switch( pWpn );
}
FinishCommand();
}
break;
case BC_DEFEND:
{
RunDefendPlan();
}
break;
default:
break;
}
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void botdata_t::RunAttackPlan( void )
{
CBaseEntity *pEnt = GetCommandTarget();
if ( !pEnt )
return;
if ( !pEnt->IsAlive() )
{
FinishCommand();
return;
}
bool bCanSeeTarget = m_hBot->FVisible( pEnt );
bool bNeedsAPath = !bCanSeeTarget;
if ( bCanSeeTarget )
{
float flDistance = (pEnt->GetAbsOrigin() - m_hBot->GetAbsOrigin()).LengthSqr();
// If it's a melee weapon, we need to close. Otherwise, stay at a nice looking distance.
if ( m_hBot->GetActiveTFWeapon() && m_hBot->GetActiveTFWeapon()->IsMeleeWeapon() )
{
float flRange = bot_com_meleerange.GetFloat();
flRange *= flRange;
bNeedsAPath = ( flDistance > flRange );
if ( !bNeedsAPath )
{
buttons |= IN_ATTACK;
}
}
else
{
float flRange = bot_com_wpnrange.GetFloat();
flRange *= flRange;
bNeedsAPath = ( flDistance > (500 * 500) );
buttons |= IN_ATTACK;
}
}
if ( bNeedsAPath && !HasPath() )
{
if ( FindPathTo( m_Commands[0].pTarget->GetAbsOrigin() ) == false )
{
FinishCommand();
return;
}
}
else if ( !bNeedsAPath && HasPath() )
{
ResetPath();
}
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void botdata_t::RunDefendPlan( void )
{
if ( bot_debug.GetInt() == 5 )
{
NDebugOverlay::Line( m_hBot->GetAbsOrigin(), GetCommandPosition(), 0, 128, 0, true, 0.1 );
}
if ( !FindEnemyTarget() )
{
if ( !HasPath() )
{
// If we're far from our defend point, move back to it.
float flDistance = (GetCommandPosition() - m_hBot->GetAbsOrigin()).LengthSqr();
if ( flDistance > (32*32) )
{
if ( FindPathTo( GetCommandPosition() ) == false )
{
// Can't get back to our defend position
FinishCommand();
return;
}
}
}
return;
}
Assert( m_hEnemy.Get() );
if ( bot_debug.GetInt() == 5 )
{
NDebugOverlay::Line( m_hBot->GetAbsOrigin(), m_hEnemy->GetAbsOrigin(), 255, 0, 0, true, 0.1 );
}
// We've got an enemy.
float flDefendRange = m_Commands[0].flData * m_Commands[0].flData;
float flDistanceToEnemy = (m_hEnemy->GetAbsOrigin() - m_hBot->GetAbsOrigin()).LengthSqr();
float flDistanceToEnemyFromDefend = (m_hEnemy->GetAbsOrigin() - GetCommandPosition()).LengthSqr();
bool bNeedsAPath = false;
// If it's a melee weapon, we need to close. Otherwise, stay at a nice looking distance.
if ( m_hBot->GetActiveTFWeapon() && m_hBot->GetActiveTFWeapon()->IsMeleeWeapon() )
{
// We can only close if we're allowed to move to the target's distance.
if ( flDistanceToEnemyFromDefend <= flDefendRange )
{
float flRange = bot_com_meleerange.GetFloat();
flRange *= flRange;
bNeedsAPath = ( flDistanceToEnemy > flRange );
if ( !bNeedsAPath )
{
buttons |= IN_ATTACK;
}
}
}
else
{
buttons |= IN_ATTACK;
}
if ( bNeedsAPath && !HasPath() )
{
FindPathTo( m_hEnemy->GetAbsOrigin() );
}
else if ( !bNeedsAPath && HasPath() )
{
ResetPath();
}
}
//-----------------------------------------------------------------------------
// Purpose: Look for a target
//-----------------------------------------------------------------------------
bool botdata_t::FindEnemyTarget( void )
{
Vector vecEyePosition = m_hBot->EyePosition();
// find the enemy team
int iEnemyTeam = ( m_hBot->GetTeamNumber() == TF_TEAM_BLUE ) ? TF_TEAM_RED : TF_TEAM_BLUE;
CTFTeam *pTeam = TFTeamMgr()->GetTeam( iEnemyTeam );
if ( !pTeam )
return false;
// If we have an enemy get his minimum distance to check against.
Vector vecSegment;
Vector vecTargetCenter;
float flMinDist2 = bot_com_viewrange.GetFloat();
flMinDist2 *= flMinDist2;
CBaseEntity *pTargetCurrent = NULL;
CBaseEntity *pTargetOld = m_hEnemy;
float flOldTargetDist2 = FLT_MAX;
// Try to target players first, then objects. However, if the enemy held was an object it will continue
// to try and attack it first.
int nTeamCount = pTeam->GetNumPlayers();
for ( int iPlayer = 0; iPlayer < nTeamCount; ++iPlayer )
{
CTFPlayer *pTargetPlayer = static_cast<CTFPlayer*>( pTeam->GetPlayer( iPlayer ) );
if ( pTargetPlayer == NULL )
continue;
// Make sure the player is alive.
if ( !pTargetPlayer->IsAlive() )
continue;
if ( pTargetPlayer->GetFlags() & FL_NOTARGET )
continue;
vecTargetCenter = pTargetPlayer->GetAbsOrigin();
vecTargetCenter += pTargetPlayer->GetViewOffset();
VectorSubtract( vecTargetCenter, vecEyePosition, vecSegment );
float flDist2 = vecSegment.LengthSqr();
// Check to see if the target is closer than the already validated target.
if ( flDist2 > flMinDist2 )
continue;
// It is closer, check to see if the target is valid.
if ( ValidTargetPlayer( pTargetPlayer, vecEyePosition, vecTargetCenter ) )
{
flMinDist2 = flDist2;
pTargetCurrent = pTargetPlayer;
// Store the current target distance if we come across it
if ( pTargetPlayer == pTargetOld )
{
flOldTargetDist2 = flDist2;
}
}
}
// If we already have a target, don't check objects.
if ( pTargetCurrent == NULL )
{
int nTeamObjectCount = pTeam->GetNumObjects();
for ( int iObject = 0; iObject < nTeamObjectCount; ++iObject )
{
CBaseObject *pTargetObject = pTeam->GetObject( iObject );
if ( !pTargetObject )
continue;
vecTargetCenter = pTargetObject->GetAbsOrigin();
vecTargetCenter += pTargetObject->GetViewOffset();
VectorSubtract( vecTargetCenter, vecEyePosition, vecSegment );
float flDist2 = vecSegment.LengthSqr();
// Store the current target distance if we come across it
if ( pTargetObject == pTargetOld )
{
flOldTargetDist2 = flDist2;
}
// Check to see if the target is closer than the already validated target.
if ( flDist2 > flMinDist2 )
continue;
// It is closer, check to see if the target is valid.
if ( ValidTargetObject( pTargetObject, vecEyePosition, vecTargetCenter ) )
{
flMinDist2 = flDist2;
pTargetCurrent = pTargetObject;
}
}
}
// We have a target.
if ( pTargetCurrent )
{
if ( pTargetCurrent != pTargetOld )
{
// flMinDist2 is the new target's distance
// flOldTargetDist2 is the old target's distance
// Don't switch unless the new target is closer by some percentage
if ( flMinDist2 < ( flOldTargetDist2 * 0.75f ) )
{
m_hEnemy = pTargetCurrent;
}
}
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool botdata_t::ValidTargetPlayer( CTFPlayer *pPlayer, const Vector &vecStart, const Vector &vecEnd )
{
if ( m_bIgnoreHumans && !pPlayer->IsFakeClient() )
return false;
// Keep shooting at spies that go invisible after we acquire them as a target.
if ( pPlayer->m_Shared.GetPercentInvisible() > 0.5 )
return false;
// Keep shooting at spies that disguise after we acquire them as at a target.
if ( pPlayer->m_Shared.InCond( TF_COND_DISGUISED ) && pPlayer->m_Shared.GetDisguiseTeam() == m_hBot->GetTeamNumber() && pPlayer != m_hEnemy )
return false;
// Not across water boundary.
if ( ( m_hBot->GetWaterLevel() == 0 && pPlayer->GetWaterLevel() >= 3 ) || ( m_hBot->GetWaterLevel() == 3 && pPlayer->GetWaterLevel() <= 0 ) )
return false;
// Ray trace!!!
return m_hBot->FVisible( pPlayer, MASK_SHOT | CONTENTS_GRATE );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool botdata_t::ValidTargetObject( CBaseObject *pObject, const Vector &vecStart, const Vector &vecEnd )
{
// Ignore objects being placed, they are not real objects yet.
if ( pObject->IsPlacing() )
return false;
// Ignore sappers.
if ( pObject->MustBeBuiltOnAttachmentPoint() )
return false;
// Not across water boundary.
if ( ( m_hBot->GetWaterLevel() == 0 && pObject->GetWaterLevel() >= 3 ) || ( m_hBot->GetWaterLevel() == 3 && pObject->GetWaterLevel() <= 0 ) )
return false;
if ( pObject->GetObjectFlags() & OF_DOESNT_HAVE_A_MODEL )
return false;
// Ray trace.
return m_hBot->FVisible( pObject, MASK_SHOT | CONTENTS_GRATE );
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void botdata_t::StartNewCommand( void )
{
switch ( m_Commands[0].iCommand )
{
case BC_DEFEND:
{
// Mark our current position as the point we're defending
m_Commands[0].vecTarget = m_hBot->GetAbsOrigin();
}
break;
case BC_ATTACK:
case BC_MOVETO_ENTITY:
case BC_MOVETO_POINT:
case BC_SWITCH_WEAPON:
default:
break;
}
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void botdata_t::FinishCommand( void )
{
if ( m_Commands.Count() > 0 )
{
m_hBotController->m_outputOnCommandFinished.FireOutput( m_hBot, m_hBot );
m_Commands.Remove(0);
}
m_bStartedCommand = false;
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void botdata_t::AddAttackCommand( CBaseEntity *pTarget )
{
int iIndex = m_Commands.AddToTail();
m_Commands[iIndex].iCommand = BC_ATTACK;
m_Commands[iIndex].pTarget = pTarget;
m_Commands[iIndex].vecTarget = vec3_origin;
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void botdata_t::AddMoveToCommand( CBaseEntity *pTarget, Vector vecTarget )
{
int iIndex = m_Commands.AddToTail();
m_Commands[iIndex].iCommand = pTarget ? BC_MOVETO_ENTITY : BC_MOVETO_POINT;
m_Commands[iIndex].pTarget = pTarget;
m_Commands[iIndex].vecTarget = vecTarget;
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void botdata_t::AddSwitchWeaponCommand( int iSlot )
{
int iIndex = m_Commands.AddToTail();
m_Commands[iIndex].iCommand = BC_SWITCH_WEAPON;
m_Commands[iIndex].flData = iSlot;
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void botdata_t::AddDefendCommand( float flRange )
{
int iIndex = m_Commands.AddToTail();
m_Commands[iIndex].iCommand = BC_DEFEND;
m_Commands[iIndex].flData = flRange;
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void botdata_t::ClearQueue( void )
{
FinishCommand();
m_Commands.Purge();
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
bool botdata_t::RunningMovementCommand( void )
{
if ( m_Commands.Count() )
return ( m_Commands[0].iCommand == BC_MOVETO_ENTITY || m_Commands[0].iCommand == BC_MOVETO_POINT );
return false;
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
bool botdata_t::CommandHasATarget( void )
{
return ( m_Commands.Count() && (m_Commands[0].iCommand == BC_MOVETO_ENTITY || m_Commands[0].iCommand == BC_ATTACK) );
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
bool botdata_t::ShouldFinishCommandOnArrival( void )
{
return ( m_Commands.Count() && (m_Commands[0].iCommand == BC_MOVETO_ENTITY || m_Commands[0].iCommand == BC_MOVETO_POINT) );
}
//-----------------------------------------------------------------------------
// Purpose: Handle movement
//-----------------------------------------------------------------------------
void botdata_t::Bot_ItemTestingThink( QAngle *vecAngles, Vector *vecMove )
{
switch ( TFGameRules()->ItemTesting_GetBotAnim() )
{
default:
case TI_BOTANIM_IDLE:
break;
case TI_BOTANIM_CROUCH:
buttons |= IN_DUCK;
break;
case TI_BOTANIM_RUN:
break;
case TI_BOTANIM_CROUCH_WALK:
buttons |= IN_DUCK;
break;
case TI_BOTANIM_JUMP:
if ( m_hBot->GetFlags() & FL_ONGROUND )
{
buttons |= IN_JUMP;
}
break;
}
if ( TFGameRules()->ItemTesting_GetBotForceFire() )
{
// Hack to make them not fire faster than the anims being played?
//if ( !m_hBot->GetAnimState()->IsGestureSlotActive( GESTURE_SLOT_ATTACK_AND_RELOAD ) )
buttons |= IN_ATTACK;
}
if ( TFGameRules()->ItemTesting_GetBotTurntable() )
{
(*vecAngles)[YAW] += (1.0f * TFGameRules()->ItemTesting_GetBotAnimSpeed());
if ( (*vecAngles)[YAW] > 360 )
{
(*vecAngles)[YAW] = 0;
}
}
(*vecMove)[0] = 0;
(*vecMove)[1] = 0;
(*vecMove)[2] = 0;
}
//===================================================================================================================
// Purpose: Mapmaker bot control entity. Used by mapmakers to add & script bot behaviors.
BEGIN_DATADESC( CTFBotController )
DEFINE_KEYFIELD( m_iszBotName, FIELD_STRING, "bot_name" ),
DEFINE_KEYFIELD( m_iBotClass, FIELD_INTEGER, "bot_class" ),
DEFINE_INPUTFUNC( FIELD_VOID, "CreateBot", InputCreateBot ),
DEFINE_INPUTFUNC( FIELD_VOID, "RespawnBot", InputRespawnBot ),
DEFINE_INPUTFUNC( FIELD_STRING, "AddCommandMoveToEntity", InputBotAddCommandMoveToEntity ),
DEFINE_INPUTFUNC( FIELD_STRING, "AddCommandAttackEntity", InputBotAddCommandAttackEntity ),
DEFINE_INPUTFUNC( FIELD_INTEGER, "AddCommandSwitchWeapon", InputBotAddCommandSwitchWeapon ),
DEFINE_INPUTFUNC( FIELD_FLOAT, "AddCommandDefend", InputBotAddCommandDefend ),
DEFINE_INPUTFUNC( FIELD_INTEGER, "SetIgnoreHumans", InputBotSetIgnoreHumans ),
DEFINE_INPUTFUNC( FIELD_VOID, "PreventMovement", InputBotPreventMovement ),
DEFINE_INPUTFUNC( FIELD_VOID, "ClearQueue", InputBotClearQueue ),
DEFINE_OUTPUT( m_outputOnCommandFinished, "OnCommandFinished" ),
END_DATADESC()
LINK_ENTITY_TO_CLASS( bot_controller, CTFBotController );
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CTFBotController::InputCreateBot( inputdata_t &inputdata )
{
m_hBot = ToTFPlayer( BotPutInServer( false, false, GetTeamNumber(), m_iBotClass ? m_iBotClass : TF_CLASS_RANDOM, STRING(m_iszBotName) ) );
if ( m_hBot )
{
BotData(m_hBot)->m_hBotController = this;
}
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CTFBotController::InputRespawnBot( inputdata_t &inputdata )
{
if ( !m_hBot->GetPlayerClass() || m_hBot->GetPlayerClass()->GetClassIndex() == TF_CLASS_UNDEFINED )
{
// Allow them to spawn instantly when they do choose
m_hBot->AllowInstantSpawn();
return;
}
m_hBot->ForceRespawn();
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CTFBotController::InputBotAddCommandMoveToEntity( inputdata_t &inputdata )
{
const char *pszEntName = inputdata.value.String();
if ( pszEntName && pszEntName[0] )
{
CBaseEntity *pEnt = gEntList.FindEntityByName( NULL, pszEntName );
if ( pEnt )
{
BotData(m_hBot)->AddMoveToCommand( pEnt, vec3_origin );
}
}
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CTFBotController::InputBotAddCommandAttackEntity( inputdata_t &inputdata )
{
const char *pszEntName = inputdata.value.String();
if ( pszEntName && pszEntName[0] )
{
CBaseEntity *pEnt = gEntList.FindEntityByName( NULL, pszEntName );
if ( pEnt )
{
BotData(m_hBot)->AddAttackCommand( pEnt );
}
}
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CTFBotController::InputBotAddCommandSwitchWeapon( inputdata_t &inputdata )
{
BotData(m_hBot)->AddSwitchWeaponCommand( inputdata.value.Int() );
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CTFBotController::InputBotAddCommandDefend( inputdata_t &inputdata )
{
BotData(m_hBot)->AddDefendCommand( inputdata.value.Float() );
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CTFBotController::InputBotSetIgnoreHumans( inputdata_t &inputdata )
{
BotData(m_hBot)->SetIgnoreHumans( inputdata.value.Int() > 0 );
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CTFBotController::InputBotPreventMovement( inputdata_t &inputdata )
{
BotData(m_hBot)->SetFrozen( inputdata.value.Bool() );
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
void CTFBotController::InputBotClearQueue( inputdata_t &inputdata )
{
BotData(m_hBot)->ClearQueue();
}
|