-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff.txt
More file actions
971 lines (912 loc) · 89.8 KB
/
Copy pathdiff.txt
File metadata and controls
971 lines (912 loc) · 89.8 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
diff --git a/BossConfig.cs b/BossConfig.cs
index 143efb4..c73a16d 100644
--- a/BossConfig.cs
+++ b/BossConfig.cs
@@ -11,8 +11,9 @@ namespace EntBossHP
public List<MathCounterConfig> MathCounterList { get; set; } = [];
[JsonPropertyName("HPBar")]
+ [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
[Obsolete("HPBar is deprecated. Use MathCounter with health_segment_counter instead.")]
- public List<HPBarConfig> HPBarList { get; set; } = [];
+ public List<HPBarConfig>? HPBarList { get; set; }
}
public class BreakableConfig
diff --git a/BossData.cs b/BossData.cs
index fef53c8..bc7f41c 100644
--- a/BossData.cs
+++ b/BossData.cs
@@ -21,6 +21,7 @@ namespace EntBossHP
public bool Enabled { get; set; }
public int HpOffset { get; set; } = 0;
public bool DefeatPending { get; set; }
+ public bool Defeated { get; set; }
}
@@ -32,6 +33,7 @@ namespace EntBossHP
public int HealthSegments { get; set; }
public int TotalHealthSegments { get; set; }
public int HealthSegmentCounterMode { get; set; } = 1;
+ public int HealthSegmentCounterHpOffset { get; set; }
}
public class BreakableBoss : SegmentedBossData
diff --git a/EntBossHP.cs b/EntBossHP.cs
index 1fd1fd9..e0de688 100644
--- a/EntBossHP.cs
+++ b/EntBossHP.cs
@@ -2,7 +2,8 @@ using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes;
using CounterStrikeSharp.API.Modules.Commands;
-using CounterStrikeSharp.API.Modules.Memory;
+using CounterStrikeSharp.API.Modules.Entities;
+using CounterStrikeSharp.API.Modules.Events;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API.Modules.Timers;
using Microsoft.Extensions.Logging;
@@ -21,12 +22,15 @@ namespace EntBossHP
{
private const ulong SteamId64Base = 76561197960265728UL;
private const uint InvalidAccountId = uint.MaxValue;
+ private const float MathCounterDefeatConfirmationDelay = 1.35f;
+ private const float BreakableDefeatConfirmationDelay = 0.3f;
+ private const float AutoSegmentLearningWindow = 1.0f;
[GeneratedRegex(@"_\d{3,}$")]
private static partial Regex BossNameSuffixRegex();
public override string ModuleName => "EntBossHP";
- public override string ModuleVersion => "2.1.5";
+ public override string ModuleVersion => "2.1.13";
public override string ModuleAuthor => "Oylsister, Credits to Kxrnl, DarkerZ [RUS] / modified by Tsukasa";
public string PluginConfigDirectory => Path.Combine(ModuleDirectory, "..", "..", "configs", "plugins", ModuleName);
@@ -34,8 +38,11 @@ namespace EntBossHP
private readonly List<BreakableBoss> _breakableBosses = [];
private readonly List<MathCounterBoss> _mathCounterBosses = [];
+ private readonly Dictionary<string, float> _mathCounterValuesByName = new(StringComparer.Ordinal);
+ private readonly RuntimeAutoSegmentLearner _autoSegmentLearner = new(AutoSegmentLearningWindow);
private static readonly System.Threading.SemaphoreSlim SaveLock = new(1, 1);
+ private static long SaveGeneration;
private CCSGameRulesProxy? _gameRulesProxy;
private bool configLoaded = false;
@@ -47,9 +54,11 @@ namespace EntBossHP
private HitEventDisplay HitEventDisplay { get; set; } = null!;
// Store delegates using the correct EntityOutputHandler type to prevent GC collection
- private CounterStrikeSharp.API.Modules.Entities.EntityIO.EntityOutputHandler? _counterOutDelegate;
- private CounterStrikeSharp.API.Modules.Entities.EntityIO.EntityOutputHandler? _breakableOutDelegate;
- private CounterStrikeSharp.API.Modules.Entities.EntityIO.EntityOutputHandler? _hitboxHookDelegate;
+ private EntityIO.EntityOutputHandler? _counterOutDelegate;
+ private EntityIO.EntityOutputHandler? _physboxMultiplayerDamagedDelegate;
+ private EntityIO.EntityOutputHandler? _physboxHealthChangedDelegate;
+ private EntityIO.EntityOutputHandler? _breakableHealthChangedDelegate;
+ private EntityIO.EntityOutputHandler? _hitboxHookDelegate;
public override void Load(bool hotReload)
{
@@ -57,17 +66,20 @@ namespace EntBossHP
HitEventDisplay = new(this);
_counterOutDelegate = CounterOut;
- _breakableOutDelegate = BreakableOut;
+ _physboxMultiplayerDamagedDelegate = BreakableOut_PhysboxMultiplayerOnDamaged;
+ _physboxHealthChangedDelegate = BreakableOut_PhysboxOnHealthChanged;
+ _breakableHealthChangedDelegate = BreakableOut_FuncBreakableOnHealthChanged;
_hitboxHookDelegate = Hitbox_Hook;
HookEntityOutput("math_counter", "OutValue", _counterOutDelegate);
- HookEntityOutput("func_physbox_multiplayer", "OnDamaged", _breakableOutDelegate);
- HookEntityOutput("func_physbox", "OnHealthChanged", _breakableOutDelegate);
- HookEntityOutput("func_breakable", "OnHealthChanged", _breakableOutDelegate);
+ HookEntityOutput("func_physbox_multiplayer", "OnDamaged", _physboxMultiplayerDamagedDelegate);
+ HookEntityOutput("func_physbox", "OnHealthChanged", _physboxHealthChangedDelegate);
+ HookEntityOutput("func_breakable", "OnHealthChanged", _breakableHealthChangedDelegate);
HookEntityOutput("prop_dynamic", "OnHealthChanged", _hitboxHookDelegate);
RegisterEventHandler<EventRoundStart>(OnRoundStart);
RegisterListener<OnMapStart>(MapStart);
+ RegisterListener<OnMapEnd>(MapEnd);
RegisterListener<OnEntityCreated>(OnEntityCreated);
RegisterListener<OnTick>(OnTick);
RegisterEventHandler<EventPlayerDisconnect>(OnPlayerDisconnect);
@@ -77,7 +89,10 @@ namespace EntBossHP
if (hotReload)
{
- MapStart(Server.MapName);
+ if (ShouldRescanExistingMathCounters(hotReload, Server.MapName))
+ {
+ MapStart(Server.MapName);
+ }
}
}
@@ -91,9 +106,90 @@ namespace EntBossHP
public override void Unload(bool hotReload)
{
- RemoveListener<OnTick>(OnTick);
+ SafeUnhookEntityOutput("math_counter", "OutValue", _counterOutDelegate);
+ SafeUnhookEntityOutput("func_physbox_multiplayer", "OnDamaged", _physboxMultiplayerDamagedDelegate);
+ SafeUnhookEntityOutput("func_physbox", "OnHealthChanged", _physboxHealthChangedDelegate);
+ SafeUnhookEntityOutput("func_breakable", "OnHealthChanged", _breakableHealthChangedDelegate);
+ SafeUnhookEntityOutput("prop_dynamic", "OnHealthChanged", _hitboxHookDelegate);
+ SafeDeregisterEventHandler<EventRoundStart>(OnRoundStart);
+ SafeDeregisterEventHandler<EventPlayerDisconnect>(OnPlayerDisconnect);
+ SafeRemoveListener<OnMapStart>(MapStart);
+ SafeRemoveListener<OnMapEnd>(MapEnd);
+ SafeRemoveListener<OnEntityCreated>(OnEntityCreated);
+ SafeRemoveListener<OnTick>(OnTick);
+ ClearRuntimeState();
+ }
+
+ private void MapEnd() => ClearRuntimeState();
+
+ private static bool ShouldRescanExistingMathCounters(bool hotReload, string? mapName)
+ {
+ return !string.IsNullOrWhiteSpace(mapName);
+ }
+
+ private void ScheduleExistingMathCounterRescan()
+ {
+ AddTimer(0.1f, RescanExistingMathCounters, TimerFlags.STOP_ON_MAPCHANGE);
+ }
+
+ private void RescanExistingMathCounters()
+ {
+ if (!configLoaded) return;
+
+ try
+ {
+ foreach (var counter in Utilities.FindAllEntitiesByDesignerName<CMathCounter>("math_counter"))
+ {
+ if (counter is not { IsValid: true }) continue;
+ if (!string.Equals(counter.DesignerName, "math_counter", StringComparison.Ordinal)) continue;
+
+ Timer_MathCounterInitial(counter);
+ }
+ }
+ catch (Exception ex)
+ {
+ Logger.LogError(ex, "Error while rescanning existing math_counter entities");
+ }
+ }
+
+ private void ClearRuntimeState()
+ {
+ ResetBossHP();
+ _breakableBosses.Clear();
+ _mathCounterBosses.Clear();
+ _mathCounterValuesByName.Clear();
+ _autoSegmentLearner.Clear();
_gameRulesProxy = null;
+ configLoaded = false;
}
+
+ private void SafeUnhookEntityOutput(string classname, string outputName, EntityIO.EntityOutputHandler? handler)
+ {
+ if (handler is null) return;
+ try { UnhookEntityOutput(classname, outputName, handler); }
+ catch (Exception ex) { Logger.LogDebug(ex, "Failed to unhook {Class}.{Output}", classname, outputName); }
+ }
+
+ private void SafeDeregisterEventHandler<T>(BasePlugin.GameEventHandler<T> handler) where T : GameEvent
+ {
+ try { DeregisterEventHandler(handler); }
+ catch (Exception ex) { Logger.LogDebug(ex, "Failed to deregister event handler {Event}", typeof(T).Name); }
+ }
+
+ private void SafeRemoveListener<T>(T handler) where T : Delegate
+ {
+ try { RemoveListener(handler); }
+ catch (Exception ex) { Logger.LogDebug(ex, "Failed to remove listener {Listener}", typeof(T).Name); }
+ }
+
+ private HookResult BreakableOut_PhysboxMultiplayerOnDamaged(CEntityIOOutput o, string n, CEntityInstance a, CEntityInstance c, CVariant v, float d)
+ => BreakableOut(o, n, a, c, v, d);
+
+ private HookResult BreakableOut_PhysboxOnHealthChanged(CEntityIOOutput o, string n, CEntityInstance a, CEntityInstance c, CVariant v, float d)
+ => BreakableOut(o, n, a, c, v, d);
+
+ private HookResult BreakableOut_FuncBreakableOnHealthChanged(CEntityIOOutput o, string n, CEntityInstance a, CEntityInstance c, CVariant v, float d)
+ => BreakableOut(o, n, a, c, v, d);
private HookResult OnPlayerDisconnect(EventPlayerDisconnect @event, GameEventInfo info)
{
@@ -114,6 +210,10 @@ namespace EntBossHP
{
_gameRulesProxy = null;
LoadConfigBasedMap(mapname);
+ if (ShouldRescanExistingMathCounters(false, mapname))
+ {
+ ScheduleExistingMathCounterRescan();
+ }
}
private void OnTick()
@@ -169,10 +269,36 @@ namespace EntBossHP
}
Logger.LogInformation($"Loaded Boss Config {configPath}");
configLoaded = true;
+ if (EnsureConfiguredSegmentCounterEntries())
+ {
+ SaveChanges();
+ }
BossDataLoading();
}
+ private bool EnsureConfiguredSegmentCounterEntries()
+ {
+ var changed = false;
+
+ var segmentCounters = BossConfigs.MathCounterList
+ .Select(entry => entry.HealthSegmentCounter)
+ .Concat(BossConfigs.BreakableList.Select(entry => entry.HealthSegmentCounter))
+ .Where(segmentCounter => !string.IsNullOrWhiteSpace(segmentCounter))
+ .Distinct(StringComparer.Ordinal)
+ .ToList();
+
+ foreach (var segmentCounter in segmentCounters)
+ {
+ changed |= SegmentCounterConfigHelper.EnsureDisabledMathCounterEntry(
+ BossConfigs,
+ segmentCounter!,
+ NamesMatchEitherDirection);
+ }
+
+ return changed;
+ }
+
private void BossDataLoading()
{
_breakableBosses.Clear();
@@ -198,24 +324,37 @@ namespace EntBossHP
foreach (var mathcounter in BossConfigs.MathCounterList)
{
- var boss = new MathCounterBoss
- {
- BossName = mathcounter.Name,
- Enabled = mathcounter.Enabled,
- MathCounterHitMode = mathcounter.MathCounterMode,
- MathCounterName = mathcounter.MathCounter,
- HpOffset = mathcounter.HpOffset,
- };
- if (!string.IsNullOrEmpty(mathcounter.HealthSegmentCounter))
- {
- boss.IsSegmented = true;
- boss.HealthSegmentCounterName = mathcounter.HealthSegmentCounter;
- boss.HealthSegmentCounterMode = mathcounter.HealthSegmentCounterMode;
- }
- _mathCounterBosses.Add(boss);
+ _mathCounterBosses.Add(CreateLiveMathCounterBoss(mathcounter));
}
}
+ private MathCounterBoss CreateLiveMathCounterBoss(MathCounterConfig config)
+ {
+ var boss = new MathCounterBoss
+ {
+ BossName = config.Name,
+ Enabled = config.Enabled,
+ MathCounterHitMode = config.MathCounterMode,
+ MathCounterName = config.MathCounter,
+ HpOffset = config.HpOffset,
+ };
+ ApplySegmentConfigToBoss(config, boss);
+ return boss;
+ }
+
+ private void ApplySegmentConfigToBoss(MathCounterConfig config, MathCounterBoss boss)
+ {
+ if (string.IsNullOrWhiteSpace(config.HealthSegmentCounter)) return;
+
+ boss.IsSegmented = true;
+ boss.HealthSegmentCounterName = config.HealthSegmentCounter;
+ boss.HealthSegmentCounterMode = config.HealthSegmentCounterMode;
+ boss.HealthSegmentCounterHpOffset = SegmentCounterConfigHelper.GetSegmentCounterHpOffset(
+ BossConfigs,
+ config.HealthSegmentCounter,
+ NamesMatchEitherDirection);
+ }
+
private HookResult OnRoundStart(EventRoundStart @event, GameEventInfo info)
{
if (configLoaded)
@@ -228,22 +367,35 @@ namespace EntBossHP
private void ResetBossHP()
{
+ _mathCounterValuesByName.Clear();
+
foreach (var boss in _breakableBosses)
{
boss.Health = 0;
boss.MaxHealth = 0;
boss.BreakableEntity = null;
+ ResetSegmentRuntime(boss);
boss.DefeatPending = false;
+ boss.Defeated = false;
}
foreach (var boss in _mathCounterBosses)
{
boss.Health = 0;
boss.MaxHealth = 0;
boss.MathCounterEntity = null;
+ ResetSegmentRuntime(boss);
boss.DefeatPending = false;
+ boss.Defeated = false;
}
}
+ private static void ResetSegmentRuntime(SegmentedBossData boss)
+ {
+ boss.HealthSegmentCounterEntity = null;
+ boss.HealthSegments = 0;
+ boss.TotalHealthSegments = 0;
+ }
+
private void OnEntityCreated(CEntityInstance entity)
{
if (!configLoaded || entity == null || !entity.IsValid || entity.DesignerName != "math_counter") return;
@@ -278,9 +430,9 @@ namespace EntBossHP
{
var entityName = GetEntityName(entity);
if (string.IsNullOrWhiteSpace(entityName)) return;
- foreach (var boss in _mathCounterBosses.Where(b => b.IsSegmented && MatchesEntityName(entityName, b.HealthSegmentCounterName))) InitializeSegmentCounter(boss, entity);
- foreach (var boss in _breakableBosses.Where(b => b.IsSegmented && MatchesEntityName(entityName, b.HealthSegmentCounterName))) InitializeSegmentCounter(boss, entity);
- foreach (var boss in _mathCounterBosses.Where(b => MatchesEntityName(entityName, b.MathCounterName))) InitializeMainCounter(boss, entity);
+ foreach (var boss in _mathCounterBosses.Where(b => b.IsSegmented && MatchesEntityName(entityName, b.HealthSegmentCounterName))) InitializeSegmentCounter(boss, entity, entityName);
+ foreach (var boss in _breakableBosses.Where(b => b.IsSegmented && MatchesEntityName(entityName, b.HealthSegmentCounterName))) InitializeSegmentCounter(boss, entity, entityName);
+ foreach (var boss in _mathCounterBosses.Where(b => MatchesEntityName(entityName, b.MathCounterName))) InitializeMainCounter(boss, entity, entityName);
}
catch (Exception ex)
{
@@ -288,25 +440,34 @@ namespace EntBossHP
}
}
- private void InitializeSegmentCounter(SegmentedBossData boss, CEntityInstance entity)
+ private void InitializeSegmentCounter(SegmentedBossData boss, CEntityInstance entity, string entityName)
{
boss.HealthSegmentCounterEntity = entity;
var segmentCounter = new CMathCounter(entity.Handle);
- boss.TotalHealthSegments = (int)Math.Round(segmentCounter.Max);
- if (boss.HealthSegmentCounterMode == 2)
+ boss.TotalHealthSegments = Math.Max(0, (int)Math.Round(segmentCounter.Max));
+
+ if (TryGetRememberedMathCounterValue(entityName, out var counterValue))
+ {
+ UpdateSegmentHealthFromCounter(boss, (int)counterValue);
+ }
+ else
{
- var destroyedSegments = (int)GetMathCounterValue(entity.Handle);
- boss.HealthSegments = Math.Max(0, boss.TotalHealthSegments - destroyedSegments);
+ boss.HealthSegments = Math.Max(0, boss.TotalHealthSegments + boss.HealthSegmentCounterHpOffset);
}
- else boss.HealthSegments = (int)GetMathCounterValue(entity.Handle);
}
- private void InitializeMainCounter(MathCounterBoss boss, CEntityInstance entity)
+ private void InitializeMainCounter(MathCounterBoss boss, CEntityInstance entity, string entityName)
{
boss.MathCounterEntity = entity;
var counter = new CMathCounter(entity.Handle);
boss.MathCounterMaxValue = (int)Math.Round(counter.Max);
if (boss.MathCounterHitMode == 0) boss.MathCounterHitMode = 1;
+
+ if (TryGetRememberedMathCounterValue(entityName, out var counterValue))
+ {
+ var currentHp = ApplyMathCounterValue(boss, counterValue);
+ if (currentHp > 0) UpdateMaxHealth(boss, currentHp);
+ }
}
private HookResult CounterOut(CEntityIOOutput output, string name, CEntityInstance activator, CEntityInstance caller, CVariant value, float delay)
@@ -320,22 +481,40 @@ namespace EntBossHP
var entityname = GetEntityName(caller);
if (string.IsNullOrWhiteSpace(entityname)) return HookResult.Continue;
var counterValue = value.Get<float>();
+ var hadPreviousValue = TryGetRememberedMathCounterValue(entityname, out var previousCounterValue);
+ var counterMaxValue = TryGetMathCounterMax(caller);
+ RememberMathCounterValue(entityname, counterValue);
var counterValueInt = (int)counterValue;
- UpdateSegmentCounters(entityname, counterValueInt, client);
+ var isSegmentCounter = configLoaded && IsConfiguredSegmentCounter(entityname);
+ var autoSegmentObservation = configLoaded && !isSegmentCounter
+ ? _autoSegmentLearner.ObserveCounter(
+ entityname,
+ counterValue,
+ hadPreviousValue ? previousCounterValue : null,
+ counterMaxValue,
+ Server.CurrentTime,
+ NamesMatchEitherDirection)
+ : new RuntimeAutoSegmentObservation(false);
+ UpdateSegmentCounters(caller, entityname, counterValueInt, client);
+
+ if (isSegmentCounter || autoSegmentObservation.SuppressAutoCreate) return HookResult.Continue;
if (configLoaded)
{
- var isSegmentCounter = BossConfigs.MathCounterList.Any(b => MatchesEntityName(entityname, b.HealthSegmentCounter)) || BossConfigs.BreakableList.Any(b => MatchesEntityName(entityname, b.HealthSegmentCounter));
- if (!isSegmentCounter && !BossConfigs.MathCounterList.Any(b => MatchesEntityName(entityname, b.MathCounter)))
+ if (!BossConfigs.MathCounterList.Any(b => MatchesEntityName(entityname, b.MathCounter)))
{
var sanitizedName = SanitizeBossName(entityname);
if (!BossConfigs.MathCounterList.Any(b => b.MathCounter == sanitizedName))
{
var newBossConfig = new MathCounterConfig { Name = sanitizedName, MathCounter = sanitizedName, MathCounterMode = 1, Enabled = (counterValue > 10), HpOffset = 0 };
BossConfigs.MathCounterList.Add(newBossConfig);
+ if (newBossConfig.Enabled)
+ {
+ _autoSegmentLearner.TrackNewMain(newBossConfig.MathCounter, Server.CurrentTime);
+ }
SaveChanges();
- var newLiveBoss = new MathCounterBoss { BossName = newBossConfig.Name, Enabled = newBossConfig.Enabled, MathCounterHitMode = newBossConfig.MathCounterMode, MathCounterName = newBossConfig.MathCounter, HpOffset = newBossConfig.HpOffset };
- InitializeMainCounter(newLiveBoss, caller);
+ var newLiveBoss = CreateLiveMathCounterBoss(newBossConfig);
+ InitializeMainCounter(newLiveBoss, caller, entityname);
_mathCounterBosses.Add(newLiveBoss);
if (newLiveBoss.Enabled)
{
@@ -382,7 +561,9 @@ namespace EntBossHP
if (configLoaded)
{
- var isSegmentCounter = BossConfigs.MathCounterList.Any(b => MatchesEntityName(entityname, b.HealthSegmentCounter)) || BossConfigs.BreakableList.Any(b => MatchesEntityName(entityname, b.HealthSegmentCounter));
+ var isSegmentCounter =
+ BossConfigs.MathCounterList.Any(b => !string.IsNullOrWhiteSpace(b.HealthSegmentCounter) && MatchesEntityName(entityname, b.HealthSegmentCounter)) ||
+ BossConfigs.BreakableList.Any(b => !string.IsNullOrWhiteSpace(b.HealthSegmentCounter) && MatchesEntityName(entityname, b.HealthSegmentCounter));
if (!isSegmentCounter && !BossConfigs.BreakableList.Any(b => MatchesEntityName(entityname, b.Breakable)))
{
var sanitizedName = SanitizeBossName(entityname);
@@ -393,7 +574,7 @@ namespace EntBossHP
SaveChanges();
var newLiveBoss = new BreakableBoss { BossName = newBossConfig.Name, Enabled = newBossConfig.Enabled, BreakableEntityName = newBossConfig.Breakable, BreakableEntity = caller, HpOffset = newBossConfig.HpOffset };
newLiveBoss.Health = hp;
- newLiveBoss.MaxHealth = engineMaxHealth > 0 ? engineMaxHealth : hp;
+ UpdateBreakableMaxHealth(newLiveBoss, hp, engineMaxHealth);
_breakableBosses.Add(newLiveBoss);
if (newLiveBoss.Enabled)
{
@@ -405,16 +586,27 @@ namespace EntBossHP
foreach (var boss in _breakableBosses.Where(b => MatchesEntityName(entityname, b.BreakableEntityName)))
{
+ if (boss.Defeated) continue;
+
boss.BreakableEntity = caller;
- if (boss.IsSegmented && hp <= 0 && boss.HealthSegmentCounterEntity is { IsValid: true })
+ if (boss.IsSegmented && hp <= 0)
{
- AddTimer(0.1f, () => {
- if (boss.HealthSegmentCounterEntity is not { IsValid: true }) return;
- HandleSegmentEnd(boss, () => {
- boss.MaxHealth = 0;
- boss.Health = 0;
- });
- }, TimerFlags.STOP_ON_MAPCHANGE);
+ if (boss.HealthSegmentCounterEntity is { IsValid: true })
+ {
+ AddTimer(0.1f, () => {
+ if (boss.HealthSegmentCounterEntity is not { IsValid: true }) return;
+ HandleSegmentEnd(boss, () => {
+ boss.MaxHealth = 0;
+ boss.Health = 0;
+ });
+ }, TimerFlags.STOP_ON_MAPCHANGE);
+ }
+ else
+ {
+ boss.MaxHealth = 0;
+ boss.Health = 0;
+ boss.DefeatPending = false;
+ }
continue;
}
if (hp <= 0)
@@ -424,9 +616,7 @@ namespace EntBossHP
}
boss.DefeatPending = false;
boss.Health = hp;
- if (engineMaxHealth > 0) boss.MaxHealth = engineMaxHealth;
- else if (boss.MaxHealth <= 0) boss.MaxHealth = hp;
- if (hp > boss.MaxHealth) boss.MaxHealth = hp;
+ UpdateBreakableMaxHealth(boss, hp, engineMaxHealth);
if (boss.Enabled)
{
@@ -443,27 +633,49 @@ namespace EntBossHP
private void ProcessMathCounterBoss(MathCounterBoss boss, float counterValue, CCSPlayerController client)
{
- var currentHp = boss.MathCounterHitMode == 1 ? (int)counterValue : boss.MathCounterMaxValue - (int)counterValue;
- if (boss.IsSegmented && currentHp <= 0 && boss.HealthSegmentCounterEntity is { IsValid: true })
+ if (boss.Defeated) return;
+
+ var currentHp = ApplyMathCounterValue(boss, counterValue);
+ if (boss.IsSegmented && boss.HealthSegmentCounterEntity is { IsValid: true } && boss.HealthSegments <= 0)
{
- AddTimer(0.1f, () => {
- if (boss.HealthSegmentCounterEntity is not { IsValid: true }) return;
- HandleSegmentEnd(boss, () => {
- boss.MaxHealth = 0;
- boss.Health = 0;
- });
- }, TimerFlags.STOP_ON_MAPCHANGE);
+ NotifyBossDefeated(boss);
+ return;
+ }
+
+ if (boss.IsSegmented && currentHp <= 0)
+ {
+ if (boss.HealthSegmentCounterEntity is { IsValid: true })
+ {
+ AddTimer(0.1f, () => {
+ if (boss.HealthSegmentCounterEntity is not { IsValid: true }) return;
+ HandleSegmentEnd(boss, () => {
+ boss.MaxHealth = 0;
+ boss.Health = 0;
+ });
+ }, TimerFlags.STOP_ON_MAPCHANGE);
+ }
+ else
+ {
+ boss.MaxHealth = 0;
+ boss.Health = 0;
+ boss.DefeatPending = false;
+ }
return;
}
if (currentHp <= 0)
{
+ boss.MaxHealth = 0;
+ var mark = _autoSegmentLearner.MarkMainHitMin(boss.MathCounterName, Server.CurrentTime);
+ if (mark.Started)
+ {
+ ScheduleAutoSegmentLearningFinalization(mark.MainCounter, mark.AttemptId);
+ }
ScheduleDefeatConfirmation(boss);
return;
}
boss.DefeatPending = false;
- boss.Health = currentHp;
UpdateMaxHealth(boss, currentHp);
if (boss.Enabled)
@@ -472,21 +684,31 @@ namespace EntBossHP
}
}
- private void UpdateSegmentCounters(string entityName, int counterValue, CCSPlayerController client)
+ private void UpdateSegmentCounters(CEntityInstance entity, string entityName, int counterValue, CCSPlayerController client)
{
- foreach (var boss in _mathCounterBosses) UpdateSegmentCounter(boss, entityName, counterValue, client);
- foreach (var boss in _breakableBosses) UpdateSegmentCounter(boss, entityName, counterValue, client);
+ foreach (var boss in _mathCounterBosses) UpdateSegmentCounter(boss, entity, entityName, counterValue, client);
+ foreach (var boss in _breakableBosses) UpdateSegmentCounter(boss, entity, entityName, counterValue, client);
}
- private void UpdateSegmentCounter(SegmentedBossData boss, string entityName, int counterValue, CCSPlayerController client)
+ private void UpdateSegmentCounter(SegmentedBossData boss, CEntityInstance entity, string entityName, int counterValue, CCSPlayerController client)
{
+ if (boss.Defeated) return;
if (!boss.IsSegmented) return;
- if (boss.HealthSegmentCounterEntity is not { IsValid: true }) return;
if (!MatchesEntityName(entityName, boss.HealthSegmentCounterName)) return;
- boss.HealthSegments = boss.HealthSegmentCounterMode == 2
- ? Math.Max(0, boss.TotalHealthSegments - counterValue)
- : counterValue;
+ if (boss.HealthSegmentCounterEntity is not { IsValid: true })
+ {
+ InitializeSegmentCounter(boss, entity, entityName);
+ }
+
+ UpdateSegmentHealthFromCounter(boss, counterValue);
+ if (boss.HealthSegments <= 0)
+ {
+ boss.Health = 0;
+ boss.MaxHealth = 0;
+ NotifyBossDefeated(boss);
+ return;
+ }
if (boss.Enabled)
{
@@ -498,12 +720,6 @@ namespace EntBossHP
{
if (boss.HealthSegmentCounterEntity is not { IsValid: true } segmentCounterEntity) return;
- if (boss.HealthSegmentCounterMode == 2)
- {
- var destroyedSegments = (int)GetMathCounterValue(segmentCounterEntity.Handle);
- boss.HealthSegments = Math.Max(0, boss.TotalHealthSegments - destroyedSegments);
- }
- else boss.HealthSegments = (int)GetMathCounterValue(segmentCounterEntity.Handle);
if (boss.HealthSegments <= 0)
{
NotifyBossDefeated(boss);
@@ -518,29 +734,115 @@ namespace EntBossHP
if (boss.DefeatPending) return;
boss.DefeatPending = true;
- AddTimer(0.3f, () => {
+ AddTimer(MathCounterDefeatConfirmationDelay, () => {
if (!boss.DefeatPending) return;
boss.DefeatPending = false;
- if (boss is MathCounterBoss mathCounterBoss && mathCounterBoss.MathCounterEntity is { IsValid: true } entity)
- {
- var counterValue = GetMathCounterValue(entity.Handle);
- var currentHp = mathCounterBoss.MathCounterHitMode == 1
- ? (int)counterValue
- : mathCounterBoss.MathCounterMaxValue - (int)counterValue;
- if (currentHp > 0) return;
- }
+ if (boss is MathCounterBoss { Health: > 0 }) return;
NotifyBossDefeated(boss);
}, TimerFlags.STOP_ON_MAPCHANGE);
}
+ private void ScheduleAutoSegmentLearningFinalization(string mainCounter, int attemptId)
+ {
+ AddTimer(AutoSegmentLearningWindow, () => {
+ var decision = _autoSegmentLearner.Finalize(mainCounter, attemptId, Server.CurrentTime);
+ ApplyRuntimeAutoSegmentDecision(decision);
+ }, TimerFlags.STOP_ON_MAPCHANGE);
+ }
+
+ private void ApplyRuntimeAutoSegmentDecision(RuntimeAutoSegmentDecision decision)
+ {
+ if (decision.Status == RuntimeAutoSegmentDecisionStatus.None) return;
+
+ if (decision.Status == RuntimeAutoSegmentDecisionStatus.Ambiguous)
+ {
+ Logger.LogWarning(
+ "Skipped runtime auto segment learning for {MainCounter}: {Reason}",
+ decision.MainCounter,
+ decision.Reason);
+ return;
+ }
+
+ if (decision.Status != RuntimeAutoSegmentDecisionStatus.Learned
+ || string.IsNullOrWhiteSpace(decision.MainCounter)
+ || string.IsNullOrWhiteSpace(decision.SegmentCounter)
+ || decision.Mode is not (1 or 2))
+ {
+ return;
+ }
+
+ var config = BossConfigs.MathCounterList.FirstOrDefault(b => MatchesEntityName(decision.MainCounter, b.MathCounter));
+ if (config == null || !string.IsNullOrWhiteSpace(config.HealthSegmentCounter)) return;
+
+ config.HealthSegmentCounter = decision.SegmentCounter;
+ config.HealthSegmentCounterMode = decision.Mode;
+ SegmentCounterConfigHelper.EnsureDisabledMathCounterEntry(
+ BossConfigs,
+ decision.SegmentCounter,
+ NamesMatchEitherDirection);
+
+ var liveBoss = _mathCounterBosses.FirstOrDefault(b => MatchesEntityName(decision.MainCounter, b.MathCounterName));
+ if (liveBoss != null)
+ {
+ liveBoss.IsSegmented = true;
+ liveBoss.HealthSegmentCounterName = decision.SegmentCounter;
+ liveBoss.HealthSegmentCounterMode = decision.Mode;
+ liveBoss.HealthSegmentCounterHpOffset = SegmentCounterConfigHelper.GetSegmentCounterHpOffset(
+ BossConfigs,
+ decision.SegmentCounter,
+ NamesMatchEitherDirection);
+ TryInitializeLearnedSegmentCounter(liveBoss);
+
+ if (!liveBoss.Defeated)
+ {
+ if (liveBoss.HealthSegmentCounterEntity is { IsValid: true } && liveBoss.HealthSegments <= 0)
+ {
+ NotifyBossDefeated(liveBoss);
+ }
+ else if (liveBoss.HealthSegmentCounterEntity is { IsValid: true })
+ {
+ liveBoss.DefeatPending = false;
+ }
+ }
+ }
+
+ SaveChanges();
+ Logger.LogInformation(
+ "Runtime auto-filled health_segment_counter for newly detected {MainCounter}: {SegmentCounter} mode {Mode}",
+ decision.MainCounter,
+ decision.SegmentCounter,
+ decision.Mode);
+ }
+
+ private void TryInitializeLearnedSegmentCounter(MathCounterBoss boss)
+ {
+ try
+ {
+ foreach (var counter in Utilities.FindAllEntitiesByDesignerName<CMathCounter>("math_counter"))
+ {
+ if (counter is not { IsValid: true }) continue;
+
+ var entityName = GetEntityName(counter);
+ if (!MatchesEntityName(entityName, boss.HealthSegmentCounterName)) continue;
+
+ InitializeSegmentCounter(boss, counter, entityName);
+ return;
+ }
+ }
+ catch (Exception ex)
+ {
+ Logger.LogDebug(ex, "Failed to initialize learned segment counter for {Boss}", boss.BossName);
+ }
+ }
+
private void ScheduleDefeatConfirmationBreakable(BreakableBoss boss)
{
if (boss.DefeatPending) return;
boss.DefeatPending = true;
- AddTimer(0.3f, () => {
+ AddTimer(BreakableDefeatConfirmationDelay, () => {
if (!boss.DefeatPending) return;
boss.DefeatPending = false;
@@ -563,6 +865,22 @@ namespace EntBossHP
}, TimerFlags.STOP_ON_MAPCHANGE);
}
+ private static void UpdateBreakableMaxHealth(BreakableBoss boss, int hp, int engineMaxHealth)
+ {
+ if (boss.HpOffset < 0)
+ {
+ if (boss.MaxHealth <= 0 || hp > boss.MaxHealth)
+ {
+ boss.MaxHealth = hp;
+ }
+ return;
+ }
+
+ if (engineMaxHealth > 0) boss.MaxHealth = engineMaxHealth;
+ else if (boss.MaxHealth <= 0) boss.MaxHealth = hp;
+ if (hp > boss.MaxHealth) boss.MaxHealth = hp;
+ }
+
private static void UpdateMaxHealth(BossData boss, int currentHp)
{
if (boss.MaxHealth <= 0)
@@ -579,6 +897,15 @@ namespace EntBossHP
private void NotifyBossDefeated(BossData boss)
{
+ if (boss.Defeated) return;
+
+ boss.Defeated = true;
+ boss.DefeatPending = false;
+ boss.Health = 0;
+ boss.MaxHealth = 0;
+
+ if (!boss.Enabled) return;
+
foreach (var player in Utilities.GetPlayers())
{
if (player == null || !player.IsValid) continue;
@@ -594,6 +921,8 @@ namespace EntBossHP
private void UpdateAndDisplayBoss(BossData boss, CCSPlayerController client)
{
+ if (boss.Defeated) return;
+
if (boss.Enabled && IsBossHudEnabled(client))
{
HitEventDisplay.ShowHitEvent(client, boss, boss.Health);
@@ -627,6 +956,19 @@ namespace EntBossHP
}
}
+ private static float? TryGetMathCounterMax(CEntityInstance entity)
+ {
+ try
+ {
+ var counter = new CMathCounter(entity.Handle);
+ return counter.IsValid ? counter.Max : null;
+ }
+ catch
+ {
+ return null;
+ }
+ }
+
private bool MatchesEntityName(string entityName, string configuredName)
{
if (string.IsNullOrWhiteSpace(entityName) || string.IsNullOrWhiteSpace(configuredName)) return false;
@@ -634,19 +976,56 @@ namespace EntBossHP
return SanitizeBossName(entityName).Equals(configuredName, StringComparison.Ordinal);
}
- private unsafe float GetMathCounterValue(nint handle)
+ private bool NamesMatchEitherDirection(string firstName, string secondName)
{
- if (handle == IntPtr.Zero) return 0;
- try
- {
- var offset = Schema.GetSchemaOffset("CMathCounter", "m_OutValue");
- return *(float*)IntPtr.Add(handle, offset + 24);
- }
- catch (Exception ex)
+ return MatchesEntityName(firstName, secondName) || MatchesEntityName(secondName, firstName);
+ }
+
+ private bool IsConfiguredSegmentCounter(string entityName)
+ {
+ return BossConfigs.MathCounterList.Any(b => !string.IsNullOrWhiteSpace(b.HealthSegmentCounter) && MatchesEntityName(entityName, b.HealthSegmentCounter)) ||
+ BossConfigs.BreakableList.Any(b => !string.IsNullOrWhiteSpace(b.HealthSegmentCounter) && MatchesEntityName(entityName, b.HealthSegmentCounter));
+ }
+
+ private void RememberMathCounterValue(string entityName, float value)
+ {
+ if (string.IsNullOrWhiteSpace(entityName)) return;
+ _mathCounterValuesByName[entityName] = value;
+ _mathCounterValuesByName[SanitizeBossName(entityName)] = value;
+ }
+
+ private bool TryGetRememberedMathCounterValue(string entityName, out float value)
+ {
+ if (_mathCounterValuesByName.TryGetValue(entityName, out value)) return true;
+
+ var sanitizedName = SanitizeBossName(entityName);
+ if (!sanitizedName.Equals(entityName, StringComparison.Ordinal)
+ && _mathCounterValuesByName.TryGetValue(sanitizedName, out value))
{
- Logger.LogDebug(ex, "Failed to read math_counter value");
- return 0;
+ return true;
}
+
+ value = 0;
+ return false;
+ }
+
+ private static int ApplyMathCounterValue(MathCounterBoss boss, float counterValue)
+ {
+ var currentHp = boss.MathCounterHitMode == 1
+ ? (int)counterValue
+ : boss.MathCounterMaxValue - (int)counterValue;
+
+ boss.Health = Math.Max(0, currentHp);
+ return currentHp;
+ }
+
+ private static void UpdateSegmentHealthFromCounter(SegmentedBossData boss, int counterValue)
+ {
+ var rawHealthSegments = boss.HealthSegmentCounterMode == 2
+ ? Math.Max(0, boss.TotalHealthSegments - counterValue)
+ : counterValue;
+
+ boss.HealthSegments = Math.Max(0, rawHealthSegments + boss.HealthSegmentCounterHpOffset);
}
private void SaveChanges()
@@ -654,15 +1033,25 @@ namespace EntBossHP
string configPath;
string? configDirectory;
string json;
+ long saveGeneration;
try
{
configPath = Path.Combine(PluginConfigDirectory, $"{Server.MapName}.jsonc");
configDirectory = Path.GetDirectoryName(configPath);
+
+#pragma warning disable CS0618
+ if (BossConfigs.HPBarList is { Count: 0 })
+ {
+ BossConfigs.HPBarList = null;
+ }
+#pragma warning restore CS0618
+
json = JsonSerializer.Serialize(BossConfigs, new JsonSerializerOptions
{
WriteIndented = true
});
+ saveGeneration = System.Threading.Interlocked.Increment(ref SaveGeneration);
}
catch (Exception ex)
{
@@ -675,6 +1064,12 @@ namespace EntBossHP
await SaveLock.WaitAsync();
try
{
+ if (saveGeneration != System.Threading.Volatile.Read(ref SaveGeneration))
+ {
+ Logger.LogDebug("Skipped stale boss config save for {ConfigPath}", configPath);
+ return;
+ }
+
if (configDirectory != null && !Directory.Exists(configDirectory)) Directory.CreateDirectory(configDirectory);
await File.WriteAllTextAsync(configPath, json);
Logger.LogInformation($"Saved updated boss config to {configPath}");
diff --git a/EntBossHP.csproj b/EntBossHP.csproj
index f5993e5..2faaa40 100644
--- a/EntBossHP.csproj
+++ b/EntBossHP.csproj
@@ -7,7 +7,7 @@
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
- <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
+ <CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies>
<GenerateDependencyFile>true</GenerateDependencyFile>
<ReferenceLibraryRoot Condition="'$(ReferenceLibraryRoot)' == '' And Exists('D:/AMPDatastore/Instances/cssharp01/counter-strike2/730/game/csgo/addons/counterstrikesharp/shared')">D:/AMPDatastore/Instances/cssharp01/counter-strike2/730/game/csgo/addons/counterstrikesharp/shared</ReferenceLibraryRoot>
@@ -40,6 +40,7 @@
<ItemGroup>
<None Remove="bin\**" />
<None Remove="obj\**" />
+ <None Remove="tests\**" />
<None Remove=".github\**" />
<None Remove="build\**" />
<None Remove="**\*.pdb" />
@@ -50,7 +51,9 @@
<ItemGroup>
<Compile Remove="vendor/**" />
+ <Compile Remove="tests/**" />
<EmbeddedResource Remove="vendor/**" />
+ <EmbeddedResource Remove="tests/**" />
<None Remove="vendor/**" />
</ItemGroup>
</Project>