-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSuperPVxInfo.cs
More file actions
2071 lines (1773 loc) · 65.7 KB
/
SuperPVxInfo.cs
File metadata and controls
2071 lines (1773 loc) · 65.7 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 Facepunch;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Oxide.Core;
using Oxide.Core.Libraries.Covalence;
using Oxide.Core.Plugins;
using Oxide.Game.Rust.Cui;
using System;
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
namespace Oxide.Plugins;
[Info("Super PVx Info", "HunterZ", "1.9.0")]
[Description("Displays PvE/PvP/etc. status on player's HUD")]
public class SuperPVxInfo : RustPlugin
{
#region Plugin Data
// list of plugins whose PVP delay statuses are tracked
public enum PvpDelayType
{
AbandonedBases,
DynamicPvp,
PlayerBasePvpZones,
RaidableBases,
TruePve
}
// primary status types tracked by this plugin
public enum PVxType { PVE, PVP, PVPDelay, SafeZone }
// PVP statuses that are managed via listening to player enter/exit hooks
[Flags]
public enum PvpBubbleTypes
{
None = 0,
// Nikedemos plugins
CargoTrainEvent = 1 << 0,
// Adem plugins
Caravan = 1 << 1,
Convoy = 1 << 2,
Sputnik = 1 << 3
}
// PVP events that are managed via listening to start/stop hooks that provide
// a PVP area definition
private enum PvpLocationEventType
{
// KpucTaJl plugins
AirEvent,
ArcticBaseEvent,
FerryTerminalEvent,
GasStationEvent,
HarborEvent,
JunkyardEvent,
PowerPlantEvent,
SatelliteDishEvent,
SupermarketEvent,
WaterEvent
}
[PluginReference] Plugin
AbandonedBases, DynamicPVP, DangerousTreasures, PlayerBasePvpZones,
PopupNotifications, RaidableBases, SimpleStatus, TruePVE, ZoneManager;
private ConfigData _configData;
// active TruePVE PVP delay timers by plugin name by player ID
private readonly Dictionary<ulong, Dictionary<string, Timer>>
_excludedPlayers = new();
// NOTE: this is not to be used directly for sending messages, but rather for
// populating the default language dictionary, and for enumerating which
// messages exist
private readonly Dictionary<string, string> _notifyMessages = new()
{
["Unexpected Exit From Abandoned Or Raidable Base"] =
"{0}Left Abandoned/Raidable Base Zone",
["Unexpected Exit From Dangerous Treasures Event"] =
"{0}Left Dangerous Treasures Zone",
["Safe Zone Entry"] =
"{0}Entering Safe Zone",
["Safe Zone Exit"] =
"{0}Leaving Safe Zone",
["PVP Height Entry"] =
"{0}WARNING: Entering Sky/Portal PVP Zone",
["PVP Height Exit"] =
"{0}Leaving Sky/Portal PVP Zone",
["PVP Depth Entry"] =
"{0}WARNING: Entering Train Tunnels PVP Zone",
["PVP Depth Exit"] =
"{0}Leaving Train Tunnels PVP Zone",
["PVP Deep Sea Entry"] =
"{0}WARNING: Entering Deep Sea PVP Zone",
["PVP Deep Sea Exit"] =
"{0}Leaving Deep Sea PVP Zone"
};
private Timer _saveDataTimer;
private StoredData _storedData;
private const string UIName = "SuperPVxInfoUI";
#endregion Plugin Data
#region Utility Methods
private static bool IsValidPlayer(BasePlayer player, bool checkConnected) =>
player &&
!player.IsNpc &&
player.userID.IsSteamId() &&
(!checkConnected || player.IsConnected);
private static PlayerWatcher GetPlayerWatcher(BasePlayer player) =>
IsValidPlayer(player, true) ? player.GetComponent<PlayerWatcher>() : null;
private void SendCannedMessage(BasePlayer player, string key)
{
if (null == _configData ||
!_configData.NotifySettings.Enabled.TryGetValue(
key, out var enabled) ||
!enabled)
{
return;
}
var message = lang.GetMessage(key, this, player.UserIDString);
if (null == message) return;
if (_configData.NotifySettings.ChatEnabled)
{
SendReply(
player, string.Format(message, _configData.NotifySettings.ChatPrefix));
}
if (_configData.NotifySettings.PopupNotificationsEnabled &&
null != PopupNotifications)
{
PopupNotifications.Call(
"CreatePopupNotification",
string.Format(
message, _configData.NotifySettings.PopupNotificationsPrefix),
player);
}
}
private void ExcludePlayerRemove(ulong userid, string pluginName)
{
// get timers-by-plugin for player
if (!_excludedPlayers.TryGetValue(userid, out var excludeTimers) ||
null == excludeTimers)
{
return;
}
// remove timer entry if present, and destroy it if needed
if (excludeTimers.Remove(pluginName, out var removedTimer))
{
DestroyTimer(removedTimer);
}
// abort if timers-by-plugin is still not empty for this player
if (excludeTimers.Count > 0) return;
// timers-by-plugin is empty - remove PVP delay status
var player = BasePlayer.FindByID(userid);
if (player)
{
SetPvpDelay(player, PvpDelayType.TruePve, false);
}
}
private static void DestroyTimer(Timer t)
{
if (TimerValid(t)) t.Destroy();
}
private static bool TimerValid(Timer t) => false == t?.Destroyed;
#endregion Utility Methods
#region Oxide Methods
protected override void LoadDefaultMessages() =>
lang.RegisterMessages(_notifyMessages, this);
private void Init()
{
LoadData();
PlayerWatcher.AllowForceUpdate =
null == _configData || _configData.ForceUpdates;
PlayerWatcher.Instance = this;
var deepSeaBounds = DeepSeaManager.DeepSeaBounds;
PlayerWatcher.DeepSeaMin = deepSeaBounds.center - deepSeaBounds.extents;
PlayerWatcher.DeepSeaMax = deepSeaBounds.center + deepSeaBounds.extents;
PlayerWatcher.UpdateIntervalSeconds =
_configData?.UpdateIntervalSeconds ?? 1.0f;
if (null != _configData && !string.IsNullOrEmpty(_configData.ToggleCommand))
{
AddCovalenceCommand(_configData.ToggleCommand, nameof(ToggleUI));
}
}
private void OnServerInitialized(bool isStartup)
{
if (Convert.ToBoolean(DynamicPVP?.Call("IsUsingExcludePlayer")))
{
Puts("OnServerInitialized(): Detected DynamicPVP support for TruePVE PVP delays");
Unsubscribe(nameof(OnPlayerAddedToPVPDelay));
Unsubscribe(nameof(OnPlayerRemovedFromPVPDelay));
}
if (Convert.ToBoolean(PlayerBasePvpZones?.Call("IsUsingExcludePlayer")))
{
Puts("OnServerInitialized(): Detected PlayerBasePvpZones support for TruePVE PVP delays");
Unsubscribe(nameof(OnPlayerBasePvpDelayStart));
Unsubscribe(nameof(OnPlayerBasePvpDelayStop));
}
if (null == ZoneManager ||
ZoneManager.Version < new VersionNumber(3, 1, 10))
{
PrintWarning("ZoneManager is outdated or not running; this plugin may not work properly");
}
if (true == _configData?.SyncAssumptions && true == TruePVE?.IsLoaded)
{
Puts("Querying TruePVE for assumptions...");
if (TruePVE?.Call("GetAboveworld") is float pvpAboveHeight)
{
_configData.PvpAboveHeight = pvpAboveHeight;
Puts($" - PVP above height: {pvpAboveHeight}");
}
if (TruePVE?.Call("GetUnderworld") is float pvpBelowHeight)
{
_configData.PvpBelowHeight = pvpBelowHeight;
Puts($" - PVP below height: {pvpBelowHeight}");
}
if (TruePVE?.Call("GetDeepSea") is bool pvpDeepSea)
{
_configData.PvpDeepSea = pvpDeepSea;
Puts($" - PVP deep sea: {pvpDeepSea}");
}
Puts("...Done");
}
PlayerWatcher.PvpAboveHeight = _configData?.PvpAboveHeight ?? 1000.0f;
PlayerWatcher.PvpBelowHeight = _configData?.PvpBelowHeight ?? -500.0f;
PlayerWatcher.PvpDeepSea = _configData?.PvpDeepSea ?? false;
var saveData = false;
if (null != _storedData)
{
// sync with TruePVE mappings in case of reload
TP_GetMappingsToStoredData();
Puts($"OnServerInitialized(): mappings count after TruePVE sync: {_storedData.Mappings.Count}");
// purge any mappings that Zone Manager doesn't recognize
var activeZoneIds = Pool.Get<List<string>>();
ZM_GetZoneIDsNoAlloc(activeZoneIds);
Puts($"OnServerInitialized(): ZoneManager active zone count: {activeZoneIds.Count}");
var deadZoneIds = Pool.Get<List<string>>();
foreach (var zoneId in _storedData.Mappings.Keys)
{
if ("default" == zoneId || activeZoneIds.Contains(zoneId)) continue;
deadZoneIds.Add(zoneId);
}
Pool.FreeUnmanaged(ref activeZoneIds);
foreach (var deadZoneId in deadZoneIds)
{
_storedData.Mappings.Remove(deadZoneId);
}
if (deadZoneIds.Count > 0)
{
PrintWarning($"OnServerInitialized(): Purged {deadZoneIds.Count} unknown/obsolete zoneId(s) from database");
saveData = true;
}
Pool.FreeUnmanaged(ref deadZoneIds);
// migrate or clear old PVP events
var oldEventsCount = _storedData.PendingPvpEvents.Count;
if (oldEventsCount > 0)
{
if (isStartup)
{
// don't use events from a previous server run
PrintWarning($"OnServerInitialized(): Purging {oldEventsCount} obsolete PVP event record(s)");
saveData = true;
}
else
{
// migrate events that haven't already been re-added by another
// plugin's OnServerInitialized()
var migratedCount = 0;
foreach (var (eventType, eventData) in _storedData.PendingPvpEvents)
{
if (!_storedData.PvpEvents.TryAdd(eventType, eventData)) continue;
++migratedCount;
}
Puts($"OnServerInitialized(): Migrated {migratedCount}/{oldEventsCount} saved PVP event record(s)");
// schedule a save if we didn't just retain everything
saveData |= migratedCount != _storedData.PendingPvpEvents.Count ||
migratedCount != _storedData.PvpEvents.Count;
}
// purge pending list regardless, as we're done with it
_storedData.PendingPvpEvents.Clear();
}
}
if (saveData)
{
SaveData();
}
// setup SimpleStatus integration if appropriate
SS_CreateStatuses();
foreach (var player in BasePlayer.activePlayerList)
{
OnPlayerConnected(player);
}
if (true ==_configData?.NotifySettings.PopupNotificationsEnabled &&
null == PopupNotifications)
{
PrintWarning("Notify via PopupNotifications enabled, but required plugin is missing");
}
}
private void Unload()
{
// clear out any active TruePVE PVP delay timers
foreach (var excludeTimers in _excludedPlayers.Values)
{
foreach (var excludeTimer in excludeTimers.Values)
{
DestroyTimer(excludeTimer);
}
excludeTimers.Clear();
}
_excludedPlayers.Clear();
// destroy GUIs for all active players
foreach (var player in BasePlayer.activePlayerList)
{
OnPlayerDisconnected(player, UIName);
}
PlayerWatcher.Instance = null;
// if save timer active, force immediate write
if (TimerValid(_saveDataTimer))
{
WriteData();
}
_saveDataTimer = null;
}
private void OnPlayerConnected(BasePlayer player)
{
if (!IsValidPlayer(player, true)) return;
// abort if an active watcher is already attached
// isActiveAndEnabled is needed because sometimes reloading the plugin
// causes it to catch a watcher that is still in the process of being
// destroyed
var watcher = player.GetComponent<PlayerWatcher>();
if (watcher && watcher.isActiveAndEnabled) return;
watcher = player.gameObject.AddComponent<PlayerWatcher>();
watcher.Init(
IsPlayerInBase(player), IsPlayerInPVPDelay(player.userID.Get()),
GetPlayerZoneType(player), player);
watcher.StartWatching();
}
private void OnPlayerDisconnected(BasePlayer player, string reason)
{
if (IsValidPlayer(player, false))
{
player.gameObject.GetComponent<PlayerWatcher>()?.OnDestroy();
}
DestroyUI(player);
}
private void OnPlayerRespawned(BasePlayer player) =>
NextTick(() =>
{
if (!IsValidPlayer(player, true)) return;
var watcher = GetPlayerWatcher(player);
if (!watcher) return;
// check everything because the player could be anywhere now
if (watcher.InBaseType != null) watcher.SetCheckBase(true);
watcher.SetCheckPVxEvent(true);
watcher.SetCheckZone(true);
watcher.SetCheckPvpDelay(true);
watcher.Force();
});
#endregion Oxide Methods
#region TruePVE Integration
#region TruePVE Utilities
// use Interface.CallHook() instead of explicitly calling TruePVE, in case
// other PVE plugins implement support for this
private void TP_GetMappingsToStoredData() =>
Interface.CallHook("GetMappingsDictionaryNoAlloc", _storedData.Mappings);
#endregion TruePVE Utilities
#region TruePVE Hook Handlers
// called when a plugin maps a Zone Manager zone to a TruePVE ruleset
private void AddOrUpdateMapping(string zoneId, string ruleset)
{
if (null == _storedData ||
string.IsNullOrEmpty(zoneId) || string.IsNullOrEmpty(ruleset))
{
return;
}
_storedData.Mappings[zoneId] = ruleset;
SaveData();
}
// called when a plugin deletes a mapping
private void RemoveMapping(string zoneId)
{
if (null == _storedData ||
string.IsNullOrEmpty(zoneId) ||
!_storedData.Mappings.Remove(zoneId))
{
return;
}
SaveData();
}
// called when a plugin does a mappings bulk remove
private void RemoveMappings(List<string> keys, List<string> _ = null)
{
if (null == _storedData) return;
var dataChanged = false;
foreach (var key in keys)
{
if (!string.IsNullOrEmpty(key) && _storedData.Mappings.Remove(key))
{
dataChanged = true;
}
}
if (dataChanged)
{
SaveData();
}
}
// called when a plugin requests a timed rule exclusion (PVP exit delay)
private void ExcludePlayer(ulong userid, float maxDelayLength, Plugin plugin)
{
if (null == plugin || !userid.IsSteamId()) return;
var pluginName = plugin.Name;
NextTick(() =>
{
// if delay is non-positive, just try to remove any existing record
if (maxDelayLength <= 0.0f)
{
ExcludePlayerRemove(userid, pluginName);
return;
}
// handle the case of updating an existing record
var hasTimers =
_excludedPlayers.TryGetValue(userid, out var excludeTimers);
if (hasTimers &&
excludeTimers.TryGetValue(pluginName, out var excludeTimer))
{
if (TimerValid(excludeTimer))
{
excludeTimer.Reset(maxDelayLength);
return;
}
// pathological: remove defunct entry; we'll create a new one below
excludeTimers.Remove(pluginName);
}
// handle the case that no timers have ever been recorded for player
// (just create an empty timers-by-plugin sub-dictionary)
if (null == excludeTimers)
{
excludeTimers = new Dictionary<string, Timer>();
_excludedPlayers.Add(userid, excludeTimers);
}
// add a timer to the dictionary that simply removes itself on fire
// existence of a dictionary entry then represents an active PVP delay
excludeTimers.Add(pluginName, timer.Once(
maxDelayLength, () => { ExcludePlayerRemove(userid, pluginName); }));
var player = BasePlayer.FindByID(userid);
if (player)
{
SetPvpDelay(player, PvpDelayType.TruePve, true);
}
});
}
#endregion TruePVE Hook Handlers
#endregion TruePVE Integration
#region ZoneManager Integration
#region ZoneManager Utilities
private void ZM_GetZoneIDsNoAlloc(List<string> list) =>
ZoneManager?.Call("GetZoneIDsNoAlloc", list);
private void ZM_GetPlayerZoneIDsNoAlloc(
BasePlayer player, List<string> list) =>
ZoneManager?.Call("GetPlayerZoneIDsNoAlloc", player, list);
// if player is in a zone, return its type if possible, else return null
public PVxType? GetPlayerZoneType(BasePlayer player)
{
if (null == _configData || !IsValidPlayer(player, true)) return null;
// get current zone (if any)
var (zoneId, zoneName) = GetSmallestZoneIdAndName(player);
// go by zone name first
if (!string.IsNullOrEmpty(zoneName))
{
foreach (var pveZoneName in _configData.PveZoneManagerNames)
{
if (zoneName.Contains(pveZoneName, CompareOptions.IgnoreCase))
{
return PVxType.PVE;
}
}
foreach (var pvpZoneName in _configData.PvpZoneManagerNames)
{
if (zoneName.Contains(pvpZoneName, CompareOptions.IgnoreCase))
{
return PVxType.PVP;
}
}
}
if (!string.IsNullOrEmpty(zoneId))
{
// return PVP if this is a TruePVE/NextGenPVE exclusion zone
// (needed for e.g. ZoneManagerAutoZones which doesn't put "PVP" in its
// zone names)
if (IsExcludeZone(zoneId))
{
return PVxType.PVP;
}
// check Zone Manager flags
if (ZM_GetZoneFlag(zoneId, "pvpgod"))
{
return ZM_GetZoneFlag(zoneId, "pvegod") ?
// no-PvP *and* no-PvE => treat as safe zone
PVxType.SafeZone :
// no-PvP only => treat as PvE zone
PVxType.PVE;
}
}
// give up
return null;
}
private (string, string) GetSmallestZoneIdAndName(BasePlayer player)
{
if (ZoneManager == null) return (null, null);
var smallestRadius = float.MaxValue;
string smallestId = null;
string smallestName = null;
var zoneIDs = Pool.Get<List<string>>();
ZM_GetPlayerZoneIDsNoAlloc(player, zoneIDs);
foreach (var zoneId in zoneIDs)
{
if (string.IsNullOrEmpty(zoneId)) continue;
var zoneName = ZM_GetZoneName(zoneId);
// get whichever of 2D zone size or radius is greater than zero
var zoneMagnitude2D = ZM_GetZoneSize(zoneId).Magnitude2D();
var zoneRadius = zoneMagnitude2D < float.Epsilon ?
ZM_GetZoneRadius(zoneId) : zoneMagnitude2D;
if (zoneRadius < float.Epsilon) continue;
if (zoneRadius >= smallestRadius) continue;
// zone is the smallest we've seen; record it as such
smallestRadius = zoneRadius;
smallestId = zoneId;
smallestName = zoneName;
}
Pool.FreeUnmanaged(ref zoneIDs);
return (smallestId, smallestName);
}
private bool ZM_GetZoneFlag(string zoneId, string zoneFlag) =>
Convert.ToBoolean(ZoneManager?.Call("HasFlag", zoneId, zoneFlag));
private string ZM_GetZoneName(string zoneId) =>
Convert.ToString(ZoneManager?.Call("GetZoneName", zoneId));
private float ZM_GetZoneRadius(string zoneId) =>
Convert.ToSingle(ZoneManager?.Call("GetZoneRadius", zoneId));
private Vector3 ZM_GetZoneSize(string zoneId) =>
ZoneManager?.Call("GetZoneSize", zoneId) is Vector3 zoneSize ?
zoneSize : Vector3.zero;
private bool IsExcludeZone(string zoneId)
{
if (null == _storedData || null == _configData ||
!_storedData.Mappings.TryGetValue(zoneId, out var ruleset))
{
return false;
}
foreach (var name in _configData.PveExclusionNames)
{
if (ruleset.Contains(name, CompareOptions.IgnoreCase)) return true;
}
return false;
}
// common logic for setting watcher's zone check request flag
private void CheckZone(BasePlayer player) =>
NextTick(() =>
{
if (!IsValidPlayer(player, true)) return;
var watcher = GetPlayerWatcher(player);
if (!watcher) return;
watcher.SetCheckZone(true);
watcher.Force();
});
#endregion ZoneManager Utilities
#region ZoneManager Hook Handlers
private void OnEnterZone(string zoneId, BasePlayer player) =>
CheckZone(player);
private void OnExitZone(string zoneId, BasePlayer player) =>
// check if player is exiting from a smaller zone into a larger one
CheckZone(player);
#endregion ZoneManager Hook Handlers
#endregion ZoneManager Integration
#region PVP Plugin Integrations
#region PVP Plugin Utilities
// create or update an event record with the given data
private void CreateOrUpdatePvpLocationEvent(
PvpLocationEventType type, Vector3 location, float radius)
{
if (null == _storedData) return;
if (_storedData.PvpEvents.TryGetValue(type, out var eventData))
{
eventData.Location = location;
eventData.Radius = radius;
}
else
{
_storedData.PvpEvents.Add(type, new PvpEventData(location, radius));
}
SaveData();
}
// delete an event record with the given data, if any
private void DeleteLocationPvpEvent(PvpLocationEventType type)
{
if (null == _storedData || !_storedData.PvpEvents.Remove(type)) return;
SaveData();
}
// check whether player is in any Raidable Base
// TODO: add Abandoned Bases support?
// this is expensive, and should only be called if state is totally unknown
// (e.g. on connect)
private PVxType? IsPlayerInBase(BasePlayer player)
{
// get list of all active Raidable Bases
if (RaidableBases?.Call("GetAllEvents") is List<(Vector3 pos, int mode,
bool allowPVP, string a, float b, float c, float loadTime,
ulong ownerId, BasePlayer owner, List<BasePlayer> raiders,
List<BasePlayer> intruders, List<BaseEntity> entities,
string baseName, DateTime spawnDateTime, DateTime despawnDateTime,
float radius, int lootRemaining)> rbEvents
// && rbEvents.Exists(x => x.intruders.Contains(player))
)
{
// look for a base that the player is in
foreach (
var (_, _, allowPVP, _, _, _, _, _, _, _, intruders, _, _, _, _, _, _)
in rbEvents)
{
if (intruders.Contains(player))
{
// base found; return its type
return allowPVP ? PVxType.PVP : PVxType.PVE;
}
}
}
// player not in any bases
return null;
}
// check whether player is in a PVP event that only provides event
// start/stop hooks with location, requiring active polling of player
// position
private bool IsPlayerInPvpEvent(BasePlayer player)
{
if (null == _storedData) return false;
foreach (var eventData in _storedData.PvpEvents.Values)
{
if (Vector3.Distance(eventData.Location, player.transform.position) <=
eventData.Radius)
{
return true;
}
}
return false;
}
// check whether player is in an event that can be PvE or PvP
// note that this is only useful for unexpected exits (e.g. respawning)
// because we don't get a PvP-versus-PvE indication from this
private bool IsPlayerInPVxEvent(BasePlayer player) =>
null != DangerousTreasures && Convert.ToBoolean(DangerousTreasures.Call(
"EventTerritory", player.transform.position));
// check if player has any PVP delays active
// this should only be called when hook-reported states don't exist yet, or
// can't be relied upon for some reason
private HashSet<PvpDelayType> IsPlayerInPVPDelay(ulong playerID)
{
var pvpDelays = new HashSet<PvpDelayType>();
if (AbandonedBases != null && Convert.ToBoolean(
AbandonedBases.Call("HasPVPDelay", playerID)))
{
pvpDelays.Add(PvpDelayType.AbandonedBases);
}
if (DynamicPVP != null && Convert.ToBoolean(
DynamicPVP.Call("IsPlayerInPVPDelay", playerID)))
{
pvpDelays.Add(PvpDelayType.DynamicPvp);
}
if (PlayerBasePvpZones != null && !string.IsNullOrEmpty(Convert.ToString(
PlayerBasePvpZones.Call("OnPlayerBasePvpDelayQuery", playerID))))
{
pvpDelays.Add(PvpDelayType.PlayerBasePvpZones);
}
if (RaidableBases != null && Convert.ToBoolean(
RaidableBases.Call("HasPVPDelay", playerID)))
{
pvpDelays.Add(PvpDelayType.RaidableBases);
}
if (_excludedPlayers.TryGetValue(playerID, out var excludeTimers) &&
excludeTimers.Count > 0)
{
pvpDelays.Add(PvpDelayType.TruePve);
}
return pvpDelays;
}
// common logic for Abandoned/Raidable Base entry hooks
private static void EnteredBase(
BasePlayer player, PVxType baseType,
Vector3 baseLocation, float baseRadius)
{
if (!IsValidPlayer(player, true)) return;
var watcher = GetPlayerWatcher(player);
if (!watcher) return;
watcher.BaseLocation = baseLocation;
watcher.BaseRadius = baseRadius;
watcher.InBaseType = baseType;
watcher.Force();
}
// common logic for Abandoned/Raidable Base exit hooks
private static void ExitedBase(
BasePlayer player, bool checkPlayerValid = true)
{
if (checkPlayerValid && !IsValidPlayer(player, true)) return;
var watcher = GetPlayerWatcher(player);
if (!watcher) return;
watcher.SetCheckZone(true);
watcher.InBaseType = null;
watcher.Force();
}
// common logic for "in PVP bubble" hooks to set/clear a player's state
private static void SetPvpBubble(
BasePlayer player, PvpBubbleTypes type, bool state)
{
if (!IsValidPlayer(player, true)) return;
var watcher = GetPlayerWatcher(player);
if (!watcher) return;
var oldState = watcher.InPvpBubbleTypes;
if (state)
{
watcher.InPvpBubbleTypes |= type;
}
else
{
watcher.InPvpBubbleTypes &= ~type;
if (PvpBubbleTypes.None == watcher.InPvpBubbleTypes)
{
watcher.SetCheckZone(true);
}
}
if (watcher.InPvpBubbleTypes != oldState)
{
watcher.Force();
}
}
// common logic for "in PVP bubble" hooks to clear all players' states
private static void EndPvpBubble(PvpBubbleTypes type)
{
foreach (var player in BasePlayer.activePlayerList)
{
SetPvpBubble(player, type, false);
}
}
// common logic for PVP Delay hooks
private static void SetPvpDelay(
BasePlayer player, PvpDelayType type, bool state)
{
if (!IsValidPlayer(player, true)) return;
var watcher = GetPlayerWatcher(player);
if (null == watcher) return;
if (state)
{
watcher.AddPvpDelay(type);
}
else if (watcher.ClearPvpDelay(type) <= 0)
{
watcher.SetCheckBase(true);
watcher.SetCheckZone(true);
}
watcher.Force();
}
// common logic for PVx event hooks
private static void SetPvxEvent(
BasePlayer player, PVxType eventType, bool state)
{
if (!IsValidPlayer(player, true)) return;
var watcher = GetPlayerWatcher(player);
if (null == watcher) return;
if (state)
{
watcher.SetInPVxEventType(eventType);
}
else
{
watcher.SetCheckZone(true);
watcher.SetInPVxEventType(null);
}
watcher.Force();
}
#endregion PVP Plugin Utilities
#region RaidableBases Hook Handlers
private void OnPlayerEnteredRaidableBase(
BasePlayer player, Vector3 location, bool allowPVP, int mode, string id,
float _, float __, float loadTime, ulong ownerId, string baseName,
DateTime spawnTime, DateTime despawnTime, float radius,
int lootRemaining) =>
NextTick(() => EnteredBase(
player, allowPVP ? PVxType.PVP : PVxType.PVE, location, radius));
private void OnPlayerExitedRaidableBase(
BasePlayer player, Vector3 location, bool allowPVP, int mode, string id,
float _, float __, float loadTime, ulong ownerId, string baseName,
DateTime spawnTime, DateTime despawnTime, float radius) =>
NextTick(() => ExitedBase(player));
private void OnRaidableBaseEnded(
Vector3 location, int mode, bool allowPvP, string id, float _,
float __, float loadTime, ulong ownerId, BasePlayer owner,
List<BasePlayer> raiders, List<BasePlayer> intruders,
List<BaseEntity> entities, string baseName, DateTime spawnDateTime,
DateTime despawnDateTime, float protectionRadius,
int lootAmountRemaining) =>
NextTick(() =>
{
// set zone check flag for any players in base radius
foreach (var player in intruders)
{
if (!IsValidPlayer(player, true)) continue;
// skip player if not within radius of raidable base
if (Vector3.Distance(location, player.transform.position) >
protectionRadius)
{
continue;
}
ExitedBase(player, false);
}
});
private void OnPlayerPvpDelayStart(BasePlayer player, int _) =>
NextTick(() => SetPvpDelay(player, PvpDelayType.RaidableBases, true));
private void OnPlayerPvpDelayReset(BasePlayer player, int _) =>
NextTick(() => SetPvpDelay(player, PvpDelayType.RaidableBases, true));
private void OnPlayerPvpDelayExpired(BasePlayer player, int _) =>
NextTick(() => SetPvpDelay(player, PvpDelayType.RaidableBases, false));
#endregion RaidableBases Hook Handlers
#region AbandonedBases Hook Handlers
private void OnPlayerEnteredAbandonedBase(
BasePlayer player, Vector3 eventPos, float radius, bool allowPVP,
List<BasePlayer> intruders, List<ulong> intruderIds,
List<BaseEntity> entities) =>
NextTick(() => EnteredBase(
player, allowPVP ? PVxType.PVP : PVxType.PVE, eventPos, radius));
private void OnPlayerExitAbandonedBase(
BasePlayer player, Vector3 location, bool allowPVP) =>
NextTick(() => ExitedBase(player));
private void OnAbandonedBaseEnded(
Vector3 eventPos, float radius, bool allowPVP,
List<BasePlayer> participants, List<ulong> participantIds,
List<BaseEntity> entities) =>
NextTick(() =>
{
foreach (var player in participants)
{
if (!IsValidPlayer(player, true)) continue;
if (Vector3.Distance(eventPos, player.transform.position) > radius)
{
continue;
}
ExitedBase(player, false);
}
});
private void OnPlayerPvpDelayStart(BasePlayer player, ulong _) =>
NextTick(() => SetPvpDelay(player, PvpDelayType.AbandonedBases, true));
private void OnPlayerPvpDelayReset(BasePlayer player, ulong _) =>
NextTick(() => SetPvpDelay(player, PvpDelayType.AbandonedBases, true));
private void OnPlayerPvpDelayExpiredII(BasePlayer player, ulong _) =>
NextTick(() => SetPvpDelay(player, PvpDelayType.AbandonedBases, false));
#endregion AbandonedBases Hook Handlers
#region DangerousTreasures Hook Handlers
private static void OnPlayerEnteredDangerousEvent(
BasePlayer player, Vector3 eventPos, bool allowPVP) =>
SetPvxEvent(player, allowPVP ? PVxType.PVP : PVxType.PVE, true);
private static void OnPlayerExitedDangerousEvent(
BasePlayer player, Vector3 eventPos, bool allowPVP) =>
SetPvxEvent(player, allowPVP ? PVxType.PVP : PVxType.PVE, false);
#endregion DangerousTreasures Hook Handlers
#region PVP Bubble Hook Handlers
#region Cargo Train Event Hook Handlers
private void OnPlayerEnterPVPBubble(
TrainEngine trainEngine, BasePlayer player) =>
NextTick(() => SetPvpBubble(
player, PvpBubbleTypes.CargoTrainEvent, true));
private void OnPlayerExitPVPBubble(
TrainEngine trainEngine, BasePlayer player) =>
NextTick(() => SetPvpBubble(
player, PvpBubbleTypes.CargoTrainEvent, false));