aboutsummaryrefslogtreecommitdiff
path: root/Northstar.Custom/mod/scripts/vscripts/rodeo/_rodeo_titan.gnut
blob: 788b6dbed1f9f00155b43821e9e97d4605d4a424 (plain)
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
untyped //Panel.s stuff needs to be typed

global function RodeoTitan_Init

global function EnableTitanRodeo
global function DisableTitanRodeo
global function DebugRodeoTimes
global function PlayerBeginsTitanRodeo
global function ForceTitanRodeoToEnd
global function PlayerRodeoViewCone
global function OpenViewCone
global function RodeoPanelIsOpen
global function PlayerRemovesBatteryPack
global function Rodeo_PilotAddsBatteryToFriendlyTitan
global function GiveFriendlyRodeoPlayerProtection
global function TakeAwayFriendlyRodeoPlayerProtection
global function Rodeo_GiveBatteryToPlayer
global function Rodeo_PilotThrowsBattery
global function Rodeo_RemoveBatteryOffPlayer
global function Rodeo_RemoveAllBatteriesOffPlayer
global function Rodeo_GiveExecutingTitanABattery
global function Rodeo_CreateBatteryPack
global function SetSoulBatteryCount
global function GetPlayerBatteryCount
global function PlayerHasMaxBatteryCount
global function Rodeo_PilotPicksUpBattery_Silent

global function AddOnRodeoStartedCallback
global function AddOnRodeoEndedCallback

global function PilotBattery_SetMaxCount
global function ThrowRiderOff

global function Burnmeter_EmergencyBattery
global function Burnmeter_AmpedBattery

global function Battery_StartFX
global function Battery_StopFX
global function Battery_StopFXAndHideIconForPlayer

global function RemovePlayerAirControl //This function should really be in a server only SP & MP utility script file. No such file exists as of right now.
global function RestorePlayerAirControl //This function should really be in a server only SP & MP utility script file. No such file exists as of right now.

#if DEV
global function SetDebugRodeoPrint
global function GetDebugRodeoPrint
#endif

#if MP
global function SetApplyBatteryCallback
#endif

const float BATTERY_PICKUP_IGNORE_FRAC = 0.98
const RODEO_EXPLOSION_DAMAGEFRAC = 0.3
global const RODEO_BATTERY_MODEL_FOR_RODEO_ANIMS = $"models/props/titan_battery_static/titan_battery_static.mdl" //Need a separate one for rodeo anims, instead of manually rotating the existing one
const RODEO_BATTERY_RIP_PILOT_PUSHED_OFF_VERTICAL_HEIGHT = 80
const RODEO_BATTERY_RIP_PILOT_PUSHED_OFF_HORIZONTAL_SPEED = 450
const RODEO_THROW_BATTERY_BUTTON_HOLD_TIME = 0.5
const RODEO_CLAMBER_FAILED_SOUND_DEBOUNCE_TIME = 2.0
global const BATTERY_FX_FRIENDLY = $"P_xo_battery"
global const BATTERY_FX_AMPED = $"P_xo_battery_amped"

const HAS_BATTERY_THIEF_ICON = false

const string PILOT_PICKS_UP_BATTERY_SOUND = "UI_TitanBattery_Pilot_PickUp"
const string PILOT_APPLIES_BATTERY_TO_TITAN_HEALTH_RESTORED_SOUND = "UI_TitanBattery_Pilot_Give_TitanBattery"


global int RODEO_BATTERY_EXPLOSION_EFFECT

const string TITAN_GOT_BATTERY_RIPPED_SOUND = "UI_TitanBattery_Pilot_Take_TitanBattery"

global float ANTI_RODEO_DEFAULT_START_DELAY = 0.5
global float ANTI_RODEO_DEFAULT_DRAIN_DURATION = 1.25
global float ANTI_RODEO_DEFAULT_WINDOW_DURATION = 0.1
global float ANTI_RODEO_DEFAULT_WINDOW_START = 0.55

struct AntiRodeoPlayerData
{
	bool antiRodeoPressed
	float startTime
	float windowStartFrac
	float windowEndFrac
	entity antiRodeoPlayer
	bool wasCrouched
}

struct
{
	array<void functionref(entity,entity)> onRodeoEndedCallbacks
	array<void functionref(entity,entity)> onRodeoStartedCallbacks

	table<entity, AntiRodeoPlayerData> antiRodeoPlayerData

	int maxPilotBatteryCount = 1
	bool debugRodeoPrint = false

	table<entity, bool> playersThatWantToUseRodeoGrenade

	void functionref(entity,entity,entity) applyBatteryCallback
} file

//-----------------------------------------------------------------------------
//  _rodeo_titan.nut
//
//  Script for a player (pilot) rodoeing a titan.
//
//-----------------------------------------------------------------------------

void function RodeoTitan_Init()
{
	PrecacheParticleSystem( $"P_impact_rodeo_damage" ) //Rodeo hit spark
	PrecacheParticleSystem( $"P_rodeo_damage_1" )  //DamageState1
	PrecacheParticleSystem( $"P_rodeo_damage_2" )  //DamageState2
	PrecacheParticleSystem( $"P_rodeo_damage_3" )  //DamageState3
	PrecacheParticleSystem( BATTERY_FX_FRIENDLY )
	PrecacheParticleSystem( BATTERY_FX_AMPED )

	RegisterSignal( "CancelAirControlLoss" )
	RegisterSignal( "FriendlyRodeoDeployWeapon" )
	RegisterSignal( "MonitorRodeoPastPointOfNoReturn" )
	RegisterSignal( "PostRodeoAirControl" )
	PrecacheModel( RODEO_BATTERY_MODEL )
	PrecacheModel( RODEO_BATTERY_MODEL_FOR_RODEO_ANIMS )

	AddSoulDeathCallback( SoulRodeoEnds )
	AddSoulTransferFunc( RecreateRodeoPanelDamageFX )

	RODEO_BATTERY_EXPLOSION_EFFECT = PrecacheParticleSystem( $"P_impact_exp_FRAG_metal" )

	AddCallback_OnPlayerKilled( Rodeo_DropAllBatteriesOnDeath )
	AddCallback_OnTouchHealthKit( "item_titan_battery", Rodeo_OnTouchBatteryPack )
	AddCallback_OnPilotBecomesTitan( Rodeo_ApplyAllBatteriesOnEmbark )

	//AddSoulInitFunc( Rodeo_HealthDecayThink )

	if ( IsMultiplayer() )
	{
		//AddDeathCallback( "player", TitanDropsBatteryOnDeath ) //SP has its own functions. Maybe we should just copy SP's stuff? They have the green highlight FX for it too
		//AddDeathCallback( "npc_titan", TitanDropsBatteryOnDeath ) //SP has its own functions. Maybe we should just copy SP's stuff? They have the green highlight FX for it too

		AddDamageCallback( "player", ShowRequestRodeoBatteryHint_OnDamage )
		AddCallback_OnPilotBecomesTitan( ShowRequestRodeoBatteryHint_OnPilotBecomesTitan )

		AddClientCommandCallback( "OfferRodeoBattery", ClientCommand_OfferRodeoBattery )
		AddClientCommandCallback( "RequestRodeoBattery", ClientCommand_RequestRodeoBattery )

		#if MP
		AddClientCommandCallback( "TryNukeGrenade", ClientCommand_TryNukeGrenade )
		RegisterSignal( "TryNukeGrenade" )
		RegisterSignal( "RodeoNukeWindowEnded" )
		#endif
	}
	else
	{
		AddSoulInitFunc( DisableBTRodeo )
	}
}

void function Rodeo_HealthDecayThink( entity soul ) //Remove if we don't want rodeo battery to drain health
{
	thread Rodeo_HealthDecayThinkInternal( soul )
}

void function Rodeo_HealthDecayThinkInternal( entity soul ) //Remove if we don't want rodeo battery to drain health
{
	soul.EndSignal( "OnDestroy" ) //This needs to be OnDestroy instead of OnDeath because souls don't have a death animation
	soul.EndSignal( "OnTitanDeath" )

	bool draining = false

	while ( 1 )
	{
		entity titan = soul.GetTitan()

		if ( Rodeo_ShouldDrainHealth( soul ) )
		{
			if ( !draining )
			{
				draining = true
				EmitSoundOnEntity( titan, "titan_energyshield_down" )
			}

			int damageAmout = Rodeo_GetDrainAmount( soul )

			titan.TakeDamage( damageAmout, soul.e.lastRodeoAttacker, soul.e.lastRodeoAttacker, { scriptType = damageTypes.rodeoBatteryRemoval | DF_NO_INDICATOR, damageSourceId = eDamageSourceId.rodeo_battery_removal, hitbox = 2 } )
		}
		else
		{
			if ( draining )
			{
				draining = false
				StopSoundOnEntity( titan, "titan_energyshield_down" )
			}
		}
		WaitFrame()
	}
}

bool function Rodeo_ShouldDrainHealth( entity soul ) //Remove if we don't want rodeo battery to drain health
{
	entity titan = soul.GetTitan()
	if ( !IsAlive( titan ) )
		return false

	if ( GetDoomedState( titan ) )
		return false

	int batt = GetSoulBatteryCount( soul )
	int maxBattHealth = GetSegmentHealthForTitan( titan ) * batt
	int health = titan.GetHealth()
	return ( health > maxBattHealth )
}

int function Rodeo_GetDrainAmount( entity soul ) //Remove if we don't want rodeo battery to drain health
{
	entity titan = soul.GetTitan()

	float damagePerSec = GetSegmentHealthForTitan( titan ) / RODEO_DRAIN_TIME
	float damagePerFrame = ceil( GetSegmentHealthForTitan( titan ) / RODEO_DRAIN_TIME ) * 0.1
	int damageAmout =  int( damagePerFrame )

	int batt = GetSoulBatteryCount( soul )
	int maxBattHealth = GetSegmentHealthForTitan( titan ) * batt
	int health = titan.GetHealth()
	if ( health - maxBattHealth < damageAmout )
		damageAmout = health - maxBattHealth

	return damageAmout
}

void function GiveFriendlyRodeoPlayerProtection( entity titan )
{
	entity friendlyRider = GetFriendlyRodeoPilot( titan )
	if ( IsValid( friendlyRider ) )
	{
		//printt( "Set friendlyRider PassDamageToParent true" )
		friendlyRider.kv.PassDamageToParent = true //rodeo player now passes damage to titan
	}
}

void function TakeAwayFriendlyRodeoPlayerProtection( entity titan )
{
	entity friendlyRider = GetFriendlyRodeoPilot( titan )
	if ( IsValid( friendlyRider ) )
	{
		//printt( "Set friendlyRider PassDamageToParent false" )
		friendlyRider.kv.PassDamageToParent = false //rodeo player now takes full damage
	}
}

void function CreateSparksInsideTitanPanel( panel )
{
	entity impactSpark = CreateEntity( "info_particle_system" )
	impactSpark.kv.start_active = 1
	impactSpark.kv.VisibilityFlags = ENTITY_VISIBLE_TO_EVERYONE
	impactSpark.SetValueForEffectNameKey( $"P_impact_rodeo_damage" )
	SetTargetName( impactSpark, UniqueString() )
	impactSpark.SetParent( panel, "hatch", false, 0 )
	DispatchSpawn( impactSpark )
	impactSpark.Kill_Deprecated_UseDestroyInstead( 1.5 )
}


void function CreateDamageStateParticlesForPanel( var panel, asset particleSystem = $"P_impact_rodeo_damage" )
{
	entity impactSpark = CreateEntity( "info_particle_system" )
	impactSpark.kv.start_active = 1
	impactSpark.SetOwner( panel.GetParent() )
	impactSpark.kv.VisibilityFlags = (ENTITY_VISIBLE_TO_FRIENDLY | ENTITY_VISIBLE_TO_ENEMY) // not visible to owner
	impactSpark.SetValueForEffectNameKey( particleSystem )
	SetTargetName( impactSpark, UniqueString() )
	impactSpark.SetParent( panel, "hatch", false, 0 )
	DispatchSpawn( impactSpark )
	if ( IsValid( panel.s.lastDamageStateParticleSystem ) )
	{
		//printt("Killing particle system: " + panel.s.lastDamageStateParticleSystem)
		panel.s.lastDamageStateParticleSystem.Kill_Deprecated_UseDestroyInstead()
	}

	panel.s.lastDamageStateParticleSystem = impactSpark
}


