forked from nillerusr/source-engine
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathai_basenpc.cpp
14131 lines (11977 loc) · 404 KB
/
ai_basenpc.cpp
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
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "ai_basenpc.h"
#include "fmtstr.h"
#include "activitylist.h"
#include "animation.h"
#include "basecombatweapon.h"
#include "soundent.h"
#include "decals.h"
#include "entitylist.h"
#include "eventqueue.h"
#include "entityapi.h"
#include "bitstring.h"
#include "gamerules.h" // For g_pGameRules
#include "scripted.h"
#include "worldsize.h"
#include "game.h"
#include "shot_manipulator.h"
#ifdef HL2_DLL
#include "ai_interactions.h"
#include "hl2_gamerules.h"
#endif // HL2_DLL
#include "ai_network.h"
#include "ai_networkmanager.h"
#include "ai_pathfinder.h"
#include "ai_node.h"
#include "ai_default.h"
#include "ai_schedule.h"
#include "ai_task.h"
#include "ai_hull.h"
#include "ai_moveprobe.h"
#include "ai_hint.h"
#include "ai_navigator.h"
#include "ai_senses.h"
#include "ai_squadslot.h"
#include "ai_memory.h"
#include "ai_squad.h"
#include "ai_localnavigator.h"
#include "ai_tacticalservices.h"
#include "ai_behavior.h"
#include "ai_dynamiclink.h"
#include "AI_Criteria.h"
#include "basegrenade_shared.h"
#include "ammodef.h"
#include "player.h"
#include "sceneentity.h"
#include "ndebugoverlay.h"
#include "mathlib/mathlib.h"
#include "bone_setup.h"
#include "IEffects.h"
#include "vstdlib/random.h"
#include "engine/IEngineSound.h"
#include "tier1/strtools.h"
#include "doors.h"
#include "BasePropDoor.h"
#include "saverestore_utlvector.h"
#include "npcevent.h"
#include "movevars_shared.h"
#include "te_effect_dispatch.h"
#include "globals.h"
#include "saverestore_bitstring.h"
#include "checksum_crc.h"
#include "iservervehicle.h"
#include "filters.h"
#ifdef HL2_DLL
#include "npc_bullseye.h"
#include "hl2_player.h"
#include "weapon_physcannon.h"
#endif
#include "waterbullet.h"
#include "in_buttons.h"
#include "eventlist.h"
#include "globalstate.h"
#include "physics_prop_ragdoll.h"
#include "vphysics/friction.h"
#include "physics_npc_solver.h"
#include "tier0/vcrmode.h"
#include "death_pose.h"
#include "datacache/imdlcache.h"
#include "vstdlib/jobthread.h"
#ifdef HL2_EPISODIC
#include "npc_alyx_episodic.h"
#endif
#ifdef PORTAL
#include "prop_portal_shared.h"
#endif
#include "env_debughistory.h"
#include "collisionutils.h"
extern ConVar sk_healthkit;
// dvs: for opening doors -- these should probably not be here
#include "ai_route.h"
#include "ai_waypoint.h"
#include "utlbuffer.h"
#include "gamestats.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#ifdef __clang__
// These clang 3.1 warnings don't seem very useful, and cannot easily be
// avoided in this file.
#pragma GCC diagnostic ignored "-Wdangling-else" // warning: add explicit braces to avoid dangling else [-Wdangling-else]
#endif
//#define DEBUG_LOOK
bool RagdollManager_SaveImportant( CAI_BaseNPC *pNPC );
#define MIN_PHYSICS_FLINCH_DAMAGE 5.0f
#define NPC_GRENADE_FEAR_DIST 200
#define MAX_GLASS_PENETRATION_DEPTH 16.0f
#define FINDNAMEDENTITY_MAX_ENTITIES 32 // max number of entities to be considered for random entity selection in FindNamedEntity
extern bool g_fDrawLines;
extern short g_sModelIndexLaser; // holds the index for the laser beam
extern short g_sModelIndexLaserDot; // holds the index for the laser beam dot
// Debugging tools
ConVar ai_no_select_box( "ai_no_select_box", "0" );
ConVar ai_show_think_tolerance( "ai_show_think_tolerance", "0" );
ConVar ai_debug_think_ticks( "ai_debug_think_ticks", "0" );
ConVar ai_debug_doors( "ai_debug_doors", "0" );
ConVar ai_debug_enemies( "ai_debug_enemies", "0" );
ConVar ai_rebalance_thinks( "ai_rebalance_thinks", "1" );
ConVar ai_use_efficiency( "ai_use_efficiency", "1" );
ConVar ai_use_frame_think_limits( "ai_use_frame_think_limits", "1" );
ConVar ai_default_efficient( "ai_default_efficient", ( IsX360() ) ? "1" : "0" );
ConVar ai_efficiency_override( "ai_efficiency_override", "0" );
ConVar ai_debug_efficiency( "ai_debug_efficiency", "0" );
ConVar ai_debug_dyninteractions( "ai_debug_dyninteractions", "0", FCVAR_NONE, "Debug the NPC dynamic interaction system." );
ConVar ai_frametime_limit( "ai_frametime_limit", "50", FCVAR_NONE, "frametime limit for min efficiency AIE_NORMAL (in sec's)." );
ConVar ai_use_think_optimizations( "ai_use_think_optimizations", "1" );
ConVar ai_test_moveprobe_ignoresmall( "ai_test_moveprobe_ignoresmall", "0" );
#ifdef HL2_EPISODIC
extern ConVar ai_vehicle_avoidance;
#endif // HL2_EPISODIC
#ifndef _RETAIL
#define ShouldUseEfficiency() ( ai_use_think_optimizations.GetBool() && ai_use_efficiency.GetBool() )
#define ShouldUseFrameThinkLimits() ( ai_use_think_optimizations.GetBool() && ai_use_frame_think_limits.GetBool() )
#define ShouldRebalanceThinks() ( ai_use_think_optimizations.GetBool() && ai_rebalance_thinks.GetBool() )
#define ShouldDefaultEfficient() ( ai_use_think_optimizations.GetBool() && ai_default_efficient.GetBool() )
#else
#define ShouldUseEfficiency() ( true )
#define ShouldUseFrameThinkLimits() ( true )
#define ShouldRebalanceThinks() ( true )
#define ShouldDefaultEfficient() ( true )
#endif
#ifndef _RETAIL
#define DbgEnemyMsg if ( !ai_debug_enemies.GetBool() ) ; else DevMsg
#else
#define DbgEnemyMsg if ( 0 ) ; else DevMsg
#endif
#ifdef DEBUG_AI_FRAME_THINK_LIMITS
#define DbgFrameLimitMsg DevMsg
#else
#define DbgFrameLimitMsg (void)
#endif
// NPC damage adjusters
ConVar sk_npc_head( "sk_npc_head","2" );
ConVar sk_npc_chest( "sk_npc_chest","1" );
ConVar sk_npc_stomach( "sk_npc_stomach","1" );
ConVar sk_npc_arm( "sk_npc_arm","1" );
ConVar sk_npc_leg( "sk_npc_leg","1" );
ConVar showhitlocation( "showhitlocation", "0" );
// Squad debugging
ConVar ai_debug_squads( "ai_debug_squads", "0" );
ConVar ai_debug_loners( "ai_debug_loners", "0" );
// Shoot trajectory
ConVar ai_lead_time( "ai_lead_time","0.0" );
ConVar ai_shot_stats( "ai_shot_stats", "0" );
ConVar ai_shot_stats_term( "ai_shot_stats_term", "1000" );
ConVar ai_shot_bias( "ai_shot_bias", "1.0" );
ConVar ai_spread_defocused_cone_multiplier( "ai_spread_defocused_cone_multiplier","3.0" );
ConVar ai_spread_cone_focus_time( "ai_spread_cone_focus_time","0.6" );
ConVar ai_spread_pattern_focus_time( "ai_spread_pattern_focus_time","0.8" );
ConVar ai_reaction_delay_idle( "ai_reaction_delay_idle","0.3" );
ConVar ai_reaction_delay_alert( "ai_reaction_delay_alert", "0.1" );
ConVar ai_strong_optimizations( "ai_strong_optimizations", ( IsX360() ) ? "1" : "0" );
bool AIStrongOpt( void )
{
return ai_strong_optimizations.GetBool();
}
//-----------------------------------------------------------------------------
//
// Crude frame timings
//
CFastTimer g_AIRunTimer;
CFastTimer g_AIPostRunTimer;
CFastTimer g_AIMoveTimer;
CFastTimer g_AIConditionsTimer;
CFastTimer g_AIPrescheduleThinkTimer;
CFastTimer g_AIMaintainScheduleTimer;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
CAI_Manager g_AI_Manager;
//-------------------------------------
CAI_Manager::CAI_Manager()
{
m_AIs.EnsureCapacity( MAX_AIS );
}
//-------------------------------------
CAI_BaseNPC **CAI_Manager::AccessAIs()
{
if (m_AIs.Count())
return &m_AIs[0];
return NULL;
}
//-------------------------------------
int CAI_Manager::NumAIs()
{
return m_AIs.Count();
}
//-------------------------------------
void CAI_Manager::AddAI( CAI_BaseNPC *pAI )
{
m_AIs.AddToTail( pAI );
}
//-------------------------------------
void CAI_Manager::RemoveAI( CAI_BaseNPC *pAI )
{
int i = m_AIs.Find( pAI );
if ( i != -1 )
m_AIs.FastRemove( i );
}
//-----------------------------------------------------------------------------
// ================================================================
// Init static data
// ================================================================
int CAI_BaseNPC::m_nDebugBits = 0;
CAI_BaseNPC* CAI_BaseNPC::m_pDebugNPC = NULL;
int CAI_BaseNPC::m_nDebugPauseIndex = -1;
CAI_ClassScheduleIdSpace CAI_BaseNPC::gm_ClassScheduleIdSpace( true );
CAI_GlobalScheduleNamespace CAI_BaseNPC::gm_SchedulingSymbols;
CAI_LocalIdSpace CAI_BaseNPC::gm_SquadSlotIdSpace( true );
string_t CAI_BaseNPC::gm_iszPlayerSquad;
int CAI_BaseNPC::gm_iNextThinkRebalanceTick;
float CAI_BaseNPC::gm_flTimeLastSpawn;
int CAI_BaseNPC::gm_nSpawnedThisFrame;
CSimpleSimTimer CAI_BaseNPC::m_AnyUpdateEnemyPosTimer;
//
// Deferred Navigation calls go here
//
CPostFrameNavigationHook g_PostFrameNavigationHook;
CPostFrameNavigationHook *PostFrameNavigationSystem( void )
{
return &g_PostFrameNavigationHook;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CPostFrameNavigationHook::Init( void )
{
m_Functors.Purge();
m_bGameFrameRunning = false;
return true;
}
// Main query job
CJob *g_pQueuedNavigationQueryJob = NULL;
static void ProcessNavigationQueries( CFunctor **pData, unsigned int nCount )
{
// Run all queued navigation on a separate thread
for ( int i = 0; i < nCount; i++ )
{
(*pData[i])();
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPostFrameNavigationHook::FrameUpdatePreEntityThink( void )
{
// If the thread is executing, then wait for it to finish
if ( g_pQueuedNavigationQueryJob )
{
g_pQueuedNavigationQueryJob->WaitForFinishAndRelease();
g_pQueuedNavigationQueryJob = NULL;
m_Functors.Purge();
}
if ( ai_post_frame_navigation.GetBool() == false )
return;
SetGrameFrameRunning( true );
}
//-----------------------------------------------------------------------------
// Purpose: Now that the game frame has collected all the navigation queries, service them
//-----------------------------------------------------------------------------
void CPostFrameNavigationHook::FrameUpdatePostEntityThink( void )
{
if ( ai_post_frame_navigation.GetBool() == false )
return;
// The guts of the NPC will check against this to decide whether or not to queue its navigation calls
SetGrameFrameRunning( false );
// Throw this off to a thread job
g_pQueuedNavigationQueryJob = ThreadExecute( &ProcessNavigationQueries, m_Functors.Base(), m_Functors.Count() );
}
//-----------------------------------------------------------------------------
// Purpose: Queue up our navigation call
//-----------------------------------------------------------------------------
void CPostFrameNavigationHook::EnqueueEntityNavigationQuery( CAI_BaseNPC *pNPC, CFunctor *pFunctor )
{
if ( ai_post_frame_navigation.GetBool() == false )
return;
m_Functors.AddToTail( pFunctor );
pNPC->SetNavigationDeferred( true );
}
//
// Deferred Navigation calls go here
//
// ================================================================
// Class Methods
// ================================================================
//-----------------------------------------------------------------------------
// Purpose: Static debug function to clear schedules for all NPCS
// Input :
// Output :
//-----------------------------------------------------------------------------
void CAI_BaseNPC::ClearAllSchedules(void)
{
CAI_BaseNPC *npc = gEntList.NextEntByClass( (CAI_BaseNPC *)NULL );
while (npc)
{
npc->ClearSchedule( "CAI_BaseNPC::ClearAllSchedules" );
npc->GetNavigator()->ClearGoal();
npc = gEntList.NextEntByClass(npc);
}
}
// ==============================================================================
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
bool CAI_BaseNPC::Event_Gibbed( const CTakeDamageInfo &info )
{
bool gibbed = CorpseGib( info );
if ( gibbed )
{
// don't remove players!
UTIL_Remove( this );
SetThink( NULL ); //We're going away, so don't think anymore.
}
else
{
CorpseFade();
}
return gibbed;
}
//=========================================================
// GetFlinchActivity - determines the best type of flinch
// anim to play.
//=========================================================
Activity CAI_BaseNPC::GetFlinchActivity( bool bHeavyDamage, bool bGesture )
{
Activity flinchActivity;
switch ( LastHitGroup() )
{
// pick a region-specific flinch
case HITGROUP_HEAD:
flinchActivity = bGesture ? ACT_GESTURE_FLINCH_HEAD : ACT_FLINCH_HEAD;
break;
case HITGROUP_STOMACH:
flinchActivity = bGesture ? ACT_GESTURE_FLINCH_STOMACH : ACT_FLINCH_STOMACH;
break;
case HITGROUP_LEFTARM:
flinchActivity = bGesture ? ACT_GESTURE_FLINCH_LEFTARM : ACT_FLINCH_LEFTARM;
break;
case HITGROUP_RIGHTARM:
flinchActivity = bGesture ? ACT_GESTURE_FLINCH_RIGHTARM : ACT_FLINCH_RIGHTARM;
break;
case HITGROUP_LEFTLEG:
flinchActivity = bGesture ? ACT_GESTURE_FLINCH_LEFTLEG : ACT_FLINCH_LEFTLEG;
break;
case HITGROUP_RIGHTLEG:
flinchActivity = bGesture ? ACT_GESTURE_FLINCH_RIGHTLEG : ACT_FLINCH_RIGHTLEG;
break;
case HITGROUP_CHEST:
flinchActivity = bGesture ? ACT_GESTURE_FLINCH_CHEST : ACT_FLINCH_CHEST;
break;
case HITGROUP_GEAR:
case HITGROUP_GENERIC:
default:
// just get a generic flinch.
if ( bHeavyDamage )
{
flinchActivity = bGesture ? ACT_GESTURE_BIG_FLINCH : ACT_BIG_FLINCH;
}
else
{
flinchActivity = bGesture ? ACT_GESTURE_SMALL_FLINCH : ACT_SMALL_FLINCH;
}
break;
}
// do we have a sequence for the ideal activity?
if ( SelectWeightedSequence ( flinchActivity ) == ACTIVITY_NOT_AVAILABLE )
{
if ( bHeavyDamage )
{
flinchActivity = bGesture ? ACT_GESTURE_BIG_FLINCH : ACT_BIG_FLINCH;
// If we fail at finding a big flinch, resort to a small one
if ( SelectWeightedSequence ( flinchActivity ) == ACTIVITY_NOT_AVAILABLE )
{
flinchActivity = bGesture ? ACT_GESTURE_SMALL_FLINCH : ACT_SMALL_FLINCH;
}
}
else
{
flinchActivity = bGesture ? ACT_GESTURE_SMALL_FLINCH : ACT_SMALL_FLINCH;
}
}
return flinchActivity;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
//-----------------------------------------------------------------------------
void CAI_BaseNPC::CleanupOnDeath( CBaseEntity *pCulprit, bool bFireDeathOutput )
{
if ( !m_bDidDeathCleanup )
{
m_bDidDeathCleanup = true;
if ( m_NPCState == NPC_STATE_SCRIPT && m_hCine )
{
// bail out of this script here
m_hCine->CancelScript();
// now keep going with the death code
}
if ( GetHintNode() )
{
GetHintNode()->Unlock();
SetHintNode( NULL );
}
if( bFireDeathOutput )
{
m_OnDeath.FireOutput( pCulprit, this );
}
// Vacate any strategy slot I might have
VacateStrategySlot();
// Remove from squad if in one
if (m_pSquad)
{
// If I'm in idle it means that I didn't see who killed me
// and my squad is still in idle state. Tell squad we have
// an enemy to wake them up and put the enemy position at
// my death position
if ( m_NPCState == NPC_STATE_IDLE && pCulprit)
{
// If we already have some danger memory, don't do this cheat
if ( GetEnemies()->GetDangerMemory() == NULL )
{
UpdateEnemyMemory( pCulprit, GetAbsOrigin() );
}
}
// Remove from squad
m_pSquad->RemoveFromSquad(this, true);
m_pSquad = NULL;
}
RemoveActorFromScriptedScenes( this, false /*all scenes*/ );
}
else
DevMsg( "Unexpected double-death-cleanup\n" );
}
void CAI_BaseNPC::SelectDeathPose( const CTakeDamageInfo &info )
{
if ( !GetModelPtr() || (info.GetDamageType() & DMG_PREVENT_PHYSICS_FORCE) )
return;
if ( ShouldPickADeathPose() == false )
return;
Activity aActivity = ACT_INVALID;
int iDeathFrame = 0;
SelectDeathPoseActivityAndFrame( this, info, LastHitGroup(), aActivity, iDeathFrame );
if ( aActivity == ACT_INVALID )
{
SetDeathPose( ACT_INVALID );
SetDeathPoseFrame( 0 );
return;
}
SetDeathPose( SelectWeightedSequence( aActivity ) );
SetDeathPoseFrame( iDeathFrame );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
//-----------------------------------------------------------------------------
void CAI_BaseNPC::Event_Killed( const CTakeDamageInfo &info )
{
if (IsCurSchedule(SCHED_NPC_FREEZE))
{
// We're frozen; don't die.
return;
}
Wake( false );
//Adrian: Select a death pose to extrapolate the ragdoll's velocity.
SelectDeathPose( info );
m_lifeState = LIFE_DYING;
CleanupOnDeath( info.GetAttacker() );
StopLoopingSounds();
DeathSound( info );
if ( ( GetFlags() & FL_NPC ) && ( ShouldGib( info ) == false ) )
{
SetTouch( NULL );
}
BaseClass::Event_Killed( info );
if ( m_bFadeCorpse )
{
m_bImportanRagdoll = RagdollManager_SaveImportant( this );
}
// Make sure this condition is fired too (OnTakeDamage breaks out before this happens on death)
SetCondition( COND_LIGHT_DAMAGE );
SetIdealState( NPC_STATE_DEAD );
// Some characters rely on getting a state transition, even to death.
// zombies, for instance. When a character becomes a ragdoll, their
// server entity ceases to think, so we have to set the dead state here
// because the AI code isn't going to pick up the change on the next think
// for us.
// Adrian - Only set this if we are going to become a ragdoll. We still want to
// select SCHED_DIE or do something special when this NPC dies and we wont
// catch the change of state if we set this to whatever the ideal state is.
if ( CanBecomeRagdoll() || IsRagdoll() )
SetState( NPC_STATE_DEAD );
// If the remove-no-ragdoll flag is set in the damage type, we're being
// told to remove ourselves immediately on death. This is used when something
// else has some special reason for us to vanish instead of creating a ragdoll.
// i.e. The barnacle does this because it's already got a ragdoll for us.
if ( info.GetDamageType() & DMG_REMOVENORAGDOLL )
{
if ( !IsEFlagSet( EFL_IS_BEING_LIFTED_BY_BARNACLE ) )
{
// Go away
RemoveDeferred();
}
}
}
//-----------------------------------------------------------------------------
void CAI_BaseNPC::Ignite( float flFlameLifetime, bool bNPCOnly, float flSize, bool bCalledByLevelDesigner )
{
BaseClass::Ignite( flFlameLifetime, bNPCOnly, flSize, bCalledByLevelDesigner );
#ifdef HL2_EPISODIC
CBasePlayer *pPlayer = AI_GetSinglePlayer();
if ( pPlayer->IRelationType( this ) != D_LI )
{
CNPC_Alyx *alyx = CNPC_Alyx::GetAlyx();
if ( alyx )
{
alyx->EnemyIgnited( this );
}
}
#endif
}
//-----------------------------------------------------------------------------
ConVar ai_block_damage( "ai_block_damage","0" );
bool CAI_BaseNPC::PassesDamageFilter( const CTakeDamageInfo &info )
{
if ( ai_block_damage.GetBool() )
return false;
// FIXME: hook a friendly damage filter to the npc instead?
if ( (CapabilitiesGet() & bits_CAP_FRIENDLY_DMG_IMMUNE) && info.GetAttacker() && info.GetAttacker() != this )
{
// check attackers relationship with me
CBaseCombatCharacter *npcEnemy = info.GetAttacker()->MyCombatCharacterPointer();
bool bHitByVehicle = false;
if ( !npcEnemy )
{
if ( info.GetAttacker()->GetServerVehicle() )
{
bHitByVehicle = true;
}
}
if ( bHitByVehicle || (npcEnemy && npcEnemy->IRelationType( this ) == D_LI) )
{
m_fNoDamageDecal = true;
if ( npcEnemy && npcEnemy->IsPlayer() )
{
m_OnDamagedByPlayer.FireOutput( info.GetAttacker(), this );
// This also counts as being harmed by player's squad.
m_OnDamagedByPlayerSquad.FireOutput( info.GetAttacker(), this );
}
return false;
}
}
if ( !BaseClass::PassesDamageFilter( info ) )
{
m_fNoDamageDecal = true;
return false;
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
int CAI_BaseNPC::OnTakeDamage_Alive( const CTakeDamageInfo &info )
{
Forget( bits_MEMORY_INCOVER );
if ( !BaseClass::OnTakeDamage_Alive( info ) )
return 0;
if ( GetSleepState() == AISS_WAITING_FOR_THREAT )
Wake();
// NOTE: This must happen after the base class is called; we need to reduce
// health before the pain sound, since some NPCs use the final health
// level as a modifier to determine which pain sound to use.
// REVISIT: Combine soldiers shoot each other a lot and then talk about it
// this improves that case a bunch, but it seems kind of harsh.
if ( !m_pSquad || !m_pSquad->SquadIsMember( info.GetAttacker() ) )
{
PainSound( info );// "Ouch!"
}
// See if we're running a dynamic interaction that should break when I am damaged.
if ( IsActiveDynamicInteraction() )
{
ScriptedNPCInteraction_t *pInteraction = GetRunningDynamicInteraction();
if ( pInteraction->iLoopBreakTriggerMethod & SNPCINT_LOOPBREAK_ON_DAMAGE )
{
// Can only break when we're in the action anim
if ( m_hCine->IsPlayingAction() )
{
m_hCine->StopActionLoop( true );
}
}
}
// If we're not allowed to die, refuse to die
// Allow my interaction partner to kill me though
if ( m_iHealth <= 0 && HasInteractionCantDie() && info.GetAttacker() != m_hInteractionPartner )
{
m_iHealth = 1;
}
#if 0
// HACKHACK Don't kill npcs in a script. Let them break their scripts first
// THIS is a Half-Life 1 hack that's not cutting the mustard in the scripts
// that have been authored for Half-Life 2 thus far. (sjb)
if ( m_NPCState == NPC_STATE_SCRIPT )
{
SetCondition( COND_LIGHT_DAMAGE );
}
#endif
// -----------------------------------
// Fire outputs
// -----------------------------------
if ( m_flLastDamageTime != gpGlobals->curtime )
{
// only fire once per frame
m_OnDamaged.FireOutput( info.GetAttacker(), this);
if( info.GetAttacker()->IsPlayer() )
{
m_OnDamagedByPlayer.FireOutput( info.GetAttacker(), this );
// This also counts as being harmed by player's squad.
m_OnDamagedByPlayerSquad.FireOutput( info.GetAttacker(), this );
}
else
{
// See if the person that injured me is an NPC.
CAI_BaseNPC *pAttacker = dynamic_cast<CAI_BaseNPC *>( info.GetAttacker() );
CBasePlayer *pPlayer = AI_GetSinglePlayer();
if( pAttacker && pAttacker->IsAlive() && pPlayer )
{
if( pAttacker->GetSquad() != NULL && pAttacker->IsInPlayerSquad() )
{
m_OnDamagedByPlayerSquad.FireOutput( info.GetAttacker(), this );
}
}
}
}
if( (info.GetDamageType() & DMG_CRUSH) && !(info.GetDamageType() & DMG_PHYSGUN) && info.GetDamage() >= MIN_PHYSICS_FLINCH_DAMAGE )
{
SetCondition( COND_PHYSICS_DAMAGE );
}
if ( m_iHealth <= ( m_iMaxHealth / 2 ) )
{
m_OnHalfHealth.FireOutput( info.GetAttacker(), this );
}
// react to the damage (get mad)
if ( ( (GetFlags() & FL_NPC) == 0 ) || !info.GetAttacker() )
return 1;
// If the attacker was an NPC or client update my position memory
if ( info.GetAttacker()->GetFlags() & (FL_NPC | FL_CLIENT) )
{
// ------------------------------------------------------------------
// DO NOT CHANGE THIS CODE W/O CONSULTING
// Only update information about my attacker I don't see my attacker
// ------------------------------------------------------------------
if ( !FInViewCone( info.GetAttacker() ) || !FVisible( info.GetAttacker() ) )
{
// -------------------------------------------------------------
// If I have an inflictor (enemy / grenade) update memory with
// position of inflictor, otherwise update with an position
// estimate for where the attack came from
// ------------------------------------------------------
Vector vAttackPos;
if (info.GetInflictor())
{
vAttackPos = info.GetInflictor()->GetAbsOrigin();
}
else
{
vAttackPos = (GetAbsOrigin() + ( g_vecAttackDir * 64 ));
}
// ----------------------------------------------------------------
// If I already have an enemy, assume that the attack
// came from the enemy and update my enemy's position
// unless I already know about the attacker or I can see my enemy
// ----------------------------------------------------------------
if ( GetEnemy() != NULL &&
!GetEnemies()->HasMemory( info.GetAttacker() ) &&
!HasCondition(COND_SEE_ENEMY) )
{
UpdateEnemyMemory(GetEnemy(), vAttackPos, GetEnemy());
}
// ----------------------------------------------------------------
// If I already know about this enemy, update his position
// ----------------------------------------------------------------
else if (GetEnemies()->HasMemory( info.GetAttacker() ))
{
UpdateEnemyMemory(info.GetAttacker(), vAttackPos);
}
// -----------------------------------------------------------------
// Otherwise just note the position, but don't add enemy to my list
// -----------------------------------------------------------------
else
{
UpdateEnemyMemory(NULL, vAttackPos);
}
}
// add pain to the conditions
if ( IsLightDamage( info ) )
{
SetCondition( COND_LIGHT_DAMAGE );
}
if ( IsHeavyDamage( info ) )
{
SetCondition( COND_HEAVY_DAMAGE );
}
ForceGatherConditions();
// Keep track of how much consecutive damage I have recieved
if ((gpGlobals->curtime - m_flLastDamageTime) < 1.0)
{
m_flSumDamage += info.GetDamage();
}
else
{
m_flSumDamage = info.GetDamage();
}
m_flLastDamageTime = gpGlobals->curtime;
if ( info.GetAttacker() && info.GetAttacker()->IsPlayer() )
m_flLastPlayerDamageTime = gpGlobals->curtime;
GetEnemies()->OnTookDamageFrom( info.GetAttacker() );
if (m_flSumDamage > m_iMaxHealth*0.3)
{
SetCondition(COND_REPEATED_DAMAGE);
}
NotifyFriendsOfDamage( info.GetAttacker() );
}
// ---------------------------------------------------------------
// Insert a combat sound so that nearby NPCs know I've been hit
// ---------------------------------------------------------------
CSoundEnt::InsertSound( SOUND_COMBAT, GetAbsOrigin(), 1024, 0.5, this, SOUNDENT_CHANNEL_INJURY );
return 1;
}
//=========================================================
// OnTakeDamage_Dying - takedamage function called when a npc's
// corpse is damaged.
//=========================================================
int CAI_BaseNPC::OnTakeDamage_Dying( const CTakeDamageInfo &info )
{
if ( info.GetDamageType() & DMG_PLASMA )
{
if ( m_takedamage != DAMAGE_EVENTS_ONLY )
{
m_iHealth -= info.GetDamage();
if (m_iHealth < -500)
{
UTIL_Remove(this);
}
}
}
return BaseClass::OnTakeDamage_Dying( info );
}
//=========================================================
// OnTakeDamage_Dead - takedamage function called when a npc's
// corpse is damaged.
//=========================================================
int CAI_BaseNPC::OnTakeDamage_Dead( const CTakeDamageInfo &info )
{
Vector vecDir;
// grab the vector of the incoming attack. ( pretend that the inflictor is a little lower than it really is, so the body will tend to fly upward a bit).
vecDir = vec3_origin;
if ( info.GetInflictor() )
{
vecDir = info.GetInflictor()->WorldSpaceCenter() - Vector ( 0, 0, 10 ) - WorldSpaceCenter();
VectorNormalize( vecDir );
g_vecAttackDir = vecDir;
}
#if 0// turn this back on when the bounding box issues are resolved.
SetGroundEntity( NULL );
GetLocalOrigin().z += 1;
// let the damage scoot the corpse around a bit.
if ( info.GetInflictor() && (info.GetAttacker()->GetSolid() != SOLID_TRIGGER) )
{
ApplyAbsVelocityImpulse( vecDir * -DamageForce( flDamage ) );
}
#endif
// kill the corpse if enough damage was done to destroy the corpse and the damage is of a type that is allowed to destroy the corpse.
if ( g_pGameRules->Damage_ShouldGibCorpse( info.GetDamageType() ) )
{
// Accumulate corpse gibbing damage, so you can gib with multiple hits
if ( m_takedamage != DAMAGE_EVENTS_ONLY )
{
m_iHealth -= info.GetDamage() * 0.1;
}
}
if ( info.GetDamageType() & DMG_PLASMA )
{
if ( m_takedamage != DAMAGE_EVENTS_ONLY )
{
m_iHealth -= info.GetDamage();
if (m_iHealth < -500)
{
UTIL_Remove(this);
}
}
}
return 1;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CAI_BaseNPC::NotifyFriendsOfDamage( CBaseEntity *pAttackerEntity )
{
CAI_BaseNPC *pAttacker = pAttackerEntity->MyNPCPointer();
if ( pAttacker )
{
const Vector &origin = GetAbsOrigin();
for ( int i = 0; i < g_AI_Manager.NumAIs(); i++ )
{
const float NEAR_Z = 10*12;
const float NEAR_XY_SQ = Square( 50*12 );
CAI_BaseNPC *pNpc = g_AI_Manager.AccessAIs()[i];
if ( pNpc && pNpc != this )
{
const Vector &originNpc = pNpc->GetAbsOrigin();
if ( fabsf( originNpc.z - origin.z ) < NEAR_Z )
{
if ( (originNpc.AsVector2D() - origin.AsVector2D()).LengthSqr() < NEAR_XY_SQ )
{
if ( pNpc->GetSquad() == GetSquad() || IRelationType( pNpc ) == D_LI )
pNpc->OnFriendDamaged( this, pAttacker );
}