aboutsummaryrefslogtreecommitdiff
path: root/Northstar.Custom/mod/scripts/vscripts/titan/sh_titan_embark.gnut
blob: 4fd4d0c672480405420a50040113e67d5639dd01 (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
untyped

global function TitanEmbark_Init

global function TitanCanStand
global function DebugEmbarkTimes
global function TitanIsCurrentlyEmbarkableForPlayer
global function PlayerCanEmbarkTitan
global function PlayerCanImmediatelyEmbarkTitan
global function FindBestEmbark
global function GenerateEmbarkActionTable
global function FindEmbarkActionForCriteria
global function GetRandomEmbarkAction
global function PlayerCanDisembarkTitan
global function IsPlayerDisembarking

#if SERVER
	global function ForceScriptedEmbark
	global function PlayerCanEmbarkIntoTitan
	global function IsPlayerEmbarking
	global function PlayerEmbarksTitan
	global function PlayerLungesToEmbark
	global function FindBestEmbarkForNpcAnim
	global function PlayerDisembarksTitan
	global function ForcedTitanDisembark
	global function ForcedTitanDisembarkCustomAnims
	global function PhaseEmbarkPhaseStart
	global function PhaseEmbarkPhaseStop
	global function OverrideCockpitLightFX
	global function StartCockpitLightThink
	global function CockpitLightStop
	global function Embark_DelayedFadeOut
	global function PlayerIsFarOffTheGround

	global function SetSmallDisembarkFailSafeTeleportVector //TODO: Re-examine this for next game, probably should have different values for SP versus MP
	global function SetLargeDisembarkFailSafeTeleportVector //TODO: Re-examine this for next game, probably should have different values for SP versus MP
#endif

#if DEV
	global function SetEmbarkDebugPrint
#endif

const FAST_EMBARK = 1
const SKIP_AHEAD_TIME = 2.0

#if MP
const EMBARK_FADE_TIME = 0.2
#else
const EMBARK_FADE_TIME = 0.3
#endif

struct
{
	asset cockpitLightFX = $"xo_cockpit_dlight"
	bool embarkDebugPrint = false
	vector smallDisembarkFailSafeTeleportVector = < 400, 400, 200 >
	vector largeDisembarkFailSafeTeleportVector = < 600, 600, 600 >
} file

function TitanEmbark_Init()
{
	if ( reloadingScripts )
		return

	level.pilotDisembarkBounds <- {}
	local end = {}
	end.up <- 50.363811
	end.forward <- 110.146927
	end.right <- 13.045869
	end.yaw <- -8.381051

	local start = {}
	start.up <- 156.750015
	start.forward <- -13.429688
	start.right <- -11.374998
	start.yaw <- 0.409042

	RefreshTitanEmbarkActions()

	level.pilotDisembarkBounds.end <- end
	level.pilotDisembarkBounds.start <- start

	RegisterSignal( "OnComplete" )
	RegisterSignal( "startembark" ) // temp

	RegisterSignal( "DisembarkingTitan" )
	RegisterSignal( "player_embarks_titan" )

	#if SERVER
		// add all the embark anims with this suffix
		AddEmbarkAnims( "titan_atlas", "atlas", true )
		AddEmbarkAnims( "titan_buddy", "buddy", true )
		AddEmbarkAnims( "titan_ogre", "ogre", true )
		AddEmbarkAnims( "titan_stryder", "stryder", true )

		// AddEmbarkAudio( "titan_atlas", "atlas" )
		// AddEmbarkAudio( "titan_buddy", "buddy" )
		// AddEmbarkAudio( "titan_ogre", "ogre" )
		// AddEmbarkAudio( "titan_stryder", "stryder" )

		RegisterSignal( "titanKneel" )
		RegisterSignal( "titanStand" )
		RegisterSignal( "titanEmbark" )
		RegisterSignal( "PhaseEmbarkPhaseStop" )

		RegisterSignal( "CockpitLightStop" )
		PrecacheParticleSystem( $"xo_cockpit_dlight" )

		AddClientCommandCallback( "TitanDisembark", ClientCommand_TitanDisembark ) //
		AddClientCommandCallback( "TitanKneel", ClientCommand_TitanKneel ) //
		//AddClientCommandCallback( "TitanStand", ClientCommand_TitanStand ) //
		AddClientCommandCallback( "TitanNextMode", ClientCommand_TitanNextMode ) //

		AddCallback_OnTitanBecomesPilot( TitanBecomesPilot_UpdateRodeoRiderHud )
		AddCallback_OnPilotBecomesTitan( PilotBecomesTitan_UpdateRodeoRiderHud )
	#endif
}

void function OverrideCockpitLightFX( asset fx )
{
	file.cockpitLightFX = fx
}

void function AddEmbarkAnims( string titan, string titanSubClass, bool thirdPersonOnly = false )
{
	// anims are string-constructed from these types:
	local Array =
	[
		"kneel_front",
		"kneel_behind",
		"kneel_right",
		"kneel_left",
		"kneel_airgrab",

		"stand_front",
		"stand_right",
		"stand_left",
		"stand_behind",
		"stand_airgrab",

		"above_right",
		"above_left",
		"kneel_above_right",
		"kneel_above_left",
	]


	// force consistency in animation names
	foreach ( item in Array )
	{
		array<string> suffixes = [ "", "_fast" ]
		foreach ( suffix in suffixes )
		{
			//printt( "Adding base " + item + " to " + titan )
			local thirdPersonAlias = "pt_mount_" + item + suffix
			local firstPersonAlias = "ptpov_mount_" + item + suffix
			local thirdPersonAnim = "pt_mount_" + titanSubClass + "_" + item + suffix
			local firstPersonAnim = "ptpov_mount_" + titanSubClass + "_" + item + suffix

			if ( thirdPersonOnly )
				firstPersonAnim = ""

			AddAnimAlias( titanSubClass, thirdPersonAlias, thirdPersonAnim )
			AddAnimAlias( titanSubClass, firstPersonAlias, firstPersonAnim )
		}
	}
}

function AddEmbarkAudio( titan, titanSubClass )
{
	// audio files are string-constructed from these types:
	local Array =
	[
		"Kneeling_Front",
		"Kneeling_Behind",
		"Kneeling_Right",
		"Kneeling_Left",
		"Kneeling_AboveRight",
		"Kneeling_AboveLeft",

		"Standing_Front",
		"Standing_Behind",
		"Standing_Airgrab",
		"Standing_AboveRight",
		"Standing_AboveLeft"
	]


	// force consistency in audio file names
	foreach ( item in Array )
	{
		//printt( "Adding base " + item + " to " + titan )
		local thirdPersonAlias = "Embark_" + item + "_3P"
		local firstPersonAlias = "Embark_" + item + "_1P"
		local thirdPersonAnim =  titanSubClass + "_Embark_" + item + "_3P"
		local firstPersonAnim =  titanSubClass + "_Embark_" + item + "_1P"

		AddAudioAlias( titanSubClass, thirdPersonAlias, thirdPersonAnim )
		AddAudioAlias( titanSubClass, firstPersonAlias, firstPersonAnim )
	}
}

function RefreshTitanEmbarkActions()
{
	if ( "titanEmbarkActions" in level )
	{
		delete level.titanEmbarkActions
		delete level.titanEmbarkFarthestDistance
	}

	local groundDist = 260

	level.titanEmbarkActions <- []
	level.titanEmbarkFarthestDistance <- 0
	local action

	action =
	{
		direction = Vector( 1, 0, 0 )
		distance = groundDist
		embark = "front"
		minDot = 0.4
		priority = 1 // tried after priority 0 actions
		titanCanStandRequired = false
		//onGround = null // either
		useAnimatedRefAttachment = true
		alignFrontEnabled = true
		canSkipAhead = true

		animSet =
		{
			firstPersonKneelingAlias = "ptpov_mount_kneel_front"
			thirdPersonKneelingAlias = "pt_mount_kneel_front"
			firstPersonStandingAlias = "ptpov_mount_stand_front"
			thirdPersonStandingAlias = "pt_mount_stand_front"
			titanKneelingAnim = "at_mount_kneel_front"
			titanStandingAnim = "at_mount_stand_front"

		}

		audioSet =
		{
			firstPersonKneelingAudioAlias = "Embark_Kneeling_Front_1P"
			thirdPersonKneelingAudioAlias = "Embark_Kneeling_Front_3P"
			firstPersonStandingAudioAlias = "Embark_Standing_Front_1P"
			thirdPersonStandingAudioAlias = "Embark_Standing_Front_3P"

		}
	}
	level.titanEmbarkActions.append( action )

	action =
	{
		direction = Vector( 1, 0, 0 )
		distance = groundDist
		embark = "front"
		minDot = -1
		priority = 2 // tried after priority 1 actions
		titanCanStandRequired = false
		//onGround = null // either
		useAnimatedRefAttachment = true
		alignFrontEnabled = true
		canSkipAhead = true

		animSet =
		{
			firstPersonKneelingAlias = "ptpov_mount_kneel_front"
			thirdPersonKneelingAlias = "pt_mount_kneel_front"
			firstPersonStandingAlias = "ptpov_mount_stand_front"
			thirdPersonStandingAlias = "pt_mount_stand_front"
			titanKneelingAnim = "at_mount_kneel_front"
			titanStandingAnim = "at_mount_stand_front"
		}

		audioSet =
		{
			firstPersonKneelingAudioAlias = "Embark_Kneeling_Front_1P"
			thirdPersonKneelingAudioAlias = "Embark_Kneeling_Front_3P"
			firstPersonStandingAudioAlias = "Embark_Standing_Front_1P"
			thirdPersonStandingAudioAlias = "Embark_Standing_Front_3P"
		}
	}
	level.titanEmbarkActions.append( action )

	action =
	{
		direction = Vector( 0, 1, 0 )
		distance = groundDist
		embark = "left"
		minDot = 0.4
		priority = 1 // tried after priority 0 actions
		titanCanStandRequired = true
		useAnimatedRefAttachment = true
		alignFrontEnabled = true
		canSkipAhead = true
		//onGround = null // either

		animSet =
		{
			firstPersonKneelingAlias = "ptpov_mount_kneel_left"
			thirdPersonKneelingAlias = "pt_mount_kneel_left"
			firstPersonStandingAlias = "ptpov_mount_stand_front"
			thirdPersonStandingAlias = "pt_mount_stand_left"
			titanKneelingAnim = "at_mount_kneel_left"
			titanStandingAnim = "at_mount_stand_left"
		}

		audioSet =
		{
			firstPersonKneelingAudioAlias = "Embark_Kneeling_Left_1P"
			thirdPersonKneelingAudioAlias = "Embark_Kneeling_Left_3P"
			firstPersonStandingAudioAlias = "Embark_Standing_Front_1P"
			thirdPersonStandingAudioAlias = "Embark_Standing_Front_3P"
		}
	}
	level.titanEmbarkActions.append( action )

	action =
	{
		direction = Vector( 0, -1, 0 )
		distance = groundDist
		embark = "right"
		minDot = 0.4
		priority = 1 // tried after priority 0 actions
		titanCanStandRequired = true
		useAnimatedRefAttachment = true
		alignFrontEnabled = true
		canSkipAhead = true
		//onGround = null // either
		animSet =
		{
			firstPersonKneelingAlias = "ptpov_mount_kneel_right"
			thirdPersonKneelingAlias = "pt_mount_kneel_right"
			firstPersonStandingAlias = "ptpov_mount_stand_front"
			thirdPersonStandingAlias = "pt_mount_stand_right"
			titanKneelingAnim = "at_mount_kneel_right"
			titanStandingAnim = "at_mount_stand_right"
		}

		audioSet =
		{
			firstPersonKneelingAudioAlias = "Embark_Kneeling_Right_1P"
			thirdPersonKneelingAudioAlias = "Embark_Kneeling_Right_3P"
			firstPersonStandingAudioAlias = "Embark_Standing_Front_1P"
			thirdPersonStandingAudioAlias = "Embark_Standing_Front_3P"
		}
	}
	level.titanEmbarkActions.append( action )


	action =
	{
		direction = Vector( -1, 0, 0 )
		distance = groundDist
		embark = "behind"
		minDot = 0.4
		priority = 1 // tried after priority 0 actions
		titanCanStandRequired = true
		useAnimatedRefAttachment = true
		canSkipAhead = false
		//onGround = null // either

		animSet =
		{
			firstPersonKneelingAlias = "ptpov_mount_kneel_behind"
			thirdPersonKneelingAlias = "pt_mount_kneel_behind"
			firstPersonStandingAlias = "ptpov_mount_stand_behind"
			thirdPersonStandingAlias = "pt_mount_stand_behind"
			titanKneelingAnim = "at_mount_kneel_behind"
			titanStandingAnim = "at_mount_stand_behind"
		}

		audioSet =
		{
			firstPersonKneelingAudioAlias = "Embark_Kneeling_Behind_1P"
			thirdPersonKneelingAudioAlias = "Embark_Kneeling_Behind_3P"
			firstPersonStandingAudioAlias = "Embark_Standing_Behind_1P"
			thirdPersonStandingAudioAlias = "Embark_Standing_Behind_3P"
		}
	}
	level.titanEmbarkActions.append( action )

	action =
	{
		direction = Vector( 0, 0, 1 ) // 0 -1 1
		distance = 350
		embark = "above_close"
		minDot = 0.88
		canSkipAhead = false
		priority = 0 // priority actions are checked first

		titanCanStandRequired = true
		useAnimatedRefAttachment = true
		//onGround = false // must be in air

		animSets =
		{
			right =
			{
		 		direction = Vector( 0, -1, 0 ) // 0 -1 1
				firstPersonKneelingAlias = "ptpov_mount_kneel_above_right"
				thirdPersonKneelingAlias = "pt_mount_kneel_above_right"
				firstPersonStandingAlias = "ptpov_mount_above_right"
				thirdPersonStandingAlias = "pt_mount_above_right"
				titanKneelingAnim = "at_mount_kneel_above"
				titanStandingAnim = "at_mount_above_right"

				audioSet =   //An annoying exception to how the audioSet is organized, better this than the alternative and having to find the "best audio set"
				{
					firstPersonKneelingAudioAlias = "Embark_Kneeling_AboveRight_1P"
					thirdPersonKneelingAudioAlias = "Embark_Kneeling_AboveRight_3P"
					firstPersonStandingAudioAlias = "Embark_Standing_AboveRight_1P"
					thirdPersonStandingAudioAlias = "Embark_Standing_AboveRight_3P"
				}
			}

			left =
			{
		 		direction = Vector( 0, 1, 0 ) // 0 -1 1
				firstPersonKneelingAlias = "ptpov_mount_kneel_above_left"
				thirdPersonKneelingAlias = "pt_mount_kneel_above_left"
				firstPersonStandingAlias = "ptpov_mount_above_left"
				thirdPersonStandingAlias = "pt_mount_above_left"
				titanKneelingAnim = "at_mount_kneel_above"
				titanStandingAnim = "at_mount_above_left"

				audioSet = //An annoying exception to how the audioSet is organized, better this than the alternative and having to find the "best audio set"
				{
					firstPersonKneelingAudioAlias = "Embark_Kneeling_AboveLeft_1P"
					thirdPersonKneelingAudioAlias = "Embark_Kneeling_AboveLeft_3P"
					firstPersonStandingAudioAlias = "Embark_Standing_AboveLeft_1P"
					thirdPersonStandingAudioAlias = "Embark_Standing_AboveLeft_3P"
				}
			}
		}
	}
	level.titanEmbarkActions.append( action )

	action =
	{
		direction = Vector( 0, 0, 1 )
		distance = 275
		embark = "above_grab"
		minDot = 0.3
		titanCanStandRequired = true
		//onGround = null // false // must be in air
		useAnimatedRefAttachment = true
		//lungeCheck = true
		canSkipAhead = true

		alignFrontEnabled = true

		priority = 0 // priority actions are checked first

		animSet =
		{
			firstPersonKneelingAlias = "ptpov_mount_kneel_airgrab"
			thirdPersonKneelingAlias = "pt_mount_kneel_airgrab"
			titanKneelingAnim = "at_mount_kneel_airgrab"

			firstPersonStandingAlias = "ptpov_mount_stand_airgrab"
			thirdPersonStandingAlias = "pt_mount_stand_airgrab"
			titanStandingAnim = "at_mount_stand_airgrab"
		}

		audioSet =
		{
			firstPersonKneelingAudioAlias = "Embark_Kneeling_Front_1P"
			thirdPersonKneelingAudioAlias = "Embark_Kneeling_Front_3P"
			firstPersonStandingAudioAlias = "Embark_Standing_Front_1P"
			thirdPersonStandingAudioAlias = "Embark_Standing_Front_3P"
		}
	}
	level.titanEmbarkActions.append( action )

	local autoParms =
	[
		"lungeCheck"
		"alignFrontEnabled"
	]

	foreach ( action in level.titanEmbarkActions )
	{
		if ( action.distance > level.titanEmbarkFarthestDistance )
		{
			level.titanEmbarkFarthestDistance = action.distance
		}
		foreach ( parm in autoParms )
		{
			if ( !( parm in action ) )
				action[ parm ] <- false
		}
	}
}

function DebugEmbarkTimes()
{
	local 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" ]
	local times = {}

	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 )
		{
			printt( "Titan: " + setting )
			foreach ( action in level.titanEmbarkActions )
			{
				printt( "Embark Direction: " + action.embark )
				if ( "animSet" in action )
				{
					local animation = GetAnimFromAlias( setting, action.animSet.thirdPersonKneelingAlias )
					local time = prop.GetSequenceDuration( animation )
					times[ model ].append( { time = time, animation = animation } )
			        printt( "Kneeling: " + time )

			        animation = GetAnimFromAlias( setting, action.animSet.thirdPersonStandingAlias )
					time = prop.GetSequenceDuration( animation )
					times[ model ].append( { time = time, animation = animation } )
			        printt( "Standing: " + time )
				}

				if ( "animSets" in action )
				{
					local animation = GetAnimFromAlias( setting, action.animSets.left.thirdPersonKneelingAlias )
					local time = prop.GetSequenceDuration( animation )
					times[ model ].append( { time = time, animation = animation } )
			        printt( "Kneeling Left: " + time )

					animation = GetAnimFromAlias( setting, action.animSets.left.thirdPersonStandingAlias )
			        time = prop.GetSequenceDuration( animation )
					times[ model ].append( { time = time, animation = animation } )
			        printt( "Standing Left: " + time )

					animation = GetAnimFromAlias( setting, action.animSets.right.thirdPersonKneelingAlias )
					time = prop.GetSequenceDuration( animation )
					times[ model ].append( { time = time, animation = animation } )
			        printt( "Kneeling Right: " + time )

					animation = GetAnimFromAlias( setting, action.animSets.right.thirdPersonStandingAlias )
			        time = prop.GetSequenceDuration( animation )
					times[ model ].append( { time = time, animation = animation } )
			        printt( "Standing Right: " + time )
				}

				printt( " " )
			}
		}

		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 )
			wrong = true
		}
	}