void function RecreateRodeoPanelDamageFX( entity soul, entity titan, entity oldTitan )
{
	thread RecreateRodeoPanelDamageFX_threaded( soul )
}


void function RecreateRodeoPanelDamageFX_threaded( entity soul )
{
	WaitEndFrame()
	entity panel = soul.soul.batteryContainer

	if (! IsValid( panel ) )
		return

	entity lastDamageStateParticleSystem = expect entity ( panel.s.lastDamageStateParticleSystem )

	if ( IsValid( lastDamageStateParticleSystem ) )
	{
		CreateDamageStateParticlesForPanel( panel, lastDamageStateParticleSystem.GetValueForEffectNameKey() ) //This kills the last particle system too
	}
}

void function RodeoPanelIsOpen( entity panel )
{
	panel.s.opened = true

	entity titan = panel.GetParent()
	Assert( titan.IsTitan() )

	entity soul = titan.GetTitanSoul()
	Assert( IsValid( soul ) )

	soul.SetLastRodeoHitTime( Time() ) //Make warning always trigger now when panel is ripped
	soul.soul.batteryContainerBeingUsed = false
}

void function RodeoBatteryRemoval( entity pilot )
{
	entity titan = GetTitanBeingRodeoed( pilot )
	if ( !IsValid( titan ) )
		return

	// THROW RODEO RIDER OFF
	entity soul = titan.GetTitanSoul()
	string titanType = GetSoulTitanSubClass( soul )

	soul.SetLastRodeoHitTime( Time() )

	RodeoBatteryPackRemovalDamage( pilot, titan, soul )

	bool playerHadBattery = PlayerHasBattery( pilot )

	if ( !playerHadBattery )
	{
		AddPlayerScore( pilot, "PilotBatteryStolen" )
		entity battery = Rodeo_CreateBatteryPack( titan )
		Rodeo_PilotPicksUpBattery( pilot, battery )
		thread BatteryThiefHighlight( pilot )

		if ( titan.IsPlayer() )
		{
			EmitSoundOnEntityOnlyToPlayer( titan, titan, TITAN_GOT_BATTERY_RIPPED_SOUND ) //Consider playing this in world once we get sounds that aren't just notification beeps
		}
	}

	vector direction = CalculateDirectionToThrowOffBatteryThief( pilot, titan )

	// for classic rodeo, let them stay on
	if ( GetCurrentPlaylistVarInt( "classic_rodeo", 0 ) == 0 )
		ThrowRiderOff( pilot, titan, direction ) //This signals RodeoOver

	#if MP
		PIN_PlayerRodeoedEnemyTitanToCompletion( pilot, titan, playerHadBattery )
	#endif
}

void function RodeoBatteryGrenadeShow( entity pilot )
{
	entity titanSoul = pilot.GetTitanSoulBeingRodeoed()
	Assert( IsValid( titanSoul ) )

	foreach( tempProp in pilot.p.rodeoAnimTempProps )
	{
		tempProp.Show()
	}
}

void function RodeoBatteryRemoval_ShowBattery( entity pilot )
{
	foreach( tempProp in pilot.p.rodeoAnimTempProps )
	{
		tempProp.Show()
	}

	entity titanSoul = pilot.GetTitanSoulBeingRodeoed()

	string titanType = GetSoulTitanSubClass( titanSoul )

	entity batteryContainer = titanSoul.soul.batteryContainer
	batteryContainer.Anim_Play( GetAnimFromAlias( titanType, "hatch_rodeo_down_idle" )  )

}


void function RodeoBatteryStealthMovementWarning( entity pilot )
{
	if ( !PlayerHasPassive( pilot, ePassives.PAS_STEALTH_MOVEMENT ) )
		return

	entity titanSoul = pilot.GetTitanSoulBeingRodeoed()

	titanSoul.SetLastRodeoHitTime( Time() ) //This shows the warning icon on the Titan's hud
}

vector function CalculateDirectionToThrowOffBatteryThief( entity batteryThief, entity titan )
{
	vector backward
	vector right

	if ( titan.IsPlayer() )
	{
		backward = titan.GetViewForward() * -1.0
		right = titan.GetViewRight()
	}
	else
	{
		backward = titan.GetForwardVector() * -1.0
		right = titan.GetRightVector()
	}

	backward.z = 0
	right.z = 0

	backward = Normalize( backward )
	right = Normalize( right )

	// map the player's controls to his angles, and add that velocity
	float xAxis = batteryThief.GetInputAxisRight()
	float yAxis = batteryThief.GetInputAxisForward()

	xAxis = GraphCapped( xAxis, -1.0, 1.0, -0.4, 0.4 )
	yAxis = GraphCapped( yAxis, -1.0, 1.0, 1.0, 0.75 ) //Cap it so you don't actually let the players jump forwards

	vector direction
	if ( fabs( xAxis ) < 0.2 && fabs( yAxis ) < 0.2 )
	{
	    // no significant controller deflection, just push forward by 0.75 as default
	    direction = backward * 0.75
	}
	else
	{
	    vector forwardVec = backward * yAxis
	    vector rightVec = right * xAxis
	    direction = rightVec + forwardVec
	}

	direction *= RODEO_BATTERY_RIP_PILOT_PUSHED_OFF_HORIZONTAL_SPEED
	direction.z = RODEO_BATTERY_RIP_PILOT_PUSHED_OFF_VERTICAL_HEIGHT

	// JFS: R2DLC-310 SCRIPT ERROR: PHONE_HOME: [SERVER] vecAbsVelocity isn't valid
	if ( LengthSqr( direction ) < 0.0 )
		return <0, 0, RODEO_BATTERY_RIP_PILOT_PUSHED_OFF_VERTICAL_HEIGHT>

	return direction
}

void function CancelAirControlLossAfterTouchGround( entity player )
{
	player.Signal( "CancelAirControlLoss" )
}


void function BatteryThiefHighlight( entity player )
{
	Highlight_SetEnemyHighlight( player, "battery_thief" )

	OnThreadEnd(
		function() : ( player )
		{
			if ( !IsValid( player ) )
				return

			if ( Hightlight_HasEnemyHighlight( player, "battery_thief" ) )
				Highlight_ClearEnemyHighlight( player )
		}
	)

	wait RODEO_BATTERY_THIEF_ICON_DURATION
}

void function ForceTitanRodeoToEnd( entity titan ) //TODO: Not typed since it is added via anim event
{
	entity soul = titan.GetTitanSoul()
	if ( !IsValid( soul ) )
		return

	SoulRodeoEnds( soul, null )
}


void function SoulRodeoEnds( entity soul, var damageInfo )
{
	entity titan = soul.GetTitan()

	if( !IsValid( titan ) )
		return

	entity rider = GetRodeoPilot( titan )

	if ( !IsValid( rider ) )
		return

	rider.Signal( "RodeoOver" )
	rider.ClearParent()
}


void function EnableTitanRodeo( entity titan )
{
	Assert( titan.IsTitan(), "tried calling EnableTitanRodeo on non-titan" )

	entity titanSoul = titan.GetTitanSoul()

	Assert( IsValid( titanSoul ) )

	titanSoul.SetIsValidRodeoTarget( true ) //Lets rodeo happen on them.
}


void function DisableTitanRodeo( entity titan )
{
	Assert( titan.IsTitan(), "tried calling DisableTitanRodeo( on non-titan" )

	entity titanSoul = titan.GetTitanSoul()

	Assert( IsValid( titanSoul ) )

	titanSoul.SetIsValidRodeoTarget( false ) //Stops rodeo from happening on them.
}

void function AddOnRodeoStartedCallback( void functionref(entity,entity) callbackFunc )
{
	Assert (!( file.onRodeoStartedCallbacks.contains( callbackFunc ) ))
	file.onRodeoStartedCallbacks.append( callbackFunc )
}

void function AddOnRodeoEndedCallback( void functionref(entity,entity) callbackFunc )
{
	Assert (!( file.onRodeoEndedCallbacks.contains( callbackFunc ) ))
	file.onRodeoEndedCallbacks.append( callbackFunc )
}

function PlayerBeginsTitanRodeo( entity player, RodeoPackageStruct rodeoPackage, entity rodeoTitan )
{
	entity soul = rodeoTitan.GetTitanSoul()
	Assert( IsValid( soul ) )

	bool sameTeam = player.GetTeam() == rodeoTitan.GetTeam()
	bool playerWasEjecting = player.p.pilotEjecting // have to store this off here because the "RodeoStarted" signal below ends eject, so it will be too late to check it in actual rodeo function. Used to check for eject -> rodeo

	player.p.rodeoShouldAdjustJumpOffVelocity = true

	player.Signal( "RodeoStarted" )

	bool playerHadBatteryAtStartOfRodeo = PlayerHasBattery( player )

	OnThreadEnd(
		function () : ( player, soul, sameTeam, rodeoTitan, playerHadBatteryAtStartOfRodeo )
		{
			RodeoPackageStruct rodeoPackage = player.p.rodeoPackage
			entity newRodeoTitan = rodeoTitan

			//Clear the rodeo alert and update the newRodeoTitan to be the soul's titan
			if ( IsValid( soul ) )
			{
				soul.SetLastRodeoHitTime( 0 ) //Clear rodeo warning for next time a player jumps on
				newRodeoTitan = soul.GetTitan() //rodeoTitan might have changed because a player embarked/disembarked etc

				foreach ( callbackFunc in file.onRodeoEndedCallbacks )
				{
					callbackFunc( player, newRodeoTitan )
				}

				for( int i = 0; i < soul.rodeoReservedSlots.len(); ++i )
				{
					if ( soul.rodeoReservedSlots[ i ] == player )
					{
						soul.rodeoReservedSlots[ i ] = null
						break
					}
				}

				if ( soul.soul.batteryContainerBeingUsed && playerHadBatteryAtStartOfRodeo ) //i.e. rodeo got interruped early
				{
					string titanType = GetSoulTitanSubClass( soul )
					entity batteryContainer = soul.soul.batteryContainer
					batteryContainer.Anim_Play( GetAnimFromAlias( titanType, "hatch_rodeo_up" ) )
					soul.soul.batteryContainerBeingUsed = false

				}

				// if the player is invalid, we still need to enable rodeo on the titan
				// normally this would happen in Rodeo_Detach(), but that only works if the player is valid
				if ( !IsValid( player ) )
					EnableTitanRodeo( newRodeoTitan )
			}

			if ( IsValid( player ) )
			{
				player.Signal( "RodeoOver" )
				player.SetNameVisibleToFriendly( true ) // show name of the pilot again
				player.SetNameVisibleToEnemy( true )
				ClearPlayerAnimViewEntity( player )
				player.AnimViewEntity_SetLerpOutTime( 0.4 ) // blend out the clear anim view entity
				player.ClearParent()
				player.Anim_Stop()
				player.SetOneHandedWeaponUsageOff()
				player.SetTitanSoulBeingRodeoed( null )
				player.UnforceStand()
				player.kv.PassDamageToParent = false
				player.TouchGround() // so you can double jump off
				StopSoundOnEntity( player, rodeoPackage.cockpitSound )
				StopSoundOnEntity( player, rodeoPackage.worldSound )
				if ( Rodeo_IsAttached( player ) )
					Rodeo_Detach( player )

				if ( IsAlive( player ) )
				{
					int attachIndex = newRodeoTitan.LookupAttachment( rodeoPackage.attachPoint )
					vector startPos = newRodeoTitan.GetAttachmentOrigin( attachIndex )

					if ( !PlayerCanTeleportHere( player, startPos, newRodeoTitan ) )
					{
						startPos = newRodeoTitan.GetOrigin()
						if ( !PlayerCanTeleportHere( player, startPos, newRodeoTitan ) )
							startPos = player.GetOrigin()
					}

					thread PlayerJumpsOffRodeoTarget( player, newRodeoTitan, startPos )
				}

				#if MP
				player.Signal( "RodeoNukeWindowEnded" )
				if ( player in file.playersThatWantToUseRodeoGrenade )
					delete file.playersThatWantToUseRodeoGrenade[ player ]
				#endif
			}
		}
	)


	soul.EndSignal( "OnTitanDeath" )
	soul.EndSignal( "OnDestroy" )
	player.EndSignal( "OnDeath" )
	player.EndSignal( "RodeoOver" )

	string rodeoTitanType = rodeoPackage.rodeoTargetType

	#if MP
		thread OpenRodeoNukeWindow( player, rodeoTitan )
	#endif

	thread WatchForPlayerJumpingOffRodeo( player )

	// hide name of the pilot while he is rodeoing
	player.SetNameVisibleToFriendly( false )
	player.SetNameVisibleToEnemy( false )
	player.ForceStand()
	thread ManagePlayerWeaponDeployment( player, soul ) //Spin this off in its own thread since there are multiple ways for weapon to be deployed
	player.SetOneHandedWeaponUsageOn()
	player.TouchGround() // so you can double jump off
	player.SetTitanSoulBeingRodeoed( soul )

	if ( soul.GetShieldHealth() > 0.0 )   // This was not evaluating properly with 0 being an int, so make it a float which works
		GiveFriendlyRodeoPlayerProtection( rodeoTitan )

	foreach ( callbackFunc in file.onRodeoStartedCallbacks )
		callbackFunc( player, rodeoTitan )

	if ( player.GetTeam() != rodeoTitan.GetTeam() && !PlayerHasPassive( player, ePassives.PAS_STEALTH_MOVEMENT ) )
		soul.SetLastRodeoHitTime( Time() ) // Alert Titan immediately if you don't have passive

	soul.soul.batteryMovedDown = false
	if ( ShouldThrowGrenadeInHatch( player ) ) //Either player is going to apply a battery, or it's going to throw a grenade. In either case, we want the battery to move
	{
		Rodeo_MoveBatteryDown( soul )
	}

	soul.soul.batteryContainerBeingUsed = true //All rodeo points mark batteryContainer as being true, various exit points mark it as being false when they are done cleaning it up (e.g. playing the appropriate battery going up/down anims)

	if ( !sameTeam )
	{
		#if FACTION_DIALOGUE_ENABLED
			thread PlayRodeoFactionDialogueAfterDelay( player, 0.5 )
		#endif
		TitanVO_AlertTitansTargetingThisTitanOfRodeo( player, soul )
	}

	waitthread PlayerClimbsIntoRodeoPosition( player, rodeoTitan, rodeoPackage, playerWasEjecting )

	#if MP
		player.Signal( "RodeoNukeWindowEnded" )
	#endif

	// There has been a wait, verify things are still valid.

	if ( !IsValid( soul ) )
		return

	entity rodeoTitan = soul.GetTitan()

	if ( !IsAlive( rodeoTitan ) )
		return

	TryBatteryStyleRodeo( player, rodeoTitan, soul, rodeoPackage )
}

