aboutsummaryrefslogtreecommitdiff
path: root/sp/src/game/server/vehicle_baseserver.cpp
blob: a2fe513ed07fe0c3b408a18d6b4f9d6527daf7af (plain) (blame)
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
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: 
//
//=============================================================================//

#include "cbase.h"
#include "vcollide_parse.h"
#include "vehicle_base.h"
#include "npc_vehicledriver.h"
#include "in_buttons.h"
#include "engine/IEngineSound.h"
#include "soundenvelope.h"
#include "SoundEmitterSystem/isoundemittersystembase.h"
#include "saverestore_utlvector.h"
#include "KeyValues.h"
#include "studio.h"
#include "bone_setup.h"
#include "collisionutils.h"
#include "animation.h"
#include "env_player_surface_trigger.h"
#include "rumble_shared.h"

#ifdef HL2_DLL
	#include "hl2_player.h"
#endif

// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"

ConVar g_debug_vehiclesound( "g_debug_vehiclesound", "0", FCVAR_CHEAT );
ConVar g_debug_vehicleexit( "g_debug_vehicleexit", "0", FCVAR_CHEAT );

ConVar sv_vehicle_autoaim_scale("sv_vehicle_autoaim_scale", "8");

bool ShouldVehicleIgnoreEntity( CBaseEntity *pVehicle, CBaseEntity *pCollide );

#define HITBOX_SET	2

//-----------------------------------------------------------------------------
// Save/load
//-----------------------------------------------------------------------------
BEGIN_DATADESC_NO_BASE( vehicle_gear_t )

	DEFINE_FIELD( flMinSpeed,			FIELD_FLOAT ),
	DEFINE_FIELD( flMaxSpeed,			FIELD_FLOAT ),
	DEFINE_FIELD( flSpeedApproachFactor,FIELD_FLOAT ),

END_DATADESC()

BEGIN_DATADESC_NO_BASE( vehicle_crashsound_t )
	DEFINE_FIELD( flMinSpeed,			FIELD_FLOAT ),
	DEFINE_FIELD( flMinDeltaSpeed,		FIELD_FLOAT ),
	DEFINE_FIELD( iszCrashSound,		FIELD_STRING ),
	DEFINE_FIELD( gearLimit,			FIELD_INTEGER ),
END_DATADESC()

BEGIN_DATADESC_NO_BASE( vehiclesounds_t )

	DEFINE_AUTO_ARRAY( iszSound,		FIELD_STRING ),
	DEFINE_UTLVECTOR( pGears,			FIELD_EMBEDDED ),
	DEFINE_UTLVECTOR( crashSounds,		FIELD_EMBEDDED ),
	DEFINE_AUTO_ARRAY( iszStateSounds,	FIELD_STRING ),
	DEFINE_AUTO_ARRAY( minStateTime,	FIELD_FLOAT ),

END_DATADESC()

BEGIN_SIMPLE_DATADESC( CPassengerInfo )
	DEFINE_FIELD( m_hPassenger,		FIELD_EHANDLE ),
	DEFINE_FIELD( m_strRoleName,	FIELD_STRING ),
	DEFINE_FIELD( m_strSeatName,	FIELD_STRING ),
	// NOT SAVED
	// DEFINE_FIELD( m_nRole,	FIELD_INTEGER ),
	// DEFINE_FIELD( m_nSeat,	FIELD_INTEGER ),
END_DATADESC()

BEGIN_SIMPLE_DATADESC( CBaseServerVehicle )

// These are reset every time by the constructor of the owning class 
//	DEFINE_FIELD( m_pVehicle, FIELD_CLASSPTR ),
//	DEFINE_FIELD( m_pDrivableVehicle; ??? ),

	// Controls
	DEFINE_FIELD( m_nNPCButtons,		FIELD_INTEGER ),
	DEFINE_FIELD( m_nPrevNPCButtons,	FIELD_INTEGER ),
	DEFINE_FIELD( m_flTurnDegrees,		FIELD_FLOAT ),
	DEFINE_FIELD( m_flVehicleVolume,	FIELD_FLOAT ),

	// We're going to reparse this data from file in Precache
	DEFINE_EMBEDDED( m_vehicleSounds ),

	DEFINE_FIELD( m_iSoundGear,			FIELD_INTEGER ),
	DEFINE_FIELD( m_flSpeedPercentage,	FIELD_FLOAT ),
	DEFINE_SOUNDPATCH( m_pStateSound ),
	DEFINE_SOUNDPATCH( m_pStateSoundFade ),
	DEFINE_FIELD( m_soundState,			FIELD_INTEGER ),
	DEFINE_FIELD( m_soundStateStartTime, FIELD_TIME ),
	DEFINE_FIELD( m_lastSpeed, FIELD_FLOAT ),
	
// NOT SAVED
//	DEFINE_FIELD( m_EntryAnimations, CUtlVector ),
//	DEFINE_FIELD( m_ExitAnimations, CUtlVector ),
//	DEFINE_FIELD( m_bParsedAnimations,	FIELD_BOOLEAN ),
//  DEFINE_UTLVECTOR( m_PassengerRoles, FIELD_EMBEDDED ),

	DEFINE_FIELD( m_iCurrentExitAnim,	FIELD_INTEGER ),
	DEFINE_FIELD( m_vecCurrentExitEndPoint, FIELD_POSITION_VECTOR ),
	DEFINE_FIELD( m_chPreviousTextureType, FIELD_CHARACTER ),

	DEFINE_FIELD( m_savedViewOffset, FIELD_VECTOR ),
	DEFINE_FIELD( m_hExitBlocker, FIELD_EHANDLE ),
	
	DEFINE_UTLVECTOR( m_PassengerInfo, FIELD_EMBEDDED ),

END_DATADESC()