//	Assert( !wrong, "Times did not match between male and female, see above" )
}


#if SERVER
bool function ClientCommand_TitanKneel( entity player, array<string> args )
{
	entity titan = player.GetPetTitan()
	if ( !IsAlive( titan ) )
		return true

	titan.Signal( "titanKneel" )
	titan.s.standQueued = false
	return true
}

/*bool function ClientCommand_TitanStand( entity player, array<string> args )
{
	entity titan = player.GetPetTitan()
	if ( !IsAlive( titan ) )
		return true

	titan.Signal( "titanStand" )
	titan.s.standQueued = true
	titan.s.kneelQueued = false
	return true
}*/

bool function ClientCommand_TitanNextMode( entity player, array<string> args )
{
	if ( !IsAlive( player ) )
		return true

	entity titan = player.GetPetTitan()
	if ( IsAlive( titan ) )
		NPCTitanNextMode( titan, player )

	return true
}
#endif // SERVER


function EmbarkLine( player, titan )
{
	player.EndSignal( "startembark" )
	local ref = player.LookupAttachment( "ref" )
	local hijack = titan.LookupAttachment( "hijack" )
	local origin
	for ( ;; )
	{
		origin = titan.GetAttachmentOrigin( hijack )
		DebugDrawLine( player.GetOrigin(), origin, 255, 0, 0, true, 0.15 )

		origin = player.GetAttachmentOrigin( ref )
		DebugDrawLine( player.GetOrigin(), origin, 0, 255, 0, true, 0.15 )
		WaitFrame()
	}
}