#if FACTION_DIALOGUE_ENABLED
void function PlayRodeoFactionDialogueAfterDelay( entity player, float delay = 0.5 )
{
	player.EndSignal( "OnDeath" )
	player.EndSignal( "RodeoOver" )

	wait delay
	PlayFactionDialogueToPlayer( "kc_rodeo", player )
}
#endif

void function Rodeo_MoveBatteryDown( entity soul )
{
	if ( soul.soul.batteryMovedDown )
		return

	string titanType = GetSoulTitanSubClass( soul )
	entity batteryContainer = soul.soul.batteryContainer
	batteryContainer.Anim_Play( GetAnimFromAlias( titanType, "hatch_rodeo_down" ) )
	soul.soul.batteryMovedDown = true
}

void function ManagePlayerWeaponDeployment( entity player, entity titanSoul )
{
	HolsterAndDisableWeapons( player )

	titanSoul.EndSignal( "OnTitanDeath" )
	titanSoul.EndSignal( "OnDestroy" )
	player.EndSignal( "OnDeath" )
	player.EndSignal( "RodeoOver" )
	player.EndSignal( "FriendlyRodeoDeployWeapon" )

	OnThreadEnd(
	function() : ( player )
		{
			DeployAndEnableWeapons( player )
		}
	)

	WaitForever()
}




vector function GetAntiRodeoThrowOffDirection( entity rodeoRider, entity titan )
{
	vector backward
	vector right

	if ( titan.IsPlayer() )
	{
		backward = titan.GetViewForward() * -1.0
		right = titan.GetViewRight()
	}
	else
	{
		backward = titan.GetForwardVector() * -1.0
		right = titan.GetRightVector()
	}

	backward.z = 0
	right.z = 0

	// map the player's controls to his angles, and add that velocity
	float xAxis = rodeoRider.GetInputAxisRight()
	float yAxis = rodeoRider.GetInputAxisForward()

	xAxis = GraphCapped( xAxis, -1.0, 1.0, -0.4, 0.4 )
	yAxis = GraphCapped( yAxis, -1.0, 1.0, 1.0, 0.75 ) //Cap it so you don't actually let the players jump forwards

	vector direction
	if ( fabs( xAxis ) < 0.2 && fabs( yAxis ) < 0.2 )
	{
		// no significant controller deflection, just push forward by 0.75 as default
		direction = backward * 0.75
	}
	else
	{
		vector forwardVec = backward * yAxis
		vector rightVec = right * xAxis
		direction = rightVec + forwardVec
	}

	direction *= 600
	direction.z = 25

	return direction
}


void function RodeoPilotPullsOutWeapon( entity rodeoPilot, entity rodeoTitan, string rodeoTitanType )
{
	PlayerRodeoViewCone( rodeoPilot, rodeoTitanType )

	Rodeo_OnFinishClimbOnAnimation( rodeoPilot ) // This is to let code know the rodeoPilot has finished climbing on the rodeo and ready to fire
	rodeoPilot.Signal( "FriendlyRodeoDeployWeapon" )
}

void function TryBatteryStyleRodeo( entity rodeoPilot, entity rodeoTitan, entity titanSoul, RodeoPackageStruct rodeoPackage )
{
	titanSoul.EndSignal( "OnTitanDeath" )

	string rodeoTitanType = rodeoPackage.rodeoTargetType
	if ( rodeoPilot.GetTeam() == rodeoTitan.GetTeam() )
	{
		if ( PilotCanApplyBattery( rodeoPilot, rodeoTitan ) )
			waitthread PlayerAppliesBatteryPack( rodeoPilot, rodeoTitan, titanSoul, rodeoPackage )

		rodeoTitan = titanSoul.GetTitan()
		Assert( IsAlive( rodeoTitan ) )

		//printt( "After applying battery" )

		//This is default R1 style rodeo, with the panel ripped and ready to be shot at
		FirstPersonSequenceStruct sequence
		sequence.attachment = "hijack"
		sequence.thirdPersonAnimIdle 	= GetAnimFromAlias( rodeoTitanType, "pt_rodeo_back_right_idle" )
		sequence.firstPersonAnimIdle 		= GetAnimFromAlias( rodeoTitanType, "ptpov_rodeo_back_right_idle" )
		sequence.useAnimatedRefAttachment  = true
		thread FirstPersonSequence( sequence, rodeoPilot, rodeoTitan )

		RodeoPilotPullsOutWeapon( rodeoPilot, rodeoTitan, rodeoTitanType )
		WaitForever()

	}

	#if MP
	if ( PlayerWantsToThrowNukeGrenade( rodeoPilot ) )
	{
		waitthread PlayerAppliesBatteryPack( rodeoPilot, rodeoTitan, titanSoul, rodeoPackage )
		return
	}
	#endif

	bool classicRodeo = MP && GetCurrentPlaylistVarInt( "classic_rodeo", 0 ) == 1
	
	if ( ShouldThrowGrenadeInHatch( rodeoPilot ) )
	{
		if ( !classicRodeo )
			waitthread PlayerThrowsGrenadeInHatch( rodeoPilot, rodeoTitan, titanSoul, rodeoPackage ) //This ends rodeo at the end of the sequence
	}
	else
	{
		waitthread PlayerRemovesBatteryPack( rodeoPilot, rodeoTitan, titanSoul, rodeoPackage ) //This ends rodeo at the end of the sequence
	}
	
	#if MP
	if ( classicRodeo )
	{	
		RodeoBatteryRemoval_ShowBattery( rodeoPilot ) // hide battery, will be shown at the end of a battery removal rodeo
	
		//This is default R1 style rodeo, with the panel ripped and ready to be shot at
		FirstPersonSequenceStruct sequence
		sequence.attachment = "hijack"
		sequence.thirdPersonAnimIdle 	= GetAnimFromAlias( rodeoTitanType, "pt_rodeo_back_right_idle" )
		sequence.firstPersonAnimIdle 		= GetAnimFromAlias( rodeoTitanType, "ptpov_rodeo_back_right_idle" )
		sequence.useAnimatedRefAttachment  = true
		thread FirstPersonSequence( sequence, rodeoPilot, rodeoTitan )

		RodeoPilotPullsOutWeapon( rodeoPilot, rodeoTitan, rodeoTitanType )
		entity weakpointHitbox = CreateClassicRodeoWeakpoint( rodeoPilot, rodeoTitan )
		
		OnThreadEnd( function() : ( weakpointHitbox )
		{
			if ( IsValid( weakpointHitbox ) )
				weakpointHitbox.Destroy()
		})
		
		while ( true ) 
		{
			// the point of no return stuff breaks jumping if you pulled a battery, so do this manually, sucks but whatever
			if ( rodeoPilot.IsInputCommandHeld( IN_JUMP ) )
				ThrowRiderOff( rodeoPilot, rodeoTitan, CalculateDirectionToThrowOffBatteryThief( rodeoPilot, rodeoTitan ) ) //This signals RodeoOver
				
			WaitFrame()
		}
	}
	#endif
}

struct RodeoRiderSequenceStruct
{
	bool wasCloaked = false
	float cloakEndTime = 0.0
	string interiorSound = ""
	string exteriorSound = ""
}

void function DisableCloakBeforeRodeoSequence( entity rodeoPilot, RodeoRiderSequenceStruct dataStruct )
{
	if ( !IsCloaked( rodeoPilot ) )
		return

	dataStruct.wasCloaked = true
	dataStruct.cloakEndTime = rodeoPilot.GetCloakEndTime()
	DisableCloak( rodeoPilot, 0.0 )

}

void function RestoreCloakAfterRodeoSequence( entity rodeoPilot, RodeoRiderSequenceStruct dataStruct )
{
	if ( !IsAlive( rodeoPilot ) )
		return

	if ( !dataStruct.wasCloaked  )
		return

	Assert( dataStruct.cloakEndTime > 0.0 )

	float remainingCloakDuration = max( 0.0, dataStruct.cloakEndTime - Time() )
	if ( remainingCloakDuration > CLOAK_FADE_IN  ) //Has to be greater than 1.0 fade in duration, otherwise will cloak forever
		EnableCloak( rodeoPilot, remainingCloakDuration, CLOAK_FADE_IN )
}

