-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathaicbhtoh.cpp
1829 lines (1585 loc) · 61.5 KB
/
aicbhtoh.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 Looking Glass Studios, Inc.
1996,1997,1998,1999,2000 Unpublished Work.
*/
///////////////////////////////////////////////////////////////////////////////
// $Header: r:/t2repos/thief2/src/ai/aicbhtoh.cpp,v 1.105 2000/03/06 22:36:26 bfarquha Exp $
//
// THINGS I HAVE TO ADD TO COMBAT THIS WEEKEND
//x a. detect what the weapon actually is
//x b. make sure sidestep and forward motion actions often end with attacks
// c. better skill dynamic range
//x d. bias against current specific mode
//x e. bias against current mode type
// f. try and deal w/distance better
//x g. support special attacks
// h. note an opponent facing away... deal with it
// what to do with blocks?
// skill usage in the HtoH combat code
// Sloth=IdleTime... if Null, should never idle
// Dodginess=Chance of doing a jitter motion (sidestep, backup)
// Aggression=Chance of doing an attack type
// Verbosity=modifier to likelihood of speaking during combat
// @TBD (toml 03-04-99): pick through these and determine what really is needed
// #define PROFILE_ON 1
#include <lg.h>
#include <mprintf.h>
#include <cfgdbg.h>
#include <appagg.h>
#include <ctagset.h>
#include <relation.h>
#include <playrobj.h>
#include <aiactloc.h>
#include <aiactmot.h>
#include <aiactmov.h>
#include <aiactori.h>
#include <aiactseq.h>
#include <aiapibhv.h>
#include <aiapisns.h>
#include <aiaware.h>
#include <aiapiact.h>
#include <aidebug.h>
#include <aicbhtoh.h>
#include <aipthloc.h>
#include <aibasabl.h>
#include <aiapisnd.h>
#include <aisndtyp.h>
#include <aiapiiai.h>
#include <aiprattr.h>
#include <aitagtyp.h>
#include <aipthcst.h>
#include <aigoal.h>
#include <aitrginf.h>
#include <mtagvals.h>
#include <objhp.h>
#include <objpos.h>
#include <dmgbase.h>
#include <physapi.h>
#include <objedit.h>
#include <simtime.h>
// @TODO: this is dark only, somehow...
#include <drkwswd.h>
#include <drkwbow.h>
#include <aiprcore.h>
// property stuff
#include <property.h>
#include <propface.h>
#include <propbase.h>
// for sAIFrustrated:
#include <aialert.h>
// for g_pRangedCombatProp:
#include <aiprrngd.h>
// for AIFleeIsDest
#include <aiflee.h>
// for cell zone info
#include <aipathdb.h>
#include <aiteams.h>
#include <traitman.h>
#include <random.h>
// for event callbacks/weapon watching
#include <weapcb.h>
#include <weapon.h>
// Must be last header
#include <dbmem.h>
#ifndef SHIP
#define AI_COMBAT_DEBUGGING
#endif
#ifdef AI_COMBAT_DEBUGGING
#define _HD "AIHTHWatch %d: "
#define _HD_P GetID()
#define _HTHWatchObj() (AIIsWatched(Cbt, GetID()))
#define _HTHWatchPrint(str) do { if (_HTHWatchObj()) mprintf(_HD##str,_HD_P); } while (0)
#define _HTHWatchPrint1(str,v1) do { if (_HTHWatchObj()) mprintf(_HD##str,_HD_P,v1); } while (0)
#define _HTHWatchPrint2(str,v1,v2) do { if (_HTHWatchObj()) mprintf(_HD##str,_HD_P,v1,v2); } while (0)
#define _HTHWatchPrint3(str,v1,v2,v3) do { if (_HTHWatchObj()) mprintf(_HD##str,_HD_P,v1,v2,v3); } while (0)
#define _HTHWatchPrint4(str,v1,v2,v3,v4) do { if (_HTHWatchObj()) mprintf(_HD##str,_HD_P,v1,v2,v3,v4); } while (0)
#define _HTHAddScreenString(str) // AddScreenString(str)
#define _HTHModeName(mode) g_AIAtkModeNames[ModeGetBase(mode)]
const char * g_AIAtkModeNames[] =
{ "Undecided","Clock","CounterClock","Charge","ChargeUnseen","Backoff",
"JumpBack","Advance","AdvanceBig","Avoid","Block","DirectedBlock",
"Dodge","Idle","NoMove","SwingQuick","SwingNormal","SwingMassive",
"SwingSpecial","TakeDamage","OffTheList" };
#else
#define _HTHWatchPrint(str)
#define _HTHWatchPrint1(str,v1)
#define _HTHWatchPrint2(str,v1,v2)
#define _HTHWatchPrint3(str,v1,v2,v3)
#define _HTHWatchPrint4(str,v1,v2,v3,v4)
#define _HTHAddScreenString(str)
#define _HTHModeName(mode)
#endif
#define _HTHWatchInterrupts(str) _HTHWatchPrint("_intr_ "str)
//////////////////////////////////////////////////////////////////////////////
#define YA_PI (3.14159265358979323846) // yet another pi
//////////////////////////////////////////////////////////////////////////////
static int overall_last_speech_time=0;
static mxs_vector default_audio;
static mxs_vector default_motion;
static IVectorProperty *g_pAIHtoHAudioResponse = NULL;
static sPropertyDesc HtoHAudioResp = { "HTHAudioResp", 0, NULL, 0, 0, { AI_ABILITY_CAT, "HtoHCombat: Audio Response" }, kPropertyChangeLocally };
static IVectorProperty *g_pAIHtoHMotionResponse = NULL;
static sPropertyDesc HtoHMotionResp = { "HTHMotionResp", 0, NULL, 0, 0, { AI_ABILITY_CAT, "HtoHCombat: Motion Response" }, kPropertyChangeLocally };
static IBoolProperty *g_pAIHtoHGruntAlways = NULL;
static sPropertyDesc HtoHGruntAlways = { "HTHGruntAlways", 0, NULL, 0, 0, { AI_ABILITY_CAT, "HtoHCombat: Grunt Always" }, kPropertyChangeLocally };
#ifdef AI_COMBAT_DEBUGGING
static IIntProperty *g_pAIHtoHModeOverride = NULL;
static sPropertyDesc HtoHModeOverride = { "HTHModeOverride", 0, NULL, 0, 0, { AI_DEBUG_CAT, "HtoHModeOverride" }, kPropertyChangeLocally };
#endif
static BOOL g_NoCombatRehosting=FALSE; // Set when defined config var "ai_no_combat_rehosting"
// These are for the first byte of network messages.
static tNetMsgHandlerID g_NetMsgRehostHandlerID;
static tNetMsgHandlerID g_NetMsgLoseControlHandlerID;
// build our properties
BOOL AIInitCombatHtoHAbility(IAIManager *)
{
g_pAIHtoHAudioResponse = CreateVectorProperty(&HtoHAudioResp,kPropertyImplVerySparse);
g_pAIHtoHMotionResponse = CreateVectorProperty(&HtoHMotionResp,kPropertyImplVerySparse);
g_pAIHtoHGruntAlways = CreateBoolProperty(&HtoHGruntAlways,kPropertyImplVerySparse);
#ifdef AI_COMBAT_DEBUGGING
g_pAIHtoHModeOverride = CreateIntProperty(&HtoHModeOverride,kPropertyImplVerySparse);
#endif
// i think i cant locally static init arrays, so i do them here once
default_audio.el[0] = 1.5; default_audio.el[1] = 7.0; default_audio.el[2] = 1.5;
default_motion.el[0] = 3.7; default_motion.el[1] = 7.0; default_motion.el[2] = 1.6;
return TRUE;
}
// clean up
BOOL AITermCombatHtoHAbility(void)
{
SafeRelease(g_pAIHtoHAudioResponse);
SafeRelease(g_pAIHtoHMotionResponse);
SafeRelease(g_pAIHtoHGruntAlways);
#ifdef AI_COMBAT_DEBUGGING
SafeRelease(g_pAIHtoHModeOverride);
#endif
return TRUE;
}
///////////////////////////////////////////////////////////////////////////////
//
// CLASS: cAIHtoHSubcombat
//
cAIHtoHSubcombat::cAIHtoHSubcombat()
: m_mode(kUndecided),
m_ModeDuration(0),
m_lastDistSq(kFloatMax),
m_OppAttacking(FALSE),
m_OppBlocking(FALSE),
m_DoDirectionBlock(-1),
m_EventQueuePtr(0),
m_TakeDamage(FALSE),
m_BackoffCount(0),
m_FrustrationTimer(20000, 45000),
m_lastChargeTime(0),
m_lastFleeTime(0),
m_failedChargePathTime(0),
m_BackoffFail(0),
m_pModeSels(&gm_DefaultModeSelections)
{
}
///////////////////////////////////////
cAIHtoHSubcombat::cAIHtoHSubcombat(sHtoHModeSelections * pModeSels)
: m_mode(kUndecided),
m_ModeDuration(0),
m_lastDistSq(kFloatMax),
m_OppAttacking(FALSE),
m_OppBlocking(FALSE),
m_DoDirectionBlock(-1),
m_EventQueuePtr(0),
m_TakeDamage(FALSE),
m_BackoffCount(0),
m_FrustrationTimer(20000, 45000),
m_lastChargeTime(0),
m_failedChargePathTime(0),
m_BackoffFail(0),
m_pModeSels(pModeSels)
{
}
///////////////////////////////////////
STDMETHODIMP_(void) cAIHtoHSubcombat::Init()
{
cAISubcombat::Init();
SetNotifications(kAICN_ActionProgress |
kAICN_Damage |
kAICN_Weapon |
kAICN_GoalChange);
}
///////////////////////////////////////
STDMETHODIMP_(const char *) cAIHtoHSubcombat::GetName()
{
return "Hand-to-hand combat";
}
///////////////////////////////////////
#define kHtoHVer 3
STDMETHODIMP_(BOOL) cAIHtoHSubcombat::Save(ITagFile * pTagFile)
{
if (cAISubcombat::Save(pTagFile))
{
if (AIOpenTagBlock(GetID(), kAISL_CombatHtoH, 0, kHtoHVer, pTagFile))
{
AITagMove(pTagFile, &m_mode);
AITagMove(pTagFile, &m_ModeDuration);
AITagMove(pTagFile, &m_lastDistSq);
AITagMove(pTagFile, &m_DoDirectionBlock);
AITagMove(pTagFile, &m_OppAttacking);
AITagMove(pTagFile, &m_OppBlocking);
AITagMove(pTagFile, &m_OppUnarmed);
AITagMove(pTagFile, &m_EventQueue);
AITagMove(pTagFile, &m_EventQueuePtr);
AITagMove(pTagFile, &m_TakeDamage);
m_FrustrationTimer.Save(pTagFile);
cStr tagStr;
m_DamageTags.ToString(&tagStr);
AITagMoveString(pTagFile, &tagStr);
AICloseTagBlock(pTagFile);
}
}
return TRUE;
}
///////////////////////////////////////
STDMETHODIMP_(BOOL) cAIHtoHSubcombat::Load(ITagFile * pTagFile)
{
if (cAISubcombat::Load(pTagFile))
{
if (AIOpenTagBlock(GetID(), kAISL_CombatHtoH, 0, kHtoHVer, pTagFile))
{
AITagMove(pTagFile, &m_mode);
AITagMove(pTagFile, &m_ModeDuration);
AITagMove(pTagFile, &m_lastDistSq);
AITagMove(pTagFile, &m_DoDirectionBlock);
AITagMove(pTagFile, &m_OppAttacking);
AITagMove(pTagFile, &m_OppBlocking);
AITagMove(pTagFile, &m_OppUnarmed);
AITagMove(pTagFile, &m_EventQueue);
AITagMove(pTagFile, &m_EventQueuePtr);
AITagMove(pTagFile, &m_TakeDamage);
m_FrustrationTimer.Load(pTagFile);
cStr tagStr;
AITagMoveString(pTagFile, &tagStr);
m_DamageTags.FromString(tagStr);
AICloseTagBlock(pTagFile);
overall_last_speech_time=0;
}
}
return TRUE;
}
////////////////////////////
// various rating interpretation/usage defines
#define RatingFltPercentage(rating) ((rating*0.2)-0.1)
#define RatingIdleTime(rating) (100+(200*rating))
///////////////////////////////////////////////////////////////////////////////
BOOL cAIHtoHSubcombat::CheckStat(eAIRating stat, eActPriority pri, float fac)
{
if (stat==kAIRT_Null)
return FALSE;
float chance=RatingFltPercentage(stat)*fac*256.0;
switch (pri)
{ // @TODO: this is dumb, need stats to be able to max things out much easier
case kRnd: chance*=((Rand()&0x7)+2)/5;
case kLow: chance/=1.8; break;
case kNorm: break;
case kHigh: chance*=1.8; break; // just use the base
case kMust: return TRUE;
}
#ifdef LISTEN_LOUD
BOOL res = (Rand()&0xff)<chance;
mprintf("Choosing %d chance %g for stat %d pri %d fac %g\n",res,chance,stat,pri,fac);
return res;
#else
return (Rand()&0xff)<chance;
#endif
}
#define CheckVerbosity(pri) (CheckStat(AIGetVerbosity(GetID()),pri,0.5))
#define CheckAptitude(pri) (CheckStat(AIGetAptitude(GetID()),pri,1.2))
///////////////////////////////////////
// check for our magic "halo code has told us to block in a direction"
STDMETHODIMP_(void) cAIHtoHSubcombat::OnGameEvent(void *magic)
{
enum eMTagDirectionValues dir_tags[]={kMTV_high,kMTV_right,kMTV_low,kMTV_left};
int phys_dir=(int)magic;
if (phys_dir<(sizeof(dir_tags)/sizeof(dir_tags[0])))
{
m_DoDirectionBlock=dir_tags[phys_dir];
SignalAction();
_HTHWatchPrint1("Halo Hit, directed block to %d\n",m_DoDirectionBlock);
}
}
DECLARE_TIMER(cAIHtoHSubcombat_OnActionProgress, Average);
STDMETHODIMP_(void) cAIHtoHSubcombat::OnActionProgress(IAIAction * pAction)
{
AUTO_TIMER(cAIHtoHSubcombat_OnActionProgress);
#ifdef NET_TODO // NEW_NETWORK_ENABLED
if (m_pAI->IsNetworkProxy())
{
// We are only controlling low-level combat actions, so don't call
// cAISubcombat::OnActionProgress which is for higher level decisions.
if (!pAction->InProgress())
SignalAction();
}
else if (m_pAIState->IsBrainsOnly())
{
// Another machine is deciding combat actions, but we still need to
// decide on goal changes.
SignalGoal();
}
else
#endif
cAISubcombat::OnActionProgress(pAction);
pAction = pAction->GetTrueAction(); // get our action in case proxied
if (pAction->GetResult() == kAIR_NoResultSwitch)
if ((pAction->GetType()==kAIAT_Locomote)||
((m_mode&kTypeInterrupt)==kTypeInterrupt))
SignalAction(); // while Loco or interruptable, signal actions
}
// if we are idling, check the timings
STDMETHODIMP_(void) cAIHtoHSubcombat::OnBeginFrame(void)
{
m_ModeDuration += AIGetFrameTime(); // let it go
}
STDMETHODIMP_(void) cAIHtoHSubcombat::OnDamage(const sDamageMsg *pMsg, ObjID realCulpritID)
{
mxs_vector *audio=&default_audio, *motion=&default_motion;
cAISubcombat::OnDamage(pMsg, realCulpritID);
if (pMsg->kind!=kDamageMsgDamage)
return; // if it isnt "damage" damage, go home
sDamage *ouch=pMsg->data.damage;
g_pAIHtoHAudioResponse->Get(GetID(),&audio);
g_pAIHtoHMotionResponse->Get(GetID(),&motion);
// add random
float dmg=ouch->amount, var;
var=((2.0*Rand()-RAND_MAX)/(RAND_MAX+1))*audio->el[2];
dmg+=var;
_HTHWatchPrint4("AudioResponse raw %g use %g parms %g %g\n",(float)ouch->amount,dmg,audio->el[0],audio->el[1]);
if (dmg>audio->el[0])
PlayCombatSound((dmg>audio->el[1])?kAISC_CombatHitDamageHigh:kAISC_CombatHitDamageLow,TRUE);
else
{
BOOL grunts=FALSE;
g_pAIHtoHGruntAlways->Get(GetID(),&grunts);
if (grunts)
{
_HTHWatchPrint("Grunt!\n"); // for now, till we have real data
PlayCombatSound(kAISC_CombatHitNoDam,TRUE);
}
}
dmg=ouch->amount;
var=((2.0*Rand()-RAND_MAX)/(RAND_MAX+1))*motion->el[2];
dmg+=var;
_HTHWatchPrint4("MotionResponse raw %g use %g parms %g %g\n",(float)ouch->amount,dmg,motion->el[0],motion->el[1]);
if (dmg>motion->el[0])
{
CacheVisualDamageTags(dmg>motion->el[1]);
m_TakeDamage=TRUE; // messages
SignalAction();
}
}
STDMETHODIMP_(void) cAIHtoHSubcombat::OnWeapon(eWeaponEvent ev, ObjID victim, ObjID culprit)
{
cAISubcombat::OnWeapon(ev, victim, culprit);
ObjID targetObj=GetTarget();
if (!targetObj)
return;
eAIHtoHCombatEvent new_ev=kAIHCE_EventNull;
if (ev&kStartEndEvents)
if (culprit==targetObj)
{ // my target has started or ended an action
if (ev&(kStartWindup|kStartAttack)) new_ev=kAIHCE_OppAttackStart;
else if (ev&kEndAttack) new_ev=kAIHCE_OppAttackEnd;
else if (ev&kStartBlock) new_ev=kAIHCE_OppBlockStart;
else if (ev&kEndBlock) new_ev=kAIHCE_OppBlockEnd;
else Warning(("what StartEndEvent is this? %x\n",ev));
}
else
if ((culprit != GetID()) && (victim != GetID()))
Warning(("Why am i being told %x %d %d\n",ev,victim,culprit));
else if (ev&kBlockEvent)
if (victim==GetID() || culprit==GetID())
new_ev=kAIHCE_Block;
else
Warning(("Hey, getting a block for %d %d, im %d\n",victim,culprit,GetID()));
else if (ev&kHitEvent)
if (victim==GetID())
new_ev=kAIHCE_Hit;
else if (culprit==GetID())
new_ev=kAIHCE_Hitting;
else
Warning(("Hey, getting a hit for %d %d, im %d\n",victim,culprit,GetID()));
if (new_ev!=kAIHCE_EventNull)
{
InformOfEvent(new_ev);
SignalAction();
}
}
///////////////////////////////////////
BOOL cAIHtoHSubcombat::CheckModeInterrupt(eMode * pNewMode)
{
// if we are in "response to ourselves" mode, do so
if (m_DoDirectionBlock!=-1) // we must Block
*pNewMode=kDirectedBlock;
else if (m_TakeDamage)
*pNewMode=kTakeDamage;
else
{
#define kTooCloseSq sq(3.5)
// See if we need a distance event
if (m_lastDistSq > kTooCloseSq && GetTargetInfo()->distSq < kTooCloseSq)
InformOfEvent(kAIHCE_TooClose);
m_lastDistSq = GetTargetInfo()->distSq;
if (m_EventQueuePtr) // hey, events to examine
if (!CheckInterruptForEvent(pNewMode)) // oh, we dont care
return FALSE;
}
return TRUE;
}
///////////////////////////////////////
float g_H2HNoFreshenRange = 34.0;
float g_H2HSpeed = 11.0;
DECLARE_TIMER(cAIHtoHSubcombat_SuggestActions, Average);
eMode cAIHtoHSubcombat::SelectMode()
{
eMode newMode = kUndecided;
if (m_mode == kIdle && m_ModeDuration < RatingIdleTime(AIGetSloth(GetID())))
{
_HTHWatchPrint1("still idling %d\n",m_ModeDuration);
newMode = kIdle; // if weve been idling under 1 second, keep going
}
else
{
switch (GetTargetInfo()->range) // now, we need to decide what to do
{
case kAICR_Unseen: newMode = kChargeUnseen; break;
case kAICR_HugeZ: newMode = kFrustrate; break;
case kAICR_Huge: newMode = kCharge; break;
case kAICR_Far: newMode = kAdvanceBig; break;
case kAICR_JustFar: newMode = kAdvance; break;
case kAICR_None:
case kAICR_Near:
if (m_BackoffCount < 3)
newMode = kBackoff;
else // this may need to become a RespTooOftenTooClose thing!!
newMode = kSwingQuick; // or should we just do a ChooseNewAttackMode?
break;
default:
{
newMode = ChooseNewAttackMode(GetTargetInfo()->id, GetTargetInfo()->loc, GetTargetInfo()->zdist);
}
break;
}
}
return newMode;
}
////////////////////////////////////////////////
// event tracking/parsing/updating sorts of code
////////////////////////////////////////////////
// update my internal gnosis of what the opponent is doing
void cAIHtoHSubcombat::UpdateOppState(eAIHtoHCombatEvent ev)
{
switch (ev) // parse what happened into quick changes in Opponent State
{
case kAIHCE_OppAttackStart: m_OppAttacking=TRUE; break;
case kAIHCE_OppAttackEnd: m_OppAttacking=FALSE; break;
case kAIHCE_OppBlockStart: m_OppBlocking=TRUE; break;
case kAIHCE_OppBlockEnd: m_OppBlocking=FALSE; break;
}
}
// tell me a combat event has happened
void cAIHtoHSubcombat::InformOfEvent(eAIHtoHCombatEvent ev)
{
if (m_EventQueuePtr>=AIHCE_EventQueueLen)
{
int i;
for (i=0; i<m_EventQueuePtr; i++)
UpdateOppState(m_EventQueue[i]);
m_EventQueuePtr=0;
}
m_EventQueue[m_EventQueuePtr++]=ev;
}
// check to see if any events in the queue imply a new mode now
BOOL cAIHtoHSubcombat::CheckInterruptForEvent(eMode * newMode)
{
sModeSelection *pSolution = NULL;
eAISoundConcept newCombatSound=kAISC_TypeMax;
int i=0;
while (i<m_EventQueuePtr)
{
eAIHtoHCombatEvent ev=m_EventQueue[i++];
UpdateOppState(ev);
#define kMaxResponseDistSq sq(10.0)
if (m_lastDistSq>kMaxResponseDistSq)
continue; // we only want to react if we are close to the opponent
switch (ev)
{
case kAIHCE_OppAttackStart:
if (!IsAttacking()&&!m_OppUnarmed&&CheckAptitude(kHigh))
pSolution=SolveResponse(m_pModeSels->responses.OpponentAttack);
else
_HTHWatchInterrupts("cant respond to attack, too bad\n");
break;
case kAIHCE_OppAttackEnd:
if (IsAvoiding())
_HTHWatchInterrupts("Ha-ha, missed me\n");
break;
case kAIHCE_OppBlockStart:
if (IsAttacking())
{
if (CheckVerbosity(kNorm))
newCombatSound=kAISC_CombatDetBlock;
_HTHWatchInterrupts("getting scared?\n");
}
break;
case kAIHCE_TooClose:
_HTHWatchInterrupts("back off\n");
if (CanRespond())
if (m_BackoffCount<2)
pSolution=SolveResponse(m_pModeSels->responses.TooCloseToOpponent);
else
pSolution=SolveResponse(m_pModeSels->responses.RemainingTooCloseToOpponent);
break;
case kAIHCE_OppBlockEnd:
if (CanRespond())
pSolution=SolveResponse(m_pModeSels->responses.Opening);
else
_HTHWatchInterrupts("cant respond to block end, too bad\n");
break;
case kAIHCE_ImContacted:
_HTHWatchInterrupts("Ooh! that hurt... not\n");
break;
case kAIHCE_TargetContacted:
_HTHWatchInterrupts("Next time you'll feel it\n");
break;
case kAIHCE_Stunned:
_HTHWatchInterrupts("Arent you tough\n");
break;
case kAIHCE_Block:
if (IsAttacking()) // oops, bummer for us
{
if (CheckVerbosity(kHigh)) newCombatSound=kAISC_CombatBlocked;
_HTHWatchInterrupts("You mock me\n");
}
else if (IsBlocking()) // take advantage
{
if (CheckVerbosity(kNorm)) newCombatSound=kAISC_CombatSuccBlock;
_HTHWatchInterrupts("Ha! nice try\n");
}
break;
case kAIHCE_ImDamaged:
_HTHWatchInterrupts("Ouch"); // if really hurt, worry about it
if (CanRespond()&&!m_OppUnarmed)
{
int my_hp=25, my_max=25;
ObjGetHitPoints(GetID(),&my_hp); ObjGetMaxHitPoints(GetID(),&my_max);
if (my_hp*3<my_max) // under 33%
pSolution=SolveResponse(m_pModeSels->responses.LowHitpoints);
}
break;
case kAIHCE_TargetDamaged:
_HTHWatchInterrupts("Ha! hit you"); // press the attack if opponent hurt
if (CanRespond())
{
int it_hp=25, it_max=25;
ObjGetHitPoints(GetTarget(),&it_hp); ObjGetMaxHitPoints(GetTarget(),&it_max);
if (it_hp*2<it_max) // under 50%
if (CheckAptitude(kHigh))
pSolution=SolveResponse(m_pModeSels->responses.Opening);
}
break;
case kAIHCE_Hitting:
break;
case kAIHCE_Hit:
if (CheckVerbosity(kNorm))
newCombatSound=kAISC_CombatSuccHit;
break;
}
}
m_EventQueuePtr=0;
if (newCombatSound!=kAISC_TypeMax)
PlayCombatSound(newCombatSound,FALSE);
if (pSolution)
{
*newMode = pSolution->mode;
return TRUE;
}
return FALSE;
}
///////////////////////////////////////
eMode cAIHtoHSubcombat::ChooseNewAttackMode(ObjID target, const cMxsVector & targetLoc, float fZDist)
{
eMode newMode;
sModeSelection * pSolution = NULL;
ObjID weap_obj=GetWeaponObjID(target);
BOOL imBehindTarget=FALSE; // ok, want to add a facing check sort of thing
ObjPos * TargetPos = ObjPosGet(target);
floatang ang(targetLoc.x,targetLoc.y,m_pAIState->GetLocation()->x,m_pAIState->GetLocation()->y);
floatang plyfac(TargetPos->fac.tz*2*YA_PI/65536.0);
float ang_diff=Delta(plyfac,ang).value;
imBehindTarget=(ang_diff>(YA_PI/1.8)); // in the back quadrant
// if (imBehindTarget)
// mprintf("imBehindYou (%g player %g ang %g)\n",ang_diff,plyfac.value,ang.value);
// @TODO: cant be used for ranged stuff yet, since it doesnt deal
#ifdef THIEF
m_OppUnarmed=((weap_obj==OBJ_NULL)||(!WeaponIsSword(target,weap_obj)));
#else
m_OppUnarmed = FALSE;
#endif
// semi-hack. Flip "high" bit if we're above, say, 2.5 ft. @TBD: make this a config setting.
// Reset bit after.
if (fZDist > 2.5)
m_mode = (eMode)(((ulong)m_mode) | kTypeTargetHigh);
if (m_OppUnarmed || imBehindTarget)
pSolution = SolveResponse(m_pModeSels->attacks.OpponentUnarmed);
else if (m_OppAttacking&&CheckAptitude(kHigh)) // perhaps i should dodge or something
pSolution = SolveResponse(m_pModeSels->attacks.OpponentAttacking);
else if (m_OppBlocking&&CheckAptitude(kNorm))
pSolution = SolveResponse(m_pModeSels->attacks.OpponentBlocking);
else if (m_mode==kCharge) // for now, want to attack if we just charged, so pretend unarmed
pSolution = SolveResponse(m_pModeSels->attacks.OpponentUnarmed);
else if (CanRespond())
pSolution = SolveResponse(m_pModeSels->attacks.NormalWhileIdle);
else
pSolution = SolveResponse(m_pModeSels->attacks.NormalWhileActive);
// Reset "high" bit.
m_mode = (eMode)(((ulong)m_mode) & ~kTypeTargetHigh);
if (pSolution)
newMode = pSolution->mode;
else // im here, im near the player (in the range sweet spot)
newMode = (eMode)(Rand()%(kNumHtoHModes-1)+1); // skip undecided, shall we
return newMode;
}
///////////////////////////////////////
float cAIHtoHSubcombat::StatWeightMode(sModeSelection *choice)
{
eAIRating use_rating=kAIRT_Avg;
float modifier=1.0;
if (choice->mode==kIdle)
use_rating=AIGetSloth(GetID());
else if (ModeTest(choice->mode,kTypeAttack))
{
use_rating=AIGetAggression(GetID());
if (!ModeTest(m_mode,kTypeAttack))
if (use_rating>=kAIRT_Avg)
modifier*=1.2; // more likely to attack after not-attack
if (ModeTest(m_mode,kTypeTargetHigh) && ModeTest(choice->mode,kTypeTargetHigh))
modifier *= 10; // we definitely want to go for a high swing.
}
else if (ModeTest(choice->mode,kTypeDefend))
use_rating=AIGetDefensive(GetID());
else if (ModeTest(choice->mode,kTypeJitter))
use_rating=AIGetDodginess(GetID());
// skip things we never do
if (use_rating==kAIRT_Null) return 0.0;
// work on the modifier some
if (m_mode==choice->mode) modifier*=0.8; // reduce chance of picking same mode twice
if ((m_mode&kModeTypeMask)==(choice->mode&kModeTypeMask))
modifier*=0.8; // if the new mode is the same type as last mode, bias against
return 2*RatingFltPercentage(use_rating)*choice->wgt*modifier;
} // returns 0-1.0, so double, so 1.0 is "basic" value
// hmm, special dont attack unless we are close, somewhere, in this
sModeSelection *cAIHtoHSubcombat::SolveResponse(sModeSelections &selections)
{
float total=0.0;
int i, pick;
sModeSelection *Choices = selections.selections;
int nChoices = kAIHC_MaxSelections;
for (i=0; i<nChoices; i++)
if (Choices[i].mode == kUndefined)
{
nChoices = i;
break;
}
if (nChoices==0)
return NULL;
for (i=0; i<nChoices; i++)
total+=StatWeightMode(&Choices[i]);
if (total<=0)
return NULL;
//Having rare problem wherein AI with a low possible number of choices could have a
//total < 1, and then when you cast it to int and take the mod you crash. Whee.
//Putting in a failsafe if < 0.1 and then multiplying by 10 otherwise.
if (total<0.1)
pick = 0;
else
pick=Rand()%((int)(total*10.0));
for (total=0.0, i=0; i<nChoices; i++)
{
total+=(10.0*StatWeightMode(&Choices[i]));
if (pick<total)
break;
}
_HTHWatchPrint4("Chose %s (%d/%d) [weighted to %g]\n",_HTHModeName(Choices[i].mode),i,nChoices,StatWeightMode(&Choices[i]));
return &Choices[i];
}
///////////////////////////////////////
// who knows, etc, etc
#define DONT_TALK_TOO_MUCH 1600
void cAIHtoHSubcombat::PlayCombatSound(eAISoundConcept CombatSound, BOOL always)
{
if (!always)
if ( GetSimTime() < overall_last_speech_time + DONT_TALK_TOO_MUCH)
{
_HTHWatchPrint("The royal WE talked recently, staying silent\n");
return;
}
else
_HTHWatchPrint("Im allowed to talk\n");
if (!m_pAI->AccessSoundEnactor())
return;
int my_hp=50, it_hp=50, my_max=50, it_max=50;
float my_val=1, it_val=1, rating=1;
cTag balance_tags[]={cTag("ComBal","Losing"),cTag("ComBal","Even"),cTag("ComBal","Winning")};
cTagSet CombatStateTags;
int pick=1; // lose even win
// get Winning - change based on stats?
ObjGetHitPoints(GetID(),&my_hp); ObjGetHitPoints(GetTarget(),&it_hp);
ObjGetMaxHitPoints(GetID(),&my_max); ObjGetMaxHitPoints(GetTarget(),&it_max);
if (my_max!=0) my_val=my_hp/(float)my_max;
if (it_max!=0) it_val=it_hp/(float)it_max;
if (it_val!=0) rating=my_val/it_val;
if (rating<0.35) pick=0; else if (rating>2.0) pick=2;
if (pick==0) if (my_val>0.85) pick=1;
if (pick==2) if (it_val>0.85) pick=1;
if (pick==2) if (my_val<0.15) pick=1;
if (pick==0) if (it_val<0.15) pick=1;
CombatStateTags.Add(balance_tags[pick]);
// get Friends - for now, lets skip this
// actually do the sound
if (m_pAI->AccessSoundEnactor()->RequestConcept(CombatSound,&CombatStateTags))
{
if (CombatSound == kAISC_ReactCharge)
SetPlayedReactCharge();
if (!always)
overall_last_speech_time=GetSimTime();
}
}
///////////////////////////////////////
#define kTagLoco "Locomote 0"
#define kTagMelee "MeleeCombat 0"
#define kTagMeleeLoco kTagLoco "," kTagMelee
#define kTagDirection "Direction"
#define kTagMiddle "Direction 0"
#define kTagLeft "Direction 1"
#define kTagRight "Direction 2"
#define kTagForward "Direction 3"
#define kTagBackward "Direction 4"
#define kTagHigh "Direction 5"
#define kTagLow "Direction 6"
#define kTagFront "Direction 7"
#define kTagBack "Direction 8"
#define kTagDirParm(d) cTag("Direction",d)
#define kTagUrgent "LocoUrgent 0"
#define kTagStand "Stand 0"
#define kTagBlock "Block 0"
#define kTagAttack "Attack 0"
#define kTagDamaged "ReceiveWound 0"
#define kTagSevereWound "SevereWound 0"
#define kTagSpecial "SpecialAttack 0"
#define kTagSearch "Search 0"
#define kTagScan "Scan 0"
#define kTagFrustrated "Discover 0, Thwarted 0"
// "Crumple 0, Die 0"
//
#define MakeTagString1(a) a
#define MakeTagString2(a, b) a "," b
#define MakeTagString3(a, b, c) a "," b "," c
#define MakeTagString4(a, b, c, d) a "," b "," c "," d
#define MakeTagString5(a, b, c, d, e) a "," b "," c "," d "," e
extern int g_CollisionObj1; // holy crap this is a hack
extern int g_CollisionObj2; // for weapreac...
void cAIHtoHSubcombat::CacheVisualDamageTags(BOOL big_hit)
{
m_DamageTags.FromString(MakeTagString2(kTagMelee,kTagDamaged));
int parm_map[4]={7,1,8,2}, idx=0;
// compute direction somehow
int i_am_obj1=TRUE;
if (g_CollisionObj1!=GetID())
if (g_CollisionObj2==GetID())
i_am_obj1=FALSE;
else
Warning(("AICBHtoH InDamage, but I (%s) not involved\n",ObjWarnName(GetID())));
mxs_vector pos;
if (!GetObjLocation((ObjID)(i_am_obj1?g_CollisionObj2:g_CollisionObj1), &pos))
{
Warning(("AICBHtoH: Locationless object %s damaged me %s\n",
ObjWarnName(i_am_obj1?g_CollisionObj2:g_CollisionObj1),
ObjWarnName(GetID())));
_HTHWatchPrint1("damage response no direction (locationless obj %s)\n",
ObjWarnName(i_am_obj1?g_CollisionObj2:g_CollisionObj1));
return;
}
floatang direction = m_pAIState->AngleTo(pos);
float val = direction.value - m_pAIState->GetFacingAng().value;
if (val<0) val+=2*YA_PI;
// val+=(5*YA_PI/16)+0.05; // fudge val
val/=(YA_PI/2);
if ((val>0)&&(val<4)) idx=(int)val;
_HTHWatchPrint3("damage response direction leads to %g from %g -> %g\n",val,direction.value,direction.value-m_pAIState->GetFacingAng().value);
m_DamageTags.Add(kTagDirParm(parm_map[idx]));
if (big_hit)
m_DamageTags.Add(cTag("SevereWound",0)); // cant seem to add this as a string
}
///////////////////////////////////////
#define kFrustration 0x110598
cAISeqAction * cAIHtoHSubcombat::CreateFrustrationAction(ObjID target, const mxs_vector & targetLoc)
{
BOOL firstRecent = FALSE;
if (m_FrustrationTimer.Expired() && m_pAI->AccessSoundEnactor())
{
m_FrustrationTimer.Reset();
m_pAI->AccessSoundEnactor()->RequestConcept(kAISC_OutOfReach);
firstRecent = TRUE;
}
cAISeqAction * pSeqAction = new cAISeqAction(this, kFrustration);
cAIMotionAction * pMotionAction,
* pRightMotionAction,
* pLeftMotionAction;
if (firstRecent || AIRandom(1, 100) < 30)
{
pMotionAction = CreateMotionAction();
pMotionAction->AddTags(cTagSet(kTagFrustrated));
pSeqAction->Add(pMotionAction);
pMotionAction->Release();
}
floatang direction = m_pAIState->AngleTo(targetLoc);
if (AIRandom(1, 100) < 10)
{
pMotionAction = CreateMotionAction();
pMotionAction->AddTags(MakeTagString2(kTagStand, kTagMelee));
pMotionAction->SetFacing(direction);
pMotionAction->SetFocus(target);
pLeftMotionAction = CreateMotionAction();
pLeftMotionAction->AddTags(cTagSet(MakeTagString2(kTagMeleeLoco, kTagLeft)));
pLeftMotionAction->SetFacing(direction);
pLeftMotionAction->SetFocus(target);
pRightMotionAction = CreateMotionAction();