#if SERVER
function PlayerEmbarksTitan( entity player, entity titan, table embark )
{
	//player.SetOrigin( Vector(314.971405, -1826.728638, 116.031250))
	//player.SetAngles( Vector(0.000000, 133.945892, 0.000000))
	//titan.SetOrigin( Vector(284.887970, -1622.180542, 112.093750))
	//titan.SetAngles(Vector(0.000000, 112.264252, 0))

	entity soul = titan.GetTitanSoul()
	string settings = GetSoulTitanSubClass( soul )
	printt( "TitanEmbarkDebug: Player ", player.GetOrigin(), player.GetAngles(), " Titan ", titan.GetOrigin(), titan.GetAngles(), settings, GetMapName() )


	Assert( IsAlive( titan ) )
	Assert( IsAlive( player ) )

	player.SetInvulnerable()

	player.EndSignal( "OnDeath" )
	player.EndSignal( "TitanEjectionStarted" )
	titan.EndSignal( "OnDeath" )

	titan.Signal( "player_embarks_titan" )
	player.Signal( "player_embarks_titan" )

//	Assert( !InSolid( titan ), titan + " is in solid" )

	DisableCloak( player )

	entity groundEntity = titan.GetGroundEntity()
	vector startOrigin = titan.GetGroundRelativePos()
	vector startAngles = titan.GetAngles()

	OnThreadEnd(
		function() : ( player, groundEntity, startOrigin, startAngles )
		{
			if ( IsValid( player ) )
			{
				player.SetCinematicEventFlags( player.GetCinematicEventFlags() & (~CE_FLAG_EMBARK) )
				TitanEmbark_PlayerCleanup( player )
				player.p.isEmbarking = false

				if ( IsAlive( player ) )
				{
					if ( player.IsTitan() ) //Defensive fix, sometimes in SP (when game is shutting down etc ) this can run without the player being alive
					{
						TitanEmbarkFailsafe( player, null, groundEntity, startOrigin )
						Remote_CallFunction_Replay( player, "ServerCallback_TitanEmbark" )
						LetTitanPlayerShootThroughBubbleShield( player )
					}
					else
					{
						player.Die() //Defensive fix, sometimes in SP (when game is shutting down etc ) this can run without the player being alive
					}

				}
			}
		}
	)

	// track the embarking player so we can kill him if the titan dies
	titan.s.embarkingPlayer <- player
	player.p.isEmbarking = true

	#if HAS_STATS
	UpdatePlayerStat( player, "misc_stats", "titanEmbarks", 1 )
	#endif
	#if SERVER && MP
		PIN_AddToPlayerCountStat( player, "embarks" )
		PIN_PlayerAbility( player, "", "embark", {}, 0 )
	#endif

	player.SetCinematicEventFlags( player.GetCinematicEventFlags() | CE_FLAG_EMBARK )
		
	waitthread PlayerEmbarksTitan_PlayerBecomesTitan( player, titan, embark )
}

function PlayerEmbarksTitan_PlayerBecomesTitan( entity player, entity titan, table embark )
{
	// a place to store the player finish time
	table e

	e.threads <- 0
	e.embarkAction <- embark.action
	e.animSet <- embark.animSet
	e.audioSet <- embark.audioSet

	e.canStand <- TitanCanStand( titan )

	e.shouldDoRegularEmbark <- ShouldDoRegularEmbark( titan )

	// player and titan do their anims and wait for each other to finish
	thread TitanEmbark_TitanEmbarks( player, titan, e )
	waitthread TitanEmbark_PlayerEmbarks( player, titan, e )
}

bool function ShouldDoRegularEmbark( entity titan )
{
	entity soul = titan.GetTitanSoul()

	if ( IsSingleplayer() && GetSoulPlayerSettings( soul ) == "titan_buddy" )
	{
		return titan.GetNPCState() == "combat" || titan.GetNPCState() == "alert"
	}

	return true
}

bool function TitanHasLeftAndRightEmbarkAnims( entity titan )
{
	entity soul = titan.GetTitanSoul()
	string settings = GetSoulPlayerSettings( soul )
	var hasAnims = Dev_GetPlayerSettingByKeyField_Global( settings, "hasLeftRightEmbarks" )
	if ( hasAnims != null && hasAnims == 1 )
	{
		return true
	}

	return false
}

function TitanEmbark_PlayerCleanup( player )
{
	expect entity( player )

	player.SetSyncedEntity( null )
	DeployViewModelAndEnableWeapons( player )
	player.UnforceStand()
	player.UnforceCrouch()
	//printt("Clearing invulnerable")
	player.ClearInvulnerable()
	player.ClearParent()
	//Let player jump in air after getting out if he wants to
	player.TouchGround()
	player.Anim_Stop()
}


void function ForceScriptedEmbark( entity player, entity titan )
{
	HolsterViewModelAndDisableWeapons( player )
	ClearPlayerAnimViewEntity( player )
	player.ClearParent()
	PilotBecomesTitan( player, titan )

	thread PlayAnim( player, "cqb_idle_mp" )
	player.Anim_Stop()

	player.SetOrigin( titan.GetOrigin() )
	vector angles = titan.GetAngles()
	angles.z = 0
	angles.x = 0
	player.SetAngles( angles )
	player.SnapEyeAngles( angles )

	SetStanceStand( player.GetTitanSoul() )

	TitanEmbark_PlayerCleanup( player )
	if ( player.ContextAction_IsBusy() )
		player.ContextAction_ClearBusy()
}


function TitanEmbarkFailsafe( entity player, entity titan, entity groundEnt, vector startOrigin )
{
	if ( GetCurrentPlaylistVarInt( "player_embark_in_solid_checks", 0 ) != 1 )
		return

	#if DEV
		if ( file.embarkDebugPrint )
		{
			if ( IsValid( titan ) )
				printt( "TitanEmbarkFailsafe, before PutEntityInSafeSpot: player origin: " + player.GetOrigin() + ", titan origin: " + titan.GetOrigin() + " safeStartPoint: " + startOrigin )
			else
				printt( "TitanEmbarkFailsafe, before PutEntityInSafeSpot: player origin: " + player.GetOrigin() + ", null titan, safeStartPoint: " + startOrigin )
		}
	#endif

	if ( !PutEntityInSafeSpot( player, titan, groundEnt, startOrigin, player.GetOrigin() ) )
		player.SetOrigin( startOrigin )

	#if DEV
		if ( file.embarkDebugPrint )
		{
			if ( IsValid( titan ) )
				printt( "TitanEmbarkFailsafe, after PutEntityInSafeSpot: player origin: " + player.GetOrigin() + ", titan origin: " + titan.GetOrigin() + " safeStartPoint: " + startOrigin )
			else
				printt( "TitanEmbarkFailsafe, after PutEntityInSafeSpot: player origin: " + player.GetOrigin() + ", null titan, safeStartPoint: " + startOrigin )
		}
	#endif
}