void function PlayerRemovesBatteryPack( entity rodeoPilot, entity rodeoTitan, entity titanSoul, RodeoPackageStruct rodeoPackage )
{
	string titanType = GetSoulTitanSubClass( titanSoul )

	RodeoRiderSequenceStruct dataStruct
	dataStruct.interiorSound = GetAudioFromAlias( titanType, "rodeo_battery_steal_1p" )
	dataStruct.exteriorSound = GetAudioFromAlias( titanType, "rodeo_battery_steal_3p" )
	DisableCloakBeforeRodeoSequence( rodeoPilot, dataStruct )

	entity tempBattery3p
	tempBattery3p = CreatePropDynamic( RODEO_BATTERY_MODEL_FOR_RODEO_ANIMS )
	tempBattery3p.SetParent( rodeoPilot, "R_HAND", false, 0.0 )
	tempBattery3p.RemoveFromSpatialPartition()
	tempBattery3p.Hide()

	entity pilotFirstPersonProxy = rodeoPilot.GetFirstPersonProxy()
	entity tempBattery1p = CreatePropDynamic( RODEO_BATTERY_MODEL_FOR_RODEO_ANIMS )
	tempBattery1p.SetParent( pilotFirstPersonProxy, "R_HAND", false, 0.0 )
	tempBattery1p.RemoveFromSpatialPartition()
	tempBattery1p.Hide()

	rodeoPilot.p.rodeoAnimTempProps.append( tempBattery1p )
	rodeoPilot.p.rodeoAnimTempProps.append( tempBattery3p )

	AddAnimEvent( rodeoPilot, "rodeo_battery_show", RodeoBatteryRemoval_ShowBattery ) //Consider adding this in add player
	AddAnimEvent( rodeoPilot, "rodeo_battery_rip", RodeoBatteryRemoval )
	AddAnimEvent( rodeoPilot, "rodeo_battery_stealth_movement_warning", RodeoBatteryStealthMovementWarning )
	thread MonitorRodeoPastPointOfNoReturn( rodeoPilot, titanSoul )

	OnThreadEnd(
		function() : ( rodeoPilot, titanSoul, titanType, dataStruct )
		{
			if ( IsValid( titanSoul ) )
			{
				entity rodeoPanel = titanSoul.soul.batteryContainer
				if ( IsValid( rodeoPanel ) )
				{
					titanSoul.soul.batteryContainerBeingUsed = false

					if ( titanSoul.soul.batteryContainerPastPointOfNoReturn )
					{
						rodeoPanel.Anim_Play( GetAnimFromAlias( titanType, "hatch_rodeo_up" ) )

					}
					else
					{
						rodeoPanel.Anim_Play( GetAnimFromAlias( titanType, "hatch_rodeo_up_idle" ) )
						rodeoPanel.Anim_DisableSequenceTransition() //Snap into place instead of blending
					}

					titanSoul.soul.batteryContainerPastPointOfNoReturn = false
				}
			}


			if ( !IsValid( rodeoPilot ) )
				return

			if (  HasAnimEvent( rodeoPilot, "rodeo_battery_rip" )  )
				DeleteAnimEvent( rodeoPilot, "rodeo_battery_rip" )

			if (  HasAnimEvent( rodeoPilot, "rodeo_battery_show" )  )
				DeleteAnimEvent( rodeoPilot, "rodeo_battery_show" )

			if ( HasAnimEvent( rodeoPilot, "rodeo_battery_stealth_movement_warning" ) )
				DeleteAnimEvent( rodeoPilot, "rodeo_battery_stealth_movement_warning" )

			ClearRodeoAnimTempProps( rodeoPilot )

			StopSoundOnEntity( rodeoPilot, dataStruct.interiorSound )
			StopSoundOnEntity( rodeoPilot, dataStruct.exteriorSound )

			RestoreCloakAfterRodeoSequence( rodeoPilot, dataStruct )
		}
	)

	FirstPersonSequenceStruct sequence
	sequence.attachment = "hijack"
	string batteryRipAnim = GetAnimFromAlias( titanType, "pt_rodeo_back_right_hijack_battery"  ) // default, old style
	//printt( "Battery Rip Anim: " + batteryRipAnim )
	sequence.thirdPersonAnim = batteryRipAnim
	sequence.firstPersonAnim = GetAnimFromAlias( titanType, "ptpov_rodeo_back_right_hijack_battery" )

	if ( GetBugReproNum() == 112023 )
		rodeoTitan.SnapEyeAngles( < 89, 100.02, 0 > )

	EmitDifferentSoundsOnEntityForPlayerAndWorld( dataStruct.interiorSound, dataStruct.exteriorSound, rodeoPilot, rodeoTitan ) //Play sound on rodeoPilot instead of panel
	FirstPersonSequence( sequence, rodeoPilot, rodeoTitan )
}

void function MonitorRodeoPastPointOfNoReturn( entity rodeoPilot, entity titanSoul )
{
	titanSoul.Signal( "MonitorRodeoPastPointOfNoReturn" )
	titanSoul.EndSignal( "MonitorRodeoPastPointOfNoReturn" )
	rodeoPilot.EndSignal( "RodeoOver" )

	titanSoul.soul.batteryContainerPastPointOfNoReturn = false

	rodeoPilot.WaitSignal( "RodeoPointOfNoReturn" )
	titanSoul.soul.batteryContainerPastPointOfNoReturn = true
}

void function PlayerThrowsGrenadeInHatch( entity rodeoPilot, entity rodeoTitan, entity titanSoul, RodeoPackageStruct rodeoPackage )
{
	AddAnimEvent( rodeoPilot, "rodeo_battery_grenade_damage", RodeoBatteryRemoval )
	AddAnimEvent( rodeoPilot, "rodeo_battery_grenade_show", RodeoBatteryGrenadeShow )
	AddAnimEvent( rodeoPilot, "rodeo_battery_stealth_movement_warning", RodeoBatteryStealthMovementWarning )

	entity grenade3p = CreatePropDynamic( GRENADE_MODEL )
	grenade3p.SetParent( rodeoPilot, "PROPGUN", false, 0.0 )
	grenade3p.RemoveFromSpatialPartition()
	grenade3p.Hide()

	entity grenade1p = CreatePropDynamic( GRENADE_MODEL )
	grenade1p.SetParent( rodeoPilot.GetFirstPersonProxy(), "PROPGUN", false, 0.0 )
	grenade1p.RemoveFromSpatialPartition()
	grenade1p.Hide()

	rodeoPilot.p.rodeoAnimTempProps.append( grenade3p )
	rodeoPilot.p.rodeoAnimTempProps.append( grenade1p )

	string titanType = GetSoulTitanSubClass( titanSoul )
	RodeoRiderSequenceStruct dataStruct
	dataStruct.interiorSound = GetAudioFromAlias( titanType, "rodeo_grenade_1p" )
	dataStruct.exteriorSound = GetAudioFromAlias( titanType, "rodeo_grenade_3p" )
	DisableCloakBeforeRodeoSequence( rodeoPilot, dataStruct )

	OnThreadEnd(
		function() : ( rodeoPilot, titanSoul, titanType, dataStruct )
		{
			if ( IsValid( titanSoul ) )
			{
				titanSoul.soul.batteryContainerBeingUsed = false
				titanSoul.soul.batteryContainer.Anim_Play( GetAnimFromAlias( titanType, "hatch_rodeo_up" ) )
			}

			if ( !IsValid( rodeoPilot ) )
				return

			if (  HasAnimEvent( rodeoPilot, "rodeo_battery_grenade_damage" )  )
				DeleteAnimEvent( rodeoPilot, "rodeo_battery_grenade_damage" )

			if (  HasAnimEvent( rodeoPilot, "rodeo_battery_grenade_show" )  )
				DeleteAnimEvent( rodeoPilot, "rodeo_battery_grenade_show" )

			if ( HasAnimEvent( rodeoPilot, "rodeo_battery_stealth_movement_warning" ) )
				DeleteAnimEvent( rodeoPilot, "rodeo_battery_stealth_movement_warning" )

			ClearRodeoAnimTempProps( rodeoPilot )

			StopSoundOnEntity( rodeoPilot, dataStruct.interiorSound )
			StopSoundOnEntity( rodeoPilot, dataStruct.exteriorSound )

			RestoreCloakAfterRodeoSequence( rodeoPilot, dataStruct )
		}
	)

	FirstPersonSequenceStruct sequence
	sequence.attachment = "hijack"
	//string batteryRipAnim = GetAnimFromAlias( titanSubClass, "pt_rodeo_back_right_hijack_battery"  ) // Do this once the animations aren't named the same/enabled for different titans
	//printt( "Battery Rip Anim: " + batteryRipAnim )
	sequence.thirdPersonAnim = GetAnimFromAlias( titanType, "pt_rodeo_grenade" )
	sequence.firstPersonAnim = GetAnimFromAlias( titanType, "ptpov_rodeo_grenade" )

	EmitDifferentSoundsOnEntityForPlayerAndWorld( dataStruct.interiorSound, dataStruct.exteriorSound, rodeoPilot, rodeoTitan ) //Play sound on rodeoPilot instead of panel

	waitthread FirstPersonSequence( sequence, rodeoPilot, rodeoTitan )
}

void function PlayerAppliesBatteryPack_DelayedClearSyncedEntity( entity rodeoPilot, entity titanSoul )
{
	if ( !IsValid( rodeoPilot ) )
	{
		return
	}

	if ( !IsValid( titanSoul ) )
	{
		return
	}

	if ( titanSoul.soul.batteryContainerBeingUsed )
	{
		return
	}

	rodeoPilot.SetSyncedEntity( null )
}

void function PlayerAppliesBatteryPack( entity rodeoPilot, entity rodeoTitan, entity titanSoul, RodeoPackageStruct rodeoPackage )
{

	entity battery

	#if MP
	bool nukeVersion = false
	if ( PlayerWantsToThrowNukeGrenade( rodeoPilot ) )
	{
		nukeVersion = true
		// battery = CreatePropDynamic( RODEO_BATTERY_MODEL_FOR_RODEO_ANIMS )
	}
	else
	{

		battery = GetBatteryOnBack( rodeoPilot )
		battery.Hide() //Hide it because the animation has a battery model already
	}
	#else
	battery = GetBatteryOnBack( rodeoPilot )
	battery.Hide() //Hide it because the animation has a battery model already
	#endif

	entity rodeoPanel = titanSoul.soul.batteryContainer

	entity tempBattery3p
	tempBattery3p = CreatePropDynamic( RODEO_BATTERY_MODEL_FOR_RODEO_ANIMS )
	tempBattery3p.SetParent( rodeoPilot, "R_HAND", false, 0.0 )
	tempBattery3p.RemoveFromSpatialPartition()

	entity tempBattery1p
	tempBattery1p = CreatePropDynamic( RODEO_BATTERY_MODEL_FOR_RODEO_ANIMS )
	tempBattery1p.SetParent( rodeoPilot.GetFirstPersonProxy(), "R_HAND", false, 0.0 )
	tempBattery1p.RemoveFromSpatialPartition()

	#if MP
		if ( nukeVersion )
			tempBattery1p.SetSkin( 1 )
	#endif
	if ( IsAmpedBattery( battery ) )
	{
		tempBattery1p.SetSkin( 2 )
		tempBattery3p.SetSkin( 2 )
	}

	rodeoPilot.p.rodeoAnimTempProps.append( tempBattery3p )
	rodeoPilot.p.rodeoAnimTempProps.append( tempBattery1p )

	string soundAlias = "rodeo_battery_return"
	string animAlias = "rodeo_back_right_apply_battery"

	#if MP
	if ( nukeVersion )
	{
		soundAlias = "nuke_rodeo_battery_return"
		animAlias = "nuke_rodeo_back_right_apply_battery"
	}
	#endif

	string titanType = GetSoulTitanSubClass( titanSoul )
	RodeoRiderSequenceStruct dataStruct
	dataStruct.interiorSound = GetAudioFromAlias( titanType, soundAlias + "_1p" )
	dataStruct.exteriorSound = GetAudioFromAlias( titanType, soundAlias + "_3p" )
	DisableCloakBeforeRodeoSequence( rodeoPilot, dataStruct )

	OnThreadEnd(
	function() : ( battery, titanSoul, titanType, rodeoPilot, dataStruct )
		{
			if ( IsValid( battery ) )
				battery.Show()

			entity batteryContainer = titanSoul.soul.batteryContainer
			if ( IsValid( batteryContainer ) )
			{
				if ( IsValid( battery ) )
				{
					batteryContainer.Anim_Play( GetAnimFromAlias( titanType, "hatch_rodeo_up" ) )
				}
				else
				{
					batteryContainer.Anim_Play( GetAnimFromAlias( titanType, "hatch_rodeo_up_idle" ) )
					batteryContainer.Anim_DisableSequenceTransition()

				}

				if ( IsValid( rodeoPilot ) && IsValid( titanSoul ) )
				{
					delaythread( 0.1 ) PlayerAppliesBatteryPack_DelayedClearSyncedEntity( rodeoPilot, titanSoul )
				}

				titanSoul.soul.batteryContainerBeingUsed = false
			}


			if ( !IsValid( rodeoPilot ) )
				return

			ClearRodeoAnimTempProps( rodeoPilot )

			StopSoundOnEntity( rodeoPilot, dataStruct.interiorSound )
			StopSoundOnEntity( rodeoPilot, dataStruct.exteriorSound )

			RestoreCloakAfterRodeoSequence( rodeoPilot, dataStruct )
		}
	)

	FirstPersonSequenceStruct sequence
	sequence.attachment = "hijack"
	string batteryApplicationAnim = GetAnimFromAlias( titanType, "pt_" + animAlias )  // default, old style
	//printt( "Battery Application Anim: " + batteryApplicationAnim )
	sequence.thirdPersonAnim 		= batteryApplicationAnim
	sequence.firstPersonAnim 		= GetAnimFromAlias( titanType, "ptpov_" + animAlias )

	EmitDifferentSoundsOnEntityForPlayerAndWorld( dataStruct.interiorSound, dataStruct.exteriorSound, rodeoPilot, rodeoTitan ) //Play sound on rodeoPilot instead of panel

	entity batteryContainer = titanSoul.soul.batteryContainer
	if ( batteryContainer )
	{
		rodeoPilot.SetSyncedEntity( batteryContainer )
	}

	waitthread FirstPersonSequence( sequence, rodeoPilot, rodeoTitan )

	//Time passed, need to update titan reference
	rodeoTitan = titanSoul.GetTitan()
	Assert( IsAlive( rodeoTitan ) )


	#if MP
		if ( nukeVersion )
			thread RodeoForceNuke( rodeoPilot )
		else
			Rodeo_PilotAddsBatteryToFriendlyTitan( rodeoPilot, rodeoTitan )
	#else
		Rodeo_PilotAddsBatteryToFriendlyTitan( rodeoPilot, rodeoTitan )
	#endif

}

