-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZeusBotAI.cs
More file actions
1307 lines (1124 loc) · 55 KB
/
ZeusBotAI.cs
File metadata and controls
1307 lines (1124 loc) · 55 KB
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
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API.Modules.Commands;
using CounterStrikeSharp.API.Modules.Admin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace ZeusBotAI
{
#region GOAP Core & Enums
public abstract class GoapAction
{
public virtual bool CheckContextPrecondition(BotAgent agent) => true;
public virtual bool IsValid(BotAgent agent) => true;
public abstract bool IsDone(BotAgent agent);
public abstract void Execute(BotAgent agent, float deltaTime);
public virtual void OnEnter(BotAgent agent) { }
public virtual void OnExit(BotAgent agent) { }
}
public abstract class GoapGoal
{
public abstract int GetPriority(BotAgent agent);
}
#endregion
#region Fact & Memory Architecture
public class Fact
{
public CCSPlayerController? Subject;
public Vector LastKnownPosition = new Vector(0, 0, 0);
public float Confidence = 1.0f;
public float ThreatLevel = 0f;
public float TimeSinceLastSeen = 0f;
}
public class WorkingMemory
{
public Dictionary<uint, Fact> Facts = new Dictionary<uint, Fact>();
public void Update(float deltaTime)
{
var keys = Facts.Keys.ToList();
foreach (var key in keys)
{
var fact = Facts[key];
if (fact.Subject == null || !fact.Subject.IsValid || !fact.Subject.PawnIsAlive)
{
Facts.Remove(key);
continue;
}
fact.TimeSinceLastSeen += deltaTime;
if (fact.TimeSinceLastSeen > 0.5f) // if not seen half a second, drop confidence rapidly
{
fact.Confidence -= deltaTime * 0.2f;
}
if (fact.Confidence <= 0)
{
Facts.Remove(key);
}
}
}
}
public class BotBlackboard
{
public Vector DesiredMoveDirection = new Vector(0, 0, 0);
public float DesiredSpeed = 0f;
public QAngle DesiredAim = new QAngle(0, 0, 0);
public ulong ButtonsToPress = 0;
public Fact? CurrentTargetFact = null;
public float FearTimer = 0f;
public float ActionCooldown = 0f;
// Navigation & Traversal
public float JumpCooldown = 0f;
// Combat Engine
public float NextStateTime = 0f;
public int MovePattern = 0;
public float StrafeDir = 1f;
public int BhopCount = 0;
}
#endregion
#region The Bot Agent
public class BotAgent
{
public CCSPlayerController Controller;
public CCSPlayerPawn Pawn => Controller.PlayerPawn.Value!;
public WorkingMemory Memory = new WorkingMemory();
public BotBlackboard Blackboard = new BotBlackboard();
public List<GoapGoal> Goals = new List<GoapGoal>();
public List<GoapAction> AvailableActions = new List<GoapAction>();
public Queue<GoapAction> CurrentPlan = new Queue<GoapAction>();
public GoapAction? CurrentAction = null;
public BotAgent(CCSPlayerController controller)
{
Controller = controller;
InitGoalsAndActions();
}
private void InitGoalsAndActions()
{
Goals.Add(new GoalSurvive());
Goals.Add(new GoalKillEnemy());
AvailableActions.Add(new ActionEquipZeus());
AvailableActions.Add(new ActionEquipKnife());
AvailableActions.Add(new ActionTraverseMap());
AvailableActions.Add(new ActionApproachTarget());
AvailableActions.Add(new ActionEvasiveRetreat());
AvailableActions.Add(new ActionEngageZeus());
AvailableActions.Add(new ActionEngageKnife());
}
public void UpdateSensor(List<CCSPlayerController> allPlayers, float currentTime)
{
if (Pawn == null || !Pawn.IsValid) return;
Vector myPos = Pawn.AbsOrigin!;
Vector myForward = MathUtils.GetForwardVector(Pawn.EyeAngles!);
bool foundValidEnemyOnMap = false;
foreach (var player in allPlayers)
{
if (player == Controller || !player.PawnIsAlive) continue;
if (player.TeamNum == Controller.TeamNum) continue;
var otherPawn = player.PlayerPawn.Value;
if (otherPawn == null || !otherPawn.IsValid) continue;
foundValidEnemyOnMap = true;
Vector otherPos = otherPawn.AbsOrigin!;
float dist = (myPos - otherPos).Length();
Vector dirToOther = MathUtils.NormalizeVector(otherPos - myPos);
// Add to memory
if (!Memory.Facts.ContainsKey(player.Index))
{
Memory.Facts[player.Index] = new Fact { Subject = player };
}
var fact = Memory.Facts[player.Index];
// We grant global wallhack "LastKnownPosition" so Base AI can natively map route to them
fact.LastKnownPosition = otherPos;
fact.Confidence = 1.0f;
// Completely eliminate cross-map sliding and wall staring by tightening Combat Thresholds
float zDiff = Math.Abs(myPos.Z - otherPos.Z);
bool isClose = dist < 750f; // Close enough to engage
bool reasonableZ = zDiff < 350f; // Allow tracking on stairs/ramps, but prevent direct ceiling staring
float dot = MathUtils.DotProduct(myForward, dirToOther);
bool inFOV = dot > 0.15f; // Loosened FOV so bots don't lose targets jumping rapidly
// Use native CS2 radar/spotted mechanics to evaluate visibility without leaking unmanaged memory
bool isSpotted = otherPawn.EntitySpottedState?.Spotted ?? false;
if (isClose && reasonableZ && inFOV && isSpotted)
{
fact.TimeSinceLastSeen = 0f;
fact.ThreatLevel = 3000f; // Instantly trigger Custom GOAP Custom Physics
}
else
{
// Not fighting. Let Base CS2 AI handle all NavMesh routing, freeze-time, and blind corners!
fact.ThreatLevel = 10f;
}
}
if (!foundValidEnemyOnMap)
{
var keys = Memory.Facts.Keys.ToList();
foreach (var k in keys) Memory.Facts.Remove(k);
}
}
public void Interrupt(string reason)
{
CurrentPlan.Clear();
CurrentAction?.OnExit(this);
CurrentAction = null;
}
public bool HasWeapon(string name)
{
if (Pawn?.WeaponServices?.MyWeapons == null) return false;
foreach (var w in Pawn.WeaponServices.MyWeapons)
{
var weapon = w.Value;
if (weapon != null && weapon.DesignerName != null && weapon.DesignerName.Contains(name))
{
return true;
}
}
return false;
}
}
#endregion
#region Goals & Actions Implementation
public class GoalKillEnemy : GoapGoal
{
public override int GetPriority(BotAgent agent) => agent.Blackboard.CurrentTargetFact != null ? 80 : 10;
}
public class GoalSurvive : GoapGoal
{
public override int GetPriority(BotAgent agent) => agent.Blackboard.FearTimer >= Server.CurrentTime ? 100 : 0;
}
public class ActionEquipZeus : GoapAction
{
public override bool IsDone(BotAgent agent)
{
var activeWeapon = agent.Pawn?.WeaponServices?.ActiveWeapon.Value;
return activeWeapon != null && activeWeapon.DesignerName.Contains("taser");
}
public override void Execute(BotAgent agent, float dt)
{
var weaponServices = agent.Pawn?.WeaponServices;
if (weaponServices?.MyWeapons != null)
{
foreach (var weaponHandle in weaponServices.MyWeapons)
{
var weapon = weaponHandle.Value;
if (weapon != null && weapon.DesignerName != null && weapon.DesignerName.Contains("taser"))
{
weaponServices.ActiveWeapon.Raw = weaponHandle.Raw;
Utilities.SetStateChanged(agent.Pawn!, "CBasePlayerPawn", "m_pWeaponServices");
break;
}
}
}
if (agent.Blackboard.CurrentTargetFact != null && agent.Blackboard.CurrentTargetFact.ThreatLevel > 100f && agent.Pawn != null && agent.Pawn.AbsOrigin != null)
{
agent.Blackboard.DesiredMoveDirection = MathUtils.NormalizeVector(agent.Blackboard.CurrentTargetFact.LastKnownPosition - agent.Pawn.AbsOrigin);
agent.Blackboard.DesiredSpeed = 250f;
}
else
{
// Ensures we aren't sliding with our weapon out during freeze-time or cross-map traversal
agent.Blackboard.DesiredSpeed = 0f;
agent.Blackboard.DesiredMoveDirection = new Vector(0,0,0);
}
}
}
public class ActionEquipKnife : GoapAction
{
public override bool IsDone(BotAgent agent)
{
var activeWeapon = agent.Pawn?.WeaponServices?.ActiveWeapon.Value;
return activeWeapon != null && activeWeapon.DesignerName.Contains("knife");
}
public override void Execute(BotAgent agent, float dt)
{
var weaponServices = agent.Pawn?.WeaponServices;
if (weaponServices?.MyWeapons != null)
{
foreach (var weaponHandle in weaponServices.MyWeapons)
{
var weapon = weaponHandle.Value;
if (weapon != null && weapon.DesignerName != null && weapon.DesignerName.Contains("knife"))
{
weaponServices.ActiveWeapon.Raw = weaponHandle.Raw;
Utilities.SetStateChanged(agent.Pawn!, "CBasePlayerPawn", "m_pWeaponServices");
break;
}
}
}
if (agent.Blackboard.CurrentTargetFact != null && agent.Blackboard.CurrentTargetFact.ThreatLevel > 100f && agent.Pawn != null && agent.Pawn.AbsOrigin != null)
{
agent.Blackboard.DesiredMoveDirection = MathUtils.NormalizeVector(agent.Blackboard.CurrentTargetFact.LastKnownPosition - agent.Pawn.AbsOrigin);
agent.Blackboard.DesiredSpeed = 250f;
}
else
{
agent.Blackboard.DesiredSpeed = 0f;
agent.Blackboard.DesiredMoveDirection = new Vector(0,0,0);
}
}
}
// NEW: Clean Map Traversal (Sprinting out of spawn normally)
public class ActionTraverseMap : GoapAction
{
public override bool CheckContextPrecondition(BotAgent agent) => agent.Blackboard.CurrentTargetFact != null;
public override bool IsDone(BotAgent agent)
{
if (agent.Blackboard.CurrentTargetFact == null) return true;
// Only stop traversing when we enter active combat (threat spikes from LOS or close proximity)
return agent.Blackboard.CurrentTargetFact.ThreatLevel > 100f;
}
public override void Execute(BotAgent agent, float dt)
{
// Fully hand off to CS2 native bot AI for map navigation.
// By NOT setting a DesiredSpeed, the InjectMotorCommands function will skip physics overrides,
// allowing the bot to freely navigate navmesh/nodes until they spot a threat!
agent.Blackboard.DesiredSpeed = 0f;
// Also zero out DesiredMoveDirection so the aim lerp math below knows we are passive
agent.Blackboard.DesiredMoveDirection = new Vector(0,0,0);
}
}
// Heavy Combat Approaching (B-hops and dodging)
public class ActionApproachTarget : GoapAction
{
public override bool CheckContextPrecondition(BotAgent agent) => agent.Blackboard.CurrentTargetFact != null;
public override bool IsDone(BotAgent agent)
{
// Instantly abort and give back control to Native CS2 AI if threat drops (target dipped behind corner or retreated)
if (agent.Blackboard.CurrentTargetFact == null || agent.Blackboard.CurrentTargetFact.ThreatLevel < 100f) return true;
float dist = (agent.Pawn.AbsOrigin! - agent.Blackboard.CurrentTargetFact.LastKnownPosition).Length();
bool hasZeus = agent.HasWeapon("taser");
var activeWep = agent.Pawn?.WeaponServices?.ActiveWeapon.Value;
bool holdsKnife = activeWep != null && activeWep.DesignerName.Contains("knife");
// Stop to swap to Zeus just before kill range
if (hasZeus && holdsKnife && dist < 450f) return true;
return dist <= (hasZeus ? 210f : 65f);
}
public override void Execute(BotAgent agent, float dt)
{
Vector targetPos = agent.Blackboard.CurrentTargetFact!.LastKnownPosition;
Vector myPos = agent.Pawn.AbsOrigin!;
float dist = (myPos - targetPos).Length();
// Dynamic Anti-Clump Offset (staggered by bot index)
float clumpOffsetAngle = agent.Controller.Index * 36f + Server.CurrentTime * 3f;
Vector approachPos = new Vector(targetPos.X + (float)Math.Cos(clumpOffsetAngle) * 55f, targetPos.Y + (float)Math.Sin(clumpOffsetAngle) * 55f, targetPos.Z);
Vector dirToApproach = MathUtils.NormalizeVector(approachPos - myPos);
Vector exactTargetDir = MathUtils.NormalizeVector(targetPos - myPos);
Vector rightDir = new Vector(-exactTargetDir.Y, exactTargetDir.X, 0);
bool isGrounded = ((uint)agent.Pawn.Flags & 1) != 0;
float currentTime = Server.CurrentTime;
if (currentTime > agent.Blackboard.NextStateTime)
{
Random r = new Random();
// Favor jumping/strafing heavily (patterns 1, 2, 3) over general ground jitter (0)
agent.Blackboard.MovePattern = r.Next(0, 4);
agent.Blackboard.NextStateTime = currentTime + (float)(r.NextDouble() * 1.0 + 0.5);
agent.Blackboard.StrafeDir = r.NextDouble() > 0.5 ? 1f : -1f;
agent.Blackboard.BhopCount = r.Next(2, 6); // More chained jumps
}
Vector mvmt = new Vector(0,0,0);
float speed = 250f;
if (agent.Blackboard.MovePattern == 1 || agent.Blackboard.MovePattern == 3)
{
// Active B-Hop Strafe
if (isGrounded && agent.Blackboard.JumpCooldown < currentTime)
{
agent.Blackboard.ButtonsToPress |= (ulong)PlayerButtons.Jump;
agent.Blackboard.JumpCooldown = currentTime + 0.3f;
agent.Blackboard.BhopCount--;
// Change strafe direction mid air randomly for harder tracking
if (agent.Blackboard.BhopCount % 2 == 0) agent.Blackboard.StrafeDir *= -1f;
}
if (!isGrounded)
{
// Sharp air strafes
mvmt = MathUtils.NormalizeVector((dirToApproach * 0.7f) + (rightDir * agent.Blackboard.StrafeDir * 1.0f));
speed = 280f;
if (agent.Blackboard.BhopCount % 3 == 0) agent.Blackboard.ButtonsToPress |= (ulong)PlayerButtons.Duck;
}
else
{
mvmt = dirToApproach;
}
}
else if (agent.Blackboard.MovePattern == 2)
{
// Wide Jump & Crouch-Slide
if (isGrounded && agent.Blackboard.JumpCooldown < currentTime)
{
agent.Blackboard.ButtonsToPress |= (ulong)PlayerButtons.Jump;
agent.Blackboard.JumpCooldown = currentTime + 0.6f;
}
float wideWeight = isGrounded ? 0.3f : 1.3f;
mvmt = MathUtils.NormalizeVector((dirToApproach * 0.7f) + (rightDir * agent.Blackboard.StrafeDir * wideWeight));
if (!isGrounded) agent.Blackboard.ButtonsToPress |= (ulong)PlayerButtons.Duck;
}
else
{
// Ground Jitter (Serpentine)
float jitter = (float)Math.Sin(currentTime * 5f + agent.Controller.Index);
if (Math.Abs(jitter) > 0.5f) agent.Blackboard.StrafeDir = Math.Sign(jitter);
mvmt = MathUtils.NormalizeVector((dirToApproach * 1.5f) + (rightDir * agent.Blackboard.StrafeDir * 0.4f));
}
agent.Blackboard.DesiredMoveDirection = mvmt;
agent.Blackboard.DesiredSpeed = speed;
}
}
public class ActionEvasiveRetreat : GoapAction
{
public override bool IsDone(BotAgent agent) => agent.Blackboard.FearTimer < Server.CurrentTime;
public override void Execute(BotAgent agent, float dt)
{
if (agent.Blackboard.CurrentTargetFact != null)
{
Vector tPos = agent.Blackboard.CurrentTargetFact.LastKnownPosition;
Vector myPos = agent.Pawn.AbsOrigin!;
Vector dirAway = MathUtils.NormalizeVector(myPos - tPos);
Vector right = new Vector(-dirAway.Y, dirAway.X, 0);
bool isGrounded = ((uint)agent.Pawn.Flags & 1) != 0;
if (isGrounded && agent.Blackboard.JumpCooldown < Server.CurrentTime)
{
agent.Blackboard.ButtonsToPress |= (ulong)PlayerButtons.Jump;
agent.Blackboard.JumpCooldown = Server.CurrentTime + 0.5f;
}
float erratic = (float)Math.Sin(Server.CurrentTime * 6f);
agent.Blackboard.DesiredMoveDirection = MathUtils.NormalizeVector((dirAway * 1.5f) + (right * Math.Sign(erratic) * 0.5f));
agent.Blackboard.DesiredSpeed = 260f;
}
}
}
public class ActionEngageZeus : GoapAction
{
public override bool CheckContextPrecondition(BotAgent agent) => true;
public override bool IsValid(BotAgent agent) => agent.Blackboard.CurrentTargetFact != null;
public override bool IsDone(BotAgent agent)
{
if (agent.Blackboard.CurrentTargetFact == null || agent.Blackboard.CurrentTargetFact.ThreatLevel < 100f) return true;
float dist = (agent.Pawn.AbsOrigin! - agent.Blackboard.CurrentTargetFact.LastKnownPosition).Length();
return dist > 230f; // Target retreated out of active range, fail and re-plan
}
public override void Execute(BotAgent agent, float dt)
{
if (agent.Blackboard.CurrentTargetFact == null) return;
Vector targetPos = agent.Blackboard.CurrentTargetFact.LastKnownPosition;
Vector myPos = agent.Pawn.AbsOrigin!;
float dist = (targetPos - myPos).Length();
// Fanning out when closing in to shoot
float clusterOffset = agent.Controller.Index * 50f + Server.CurrentTime * 2f;
Vector attackPos = new Vector(targetPos.X + (float)Math.Cos(clusterOffset) * 45f, targetPos.Y + (float)Math.Sin(clusterOffset) * 45f, targetPos.Z);
Vector dirToApproach = MathUtils.NormalizeVector(attackPos - myPos);
Vector exactDirToTarget = MathUtils.NormalizeVector(targetPos - myPos);
Vector rightDir = new Vector(-exactDirToTarget.Y, exactDirToTarget.X, 0);
bool isGrounded = ((uint)agent.Pawn.Flags & 1) != 0;
float time = Server.CurrentTime;
// Combat Dance
if (time > agent.Blackboard.NextStateTime)
{
Random r = new Random();
agent.Blackboard.MovePattern = r.Next(0, 3); // Better combat variety
agent.Blackboard.NextStateTime = time + 0.4f;
agent.Blackboard.StrafeDir = r.NextDouble() > 0.5 ? 1f : -1f;
}
if (agent.Blackboard.MovePattern == 0)
{
// Erratic ADAD Peek
float strafeVal = Math.Sign(Math.Sin(time * 6f));
agent.Blackboard.DesiredMoveDirection = MathUtils.NormalizeVector((dirToApproach * 0.4f) + (rightDir * strafeVal * 0.8f));
if (strafeVal > 0 && isGrounded) agent.Blackboard.ButtonsToPress |= (ulong)PlayerButtons.Duck;
}
else if (agent.Blackboard.MovePattern == 1)
{
// Micro jump strafe
agent.Blackboard.DesiredMoveDirection = MathUtils.NormalizeVector(dirToApproach + (rightDir * agent.Blackboard.StrafeDir * 0.5f));
if (isGrounded && agent.Blackboard.JumpCooldown < time)
{
agent.Blackboard.ButtonsToPress |= (ulong)PlayerButtons.Jump;
agent.Blackboard.JumpCooldown = time + 0.6f;
}
}
else
{
// Aggressive close with slight staggering
agent.Blackboard.DesiredMoveDirection = MathUtils.NormalizeVector(dirToApproach + (rightDir * agent.Blackboard.StrafeDir * 0.2f));
}
agent.Blackboard.DesiredSpeed = 260f;
// Aim Math
float eyeHeight = ((uint)agent.Pawn.Flags & 2) != 0 ? 46f : 64f;
Vector botHead = new Vector(myPos.X, myPos.Y, myPos.Z + eyeHeight);
float targetZ = Math.Clamp(botHead.Z, targetPos.Z, targetPos.Z + 72f);
Vector exactTarget = new Vector(targetPos.X, targetPos.Y, targetZ);
Vector exactDir = MathUtils.NormalizeVector(exactTarget - botHead);
Vector curForward = MathUtils.GetForwardVector(agent.Pawn.EyeAngles!);
float aimDot = MathUtils.DotProduct(curForward, exactDir);
// Firing threshold loosened to accommodate the organic noise/margin of aiming inaccuracy
if (aimDot > 0.985f || (dist < 150f && aimDot > 0.960f))
{
if (agent.Blackboard.ActionCooldown <= Server.CurrentTime)
{
agent.Blackboard.ButtonsToPress |= (ulong)PlayerButtons.Attack;
agent.Blackboard.ActionCooldown = Server.CurrentTime + 0.5f;
}
}
}
}
public class ActionEngageKnife : GoapAction
{
public override bool CheckContextPrecondition(BotAgent agent) => true;
public override bool IsValid(BotAgent agent) => agent.Blackboard.CurrentTargetFact != null;
public override bool IsDone(BotAgent agent)
{
if (agent.Blackboard.CurrentTargetFact == null || agent.Blackboard.CurrentTargetFact.ThreatLevel < 100f) return true;
float dist = (agent.Pawn.AbsOrigin! - agent.Blackboard.CurrentTargetFact.LastKnownPosition).Length();
return dist > 85f;
}
public override void Execute(BotAgent agent, float dt)
{
if (agent.Blackboard.CurrentTargetFact != null)
{
Vector targetPos = agent.Blackboard.CurrentTargetFact.LastKnownPosition;
Vector myPos = agent.Pawn.AbsOrigin!;
// Prevent exact body-stacking
float clusterOffset = agent.Controller.Index * 60f + Server.CurrentTime;
Vector stabPos = new Vector(targetPos.X + (float)Math.Cos(clusterOffset) * 20f, targetPos.Y + (float)Math.Sin(clusterOffset) * 20f, targetPos.Z);
Vector dirToTarget = MathUtils.NormalizeVector(stabPos - myPos);
agent.Blackboard.DesiredMoveDirection = dirToTarget;
agent.Blackboard.DesiredSpeed = 270f; // Slightly faster for knife
// Jump randomly if close to throw off enemy aim
if (((uint)agent.Pawn.Flags & 1) != 0 && agent.Blackboard.JumpCooldown < Server.CurrentTime && (targetPos - myPos).Length() < 150f)
{
agent.Blackboard.ButtonsToPress |= (ulong)PlayerButtons.Jump;
agent.Blackboard.JumpCooldown = Server.CurrentTime + 0.8f;
}
}
if (agent.Blackboard.ActionCooldown <= Server.CurrentTime)
{
agent.Blackboard.ButtonsToPress |= (ulong)PlayerButtons.Attack2;
agent.Blackboard.ActionCooldown = Server.CurrentTime + 0.8f;
}
}
}
#endregion
#region The GOAP Planner
public class GoapPlanner
{
public Queue<GoapAction> Plan(BotAgent agent, GoapGoal goal)
{
var usableActions = agent.AvailableActions.Where(a => a.CheckContextPrecondition(agent)).ToList();
List<GoapAction> plan = new List<GoapAction>();
if (goal is GoalSurvive)
{
plan.Add(usableActions.First(a => a is ActionEvasiveRetreat));
return new Queue<GoapAction>(plan);
}
if (goal is GoalKillEnemy)
{
float dist = 9999f;
bool inActiveCombat = false;
if (agent.Blackboard.CurrentTargetFact != null)
{
dist = (agent.Pawn.AbsOrigin! - agent.Blackboard.CurrentTargetFact.LastKnownPosition).Length();
inActiveCombat = agent.Blackboard.CurrentTargetFact.ThreatLevel > 100f;
}
bool hasZeus = agent.HasWeapon("taser");
if (!inActiveCombat)
{
// Far away or tracking behind walls -> Knife sprint
var equipKnife = usableActions.FirstOrDefault(a => a is ActionEquipKnife);
if (equipKnife != null) plan.Add(equipKnife);
var traverse = usableActions.FirstOrDefault(a => a is ActionTraverseMap);
if (traverse != null) plan.Add(traverse);
}
else
{
// In active combat logic
if (hasZeus)
{
if (dist > 450f)
{
var prepKnife = usableActions.FirstOrDefault(a => a is ActionEquipKnife);
if (prepKnife != null) plan.Add(prepKnife);
var approach = usableActions.FirstOrDefault(a => a is ActionApproachTarget);
if (approach != null) plan.Add(approach);
}
else
{
var pullZeus = usableActions.FirstOrDefault(a => a is ActionEquipZeus);
if (pullZeus != null) plan.Add(pullZeus);
if (dist > 210f)
{
var approachDodge = usableActions.FirstOrDefault(a => a is ActionApproachTarget);
if (approachDodge != null) plan.Add(approachDodge);
}
var kill = usableActions.FirstOrDefault(a => a is ActionEngageZeus);
if (kill != null) plan.Add(kill);
}
}
else
{
// No Zeus, pure knife run
var equipKnife = usableActions.FirstOrDefault(a => a is ActionEquipKnife);
if (equipKnife != null) plan.Add(equipKnife);
if (dist > 65f)
{
var approach = usableActions.FirstOrDefault(a => a is ActionApproachTarget);
if (approach != null) plan.Add(approach);
}
var kill = usableActions.FirstOrDefault(a => a is ActionEngageKnife);
if (kill != null) plan.Add(kill);
}
}
}
return new Queue<GoapAction>(plan);
}
}
#endregion
#region Math Utilities
public static class MathUtils
{
public static float NormalizeAngle(float angle)
{
if (float.IsNaN(angle) || float.IsInfinity(angle)) return 0f;
angle %= 360f;
if (angle > 180f) angle -= 360f;
else if (angle < -180f) angle += 360f;
return angle;
}
public static Vector GetForwardVector(QAngle angles)
{
float pitchRad = angles.X * (float)(Math.PI / 180.0);
float yawRad = angles.Y * (float)(Math.PI / 180.0);
return new Vector((float)(Math.Cos(yawRad) * Math.Cos(pitchRad)), (float)(Math.Sin(yawRad) * Math.Cos(pitchRad)), (float)(-Math.Sin(pitchRad)));
}
public static Vector NormalizeVector(Vector vec)
{
float length = (float)Math.Sqrt(vec.X * vec.X + vec.Y * vec.Y + vec.Z * vec.Z);
return length == 0 ? new Vector(0, 0, 0) : new Vector(vec.X / length, vec.Y / length, vec.Z / length);
}
public static float DotProduct(Vector v1, Vector v2) => (v1.X * v2.X) + (v1.Y * v2.Y) + (v1.Z * v2.Z);
}
#endregion
#region Main Plugin Component
public class ZeusBotConfig
{
[JsonPropertyName("PLAYERS_MANAGE_BOTS")]
public bool PlayersManageBots { get; set; } = true;
}
public class ZeusBotAIGoapPlugin : BasePlugin
{
public override string ModuleName => "Zeus Bot AI (Refactored Core)";
public override string ModuleVersion => "3.0.0";
private bool botsEnabled = true;
private ZeusBotConfig _config = new ZeusBotConfig();
private Dictionary<uint, BotAgent> agents = new Dictionary<uint, BotAgent>();
private GoapPlanner planner = new GoapPlanner();
private int tickCounter = 0;
private static readonly string[] BotNames = new string[]
{
"Zappy", "Sparky", "Zeus", "Bolt", "Zip", "Static", "Flicker", "Thor", "Jolt", "Volt",
"Watt", "Amp", "Ohm", "Tesla", "Arc", "Ion", "Surge", "Livewire", "Shorty", "Buzzer",
"Glow", "Indra", "Raiju", "Flash", "Shock", "Plasma", "Neon", "Zap", "Blitz", "Storm"
};
private Dictionary<uint, string> assignedNames = new Dictionary<uint, string>();
private Random rnd = new Random();
public override void Load(bool hotReload)
{
LoadConfig();
RegisterListener<Listeners.OnTick>(OnTick);
RegisterListener<Listeners.OnMapStart>(OnMapStart);
RegisterEventHandler<EventPlayerSpawn>(OnPlayerSpawn);
RegisterEventHandler<EventPlayerConnectFull>(OnPlayerConnectFull);
RegisterEventHandler<EventPlayerDisconnect>(OnPlayerDisconnect);
AddCommandListener("say", OnPlayerChat);
AddCommandListener("say_team", OnPlayerChat);
// Apply names to any bots already on the server (e.g. after hot reload)
Server.NextFrame(() => {
foreach (var player in Utilities.GetPlayers())
{
if (player.IsBot) EnsureBotName(player);
}
});
AddCommand("zeusbots", "Enable Zeus Bots", (player, info) => {
if (CheckCommandPermission(player))
{
botsEnabled = true;
Server.PrintToChatAll("Zeus Bots Enabled via Console Command");
}
});
AddCommand("normalbots", "Disable Zeus Bots", (player, info) => {
if (CheckCommandPermission(player))
{
botsEnabled = false;
Server.PrintToChatAll("Zeus Bots Disabled via Console Command");
}
});
AddCommand("removeallbots", "Kick all bots", (player, info) => {
if (CheckCommandPermission(player))
{
Server.ExecuteCommand("bot_kick");
Server.PrintToChatAll("All bots kicked via Console Command");
}
});
AddCommand("addtbot", "Add T Bot", (player, info) => {
if (CheckCommandPermission(player))
{
Server.ExecuteCommand("bot_add_t");
Server.PrintToChatAll("Terrorist Bot Added via Console Command");
}
});
AddCommand("addctbot", "Add CT Bot", (player, info) => {
if (CheckCommandPermission(player))
{
Server.ExecuteCommand("bot_add_ct");
Server.PrintToChatAll("CT Bot Added via Console Command");
}
});
Console.WriteLine("[Zeus Bot GOAP] Core Engine v3 loaded.");
}
private void LoadConfig()
{
string configPath = Path.Combine(ModuleDirectory, "../../configs/plugins/ZeusBotAI/config.json");
// If running locally/testing, fallback to local path
if (!File.Exists(configPath))
{
configPath = Path.Combine(ModuleDirectory, "config.json");
}
if (File.Exists(configPath))
{
try
{
string json = File.ReadAllText(configPath);
var config = JsonSerializer.Deserialize<ZeusBotConfig>(json);
if (config != null)
{
_config = config;
Console.WriteLine($"[ZeusBotAI] Config Loaded: PLAYERS_MANAGE_BOTS={_config.PlayersManageBots}");
}
}
catch (Exception ex)
{
Console.WriteLine($"[ZeusBotAI] Error loading config: {ex.Message}");
}
}
else
{
Console.WriteLine($"[ZeusBotAI] Config not found at {configPath}, using defaults.");
}
}
private void SaveConfig()
{
string configPath = Path.Combine(ModuleDirectory, "../../configs/plugins/ZeusBotAI/config.json");
if (!File.Exists(configPath))
{
configPath = Path.Combine(ModuleDirectory, "config.json");
}
try
{
string json = JsonSerializer.Serialize(_config, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(configPath, json);
Console.WriteLine($"[ZeusBotAI] Config Saved: PLAYERS_MANAGE_BOTS={_config.PlayersManageBots}");
}
catch (Exception ex)
{
Console.WriteLine($"[ZeusBotAI] Error saving config: {ex.Message}");
}
}
private bool CheckCommandPermission(CCSPlayerController? player)
{
if (player == null) return true; // Console/Server always has permission
if (_config.PlayersManageBots) return true;
bool isAdmin = AdminManager.PlayerHasPermissions(player, "@css/generic");
if (!isAdmin)
{
player.PrintToChat(" \x02[ZeusBots] You do not have permission to use this command.");
return false;
}
return true;
}
private void PrintHelpMessage(CCSPlayerController player)
{
bool isAdmin = AdminManager.PlayerHasPermissions(player, "@css/generic");
bool canManage = isAdmin || _config.PlayersManageBots;
if (!canManage) return;
// Header: Three dashes (White), Title (Blue), Three dashes (White)
player.PrintToChat(" \x01--- \x0CZeusBotAI Commands\x01 ---");
if (isAdmin)
{
player.PrintToChat(" \x0C!playersmanage\x01 - Allow players to manage bots");
player.PrintToChat(" \x0C!adminsmanage\x01 - Restrict management to admins");
}
// General Commands
if (canManage)
{
player.PrintToChat(" \x0C!zeusbots\x01 - Enable Zeus Bots");
player.PrintToChat(" \x0C!normalbots\x01 - Disable Zeus Bots");
player.PrintToChat(" \x0C!addtbot\x01 - Add Terrorist Bot");
player.PrintToChat(" \x0C!addctbot\x01 - Add Counter-Terrorist Bot");
player.PrintToChat(" \x0C!removeallbots\x01 - Kick all bots");
player.PrintToChat(" \x0C!help\x01 - Show this help");
}
}
private HookResult OnPlayerChat(CCSPlayerController? player, CommandInfo info)
{
if (player == null || !player.IsValid) return HookResult.Continue;
string text = info.GetArg(1).Trim();
// Remove quotes if present (sometimes arguments come quoted)
if (text.StartsWith("\"") && text.EndsWith("\"") && text.Length >= 2)
{
text = text.Substring(1, text.Length - 2);
}
if (string.Equals(text, "zeusbots", StringComparison.OrdinalIgnoreCase) ||
string.Equals(text, "!zeusbots", StringComparison.OrdinalIgnoreCase))
{
if (CheckCommandPermission(player))
{
botsEnabled = true;
Server.PrintToChatAll($"Zeus Bots Enabled by {player.PlayerName}");
}
}
else if (string.Equals(text, "normalbots", StringComparison.OrdinalIgnoreCase) ||
string.Equals(text, "!normalbots", StringComparison.OrdinalIgnoreCase))
{
if (CheckCommandPermission(player))
{
botsEnabled = false;
Server.PrintToChatAll($"Zeus Bots Disabled by {player.PlayerName}");
}
}
else if (string.Equals(text, "removeallbots", StringComparison.OrdinalIgnoreCase) ||
string.Equals(text, "!removeallbots", StringComparison.OrdinalIgnoreCase))
{
if (CheckCommandPermission(player))
{
Server.ExecuteCommand("bot_kick");
Server.PrintToChatAll($"All bots kicked by {player.PlayerName}");
}
}
else if (string.Equals(text, "addtbot", StringComparison.OrdinalIgnoreCase) ||
string.Equals(text, "!addtbot", StringComparison.OrdinalIgnoreCase))
{
if (CheckCommandPermission(player))
{
Server.ExecuteCommand("bot_add_t");
Server.PrintToChatAll($"Terrorist Bot Added by {player.PlayerName}");
}
}
else if (string.Equals(text, "addctbot", StringComparison.OrdinalIgnoreCase) ||
string.Equals(text, "!addctbot", StringComparison.OrdinalIgnoreCase))
{
if (CheckCommandPermission(player))
{
Server.ExecuteCommand("bot_add_ct");
Server.PrintToChatAll($"CT Bot Added by {player.PlayerName}");
}
}
else if (string.Equals(text, "playersmanage", StringComparison.OrdinalIgnoreCase) ||
string.Equals(text, "!playersmanage", StringComparison.OrdinalIgnoreCase))
{
if (AdminManager.PlayerHasPermissions(player, "@css/generic"))
{
_config.PlayersManageBots = true;
SaveConfig();
Server.PrintToChatAll(" \x0C[ZeusBots] Config Updated: Players can now manage bots.");
}
else
{
player.PrintToChat(" \x02[ZeusBots] You do not have permission to use this command.");
}
}
else if (string.Equals(text, "adminsmanage", StringComparison.OrdinalIgnoreCase) ||
string.Equals(text, "!adminsmanage", StringComparison.OrdinalIgnoreCase))
{
if (AdminManager.PlayerHasPermissions(player, "@css/generic"))
{
_config.PlayersManageBots = false;
SaveConfig();
Server.PrintToChatAll(" \x0C[ZeusBots] Config Updated: Only admins can now manage bots.");
}
else
{
player.PrintToChat(" \x02[ZeusBots] You do not have permission to use this command.");
}
}
else if (string.Equals(text, "help", StringComparison.OrdinalIgnoreCase) ||
string.Equals(text, "!help", StringComparison.OrdinalIgnoreCase))
{
PrintHelpMessage(player);
}
return HookResult.Continue;
}
private HookResult OnPlayerConnectFull(EventPlayerConnectFull @event, GameEventInfo info)
{
if (@event.Userid == null || !@event.Userid.IsValid) return HookResult.Continue;
var player = @event.Userid;
if (!player.IsBot)
{
PrintHelpMessage(player);
}
else
{
EnsureBotName(player);
}
return HookResult.Continue;
}
private HookResult OnPlayerDisconnect(EventPlayerDisconnect @event, GameEventInfo info)
{
// Free up the name when a bot disconnects
if (@event.Userid != null && @event.Userid.IsBot && assignedNames.ContainsKey(@event.Userid.Index))
{