function TitanEmbark_PlayerEmbarks( entity player, entity titan, table e )
{
	player.EndSignal( "OnDeath" )
	player.EndSignal( "TitanEjectionStarted" )
	titan.EndSignal( "OnDeath" )

	e.threads++
	OnThreadEnd(
		function() : ( player, e )
		{
			if ( IsValid( player ) )
			{
				// ensure these are cleared regardless
				ClearPlayerAnimViewEntity( player )

				if ( player.ContextAction_IsBusy() )
					player.ContextAction_ClearBusy()
			}

			e.threads--
			if ( !e.threads )
			{
				Signal( e, "OnComplete" )
			}
		}
	)

    player.ContextAction_SetBusy()

	bool standing = false

	if ( e.canStand )
	{
		if ( e.shouldDoRegularEmbark )
		{
			player.ForceStand()
			switch ( titan.GetTitanSoul().GetStance() )
			{
				case STANCE_KNEELING:
				case STANCE_KNEEL:
					standing = false
					break

				default:
					standing = true
					break
			}
		}
		else
		{
			standing = false
		}
	}
	else
	{
		player.ForceCrouch()
	}

	HolsterViewModelAndDisableWeapons( player )

	FirstPersonSequenceStruct sequence
	sequence.attachment = "hijack"
	sequence.useAnimatedRefAttachment = expect bool ( e.embarkAction.useAnimatedRefAttachment )
	sequence.blendTime = 0.5

	entity soul = titan.GetTitanSoul()
	string settings = GetSoulTitanSubClass( soul )

	local hasViewCone

	// string thirdPersonAudio
	// string firstPersonAudio

	if ( standing )
	{
		sequence.firstPersonAnim = GetAnimFromAlias( settings, e.animSet.firstPersonStandingAlias )
		sequence.thirdPersonAnim = GetAnimFromAlias( settings, e.animSet.thirdPersonStandingAlias )
		hasViewCone = false
		// thirdPersonAudio = GetAudioFromAlias( settings, e.audioSet.thirdPersonStandingAudioAlias )
		// firstPersonAudio = GetAudioFromAlias( settings, e.audioSet.firstPersonStandingAudioAlias )

	}
	else
	{
		sequence.firstPersonAnim = GetAnimFromAlias( settings, e.animSet.firstPersonKneelingAlias )
		sequence.thirdPersonAnim = GetAnimFromAlias( settings, e.animSet.thirdPersonKneelingAlias )
		hasViewCone = true
		// thirdPersonAudio = GetAudioFromAlias( settings, e.audioSet.thirdPersonKneelingAudioAlias )
		// firstPersonAudio = GetAudioFromAlias( settings, e.audioSet.firstPersonKneelingAudioAlias )
	}

	sequence.thirdPersonAnimIdle = "pt_mount_idle"

	bool doFirstPersonAnim = true

	if ( sequence.firstPersonAnim == "" )
	{// if there is no first person anim, then there must be a third person camera
		sequence.thirdPersonCameraAttachments.append( "VDU" )
		sequence.thirdPersonCameraVisibilityChecks = true
		doFirstPersonAnim = false
	}

	if ( hasViewCone )
	{
		sequence.viewConeFunction = EmbarkViewCone
		thread DelayedClearViewCone( player )
	}

	//thread DelayedDisableEmbarkPlayerHud( player, sequence )

	AddAnimEvent( player, "phase_shift_start", PhaseEmbarkPhaseStart )
	AddAnimEvent( player, "phase_shift_stop", PhaseEmbarkPhaseStop )
	AddAnimEvent( titan, "cockpit_light_start", CockpitLightStart )
	AddAnimEvent( titan, "cockpit_light_stop", CockpitLightStop )

	OnThreadEnd(
	function() : ( player, titan )
		{
			if ( IsValid( player ) )
			{
				Signal( player, "PhaseEmbarkPhaseStop" )
				DeleteAnimEvent( player, "phase_shift_start" )
				DeleteAnimEvent( player, "phase_shift_stop" )
			}

			if ( IsAlive( titan ) ) //Consider clearing titan.s.embarkingPlayer here?
				titan.Die()
		}
	)
	
	#if MP
	if ( GetCurrentPlaylistVarInt( "fp_embark_enabled", 0 ) == 1 && !doFirstPersonAnim )
		FirstPersonSequenceForce1P( sequence, player, titan  )
	#endif

	thread FirstPersonSequence( sequence, player, titan )
	// EmitDifferentSoundsOnEntityForPlayerAndWorld( firstPersonAudio, thirdPersonAudio, titan, player )

	float animDuration = player.GetSequenceDuration( sequence.thirdPersonAnim )

	if ( ShouldSkipAheadIntoEmbark( standing, player, titan, e ) )
	{
		local duration = player.GetSequenceDuration( sequence.thirdPersonAnim )
		if ( duration >= SKIP_AHEAD_TIME )
		{
			player.Anim_SetInitialTime( duration - SKIP_AHEAD_TIME )
			entity viewModel = player.GetFirstPersonProxy()

			if ( IsValid( viewModel ) && EntHasModelSet( viewModel ) && doFirstPersonAnim ) //JFS: Defensive fix for player not having view models sometimes
				viewModel.Anim_SetInitialTime( duration - SKIP_AHEAD_TIME )

			animDuration = SKIP_AHEAD_TIME
		}
	}

	thread Embark_DelayedFadeOut( player, titan, animDuration )

	WaittillAnimDone( player )

	Signal( player, "PhaseEmbarkPhaseStop" )

	ClearPlayerAnimViewEntity( player )
	PilotBecomesTitan( player, titan )

	thread PlayAnim( player, "cqb_idle_mp" )
	player.Anim_Stop()
	player.SetVelocity( <0,0,0> )

	player.SetOrigin( titan.GetOrigin() )
	local angles = titan.GetAngles()
	angles.z = 0
	angles.x = 0
	player.SetAngles( angles )
	player.SnapEyeAngles( angles )

	// soul stuff should be from anim event
	Assert( IsServer() )
	SetStanceStand( player.GetTitanSoul() )
	titan.Destroy()
}

void function Embark_DelayedFadeOut( entity player, entity titan, float delay )
{
	if ( !IsAlive( player ) )
		return

	if ( !IsValid( titan ) )
		return

	player.EndSignal( "OnDeath" )
	titan.EndSignal( "OnDestroy" )
		
	wait delay - EMBARK_FADE_TIME

	if ( GetCurrentPlaylistVarInt( "fp_embark_enabled", 0 ) == 0 )
	{
		ScreenFadeToBlack( player, EMBARK_FADE_TIME, EMBARK_FADE_TIME + 0.2 ) // a little extra so we stay black
		wait EMBARK_FADE_TIME
	}
	else
	{
		wait EMBARK_FADE_TIME - 0.2
		ScreenFadeToBlack( player, 0.2, 0.4 )
		wait 0.2
	}
	
	ScreenFadeFromBlack( player, EMBARK_FADE_TIME, EMBARK_FADE_TIME )
}

void function PlayStartupSounds( entity titan )
{
	entity soul = titan.GetTitanSoul()
	if ( !IsValid( soul ) )
		return
	entity player = soul.GetBossPlayer()
	if ( !IsValid( player ) )
		return

	player.EndSignal( "OnDeath" )

	string titanSettings = GetSoulPlayerSettings( soul )
	var startupSound = Dev_GetPlayerSettingByKeyField_Global( titanSettings, "startup_sound" )

	if ( startupSound != null )
		EmitSoundOnEntityOnlyToPlayer( player, player, expect string(startupSound) )
}


void function CockpitLightStart( entity titan )
{
	thread StartCockpitLightThink( titan, 5.0 )
}

void function StartCockpitLightThink( entity titan, float timeout )
{
	titan.EndSignal( "OnDestroy" )
	titan.EndSignal( "CockpitLightStop" )

	int attachID = titan.LookupAttachment( "HIJACK" )
	int fxID = GetParticleSystemIndex( file.cockpitLightFX )
	entity fx = StartParticleEffectOnEntity_ReturnEntity( titan, fxID, FX_PATTACH_POINT_FOLLOW, attachID )

	OnThreadEnd(
	function() : ( fx )
		{
			if ( IsValid( fx ) )
				EffectStop( fx )
		}
	)

	if ( timeout < 0 )
		WaitForever()
	else
		wait timeout
}