void function ClearRodeoAnimTempProps( entity player )
{
	foreach( tempProp in player.p.rodeoAnimTempProps )
	{
		if ( IsValid( tempProp ) )
			tempProp.Destroy()
		}

	player.p.rodeoAnimTempProps.clear()
}

void function RodeoBatteryPackRemovalDamage( entity attacker, entity victim, entity victimTitanSoul )
{
	victimTitanSoul.e.lastRodeoAttacker = attacker

	int damageAmount = GetSegmentHealthForTitan( victim )

	if ( PlayerHasBattery( attacker ) ) //i.e. you are throwing a grenade
		damageAmount /= 2

	SetSoulBatteryCount( victimTitanSoul, GetSoulBatteryCount( victimTitanSoul ) - 1 )

	int damageScriptType = damageTypes.rodeoBatteryRemoval

	if ( GetDoomedState( victim ) )
	{
		damageAmount = victim.GetHealth() + 1
	}
	else if ( IsHardcoreGameMode() )
	{
		damageAmount = victim.GetHealth()
	}

	table damageTable =
	{
		scriptType = damageScriptType
		forceKill = false
		damageSourceId = eDamageSourceId.rodeo_battery_removal
		origin = victim.GetOrigin()
		hitbox = 2
	}

	victim.TakeDamage( damageAmount, attacker, attacker, damageTable )
	if ( victim.IsNPC() )
		victim.SetEnemyLKP( attacker, attacker.GetOrigin() )

	entity batteryContainer = victimTitanSoul.soul.batteryContainer
	int hatchAttachmentIndex = batteryContainer.LookupAttachment( "REF" )

	TitanLoseSegementFX( victim, attacker, victim.GetAttachmentOrigin( hatchAttachmentIndex ) )

	if ( IsSingleplayer() && attacker.IsPlayer() )
	{
		UnlockAchievement( attacker, achievements.RODEO )
	}
}

void function Rodeo_DropAllBatteriesOnDeath( entity player, entity attacker, var damageInfo )
{
	Rodeo_DropAllBatteries( player )
}

void function Rodeo_ApplyAllBatteriesOnEmbark( entity player, entity titan )
{
	thread Rodeo_ApplyAllBatteriesOnEmbark_Thread( player, titan )
}

void function Rodeo_ApplyAllBatteriesOnEmbark_Thread( entity player, entity titan )
{
	player.EndSignal( "OnDeath" )

	if ( !PlayerHasBattery( player ) )
		return

	entity soul = player.GetTitanSoul()
	soul.EndSignal( "OnDestroy" )
	soul.EndSignal( "OnTitanDeath" )

	table<string,bool> e
	e[ "hadAmped" ] <- false

	while ( GetPlayerBatteryCount( player ) > 0 )
	{
		thread Rodeo_ApplyBatteryDelayed( player, e )
	}

	wait 0.4

	MessagePlayerGivingBatteryToTitan( player, player, eEventNotifications.Rodeo_YouEmbarkedWithABattery, -1, e[ "hadAmped" ] )
}

void function Rodeo_ApplyBatteryDelayed( entity player, table<string,bool> e )
{
	entity battery = Rodeo_TakeBatteryAwayFromPilot( player )
	e[ "hadAmped" ] = e[ "hadAmped" ] || IsAmpedBattery( battery )
	int skin = battery.GetSkin()
	battery.Destroy()

	entity dummyBattery = CreatePropDynamic( RODEO_BATTERY_MODEL_FOR_RODEO_ANIMS )
	dummyBattery.SetSkin( skin )
	dummyBattery.Hide()

	entity soul = player.GetTitanSoul()

	OnThreadEnd(
		function() : ( dummyBattery ) {
			if ( IsValid( dummyBattery ) )
				dummyBattery.Destroy()
		}
	)

	if ( !IsValid( soul ) )
		return

	dummyBattery.EndSignal( "OnDestroy" )
	soul.EndSignal( "OnDestroy" )
	soul.EndSignal( "OnTitanDeath" )

	wait 0.4 // delay so that it applies the battery when the player is inside the titan, so he can see the health bar change

	if ( IsValid( soul.GetTitan() ) )
		Rodeo_ApplyBatteryToTitan( dummyBattery, soul.GetTitan() )
}

void function Rodeo_GiveExecutingTitanABattery( entity attacker )
{
	Rodeo_ApplyBatteryToTitan( null, attacker )
	MessagePlayerGivingBatteryToTitan( attacker, attacker, eEventNotifications.Rodeo_TitanPickedUpBattery, -1, false )
}

void function Rodeo_GiveBatteryToPlayer( entity player )
{
	if ( PlayerHasMaxBatteryCount( player ) )
		return

	entity battery = Rodeo_CreateBatteryPack()
	Rodeo_OnTouchBatteryPack_Internal( player,  battery ) //Just setting the origin to the player's origin also works, but it will parent weirdly to a pilot's back. probably because we end up doing 2 SetOrigins in the same frame
}

void function Burnmeter_AmpedBattery( entity player )
{
	#if MP
	Burnmeter_EmergencyBattery( player )
	entity battery = GetBatteryOnBack( player )

	if ( battery == null ) // not ideal but at least the game won't crash
		return

	battery.SetSkin( 2 ) // yellow - CHANGE SKIN TO ORANGE someday
	Battery_StartFX( battery )
	#endif
}

void function Burnmeter_EmergencyBattery( entity player )
{
	entity battery = Rodeo_CreateBatteryPack()
	if ( !PlayerHasMaxBatteryCount( player ) )
	{
		Rodeo_OnTouchBatteryPack_Internal( player,  battery ) //Just setting the origin to the player's origin also works, but it will parent weirdly to a pilot's back. probably because we end up doing 2 SetOrigins in the same frame
		return
	}
	else
	{
		//Based off ThrowBattery
		vector ornull thrownSpot = CalculateSpotForThrownBattery( player, battery )

		if ( thrownSpot == null )
			thrownSpot = player.GetOrigin()

		expect vector( thrownSpot )

		vector viewVector = player.GetViewVector()

		//printt( "viewVector: " + viewVector )
		//battery.SetPhysics( MOVETYPE_FLYGRAVITY )

		battery.SetParent( player ) //HACK: Clear Ground Entity of battery. Not really sure why this is needed
		battery.ClearParent()

		battery.SetAngles( < 0, 0, 0 > )
		battery.SetOrigin( thrownSpot )

		vector playerVel = player.GetVelocity()
		vector verticalAdjustment = < 0, 0, 0 >
		if ( playerVel.z == 0 )
			verticalAdjustment = < 0, 0, 100 >

		vector batteryVel = playerVel + viewVector * 50 + verticalAdjustment
		battery.SetVelocity( batteryVel )

	}

}

entity function Rodeo_CreateBatteryPack( entity titanStolenFrom = null )
{
	entity batteryPack = CreateEntity( "item_titan_battery" )
	batteryPack.SetValueForModelKey( RODEO_BATTERY_MODEL )
	batteryPack.kv.fadedist = 10000
	DispatchSpawn( batteryPack )
	batteryPack.SetModel( RODEO_BATTERY_MODEL )
	batteryPack.s.touchEnabledTime <- 0
	batteryPack.s.batteryCarriedStatusEffect <- 0

	batteryPack.Minimap_SetAlignUpright( true )
	batteryPack.Minimap_SetZOrder( MINIMAP_Z_OBJECT )
	batteryPack.Minimap_SetClampToEdge( false )
	batteryPack.Minimap_AlwaysShow( TEAM_MILITIA, null )
	batteryPack.Minimap_AlwaysShow( TEAM_IMC, null )

	Battery_StartFX( batteryPack )

	if ( HAS_BATTERY_THIEF_ICON && titanStolenFrom != null )
	{
		Assert( titanStolenFrom.IsTitan() )
		if ( titanStolenFrom.IsPlayer() )
		{
			batteryPack.SetBossPlayer( titanStolenFrom )
		}
		else
		{
			entity titanOwner = titanStolenFrom.GetBossPlayer()
			if ( IsValid( titanOwner ) )
				batteryPack.SetBossPlayer( titanOwner )
		}

		thread ClearBatteryBossPlayerAfterDelay( batteryPack, titanStolenFrom, RODEO_BATTERY_THIEF_ICON_DURATION )
	}

	batteryPack.Highlight_SetInheritHighlight( true )

	if ( IsSingleplayer() )
	{
		thread AttachTriggerToBattery( batteryPack )
	}

	//thread MonitorBatteryVelocity( batteryPack )
	return batteryPack
}

void function Battery_StartFX( entity battery )
{
	Battery_StopFX( battery ) //Clear existing fx first. Not quite ideal but easier to do this than have bug potential for FX to stack on top of each other.
	int attachID = battery.LookupAttachment( "fx_center" )

	asset fx = BATTERY_FX_FRIENDLY
	if ( IsAmpedBattery( battery ) )
		fx = BATTERY_FX_AMPED

	battery.e.fxArray.append( StartParticleEffectOnEntity_ReturnEntity( battery, GetParticleSystemIndex( fx ), FX_PATTACH_POINT_FOLLOW, attachID ) )
}

void function Battery_StopFX( entity battery )
{
	foreach( fx in battery.e.fxArray )
	{
		EffectStop( fx )
	}

	battery.e.fxArray.clear()
}

void function Battery_StopFXAndHideIconForPlayer( entity player )
{
	if ( !PlayerHasBattery( player ) )
		return

	entity battery = GetBatteryOnBack( player )

	Battery_StopFX( battery )
	battery.ClearBossPlayer() //Boss player controls visibility of icon
}

