forked from northwood-studios/LabAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlayer.cs
More file actions
1542 lines (1319 loc) · 60.9 KB
/
Player.cs
File metadata and controls
1542 lines (1319 loc) · 60.9 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 CentralAuth;
using CommandSystem;
using CustomPlayerEffects;
using Footprinting;
using Generators;
using Hints;
using InventorySystem;
using InventorySystem.Disarming;
using InventorySystem.Items;
using InventorySystem.Items.Firearms.Ammo;
using InventorySystem.Items.Pickups;
using MapGeneration;
using Mirror;
using Mirror.LiteNetLib4Mirror;
using NorthwoodLib.Pools;
using PlayerRoles;
using PlayerRoles.FirstPersonControl;
using PlayerRoles.PlayableScps.HumeShield;
using PlayerRoles.Spectating;
using PlayerRoles.Voice;
using PlayerStatsSystem;
using RoundRestarting;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using LabApi.Features.Stores;
using UnityEngine;
using Utils.Networking;
using Utils.NonAllocLINQ;
using VoiceChat;
using VoiceChat.Playbacks;
using static PlayerStatsSystem.AhpStat;
namespace LabApi.Features.Wrappers;
/// <summary>
/// The wrapper representing <see cref="ReferenceHub">reference hubs</see>, the in-game players.
/// </summary>
public class Player
{
/// <summary>
/// Contains all the cached players in the game, accessible through their <see cref="ReferenceHub"/>.
/// </summary>
public static Dictionary<ReferenceHub, Player> Dictionary { get; } = [];
/// <summary>
/// A cache of players by their User ID. Does not necessarily contain all players.
/// </summary>
private static readonly Dictionary<string, Player> UserIdCache = new(CustomNetworkManager.slots, StringComparer.OrdinalIgnoreCase);
/// <summary>
/// A reference to all <see cref="Player"/> instances currently in the game.
/// </summary>
/// <remarks>
/// This list includes the host player, NPCs and unauthenticated players.
/// <para>
/// Unauthenticated players you must be especially careful with as interacting with them incorrectly will cause them to softlock while joining the game.
/// Use <see cref="ReadyList"/> to get connected players that you can send network messages to.
/// </para>
/// </remarks>
public static IReadOnlyCollection<Player> List => Dictionary.Values;
/// <summary>
/// A reference to all <see cref="Player"/> instances that are authenticated or dummy players.
/// </summary>
public static IEnumerable<Player> ReadyList => List.Where(x => x.IsDummy || (x.IsPlayer && x.IsReady));
/// <summary>
/// A reference to all <see cref="Player"/> instances that are Npcs.
/// </summary>
/// <remarks>
/// The host player is not counted as an Npc.
/// </remarks>
public static IEnumerable<Player> NpcList => List.Where(x => x.IsNpc);
/// <summary>
/// A reference to all <see cref="Player"/> instance that are real players but are not authenticated yet.
/// </summary>
public static IEnumerable<Player> UnauthenticatedList => List.Where(x => x.IsPlayer && !x.IsReady);
/// <summary>
/// The <see cref="Player"/> representing the host or server.
/// </summary>
public static Player? Host => Server.Host;
/// <summary>
/// Gets the amount of ready players or dummies.
/// </summary>
public static int Count => ReadyList.Count();
/// <summary>
/// Gets the amount of non-verified players
/// </summary>
public static int NonVerifiedCount => ConnectionsCount - Count;
/// <summary>
/// Gets the amount of connected players. Regardless of their authentication status.
/// </summary>
public static int ConnectionsCount => LiteNetLib4MirrorCore.Host.ConnectedPeersCount;
/// <summary>
/// Initializes the <see cref="Player"/> class to subscribe to <see cref="ReferenceHub"/> events and handle the player cache.
/// </summary>
[InitializeWrapper]
internal static void Initialize()
{
Dictionary.Clear();
UserIdCache.Clear();
ReferenceHub.OnPlayerAdded += AddPlayer;
ReferenceHub.OnPlayerRemoved += RemovePlayer;
}
/// <summary>
/// An internal constructor to prevent external instantiation.
/// </summary>
/// <param name="referenceHub">The reference hub of the player.</param>
internal Player(ReferenceHub referenceHub)
{
Dictionary.Add(referenceHub, this);
ReferenceHub = referenceHub;
CustomDataStoreManager.AddPlayer(this);
}
/// <summary>
/// The <see cref="ReferenceHub">Reference Hub</see> of the player.
/// </summary>
public ReferenceHub ReferenceHub { get; }
/// <summary>
/// Gets the player's <see cref="GameObject"/>.
/// </summary>
public GameObject GameObject => ReferenceHub.gameObject;
/// <summary>
/// Gets whether the player is the host or server.
/// </summary>
public bool IsHost => ReferenceHub.connectionToClient is LocalConnectionToClient;
/// <summary>
/// Gets whether the player is the dedicated server.
/// </summary>
public bool IsServer => ReferenceHub.isLocalPlayer;
/// <summary>
/// Gets whether this <see cref="Player"/> instance is not controlled by a real human being.
/// </summary>
/// <remarks>
/// This list includes dummy players.
/// </remarks>
public bool IsNpc => !IsHost && ReferenceHub.connectionToClient.GetType() != typeof(NetworkConnectionToClient);
/// <summary>
/// Gets whether the player is a real player and not the host or an Npc.
/// </summary>
public bool IsPlayer => Connection.GetType() == typeof(NetworkConnectionToClient);
/// <summary>
/// Gets whether the player is a dummy instance.
/// </summary>
public bool IsDummy => ReferenceHub.authManager.InstanceMode == ClientInstanceMode.Dummy;
/// <summary>
/// Gets the Player's User ID.
/// </summary>
public string UserId => ReferenceHub.authManager.UserId;
/// <summary>
/// Gets the player's Network ID.
/// </summary>
public uint NetworkId => ReferenceHub.characterClassManager.netId;
/// <summary>
/// Gets the player's <see cref="NetworkConnection"/>.
/// </summary>
public NetworkConnection Connection => IsServer ? ReferenceHub.networkIdentity.connectionToServer : ReferenceHub.networkIdentity.connectionToClient;
/// <summary>
/// Gets the player's <see cref="RecyclablePlayerId"/> value.
/// </summary>
public int PlayerId => ReferenceHub.PlayerId;
/// <summary>
/// Gets if the player is currently offline.
/// </summary>
public bool IsOffline => GameObject == null;
/// <summary>
/// Gets if the player is currently online.
/// </summary>
public bool IsOnline => !IsOffline;
/// <summary>
/// Gets if the player is properly connected and authenticated.
/// </summary>
public bool IsReady => ReferenceHub.authManager.InstanceMode != ClientInstanceMode.Unverified && ReferenceHub.nicknameSync.NickSet;
/// <summary>
/// Gets the player's IP address.
/// </summary>
public string IpAddress => ReferenceHub.characterClassManager.connectionToClient.address;
/// <summary>
/// Gets or sets the player's current role.
/// </summary>
public RoleTypeId Role
{
get => ReferenceHub.GetRoleId();
set => ReferenceHub.roleManager.ServerSetRole(value, RoleChangeReason.RemoteAdmin);
}
/// <summary>
/// Gets the player's current <see cref="PlayerRoleBase"/>.
/// </summary>
public PlayerRoleBase RoleBase => ReferenceHub.roleManager.CurrentRole;
/// <summary>
/// Gets the Player's Nickname.
/// </summary>
public string Nickname => ReferenceHub.nicknameSync.MyNick;
/// <summary>
/// Gets or sets the Player's Display Name.
/// </summary>
public string DisplayName
{
get => ReferenceHub.nicknameSync.DisplayName;
set => ReferenceHub.nicknameSync.DisplayName = value;
}
/// <summary>
/// Gets the log name needed for command senders.
/// </summary>
public string LogName => IsServer ? "SERVER CONSOLE" : $"{Nickname} ({UserId})";
/// <summary>
/// Gets or sets the player's custom info.<br/>
/// Do note that custom info is restriced by several things listed in <see cref="ValidateCustomInfo"/>.
/// Please use this method to validate your string as it is validated on the client by the same method.
/// </summary>
public string CustomInfo
{
get => ReferenceHub.nicknameSync.CustomPlayerInfo;
set => ReferenceHub.nicknameSync.CustomPlayerInfo = value;
}
/// <summary>
/// Gets or sets the player's current health.
/// </summary>
public float Health
{
get => ReferenceHub.playerStats.GetModule<HealthStat>().CurValue;
set => ReferenceHub.playerStats.GetModule<HealthStat>().CurValue = value;
}
/// <summary>
/// Gets or sets the player's current maximum health.
/// </summary>
public float MaxHealth
{
get => ReferenceHub.playerStats.GetModule<HealthStat>().MaxValue;
set => ReferenceHub.playerStats.GetModule<HealthStat>().MaxValue = value;
}
/// <summary>
/// Gets or sets the player's current artificial health.<br/>
/// Setting the value will clear all the current "processes" (each process is responsible for decaying AHP value separately. Eg 2 processes blue candy AHP, which doesn't decay and adrenaline proccess, where AHP does decay).<br/>
/// Note: This value cannot be greater than <see cref="MaxArtificialHealth"/>. Set it to your desired value first if its over <see cref="AhpStat.DefaultMax"/> and then set this one.
/// </summary>
public float ArtificialHealth
{
get => ReferenceHub.playerStats.GetModule<AhpStat>().CurValue;
set
{
AhpStat ahp = ReferenceHub.playerStats.GetModule<AhpStat>();
ahp.ServerKillAllProcesses();
if (value > 0)
ReferenceHub.playerStats.GetModule<AhpStat>().ServerAddProcess(value, MaxArtificialHealth, 0f, 1f, 0f, false);
}
}
/// <summary>
/// Gets or sets the player's current maximum artificial health or hume shield.<br/>
/// Note: The value resets to <see cref="AhpStat.DefaultMax"/> when the player's AHP reaches 0.
/// </summary>
public float MaxArtificialHealth
{
get => ReferenceHub.playerStats.GetModule<AhpStat>().MaxValue;
set => ReferenceHub.playerStats.GetModule<AhpStat>().MaxValue = value;
}
/// <summary>
/// Gets or sets the player's hume shield current value.
/// </summary>
public float HumeShield
{
get => ReferenceHub.playerStats.GetModule<HumeShieldStat>().CurValue;
set => ReferenceHub.playerStats.GetModule<HumeShieldStat>().CurValue = value;
}
/// <summary>
/// Gets or sets the player's maximum hume shield value.
/// Note: This value may change if the player passes a new humeshield treshold for SCPs.
/// </summary>
public float MaxHumeShield
{
get => ReferenceHub.playerStats.GetModule<HumeShieldStat>().MaxValue;
set => ReferenceHub.playerStats.GetModule<HumeShieldStat>().MaxValue = value;
}
/// <summary>
/// Gets or sets the current regeneration rate of the hume shield per second.
/// Returns -1 if the player's role doesn't have hume shield controller.
/// </summary>
public float HumeShieldRegenRate
{
get
{
if (ReferenceHub.roleManager.CurrentRole is not IHumeShieldedRole role)
return -1;
return role.HumeShieldModule.HsRegeneration;
}
set
{
if (ReferenceHub.roleManager.CurrentRole is not IHumeShieldedRole role)
return;
(role.HumeShieldModule as DynamicHumeShieldController).RegenerationRate = value;
}
}
/// <summary>
/// Gets or sets the time that must pass after taking damage for hume shield to regenerate again.
/// Returns -1 if the player's role doesn't have hume shield controller.
/// </summary>
public float HumeShieldRegenCooldown
{
get
{
if (ReferenceHub.roleManager.CurrentRole is not IHumeShieldedRole role)
return -1;
return (role.HumeShieldModule as DynamicHumeShieldController).RegenerationCooldown;
}
set
{
if (ReferenceHub.roleManager.CurrentRole is not IHumeShieldedRole role)
return;
(role.HumeShieldModule as DynamicHumeShieldController).RegenerationCooldown = value;
}
}
/// <summary>
/// Gets or sets the player's current gravity. Default value is <see cref="FpcGravityController.DefaultGravity"/>.<br/>
/// If the player's current role is not first person controlled (inherit from <see cref="IFpcRole"/> then <see cref="Vector3.zero"/> is returned.<br/>
/// Y-axis is up and down. Negative values makes the player go down. Positive upwards. Player must not be grounded in order for gravity to take effect.
/// </summary>
public Vector3 Gravity
{
get
{
if (ReferenceHub.roleManager.CurrentRole is IFpcRole role)
return role.FpcModule.Motor.GravityController.Gravity;
return Vector3.zero;
}
set
{
if (ReferenceHub.roleManager.CurrentRole is IFpcRole role)
role.FpcModule.Motor.GravityController.Gravity = value;
}
}
/// <summary>
/// Gets a value indicating whether the player has remote admin access.
/// </summary>
public bool RemoteAdminAccess => ReferenceHub.serverRoles.RemoteAdmin;
/// <summary>
/// Gets a value indicating whether the player has Do-Not-Track enabled.
/// </summary>
public bool DoNotTrack => ReferenceHub.authManager.DoNotTrack;
/// <summary>
/// Gets or sets a value indicating whether the player is in overwatch mode.
/// </summary>
public bool IsOverwatchEnabled
{
get => ReferenceHub.serverRoles.IsInOverwatch;
set => ReferenceHub.serverRoles.IsInOverwatch = value;
}
/// <summary>
/// Gets the player this player is currently spectating.<br/>
/// Returns null if current player is not spectator or the spectated player is not valid.
/// </summary>
public Player? CurrentlySpectating
{
get
{
if (RoleBase is not SpectatorRole sr)
return null;
if (!ReferenceHub.TryGetHubNetID(sr.SyncedSpectatedNetId, out ReferenceHub hub))
return null;
return Get(hub);
}
}
/// <summary>
/// Gets a pooled list of players who are currently spectating this player.
/// </summary>
public List<Player> CurrentSpectators
{
get
{
List<Player> list = ListPool<Player>.Shared.Rent();
foreach (Player player in List)
{
if (ReferenceHub.IsSpectatedBy(player.ReferenceHub))
list.Add(player);
}
return list;
}
}
/// <summary>
/// Gets or sets the player's current <see cref="Item">item</see>.
/// </summary>
public Item? CurrentItem
{
get => Item.Get(Inventory.CurInstance);
set
{
if (value == null || value.Type == ItemType.None)
Inventory.ServerSelectItem(0);
else
Inventory.ServerSelectItem(value.Serial);
}
}
/// <summary>
/// Gets the player's currently active <see cref="StatusEffectBase">status effects</see>.
/// </summary>
public IEnumerable<StatusEffectBase> ActiveEffects => ReferenceHub.playerEffectsController.AllEffects.Where(x => x.Intensity > 0);
/// <summary>
/// Gets the <see cref="RoomIdentifier"/> at the player's current position.
/// </summary>
public Room? Room => Room.GetRoomAtPosition(Position);
/// <summary>
/// Gets the <see cref="FacilityZone"/> for the player's current room. Returns <see cref="FacilityZone.None"/> if the room is null.
/// </summary>
public FacilityZone Zone => Room?.Zone ?? FacilityZone.None;
/// <summary>
/// Gets the <see cref="Item">items</see> in the player's inventory.
/// </summary>
public IEnumerable<Item?> Items => Inventory.UserInventory.Items.Values.Select(Item.Get);
/// <summary>
/// Gets the player's Reserve Ammo.
/// </summary>
public Dictionary<ItemType, ushort> Ammo => Inventory.UserInventory.ReserveAmmo;
/// <summary>
/// Gets or sets the player's group color.
/// </summary>
public string GroupColor
{
get => ReferenceHub.serverRoles.Network_myColor;
set => ReferenceHub.serverRoles.SetColor(value);
}
/// <summary>
/// Gets or sets what is displayed for the player's group.
/// </summary>
public string GroupName
{
get => ReferenceHub.serverRoles.Network_myText;
set => ReferenceHub.serverRoles.SetText(value);
}
/// <summary>
/// Gets or sets the player's <see cref="UserGroup"/>.
/// </summary>
public UserGroup? UserGroup
{
get => ReferenceHub.serverRoles.Group;
set => ReferenceHub.serverRoles.SetGroup(value);
}
/// <summary>
/// Gets the player's default permission group name. Or null if the player is not in a group.
/// </summary>
public string? PermissionsGroupName => ServerStatic.PermissionsHandler.Members.GetValueOrDefault(UserId);
/// <summary>s
/// Gets the player's unit ID, or -1 if the role is not a <see cref="HumanRole"/>.
/// </summary>
public int UnitId => RoleBase is HumanRole humanRole ? humanRole.UnitNameId : -1;
/// <summary>
/// Gets a value indicating whether the player has a reserved slot.
/// </summary>
public bool HasReservedSlot => ReservedSlot.HasReservedSlot(UserId);
/// <summary>
/// Gets the player's velocity.
/// </summary>
public Vector3 Velocity => ReferenceHub.GetVelocity();
/// <summary>
/// Gets the player's <see cref="Inventory"/>.
/// </summary>
public Inventory Inventory => ReferenceHub.inventory;
/// <summary>
/// Gets the <see cref="VoiceModuleBase"/> for the player, or null if the player does not have a voice module.
/// </summary>
public VoiceModuleBase? VoiceModule => RoleBase is IVoiceRole voiceRole ? voiceRole.VoiceModule : null;
/// <summary>
/// Gets the current <see cref="VoiceChatChannel"/> for the player, or <see cref="VoiceChatChannel.None"/> if the player is not using a voice module.
/// </summary>
public VoiceChatChannel VoiceChannel => VoiceModule?.CurrentChannel ?? VoiceChatChannel.None;
/// <summary>
/// Gets a value indicating whether the player has no items in their inventory.
/// </summary>
public bool IsWithoutItems => Inventory.UserInventory.Items.Count == 0;
/// <summary>
/// Gets a value indicating whether the player's inventory is full.
/// </summary>
public bool IsInventoryFull => Inventory.UserInventory.Items.Count >= Inventory.MaxSlots;
/// <summary>
/// Gets a value indicating whether the player is out of ammunition.
/// </summary>
public bool IsOutOfAmmo => Inventory.UserInventory.ReserveAmmo.All(ammo => ammo.Value == 0);
/// <summary>
/// Gets or sets a value indicating whether the player is disarmed.
/// </summary>
public bool IsDisarmed
{
get => Inventory.IsDisarmed();
set
{
if (value)
{
Inventory.SetDisarmedStatus(null);
DisarmedPlayers.Entries.Add(new DisarmedPlayers.DisarmedEntry(ReferenceHub.networkIdentity.netId, 0U));
new DisarmedPlayersListMessage(DisarmedPlayers.Entries).SendToAuthenticated();
return;
}
Inventory.SetDisarmedStatus(null);
new DisarmedPlayersListMessage(DisarmedPlayers.Entries).SendToAuthenticated();
}
}
/// <summary>
/// Gets a value indicating whether the player is muted.
/// </summary>
public bool IsMuted => VoiceChatMutes.QueryLocalMute(UserId);
/// <summary>
/// Gets a value indicating whether the player is muted from the intercom.
/// </summary>
public bool IsIntercomMuted => VoiceChatMutes.QueryLocalMute(UserId, true);
/// <summary>
/// Gets a value indicating whether the player is talking through a radio.
/// </summary>
public bool IsUsingRadio => PersonalRadioPlayback.IsTransmitting(ReferenceHub);
/// <summary>
/// Gets a value indicating whether the player is speaking.
/// </summary>
public bool IsSpeaking => VoiceModule != null && VoiceModule.IsSpeaking;
/// <summary>
/// Gets a value indicating whether the player is a Global Moderator.
/// </summary>
public bool IsGlobalModerator => ReferenceHub.authManager.RemoteAdminGlobalAccess;
/// <summary>
/// Gets a value indicating whether the player is a Northwood Staff member.
/// </summary>
public bool IsNorthwoodStaff => ReferenceHub.authManager.NorthwoodStaff;
/// <summary>
/// Gets or sets a value indicating whether bypass mode is enabled for the player, allowing them to open doors/gates without keycards.
/// </summary>
public bool IsBypassEnabled
{
get => ReferenceHub.serverRoles.BypassMode;
set => ReferenceHub.serverRoles.BypassMode = value;
}
/// <summary>
/// Gets or sets a value indicating whether god mode is enabled for the player.
/// </summary>
public bool IsGodModeEnabled
{
get => ReferenceHub.characterClassManager.GodMode;
set => ReferenceHub.characterClassManager.GodMode = value;
}
/// <summary>
/// Gets or sets a value indicating whether noclip mode is enabled for the player.
/// </summary>
public bool IsNoclipEnabled
{
get => ReferenceHub.playerStats.GetModule<AdminFlagsStat>().HasFlag(AdminFlags.Noclip);
set => ReferenceHub.playerStats.GetModule<AdminFlagsStat>().SetFlag(AdminFlags.Noclip, value);
}
/// <summary>
/// Gets or sets the player who disarmed this player.
/// </summary>
public Player? DisarmedBy
{
get
{
if (!IsDisarmed) return null;
DisarmedPlayers.DisarmedEntry entry = DisarmedPlayers.Entries.Find(x => x.DisarmedPlayer == NetworkId);
return Get(entry.Disarmer);
}
set
{
Inventory.SetDisarmedStatus(null);
if (value == null)
return;
DisarmedPlayers.Entries.Add(new DisarmedPlayers.DisarmedEntry(NetworkId, value.NetworkId));
new DisarmedPlayersListMessage(DisarmedPlayers.Entries).SendToAuthenticated();
}
}
/// <summary>
/// Gets the player's current <see cref="Team"/>.
/// </summary>
public Team Team => RoleBase.Team;
/// <summary>
/// Gets whether the player is currently Alive.
/// </summary>
public bool IsAlive => Team != Team.Dead;
/// <summary>
/// Gets if the player is an SCP.
/// </summary>
public bool IsSCP => Team == Team.SCPs;
/// <summary>
/// Gets if the player is a human.
/// </summary>
public bool IsHuman => IsAlive && !IsSCP;
/// <summary>
/// Gets if the player is part of the NTF.
/// </summary>
public bool IsNTF => Team == Team.FoundationForces;
/// <summary>
/// Gets if the player is part of the Chaos Insurgency.
/// </summary>
public bool IsChaos => Team == Team.ChaosInsurgency;
/// <summary>
/// Gets if the player is a tutorial.
/// </summary>
public bool IsTutorial => Role == RoleTypeId.Tutorial;
/// <summary>
/// Gets the player's Camera <see cref="Transform"/>.
/// </summary>
public Transform Camera => ReferenceHub.PlayerCameraReference;
/// <summary>
/// Gets or sets the player's position.<br/>
/// Returns <see cref="Vector3.zero"/> if the player's role is not currently derived from <see cref="IFpcRole"/>.
/// </summary>
public Vector3 Position
{
get
{
if (RoleBase is not IFpcRole fpcRole)
return Vector3.zero;
return fpcRole.FpcModule.Position;
}
set => ReferenceHub.TryOverridePosition(value);
}
/// <summary>
/// Gets or sets the player's rotation.
/// </summary>
public Quaternion Rotation
{
get => GameObject.transform.rotation;
set => ReferenceHub.TryOverrideRotation(value.eulerAngles);
}
/// <summary>
/// Gets or sets the player's look rotation. X is vertical axis while Y is horizontal. Vertical axis is clamped by the base game logic.<br/>
/// Returns <see cref="Vector2.zero"/> if the player's role is not currently derived from <see cref="IFpcRole"/>.
/// </summary>
public Vector2 LookRotation
{
get
{
if (ReferenceHub.roleManager.CurrentRole is not IFpcRole fpcRole)
return Vector2.zero;
FpcMouseLook mouseLook = fpcRole.FpcModule.MouseLook;
return new Vector2(mouseLook.CurrentVertical, mouseLook.CurrentHorizontal);
}
set => ReferenceHub.TryOverrideRotation(value);
}
/// <summary>
/// Gets or sets player's remaining stamina (min = 0, max = 1).
/// </summary>
public float StaminaRemaining
{
get => ReferenceHub.playerStats.GetModule<StaminaStat>().CurValue;
set => ReferenceHub.playerStats.GetModule<StaminaStat>().CurValue = value;
}
/// <summary>
/// Validates the custom info text and returns result whether it is valid or invalid.<br/>
/// Current validation requirements are the following:
///
/// <list type="bullet">
/// <item>Match the <see cref="Misc.PlayerCustomInfoRegex"/> regex.</item>
/// <item>Use only color,i,b and size rich text tags.</item>
/// <item>Colors used have to be from <see cref="Misc.AcceptedColours"/></item>
/// </list>
///
/// </summary>
/// <param name="text">The text to check on.</param>
/// <param name="rejectionReason">Out parameter containing rejection reason.</param>
/// <returns>Whether is the info parameter valid.</returns>
public static bool ValidateCustomInfo(string text, out string rejectionReason) => NicknameSync.ValidateCustomInfo(text, out rejectionReason);
#region Player Getters
/// <summary>
/// Gets the player wrapper from the <see cref="Dictionary"/>, or creates a new one if it doesn't exist.
/// </summary>
/// <param name="referenceHub">The reference hub of the player.</param>
/// <returns>The requested player or null if the reference hub is null.</returns>
[return: NotNullIfNotNull(nameof(referenceHub))]
public static Player? Get(ReferenceHub? referenceHub)
{
if (referenceHub == null)
return null;
return Dictionary.TryGetValue(referenceHub, out Player player) ? player : new Player(referenceHub);
}
/// <summary>
/// Gets a list of players from a list of reference hubs.
/// </summary>
/// <param name="referenceHubs">The reference hubs of the players.</param>
/// <returns>A list of players.</returns>
public static List<Player> Get(IEnumerable<ReferenceHub> referenceHubs)
{
// We rent a list from the pool to avoid unnecessary allocations.
// We don't care if the developer forgets to return the list to the pool
// as at least it will be more efficient than always allocating a new list.
List<Player> list = ListPool<Player>.Shared.Rent();
return GetNonAlloc(referenceHubs, list);
}
/// <summary>
/// Gets a list of players from a list of reference hubs without allocating a new list.
/// </summary>
/// <param name="referenceHubs">The reference hubs of the players.</param>
/// <param name="list">A reference to the list to add the players to.</param>
public static List<Player> GetNonAlloc(IEnumerable<ReferenceHub> referenceHubs, List<Player> list)
{
// We clear the list to avoid any previous data.
list.Clear();
// And then we add all the players to the list.
list.AddRange(referenceHubs.Select(Get));
// We finally return the list.
return list;
}
#region Get Player from a GameObject
/// <summary>
/// Gets the <see cref="Player"/> associated with the <see cref="GameObject"/>.
/// </summary>
/// <param name="gameObject">The <see cref="UnityEngine.GameObject"/> to get the player from.</param>
/// <returns>The <see cref="Player"/> associated with the <see cref="GameObject"/> or null if it doesn't exist.</returns>
public static Player? Get(GameObject? gameObject) => TryGet(gameObject, out Player? player) ? player : null;
/// <summary>
/// Tries to get the <see cref="Player"/> associated with the <see cref="GameObject"/>.
/// </summary>
/// <param name="gameObject">The <see cref="UnityEngine.GameObject"/> to get the player from.</param>
/// <param name="player">The <see cref="Player"/> associated with the <see cref="UnityEngine.GameObject"/> or null if it doesn't exist.</param>
/// <returns>Whether the player was successfully retrieved.</returns>
public static bool TryGet(GameObject? gameObject, [NotNullWhen(true)] out Player? player)
{
player = null;
if (gameObject == null)
return false;
if (!ReferenceHub.TryGetHub(gameObject, out ReferenceHub? hub))
return false;
player = Get(hub);
return true;
}
#endregion
#region Get Player from a NetworkIdentity
/// <summary>
/// Gets the <see cref="Player"/> associated with the <see cref="NetworkIdentity"/>.
/// </summary>
/// <param name="identity">The <see cref="NetworkIdentity"/> to get the player from.</param>
/// <returns>The <see cref="Player"/> associated with the <see cref="NetworkIdentity"/> or null if it doesn't exist.</returns>
public static Player? Get(NetworkIdentity? identity) => TryGet(identity, out Player? player) ? player : null;
/// <summary>
/// Tries to get the <see cref="Player"/> associated with the <see cref="NetworkIdentity"/>.
/// </summary>
/// <param name="identity">The <see cref="NetworkIdentity"/> to get the player from.</param>
/// <param name="player">The <see cref="Player"/> associated with the <see cref="NetworkIdentity"/> or null if it doesn't exist.</param>
/// <returns>Whether the player was successfully retrieved.</returns>
public static bool TryGet(NetworkIdentity? identity, [NotNullWhen(true)] out Player? player)
{
player = null;
if (identity == null)
return false;
if (!TryGet(identity.netId, out player))
return false;
return true;
}
#endregion
#region Get Player from a NetworkIdentity.netId (uint)
/// <summary>
/// Gets the <see cref="Player"/> associated with the <see cref="NetworkIdentity.netId"/>.
/// </summary>
/// <param name="netId">The <see cref="NetworkIdentity.netId"/> to get the player from.</param>
/// <returns>The <see cref="Player"/> associated with the <see cref="NetworkIdentity.netId"/> or null if it doesn't exist.</returns>
public static Player? Get(uint netId) => TryGet(netId, out Player? player) ? player : null;
/// <summary>
/// Tries to get the <see cref="Player"/> associated with the <see cref="NetworkIdentity.netId"/>.
/// </summary>
/// <param name="netId">The <see cref="NetworkIdentity.netId"/> to get the player from.</param>
/// <param name="player">The <see cref="Player"/> associated with the <see cref="NetworkIdentity.netId"/> or null if it doesn't exist.</param>
/// <returns>Whether the player was successfully retrieved.</returns>
public static bool TryGet(uint netId, [NotNullWhen(true)] out Player? player)
{
player = null;
if (!ReferenceHub.TryGetHubNetID(netId, out ReferenceHub hub))
return false;
player = Get(hub);
return true;
}
#endregion
#region Get Player from a ICommandSender
/// <summary>
/// Gets the <see cref="Player"/> associated with the <see cref="ICommandSender"/>.
/// </summary>
/// <param name="sender">The <see cref="ICommandSender"/> to get the player from.</param>
/// <returns>The <see cref="Player"/> associated with the <see cref="ICommandSender"/> or null if it doesn't exist.</returns>
public static Player? Get(ICommandSender? sender) => TryGet(sender, out Player? player) ? player : null;
/// <summary>
/// Tries to get the <see cref="Player"/> associated with the <see cref="ICommandSender"/>.
/// </summary>
/// <param name="sender">The <see cref="ICommandSender"/> to get the player from.</param>
/// <param name="player">The <see cref="Player"/> associated with the <see cref="ICommandSender"/> or null if it doesn't exist.</param>
/// <returns>Whether the player was successfully retrieved.</returns>
public static bool TryGet(ICommandSender? sender, [NotNullWhen(true)] out Player? player)
{
player = null;
if (sender is not CommandSender commandSender)
return false;
return TryGet(commandSender.SenderId, out player);
}
#endregion
#region Get Player from a UserId
/// <summary>
/// Gets the <see cref="Player"/> associated with the <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The User ID of the player.</param>
/// <returns>The <see cref="Player"/> associated with the <paramref name="userId"/> or null if it doesn't exist.</returns>
public static Player? Get(string? userId) => TryGet(userId, out Player? player) ? player : null;
/// <summary>
/// Tries to get the <see cref="Player"/> associated with the <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The user ID of the player.</param>
/// <param name="player">The <see cref="Player"/> associated with the <paramref name="userId"/> or null if it doesn't exist.</param>
/// <returns>Whether the player was successfully retrieved.</returns>
public static bool TryGet(string? userId, [NotNullWhen(true)] out Player? player)
{
player = null;
if (string.IsNullOrEmpty(userId))
return false;
if (UserIdCache.TryGetValue(userId!, out player) && player.IsOnline)
return true;
player = List.FirstOrDefault(x => x.UserId == userId);
if (player == null)
return false;
UserIdCache[userId!] = player;
return true;
}
#endregion
#region Get Player from a Player Id
/// <summary>
/// Gets the <see cref="Player" /> associated with the <paramref name="playerId" />.
/// </summary>
/// <param name="playerId">The player ID of the player.</param>
/// <returns>The <see cref="Player" /> associated with the <paramref name="playerId" /> or null if it doesn't exist.</returns>
public static Player? Get(int playerId) => TryGet(playerId, out Player? player) ? player : null;
/// <summary>
/// Tries to get the <see cref="Player" /> associated with the <paramref name="playerId" />.
/// </summary>
/// <param name="playerId">The player ID of the player.</param>
/// <param name="player">The <see cref="Player" /> associated with the <paramref name="playerId" /> or null if it doesn't exist.</param>
/// <returns>Whether the player was successfully retrieved.</returns>
public static bool TryGet(int playerId, [NotNullWhen(true)] out Player? player)
{
player = List.FirstOrDefault(n => n.PlayerId == playerId);
return player != null;
}
#endregion
#region Get Player from a Name
/// <summary>
/// Tries to get players by name by seeing if their name starts with the input.
/// </summary>
/// <param name="input">The input to search for.</param>
/// <param name="players">The output players if found.</param>
/// <returns>True if the players are found, false otherwise.</returns>
public static bool TryGetPlayersByName(string input, out List<Player> players)
{
players = GetNonAlloc(ReferenceHub.AllHubs.Where(x => x.nicknameSync.Network_myNickSync.StartsWith(input, StringComparison.OrdinalIgnoreCase)),
ListPool<Player>.Shared.Rent());
return players.Count > 0;
}
#endregion
#endregion
/// <summary>
/// Teleports the player by the delta location.
/// </summary>
/// <param name="delta">Position to add to the current one.</param>
public void Move(Vector3 delta) => ReferenceHub.TryOverridePosition(Position + delta);