void function CockpitLightStop( entity titan )
{
	titan.Signal( "CockpitLightStop" )
}

void function PhaseEmbarkPhaseStart( entity player )
{
	player.MakeInvisible()
	PlayPhaseShiftDisappearFX( player )
	EmitSoundOnEntity( player, "pilot_phaseembark_activate_3p" )
	
	if ( GetCurrentPlaylistVarInt( "fp_embark_enabled", 0 ) == 1 )
		player.PhaseShiftBegin( 0.0, 0.2 )
	
	thread PhaseEmbarkPhaseCleanup( player )
}

void function PhaseEmbarkPhaseCleanup( player )
{
	EndSignal( player, "OnDeath" )

	OnThreadEnd(
	function() : ( player )
		{
			if ( IsValid( player ) )
			{
				player.MakeVisible()
			}
		}
	)

	WaitSignal( player, "PhaseEmbarkPhaseStop" )
}

void function PhaseEmbarkPhaseStop( entity player )
{
	Signal( player, "PhaseEmbarkPhaseStop" )
	PlayPhaseShiftDisappearFX( player )
	EmitSoundOnEntity( player, "pilot_phaseembark_end_3p" )
	
	if ( GetCurrentPlaylistVarInt( "fp_embark_enabled", 0 ) == 1 )
		player.PhaseShiftCancel()
}

function ShouldSkipAheadIntoEmbark( standing, player, titan, e )
{
	if ( !standing )
		return false

	if ( !e.embarkAction.canSkipAhead )
		return false

	local playerEye = player.EyePosition()
	local titanOrg = titan.GetOrigin()
	local vec = playerEye - titanOrg
	vec.Norm()
	vec.z = 0
	local start = playerEye
	local end = playerEye + vec * 24

	if ( Distance( player.GetOrigin(), titan.GetOrigin() ) >= 145 )
		return false

	local mask = TRACE_MASK_PLAYERSOLID
	TraceResults result = TraceLine( start, end, [ titan, player ], mask, TRACE_COLLISION_GROUP_NONE )
	//DebugDrawLine( start, result.endPos, 0, 255, 0, true, 10.0 )
	//DebugDrawLine( result.endPos, end, 255, 0, 0, true, 10.0 )
	return result.fraction < 1.0
}
#endif // SERVER

function DelayedDisableEmbarkPlayerHud( player, sequence )
{
	player.EndSignal( "OnDeath" )

	local duration = player.GetSequenceDuration( sequence.thirdPersonAnim )
	wait duration - 1.0
	player.SetCinematicEventFlags( player.GetCinematicEventFlags() | CE_FLAG_EMBARK )
}

#if SERVER
function DelayedClearViewCone( player )
{
	player.EndSignal( "OnDeath" )
	wait 1.0
	player.PlayerCone_SetLerpTime( 0.5 )
	player.PlayerCone_FromAnim()
	player.PlayerCone_SetMinYaw( 0 )
	player.PlayerCone_SetMaxYaw( 0 )
	player.PlayerCone_SetMinPitch( 0 )
	player.PlayerCone_SetMaxPitch( 0 )
}

void function EmbarkViewCone( entity player )
{
	player.PlayerCone_FromAnim()
	player.PlayerCone_SetMinYaw( -70 )
	player.PlayerCone_SetMaxYaw( 60 )
	player.PlayerCone_SetMinPitch( -80 )
	player.PlayerCone_SetMaxPitch( 30 )
}

function TitanEmbark_TitanEmbarks( player, titan, e )
{
	expect entity( player )
	expect entity( titan )

	player.EndSignal( "OnDeath" )
	player.EndSignal( "TitanEjectionStarted" )
	titan.EndSignal( "OnDeath" )

	titan.ContextAction_SetBusy()

	AddAnimEvent( titan, "play_startup_sound", PlayStartupSounds )

	e.threads++
	OnThreadEnd(
		function() : ( e, player, titan )
		{
			e.threads--
			if ( !e.threads )
			{
				Signal( e, "OnComplete" )
			}

			if ( !IsAlive( player ) && IsAlive( titan ) )
			{
				titan.Anim_Stop()
				titan.ContextAction_ClearBusy()
				DeleteAnimEvent( titan, "play_startup_sound" )
			}
		}
	)

	local soul = titan.GetTitanSoul()

	// dont let other players get in

	local animation
//	local waittillAnimDone
	local alignFront
	bool standing = false

	if ( e.canStand )
	{
		if ( e.shouldDoRegularEmbark )
		{
			// default
			switch ( titan.GetTitanSoul().GetStance() )
			{
				case STANCE_KNEELING:
				case STANCE_KNEEL:
					animation = e.animSet.titanKneelingAnim
					alignFront = false
					break

				default:
					animation = e.animSet.titanStandingAnim
					if ( TitanHasLeftAndRightEmbarkAnims( titan ) )
						alignFront = false
					else
						alignFront = true
					standing = true
					break
			}
		}
		else
		{
			// special for BT if he is in casual mode
			animation = e.animSet.titanKneelingAnim
			alignFront = false
		}
	}
	else
	{
		animation = "at_mount_kneel_without_standing"
		alignFront = false
//		waittillAnimDone = false
	}

	//sequence.blendTime = 0.5

    printt("This is mount animation name: " + animation )
	if ( e.embarkAction.alignFrontEnabled && alignFront )
	{
		local titanOrg = titan.GetOrigin()
		local vec = player.GetOrigin() - titanOrg
		local angles = VectorToAngles( vec )
		angles.x = 0
		angles.z = 0
		thread PlayAnimGravityClientSyncing( titan, animation, titanOrg, angles )
	}
	else
	{
		thread PlayAnimGravityClientSyncing( titan, animation )
	}

	if ( ShouldSkipAheadIntoEmbark( standing, player, titan, e ) )
	{
		local duration = titan.GetSequenceDuration( animation )

		if ( duration >= SKIP_AHEAD_TIME ) // failsafe
			titan.Anim_SetInitialTime( duration - SKIP_AHEAD_TIME )
	}

	// titan will become player now
	WaitForever()
}

bool function ClientCommand_TitanDisembark( entity player, array<string> args )
{
	if ( !PlayerCanDisembarkTitan( player ) )
		return true

	ScreenFade( player, 0, 1, 0, 255, 0.2, 0.2, FFADE_IN | FFADE_PURGE )
	player.CockpitStartDisembark()
	Remote_CallFunction_Replay( player, "ServerCallback_TitanDisembark" )

	thread PlayerDisembarksTitan( player )

	return true
}

void function ForcedTitanDisembark( entity player )
{
	Assert( PlayerCanDisembarkTitan( player ) )

	player.CockpitStartDisembark()
	Remote_CallFunction_Replay( player, "ServerCallback_TitanDisembark" )

	waitthread PlayerDisembarksTitan( player )
}

function ForcedTitanDisembarkCustomAnims( entity player, FirstPersonSequenceStruct functionref( entity, entity ) playerSequenceFunc, FirstPersonSequenceStruct functionref( entity, entity ) titanSequenceFunc )
{
	Assert( PlayerCanDisembarkTitan( player ) )

	player.CockpitStartDisembark()
	Remote_CallFunction_Replay( player, "ServerCallback_TitanDisembark" )

	player.p.isCustomDisembark = true
	waitthread PlayerDisembarksTitanWithSequenceFuncs( player, playerSequenceFunc, titanSequenceFunc )
	player.p.isCustomDisembark = false
}

#endif // SERVER

function PlayerCanDisembarkTitan( entity player )
{
	if ( !player.IsTitan() )
		return false

	if ( !IsAlive( player ) )
		return false

	if ( IsValid( player.GetParent() ) )
		return false

	if ( Riff_TitanExitEnabled() == eTitanExitEnabled.Never )
		return false

	if ( !CanDisembark( player ) )
		return false

	#if SERVER
		if ( player.IsNoclipping() )
			return false
		// client doesn't know these things
		if ( IsPlayerDisembarking( player ) )
			return false
		if ( IsPlayerEmbarking( player ) )
			return false
	#endif

	if ( !HasSoul( player ) )
		return false

	local soul = player.GetTitanSoul()
	if ( soul.IsEjecting() )
		return false

	Assert( soul == player.GetTitanSoul() )

	return true
}

#if SERVER

function PlayerDisembarksTitan( player )
{
	expect entity( player )
	PlayerDisembarksTitanWithSequenceFuncs( player, GetDisembarkSequenceForPlayer, GetDisembarkSequenceForTitan )
}