void function AttachTriggerToBattery( entity batteryPack )
{
	entity trigger = CreateEntity( "trigger_cylinder" )
	trigger.SetRadius( 100 )
	trigger.SetAboveHeight( 100 )
	trigger.SetBelowHeight( 100 ) //i.e. make the trigger a sphere as opposed to a cylinder
	trigger.SetOrigin( batteryPack.GetOrigin() )
	trigger.SetParent( batteryPack )
	trigger.kv.triggerFilterNpc = "none" // none
	trigger.kv.triggerFilterPlayer = "titan" // titan players only
	DispatchSpawn( trigger )
	trigger.SetEnterCallback( BatteryTrigger_ApplyBattery )
}

void function BatteryTrigger_ApplyBattery( entity trigger, entity player )
{
	if ( player.IsTitan() )
	{
		entity batteryPack = trigger.GetParent()

		if ( batteryPack != null )
		{
			Rodeo_OnTouchBatteryPack( player, batteryPack )
		}
	}
}

void function Rodeo_PilotPicksUpBattery_Silent( entity pilot, entity battery )
{
	Assert( battery.GetParent() == null )

	if ( PlayerHasBattery( pilot ) )
	{
		battery.Destroy()
		battery = GetBatteryOnBack( pilot )
	}

	SetPlayerBatteryCount( pilot, GetPlayerBatteryCount( pilot ) + 1 )
	if ( GetPlayerBatteryCount( pilot ) == 1 )
	{
		battery.SetParent( pilot, "BATTERY_ATTACH" )
		battery.MarkAsNonMovingAttachment()
		battery.RemoveFromSpatialPartition()
		SetBatteryOnBack( pilot, battery )
	}

	if ( GAMETYPE == FREE_AGENCY && PlayerHasMaxBatteryCount( pilot ) && PlayerEarnMeter_GetOwnedFrac( pilot ) < 1.0 )
	{
		Rodeo_RemoveAllBatteriesOffPlayer( pilot )
		return
	}

	if ( battery.s.batteryCarriedStatusEffect == 0 )
		battery.s.batteryCarriedStatusEffect = StatusEffect_AddEndless( battery, eStatusEffect.battery_carried, 1.0 )
	battery.Minimap_Hide( TEAM_MILITIA, null )
	battery.Minimap_Hide( TEAM_IMC, null )
}

void function Rodeo_PilotPicksUpBattery( entity pilot, entity battery )
{
	Rodeo_PilotPicksUpBattery_Silent( pilot, battery )
	EmitSoundOnEntityOnlyToPlayer( pilot, pilot, PILOT_PICKS_UP_BATTERY_SOUND )
	//AddPlayerHeldButtonEventCallback( player, IN_USE, Rodeo_PilotThrowsBattery, RODEO_THROW_BATTERY_BUTTON_HOLD_TIME )
}

entity function Rodeo_TakeBatteryAwayFromPilot( entity pilot )
{
	//RemovePlayerHeldButtonEventCallback( player, IN_USE, Rodeo_PilotThrowsBattery, RODEO_THROW_BATTERY_BUTTON_HOLD_TIME )
	SetPlayerBatteryCount( pilot, GetPlayerBatteryCount( pilot ) - 1 )

	if ( GetPlayerBatteryCount( pilot ) == 0 )
	{
		entity battery = GetBatteryOnBack( pilot )
		Assert( IsValid( battery ) )
		Assert( battery.GetParent() == pilot )

		SetBatteryOnBack( pilot, null ) //Defensive fix for 209362. Set it to null before doing any other actions on it which might cause execution to jump somewhere else. I think doing PutEntityInSafeSpot() might cause this?
		battery.Minimap_AlwaysShow( TEAM_MILITIA, null )
		battery.Minimap_AlwaysShow( TEAM_IMC, null )

		battery.s.touchEnabledTime = Time() + 0.3

		Battery_StartFX( battery ) //Needed to properly restore effect when player is killed while cloaked and carrying a battery

		battery.Show()

		if ( battery.s.batteryCarriedStatusEffect > 0 )
		{
			StatusEffect_Stop( battery, battery.s.batteryCarriedStatusEffect )
			battery.s.batteryCarriedStatusEffect = 0
		}

		battery.ClearParent()
		battery.AddToSpatialPartition()
		battery.SetAngles( <0, 0, 0 > )
		battery.SetVelocity( < 0, 0, 1 > )
		PutEntityInSafeSpot( battery, pilot, null, pilot.GetOrigin(), battery.GetOrigin() ) //This might cause thread of execution to jump somewhere else, see 209362
		return battery
	}
	else
	{
		return null
	}

	unreachable
}

void function Rodeo_PilotThrowsBattery( entity pilot )
{
	if ( pilot.ContextAction_IsActive() ) //Maybe letting you throw the battery out of the dropship might be cool?
		return

	entity battery = GetBatteryOnBack( pilot )

	vector ornull thrownSpot = CalculateSpotForThrownBattery( pilot, battery )

	if ( thrownSpot == null )
	{
		EmitSoundOnEntityOnlyToPlayer( pilot, pilot, "CoOp_SentryGun_DeploymentDeniedBeep" )
		return
	}

	expect vector( thrownSpot )

	vector viewVector = pilot.GetViewVector()

	//printt( "viewVector: " + viewVector )

	entity playerBattery = Rodeo_TakeBatteryAwayFromPilot( pilot )
	Assert( playerBattery == battery )

	//battery.SetPhysics( MOVETYPE_FLYGRAVITY )

	battery.SetAngles( < 0, 0, 0 > )
	battery.SetOrigin( thrownSpot )
	vector pilotVel = pilot.GetVelocity()
	vector verticalAdjustment = < 0, 0, 0 >
	if ( pilotVel.z == 0 )
		verticalAdjustment = < 0, 0, 200 >

	vector batteryVel = pilotVel + viewVector * 300 + verticalAdjustment
	//printt( "batteryVel: " + batteryVel)
	//battery.SetVelocity( Vector( 0, 0, 0 ) )
	battery.SetVelocity( batteryVel )

	MessageToPlayer( pilot, eEventNotifications.Rodeo_YouDroppedABattery )
}

vector ornull function CalculateSpotForThrownBattery( entity pilot, entity battery )
{
	vector viewVector = pilot.GetViewVector()
	vector eyePos = pilot.EyePosition()
	vector batteryMins = battery.GetBoundingMins()
	vector batteryMaxs = battery.GetBoundingMaxs()
	vector endPos = eyePos + viewVector * 100
	TraceResults hullResult = TraceHull( eyePos, endPos, batteryMins, batteryMaxs, pilot, TRACE_MASK_SOLID | TRACE_MASK_SHOT, TRACE_COLLISION_GROUP_NONE )

	//PrintTraceResults( hullResult )

	if ( hullResult.startSolid )
		return null

	if ( hullResult.hitEnt == pilot )
		return null

	if ( hullResult.fraction == 1.0 )
		return endPos

	return hullResult.endPos
}

void function Rodeo_DropAllBatteries( entity player )
{
	if ( !PlayerHasBattery( player ) )
		return

	while ( GetPlayerBatteryCount( player ) > 1 )
	{
		entity newBattery = Rodeo_CreateBatteryPack()
		newBattery.s.touchEnabledTime = Time() + 0.3
		//look into using the players bounds for placement, instead of hardcoded numbers
		array<vector> offsets = [<0,0,0>, <30,0,0>, <0,30,0>, <0,-30,0> ]
		newBattery.SetOrigin( player.GetWorldSpaceCenter() + offsets[ GetPlayerBatteryCount( player ) ] ) //Temp fix, should change the origin
		newBattery.SetAngles( <0, 0, 0 > )
		vector baseVelocity = player.GetVelocity()
		baseVelocity.z = 0
		newBattery.SetVelocity( baseVelocity + AnglesToForward( <0, RandomInt( 360.0 ), 0 > ) * 100 + <0,0,1> )
		Rodeo_TakeBatteryAwayFromPilot( player )
	}

	entity battery = Rodeo_TakeBatteryAwayFromPilot( player )
	Assert ( IsValid( battery ) )
}

void function Rodeo_RemoveBatteryOffPlayer( entity player ) //Meant to be used in prematch etc.
{
	if ( !PlayerHasBattery( player ) )
		return

	entity battery = Rodeo_TakeBatteryAwayFromPilot( player )
	if ( IsValid( battery ) )
	{
		battery.Destroy()
	}
}

void function Rodeo_RemoveAllBatteriesOffPlayer( entity player ) //Meant to be used in prematch etc.
{
	if ( !PlayerHasBattery( player ) )
		return

	while ( GetPlayerBatteryCount( player ) > 0 )
	{
		Rodeo_RemoveBatteryOffPlayer( player )
	}
}

void function Rodeo_ApplyBatteryToTitan( entity battery, entity titan )
{
	entity soul = titan.GetTitanSoul()

	if ( !IsValid( soul ) )
		return

	int healingAmount
	if ( IsSingleplayer() )
		healingAmount = 2000
	else
		healingAmount = GetSegmentHealthForTitan( titan )

	int health = titan.GetHealth()
	int maxHealth = titan.GetMaxHealth()

	SetSoulBatteryCount( soul, GetSoulBatteryCount( soul ) + 1 )

	int healthDifference = maxHealth - health

	if ( IsSingleplayer() )
	{
		if ( soul.IsDoomed() )
			UndoomTitan( titan, 1 )
		else if ( healthDifference >= healingAmount )
			titan.SetHealth( titan.GetHealth() + healingAmount )
		else
			titan.SetHealth( titan.GetMaxHealth() )

 		if ( GetHealthFrac( titan ) >= BATTERY_PICKUP_IGNORE_FRAC )
 		{
 			titan.SetHealth( titan.GetMaxHealth() )
 		}

 		titan.GetTitanSoul().nextRegenTime = Time()
	 	if ( healthDifference < healingAmount )
		{
			titan.GetTitanSoul().SetShieldHealth( healingAmount - healthDifference + titan.GetTitanSoul().GetShieldHealth() )
		}

		if ( GetShieldHealthFrac( titan ) >= BATTERY_PICKUP_IGNORE_FRAC )
 		{
 			titan.GetTitanSoul().SetShieldHealth( titan.GetTitanSoul().GetShieldHealthMax() )
 		}

	}
	else if ( IsMultiplayer() )
	{
		if ( SoulHasPassive( soul, ePassives.PAS_VANGUARD_DOOM ) && soul.IsDoomed() )
		{
			UndoomTitan( titan, 1 )
			titan.SetHealth( 1 )
		}
		float coreFrac = GetCurrentPlaylistVarFloat( "battery_core_frac", 0.2 )
		float shieldFrac = GetCurrentPlaylistVarFloat( "battery_shield_frac", 1.0 )
		float ampedHealthSegmentFrac = GetCurrentPlaylistVarFloat( "amped_battery_health_frac", 2.0 )
		float healthSegmentFrac = GetCurrentPlaylistVarFloat( "battery_health_frac", 0.5 )

		AddCreditToTitanCoreBuilder( titan, coreFrac ) //Always give core

		int shieldHealth = soul.GetShieldHealth()
		int shieldMaxHealth = soul.GetShieldHealthMax()

		int shieldDifference = shieldMaxHealth - shieldHealth

		bool batteryIsAmped = IsAmpedBattery( battery )
		float frac = batteryIsAmped ? ampedHealthSegmentFrac : healthSegmentFrac

		int addHealth = int( healingAmount * frac )

		int totalHealth = minint( titan.GetMaxHealth(), titan.GetHealth() + addHealth )
		if ( soul.IsDoomed() && batteryIsAmped )
		{
			UndoomTitan( titan, 1 )
			soul.SetShieldHealth( soul.GetShieldHealthMax() )
		}
		else
		{
			titan.SetHealth( totalHealth )
			soul.SetShieldHealth( soul.GetShieldHealthMax() )
		}
	}

	if ( battery != null )
	{
		Assert( battery.GetParent() == null )
		battery.Destroy()
	}
}