//-----------------------------------------------------------------------------
// Purpose: Base class for drivable vehicle handling. Contain it in your 
//			drivable vehicle.
//-----------------------------------------------------------------------------
CBaseServerVehicle::CBaseServerVehicle( void )
{
	m_pVehicle = NULL;
	m_pDrivableVehicle = NULL;
	m_nNPCButtons = 0;
	m_nPrevNPCButtons = 0;
	m_flTurnDegrees = 0;

	m_bParsedAnimations = false;
	m_iCurrentExitAnim = 0;
	m_vecCurrentExitEndPoint = vec3_origin;

	m_flVehicleVolume = 0.5;
	m_iSoundGear = 0;
	m_pStateSound = NULL;
	m_pStateSoundFade = NULL;
	m_soundState = SS_NONE;
	m_flSpeedPercentage = 0;
	m_bUseLegacyExitChecks = false;

	m_vehicleSounds.Init();
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
CBaseServerVehicle::~CBaseServerVehicle( void )
{
	SoundShutdown(0);
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CBaseServerVehicle::Precache( void )
{
	int i;
	// Precache our other sounds
	for ( i = 0; i < VS_NUM_SOUNDS; i++ )
	{
		if ( m_vehicleSounds.iszSound[i] != NULL_STRING )
		{
			CBaseEntity::PrecacheScriptSound( STRING(m_vehicleSounds.iszSound[i]) );
		}
	}
	for ( i = 0; i < m_vehicleSounds.crashSounds.Count(); i++ )
	{
		if ( m_vehicleSounds.crashSounds[i].iszCrashSound != NULL_STRING )
		{
			CBaseEntity::PrecacheScriptSound( STRING(m_vehicleSounds.crashSounds[i].iszCrashSound) );
		}
	}

	for ( i = 0; i < SS_NUM_STATES; i++ )
	{
		if ( m_vehicleSounds.iszStateSounds[i] != NULL_STRING )
		{
			CBaseEntity::PrecacheScriptSound( STRING(m_vehicleSounds.iszStateSounds[i]) );
		}
	}
}

//-----------------------------------------------------------------------------
// Purpose: Parses the vehicle's script for the vehicle sounds
//-----------------------------------------------------------------------------
bool CBaseServerVehicle::Initialize( const char *pScriptName )
{
	// Attempt to parse our vehicle script
	if ( PhysFindOrAddVehicleScript( pScriptName, NULL, &m_vehicleSounds ) == false )
		return false;

	Precache();

	return true;
}


//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CBaseServerVehicle::SetVehicle( CBaseEntity *pVehicle )
{ 
	m_pVehicle = pVehicle; 
	m_pDrivableVehicle = dynamic_cast<IDrivableVehicle*>(m_pVehicle);
	Assert( m_pDrivableVehicle );
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
IDrivableVehicle *CBaseServerVehicle::GetDrivableVehicle( void )
{
	Assert( m_pDrivableVehicle );
	return m_pDrivableVehicle;
}

//-----------------------------------------------------------------------------
// Purpose: Returns the driver. Unlike GetPassenger(VEHICLE_ROLE_DRIVER), it will return
//			the NPC driver if it has one.
//-----------------------------------------------------------------------------
CBaseEntity	*CBaseServerVehicle::GetDriver( void )
{
	return GetPassenger( VEHICLE_ROLE_DRIVER );
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
CBaseCombatCharacter *CBaseServerVehicle::GetPassenger( int nRole ) 
{ 
	Assert( nRole == VEHICLE_ROLE_DRIVER ); 
	CBaseEntity *pDriver = GetDrivableVehicle()->GetDriver();

	if ( pDriver == NULL )
		return NULL;

	return pDriver->MyCombatCharacterPointer();
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
int CBaseServerVehicle::GetPassengerRole( CBaseCombatCharacter *pPassenger )
{
	if ( pPassenger == GetDrivableVehicle()->GetDriver() )
		return VEHICLE_ROLE_DRIVER;

	return VEHICLE_ROLE_NONE;
}

//-----------------------------------------------------------------------------
// Purpose: Adds a passenger to the vehicle
// Input  : nSeat - seat to sit in
//			*pPassenger - character to enter
//-----------------------------------------------------------------------------
bool CBaseServerVehicle::NPC_AddPassenger( CBaseCombatCharacter *pPassenger, string_t strRoleName, int nSeat )
{
	// Players cannot yet use this code! - jdw
	Assert( pPassenger != NULL && pPassenger->IsPlayer() == false );
	if ( pPassenger == NULL || pPassenger->IsPlayer() )
		return false;

	// Find our role
	int nRole = FindRoleIndexByName( strRoleName );
	if ( nRole == -1 )
		return false;

	// Cannot evict a passenger already in this position
	CBaseCombatCharacter *pCurrentPassenger = NPC_GetPassengerInSeat( nRole, nSeat );
	if ( pCurrentPassenger == pPassenger )
		return true;

	// If we weren't the same passenger, we need to be empty
	if ( pCurrentPassenger != NULL )
		return false;

	// Find the seat
	for ( int i = 0; i < m_PassengerInfo.Count(); i++ )
	{
		if ( m_PassengerInfo[i].GetSeat() == nSeat && m_PassengerInfo[i].GetRole() == nRole )
		{
			m_PassengerInfo[i].m_hPassenger = pPassenger;
			return true;
		}
	}

	return false;
}

//-----------------------------------------------------------------------------
// Purpose: Removes a passenger from the vehicle
// Input  : *pPassenger - Passenger to remove
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CBaseServerVehicle::NPC_RemovePassenger( CBaseCombatCharacter *pPassenger )
{
	// Players cannot yet use this code! - jdw
	Assert( pPassenger != NULL && pPassenger->IsPlayer() == false );
	if ( pPassenger == NULL || pPassenger->IsPlayer() )
		return false;

	// Find the seat
	for ( int i = 0; i < m_PassengerInfo.Count(); i++ )
	{
		if ( m_PassengerInfo[i].m_hPassenger == pPassenger )
		{
			m_PassengerInfo[i].m_hPassenger = NULL;
			return true;
		}
	}

	return false;
}

//-----------------------------------------------------------------------------
// Purpose: Returns the attachment point index for the passenger's seat
// Input  : *pPassenger - Passenger in the seat
// Output : int - Attachment point index for the vehicle
//-----------------------------------------------------------------------------
int CBaseServerVehicle::NPC_GetPassengerSeatAttachment( CBaseCombatCharacter *pPassenger )
{
	// Get the role and seat the the supplied passenger
	for ( int i = 0; i < m_PassengerInfo.Count(); i++ )
	{
		// If this is the passenger, get the attachment it'll be at
		if ( m_PassengerInfo[i].m_hPassenger == pPassenger )
		{
			// The seat is the attachment point
			int nSeat = m_PassengerInfo[i].GetSeat();
			int nRole = m_PassengerInfo[i].GetRole();
			
			return m_PassengerRoles[nRole].m_PassengerSeats[nSeat].GetAttachmentID();
		}
	}

	return -1;
}

//-----------------------------------------------------------------------------
// Purpose: Get the worldspace position and angles of the specified seat
// Input  : *pPassenger - Passenger's seat to use
//-----------------------------------------------------------------------------
bool CBaseServerVehicle::NPC_GetPassengerSeatPosition( CBaseCombatCharacter *pPassenger, Vector *vecResultPos, QAngle *vecResultAngles )
{
	// Get our attachment point
	int nSeatAttachment = NPC_GetPassengerSeatAttachment( pPassenger );
	if ( nSeatAttachment == -1 )
		return false;

	// Figure out which entrypoint hitbox the player is in
	CBaseAnimating *pAnimating = dynamic_cast< CBaseAnimating * >( m_pVehicle );
	if ( pAnimating == NULL )
		return false;

	Vector vecPos;
	QAngle vecAngles;
	pAnimating->GetAttachment( nSeatAttachment, vecPos, vecAngles );

	if ( vecResultPos != NULL )
	{
		*vecResultPos = vecPos;
	}

	if ( vecResultAngles != NULL )
	{
		*vecResultAngles = vecAngles;
	}

	return true;
}

//-----------------------------------------------------------------------------
// Purpose: Get the localspace position and angles of the specified seat
// Input  : *pPassenger - Passenger's seat to use
//-----------------------------------------------------------------------------
bool CBaseServerVehicle::NPC_GetPassengerSeatPositionLocal( CBaseCombatCharacter *pPassenger, Vector *vecResultPos, QAngle *vecResultAngles )
{
	// Get our attachment point
	int nSeatAttachment = NPC_GetPassengerSeatAttachment( pPassenger );
	if ( nSeatAttachment == -1 )
		return false;

	// Figure out which entrypoint hitbox the player is in
	CBaseAnimating *pAnimating = m_pVehicle->GetBaseAnimating();
	if ( pAnimating == NULL )
		return false;

	Vector vecPos;
	QAngle vecAngles;
	pAnimating->InvalidateBoneCache(); // NOTE: We're moving with velocity, so we're almost always out of date
	pAnimating->GetAttachmentLocal( nSeatAttachment, vecPos, vecAngles );

	if ( vecResultPos != NULL )
	{
		*vecResultPos = vecPos;
	}

	if ( vecResultAngles != NULL )
	{
		*vecResultAngles = vecAngles;
	}

	return true;
}

//-----------------------------------------------------------------------------
// Purpose: Retrieves a list of animations used to enter/exit the seat occupied by the passenger
// Input  : *pPassenger - Passenger who's seat anims to retrieve
//			nType - which set of animations to retrieve
//-----------------------------------------------------------------------------
const PassengerSeatAnims_t *CBaseServerVehicle::NPC_GetPassengerSeatAnims( CBaseCombatCharacter *pPassenger, PassengerSeatAnimType_t nType )
{
	// Get the role and seat the the supplied passenger
	for ( int i = 0; i < m_PassengerInfo.Count(); i++ )
	{
		if ( m_PassengerInfo[i].m_hPassenger == pPassenger )
		{
			int nSeat = m_PassengerInfo[i].GetSeat();
			int nRole = m_PassengerInfo[i].GetRole();
			switch( nType )
			{
			case PASSENGER_SEAT_ENTRY:
				return &m_PassengerRoles[nRole].m_PassengerSeats[nSeat].m_EntryTransitions;
				break;

			case PASSENGER_SEAT_EXIT:
				return &m_PassengerRoles[nRole].m_PassengerSeats[nSeat].m_ExitTransitions;
				break;

			default:
				return NULL;
				break;
			}
		}
	}

	return NULL;
}

//-----------------------------------------------------------------------------
// Purpose: Get and set the current driver. Use PassengerRole_t enum in shareddefs.h for adding passengers
//-----------------------------------------------------------------------------
void CBaseServerVehicle::SetPassenger( int nRole, CBaseCombatCharacter *pPassenger )
{
	// Baseclass only handles vehicles with a single passenger
	Assert( nRole == VEHICLE_ROLE_DRIVER ); 

	if ( pPassenger != NULL && pPassenger->IsPlayer() == false )
	{
		// Use NPC_AddPassenger() for NPCs at the moment, these will all be collapsed into one system -- jdw
		Assert( 0 );
		return;
	}

	// Getting in? or out?
	if ( pPassenger != NULL )
	{
		CBasePlayer *pPlayer = ToBasePlayer( pPassenger );
		if ( pPlayer != NULL )
		{
			m_savedViewOffset = pPlayer->GetViewOffset();
			pPlayer->SetViewOffset( vec3_origin );
			pPlayer->ShowCrosshair( false );

			GetDrivableVehicle()->EnterVehicle( pPassenger );

#ifdef HL2_DLL
			// Stop the player sprint and flashlight.
			CHL2_Player *pHL2Player = dynamic_cast<CHL2_Player*>( pPlayer );
			if ( pHL2Player )
			{
				if ( pHL2Player->IsSprinting() )
				{
					pHL2Player->StopSprinting();
				}

				if ( pHL2Player->FlashlightIsOn() )
				{
					pHL2Player->FlashlightTurnOff();
				}
			}
#endif
		}
	}
	else
	{
		CBasePlayer *pPlayer = ToBasePlayer( GetDriver() );
		if ( pPlayer )
		{
			// Restore the exiting player's view offset			
			pPlayer->SetViewOffset( m_savedViewOffset );
			pPlayer->ShowCrosshair( true );
		}

		GetDrivableVehicle()->ExitVehicle( nRole );
		GetDrivableVehicle()->SetVehicleEntryAnim( false );
		UTIL_Remove( m_hExitBlocker );
	}
}
	
//-----------------------------------------------------------------------------
// Purpose: Get a position in *world space* inside the vehicle for the player to start at
//-----------------------------------------------------------------------------
void CBaseServerVehicle::GetPassengerSeatPoint( int nRole, Vector *pPoint, QAngle *pAngles )
{
	Assert( nRole == VEHICLE_ROLE_DRIVER ); 

	CBaseAnimating *pAnimating = dynamic_cast<CBaseAnimating *>(m_pVehicle);
	if ( pAnimating )
	{
		char pAttachmentName[32];
		Q_snprintf( pAttachmentName, sizeof( pAttachmentName ), "vehicle_feet_passenger%d", nRole );
		int nFeetAttachmentIndex = pAnimating->LookupAttachment(pAttachmentName);
		int nIdleSequence = pAnimating->SelectWeightedSequence( ACT_IDLE );
		if ( nFeetAttachmentIndex > 0 && nIdleSequence != -1 )
		{
			// FIXME: This really wants to be a faster query than this implementation!
			Vector vecOrigin;
			QAngle vecAngles;
			if ( GetLocalAttachmentAtTime( nIdleSequence, nFeetAttachmentIndex, 0.0f, &vecOrigin, &vecAngles ) )
			{
				UTIL_ParentToWorldSpace( pAnimating, vecOrigin, vecAngles );
				if ( pPoint )
				{
					*pPoint = vecOrigin;
				}

				if ( pAngles )
				{
					*pAngles = vecAngles;
				}

				return;
			}
		}
	}

	// Couldn't find the attachment point, so just use the origin
	if ( pPoint )
	{
		*pPoint = m_pVehicle->GetAbsOrigin();
	}

	if ( pAngles )
	{
		*pAngles = m_pVehicle->GetAbsAngles();
	}
}

//---------------------------------------------------------------------------------
// Check Exit Point for leaving vehicle.
//
// Input: yaw/roll from vehicle angle to check for exit
//		  distance from origin to drop player (allows for different shaped vehicles
// Output: returns true if valid location, pEndPoint
//         updated with actual exit point
//---------------------------------------------------------------------------------
bool CBaseServerVehicle::CheckExitPoint( float yaw, int distance, Vector *pEndPoint )
{
	QAngle vehicleAngles = m_pVehicle->GetLocalAngles();
  	Vector vecStart = m_pVehicle->GetAbsOrigin();
  	Vector vecDir;
   
  	vecStart.z += 12;		// always 12" from ground
  	vehicleAngles[YAW] += yaw;	
  	AngleVectors( vehicleAngles, NULL, &vecDir, NULL );
	// Vehicles are oriented along the Y axis
	vecDir *= -1;
  	*pEndPoint = vecStart + vecDir * distance;
  
  	trace_t tr;
  	UTIL_TraceHull( vecStart, *pEndPoint, VEC_HULL_MIN, VEC_HULL_MAX, MASK_PLAYERSOLID, m_pVehicle, COLLISION_GROUP_NONE, &tr );

	if ( tr.fraction < 1.0 )
		return false;
  
  	return true;
}

//-----------------------------------------------------------------------------
// Purpose: Where does this passenger exit the vehicle?
//-----------------------------------------------------------------------------
bool CBaseServerVehicle::GetPassengerExitPoint( int nRole, Vector *pExitPoint, QAngle *pAngles )
{ 
	Assert( nRole == VEHICLE_ROLE_DRIVER ); 

	// First, see if we've got an attachment point
	CBaseAnimating *pAnimating = dynamic_cast<CBaseAnimating *>(m_pVehicle);
	if ( pAnimating )
	{
		Vector vehicleExitOrigin;
		QAngle vehicleExitAngles;
		if ( pAnimating->GetAttachment( "vehicle_driver_exit", vehicleExitOrigin, vehicleExitAngles ) )
		{
			// Make sure it's clear
			trace_t tr;
			UTIL_TraceHull( vehicleExitOrigin + Vector(0, 0, 12), vehicleExitOrigin, VEC_HULL_MIN, VEC_HULL_MAX, MASK_PLAYERSOLID, m_pVehicle, COLLISION_GROUP_NONE, &tr );
			if ( !tr.startsolid )
			{
				*pAngles = vehicleExitAngles;
				*pExitPoint = tr.endpos;
				return true;
			}
		}
	}

	// left side 
	if( CheckExitPoint( 90, 90, pExitPoint ) )	// angle from car, distance from origin, actual exit point
		return true;

	// right side
	if( CheckExitPoint( -90, 90, pExitPoint ) )
		return true;

	// front
	if( CheckExitPoint( 0, 100, pExitPoint ) )
		return true;

	// back
	if( CheckExitPoint( 180, 170, pExitPoint ) )
		return true;

	// All else failed, try popping them out the top.
	Vector vecWorldMins, vecWorldMaxs;
	m_pVehicle->CollisionProp()->WorldSpaceAABB( &vecWorldMins, &vecWorldMaxs );
	pExitPoint->x = (vecWorldMins.x + vecWorldMaxs.x) * 0.5f;
	pExitPoint->y = (vecWorldMins.y + vecWorldMaxs.y) * 0.5f;
	pExitPoint->z = vecWorldMaxs.z + 50.0f;

	// Make sure it's clear
	trace_t tr;
	UTIL_TraceHull( m_pVehicle->CollisionProp()->WorldSpaceCenter(), *pExitPoint, VEC_HULL_MIN, VEC_HULL_MAX, MASK_PLAYERSOLID, m_pVehicle, COLLISION_GROUP_NONE, &tr );
	if ( !tr.startsolid )
	{
		return true;
	}

	// No clear exit point available!
	return false;
}


//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CBaseServerVehicle::ParseExitAnim( KeyValues *pkvExitList, bool bEscapeExit )
{
	// Look through the entry animations list
	KeyValues *pkvExitAnim = pkvExitList->GetFirstSubKey();
	while ( pkvExitAnim )
	{
		// Add 'em to our list
		int iIndex = m_ExitAnimations.AddToTail();
		Q_strncpy( m_ExitAnimations[iIndex].szAnimName, pkvExitAnim->GetName(), sizeof(m_ExitAnimations[iIndex].szAnimName) );
		m_ExitAnimations[iIndex].bEscapeExit = bEscapeExit;
		if ( !Q_strncmp( pkvExitAnim->GetString(), "upsidedown", 10 ) )
		{
			m_ExitAnimations[iIndex].bUpright = false;
		}
		else 
		{
			m_ExitAnimations[iIndex].bUpright = true;
		}

		pkvExitAnim = pkvExitAnim->GetNextKey();
	}
}

//-----------------------------------------------------------------------------
// Purpose: Parse the transition information
// Input  : *pTransitionKeyValues - key values to parse
//-----------------------------------------------------------------------------
void CBaseServerVehicle::ParseNPCSeatTransition( KeyValues *pTransitionKeyValues, CPassengerSeatTransition *pTransition )
{
	// Store it
	const char *lpszAnimName = pTransitionKeyValues->GetString( "animation" );
	pTransition->m_strAnimationName = AllocPooledString( lpszAnimName );
	pTransition->m_nPriority = pTransitionKeyValues->GetInt( "priority" );
}

//-----------------------------------------------------------------------------
// Purpose: Sorting function for vehicle seat animation priorities
//-----------------------------------------------------------------------------
typedef CPassengerSeatTransition SortSeatPriorityType;
int __cdecl SeatPrioritySort( const SortSeatPriorityType *s1, const SortSeatPriorityType *s2 )
{
	return ( s1->GetPriority() > s2->GetPriority() );
}

//-----------------------------------------------------------------------------
// Purpose: Parse one set of entry/exit data
// Input  : *pSetKeyValues - Key values for this set
//-----------------------------------------------------------------------------
void CBaseServerVehicle::ParseNPCPassengerSeat( KeyValues *pSetKeyValues, CPassengerSeat *pSeat )
{
	CBaseAnimating *pAnimating = (CBaseAnimating *) m_pVehicle;

	// Get our attachment name
	const char *lpszAttachmentName = pSetKeyValues->GetString( "target_attachment" );
	int nAttachmentID = pAnimating->LookupAttachment( lpszAttachmentName );
	pSeat->m_nAttachmentID = nAttachmentID;
	pSeat->m_strSeatName = AllocPooledString( lpszAttachmentName );

	KeyValues *pKey = pSetKeyValues->GetFirstSubKey();
	while ( pKey != NULL )
	{
		const char *lpszName = pKey->GetName();

		if ( Q_stricmp( lpszName, "entry" ) == 0 )
		{
			int nIndex = pSeat->m_EntryTransitions.AddToTail();
			Assert( pSeat->m_EntryTransitions.IsValidIndex( nIndex ) );

			ParseNPCSeatTransition( pKey, &pSeat->m_EntryTransitions[nIndex] );
		}
		else if ( Q_stricmp( lpszName, "exit" ) == 0 )
		{
			int nIndex = pSeat->m_ExitTransitions.AddToTail();
			Assert( pSeat->m_ExitTransitions.IsValidIndex( nIndex ) );

			ParseNPCSeatTransition( pKey, &pSeat->m_ExitTransitions[nIndex] );
		}

		// Advance
		pKey = pKey->GetNextKey();
	}

	// Sort the seats based on their priority
	pSeat->m_EntryTransitions.Sort( SeatPrioritySort );
	pSeat->m_ExitTransitions.Sort( SeatPrioritySort );
}

//-----------------------------------------------------------------------------
// Purpose: Find a passenger role (by name), or create a new one of that names
// Input  : strName - name of the role
//		  : *nIndex - the index into the CUtlBuffer where this role resides
// Output : CPassengerRole * - Role found or created
//-----------------------------------------------------------------------------
CPassengerRole *CBaseServerVehicle::FindOrCreatePassengerRole( string_t strName, int *nIndex )
{
	// Try to find an already created container of the same name
	for ( int i = 0; i < m_PassengerRoles.Count(); i++ )
	{
		// If we match, return it
		if ( FStrEq( STRING( m_PassengerRoles[i].m_strName ), STRING( strName ) ) )
		{
			// Supply the index, if requested
			if ( nIndex != NULL )
			{
				*nIndex = i;
			}

			return &m_PassengerRoles[i];
		}
	}

	// Create a new container
	int nNewIndex = m_PassengerRoles.AddToTail();
	Assert( m_PassengerRoles.IsValidIndex( nNewIndex ) );
	
	m_PassengerRoles[nNewIndex].m_strName = strName;
	
	// Supply the index, if requested
	if ( nIndex != NULL )
	{
		*nIndex = nNewIndex;
	}
	
	return &m_PassengerRoles[nNewIndex];
}

ConVar g_debug_npc_vehicle_roles( "g_debug_npc_vehicle_roles", "0" );

//-----------------------------------------------------------------------------
// Purpose: Parse NPC entry and exit anim data
// Input  : *pModelKeyValues - Key values from the vehicle model
//-----------------------------------------------------------------------------
void CBaseServerVehicle::ParseNPCRoles( KeyValues *pkvPassengerList )
{
	// Get the definition section
	if ( pkvPassengerList == NULL )
		return;

	// Get our animating class
	CBaseAnimating *pAnimating = dynamic_cast<CBaseAnimating *>(m_pVehicle);
	Assert( pAnimating != NULL );
	if ( pAnimating == NULL )
		return;

	// For attachment polling
	CStudioHdr *pStudioHdr = pAnimating->GetModelPtr();
	Assert( pStudioHdr != NULL );
	if ( pStudioHdr == NULL )
		return;

	// Parse all subkeys
	int nRoleIndex;
	KeyValues *pkvPassengerKey = pkvPassengerList->GetFirstSubKey();
	while ( pkvPassengerKey != NULL )
	{
		string_t strRoleName = AllocPooledString( pkvPassengerKey->GetName() );

		// Find or create the container
		CPassengerRole *pRole = FindOrCreatePassengerRole( strRoleName, &nRoleIndex );
		if ( pRole == NULL )
			continue;

		// Add a new role
		int nSeatIndex = pRole->m_PassengerSeats.AddToTail();
		Assert( pRole->m_PassengerSeats.IsValidIndex( nSeatIndex ) );

		// Parse the information
		ParseNPCPassengerSeat( pkvPassengerKey, &pRole->m_PassengerSeats[nSeatIndex] );
	
		// Add a matching entry into our passenger manifest
		int nPassengerIndex = m_PassengerInfo.AddToTail();
		m_PassengerInfo[nPassengerIndex].m_hPassenger = NULL;
		m_PassengerInfo[nPassengerIndex].m_nSeat = nSeatIndex;
		m_PassengerInfo[nPassengerIndex].m_nRole = nRoleIndex;
		
		// The following are used for index fix-ups after save game restoration
		m_PassengerInfo[nPassengerIndex].m_strRoleName = strRoleName;
		m_PassengerInfo[nPassengerIndex].m_strSeatName = pRole->m_PassengerSeats[nSeatIndex].m_strSeatName;

		// Advance to the next key
		pkvPassengerKey = pkvPassengerKey->GetNextKey();
	}

	// ======================================================================================================
	// Debug print

	if ( g_debug_npc_vehicle_roles.GetBool() )
	{
		Msg("Passenger Roles Parsed:\t%d\n\n", m_PassengerRoles.Count() );
		for ( int i = 0; i < m_PassengerRoles.Count(); i++ )
		{
			Msg("\tPassenger Role:\t%s (%d seats)\n", STRING(m_PassengerRoles[i].m_strName), m_PassengerRoles[i].m_PassengerSeats.Count() );
			
			// Iterate through all information sets under this name
			for ( int j = 0; j < m_PassengerRoles[i].m_PassengerSeats.Count(); j++ )
			{
				Msg("\t\tAttachment: %d\n", m_PassengerRoles[i].m_PassengerSeats[j].m_nAttachmentID );
				
				// Entries
				Msg("\t\tEntries:\t%d\n", m_PassengerRoles[i].m_PassengerSeats[j].m_EntryTransitions.Count() );
				Msg("\t\t=====================\n" );

				for ( int nEntry = 0; nEntry < m_PassengerRoles[i].m_PassengerSeats[j].m_EntryTransitions.Count(); nEntry++ )
				{
					Msg("\t\t\tAnimation:\t%s\t(Priority %d)\n", STRING(m_PassengerRoles[i].m_PassengerSeats[j].m_EntryTransitions[nEntry].m_strAnimationName), 
																 m_PassengerRoles[i].m_PassengerSeats[j].m_EntryTransitions[nEntry].m_nPriority );
				}
				
				Msg("\n");

				// Exits
				Msg("\t\tExits:\t%d\n", m_PassengerRoles[i].m_PassengerSeats[j].m_ExitTransitions.Count() );
				Msg("\t\t=====================\n" );

				for ( int nExits = 0; nExits < m_PassengerRoles[i].m_PassengerSeats[j].m_ExitTransitions.Count(); nExits++ )
				{
					Msg("\t\t\tAnimation:\t%s\t(Priority %d)\n", STRING(m_PassengerRoles[i].m_PassengerSeats[j].m_ExitTransitions[nExits].m_strAnimationName), 
																 m_PassengerRoles[i].m_PassengerSeats[j].m_ExitTransitions[nExits].m_nPriority );
				}
			}

			Msg("\n");
		}
	}

	// ======================================================================================================
}
//-----------------------------------------------------------------------------
// Purpose: Get an attachment point at a specified time in its cycle (note: not exactly a speedy query, use sparingly!)
// Input  : nSequence - sequence to test
//			nAttachmentIndex - attachment to test
//			flCyclePoint - 0.0 - 1.0
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CBaseServerVehicle::GetLocalAttachmentAtTime( int nQuerySequence, int nAttachmentIndex, float flCyclePoint, Vector *vecOriginOut, QAngle *vecAnglesOut )
{
	CBaseAnimating *pAnimating = m_pVehicle->GetBaseAnimating();
	if ( pAnimating == NULL )
		return false;

	// TODO: It's annoying to stomp and restore this off each time when we're just going to stomp it again later, but the function 
	//		 should really leave the car in an acceptable state to run this query -- jdw

	// Store this off for restoration later
	int nOldSequence = pAnimating->GetSequence();
	float flOldCycle = pAnimating->GetCycle();

	// Setup the model for the query
	pAnimating->SetSequence( nQuerySequence );
	pAnimating->SetCycle( flCyclePoint );
	pAnimating->InvalidateBoneCache();

	// Query for the point
	Vector vecOrigin;
	QAngle vecAngles;
	pAnimating->GetAttachmentLocal( nAttachmentIndex, vecOrigin, vecAngles );

	if ( vecOriginOut != NULL )
	{
		*vecOriginOut = vecOrigin;
	}

	if ( vecAnglesOut != NULL )
	{
		*vecAnglesOut = vecAngles;
	}

	// Restore the model after the query
	pAnimating->SetSequence( nOldSequence );
	pAnimating->SetCycle( flOldCycle );
	pAnimating->InvalidateBoneCache();

	return true;
}

//-----------------------------------------------------------------------------
// Purpose: Get an attachment point at a specified time in its cycle (note: not exactly a speedy query, use sparingly!)
// Input  : lpszAnimName - name of the sequence to test
//			nAttachmentIndex - attachment to test
//			flCyclePoint - 0.0 - 1.0
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CBaseServerVehicle::GetLocalAttachmentAtTime( const char *lpszAnimName, int nAttachmentIndex, float flCyclePoint, Vector *vecOriginOut, QAngle *vecAnglesOut )
{
	CBaseAnimating *pAnimating = m_pVehicle->GetBaseAnimating();
	if ( pAnimating == NULL )
		return false;

	int nQuerySequence = pAnimating->LookupSequence( lpszAnimName );
	if ( nQuerySequence < 0 )
		return false;

	return GetLocalAttachmentAtTime( nQuerySequence, nAttachmentIndex, flCyclePoint, vecOriginOut, vecAnglesOut );
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CBaseServerVehicle::CacheEntryExitPoints( void )
{
	CBaseAnimating *pAnimating = m_pVehicle->GetBaseAnimating();
	if ( pAnimating == NULL )
		return;

	int nAttachment = pAnimating->LookupAttachment( "vehicle_driver_eyes" );
	
	// For each exit animation, determine where the end point is and cache it
	for ( int i = 0; i < m_ExitAnimations.Count(); i++ )
	{
		if ( GetLocalAttachmentAtTime( m_ExitAnimations[i].szAnimName, nAttachment, 1.0f, &m_ExitAnimations[i].vecExitPointLocal, &m_ExitAnimations[i].vecExitAnglesLocal ) == false )
		{
			Warning("Exit animation %s failed to cache target points properly!\n", m_ExitAnimations[i].szAnimName );
		}

		if ( g_debug_vehicleexit.GetBool() )
		{
			Vector vecExitPoint = m_ExitAnimations[i].vecExitPointLocal;
			QAngle vecExitAngles = m_ExitAnimations[i].vecExitAnglesLocal;
			UTIL_ParentToWorldSpace( pAnimating, vecExitPoint, vecExitAngles );

			NDebugOverlay::Box( vecExitPoint, -Vector(8,8,8), Vector(8,8,8), 0, 255, 0, 0, 20.0f );
			NDebugOverlay::Axis( vecExitPoint, vecExitAngles, 8.0f, true, 20.0f );
		}
	}
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CBaseServerVehicle::ParseEntryExitAnims( void )
{
	// Try and find the right animation to play in the model's keyvalues
	KeyValues *modelKeyValues = new KeyValues("");
	if ( modelKeyValues->LoadFromBuffer( modelinfo->GetModelName( m_pVehicle->GetModel() ), modelinfo->GetModelKeyValueText( m_pVehicle->GetModel() ) ) )
	{
		// Do we have an entry section?
		KeyValues *pkvEntryList = modelKeyValues->FindKey("vehicle_entry");
		if ( pkvEntryList )
		{
			// Look through the entry animations list
			KeyValues *pkvEntryAnim = pkvEntryList->GetFirstSubKey();
			while ( pkvEntryAnim )
			{
				// Add 'em to our list
				int iIndex = m_EntryAnimations.AddToTail();
				Q_strncpy( m_EntryAnimations[iIndex].szAnimName, pkvEntryAnim->GetName(), sizeof(m_EntryAnimations[iIndex].szAnimName) );
				m_EntryAnimations[iIndex].iHitboxGroup = pkvEntryAnim->GetInt();

				pkvEntryAnim = pkvEntryAnim->GetNextKey();
			}
		}

		// Do we have an exit section?
		KeyValues *pkvExitList = modelKeyValues->FindKey("vehicle_exit");
		if ( pkvExitList )
		{
			ParseExitAnim( pkvExitList, false );
		}

		// Do we have an exit section?
		pkvExitList = modelKeyValues->FindKey("vehicle_escape_exit");
		if ( pkvExitList )
		{
			ParseExitAnim( pkvExitList, true );
		}

		// Parse the NPC vehicle roles as well
		KeyValues *pkvPassengerList = modelKeyValues->FindKey( "vehicle_npc_passengers" );
		if ( pkvPassengerList  )
		{
			ParseNPCRoles( pkvPassengerList );
		}
	}

	modelKeyValues->deleteThis();

	// Determine the entry and exit points for the 
	CacheEntryExitPoints();
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CBaseServerVehicle::HandlePassengerEntry( CBaseCombatCharacter *pPassenger, bool bAllowEntryOutsideZone )
{
	CBasePlayer *pPlayer = ToBasePlayer( pPassenger );
	if ( pPlayer != NULL )
	{
		// Find out which hitbox the player's eyepoint is within
		int iEntryAnim = GetEntryAnimForPoint( pPlayer->EyePosition() );

		// Get this interface for animation queries
		CBaseAnimating *pAnimating = dynamic_cast<CBaseAnimating *>(m_pVehicle);
		if ( !pAnimating )
			return;

		// Are we in an entrypoint zone? 
		if ( iEntryAnim == ACTIVITY_NOT_AVAILABLE )
		{
			// Normal get in refuses to allow entry
			if ( !bAllowEntryOutsideZone )
				return;

			// We failed to find a valid entry anim, but we've got to get back in because the player's
			// got stuck exiting the vehicle. For now, just use the first get in anim
			// UNDONE: We need a better solution for this.
			iEntryAnim = pAnimating->LookupSequence( m_EntryAnimations[0].szAnimName );
		}

		// Check to see if this vehicle can be controlled or if it's locked
		if ( GetDrivableVehicle()->CanEnterVehicle( pPlayer ) )
		{
			// Make sure the passenger can get in as well
			if ( pPlayer->CanEnterVehicle( this, VEHICLE_ROLE_DRIVER ) )
			{
				// Setup the "enter" vehicle sequence and skip the animation if it isn't present.
				pAnimating->SetCycle( 0 );
				pAnimating->m_flAnimTime = gpGlobals->curtime;
				pAnimating->ResetSequence( iEntryAnim );
				pAnimating->ResetClientsideFrame();
				pAnimating->InvalidateBoneCache();	// This is necessary because we need to query attachment points this frame for blending!
				GetDrivableVehicle()->SetVehicleEntryAnim( true );

				pPlayer->GetInVehicle( this, VEHICLE_ROLE_DRIVER );
			}
		}
	}
	else
	{
		// NPCs handle transitioning themselves, they should NOT call this function
		Assert( 0 );
	}
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
bool CBaseServerVehicle::HandlePassengerExit( CBaseCombatCharacter *pPassenger )
{
	CBasePlayer *pPlayer = ToBasePlayer( pPassenger );
	if ( pPlayer != NULL )
	{
		// Clear hud hints
		UTIL_HudHintText( pPlayer, "" );

		vbs_sound_update_t params;
		InitSoundParams(params);
		params.bExitVehicle = true;
		SoundState_Update( params );

		// Find the right exit anim to use based on available exit points.
		Vector vecExitPoint;
		bool bAllPointsBlocked;
		int iSequence = GetExitAnimToUse( vecExitPoint, bAllPointsBlocked );

		// If all exit points were blocked and this vehicle doesn't allow exiting in
		// these cases, bail.
		Vector vecNewPos = pPlayer->GetAbsOrigin();
		QAngle angNewAngles = pPlayer->GetAbsAngles();

		int nRole = GetPassengerRole( pPlayer );
		if ( ( bAllPointsBlocked ) || ( iSequence == ACTIVITY_NOT_AVAILABLE ) )
		{
			// Animation-driven exit points are all blocked, or we have none. Fall back to the more simple static exit points.
			if ( !GetPassengerExitPoint( nRole, &vecNewPos, &angNewAngles ) && !GetDrivableVehicle()->AllowBlockedExit( pPlayer, nRole ) )
				return false;

			// At this point, the player has exited the vehicle but did so without playing an animation.  We need to give the vehicle a
			// chance to do any post-animation clean-up it may need to perform.
			HandleEntryExitFinish( false, true );
		}

		// Now we either have an exit sequence to play, a valid static exit position, or we don't care
		// whether we're blocked or not. We're getting out, one way or another.
		GetDrivableVehicle()->PreExitVehicle( pPlayer, nRole );

		if ( iSequence > ACTIVITY_NOT_AVAILABLE )
		{
			CBaseAnimating *pAnimating = dynamic_cast<CBaseAnimating *>(m_pVehicle);
			if ( pAnimating )
			{
				pAnimating->SetCycle( 0 );
				pAnimating->m_flAnimTime = gpGlobals->curtime;
				pAnimating->ResetSequence( iSequence );
				pAnimating->ResetClientsideFrame();
				GetDrivableVehicle()->SetVehicleExitAnim( true, vecExitPoint );

				// Re-deploy our weapon
				if ( pPlayer && pPlayer->IsAlive() )
				{
					if ( pPlayer->GetActiveWeapon() )
					{
						pPlayer->GetActiveWeapon()->Deploy();
						pPlayer->ShowCrosshair( true );
					}
				}

				// To prevent anything moving into the volume the player's going to occupy at the end of the exit
				// NOTE: Set the player as the blocker's owner so the player is allowed to intersect it
				Vector vecExitFeetPoint = vecExitPoint - VEC_VIEW;
				m_hExitBlocker = CEntityBlocker::Create( vecExitFeetPoint, VEC_HULL_MIN, VEC_HULL_MAX, pPlayer, true );

				// We may as well stand where we're going to get out at and stop being parented
				pPlayer->SetAbsOrigin( vecExitFeetPoint );
				pPlayer->SetParent( NULL );

				return true;
			}
		}

		// Couldn't find an animation, so exit immediately
		pPlayer->LeaveVehicle( vecNewPos, angNewAngles );
		return true;
	}
	else
	{
		// NPCs handle transitioning themselves, they should NOT call this function
		Assert( 0 );
	}

	return false;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
int CBaseServerVehicle::GetEntryAnimForPoint( const Vector &vecEyePoint )
{
	// Parse the vehicle animations the first time they get in the vehicle
	if ( !m_bParsedAnimations )
	{
		// Load the entry/exit animations from the vehicle
		ParseEntryExitAnims();
		m_bParsedAnimations = true;
	}

	// No entry anims? Vehicles with no entry anims are always enterable.
	if ( !m_EntryAnimations.Count() )
		return 0;

	// Figure out which entrypoint hitbox the player is in
	CBaseAnimating *pAnimating = dynamic_cast<CBaseAnimating *>(m_pVehicle);
	if ( !pAnimating )
		return 0;

	CStudioHdr *pStudioHdr = pAnimating->GetModelPtr();
	if (!pStudioHdr)
		return 0;
	int iHitboxSet = FindHitboxSetByName( pStudioHdr, "entryboxes" );
	mstudiohitboxset_t *set = pStudioHdr->pHitboxSet( iHitboxSet );
	if ( !set || !set->numhitboxes )
		return 0;

	// Loop through the hitboxes and find out which one we're in
	for ( int i = 0; i < set->numhitboxes; i++ )
	{
		mstudiobbox_t *pbox = set->pHitbox( i );

		Vector vecPosition;
		QAngle vecAngles;
		pAnimating->GetBonePosition( pbox->bone, vecPosition, vecAngles );

		// Build a rotation matrix from orientation
		matrix3x4_t fRotateMatrix;
		AngleMatrix( vecAngles, vecPosition, fRotateMatrix);

		Vector localEyePoint;
		VectorITransform( vecEyePoint, fRotateMatrix, localEyePoint );
		if ( IsPointInBox( localEyePoint, pbox->bbmin, pbox->bbmax ) )
		{
			// Find the entry animation for this hitbox
			int iCount = m_EntryAnimations.Count();
			for ( int entry = 0; entry < iCount; entry++ )
			{
				if ( m_EntryAnimations[entry].iHitboxGroup == pbox->group )
				{
					// Get the sequence for the animation
					return pAnimating->LookupSequence( m_EntryAnimations[entry].szAnimName );
				}
			}
		}
	}

	// Fail
	return ACTIVITY_NOT_AVAILABLE;
}

//-----------------------------------------------------------------------------
// Purpose: Find an exit animation that'll get the player to a valid position
// Input  : vecEyeExitEndpoint - Returns with the final eye position after exiting.
//			bAllPointsBlocked - Returns whether all exit points were found to be blocked.
// Output : 
//-----------------------------------------------------------------------------
int CBaseServerVehicle::GetExitAnimToUse( Vector &vecEyeExitEndpoint, bool &bAllPointsBlocked )
{
	bAllPointsBlocked = false;
	
	// Parse the vehicle animations the first time they get in the vehicle
	if ( !m_bParsedAnimations )
	{
		// Load the entry/exit animations from the vehicle
		ParseEntryExitAnims();
		m_bParsedAnimations = true;
	}

	// No exit anims? 
	if ( !m_ExitAnimations.Count() )
		return ACTIVITY_NOT_AVAILABLE;

	// Figure out which entrypoint hitbox the player is in
	CBaseAnimating *pAnimating = dynamic_cast<CBaseAnimating *>(m_pVehicle);
	if ( !pAnimating )
		return ACTIVITY_NOT_AVAILABLE;

	CStudioHdr *pStudioHdr = pAnimating->GetModelPtr();
	if (!pStudioHdr)
		return ACTIVITY_NOT_AVAILABLE;

	bool bUpright = IsVehicleUpright();

	// Loop through the exit animations and find one that ends in a clear position
	// Also attempt to choose the animation which brings you closest to your view direction.
	CBasePlayer *pPlayer = ToBasePlayer( GetDriver() );
	if ( pPlayer == NULL )
		return ACTIVITY_NOT_AVAILABLE;

	int nRole = GetPassengerRole( pPlayer );

	int nBestExitAnim = -1;
	bool bBestExitIsEscapePoint = true;
	Vector vecViewDirection, vecViewOrigin, vecBestExitPoint( 0, 0, 0 );
	vecViewOrigin = pPlayer->EyePosition();
	pPlayer->EyeVectors( &vecViewDirection );
	vecViewDirection.z = 0.0f;
	VectorNormalize( vecViewDirection );

	float flMaxCosAngleDelta = -2.0f;

	int iCount = m_ExitAnimations.Count();
	for ( int i = 0; i < iCount; i++ )
	{
		if ( m_ExitAnimations[i].bUpright != bUpright )
			continue;

		// Don't use an escape point if we found a non-escape point already
		if ( !bBestExitIsEscapePoint && m_ExitAnimations[i].bEscapeExit )
			continue;
		
		Vector vehicleExitOrigin;
		QAngle vehicleExitAngles;

		// NOTE: HL2 and Ep1 used a method that relied on the animators to place attachment points in the model which marked where
		//		 the player would exit to.  This was rendered unnecessary in Ep2, but the choreo vehicles of these older products
		//		 did not have proper exit animations and relied on the exact queries that were happening before.  For choreo vehicles,
		//		 we now just allow them to perform those older queries to keep those products happy.  - jdw

		// Get the position we think we're going to end up at
		if ( m_bUseLegacyExitChecks )
		{
			pAnimating->GetAttachment( m_ExitAnimations[i].szAnimName, vehicleExitOrigin, vehicleExitAngles );
		}
		else
		{
			vehicleExitOrigin = m_ExitAnimations[i].vecExitPointLocal;
			vehicleExitAngles = m_ExitAnimations[i].vecExitAnglesLocal;
			UTIL_ParentToWorldSpace( pAnimating, vehicleExitOrigin, vehicleExitAngles );
		}

		// Don't bother checking points which are farther from our view direction.
		Vector vecDelta;
		VectorSubtract( vehicleExitOrigin, vecViewOrigin, vecDelta );
		vecDelta.z = 0.0f;
		VectorNormalize( vecDelta );
		float flCosAngleDelta = DotProduct( vecDelta, vecViewDirection );

		// But always check non-escape exits if our current best exit is an escape exit.
		if ( !bBestExitIsEscapePoint || m_ExitAnimations[i].bEscapeExit )
		{
			if ( flCosAngleDelta < flMaxCosAngleDelta )
				continue;
		}

		// The attachment points are where the driver's eyes will end up, so we subtract the view offset
		// to get the actual exit position.
		vehicleExitOrigin -= VEC_VIEW;

		Vector vecMove(0,0,64);
		Vector vecStart = vehicleExitOrigin + vecMove;
		Vector vecEnd = vehicleExitOrigin - vecMove;

		// Starting at the exit point, trace a flat plane down until we hit ground
		// NOTE: The hull has no vertical span because we want to test the lateral constraints against the ground, not height (yet)
		trace_t tr;
		UTIL_TraceHull( vecStart, vecEnd, VEC_HULL_MIN, Vector( VEC_HULL_MAX.x, VEC_HULL_MAX.y, VEC_HULL_MIN.z ), MASK_PLAYERSOLID, NULL, COLLISION_GROUP_NONE, &tr );
		
		if ( g_debug_vehicleexit.GetBool() )
		{
			NDebugOverlay::SweptBox( vecStart, vecEnd, VEC_HULL_MIN, Vector( VEC_HULL_MAX.x, VEC_HULL_MAX.y, VEC_HULL_MIN.y ), vec3_angle, 255, 255, 255, 8.0f, 20.0f );
		}
		
		if ( tr.fraction < 1.0f )
		{
			// If we hit the ground, try to now "stand up" at that point to see if we'll fit
			UTIL_TraceHull( tr.endpos, tr.endpos, VEC_HULL_MIN, VEC_HULL_MAX, MASK_PLAYERSOLID, NULL, COLLISION_GROUP_NONE, &tr );
			
			// See if we're unable to stand at this space
			if ( tr.startsolid )
			{
				if ( g_debug_vehicleexit.GetBool() )
				{
					NDebugOverlay::Box( tr.endpos, VEC_HULL_MIN, VEC_HULL_MAX, 255, 0, 0, 8.0f, 20.0f );
				}
				continue;
			}

			if ( g_debug_vehicleexit.GetBool() )
			{
				NDebugOverlay::Box( tr.endpos, VEC_HULL_MIN, VEC_HULL_MAX, 0, 255, 0, 8.0f, 20.0f );
			}
		}
		else if ( tr.allsolid || ( ( tr.fraction == 1.0 ) && !GetDrivableVehicle()->AllowMidairExit( pPlayer, nRole ) ) )
		{
			if ( g_debug_vehicleexit.GetBool() )
			{
				NDebugOverlay::Box( tr.endpos, VEC_HULL_MIN, VEC_HULL_MAX, 255,0,0, 64, 10 );
			}
			continue;
		}
		
		// Calculate the exit endpoint & viewpoint
		Vector vecExitEndPoint = tr.endpos;

		// Make sure we can trace to the center of the exit point
		UTIL_TraceLine( vecViewOrigin, vecExitEndPoint, MASK_PLAYERSOLID, pAnimating, COLLISION_GROUP_NONE, &tr );

		if ( tr.fraction != 1.0 )
		{
#ifdef HL2_EPISODIC
			if ( ShouldVehicleIgnoreEntity( GetVehicleEnt(), tr.m_pEnt ) == false )
#endif //HL2_EPISODIC
			{
				if ( g_debug_vehicleexit.GetBool() )
				{
					NDebugOverlay::Line( vecViewOrigin, vecExitEndPoint, 255,0,0, true, 10 );
				}
				continue;
			}
		}

		bBestExitIsEscapePoint = m_ExitAnimations[i].bEscapeExit;
		vecBestExitPoint = vecExitEndPoint;
		nBestExitAnim = i;
		flMaxCosAngleDelta = flCosAngleDelta;
	}

	if ( nBestExitAnim >= 0 )
	{
		m_vecCurrentExitEndPoint = vecBestExitPoint;

		if ( g_debug_vehicleexit.GetBool() )
		{
			NDebugOverlay::Cross3D( m_vecCurrentExitEndPoint, 16, 0, 255, 0, true, 10 );
			NDebugOverlay::Box( m_vecCurrentExitEndPoint, VEC_HULL_MIN, VEC_HULL_MAX, 255,255,255, 8, 10 );
		}

		vecEyeExitEndpoint = vecBestExitPoint + VEC_VIEW;
		m_iCurrentExitAnim = nBestExitAnim;
		return pAnimating->LookupSequence( m_ExitAnimations[m_iCurrentExitAnim].szAnimName );
	}

	// Fail, all exit points were blocked.
	bAllPointsBlocked = true;
	return ACTIVITY_NOT_AVAILABLE;	
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CBaseServerVehicle::HandleEntryExitFinish( bool bExitAnimOn, bool bResetAnim )
{
	// Parse the vehicle animations. This is needed because they may have 
	// saved, and loaded during exit anim, which would clear the exit anim.
	if ( !m_bParsedAnimations )
	{
		// Load the entry/exit animations from the vehicle
		ParseEntryExitAnims();
		m_bParsedAnimations = true;
	}

	// Figure out which entrypoint hitbox the player is in
	CBaseAnimating *pAnimating = m_pVehicle->GetBaseAnimating();
	if ( !pAnimating )
		return;
		
	// Did the entry anim just finish?
	if ( bExitAnimOn )
	{
		// The exit animation just finished
		CBasePlayer *pPlayer = ToBasePlayer( GetDriver() );
		if ( pPlayer != NULL )
		{
			Vector vecEyes;
			QAngle vecEyeAng;
			if ( m_iCurrentExitAnim >= 0 && m_iCurrentExitAnim < m_ExitAnimations.Count() )
			{
				// Convert our offset points to worldspace ones
				vecEyes = m_ExitAnimations[m_iCurrentExitAnim].vecExitPointLocal;
				vecEyeAng = m_ExitAnimations[m_iCurrentExitAnim].vecExitAnglesLocal;
				UTIL_ParentToWorldSpace( pAnimating, vecEyes, vecEyeAng );

				// Use the endpoint we figured out when we exited
				vecEyes = m_vecCurrentExitEndPoint;
			}
			else
			{
				pAnimating->GetAttachment( "vehicle_driver_eyes", vecEyes, vecEyeAng );
			}

			if ( g_debug_vehicleexit.GetBool() )
			{
				NDebugOverlay::Box( vecEyes, -Vector(2,2,2), Vector(2,2,2), 255,0,0, 64, 10.0 );
			}

			// If the end point isn't clear, get back in the vehicle
			/*
			trace_t tr;
			UTIL_TraceHull( vecEyes, vecEyes, VEC_HULL_MIN, VEC_HULL_MAX, MASK_SOLID, NULL, COLLISION_GROUP_NONE, &tr );
			if ( tr.startsolid && tr.fraction < 1.0 )
			{
				pPlayer->LeaveVehicle( vecEyes, vecEyeAng );
				m_pVehicle->Use( pPlayer, pPlayer, USE_TOGGLE, 1 );
				return;
			}
			*/

			pPlayer->LeaveVehicle( vecEyes, vecEyeAng );
		}
	}

	// Only reset the animation if we're told to
	if ( bResetAnim )
	{
		// Start the vehicle idling again
		int iSequence = pAnimating->SelectWeightedSequence( ACT_IDLE );
		if ( iSequence > ACTIVITY_NOT_AVAILABLE )
		{
			pAnimating->SetCycle( 0 );
			pAnimating->m_flAnimTime = gpGlobals->curtime;
			pAnimating->ResetSequence( iSequence );
			pAnimating->ResetClientsideFrame();
		}
	}

	GetDrivableVehicle()->SetVehicleEntryAnim( false );
	GetDrivableVehicle()->SetVehicleExitAnim( false, vec3_origin );
}

//-----------------------------------------------------------------------------
// Purpose: Where does the passenger see from?
//-----------------------------------------------------------------------------
void CBaseServerVehicle::GetVehicleViewPosition( int nRole, Vector *pAbsOrigin, QAngle *pAbsAngles, float *pFOV /*= NULL*/ )
{
	Assert( nRole == VEHICLE_ROLE_DRIVER );
	CBaseCombatCharacter *pPassenger = GetPassenger( VEHICLE_ROLE_DRIVER );
	Assert( pPassenger );

	CBasePlayer *pPlayer = ToBasePlayer( pPassenger );
	if ( pPlayer != NULL )
	{
		// Call through the player to resolve the actual position (if available)
		if ( pAbsOrigin != NULL )
		{
			*pAbsOrigin = pPlayer->EyePosition();
		}
		
		if ( pAbsAngles != NULL )
		{
			*pAbsAngles = pPlayer->EyeAngles();
		}

		if ( pFOV )
		{
			*pFOV = pPlayer->GetFOV();
		}
	}
	else
	{
		// NPCs are not supported
		Assert( 0 );
	}
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CBaseServerVehicle::SetupMove( CBasePlayer *player, CUserCmd *ucmd, IMoveHelper *pHelper, CMoveData *move )
{
	GetDrivableVehicle()->SetupMove( player, ucmd, pHelper, move );
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CBaseServerVehicle::ProcessMovement( CBasePlayer *pPlayer, CMoveData *pMoveData )
{
	GetDrivableVehicle()->ProcessMovement( pPlayer, pMoveData );

	trace_t	tr;
	UTIL_TraceLine( pPlayer->GetAbsOrigin(), pPlayer->GetAbsOrigin() - Vector( 0, 0, 256 ), MASK_PLAYERSOLID, GetVehicleEnt(), COLLISION_GROUP_NONE, &tr );

	// If our gamematerial has changed, tell any player surface triggers that are watching
	IPhysicsSurfaceProps *physprops = MoveHelper()->GetSurfaceProps();
	const surfacedata_t *pSurfaceProp = physprops->GetSurfaceData( tr.surface.surfaceProps );
	char cCurrGameMaterial = pSurfaceProp->game.material;

	// Changed?
	if ( m_chPreviousTextureType != cCurrGameMaterial )
	{
		CEnvPlayerSurfaceTrigger::SetPlayerSurface( pPlayer, cCurrGameMaterial );
	}

	m_chPreviousTextureType = cCurrGameMaterial;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CBaseServerVehicle::FinishMove( CBasePlayer *player, CUserCmd *ucmd, CMoveData *move )
{
	GetDrivableVehicle()->FinishMove( player, ucmd, move );
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CBaseServerVehicle::ItemPostFrame( CBasePlayer *player )
{
	Assert( player == GetDriver() );

	GetDrivableVehicle()->ItemPostFrame( player );

	if ( player->m_afButtonPressed & IN_USE )
	{
		if ( GetDrivableVehicle()->CanExitVehicle(player) )
		{
			if ( !HandlePassengerExit( player ) && ( player != NULL ) )
			{
				player->PlayUseDenySound();
			}
		}
	}
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CBaseServerVehicle::NPC_ThrottleForward( void )
{
	m_nNPCButtons |= IN_FORWARD;
	m_nNPCButtons &= ~IN_BACK;
	m_nNPCButtons &= ~IN_JUMP;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CBaseServerVehicle::NPC_ThrottleReverse( void )
{
	m_nNPCButtons |= IN_BACK;
	m_nNPCButtons &= ~IN_FORWARD;
	m_nNPCButtons &= ~IN_JUMP;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CBaseServerVehicle::NPC_ThrottleCenter( void )
{
	m_nNPCButtons &= ~IN_FORWARD;
	m_nNPCButtons &= ~IN_BACK;
	m_nNPCButtons &= ~IN_JUMP;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CBaseServerVehicle::NPC_Brake( void )
{
	m_nNPCButtons &= ~IN_FORWARD;
	m_nNPCButtons &= ~IN_BACK;
	m_nNPCButtons |= IN_JUMP;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CBaseServerVehicle::NPC_TurnLeft( float flDegrees )
{
	m_nNPCButtons |= IN_MOVELEFT;
	m_nNPCButtons &= ~IN_MOVERIGHT;
	m_flTurnDegrees = -flDegrees;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CBaseServerVehicle::NPC_TurnRight( float flDegrees )
{
	m_nNPCButtons |= IN_MOVERIGHT;
	m_nNPCButtons &= ~IN_MOVELEFT;
	m_flTurnDegrees = flDegrees;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CBaseServerVehicle::NPC_TurnCenter( void )
{
	m_nNPCButtons &= ~IN_MOVERIGHT;
	m_nNPCButtons &= ~IN_MOVELEFT;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CBaseServerVehicle::NPC_PrimaryFire( void )
{
	m_nNPCButtons |= IN_ATTACK;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CBaseServerVehicle::NPC_SecondaryFire( void )
{
	m_nNPCButtons |= IN_ATTACK2;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CBaseServerVehicle::Weapon_PrimaryRanges( float *flMinRange, float *flMaxRange )
{
	*flMinRange = 64;
	*flMaxRange = 1024;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CBaseServerVehicle::Weapon_SecondaryRanges( float *flMinRange, float *flMaxRange )
{
	*flMinRange = 64;
	*flMaxRange = 1024;
}

//-----------------------------------------------------------------------------
// Purpose: Return the time at which this vehicle's primary weapon can fire again
//-----------------------------------------------------------------------------
float CBaseServerVehicle::Weapon_PrimaryCanFireAt( void )
{
	return gpGlobals->curtime;
}

//-----------------------------------------------------------------------------
// Purpose: Return the time at which this vehicle's secondary weapon can fire again
//-----------------------------------------------------------------------------
float CBaseServerVehicle::Weapon_SecondaryCanFireAt( void )
{
	return gpGlobals->curtime;
}

const char *pSoundStateNames[] =
{
	"SS_NONE",
	"SS_SHUTDOWN",
	"SS_SHUTDOWN_WATER",
	"SS_START_WATER",
	"SS_START_IDLE",
	"SS_IDLE",
	"SS_GEAR_0",
	"SS_GEAR_1",
	"SS_GEAR_2",
	"SS_GEAR_3",
	"SS_GEAR_4",
	"SS_SLOWDOWN",
	"SS_SLOWDOWN_HIGHSPEED",
	"SS_GEAR_0_RESUME",
	"SS_GEAR_1_RESUME",
	"SS_GEAR_2_RESUME",
	"SS_GEAR_3_RESUME",
	"SS_GEAR_4_RESUME",
	"SS_TURBO",
	"SS_REVERSE",
};


static int SoundStateIndexFromName( const char *pName )
{
	for ( int i = 0; i < SS_NUM_STATES; i++ )
	{
		Assert( i < ARRAYSIZE(pSoundStateNames) );
		if ( !strcmpi( pSoundStateNames[i], pName ) )
			return i;
	}
	return -1;
}

static const char *SoundStateNameFromIndex( int index )
{
	index = clamp(index, 0, SS_NUM_STATES-1 );
	return pSoundStateNames[index];
}

void CBaseServerVehicle::PlaySound( const char *pSound )
{
	if ( !pSound || !pSound[0] )
		return;

	if ( g_debug_vehiclesound.GetInt() )
	{
		Msg("Playing non-looping vehicle sound: %s\n", pSound );
	}
	m_pVehicle->EmitSound( pSound );
}

void CBaseServerVehicle::StopLoopingSound( float fadeTime )
{
	CSoundEnvelopeController &controller = CSoundEnvelopeController::GetController();
	if ( m_pStateSoundFade )
	{
		controller.SoundDestroy( m_pStateSoundFade );
		m_pStateSoundFade = NULL;
	}
	if ( m_pStateSound )
	{
		m_pStateSoundFade = m_pStateSound;
		m_pStateSound = NULL;
		controller.SoundFadeOut( m_pStateSoundFade, fadeTime, false );
	}
}

void CBaseServerVehicle::PlayLoopingSound( const char *pSoundName )
{
	CSoundEnvelopeController &controller = CSoundEnvelopeController::GetController();

	CPASAttenuationFilter filter( m_pVehicle );
	CSoundPatch *pNewSound = NULL;
	if ( pSoundName && pSoundName[0] )
	{
		pNewSound = controller.SoundCreate( filter, m_pVehicle->entindex(), CHAN_STATIC, pSoundName, ATTN_NORM );
	}

	if ( m_pStateSound && pNewSound && controller.SoundGetName( pNewSound ) == controller.SoundGetName( m_pStateSound ) )
	{
		// if the sound is the same, don't play this, just re-use the old one
		controller.SoundDestroy( pNewSound );
		pNewSound = m_pStateSound;
		controller.SoundChangeVolume( pNewSound, 1.0f, 0.0f );
		m_pStateSound = NULL;
	}
	else if ( g_debug_vehiclesound.GetInt() )
	{
		const char *pStopSound = m_pStateSound ?  controller.SoundGetName( m_pStateSound ).ToCStr() : "NULL";
		const char *pStartSound = pNewSound ?  controller.SoundGetName( pNewSound ).ToCStr() : "NULL";
		Msg("Stop %s, start %s\n", pStopSound, pStartSound );
	}

	StopLoopingSound();
	m_pStateSound = pNewSound;
	if ( m_pStateSound )
	{
		controller.Play( m_pStateSound, 1.0f, 100 );
	}
}

static sound_states MapGearToState( vbs_sound_update_t &params, int gear )
{
	switch( gear )
	{
	case 0: return params.bReverse ? SS_REVERSE : SS_GEAR_0;
	case 1: return SS_GEAR_1;
	case 2: return SS_GEAR_2;
	case 3: return SS_GEAR_3;
	default:case 4: return SS_GEAR_4;
	}
}

static sound_states MapGearToMidState( vbs_sound_update_t &params, int gear )
{
	switch( gear )
	{
	case 0: return params.bReverse ? SS_REVERSE : SS_GEAR_0_RESUME;
	case 1: return SS_GEAR_1_RESUME;
	case 2: return SS_GEAR_2_RESUME;
	case 3: return SS_GEAR_3_RESUME;
	default:case 4: return SS_GEAR_4_RESUME;
	}
}

bool CBaseServerVehicle::PlayCrashSound( float speed )
{
	int i;
	float delta = 0;
	float absSpeed = fabs(speed);
	float absLastSpeed = fabs(m_lastSpeed);
	if ( absLastSpeed > absSpeed )
	{
		delta = fabs(m_lastSpeed - speed);
	}
	
	float rumble = delta / 8.0f;

	if( rumble > 60.0f )
		rumble = 60.0f;

	if( rumble > 5.0f )
	{
		if ( GetDriver() )
		{
			UTIL_ScreenShake( GetDriver()->GetAbsOrigin(), rumble, 150.0f, 1.0f, 240.0f, SHAKE_START_RUMBLEONLY, true );
		}
	}

	for ( i = 0; i < m_vehicleSounds.crashSounds.Count(); i++ )
	{
		const vehicle_crashsound_t &crash = m_vehicleSounds.crashSounds[i];
		if ( !crash.gearLimit )
			continue;

		if ( m_iSoundGear <= crash.gearLimit )
		{
			if ( delta > crash.flMinDeltaSpeed && absLastSpeed > crash.flMinSpeed )
			{
				PlaySound( crash.iszCrashSound.ToCStr() );
				return true;
			}
		}
	}

	for ( i = m_vehicleSounds.crashSounds.Count()-1; i >= 0; --i )
	{
		const vehicle_crashsound_t &crash = m_vehicleSounds.crashSounds[i];
		if ( delta > crash.flMinDeltaSpeed && absLastSpeed > crash.flMinSpeed )
		{
			PlaySound( crash.iszCrashSound.ToCStr() );
			return true;
		}
	}
	return false;
}


bool CBaseServerVehicle::CheckCrash( vbs_sound_update_t &params )
{
	if ( params.bVehicleInWater )
		return false;

	bool bCrashed = PlayCrashSound( params.flWorldSpaceSpeed );
	if ( bCrashed )
	{
		if ( g_debug_vehiclesound.GetInt() )
		{
			Msg("Crashed!: speed %.2f, lastSpeed %.2f\n", params.flWorldSpaceSpeed, m_lastSpeed );
		}
	}
	m_lastSpeed = params.flWorldSpaceSpeed;
	return bCrashed;
}


sound_states CBaseServerVehicle::SoundState_ChooseState( vbs_sound_update_t &params )
{
	float timeInState = gpGlobals->curtime - m_soundStateStartTime;
	bool bInStateForMinTime = timeInState > m_vehicleSounds.minStateTime[m_soundState] ? true : false;

	sound_states stateOut = m_soundState;

	// exit overrides everything else
	if ( params.bExitVehicle )
	{
		switch ( m_soundState )
		{
		case SS_NONE:
		case SS_SHUTDOWN:
		case SS_SHUTDOWN_WATER:
			return m_soundState;
		}
		return SS_SHUTDOWN;
	}

	// check global state in states that don't mask them
	switch( m_soundState )
	{
	// global states masked for these states.
	case SS_NONE:
	case SS_START_IDLE:
	case SS_SHUTDOWN:
		break;
	case SS_START_WATER:
	case SS_SHUTDOWN_WATER:
		if ( !params.bVehicleInWater )
			return SS_START_IDLE;
		break;

	case SS_TURBO:
		if ( params.bVehicleInWater )
			return SS_SHUTDOWN_WATER;
		if ( CheckCrash(params) )
			return SS_IDLE;
		break;
	
	case SS_IDLE:
		if ( params.bVehicleInWater )
			return SS_SHUTDOWN_WATER;
		break;

	case SS_REVERSE:
	case SS_GEAR_0:
	case SS_GEAR_1:
	case SS_GEAR_2:
	case SS_GEAR_3:
	case SS_GEAR_4:
	case SS_SLOWDOWN:
	case SS_SLOWDOWN_HIGHSPEED:
	case SS_GEAR_0_RESUME:
	case SS_GEAR_1_RESUME:
	case SS_GEAR_2_RESUME:
	case SS_GEAR_3_RESUME:
	case SS_GEAR_4_RESUME:
		if ( params.bVehicleInWater )
		{
			return SS_SHUTDOWN_WATER;
		}
		if ( params.bTurbo )
		{
			return SS_TURBO;
		}
		if ( CheckCrash(params) )
			return SS_IDLE;
		break;
	}

	switch( m_soundState )
	{
	case SS_START_IDLE:
		if ( bInStateForMinTime || params.bThrottleDown )
			return SS_IDLE;
		break;
	case SS_IDLE:
		if ( bInStateForMinTime && params.bThrottleDown )
		{
			if ( params.bTurbo )
				return SS_TURBO;
			return params.bReverse ? SS_REVERSE : SS_GEAR_0;
		}
		break;

	case SS_GEAR_0_RESUME:
	case SS_GEAR_0:
		if ( (bInStateForMinTime && !params.bThrottleDown) || params.bReverse )
		{
			return SS_IDLE;
		}
		if ( m_iSoundGear > 0 )
		{
			return SS_GEAR_1;
		}
		break;
	case SS_GEAR_1_RESUME:
	case SS_GEAR_1:
		if ( bInStateForMinTime )
		{
			if ( !params.bThrottleDown )
				return SS_SLOWDOWN;
		}
		if ( m_iSoundGear != 1 )
			return MapGearToState( params, m_iSoundGear);
		break;

	case SS_GEAR_2_RESUME:
	case SS_GEAR_2:
		if ( bInStateForMinTime )
		{
			if ( !params.bThrottleDown )
				return SS_SLOWDOWN;
			else if ( m_iSoundGear != 2 )
				return MapGearToState(params, m_iSoundGear);
		}
		break;

	case SS_GEAR_3_RESUME:
	case SS_GEAR_3:
		if ( bInStateForMinTime )
		{
			if ( !params.bThrottleDown )
				return SS_SLOWDOWN;
			else if ( m_iSoundGear != 3 )
				return MapGearToState(params, m_iSoundGear);
		}
		break;

	case SS_GEAR_4_RESUME:
	case SS_GEAR_4:
		if ( bInStateForMinTime && !params.bThrottleDown )
		{
			return SS_SLOWDOWN;
		}
		if ( m_iSoundGear != 4 )
		{
			return MapGearToMidState(params, m_iSoundGear);
		}
		break;
	case SS_REVERSE:
		if ( bInStateForMinTime && !params.bReverse )
		{
			return SS_SLOWDOWN;
		}
		break;

	case SS_SLOWDOWN_HIGHSPEED:
	case SS_SLOWDOWN:
		if ( params.bThrottleDown )
		{
			// map gears
			return MapGearToMidState(params, m_iSoundGear);
		}
		if ( m_iSoundGear == 0 )
		{
			return SS_IDLE;
		}
		break;

	case SS_NONE:
		stateOut = params.bVehicleInWater ? SS_START_WATER : SS_START_IDLE;
		break;
	case SS_TURBO:
		if ( bInStateForMinTime && !params.bTurbo )
		{
			return MapGearToMidState(params, m_iSoundGear);
		}
		break;
	default:
		break;
	}

	return stateOut;
}

const char *CBaseServerVehicle::StateSoundName( sound_states state )
{
	return m_vehicleSounds.iszStateSounds[state].ToCStr();
}

void CBaseServerVehicle::SoundState_OnNewState( sound_states lastState )
{
	if ( g_debug_vehiclesound.GetInt() )
	{
		int index = m_soundState;
		Msg("Switched to state: %d (%s)\n", m_soundState, SoundStateNameFromIndex(index) );
	}

	switch ( m_soundState )
	{
	case SS_SHUTDOWN:
	case SS_SHUTDOWN_WATER:
	case SS_START_WATER:
		StopLoopingSound();
		PlaySound( StateSoundName(m_soundState) );
		break;
	case SS_IDLE:
		m_lastSpeed = -1;
		PlayLoopingSound( StateSoundName(m_soundState) );
		break;
	case SS_START_IDLE:
	case SS_REVERSE:
	case SS_GEAR_0:
	case SS_GEAR_0_RESUME:
	case SS_GEAR_1:
	case SS_GEAR_1_RESUME:
	case SS_GEAR_2:
	case SS_GEAR_2_RESUME:
	case SS_GEAR_3:
	case SS_GEAR_3_RESUME:
	case SS_GEAR_4:
	case SS_GEAR_4_RESUME:
	case SS_TURBO:
		PlayLoopingSound( StateSoundName(m_soundState) );
		break;

	case SS_SLOWDOWN_HIGHSPEED:
	case SS_SLOWDOWN:
		if ( m_iSoundGear < 2 )
		{
			PlayLoopingSound( StateSoundName( SS_SLOWDOWN ) );
		}
		else
		{
			PlayLoopingSound( StateSoundName( SS_SLOWDOWN_HIGHSPEED ) );
		}
		break;
		
	default:break;
	}

	m_soundStateStartTime = gpGlobals->curtime;
}


void CBaseServerVehicle::SoundState_Update( vbs_sound_update_t &params )
{
	sound_states newState = SoundState_ChooseState( params );
	if ( newState != m_soundState )
	{
		sound_states lastState = m_soundState;
		m_soundState = newState;
		SoundState_OnNewState( lastState );
	}

	switch( m_soundState )
	{
	case SS_SHUTDOWN:
	case SS_SHUTDOWN_WATER:
	case SS_START_WATER:
	case SS_START_IDLE:
	case SS_IDLE:
	case SS_REVERSE:
	case SS_GEAR_0:
	case SS_GEAR_4:
	case SS_SLOWDOWN_HIGHSPEED:
	case SS_SLOWDOWN:
	case SS_GEAR_0_RESUME:
	case SS_GEAR_4_RESUME:
		break;
	default:break;
	}
}

void CBaseServerVehicle::InitSoundParams( vbs_sound_update_t &params )
{
	params.Defaults();
	params.bVehicleInWater = IsVehicleBodyInWater();
}

//-----------------------------------------------------------------------------
// Purpose: Vehicle Sound Start
//-----------------------------------------------------------------------------
void CBaseServerVehicle::SoundStart()
{
	StartEngineRumble();

	m_soundState = SS_NONE;
	vbs_sound_update_t params;
	InitSoundParams(params);

	SoundState_Update( params );
}

// vehicle is starting up disabled, but in some cases you still want to play a sound
// HACK: handle those here.
void CBaseServerVehicle::SoundStartDisabled()
{
	m_soundState = SS_NONE;
	vbs_sound_update_t params;
	InitSoundParams(params);
	sound_states newState = SoundState_ChooseState( params );

	switch( newState )
	{
	case SS_START_WATER:
		PlaySound( StateSoundName(newState) );
		break;
	}
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CBaseServerVehicle::SoundShutdown( float flFadeTime )
{
	StopEngineRumble();

	// Stop any looping sounds that may be running, as the following stop sound may not exist
	// and thus leave a looping sound playing after the user gets out.
	for ( int i = 0; i < NUM_SOUNDS_TO_STOP_ON_EXIT; i++ )
	{
		StopSound( g_iSoundsToStopOnExit[i] );
	}

	CSoundEnvelopeController &controller = CSoundEnvelopeController::GetController();
	if ( m_pStateSoundFade )
	{
		controller.SoundFadeOut( m_pStateSoundFade, flFadeTime, true );
		m_pStateSoundFade = NULL;
	}
	if ( m_pStateSound )
	{
		controller.SoundFadeOut( m_pStateSound, flFadeTime, true );
		m_pStateSound = NULL;
	}
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CBaseServerVehicle::SoundUpdate( vbs_sound_update_t &params )
{
	if ( g_debug_vehiclesound.GetInt() > 1 )
	{
		Msg("Throttle: %s, Reverse: %s\n", params.bThrottleDown?"on":"off", params.bReverse?"on":"off" );
	}

	float flCurrentSpeed = params.flCurrentSpeedFraction;
	if ( g_debug_vehiclesound.GetInt() > 1 )
	{
		Msg("CurrentSpeed: %.3f  ", flCurrentSpeed );
	}

	// Figure out our speed for the purposes of sound playing.
	// We slow the transition down a little to make the gear changes slower.
	if ( m_vehicleSounds.pGears.Count() > 0 )
	{
		if ( flCurrentSpeed > m_flSpeedPercentage )
		{
			// don't accelerate when the throttle isn't down
			if ( !params.bThrottleDown )
			{
				flCurrentSpeed = m_flSpeedPercentage;
			}
			flCurrentSpeed = Approach( flCurrentSpeed, m_flSpeedPercentage, params.flFrameTime * m_vehicleSounds.pGears[m_iSoundGear].flSpeedApproachFactor );
		}
	}
	m_flSpeedPercentage = clamp( flCurrentSpeed, 0.0f, 1.0f );

	if ( g_debug_vehiclesound.GetInt() > 1 )
	{
		Msg("Sound Speed: %.3f\n", m_flSpeedPercentage );
	}

	// Only do gear changes when the throttle's down
	RecalculateSoundGear( params );

	SoundState_Update( params );
}

//-----------------------------------------------------------------------------
// Purpose: Play a non-gear based vehicle sound
//-----------------------------------------------------------------------------
void CBaseServerVehicle::PlaySound( vehiclesound iSound )
{
	if ( m_vehicleSounds.iszSound[iSound] != NULL_STRING )
	{
		CPASAttenuationFilter filter( m_pVehicle );

		EmitSound_t ep;
		ep.m_nChannel = CHAN_VOICE;
		ep.m_pSoundName = STRING(m_vehicleSounds.iszSound[iSound]);
		ep.m_flVolume = m_flVehicleVolume;
		ep.m_SoundLevel = SNDLVL_NORM;

		CBaseEntity::EmitSound( filter, m_pVehicle->entindex(), ep );
		if ( g_debug_vehiclesound.GetInt() )
		{
			Msg("Playing vehicle sound: %s\n", ep.m_pSoundName );
		}
	}
}

//-----------------------------------------------------------------------------
// Purpose: Stop a non-gear based vehicle sound
//-----------------------------------------------------------------------------
void CBaseServerVehicle::StopSound( vehiclesound iSound )
{
	if ( m_vehicleSounds.iszSound[iSound] != NULL_STRING )
	{
		CBaseEntity::StopSound( m_pVehicle->entindex(), CHAN_VOICE, STRING(m_vehicleSounds.iszSound[iSound]) );
	}
}

//-----------------------------------------------------------------------------
// Purpose: Calculate the gear we should be in based upon the vehicle's current speed
//-----------------------------------------------------------------------------
void CBaseServerVehicle::RecalculateSoundGear( vbs_sound_update_t &params )
{
	int iNumGears = m_vehicleSounds.pGears.Count();
	for ( int i = (iNumGears-1); i >= 0; i-- )
	{
		if ( m_flSpeedPercentage > m_vehicleSounds.pGears[i].flMinSpeed )
		{
			m_iSoundGear = i;
			break;
		}
	}

	// If we're going in reverse, we want to stay in first gear
	if ( params.bReverse )
	{
		m_iSoundGear = 0;
	}
}

//---------------------------------------------------------
//---------------------------------------------------------
void CBaseServerVehicle::StartEngineRumble()
{
	return;
}

//---------------------------------------------------------
//---------------------------------------------------------
void CBaseServerVehicle::StopEngineRumble()
{
	return;
}

//-----------------------------------------------------------------------------
// Purpose: Find the passenger in the given seat of the vehicle
// Input  : nSeatID - seat ID to check
// Output : CBaseCombatCharacter - character in the seat
//-----------------------------------------------------------------------------
CBaseCombatCharacter *CBaseServerVehicle::NPC_GetPassengerInSeat( int nRoleID, int nSeatID )
{
	// Search all passengers in the vehicle
	for ( int i = 0; i < m_PassengerInfo.Count(); i++ )
	{
		// If the seat ID matches, return the entity in that seat
		if ( m_PassengerInfo[i].GetSeat() == nSeatID && m_PassengerInfo[i].GetRole() == nRoleID )
			return m_PassengerInfo[i].m_hPassenger;
	}

	return NULL;
}

//-----------------------------------------------------------------------------
// Purpose: Find the first available seat (ranked by priority)
// Input  : nRoleID - Role index
// Output : int - Seat by index
//-----------------------------------------------------------------------------
int CBaseServerVehicle::NPC_GetAvailableSeat_Any( CBaseCombatCharacter *pPassenger, int nRoleID )
{
	// Look through all available seats
	for ( int i = 0; i < m_PassengerRoles[nRoleID].m_PassengerSeats.Count(); i++ )
	{
		// See if anyone is already in this seat
		CBaseCombatCharacter *pCurrentPassenger = NPC_GetPassengerInSeat( nRoleID, i );
		if ( pCurrentPassenger != NULL && pCurrentPassenger != pPassenger )
			continue;

		// This seat is open
		return i;
	}

	// Nothing found
	return -1;
}

//-----------------------------------------------------------------------------
// Purpose: Find the seat with the nearest entry point to the querier
// Input  : *pPassenger - Terget to be nearest to
//			nRoleID - Role index
// Output : int - Seat by index
//-----------------------------------------------------------------------------
int CBaseServerVehicle::NPC_GetAvailableSeat_Nearest( CBaseCombatCharacter *pPassenger, int nRoleID )
{
	// Not yet implemented
	Assert( 0 );
	return -1;
}

//-----------------------------------------------------------------------------
// Purpose: Get a seat in the vehicle based on our role and criteria
// Input  : *pPassenger - Entity attempting to find a seat
//			strRoleName - Role the seat must serve
//			nQueryType -  Method for choosing the best seat (if multiple)
// Output : int - Seat by unique ID
//-----------------------------------------------------------------------------
int CBaseServerVehicle::NPC_GetAvailableSeat( CBaseCombatCharacter *pPassenger, string_t strRoleName, VehicleSeatQuery_e nQueryType )
{
	// Parse the vehicle animations the first time they get in the vehicle
	if ( m_bParsedAnimations == false )
	{
		// Load the entry/exit animations from the vehicle
		ParseEntryExitAnims();
		m_bParsedAnimations = true;
	}

	// Get the role index
	int nRole = FindRoleIndexByName( strRoleName );
	if ( m_PassengerRoles.IsValidIndex( nRole ) == false )
		return -1;

	switch( nQueryType )
	{
	case VEHICLE_SEAT_ANY:
		return NPC_GetAvailableSeat_Any( pPassenger, nRole );
		break;

	case VEHICLE_SEAT_NEAREST:
		return NPC_GetAvailableSeat_Nearest( pPassenger, nRole );
		break;

	default:
		Assert( 0 );
		break;
	};

	return -1;
}

//-----------------------------------------------------------------------------
// Purpose: Determine if there's an available seat of a given role name
// Input  : strRoleName - name of the role
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CBaseServerVehicle::NPC_HasAvailableSeat( string_t strRoleName )
{
	return ( NPC_GetAvailableSeat( NULL, strRoleName, VEHICLE_SEAT_ANY ) != -1 );
}

//-----------------------------------------------------------------------------
// Purpose: Find a role index by name
// Input  : strRoleName - name of the role
//-----------------------------------------------------------------------------
int CBaseServerVehicle::FindRoleIndexByName( string_t strRoleName )
{
	// Search through all our known roles
	for ( int i = 0; i < m_PassengerRoles.Count(); i++ )
	{
		// Return the index if the name matches
		if ( FStrEq( STRING( m_PassengerRoles[i].GetName() ), STRING( strRoleName ) ) )
			return i;
	}

	return -1;
}

//-----------------------------------------------------------------------------
// Purpose: Find a seat index by its name
// Input  : strSeatName - name of the seat
//-----------------------------------------------------------------------------
int CBaseServerVehicle::FindSeatIndexByName( int nRoleIndex, string_t strSeatName )
{
	// Role must be valid
	if ( m_PassengerRoles.IsValidIndex( nRoleIndex ) == false )
		return -1;

	// Used for attachment polling
	CBaseAnimating *pAnimating = dynamic_cast<CBaseAnimating *>(GetVehicleEnt());
	if ( pAnimating == NULL )
		return -1;

	// Get the index of the named attachment in the model
	int nAttachmentID = pAnimating->LookupAttachment( STRING( strSeatName ) );

	// Look through the roles for this seat attachment ID
	for ( int i = 0; i < m_PassengerRoles[nRoleIndex].m_PassengerSeats.Count(); i++ )
	{
		// Return that index if found
		if ( m_PassengerRoles[nRoleIndex].m_PassengerSeats[i].GetAttachmentID() == nAttachmentID )
			return i;
	}

	return -1;
}

//-----------------------------------------------------------------------------
// Purpose: Called after loading a saved game
//-----------------------------------------------------------------------------
void CBaseServerVehicle::RestorePassengerInfo( void )
{
	// If there is passenger information, then we have passengers in the vehicle
	if ( m_PassengerInfo.Count() != 0 && m_bParsedAnimations == false )
	{
		// Load the entry/exit animations from the vehicle
		ParseEntryExitAnims();
		m_bParsedAnimations = true;
	}

	// FIXME: If a passenger cannot fix-up its indices, it must be removed from the vehicle!

	// Fix-up every passenger with updated indices
	for ( int i = 0; i < m_PassengerInfo.Count(); i++ )
	{
		// Fix up the role first
		int nRoleIndex = FindRoleIndexByName( m_PassengerInfo[i].m_strRoleName );
		if ( m_PassengerRoles.IsValidIndex( nRoleIndex ) )
		{
			// New role index
			m_PassengerInfo[i].m_nRole = nRoleIndex;
			
			// Then fix up the seat via attachment name
			int nSeatIndex = FindSeatIndexByName( nRoleIndex, m_PassengerInfo[i].m_strSeatName );
			if ( m_PassengerRoles[nRoleIndex].m_PassengerSeats.IsValidIndex( nSeatIndex ) )
			{
				// New seat index
				m_PassengerInfo[i].m_nSeat = nSeatIndex;
			}
			else
			{
				// The seat attachment was not found.  This most likely means that the seat attachment name has changed
				// in the target vehicle and the NPC passenger is now stranded!
				Assert( 0 );
			}
		}
		else
		{
			// The role was not found.  This most likely means that the role names have changed
			// in the target vehicle and the NPC passenger is now stranded!
			Assert( 0 );
		}
	}
}

void CBaseServerVehicle::ReloadScript()
{
	if ( m_pDrivableVehicle )
	{
		string_t script = m_pDrivableVehicle->GetVehicleScriptName();
		IPhysicsVehicleController *pController = GetVehicleController();
		vehicleparams_t *pVehicleParams = pController ? &(pController->GetVehicleParamsForChange()) : NULL;
		PhysFindOrAddVehicleScript( script.ToCStr(), pVehicleParams, &m_vehicleSounds );
		if ( pController )
		{
			pController->VehicleDataReload();
		}
	}
}

//-----------------------------------------------------------------------------
// Purpose: Passes this call down into the server vehicle where the tests are done
//-----------------------------------------------------------------------------
bool CBaseServerVehicle::PassengerShouldReceiveDamage( CTakeDamageInfo &info )
{ 
	if ( GetDrivableVehicle() )
		return GetDrivableVehicle()->PassengerShouldReceiveDamage( info );

	return true;
}

//===========================================================================================================
// Vehicle Sounds
//===========================================================================================================

// These are sounds that are to be automatically stopped whenever the vehicle's driver leaves it
vehiclesound g_iSoundsToStopOnExit[] =
{
	VS_ENGINE2_START,
	VS_ENGINE2_STOP,
};

const char *vehiclesound_parsenames[VS_NUM_SOUNDS] =
{
	"skid_lowfriction",
	"skid_normalfriction",
	"skid_highfriction",
	"engine2_start",
	"engine2_stop",
	"misc1",
	"misc2",
	"misc3",
	"misc4",
};

CVehicleSoundsParser::CVehicleSoundsParser( void )
{
	// UNDONE: Revisit this pattern - move sub-block processing ideas into the parser architecture
	m_iCurrentGear = -1;
	m_iCurrentState = -1;
	m_iCurrentCrashSound = -1;
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CVehicleSoundsParser::ParseKeyValue( void *pData, const char *pKey, const char *pValue )
{
	vehiclesounds_t *pSounds = (vehiclesounds_t *)pData;
	// New gear?
	if ( !strcmpi( pKey, "gear" ) )
	{
		// Create, initialize, and add a new gear to our list
		int iNewGear = pSounds->pGears.AddToTail();
		pSounds->pGears[iNewGear].flMaxSpeed = 0;
		pSounds->pGears[iNewGear].flSpeedApproachFactor = 1.0;

		// Set our min speed to the previous gear's max
		if ( iNewGear == 0 )
		{
			// First gear, so our minspeed is 0
			pSounds->pGears[iNewGear].flMinSpeed = 0;
		}
		else
		{
			pSounds->pGears[iNewGear].flMinSpeed = pSounds->pGears[iNewGear-1].flMaxSpeed;
		}

		// Remember which gear we're reading data from
		m_iCurrentGear = iNewGear;
	}
	else if ( !strcmpi( pKey, "state" ) )
	{
		m_iCurrentState = 0;
	}
	else if ( !strcmpi( pKey, "crashsound" ) )
	{
		m_iCurrentCrashSound = pSounds->crashSounds.AddToTail();
		pSounds->crashSounds[m_iCurrentCrashSound].flMinSpeed = 0;
		pSounds->crashSounds[m_iCurrentCrashSound].flMinDeltaSpeed = 0;
		pSounds->crashSounds[m_iCurrentCrashSound].iszCrashSound = NULL_STRING;
	}
	else
	{
		int i;

		// Are we currently in a gear block?
		if ( m_iCurrentGear >= 0 )
		{
			Assert( m_iCurrentGear < pSounds->pGears.Count() );

			// Check gear keys
			if ( !strcmpi( pKey, "max_speed" ) )
			{
				pSounds->pGears[m_iCurrentGear].flMaxSpeed = atof(pValue);
				return;
			}
			if ( !strcmpi( pKey, "speed_approach_factor" ) )
			{
				pSounds->pGears[m_iCurrentGear].flSpeedApproachFactor = atof(pValue);
				return;
			}
		}
		// We're done reading a gear, so stop checking them.
		m_iCurrentGear = -1;

		if ( m_iCurrentState >= 0 )
		{
			if ( !strcmpi( pKey, "name" ) )
			{
				m_iCurrentState = SoundStateIndexFromName( pValue );
				pSounds->iszStateSounds[m_iCurrentState] = NULL_STRING;
				pSounds->minStateTime[m_iCurrentState] = 0.0f;
				return;
			}
			else if ( !strcmpi( pKey, "sound" ) )
			{
				pSounds->iszStateSounds[m_iCurrentState] = AllocPooledString(pValue);
				return;
			}
			else if ( !strcmpi( pKey, "min_time" ) )
			{
				pSounds->minStateTime[m_iCurrentState] = atof(pValue);
				return;
			}
		}
		// 
		m_iCurrentState = -1;

		if ( m_iCurrentCrashSound >= 0 )
		{
			if ( !strcmpi( pKey, "min_speed" ) )
			{
				pSounds->crashSounds[m_iCurrentCrashSound].flMinSpeed = atof(pValue);
				return;
			}
			else if ( !strcmpi( pKey, "sound" ) )
			{
				pSounds->crashSounds[m_iCurrentCrashSound].iszCrashSound = AllocPooledString(pValue);
				return;
			}
			else if ( !strcmpi( pKey, "min_speed_change" ) )
			{
				pSounds->crashSounds[m_iCurrentCrashSound].flMinDeltaSpeed = atof(pValue);
				return;
			}
			else if ( !strcmpi( pKey, "gear_limit" ) )
			{
				pSounds->crashSounds[m_iCurrentCrashSound].gearLimit = atoi(pValue);
				return;
			}
		}
		m_iCurrentCrashSound = -1;

		for ( i = 0; i < VS_NUM_SOUNDS; i++ )
		{
			if ( !strcmpi( pKey, vehiclesound_parsenames[i] ) )
			{
				pSounds->iszSound[i] = AllocPooledString(pValue);
				return;
			}
		}
	}
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CVehicleSoundsParser::SetDefaults( void *pData ) 
{
	vehiclesounds_t *pSounds = (vehiclesounds_t *)pData;
	pSounds->Init();
}