void function PlayerDisembarksTitanWithSequenceFuncs( entity player, FirstPersonSequenceStruct functionref( entity, entity ) playerSequenceFunc, FirstPersonSequenceStruct functionref( entity, entity ) titanSequenceFunc )
{
	//printt( "Player disembarking with origin " + player.GetOrigin() + " and yaw " + player.GetAngles().y )

  	//player.SetOrigin( Vector(420.847626, -5214.960938, 173.789520) )
  	//player.SetAngles( Vector(0.000000, 179.572052, 0.000000 ) )

	printt( "TitanDisembarkDebug: Player ", player.GetOrigin(), player.GetAngles(), GetMapName() )

	player.EndSignal( "OnDeath" )
	player.Signal( "DisembarkingTitan" )

	//Assert( !InSolid( player ), player + " is in solid" )

	local e = {}
	e.titan <- null
	e.PilotCleanUpDone <- false

	e.startOrigin <- player.GetOrigin()
	//e.startAngles <- player.GetAngles()

	player.p.isDisembarking = true
	player.SetCinematicEventFlags( player.GetCinematicEventFlags() | CE_FLAG_DISEMBARK )

	bool wasCustomDisembark = player.p.isCustomDisembark

	player.ContextAction_SetBusy()

	OnThreadEnd(
		function() : ( player, e )
		{
			if ( IsValid( player ) )
			{
				PlayerEndsDisembark( player, e )

				local titan = e.titan
				if ( !IsValid( titan ) )
					titan = null
			}

			if ( IsAlive( expect entity( e.titan ) ) )
			{
				if ( IsAlive( player ) )
				{
					thread PlayerOwnsTitanUntilSeparation( player, e.titan, 80 )
				}

				delete e.titan.s.disembarkingPlayer
				ClearInvincible( expect entity( e.titan ) )


				//Make Titan get up immediately if he's kneeling and can stand
				//If he can't get up, well, then since the titan doesn't move when crouched he's going to be stuck...
				if ( !( "embarkingPlayer" in e.titan.s ) )
				{
					thread TitanNPC_Think( expect entity( e.titan ) ) //titan.s.disableAutoTitanConversation is deleted inside here
				}
			}
		}
	)

	bool standing = player.IsStanding()

	player.SetInvulnerable()
	player.SnapFeetToEyes()

	entity titan = CreateAutoTitanForPlayer_ForTitanBecomesPilot( player )
	DispatchSpawn( titan )
	e.titan = titan

	if ( !PlayerIsFarOffTheGround( player, [ player,titan ] ) ) //PlayerIsFarOffTheGround() necessary now for R2 because we have Titans that can jump/geo where Titans can fall down from large heights. Without check, mid-air disembarking will cause player to be teleported to the ground
	{
		vector ornull clampedPos = NavMesh_ClampPointForAIWithExtents( titan.GetOrigin(), titan, file.smallDisembarkFailSafeTeleportVector )
		if ( clampedPos == null )
			clampedPos = NavMesh_ClampPointForAIWithExtents( titan.GetOrigin(), titan, file.largeDisembarkFailSafeTeleportVector )

		if ( clampedPos != null )
		{
			expect vector( clampedPos )
			vector titanOrigin = titan.GetOrigin()

			array<entity> ignoreEnts = []
			ignoreEnts.append( titan )

			TraceResults result = TraceHull( titanOrigin, titanOrigin, titan.GetBoundingMins(), titan.GetBoundingMaxs(), ignoreEnts, TRACE_MASK_TITANSOLID, TRACE_COLLISION_GROUP_NONE )

			// expensive checks to make sure titan doesn't teleport to navmesh on other side of wall usually in invalid places
			if ( result.startSolid ||
				 TraceLineSimple( titanOrigin + Vector( 0, 0, 128 ), clampedPos + Vector( 0, 0, 0 ), titan ) == 1.0 ||
			     TraceLineSimple( titanOrigin + Vector( 0, 0, 200 ), clampedPos + Vector( 0, 0, 0 ), titan ) == 1.0 ||
			     TraceLineSimple( titanOrigin + Vector( 0, 0, 200 ), clampedPos + Vector( 0, 0, 128 ), titan ) == 1.0 )
			{
				#if DEV
					if ( file.embarkDebugPrint )
					{
						printt( "PlayerDisembarksTitanWithSequenceFuncs, player origin: " + player.GetOrigin()+ ", titan origin: " + titan.GetOrigin() + ", clampedPos: " + clampedPos )
					}
				#endif
				titan.SetOrigin( clampedPos )
				titan.ForceCheckGroundEntity()
			}
		}
	}
	else
	{
		#if DEV
			if ( file.embarkDebugPrint )
			{
				printt( "PlayerIsFarOffGround() returned true, skip doing NavMesh_ClampPointForAIWithExtents checks" )
			}
		#endif
	}

	titan.s.disembarkingPlayer <- player
	titan.EndSignal( "OnDeath" )

	player.SetSyncedEntity( titan )
	titan.s.disableAutoTitanConversation <- true

	Assert( titan.IsTitan() )
	Assert( IsAlive( player ) )
	Assert( player.IsTitan() )
	//Set player to be temporarily invulnerable. Will be removed at end of animation
	//printt("Set player invulnerable")
	HolsterViewModelAndDisableWeapons( player )  //Holstering weapon before becoming pilot so we don't play the holster animation as a pilot. Player as Titan won't play the holster animation either since it'll be interrupted by the disembark animation

	TitanBecomesPilot( player, titan )

	string titanSubClass = GetSoulTitanSubClass( titan.GetTitanSoul() )
	switch ( titanSubClass )
	{
		case "ogre":
			ShowMainTitanWeapons( titan ) //JFS: Because we hide the Titan's weapons upon kneeling for ogre
			break
	}

	titan.s.disembarkTime <- Time() // disembark debounce

	// compound strings into these animations:
	// pt_dismount_atlas_stand
	// pt_dismount_ogre_stand
	// pt_dismount_stryder_stand
	// pt_dismount_atlas_crouch
	// pt_dismount_ogre_crouch
	// pt_dismount_stryder_crouch
	// ptpov_dismount_atlas_stand
	// ptpov_dismount_ogre_stand
	// ptpov_dismount_stryder_stand
	// ptpov_dismount_atlas_crouch
	// ptpov_dismount_ogre_crouch
	// ptpov_dismount_stryder_crouch

	FirstPersonSequenceStruct playerSequence = playerSequenceFunc( player, titan )
	FirstPersonSequenceStruct titanSequence = titanSequenceFunc( player, titan )

	#if SERVER
		StatusEffect_StopAll( player, eStatusEffect.lockon_detected_titan )
	#endif

	player.ForceStand()

	thread FirstPersonSequence( titanSequence, titan )
	thread FirstPersonSequence( playerSequence, player, titan )

	if ( !wasCustomDisembark )
		thread ClearParentBeforeIntersect( player, titan, playerSequence.thirdPersonAnim, e )

	if ( !standing )
	{
		SetStanceKneel( titan.GetTitanSoul() )
	}

	//player.Anim_EnablePlanting()

	#if SERVER && MP
		PIN_AddToPlayerCountStat( player, "disembarks" )
		PIN_PlayerAbility( player, "", "disembark", {}, 0 )
	#endif

	WaittillAnimDone( player )
}

bool function PlayerIsFarOffTheGround( entity player, array<entity> ignoreEnts )
{
	vector boundingMaxs = player.GetBoundingMaxs()
	float halfHeight =  boundingMaxs.z / 2.0

	vector startpos = player.GetOrigin()
	vector endpos = startpos
	endpos.z -= halfHeight

	TraceResults result = TraceHull( startpos, endpos, player.GetBoundingMins(), player.GetBoundingMaxs(), ignoreEnts, TRACE_MASK_PLAYERSOLID, TRACE_COLLISION_GROUP_PLAYER )
	//PrintTraceResults( result )

	if ( result.startSolid )
		return false

	if ( result.allSolid )
		return false

	return ( result.fraction >= 1.0 )
}

FirstPersonSequenceStruct function GetDisembarkSequenceForPlayer( entity player, entity titan )
{
	string titanSubClass = GetSoulTitanSubClass( titan.GetTitanSoul() )

	string player3pAnim, player1pAnim
	if ( player.IsStanding() )
	{
		player3pAnim = "pt_dismount_" + titanSubClass + "_stand"
		player1pAnim = "ptpov_dismount_" + titanSubClass + "_stand"
	}
	else
	{
		player3pAnim = "pt_dismount_" + titanSubClass + "_crouch"
		player1pAnim = "ptpov_dismount_" + titanSubClass + "_crouch"
	}

	if ( player.HasPassive( ePassives.PAS_FAST_EMBARK ) )
	{
		player1pAnim += "_fast"
		player3pAnim += "_fast"
	}

	FirstPersonSequenceStruct playerSequence
	playerSequence.blendTime = 0
	playerSequence.teleport = true
	playerSequence.attachment = "hijack"
	playerSequence.thirdPersonAnim = player3pAnim
	playerSequence.firstPersonAnim = player1pAnim
	playerSequence.useAnimatedRefAttachment = true

	return playerSequence
}