bool function Rodeo_OnTouchBatteryPack( entity player, entity batteryPack )
{
	Rodeo_OnTouchBatteryPack_Internal( player, batteryPack )

	//Basically always return false since we don't want the battery pack to go away when being touched. ApplyBatteryToTitan() etc will deal with lifetime of battery
	return false
}

void function Rodeo_OnTouchBatteryPack_Internal( entity player, entity batteryPack )
{
	float currentTime = Time()

	if ( currentTime < batteryPack.s.touchEnabledTime )
		return

	if ( !IsAlive( player ) )
		return

	if ( player.IsPhaseShifted() )
		return

	if ( IsValid( batteryPack.GetParent() ) )
		return

	if ( PlayerHasMaxBatteryCount( player ) )
	{
		if ( IsSingleplayer() )
		{
			MessageToPlayer( player, eEventNotifications.BATT_Full, batteryPack )
		}
		return
	}

	if ( player.IsTitan() )
	{
		//Try Titans not being able to pick up battery
		if ( GetCurrentPlaylistVarInt( "rodeo_battery_disembark_to_pickup", 1 ) == 1 )
		{
			if ( currentTime - player.p.batteryLastTouchedNotificationTime > 5.0 )
			{
				MessageToPlayer( player, eEventNotifications.Rodeo_DisembarkToPickUpBattery )
				player.p.batteryLastTouchedNotificationTime  = currentTime

			}
		}
		else
		{
			if ( IsSingleplayer() )
			{
				if ( player.GetHealth() >= player.GetMaxHealth() * BATTERY_PICKUP_IGNORE_FRAC && player.GetTitanSoul().GetShieldHealth() >= player.GetTitanSoul().GetShieldHealthMax() * BATTERY_PICKUP_IGNORE_FRAC )
				{
					MessageToPlayer( player, eEventNotifications.BATT_HealthFull, batteryPack )
					return
				}
			}
			bool amped = IsAmpedBattery( batteryPack )

			Rodeo_ApplyBatteryToTitan( batteryPack, player )
			MessagePlayerGivingBatteryToTitan( player, player, eEventNotifications.Rodeo_TitanPickedUpBattery, -1, amped )
		}
		return
	}
	else
	{
		if ( IsCloaked( player ) )
			Battery_StopFX( batteryPack ) //Will be turned on again when player loses cloak

		Rodeo_PilotPicksUpBattery( player, batteryPack )
		AddPlayerScore( player, "PilotBatteryPickup" )
//		MessageToPlayer( player, eEventNotifications.Rodeo_PilotPickedUpBattery )
		return
	}
}

void function Rodeo_PilotAddsBatteryToFriendlyTitan( entity rider, entity titan )
{
	if ( !titan.IsTitan() )
		return

	if ( titan.GetTeam() != rider.GetTeam() )
		return

	if ( !PlayerHasBattery( rider ) )
		return

	entity battery = Rodeo_TakeBatteryAwayFromPilot( rider )
	bool amped = IsAmpedBattery( battery )

	if ( file.applyBatteryCallback != null )
		file.applyBatteryCallback( rider, titan, battery )

	Rodeo_ApplyBatteryToTitan( battery, titan ) //This destroys the battery

	AddPlayerScore( rider, "PilotBatteryApplied" )

	EmitSoundOnEntityOnlyToPlayer( rider, rider, PILOT_APPLIES_BATTERY_TO_TITAN_HEALTH_RESTORED_SOUND )

	if ( titan.IsPlayer() )
		MessagePlayerGivingBatteryToTitan( titan, rider, eEventNotifications.Rodeo_PilotAppliedBatteryToYou, eEventNotifications.Rodeo_YouAppliedBatteryToTitan, amped )
	else
		MessagePlayerGivingBatteryToTitan( titan, rider, eEventNotifications.Rodeo_PilotAppliedBatteryToYourPetTitan, eEventNotifications.Rodeo_YouAppliedBatteryToPetTitan, amped )
}

void function MessagePlayerGivingBatteryToTitan( entity receivingTitan, entity givingPlayer, int enumForRecevingHealth, int enumForGivingHealth, bool wasAmped )
{
	entity receivingPlayer = receivingTitan

	if ( !receivingTitan.IsPlayer() )
		receivingPlayer = receivingTitan.GetBossPlayer()

	if ( !IsValid( receivingPlayer ) )
		return

	MessageToPlayer( receivingPlayer, enumForRecevingHealth, givingPlayer, wasAmped )
	if ( givingPlayer != receivingPlayer )
		MessageToPlayer( givingPlayer, enumForGivingHealth, receivingTitan, wasAmped )
}

bool function IsTitanAtFullHealth( entity receivingTitan )
{
	if ( !receivingTitan.IsTitan() )
		return false

	return ( receivingTitan.GetHealth() == receivingTitan.GetMaxHealth() )
}

function DebugRodeoTimes()
{
	array<string> settings = [ "atlas", "ogre", "stryder" ]

	array< asset > models = [ $"models/Humans/imc_pilot/male_cq/imc_pilot_male_cq.mdl", $"models/humans/pilot/female_cq/pilot_female_cq.mdl" ]
	table times = {}

	array<string> rodeoAnims = [
			"pt_rodeo_move_back_entrance",
			"pt_rodeo_move_right_entrance",
			"pt_rodeo_move_front_entrance",
			"pt_rodeo_move_front_lower_entrance",
			"pt_rodeo_move_back_mid_entrance",
			"pt_rodeo_move_back_lower_entrance",
			"pt_rodeo_move_left_entrance"
			]

	foreach ( model in models )
	{
		times[ model ] <- []
		entity prop = CreatePropDynamic( model, Vector(0,0,0), Vector(0,0,0) )
		printt( "Human model: " + model )

		foreach ( setting in settings )
		{
			foreach ( alias in rodeoAnims )
			{
				string animation = GetAnimFromAlias( setting, alias )
		        float time = prop.GetSequenceDuration( animation )
				times[ model ].append( { time = time, animation = animation } )
		    }
		}

		prop.Kill_Deprecated_UseDestroyInstead()
	}

	printt( "Time comparison: " )
	bool wrong = false
	for ( int i = 0; i < times[ models[0] ].len(); i++ )
	{
		if ( times[models[0]][i].time == times[models[1]][i].time )
		{
			printt( "   MATCH: " + ( i + 1 ) + " times: 	" + times[models[0]][i].time + "	 	" + times[models[1]][i].time + " 	" + times[models[1]][i].animation )
		}
		else
		{
			printt( "MISMATCH: " + ( i + 1 ) + " times: 	" + times[models[0]][i].time + "		 " + times[models[1]][i].time + " 	" + times[models[1]][i].animation )
		}
		if ( ( i + 1 ) % rodeoAnims.len() == 0 )
			printt( " " )
	}
	Assert( !wrong, "Times did not match between male and female, see above" )
}

void function SetBatteryOnBack( entity player, entity battery )
{
	player.SetPlayerNetEnt( "batteryOnBack", battery )
}

bool function ClientCommand_RequestRodeoBattery( entity player, array<string> args )
{
	//PrintFunc()
	if ( !ShouldLetPlayerRequestBattery( player ) )
		return true

	player.SetPlayerNetTime( "requestRodeoBatteryLastUsedTime", Time() )

	foreach( friendlyPlayer in GetPlayerArrayOfTeam( player.GetTeam() ) )
	{
		if ( friendlyPlayer == player )
			continue

		if ( friendlyPlayer.IsTitan() )
			continue

		//Could check to see if players actually have a battery here, but that stops players from being told that they should pick up a battery for someone in need
		MessageToPlayer( friendlyPlayer, eEventNotifications.Rodeo_RequestBattery, player )
	}

	return true
}

bool function ClientCommand_OfferRodeoBattery( entity player, array<string> args )
{
	//PrintFunc()
	if ( args.len() != 1 )
		return true

	int friendlyTitanEntIndex = args[ 0 ].tointeger()

	if ( friendlyTitanEntIndex < 1 ) //Data sanitation. GetEntByIndex() will assert if passed a negative number. 0 is always world spawn, so the first valid argument is 1
		return true

	entity friendlyTitan = GetEntByIndex( friendlyTitanEntIndex )

	if ( !ShouldShowOfferRodeoBatteryHint( player, friendlyTitan ) )
		return true

	entity battery = GetBatteryOnBack( player )

	MessageToPlayer( friendlyTitan, eEventNotifications.Rodeo_FriendlyPickedUpBattery, player, battery.GetEncodedEHandle() )

	player.SetPlayerNetTime( "offerRodeoBatteryLastUsedTime", Time() )

	return true

}

void function PlayerRodeoViewCone( entity player, string rodeoTargetType )
{
	player.PlayerCone_FromAnim()
	player.GetFirstPersonProxy().HideFirstPersonProxy()
	OpenViewCone( player )
	player.PlayerCone_Disable()
	player.EnableWorldSpacePlayerEyeAngles()
}


void function OpenViewCone( entity player )
{
	player.PlayerCone_FromAnim()
	player.PlayerCone_SetMinYaw( -179 )
	player.PlayerCone_SetMaxYaw( 181 )
	player.PlayerCone_SetMinPitch( -60 )
	player.PlayerCone_SetMaxPitch( 60 )
}

bool function PilotCanApplyBattery( entity rodeoPilot, entity rodeoTitan )
{
	if ( !IsAlive( rodeoTitan ) )
		return false

	if ( rodeoTitan.GetTeam() != rodeoPilot.GetTeam() )
		return false

	if ( !PlayerHasBattery( rodeoPilot ) )
		return false

	entity titanSoul = rodeoTitan.GetTitanSoul()
	Assert( IsValid( titanSoul ) )

	string titanType = GetSoulTitanSubClass( titanSoul )

	return true
}

void function ClearBatteryBossPlayerAfterDelay( entity battery, entity titan, float delay )
{
	entity soul = titan.GetTitanSoul()

	if ( !IsValid( soul ) )
		return

	soul.EndSignal( "OnTitanDeath" ) //End signal on soul to properly handle pilot getting in/out of titan
	battery.EndSignal( "OnDestroy" )

	OnThreadEnd(
		function() : ( battery  )
		{
			if ( IsValid( battery ) )
				battery.ClearBossPlayer()
		}
	)

	wait delay
}

const float BATTERY_USES_ATTACKER_ORIGIN_THRESHOLD = 500 * 500 //500 seems like a lot, but the Titan melee execution sequences can go pretty far

void function TitanDropsBatteryOnDeath( entity titan, var damageInfo ) //Todo: Might want to do something special for titan melee execution, so the attacker automatically gets a battery
{
	if ( !titan.IsTitan() )
		return

	entity battery = Rodeo_CreateBatteryPack()
	vector titanOrigin = titan.GetOrigin()
	battery.SetOrigin( titanOrigin )
	entity attacker = DamageInfo_GetAttacker( damageInfo )
	vector safeOrigin = titanOrigin
	vector attackerOrigin
	if ( IsValid( attacker ) )
	{
		vector attackerOrigin = attacker.GetOrigin()
		float distSqr = DistanceSqr( attackerOrigin, titanOrigin )
		//printt( "Distance sqr: " + distSqr  )
		if ( distSqr <= ( BATTERY_USES_ATTACKER_ORIGIN_THRESHOLD ) ) //
		{
			//printt( "Putting attackerOrigin as safeOrigin" )

			safeOrigin = attackerOrigin
		}
	}

	bool result = PutEntityInSafeSpot( battery, null, null, safeOrigin, titanOrigin )
	if ( !result )
	{
		battery.Destroy() //Can't put the battery anywhere safe, so just destroy it.
		//printt( "Destroy battery since we can't put it in a safe spot" )
	}
}

void function ShowRequestRodeoBatteryHint_OnDamage( entity playerTitan, var damageInfo )
{
	ShowRequestRodeoBatteryHint( playerTitan )
}

void function ShowRequestRodeoBatteryHint_OnPilotBecomesTitan( entity player, entity titan )
{
	//printt( "player health: " + player.GetHealth() )
	ShowRequestRodeoBatteryHint( player )
}

