forked from dvize/Donuts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DonutComponent.cs
553 lines (462 loc) · 19.1 KB
/
DonutComponent.cs
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
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using SPT.Reflection.Utils;
using BepInEx.Logging;
using Comfort.Common;
using Cysharp.Threading.Tasks;
using Donuts.Models;
using EFT;
using HarmonyLib;
using Systems.Effects;
using UnityEngine;
using static Donuts.DefaultPluginVars;
#pragma warning disable IDE0007, IDE0044
namespace Donuts
{
public class DonutComponent : MonoBehaviour
{
internal static FightLocations fightLocations;
internal static FightLocations sessionLocations;
internal static List<List<Entry>> groupedFightLocations;
internal static Dictionary<int, List<HotspotTimer>> groupedHotspotTimers;
internal List<WildSpawnType> validDespawnListPMC = new List<WildSpawnType>()
{
WildSpawnType.pmcUSEC,
WildSpawnType.pmcBEAR
};
internal List<WildSpawnType> validDespawnListScav = new List<WildSpawnType>()
{
WildSpawnType.assault,
WildSpawnType.cursedAssault
};
internal static bool fileLoaded = false;
internal static Gizmos gizmos;
internal static string maplocation;
internal static int PMCBotLimit = 0;
internal static int SCAVBotLimit = 0;
internal static int currentInitialPMCs = 0;
internal static int currentInitialSCAVs = 0;
internal static GameWorld gameWorld;
internal static BotSpawner botSpawnerClass;
internal static IBotCreator botCreator;
internal static List<Player> playerList = new List<Player>();
internal float PMCdespawnCooldown = 0f;
internal float PMCdespawnCooldownDuration = despawnInterval.Value;
internal float SCAVdespawnCooldown = 0f;
internal float SCAVdespawnCooldownDuration = despawnInterval.Value;
internal static List<HotspotTimer> hotspotTimers;
internal static Dictionary<string, MethodInfo> methodCache;
internal static MethodInfo displayMessageNotificationMethod;
internal static WildSpawnType sptUsec;
internal static WildSpawnType sptBear;
internal static bool isInBattle;
internal static float timeSinceLastHit = 0;
internal static Player mainplayer;
internal static ManualLogSource Logger
{
get; private set;
}
public DonutComponent()
{
Logger ??= BepInEx.Logging.Logger.CreateLogSource(nameof(DonutComponent));
}
internal static void Enable()
{
if (Singleton<IBotGame>.Instantiated)
{
gameWorld = Singleton<GameWorld>.Instance;
gameWorld.GetOrAddComponent<DonutComponent>();
Logger.LogDebug("Donuts Enabled");
}
}
private void Awake()
{
botSpawnerClass = Singleton<IBotGame>.Instance.BotsController.BotSpawner;
botCreator = AccessTools.Field(botSpawnerClass.GetType(), "_botCreator").GetValue(botSpawnerClass) as IBotCreator;
methodCache = new Dictionary<string, MethodInfo>();
gizmos = new Gizmos(this);
var displayMessageNotification = PatchConstants.EftTypes.Single(x => x.GetMethod("DisplayMessageNotification") != null).GetMethod("DisplayMessageNotification");
if (displayMessageNotification != null)
{
methodCache["DisplayMessageNotification"] = displayMessageNotification;
}
var methodInfo = typeof(BotSpawner).GetMethod("method_9", BindingFlags.Instance | BindingFlags.NonPublic);
if (methodInfo != null)
{
methodCache[methodInfo.Name] = methodInfo;
}
methodInfo = AccessTools.Method(typeof(BotSpawner), "method_10");
if (methodInfo != null)
{
methodCache[methodInfo.Name] = methodInfo;
}
if (gameWorld.RegisteredPlayers.Count > 0)
{
foreach (var player in gameWorld.AllPlayersEverExisted)
{
if (!player.IsAI)
{
playerList.Add(player);
}
}
}
botSpawnerClass.OnBotRemoved += removedBot =>
{
foreach (var player in playerList)
{
removedBot.Memory.DeleteInfoAboutEnemy(player);
}
removedBot.EnemiesController.EnemyInfos.Clear();
foreach (var player in gameWorld.AllAlivePlayersList)
{
if (!player.IsAI)
{
continue;
}
var botOwner = player.AIData.BotOwner;
botOwner.Memory.DeleteInfoAboutEnemy(removedBot);
botOwner.BotsGroup.RemoveInfo(removedBot);
botOwner.BotsGroup.RemoveEnemy(removedBot, EBotEnemyCause.death);
botOwner.BotsGroup.RemoveAlly(removedBot);
}
};
}
private Stopwatch spawnCheckTimer = new Stopwatch();
private const int SpawnCheckInterval = 1000;
private void Start()
{
Initialization.InitializeStaticVariables();
maplocation = gameWorld.MainPlayer.Location.ToLower();
mainplayer = gameWorld.MainPlayer;
isInBattle = false;
Logger.LogDebug("Setup maplocation: " + maplocation);
Initialization.LoadFightLocations();
if (PluginEnabled.Value && fileLoaded)
{
Initialization.InitializeHotspotTimers();
}
Logger.LogDebug("Setup PMC Bot limit: " + PMCBotLimit);
Logger.LogDebug("Setup SCAV Bot limit: " + SCAVBotLimit);
spawnCheckTimer.Start();
mainplayer.BeingHitAction += BeingHitBattleCoolDown;
}
private void BeingHitBattleCoolDown(DamageInfo info, EBodyPart part, float arg3)
{
switch (info.DamageType)
{
case EDamageType.Btr:
case EDamageType.Melee:
case EDamageType.Bullet:
case EDamageType.Explosion:
case EDamageType.GrenadeFragment:
case EDamageType.Sniper:
isInBattle = true;
timeSinceLastHit = 0;
break;
default:
break;
}
}
private void Update()
{
if (!PluginEnabled.Value || !fileLoaded)
return;
timeSinceLastHit += Time.deltaTime;
foreach (var hotspotTimer in hotspotTimers)
{
hotspotTimer.UpdateTimer();
}
if (spawnCheckTimer.ElapsedMilliseconds >= SpawnCheckInterval)
{
spawnCheckTimer.Restart();
StartSpawnProcess().Forget();
}
Gizmos.DisplayMarkerInformation();
}
private async UniTask StartSpawnProcess()
{
if (DespawnEnabledPMC.Value)
{
await DespawnFurthestBot("pmc");
}
if (DespawnEnabledSCAV.Value)
{
await DespawnFurthestBot("scav");
}
if (groupedHotspotTimers.Count > 0)
{
foreach (var groupHotspotTimers in groupedHotspotTimers.Values)
{
if (groupHotspotTimers.Count == 0)
{
continue;
}
bool spawnTriggered = false;
var randomIndex = UnityEngine.Random.Range(0, groupHotspotTimers.Count);
for (int i = 0; i < groupHotspotTimers.Count; i++)
{
var index = (randomIndex + i) % groupHotspotTimers.Count;
var hotspotTimer = groupHotspotTimers[index];
if (hotspotTimer.ShouldSpawn())
{
Vector3 coordinate = new Vector3(hotspotTimer.Hotspot.Position.x, hotspotTimer.Hotspot.Position.y, hotspotTimer.Hotspot.Position.z);
if (isInBattle)
{
if (timeSinceLastHit < battleStateCoolDown.Value)
{
break;
}
else
{
isInBattle = false;
}
}
if (CanSpawn(hotspotTimer, coordinate))
{
await TriggerSpawn(hotspotTimer, coordinate);
spawnTriggered = true;
break;
}
}
}
if (spawnTriggered)
{
ResetGroupTimers(groupHotspotTimers[0].Hotspot.GroupNum);
}
}
}
}
private bool CanSpawn(HotspotTimer hotspotTimer, Vector3 coordinate)
{
if (BotSpawn.IsWithinBotActivationDistance(hotspotTimer.Hotspot, coordinate) && maplocation == hotspotTimer.Hotspot.MapName)
{
if ((hotspotTimer.Hotspot.WildSpawnType == "pmc" && hotspotBoostPMC.Value) ||
(hotspotTimer.Hotspot.WildSpawnType == "scav" && hotspotBoostSCAV.Value))
{
hotspotTimer.Hotspot.SpawnChance = 100;
}
return UnityEngine.Random.Range(0, 100) < hotspotTimer.Hotspot.SpawnChance;
}
return false;
}
private async UniTask TriggerSpawn(HotspotTimer hotspotTimer, Vector3 coordinate)
{
if (forceAllBotType.Value != "Disabled")
{
hotspotTimer.Hotspot.WildSpawnType = forceAllBotType.Value.ToLower();
}
var tasks = new List<UniTask<bool>>();
if (HardCapEnabled.Value)
{
tasks.Add(CheckHardCap(hotspotTimer.Hotspot.WildSpawnType));
}
tasks.Add(CheckRaidTime(hotspotTimer.Hotspot.WildSpawnType));
bool[] results = await UniTask.WhenAll(tasks);
if (results.Any(result => !result))
{
return;
}
await BotSpawn.SpawnBots(hotspotTimer, coordinate);
hotspotTimer.timesSpawned++;
if (hotspotTimer.timesSpawned >= hotspotTimer.Hotspot.MaxSpawnsBeforeCoolDown)
{
hotspotTimer.inCooldown = true;
}
ResetGroupTimers(hotspotTimer.Hotspot.GroupNum);
}
private async UniTask<bool> CheckHardCap(string wildSpawnType)
{
int activePMCs = await BotCountManager.GetAlivePlayers("pmc");
int activeSCAVs = await BotCountManager.GetAlivePlayers("scav");
if (wildSpawnType == "pmc" && activePMCs >= PMCBotLimit && !hotspotIgnoreHardCapPMC.Value)
{
Logger.LogDebug($"PMC spawn not allowed due to PMC bot limit - skipping this spawn. Active PMCs: {activePMCs}, PMC Bot Limit: {PMCBotLimit}");
return false;
}
if (wildSpawnType == "scav" && activeSCAVs >= SCAVBotLimit && !hotspotIgnoreHardCapSCAV.Value)
{
Logger.LogDebug($"SCAV spawn not allowed due to SCAV bot limit - skipping this spawn. Active SCAVs: {activeSCAVs}, SCAV Bot Limit: {SCAVBotLimit}");
return false;
}
return true;
}
private async UniTask<bool> CheckRaidTime(string wildSpawnType)
{
if (wildSpawnType == "pmc" && hardStopOptionPMC.Value && !IsRaidTimeRemaining("pmc"))
{
#if DEBUG
Logger.LogDebug("PMC spawn not allowed due to raid time conditions - skipping this spawn");
#endif
return false;
}
if (wildSpawnType == "scav" && hardStopOptionSCAV.Value && !IsRaidTimeRemaining("scav"))
{
#if DEBUG
Logger.LogDebug("SCAV spawn not allowed due to raid time conditions - skipping this spawn");
#endif
return false;
}
return true;
}
private bool IsRaidTimeRemaining(string spawnType)
{
int hardStopTime;
int hardStopPercent;
if (spawnType == "pmc")
{
hardStopTime = hardStopTimePMC.Value;
hardStopPercent = hardStopPercentPMC.Value;
}
else
{
hardStopTime = hardStopTimeSCAV.Value;
hardStopPercent = hardStopPercentSCAV.Value;
}
int raidTimeLeftTime = (int)SPT.SinglePlayer.Utils.InRaid.RaidTimeUtil.GetRemainingRaidSeconds(); // Time left
int raidTimeLeftPercent = (int)(SPT.SinglePlayer.Utils.InRaid.RaidTimeUtil.GetRaidTimeRemainingFraction() * 100f); // Percent left
//why is this method failing?
Logger.LogWarning("RaidTimeLeftTime: " + raidTimeLeftTime + " RaidTimeLeftPercent: " + raidTimeLeftPercent + " HardStopTime: " + hardStopTime + " HardStopPercent: " + hardStopPercent);
return useTimeBasedHardStop.Value ? raidTimeLeftTime >= hardStopTime : raidTimeLeftPercent >= hardStopPercent;
}
private void ResetGroupTimers(int groupNum)
{
foreach (var timer in groupedHotspotTimers[groupNum])
{
timer.ResetTimer();
if (timer.Hotspot.IgnoreTimerFirstSpawn)
timer.Hotspot.IgnoreTimerFirstSpawn = false;
}
}
private UniTask<Player> UpdateDistancesAndFindFurthestBot()
{
return UniTask.Create(async () =>
{
float maxDistance = float.MinValue;
Player furthestBot = null;
foreach (var bot in gameWorld.AllAlivePlayersList)
{
// Get distance of bot to player using squared distance
float distance = (mainplayer.Transform.position - bot.Transform.position).sqrMagnitude;
// Check if this is the furthest distance
if (distance > maxDistance)
{
maxDistance = distance;
furthestBot = bot;
}
}
if (furthestBot == null)
{
Logger.LogWarning("Furthest bot is null. No bots found in the list.");
}
else
{
Logger.LogDebug($"Furthest bot found: {furthestBot.Profile.Info.Nickname} at distance {Mathf.Sqrt(maxDistance)}");
}
return furthestBot;
});
}
private async UniTask DespawnFurthestBot(string bottype)
{
if (bottype != "pmc" && bottype != "scav")
return;
float despawnCooldown = bottype == "pmc" ? PMCdespawnCooldown : SCAVdespawnCooldown;
float despawnCooldownDuration = bottype == "pmc" ? PMCdespawnCooldownDuration : SCAVdespawnCooldownDuration;
if (Time.time - despawnCooldown < despawnCooldownDuration)
{
return;
}
if (!await ShouldConsiderDespawning(bottype))
{
return;
}
Player furthestBot = await UpdateDistancesAndFindFurthestBot();
if (furthestBot != null)
{
DespawnBot(furthestBot, bottype);
}
else
{
Logger.LogWarning("No bot found to despawn.");
}
}
private void DespawnBot(Player furthestBot, string bottype)
{
if (furthestBot == null)
{
Logger.LogError("Attempted to despawn a null bot.");
return;
}
BotOwner botOwner = furthestBot.AIData.BotOwner;
if (botOwner == null)
{
Logger.LogError("BotOwner is null for the furthest bot.");
return;
}
#if DEBUG
Logger.LogDebug($"Despawning bot: {furthestBot.Profile.Info.Nickname} ({furthestBot.name})");
#endif
gameWorld.RegisteredPlayers.Remove(botOwner);
gameWorld.AllAlivePlayersList.Remove(botOwner.GetPlayer);
var botgame = Singleton<IBotGame>.Instance;
Singleton<Effects>.Instance.EffectsCommutator.StopBleedingForPlayer(botOwner.GetPlayer);
botOwner.Deactivate();
botOwner.Dispose();
botgame.BotsController.BotDied(botOwner);
botgame.BotsController.DestroyInfo(botOwner.GetPlayer);
DestroyImmediate(botOwner.gameObject);
Destroy(botOwner);
// Update the cooldown
if (bottype == "pmc")
{
PMCdespawnCooldown = Time.time;
}
else if (bottype == "scav")
{
SCAVdespawnCooldown = Time.time;
}
}
private async UniTask<bool> ShouldConsiderDespawning(string botType)
{
int botLimit = botType == "pmc" ? PMCBotLimit : SCAVBotLimit;
int activeBotCount = await BotCountManager.GetAlivePlayers(botType);
return activeBotCount > botLimit; // Only consider despawning if the number of active bots of the type exceeds the limit
}
private void OnGUI()
{
gizmos.ToggleGizmoDisplay(DebugGizmos.Value);
}
private void OnDestroy()
{
botSpawnerClass.OnBotRemoved -= removedBot =>
{
foreach (var player in playerList)
{
removedBot.Memory.DeleteInfoAboutEnemy(player);
}
removedBot.EnemiesController.EnemyInfos.Clear();
foreach (var player in gameWorld.AllAlivePlayersList)
{
if (!player.IsAI)
{
continue;
}
var botOwner = player.AIData.BotOwner;
botOwner.Memory.DeleteInfoAboutEnemy(removedBot);
botOwner.BotsGroup.RemoveInfo(removedBot);
botOwner.BotsGroup.RemoveEnemy(removedBot, EBotEnemyCause.death);
botOwner.BotsGroup.RemoveAlly(removedBot);
}
};
mainplayer.BeingHitAction -= BeingHitBattleCoolDown;
StopAllCoroutines();
isInBattle = false;
groupedFightLocations = null;
groupedHotspotTimers = null;
hotspotTimers = null;
methodCache = null;
Logger.LogWarning("Donuts Component cleaned up and disabled.");
}
}
}