FirstPersonSequenceStruct function GetDisembarkSequenceForTitan( entity player, entity titan )
{
	bool standing = player.IsStanding()

	string titanDisembarkAnim
	if ( standing )
		titanDisembarkAnim = "at_dismount_stand"
	else
		titanDisembarkAnim = "at_dismount_crouch"

	if ( player.HasPassive( ePassives.PAS_FAST_EMBARK ) )
		titanDisembarkAnim += "_fast"

	vector origin = titan.GetOrigin()
	vector angles = titan.EyeAngles()
	angles.z = 0
	angles.x = 0

	FirstPersonSequenceStruct titanSequence
	titanSequence.blendTime = 0.3
	titanSequence.thirdPersonAnim = titanDisembarkAnim
	if ( !standing )
		titanSequence.thirdPersonAnimIdle = "at_MP_embark_idle_blended"
	titanSequence.gravity = true
	titanSequence.origin = origin
	titanSequence.angles = angles

	return titanSequence
}

function DelayedSafePlayerLocationForDisembark( entity player, entity titan )
{
	float currentTime = Time()
	float allowedTime = player.p.isCustomDisembark ? 10.0 : 2.0

	player.EndSignal( "OnDestroy" )

	while( IsPlayerDisembarking( player )  )
	{
		Assert( Time() - currentTime < allowedTime ) // Failsafe of waiting 2 seconds in case SOMETHING REALLY GOES WRONG.
		if ( !IsAlive( player ) )
			return

		WaitFrame()
	}

	if ( player.ContextAction_IsActive() ) //Immediately after disembarking player might have gotten pulled into another context action e.g. embarking into evac dropship
		return

	player.ClearParent()
	player.PlayerCone_Disable()
	player.ViewOffsetEntity_Clear()
	player.GetFirstPersonProxy().HideFirstPersonProxy()

	vector safeStartPoint

	if ( IsValid( titan ) )
	{
		vector titanBoundingMaxs = titan.GetBoundingMaxs()
		float halfTitanHeight = titanBoundingMaxs.z * 0.5
		safeStartPoint = titan.GetOrigin() + < 0, 0, halfTitanHeight > //Let the start point of PutEntityInSafeSpot be closer to where the player is when disebmarking instead of the ground origin
	}
	else
	{
		titan = null
		safeStartPoint = player.GetOrigin()
	}

	#if DEV
		if ( file.embarkDebugPrint )
			printt( "DelayedSafePlayerLocationForDisembark, before PutEntityInSafeSpot: player origin: " + player.GetOrigin() + ", titan origin: " + titan.GetOrigin() + " safeStartPoint: " + safeStartPoint )
	#endif



	if ( !PutEntityInSafeSpot( player, titan, null, safeStartPoint, player.GetOrigin() ) )
		player.SetOrigin( safeStartPoint )

	#if DEV
		if ( file.embarkDebugPrint )
			printt( "DelayedSafePlayerLocationForDisembark, after PutEntityInSafeSpot: player origin: " + player.GetOrigin() + ", titan origin: " + titan.GetOrigin() + " safeStartPoint: " + safeStartPoint )
	#endif

}

function ClearParentBeforeIntersect( entity player, entity titan, anim, e )
{
	player.EndSignal( "OnDeath" )
	player.EndSignal( "OnAnimationDone" )
	player.EndSignal( "OnAnimationInterrupted" )
	//local mins = player.GetBoundingMins()
	//local maxs = player.GetBoundingMaxs()

	OnThreadEnd(
		function() : ( player, e )
		{
			if ( IsValid( player ) )
				thread DelayedSafePlayerLocationForDisembark( player, expect entity( e.titan ) )
		}
	)

	wait 0.25

	vector lastOrigin = player.GetOrigin()
	for ( ;; )
	{
		if ( EntityInSolid( player, titan, 24 ) )
			break

		lastOrigin = player.GetOrigin()
		WaitFrame()
	}

	player.SetOrigin( lastOrigin )
}

function LockedViewCone( human )
{
	human.PlayerCone_FromAnim()
	human.PlayerCone_SetMinYaw( 0 )
	human.PlayerCone_SetMaxYaw( 0 )
	human.PlayerCone_SetMinPitch( 0 )
	human.PlayerCone_SetMaxPitch( 0 )
}


function PlayerOwnsTitanUntilSeparation( player, titan, dist )
{
	titan.SetOwner( player )

	player.EndSignal( "OnDeath" )
	titan.EndSignal( "OnDeath" )

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

			titan.SetOwner( null )
		}
	)

	// wait until player moves away
	local distSqr = dist * dist
	for ( ;; )
	{
		if ( DistanceSqr( titan.GetOrigin(), player.GetOrigin() ) > distSqr )
			break

		wait 0.5
	}
}

function PlayerEndsDisembark( player, e )
{
	thread PlayerEndsDisembarkThread( player, e )
}

function PlayerEndsDisembarkThread( player, e )
{
	expect entity( player )
	player.EndSignal( "OnDestroy" )

	if ( e.PilotCleanUpDone )
		return

	e.PilotCleanUpDone = true
	bool wasCustomDisembark = player.p.isCustomDisembark

	wait 0.1

	ClearPlayerAnimViewEntity( player )
	if ( player.ContextAction_IsBusy() )
		player.ContextAction_ClearBusy()

	player.SetCinematicEventFlags( player.GetCinematicEventFlags() & (~CE_FLAG_DISEMBARK) )

	player.Show()
	TitanEmbark_PlayerCleanup( player )
	player.p.isDisembarking = false

	//// give a player a boost out the door
    //
    //
	if ( IsAlive( player ) && !wasCustomDisembark )
	{
		local angles = player.EyeAngles()
		if ( IsValid( e.titan ) )
			angles = e.titan.GetAngles()

		angles.x = 0
		angles.z = 0
		local forward = AnglesToForward( angles )
		local up = AnglesToUp( angles )
		local vel = forward * 250 + up * 200
		player.SetVelocity( vel )
		//DebugDrawLine( player.GetOrigin(), player.GetOrigin() + forward * 500, 255, 0, 0, true, 5.0 )
	}
}

function IsPlayerEmbarking( player )
{
	expect entity ( player )
	return player.p.isEmbarking
}
#endif // SERVER

function IsPlayerDisembarking( player )
{
	expect entity ( player )
	return player.p.isDisembarking
}

function PlayerCanEmbarkIntoTitan( entity player, entity titan ) //TODO: Collapse PlayerCanEmbarkTitan(), PlayerCanEmbarkIntoTitan(), PlayerCanImmediatelyEmbarkTitan() and TitanIsCurrentlyEmbarkableForPlayer() into one function
{
	if ( player.IsNoclipping() )
		return false

	if ( !TitanIsCurrentlyEmbarkableForPlayer( player, titan ) )
		return false

	return FindBestEmbark( player, titan ) != null
}

bool function TitanIsCurrentlyEmbarkableForPlayer( entity player, entity titan ) //TODO: Collapse PlayerCanEmbarkTitan(), PlayerCanEmbarkIntoTitan(), PlayerCanImmediatelyEmbarkTitan() and TitanIsCurrentlyEmbarkableForPlayer() into one function
{
	if ( !CanEmbark( player ) )
		return false

	if ( player.Anim_IsActive() )
		return false

	if ( !player.IsHuman() )
		return false

	if ( player.ContextAction_IsActive() )
		return false

	if ( !titan.IsEntAlive() )
		return false

	if ( titan.ContextAction_IsActive() )
		return false

	if ( !titan.IsInterruptable() )
		return false

	if ( IsValid( titan.GetParent() ) )
		return false

	if ( !HasSoul( titan ) )
		return false

	local soul = titan.GetTitanSoul()

	if ( GetDoomedState( titan ) && !PROTO_AlternateDoomedState() )
		return false

	if ( soul.IsEjecting() )
		return false

	#if SERVER
		// client doesn't know these things
		if ( IsPlayerEmbarking( player ) )
			return false

		if ( IsPlayerDisembarking( player ) )
			return false
	#endif

	if ( "disembarkTime" in titan.s )
	{
		if ( Time() - titan.s.disembarkTime < 1.65 )
			return false
	}

	return true
}

function FindEmbarkActionForCriteria( criteria )
{
	local embarkAction
	foreach ( option in level.titanEmbarkActions )
	{
		bool failed = false
		foreach ( key, value in criteria )
		{
			if ( value != option[key] )
			{
				failed = true
				break
			}
		}

		if ( !failed )
		{
			embarkAction = option
			break
		}
	}

	return embarkAction

}

function GetRandomEmbarkAction()
{
	return level.titanEmbarkActions[ RandomInt( level.titanEmbarkActions.len() ) ]
}

function FindBestEmbark( entity player, entity titan, bool doDistCheck = true )
{
//	if ( IsServer() )
//		printt( "finding best embark for " + player + " to " + titan )
	vector playerPos = player.GetOrigin()
	vector titanPos = titan.GetOrigin()

	vector relTitanToPlayerDir = CalculateTitanToPlayerDir( titan, player )

	local bestAction = null
	float bestDot = -2
	float dist = 0

	if ( doDistCheck )
	{
		dist = Distance( playerPos, titanPos )
		if ( dist > level.titanEmbarkFarthestDistance )
			return null
	}
	//if ( IsServer() )
	//	printt( "dist: " + dist )

	for ( int i = 0; i < 3; i++ )
	{
		bestAction = GetBestEmbarkAction( i, player, titan, dist, relTitanToPlayerDir )
		if ( bestAction != null )
			break
	}

	if ( bestAction == null )
		return null

	return GenerateEmbarkActionTable( player, titan, bestAction, relTitanToPlayerDir )
}