void function ShowRequestRodeoBatteryHint( entity playerTitan )
{
	//PrintFunc()
	if ( !ShouldLetPlayerRequestBattery( playerTitan ) )
		return

	float currentTime = Time()

	if ( playerTitan.p.rodeoRequestBatteryHintLastShownTime > 0.0 && currentTime < playerTitan.p.rodeoRequestBatteryHintLastShownTime + REQUEST_RODEO_BATTERY_HINT_COOLDOWN ) //Use a different cooldown for the hint as opposed to the ability
	{
		//printt( "Current time: " + currentTime + ", lastShownTime: " + playerTitan.p.rodeoRequestBatteryHintLastShownTime + ", cooldown: " + REQUEST_RODEO_BATTERY_HINT_COOLDOWN )
		return
	}

	int stringID = GetStringID( "#RODEO_REQUEST_BATTERY_HINT" )
	MessageToPlayer( playerTitan, eEventNotifications.Rodeo_ShowBatteryHint, null, stringID )

	playerTitan.p.rodeoRequestBatteryHintLastShownTime = currentTime
}

void function SetSoulBatteryCount( entity soul, int count )
{
	count = maxint( 0, count )

	soul.SetTitanSoulNetInt( "rodeoBatteryCount", count )
}

void function PilotBattery_SetMaxCount( int batteryCount )
{
	file.maxPilotBatteryCount = batteryCount
}

bool function PlayerHasMaxBatteryCount( entity player )
{
	if ( !PlayerHasBattery( player ) )
	{
		Assert( GetPlayerBatteryCount( player ) == 0 )
		return false
	}

	return GetPlayerBatteryCount( player ) == file.maxPilotBatteryCount
}

void function ThrowRiderOff( entity rider, entity titan, vector direction, bool adjustAirControl = true )
{
	if ( GetBugReproNum() == 112023 ) //Track down why eye angles of rider snaps violently when titan is looking downwards
	{
		thread AnglesDebug( rider )
	}

	rider.p.rodeoShouldAdjustJumpOffVelocity = false

	rider.Signal( "RodeoOver" )
	rider.ClearParent()

	#if DEV
		if ( GetDebugRodeoPrint() )
			printt( "Throw Rider off: origin before vertical adjustment: " + rider.GetOrigin() )
	#endif

	rider.SetOrigin( rider.GetOrigin() + Vector( 0, 0, 100 ) )

	#if DEV
		if ( GetDebugRodeoPrint() )
			printt( "Throw Rider off: origin after vertical adjustment: " + rider.GetOrigin() )
	#endif

	//printt( "Rider eye angles: " + rider.EyeAngles() + ", rider Angles: " + rider.GetAngles() + " titan eye Angles:" + titan.EyeAngles() )

	// Set it higher in SP so bosses less exploitable
	#if SP
		direction += Vector( 0, 0, SP_RODEO_BOOST )
	#endif

	rider.SetVelocity( direction )
	rider.JumpedOffRodeo()

	int attachIndex = titan.LookupAttachment( "hijack" ) //TODO: Hardcoded, no way to get rodeopackage.attachpoint easily at this point anymore!
	vector startPos = titan.GetAttachmentOrigin( attachIndex )

	//printt( "startPos of attachment: " + startPos )

	if ( !PlayerCanTeleportHere( rider, startPos, titan ) )
	{
		startPos = titan.GetOrigin()
		if ( !PlayerCanTeleportHere( rider, startPos, titan ) )
			startPos = rider.GetOrigin()
	}

	PutEntityInSafeSpot( rider, titan, null, startPos, rider.GetOrigin() )

	#if DEV
		if ( GetDebugRodeoPrint() )
			printt( "Throw Rider off: origin after PutEntityInSafeSpot: " + rider.GetOrigin() )
	#endif

	if ( adjustAirControl )
		thread PostRodeoAirControl( rider )
}

void function PostRodeoAirControl( entity player )
{
	player.Signal( "PostRodeoAirControl" )
	player.EndSignal( "PostRodeoAirControl" )
	player.EndSignal( "OnDeath" )

	OnThreadEnd(
		function() : ( player )
		{
			RestorePlayerAirControl( player )
		}
	)

	const float POST_RODEO_AIR_CONTROL_DURATION = 0.75
	const float POST_RODEO_AIR_CONTROL_SCALE = 0.5
	const float POST_RODEO_AIR_CONTROL_JUMP_DELAY = 0.45

	// give the player time to be thrown in the proper direction before they get back double jump
	RemovePlayerAirControl( player )
	player.ConsumeDoubleJump()
	wait POST_RODEO_AIR_CONTROL_JUMP_DELAY
	player.TouchGround()

	float startTime = Time()
	while ( Time() - startTime < POST_RODEO_AIR_CONTROL_DURATION && !player.IsOnGround() && !player.IsWallRunning() && !player.IsWallHanging() )
	{
		float elapsedTime = Time() - startTime
		player.kv.airSpeed = player.GetPlayerSettingsField( "airSpeed" ) * POST_RODEO_AIR_CONTROL_SCALE * (1 - (elapsedTime / POST_RODEO_AIR_CONTROL_DURATION))
		player.kv.airAcceleration = GetCurrentPlaylistVarInt( "custom_air_accel_pilot", int( player.GetPlayerSettingsField( "airAcceleration" ) ) ) * POST_RODEO_AIR_CONTROL_SCALE * (1 - (elapsedTime / POST_RODEO_AIR_CONTROL_DURATION))
		//printt( "scale", POST_RODEO_AIR_CONTROL_SCALE * (1 - (elapsedTime / POST_RODEO_AIR_CONTROL_DURATION)) )

		WaitFrame()
	}
}

void function AnglesDebug( rider )
{
	printt( "Begin Angles Debug, Rider eye angles: " + rider.EyeAngles() + ", rider Angles: " + rider.GetAngles() )
	while( !rider.IsOnGround() )
	{
		printt( "Rider eye angles: " + rider.EyeAngles() + ", rider Angles: " + rider.GetAngles() )
		WaitFrame()
	}

	printt( "End Angles Debug, Rider eye angles: " + rider.EyeAngles() + ", rider Angles: " + rider.GetAngles() )
}



void function SetPlayerBatteryCount( entity player, int count )
{
	Assert( count <= file.maxPilotBatteryCount )
	Assert( count >= 0 )
	player.SetPlayerNetInt( "batteryCount", count )
}

int function GetPlayerBatteryCount( entity player )
{
	return player.GetPlayerNetInt( "batteryCount" )
}

void function DisableBTRodeo( entity soul )
{
	string settings = GetSoulPlayerSettings( soul )
	var rodeoAllow = Dev_GetPlayerSettingByKeyField_Global( settings, "rodeo_allow" )

	if ( rodeoAllow == null )
		return

	if ( rodeoAllow == 0 )
	{
		soul.SetIsValidRodeoTarget( false )
	}
}
void function RemovePlayerAirControl( entity player ) //This function should really be in a server only SP & MP utility script file. No such file exists as of right now.
{
	Assert( player.IsPlayer() )
	player.kv.airSpeed = 0
	player.kv.airAcceleration = 0
}

void function RestorePlayerAirControl( entity player ) //This function should really be in a server only SP & MP utility script file. No such file exists as of right now.
{
	Assert( player.IsPlayer() )
	player.kv.airSpeed = player.GetPlayerSettingsField( "airSpeed" )
	player.kv.airAcceleration = GetCurrentPlaylistVarInt( "custom_air_accel_pilot", int( player.GetPlayerSettingsField( "airAcceleration" ) ) )
}

bool function ShouldThrowGrenadeInHatch( entity rodeoPilot )
{
	bool batteryPullingDisabled = (GetCurrentPlaylistVarInt( "rodeo_battery_disable_pulls_from_titans", 0 ) == 1)
	if ( batteryPullingDisabled )
		return true

	#if MP
	if ( PlayerWantsToThrowNukeGrenade( rodeoPilot ) )
		return false
	#endif

	if ( PlayerHasBattery( rodeoPilot ) )
		return true

	return false
}


#if DEV
void function SetDebugRodeoPrint( bool value )
{
	file.debugRodeoPrint = value
}

bool function GetDebugRodeoPrint()
{
	return file.debugRodeoPrint
}
#endif

#if MP
void function SetApplyBatteryCallback( void functionref(entity,entity,entity) func )
{
	file.applyBatteryCallback = func
}

bool function PlayerWantsToThrowNukeGrenade( entity player )
{
	return ( player in file.playersThatWantToUseRodeoGrenade )
}

bool function HasSuperRodeoGrenade( entity player )
{
	// HACK: because we ran out of player global net ints for "numSuperRodeoGrenades" in bounty hunt
	if ( GameRules_GetGameMode() != FD )
		return false
	return player.GetPlayerNetInt( "numSuperRodeoGrenades" ) > 0
}

void function DeductSuperRodeoGrenade( entity player, int amount )
{
	int num = player.GetPlayerNetInt( "numSuperRodeoGrenades" )
	player.SetPlayerNetInt( "numSuperRodeoGrenades", num-amount )
}

void function RodeoForceNuke( entity pilot )
{
	entity titan = GetTitanBeingRodeoed( pilot )
	if ( !IsValid( titan ) )
		return

	if ( !titan.IsNPC() || titan.GetTitanSoul().IsEjecting() )
		return

	table damageTable =
	{
		scriptType = damageTypes.rodeoBatteryRemoval
		forceKill = false
		damageSourceId = eDamageSourceId.core_overload
		origin = titan.GetOrigin()
		hitbox = 2
	}
	titan.TakeDamage( 1, pilot, pilot, damageTable )

	if ( !IsAlive( titan ) || titan.GetTitanSoul().IsEjecting() )
		return

	DeductSuperRodeoGrenade( pilot, 1 )

	// THROW RODEO RIDER OFF
	entity soul = titan.GetTitanSoul()
	soul.soul.nukeAttacker = pilot
	NPC_SetNuclearPayload( titan )

	vector ejectAngles = titan.GetAngles()
	ejectAngles.x = 270
	vector riderEjectAngles = AnglesCompose( ejectAngles, < 5, 0, 0 > )

	float speed = RandomFloatRange( 1900, 2100 )
	float gravityScale = expect float ( pilot.GetPlayerSettingsField( "gravityscale" ) )
	vector riderVelocity = AnglesToForward( riderEjectAngles ) * (speed * gravityScale) * 0.95
	ThrowRiderOff( pilot, titan, riderVelocity )

	if ( titan.ContextAction_IsBusy() )
		titan.ContextAction_ClearBusy()
	thread TitanEjectPlayer( titan, true )
}

void function OpenRodeoNukeWindow( entity player, entity titan )
{
	player.EndSignal( "RodeoNukeWindowEnded" )
	player.EndSignal( "OnDeath" )
	player.EndSignal( "RodeoOver" )
	titan.EndSignal( "OnDeath" )

	if ( player in file.playersThatWantToUseRodeoGrenade )
		delete file.playersThatWantToUseRodeoGrenade[ player ]

	if ( player.GetTeam() == titan.GetTeam() )
		return

	if ( !HasSuperRodeoGrenade( player ) )
		return

	Remote_CallFunction_NonReplay( player, "ServerCallback_NukeGrenadeWindowOpen" )

	OnThreadEnd(
	function() : ( player )
		{
			if ( IsValid( player ) )
				Remote_CallFunction_NonReplay( player, "ServerCallback_NukeGrenadeWindowClosed" )
		}
	)

	player.WaitSignal( "TryNukeGrenade" )

	if ( !HasSuperRodeoGrenade( player ) )
		return

	file.playersThatWantToUseRodeoGrenade[ player ] <- true

	MessageToPlayer( player, eEventNotifications.FD_SuperRodeoUsed )
	Rodeo_MoveBatteryDown( titan.GetTitanSoul() )
}

bool function ClientCommand_TryNukeGrenade( entity player, array<string> args )
{
	if ( HasSuperRodeoGrenade( player ) )
		player.Signal( "TryNukeGrenade" )

	return true
}
#endif