aboutsummaryrefslogtreecommitdiff
path: root/Northstar.Custom/mod/scripts/vscripts/melee/sh_melee.gnut
blob: 89ea38f03e3d00e7194dba328ddde4dfa7ff2323 (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
untyped

global function MeleeShared_Init

global function CodeCallback_OnMeleePressed
//global function CodeCallback_OnMeleeHeld
//global function CodeCallback_OnMeleeReleased
global function CodeCallback_IsValidMeleeExecutionTarget
global function CodeCallback_IsValidMeleeAttackTarget
global function CodeCallback_OnMeleeAttackAnimEvent
global function AddSyncedMeleeServerCallback
global function AddSyncedMeleeServerThink

global function GetSyncedMeleeChooser
global function CreateSyncedMeleeChooser
global function PlayerTriesSyncedMelee
global function FindBestSyncedMelee
global function GetSyncedMeleeChooserForPlayerVsTarget
global function AddSyncedMelee
global function GetEyeOrigin
global function SetObjectCanBeMeleed
global function ObjectCanBeMeleed
global function ShouldClampTargetVelocity
global function ClampVerticalVelocity
global function IsInExecutionMeleeState

global function GetLungeTargetForPlayer
global function Melee_IsAllowed
global function IsAttackerRef
global function AddCallback_IsValidMeleeExecutionTarget

#if SERVER
	global function Melee_Enable
	global function Melee_Disable
	global function SyncedMelee_Enable
	global function SyncedMelee_Disable
	global function InitMeleeAnimEventCallbacks
	global function GetRefAnglesBetweenEnts
	global function CreateMeleeScriptMoverBetweenEnts
	global function ShouldHolsterWeaponForMelee
	global function ShouldHolsterWeaponForSyncedMelee
	global function NPCTriesSyncedMeleeVsPlayer
#endif

const SMOOTH_TIME = 0.2
const INSTA_KILL_TIME_THRESHOLD = 0.35
const BUG_REPRO_MOVEMELEE = 19114

global struct SyncedMelee
{
	string ref
	bool enabled = true
	vector direction = < 1, 0, 0 >
	float distance
	float distanceSqr
	string attackerAnimation1p
	string attackerAnimation3p
//	void function AddAnimEvent( entity ent, string eventName, void functionref( entity ent ) func, var optionalVar = null )
	array<AnimEventData> attacker3pAnimEvents
	array<AnimEventData> target3pAnimEvents
	string targetAnimation1p
	string targetAnimation3p
	string thirdPersonCameraAttachment
	asset attachModel1p
	string attachTag1p
	float minDot = -1.0 // always happens
	string animRefPos = "target"
	bool canTargetNPCs = true
	float percentDamageDealtPerHit = 1.0
	bool usableByPlayers = true

	float targetMinHealthRatio = 0.0 // target health ratio must be at least this high
	float targetMaxHealthRatio = 1.0 // target health ratio must be at or below this
	bool onlyIfLethal // only if the strike would be lethal
	bool isAttackerRef = true

}

global struct SyncedMeleeChooser
{
	vector functionref( entity ) attackerOriginFunc
	vector functionref( entity ) targetOriginFunc
	array<SyncedMelee> syncedMelees
	bool displayMeleePrompt = true
}

struct
{
	table<string, table<string,SyncedMeleeChooser> > syncedMeleeChoosers
	table<SyncedMeleeChooser, array<void functionref( SyncedMeleeChooser actions, SyncedMelee action, entity player, entity target )> > syncedMeleeServerCallbacks
	table<SyncedMeleeChooser, bool functionref( SyncedMelee action, entity player, entity target ) > syncedMeleeServerThink
	array<bool functionref(entity attacker, entity target)> isValidMeleeExecutionTargetCallBacks
	string lastExecutionUsed = ""
} file

function MeleeShared_Init()
{
	FlagInit( "ForceSyncedMelee" )

	level.HUMAN_VS_TITAN_MELEE <- 1
	level.titan_attack_anim_event_count <- 0
	level.titan_attack_push_button_count <- 0

	MeleeHumanShared_Init()
	MeleeTitanShared_Init()
	MeleeSyncedHumanShared_Init()
	MeleeSyncedTitanShared_Init()

	#if SERVER
		VerifySyncedMelee()
		MeleeSyncedServer_Init()
	#endif

	RegisterSignal( "SyncedMeleeComplete" )
	RegisterSignal( "OnSyncedMelee" )
	RegisterSignal( "OnSyncedMeleeVictim" )
	RegisterSignal( "OnSyncedMeleeAttacker" )
}

int function GetPlayerMeleeDamage( entity player )
{
	Assert( player.IsPlayer() )
	foreach ( weapon in player.GetMainWeapons() )
	{
		switch ( weapon.GetWeaponInfoFileKeyField( "fire_mode" ) )
		{
			case "offhand_melee":
				return expect int( weapon.GetWeaponInfoFileKeyField( "melee_damage" ) )
		}
	}

	return 0
}

void function AddSyncedMeleeServerCallback( SyncedMeleeChooser chooser, void functionref( SyncedMeleeChooser actions, SyncedMelee action, entity player, entity target ) func )
{
	if ( !( chooser in file.syncedMeleeServerCallbacks ) )
		file.syncedMeleeServerCallbacks[ chooser ] <- []

	file.syncedMeleeServerCallbacks[ chooser ].append( func )
}

void function AddSyncedMeleeServerThink( SyncedMeleeChooser chooser, bool functionref( SyncedMelee action, entity player, entity target ) func )
{
	file.syncedMeleeServerThink[ chooser ] <- func
}


function VerifySyncedMelee()
{
	foreach ( attackerChoosers in file.syncedMeleeChoosers )
	{
		foreach ( chooser in attackerChoosers )
		{
			//Assert( chooser in file.syncedMeleeServerCallbacks, "Need to add synced server melee callback for synced melee chooser" )
			//Assert( file.syncedMeleeServerCallbacks[ chooser ].len() > 0, "Need to create a callback for chooser" )
			Assert( chooser in file.syncedMeleeServerThink, "Need to add synced server melee callback for synced melee chooser" )
		}
	}
}

SyncedMeleeChooser function GetSyncedMeleeChooser( string attackerType, string victimType )
{
	return file.syncedMeleeChoosers[ attackerType ][ victimType ]
}

SyncedMeleeChooser function CreateSyncedMeleeChooser( string attackerType, string victimType )
{
	SyncedMeleeChooser chooser

	chooser.attackerOriginFunc = GetEyeOrigin
	chooser.targetOriginFunc = GetEyeOrigin

	if ( !( attackerType in file.syncedMeleeChoosers ) )
		file.syncedMeleeChoosers[ attackerType ] <- {}

	Assert( !( victimType in file.syncedMeleeChoosers[ attackerType ] ), "Already has " + victimType )
	file.syncedMeleeChoosers[ attackerType ][ victimType ] <- chooser
	return chooser
}

vector function GetEyeOrigin( entity ent )
{
	return ent.EyePosition()
}

void function AddCallback_IsValidMeleeExecutionTarget( bool functionref( entity attacker, entity target ) callbackFunc )
{
	file.isValidMeleeExecutionTargetCallBacks.append( callbackFunc )
}

//Called after pressing the melee button to recheck for targets
bool function CodeCallback_IsValidMeleeExecutionTarget( entity attacker, entity target )
{
	if ( attacker == target )
		return false

	if ( !ShouldPlayerExecuteTarget( attacker, target ) )
		return false

	if ( !attacker.IsOnGround() && attacker.IsHuman() )
		return false

	if ( !IsAlive( target ) )
		return false

	if ( target.IsInvulnerable() )
		return false

	if ( !CanBeMeleed( target ) )
		return false

	if ( target.IsNPC() && !target.CanBeMeleeExecuted() )
		return false

	// Disallow executing someone that is already in execution. That road leads to script errors and asserts.
	if ( target.ContextAction_IsMeleeExecution() )
		return false

	if ( attacker.IsTitan() && target.IsTitan() )
	{
		// no melee execute for berserker
		if ( PlayerHasPassive( attacker, ePassives.PAS_BERSERKER ) )
			return false

		if ( PlayerHasPassive( attacker, ePassives.PAS_SHIFT_CORE ) )
			return false

		if ( HasSoul( target ) && target.GetTitanSoul().IsEjecting() )
			return false

		if ( attacker.ContextAction_IsActive() )
			return false

		if ( target.ContextAction_IsActive() )
			return false

		if ( GetCurrentPlaylistVarInt( "vortex_blocks_melee", 0 ) == 1 )
		{
			vector traceStartPos = attacker.EyePosition()
			vector traceEndPos = target.EyePosition()
			VortexBulletHit ornull vortexHit = VortexBulletHitCheck( attacker, traceStartPos, traceEndPos )
			if ( vortexHit != null )
			{
				return false
			}
		}
	}

	if ( !CheckVerticallyCloseEnough( attacker, target ) )
		return false

	//No necksnaps while wall running or mantling
	if ( attacker.IsWallRunning() )
		return false

	if ( attacker.IsTraversing() )
		return false

	if ( target.IsPlayer() ) //Disallow execution on a bunch of player-only actions
	{

		if ( target.IsHuman() )
		{
			if ( target.IsWallRunning() )
				return false

			if ( target.IsTraversing() )
				return false

			if ( !target.IsOnGround() ) //disallow mid-air necksnaps. Can't really do that for Titan executions since dash puts them in mid air... will have visual glitches unfortunately.
				return false

			if ( target.IsCrouched() )
				return false

			if ( Rodeo_IsAttached( target ) )
				return false
		}
	}

	if ( target.IsPhaseShifted() )
		return false

	//Disallow executions on contextActions marked Busy. Note that this allows
	//execution on melee and leeching context actions!
	if ( target.ContextAction_IsBusy() )
		return false

	if ( target.IsNPC() ) //NPC only checks
	{
		if ( target.ContextAction_IsActive() )
			return false

		if ( !target.IsInterruptable() )
			return false
	}

	if ( attacker.GetTeam() == target.GetTeam() )
		return false

#if SERVER
	if ( "syncedMeleeAttacker" in target.s ) //Don't allow necksnap on a guy who'se already getting necksnapped
		return false
#endif // #if SERVER

	SyncedMeleeChooser ornull actions = GetSyncedMeleeChooserForPlayerVsTarget( attacker, target )
	if ( actions == null )
		return false
	expect SyncedMeleeChooser( actions )

	SyncedMelee ornull action = FindBestSyncedMelee( attacker, target, actions )
	if ( action == null )
		return false

	if ( !PlayerMelee_IsExecutionReachable( attacker, target, 0.3 ) )
		return false

	foreach ( callbackFunc in file.isValidMeleeExecutionTargetCallBacks )
	{
		if ( !callbackFunc( attacker, target ) )
		{
			return false
		}
	}

	return true
}

bool function CodeCallback_IsValidMeleeAttackTarget( entity attacker, entity target )
{
	if ( attacker == target )
		return false

	if ( target.IsBreakableGlass() )
		return true

	if ( !CanBeMeleed( target ) )
		return false

	if ( attacker.GetTeam() == target.GetTeam() )
		return false

#if SERVER
	if ( target.IsPlayer() )
	{
		//Make titans not able to melee the pilot who is doing the embark animation
		if ( GetTitanBeingRodeoed( target ) == attacker )
			return false
	}
#endif // #if SERVER

	if ( target.IsPhaseShifted() )
		return false

	if ( target.GetParent() == attacker )
		return false

	#if SERVER //Awkward, needed because it's CBaseCombatCharacter on server and C_BaseCombatCharacter on client, and because we allow melee on non BaseCombatCharacters like props that don't have ContextActions defined
		if ( target instanceof CBaseCombatCharacter && target.ContextAction_IsMeleeExecutionTarget() ) //Don't lunge towards a victim that is already being executed )
			return false
	#elseif CLIENT
		if ( target instanceof C_BaseCombatCharacter && target.ContextAction_IsMeleeExecutionTarget() ) //Don't lunge towards a victim that is already being executed )
			return false
	#endif

	entity meleeWeapon = attacker.GetMeleeWeapon()
	if ( !IsValid( meleeWeapon ) )
		return false;

	if ( !meleeWeapon.GetMeleeCanHitHumanSized() && IsHumanSized( target ) )
		return false;
	if ( !meleeWeapon.GetMeleeCanHitTitans() && target.IsTitan() )
		return false;

	return true
}

void function CodeCallback_OnMeleePressed( entity player )
{

	if ( !Melee_IsAllowed( player ) )
	{
#if SERVER
		print( "SERVER: Melee_IsAllowed() for " + player + " is false\n" )
#else
		print( "CLIENT: Melee_IsAllowed() for " + player + " is false\n" )
#endif
		return
	}

#if SERVER
	if ( svGlobal.cloakBreaksOnMelee && IsCloaked( player ) )
		player.SetCloakFlicker( 1.0, 2.0 )
#endif // #if SERVER

	if ( player.IsWeaponDisabled() )
	{
#if SERVER
		print( "SERVER: IsWeaponDisabled() for " + player + " is true\n" )
#else
		print( "CLIENT: IsWeaponDisabled() for " + player + " is true\n" )
#endif
		return
	}

	if ( player.PlayerMelee_GetState() != PLAYER_MELEE_STATE_NONE )
		return

	if ( !IsAlive( player ) )
		return

	thread CodeCallback_OnMeleePressed_InternalThread( player )
}

void function CodeCallback_OnMeleePressed_InternalThread( entity player )
{
	if ( player.IsTitan() )
	{
		TitanUnsyncedMelee( player )
	}
	else if ( player.IsHuman() )
	{
		const float STUN_EFFECT_CUTOFF = 0.05
		float movestunEffect = StatusEffect_Get( player, eStatusEffect.move_slow )
		bool movestunBlocked = (movestunEffect > STUN_EFFECT_CUTOFF)

		HumanUnsyncedMelee( player, movestunBlocked )
	}
}

//void function CodeCallback_OnMeleeHeld( entity player )
//{
//}

//void function CodeCallback_OnMeleeReleased( entity player )
//{
//}

bool function ShouldHolsterWeaponForSyncedMelee( entity player )
{
	if ( player.GetPlayerSettings() == "titan_ogre_minigun" )
		return false

	return ShouldHolsterWeaponForMelee( player )
}

bool function ShouldHolsterWeaponForMelee( entity player )
{
	#if !SERVER
		return true
	#endif

	if ( !player.IsTitan() )
		return true

	return Time() - player.s.startDashMeleeTime > 1.0 //Fix issue with gun being out when it shouldn't, according to Mackey...
}

#if SERVER
bool function NPCTriesSyncedMeleeVsPlayer( entity npc, entity player )
{
	Assert( npc.IsNPC() )
	Assert( player.IsPlayer() )
	Assert( IsAlive( player ) )
	Assert( player.IsPlayer() )
	Assert( IsPilot( player ) )
	if ( player.ContextAction_IsBusy() )
		return false

	//#if SERVER
	//player.PlayerMelee_SetState( PLAYER_MELEE_STATE_HUMAN_EXECUTION )
	//#else
	//player.PlayerMelee_SetState( PLAYER_MELEE_STATE_HUMAN_EXECUTION_PREDICTED )
	//#endif

	return DoSyncedMelee( npc, player )
}
#endif



bool function PlayerTriesSyncedMelee( entity player, entity target )
{
	if ( !target )
		return false
	if ( !IsAlive( target ) )
		return false

	if ( target.ContextAction_IsBusy() )
		return false

	if ( player.IsTitan() )
	{
#if SERVER
		player.PlayerMelee_SetState( PLAYER_MELEE_STATE_TITAN_EXECUTION )
#else
		player.PlayerMelee_SetState( PLAYER_MELEE_STATE_TITAN_EXECUTION_PREDICTED )
#endif
	}
	else
	{
#if SERVER
		player.PlayerMelee_SetState( PLAYER_MELEE_STATE_HUMAN_EXECUTION )
#else
		player.PlayerMelee_SetState( PLAYER_MELEE_STATE_HUMAN_EXECUTION_PREDICTED )
#endif
	}

	if ( !player.Lunge_IsActive() || !player.Lunge_IsGroundExecute() || !player.Lunge_IsLungingToEntity() || (player.Lunge_GetTargetEntity() != target) )
		player.Lunge_SetTargetEntity( target, false )

#if SERVER
	OnThreadEnd(
		function() : ( player, target )
		{
			if ( IsValid( player ) && player.IsPlayer() )
			{
				RemoveCinematicFlag( player, CE_FLAG_TITAN_3P_CAM )
				RemoveCinematicFlag( player, CE_FLAG_EXECUTION )
			}
			if ( IsValid( target ) && target.IsPlayer() )
			{
				RemoveCinematicFlag( target, CE_FLAG_TITAN_3P_CAM )
				RemoveCinematicFlag( target, CE_FLAG_EXECUTION )
			}
		}
	)

	if ( player.IsTitan() )
		TransferDamageHistoryToTarget( target )
	if ( player.IsPlayer() )
	{
		AddCinematicFlag( player, CE_FLAG_TITAN_3P_CAM )
		AddCinematicFlag( player, CE_FLAG_EXECUTION )
	}
	if ( IsValid( target ) && target.IsPlayer() )
	{
		AddCinematicFlag( target, CE_FLAG_TITAN_3P_CAM )
		AddCinematicFlag( player, CE_FLAG_EXECUTION )
	}
#endif

	bool success = DoSyncedMelee( player, target )
	if ( !success )
	{
		player.Lunge_ClearTarget()
	}

	return success
}

function TransferDamageHistoryToTarget( entity target )
{
	entity titanSoul = target.GetTitanSoul()
	target.e.recentDamageHistory = titanSoul.e.recentDamageHistory
}

bool function DoSyncedMelee( entity player, entity target )
{
	SyncedMeleeChooser ornull actions = GetSyncedMeleeChooserForPlayerVsTarget( player, target )

	Assert( actions != null, "No melee action for " + player + " vs " + target )
	expect SyncedMeleeChooser( actions )

#if SERVER
	if ( player.IsPlayer() )
	{
		PlayerMelee_StartLagCompensateTargetForLunge( player, target )
	}
#endif // #if SERVER

	SyncedMelee ornull action = FindBestSyncedMelee( player, target, actions )

#if SERVER
	if ( player.IsPlayer() )
	{

		player.ForceStand()
		player.UnforceStand()
		PlayerMelee_FinishLagCompensateTarget( player )
	}
#endif // #if SERVER

	if ( action == null )
		return false

	expect SyncedMelee( action )



	player.Signal( "OnSyncedMelee" )
	target.Signal( "OnSyncedMelee" )
	player.Signal( "OnSyncedMeleeAttacker" )
	target.Signal( "OnSyncedMeleeVictim" )

#if SERVER
	player.p.lastExecutionUsed = action.ref

	if ( actions in file.syncedMeleeServerCallbacks )
		thread SyncedMeleeServerCallbacks( actions, action, player, target )
	bool functionref( SyncedMelee action, entity player, entity target ) think = file.syncedMeleeServerThink[ actions ]
	return think( action, player, target )
#endif // #if SERVER

	return true
}

void function SyncedMeleeServerCallbacks( SyncedMeleeChooser actions, SyncedMelee action, entity player, entity target )
{
	// Added via AddSyncedMeleeServerCallback
	foreach ( index, _ in file.syncedMeleeServerCallbacks[ actions ] )
	{
		void functionref( SyncedMeleeChooser actions, SyncedMelee action, entity player, entity target ) item = file.syncedMeleeServerCallbacks[ actions ][ index ]
		item( actions, action, player, target )
	}
}

/*
void function CodeCallback_OnMeleeReleased( entity player )
{
}
*/

function TextDebug( string msg )
{
	wait 0.5
	printt( msg )
}

bool function ShouldClampTargetVelocity( vector targetVelocity, vector pushBackVelocity, float clampRatio )
{
	float dot = DotProduct( targetVelocity, pushBackVelocity )
	if ( dot < 0 )
		return true

	if ( dot <= 0 )
		return false

	float velRatio = LengthSqr( targetVelocity ) / LengthSqr( pushBackVelocity )

	return velRatio < clampRatio
}

bool function CanBeMeleed( entity target )
{
	if ( target.IsPlayer() )
		return true
	if ( target.IsNPC() )
		return true

	if ( ObjectCanBeMeleed( target ) )
		return true

	return false
}

// IMPORTANT: Only used for non-player, non-living special cases like prop_dynamics we want to be able to melee (drones, etc)
bool function ObjectCanBeMeleed( entity ent )
{
	if ( !( "canBeMeleed" in ent.s ) )
		return false

	return expect bool( ent.s.canBeMeleed )
}

// IMPORTANT: Only used for non-player, non-living special cases like prop_dynamics we want to be able to melee (drones, etc)
function SetObjectCanBeMeleed( entity ent, bool value )
{
	Assert( !ent.IsPlayer(), ent + " should not be a player. This is for non-player, non-NPC entities.")
	Assert( !ent.IsNPC(), ent + " should not be an NPC. This is for non-player, non-NPC entities.")

	if ( !( "canBeMeleed" in ent.s ) )
		ent.s.canBeMeleed <- false

	ent.s.canBeMeleed = value
}

//function TitanExposionDeath( entity titan, entity attacker )
//{
//	if ( !IsAlive( titan ) )
//		return
//
//	ExplodeTitanBits( titan )
//	// and your pretty titan too!
//
//	//TitanEjectExplosion
//	table deathTable = { scriptType = damageTypes.titanMelee, forceKill = true, damageType = DMG_MELEE_EXECUTION, damageSourceId = eDamageSourceId.titan_execution }
//	titan.TakeDamage( titan.GetMaxHealth() + 1, attacker, attacker, deathTable )
//}

#if SERVER
vector function GetRefAnglesBetweenEnts( entity attacker, entity target )
{
	vector endOrigin = target.GetOrigin()
	vector startOrigin = attacker.GetOrigin()
	vector refVec = endOrigin - startOrigin
	vector refAng = VectorToAngles( refVec )
	if ( fabs( AngleNormalize( refAng.x ) ) > 35 ) //If pitch is too much, use angles from either attacker or target
	{
		if ( attacker.IsTitan() )
			refAng = attacker.GetAngles()  //Doing titan synced kill from front, so use attacker's origin
		else
			refAng = target.GetAngles()  // Doing rear necksnap, so use target's angles
	}
	return refAng
}

entity function CreateMeleeScriptMoverBetweenEnts( entity attacker, entity target )
{
	vector refAng = GetRefAnglesBetweenEnts( attacker, target )

	vector endOrigin = target.GetOrigin()
	vector startOrigin = attacker.GetOrigin()
	vector refVec = endOrigin - startOrigin
	vector refPos = endOrigin - refVec * 0.5

	entity ref = CreateOwnedScriptMover( attacker )
	ref.SetOrigin( refPos )
	ref.SetAngles( refAng )

	return ref
}
#endif // SERVER

void function AddSyncedMelee( SyncedMeleeChooser chooser, SyncedMelee melee )
{
	// sqr the distance
	melee.distanceSqr = melee.distance * melee.distance

	chooser.syncedMelees.append( melee )
}

SyncedMelee ornull function FindBestSyncedMelee( entity attacker, entity target, SyncedMeleeChooser actions )
{
	#if CLIENT
		Assert( attacker == GetLocalViewPlayer() )
	#endif // CLIENT

	vector absTargetToPlayerDir
	if ( attacker.IsPlayer() && attacker.Lunge_IsActive() && (attacker.Lunge_GetTargetEntity() == target) )
	{
		absTargetToPlayerDir = attacker.Lunge_GetStartPositionOffset()
		absTargetToPlayerDir = Normalize( absTargetToPlayerDir )
	}
	else
	{
		vector attackerPos = actions.attackerOriginFunc( attacker ) // + ( attacker.GetVelocity() * SMOOTH_TIME )
		vector targetPos = actions.targetOriginFunc( target )

		if ( attackerPos == targetPos )
		{
			absTargetToPlayerDir = < 1, 0, 0 >
		}
		else
		{
			absTargetToPlayerDir = Normalize( attackerPos - targetPos )
		}
	}

	vector angles = attacker.EyeAngles()
	vector forward = AnglesToForward( angles )

	vector relTargetToPlayerDir = CalcRelativeVector( < 0, target.EyeAngles().y, 0 >, absTargetToPlayerDir )

	array<SyncedMelee> bestActions
	float bestDot = -2.0
	float distSqr = LengthSqr( actions.attackerOriginFunc( attacker ) - actions.targetOriginFunc( target ) )

	bool npcTarget = target.IsNPC()
	bool playerAttacker = attacker.IsPlayer()

	int health = target.GetHealth()
	float healthRatio = HealthRatio( target )
	int meleeDamage
	if ( attacker.IsNPC() )
	{
		meleeDamage = attacker.GetMeleeDamageMaxForTarget( target )
	}
	else if ( attacker.IsPlayer() )
	{
		meleeDamage = GetPlayerMeleeDamage( attacker )
	}

	SyncedMelee ornull returnVal = null

#if MP
	if ( IsPilot( attacker ) )
	{
		PilotLoadoutDef loadout = GetActivePilotLoadout( attacker )

		foreach ( action in actions.syncedMelees )
		{
			if ( action.ref != loadout.execution )
				continue

			if ( npcTarget && !action.canTargetNPCs )
				break

			if ( playerAttacker && !action.usableByPlayers )
				break

			if ( healthRatio < action.targetMinHealthRatio )
				break

			if ( healthRatio > action.targetMaxHealthRatio )
				break

			if ( action.onlyIfLethal && health > meleeDamage )
				break

			if ( distSqr > action.distanceSqr )
				break

			float dot = relTargetToPlayerDir.Dot( action.direction )
			if ( dot < action.minDot )
				break

#if SERVER
			//Random Execution
			if ( string( attacker.GetPersistentVar( "activePilotLoadout.execution" )) == "execution_random")
			{
				returnVal = PickRandomExecution(actions, attacker)
				break
			}
#endif

			returnVal = action
			break
		}
	}
	else
	{
#endif
		foreach ( action in actions.syncedMelees )
		{
			if ( !action.enabled )
				continue

			if ( npcTarget && !action.canTargetNPCs )
				continue

			if ( playerAttacker && !action.usableByPlayers )
				continue

			if ( healthRatio < action.targetMinHealthRatio )
				continue

			if ( healthRatio > action.targetMaxHealthRatio )
				continue

			if ( action.onlyIfLethal && health > meleeDamage )
				continue

			if ( distSqr > action.distanceSqr )
				continue

			float dot = relTargetToPlayerDir.Dot( action.direction )

			//printt( "Dot: " + dot )

			if ( dot < action.minDot )
				continue

			if ( dot == bestDot )
			{
				bestActions.append( action )
				continue
			}

			if ( dot > bestDot )
			{
				// found new best dot
				bestActions.clear()
				bestDot = dot
				bestActions.append( action )
			}
		}

		if ( bestActions.len() )
			returnVal = bestActions.getrandom()
#if MP
	}
#endif

	return returnVal
}

string function GetAttackerSyncedMelee( entity ent )
{
	if ( ent.IsPlayer() )
	{
		// TODO: for MP, change this to be based on loadout choice
		string bodyType = GetPlayerBodyType( ent )
		if ( bodyType == "human" )
		{
			entity weapon = ent.GetActiveWeapon()
			var weaponSyncedMelee

			if ( IsValid( weapon ) )
				weaponSyncedMelee = weapon.GetWeaponInfoFileKeyField( "synced_melee_action" )

			if ( weaponSyncedMelee )
				return string( weaponSyncedMelee )
		}

		return bodyType

	}
	else if ( IsProwler( ent ) )
	{
		return "prowler"
	}
	else if ( IsPilotElite( ent ) )
	{
		return "pilotelite"
	}
	else if ( IsSpectre( ent ) )
	{
		return "spectre"
	}
	else if ( ent.IsNPC() )
	{
		return ent.GetBodyType()
	}
	else if ( ent.IsTitan() )
	{
		return "titan"
	}

	unreachable
}

string function GetVictimSyncedMeleeTargetType( entity ent )
{
	string targetType

	if ( ent.IsPlayer() && GetPlayerBodyType( ent ) == "human" )
	{
		targetType = "human"
	}
	else if ( IsProwler( ent ) )
	{
		targetType = "prowler"
	}

	// Disabled to allow for executing NPC Pilots

	// The way this function works, is that if an entity gets added here, then whatever "targetType" it returns
	// gets passed to sh_melee_synced_human.gnut or sh_melee_synced_titan.gnut,
	// which determines what animation set that entity should use when getting executed
	// If an entity is not included, the it uses its BodyType to determine it ( see line 83 in sh_melee_synced_human)
	// As you can see: Grunts, and Spectres are not included here, so it gets their BodyType (human) and goes from there

	// I imagine the reason Respawn added the NPC Pilots to this function, is so they could make unique executions for them,
	// just like the Prowlers
	// Unfortunately, they either scrapped them, or simply never got around to making them
	// That means this piece of code has basically no reason to exist anymore
	// The only thing it does is break executions and thats it
	// Since NPC Pilots also use the "human" BodyType, it means we can execute them with no issues

/*
	else if ( IsPilotElite( ent ) )
	{
		targetType = "pilotelite"
	}
*/
	else if ( ent.IsNPC() )
	{
		targetType = ent.GetBodyType()
	}
	else if ( ent.IsTitan() )
	{
		targetType = "titan"
	}
	else
	{
		Assert( 0, "Unknown ent type" )
	}

	return targetType
}

SyncedMeleeChooser ornull function GetSyncedMeleeChooserForPlayerVsTarget( entity attacker, entity target )
{
	string attackerType = GetAttackerSyncedMelee( attacker )
	string targetType = GetVictimSyncedMeleeTargetType( target )

	if ( !( attackerType in file.syncedMeleeChoosers ) )
		return null

	if ( !( targetType in file.syncedMeleeChoosers[ attackerType ] ) )
		return null

	return file.syncedMeleeChoosers[ attackerType ][ targetType ]
}

void function CodeCallback_OnMeleeAttackAnimEvent( entity player )
{
	Assert( IsValid( player ) )

	if ( player.PlayerMelee_IsAttackActive() )
	{
		if ( player.IsTitan() )
			TitanMeleeAttack( player )
		else if ( player.IsHuman() )
			HumanMeleeAttack( player )
	}
}

bool function IsInExecutionMeleeState( entity player )
{
	local meleeState = player.PlayerMelee_GetState()
	switch ( meleeState )
	{
		case PLAYER_MELEE_STATE_HUMAN_EXECUTION_PREDICTED:
		case PLAYER_MELEE_STATE_HUMAN_EXECUTION:
		case PLAYER_MELEE_STATE_TITAN_EXECUTION_PREDICTED:
		case PLAYER_MELEE_STATE_TITAN_EXECUTION:
			return true

		default:
			return false
	}

	unreachable
}

#if SERVER
void function InitMeleeAnimEventCallbacks( entity player )
{
	AddAnimEvent( player, "screen_blackout", MeleeBlackoutScreen_AE )
}

void function MeleeBlackoutScreen_AE( entity player )
{
	ScreenFadeToBlack( player, 0.7, 1.2 )
}
#endif

bool function ShouldPlayerExecuteTarget( entity player, entity target )
{
	if ( player.IsTitan() )
	{
		if ( !target.IsTitan() )
			return false

		if ( Flag( "ForceSyncedMelee" )  )
			return true

		if ( !GetDoomedState( target ) )
			return false

		entity soul = target.GetTitanSoul()
		if ( soul != null )
		{
			if ( soul.GetShieldHealth() > 0 && GetCurrentPlaylistVarInt( "titan_shield_blocks_execution", 0 ) != 0 )
				return false
		}

		if ( !SyncedMelee_IsAllowed( player ) )
			return false

		return true
	}

	if ( player.IsHuman() )
	{
		if ( !IsHumanSized( target ) )
			return false

#if SERVER
		if ( Flag( "ForceSyncedMelee" )  )
			return true
#endif // #if SERVER

		if ( !SyncedMelee_IsAllowed( player ) )
			return false
	}

	return true
}

vector function ClampVerticalVelocity( vector targetVelocity, float maxVerticalVelocity )
{
	vector clampedVelocity = targetVelocity
	if ( clampedVelocity.z > maxVerticalVelocity )
	{
		printt( "clampedVelocity.z: " + clampedVelocity.z +", maxVerticalVelocity:" + maxVerticalVelocity )
		clampedVelocity = Vector( targetVelocity.x, targetVelocity.y, maxVerticalVelocity )
	}

	return clampedVelocity
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

bool function CheckVerticallyCloseEnough( entity attacker, entity target )
{
	vector attackerOrigin = attacker.GetOrigin()
	vector targetOrigin = target.GetOrigin()

	float verticalDistance = fabs( attackerOrigin.z - targetOrigin.z )
	float halfHeight = 0

	if ( attacker.IsTitan() )
		halfHeight = 92.5
	else if ( attacker.IsHuman() )
		halfHeight = 30

	Assert( halfHeight, "Attacker is neither Titan nor Human" )

	//printt( "vertical distance: " + verticalDistance )
	return verticalDistance < halfHeight
}


entity function GetLungeTargetForPlayer( entity player )
{
	// Titan melee does not lunge
	if ( player.IsTitan() )
		return null

	if ( player.IsPhaseShifted() )
		return null

	entity lungeTarget = PlayerMelee_LungeConeTrace( player, SHARED_CB_IS_VALID_MELEE_ATTACK_TARGET )
	return lungeTarget
}

#if SERVER
void function Melee_Enable( entity player )
{
	player.SetPlayerNetBool( "playerAllowedToMelee", true )
}

void function Melee_Disable( entity player )
{
	player.SetPlayerNetBool( "playerAllowedToMelee", false )
}

void function SyncedMelee_Enable( entity player )
{
	player.SetPlayerNetBool( "playerAllowedToSyncedMelee", true )
}

void function SyncedMelee_Disable( entity player )
{
	player.SetPlayerNetBool( "playerAllowedToSyncedMelee", false )
}
#endif

bool function Melee_IsAllowed( entity player )
{
	return player.GetPlayerNetBool( "playerAllowedToMelee" )
}

bool function SyncedMelee_IsAllowed( entity player )
{
	return player.GetPlayerNetBool( "playerAllowedToSyncedMelee" )
}

bool function IsAttackerRef( SyncedMelee ornull action, entity target )
{
	if ( action != null )
	{
		expect SyncedMelee( action )
		if ( action.isAttackerRef )
		{
			return true
		}
	}

	if ( !target )
		return true

	if ( !IsValid( target ) )
		return true

	if ( !target.IsPlayer() )
		return true

	return false
}

#if MP
#if SERVER
SyncedMelee ornull function PickRandomExecution( SyncedMeleeChooser actions, entity attacker )
{
	array<SyncedMelee> possibleExecutions = []

	SyncedMelee neckSnap

	foreach ( action in actions.syncedMelees )
	{
		if (action.ref == "execution_neck_snap")
			neckSnap = action

		if(!IsItemLocked( attacker, action.ref ) && action.ref != "execution_random" && action.ref != attacker.p.lastExecutionUsed)

			possibleExecutions.append(action)
	}

	if (possibleExecutions.len() == 0)
		return neckSnap

	possibleExecutions.randomize()

	return possibleExecutions[0]
}
#endif
#endif