vector function CalculateTitanToPlayerDir( entity titan, entity player )
{
	vector playerPos = player.GetOrigin()
	vector titanPos = titan.GetOrigin()

	vector absTitanToPlayerDir
	if ( playerPos == titanPos )
	{
		absTitanToPlayerDir = Vector( 1, 0, 0 )
	}
	else
	{
		vector angles = player.EyeAngles()
		vector forward = AnglesToForward( angles )

		absTitanToPlayerDir = ( playerPos - titanPos )


		absTitanToPlayerDir.Norm()

//		not needed cause we can't get in without a legal use
//		// is the target in my fov?
//		if ( forward.Dot( absTitanToPlayerDir * -1 ) < 0.77 )
//			return null
	}

	vector titanAngles = titan.GetAngles()
	titanAngles.x = 0
	if ( titan.GetTitanSoul().GetStance() >= STANCE_STANDING )
		titanAngles = AnglesCompose( titanAngles, Vector( 0, -30, 0 ) )

	vector relTitanToPlayerDir = CalcRelativeVector( titanAngles, absTitanToPlayerDir )
	return relTitanToPlayerDir
}

function GenerateEmbarkActionTable( entity player, entity titan, bestAction, var relTitanToPlayerDir = null )
{
	bool useFastAnims = player.IsPlayer() && player.HasPassive( ePassives.PAS_FAST_EMBARK )

	if ( relTitanToPlayerDir == null )
	{
 		relTitanToPlayerDir = CalculateTitanToPlayerDir( titan, player )
 		expect vector( relTitanToPlayerDir )
	}
	else
	{
		expect vector( relTitanToPlayerDir )
	}

	local Table = {}
	Table.action <- bestAction

	if ( "animSet" in bestAction )
	{
		Table.animSet <- bestAction.animSet
		Table.audioSet <- bestAction.audioSet
	}
	else
	{
		local bestAnimSet
		local bestAudioSet
		local bestDot = -2
		Assert( "animSets" in bestAction, "Table has no animSet and no animSets!" )
		foreach ( animSet in bestAction.animSets )
		{
			local dot = relTitanToPlayerDir.Dot( animSet.direction )

			if ( dot > bestDot )
			{
				bestAnimSet = animSet
				bestAudioSet = animSet.audioSet
				bestDot = dot
			}
		}

		Table.animSet <- bestAnimSet
		Table.audioSet <- bestAudioSet
	}

	if ( useFastAnims )
	{
		Table.animSet = clone Table.animSet

		foreach ( string idx, item in Table.animSet )
		{
			if ( IsString( item ) )
				Table.animSet[ idx ] = item + "_fast"
		}
	}

	return Table
}

function GetBestEmbarkAction( int priority, entity player, entity titan, float dist, vector relTitanToPlayerDir )
{
	local bestAction = null
	local bestDot = -2

	foreach ( action in level.titanEmbarkActions )
	{
		if ( action.priority != priority )
			continue

		if ( dist > action.distance )
		{
			//if ( IsServer() )
				//printt( "Failed: Action " + action.embark + " had dist " + action.distance + " vs actual dist " + dist )
			continue
		}

		if ( action.lungeCheck )
		{
			if ( player.IsNPC() )
				continue

			if ( player.Lunge_IsActive() != action.lungeCheck )
				continue
		}

		local dot = relTitanToPlayerDir.Dot( action.direction )

		if ( dot < action.minDot )
		{
			//if ( IsServer() )
				//printt( "Failed: Action " + action.embark + " had dot " + dot )
			continue
		}

		if ( expect bool( action.titanCanStandRequired ) && !TitanCanStand( titan ) )
		{
			//if ( IsServer() )
				//printt( "Failed: Action " + action.embark + " cant stand" )
			continue
		}

		if ( dot > bestDot )
		{
			//if ( IsServer() )
				//printt( "Action " + action.embark + " had dot " + dot )
			bestAction = action
			bestDot = dot
		}
	}

	return bestAction
}

function FindBestEmbarkForNpcAnim( entity npc, entity titan )
{
	bool doDistCheck = false
	return FindBestEmbark( npc, titan, doDistCheck )
}




bool function TitanCanStand( entity titan )
{
	#if SERVER
		vector maxs = titan.GetBoundingMaxs()
		vector mins = titan.GetBoundingMins()

		vector start = titan.GetOrigin()
		vector end = titan.GetOrigin()
		entity soul = titan.GetTitanSoul()
		entity ignoreEnt = null

		if ( IsValid( soul.soul.bubbleShield ) )
			ignoreEnt = soul.soul.bubbleShield
		int mask = titan.GetPhysicsSolidMask()
		//printt( "mask has " + MaskTester( mask ) )
		TraceResults result = TraceHull( start, end, mins, maxs, ignoreEnt, mask, TRACE_COLLISION_GROUP_NONE )
		//printt( "start " + start + " end " + end )

		//DebugDrawLine( start, result.endPos, 0, 255, 0, true, 5.0 )
		//DebugDrawLine( result.endPos, end, 255, 0, 0, true, 5.0 )

		bool canStand = result.fraction >= 1.0
		titan.SetCanStand( canStand )
		return canStand
	#else
		return titan.GetCanStand() != 0
	#endif
}

bool function PlayerCanEmbarkTitan( entity player, entity titan ) //TODO: Collapse PlayerCanEmbarkTitan(), PlayerCanEmbarkIntoTitan(), PlayerCanImmediatelyEmbarkTitan() and TitanIsCurrentlyEmbarkableForPlayer() into one function
{
	PerfStart( PerfIndexClient.PlayerCanEmbarkTitan1 )
	if ( !TitanIsCurrentlyEmbarkableForPlayer( player, titan ) )
	{
		PerfEnd( PerfIndexClient.PlayerCanEmbarkTitan1 )
		return false
	}
	PerfEnd( PerfIndexClient.PlayerCanEmbarkTitan1 )

	PerfStart( PerfIndexClient.FindBestEmbark )
	bool res = FindBestEmbark( player, titan ) != null
	PerfEnd( PerfIndexClient.FindBestEmbark )

	return res
}

bool function PlayerCanImmediatelyEmbarkTitan( entity player, entity titan ) //TODO: Collapse PlayerCanEmbarkTitan(), PlayerCanEmbarkIntoTitan(), PlayerCanImmediatelyEmbarkTitan() and TitanIsCurrentlyEmbarkableForPlayer() into one function
{
	if ( "embarkingPlayer" in titan.s )
		return false

	if ( player.IsNoclipping() )
		return false

	if ( !IsAlive( player ) || !IsAlive( titan ) )
		return false

	return FindBestEmbark( player, titan ) != null
}

#if SERVER
function PlayerLungesToEmbark( entity player, entity ent )
{
	Assert( TitanIsCurrentlyEmbarkableForPlayer( player, ent ) )

	if ( PlayerCanImmediatelyEmbarkTitan( player, ent ) )
	{
		table embarkDirection = expect table( FindBestEmbark( player, ent ) )
		thread PlayerEmbarksTitan( player, ent, embarkDirection )
		return
	}

	if ( player.IsNoclipping() )
		return

	// already lunging
	if ( player.Lunge_IsActive() )
		return

	if ( ShouldStopLunging( player, ent ) )
		return

	player.Lunge_SetTargetEntity( ent, false )
	player.Lunge_SetSmoothTime( 3.0 )
}

void function TitanBecomesPilot_UpdateRodeoRiderHud( entity playerTitan, entity npc_titan )
{
	entity rodeoPilot = GetRodeoPilot( npc_titan )
	if ( !IsValid( rodeoPilot ) )
		return

	Remote_CallFunction_Replay( rodeoPilot, "ServerCallback_UpdateRodeoRiderHud" )
}

void function PilotBecomesTitan_UpdateRodeoRiderHud( entity playerTitan, entity npc_titan )
{
	entity rodeoPilot = GetRodeoPilot( playerTitan )
	if ( !IsValid( rodeoPilot ) )
		return

	Remote_CallFunction_Replay( rodeoPilot, "ServerCallback_UpdateRodeoRiderHud" )

}

void function SetSmallDisembarkFailSafeTeleportVector( vector value ) //TODO: Re-examine this for next game, probably should have different values for SP versus MP
{
	file.smallDisembarkFailSafeTeleportVector = value
}

void function SetLargeDisembarkFailSafeTeleportVector( vector value ) //TODO: Re-examine this for next game, probably should have different values for SP versus MP
{
	file.largeDisembarkFailSafeTeleportVector = value
}

#endif // SERVER

#if DEV
void function SetEmbarkDebugPrint( bool value )
{
	file.embarkDebugPrint = value
}
#endif