forked from Unity-Technologies/com.unity.netcode.gameobjects
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNetworkObject.cs
3590 lines (3202 loc) · 173 KB
/
NetworkObject.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
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 System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using Unity.Collections;
using Unity.Netcode.Components;
#if UNITY_EDITOR
using UnityEditor;
#if UNITY_2021_2_OR_NEWER
using UnityEditor.SceneManagement;
#else
using UnityEditor.Experimental.SceneManagement;
#endif
#endif
using UnityEngine;
using UnityEngine.SceneManagement;
namespace Unity.Netcode
{
/// <summary>
/// A component used to identify that a GameObject in the network
/// </summary>
[AddComponentMenu("Netcode/Network Object", -99)]
[DisallowMultipleComponent]
public sealed class NetworkObject : MonoBehaviour
{
[HideInInspector]
[SerializeField]
internal uint GlobalObjectIdHash;
/// <summary>
/// Used to track the source GlobalObjectIdHash value of the associated network prefab.
/// When an override exists or it is in-scene placed, GlobalObjectIdHash and PrefabGlobalObjectIdHash
/// will be different. The PrefabGlobalObjectIdHash value is what is used when sending a <see cref="CreateObjectMessage"/>.
/// </summary>
internal uint PrefabGlobalObjectIdHash;
/// <summary>
/// This is the source prefab of an in-scene placed NetworkObject. This is not set for in-scene
/// placd NetworkObjects that are not prefab instances, dynamically spawned prefab instances,
/// or for network prefab assets.
/// </summary>
[HideInInspector]
[SerializeField]
internal uint InScenePlacedSourceGlobalObjectIdHash;
/// <summary>
/// Metadata sent during the instantiation process.
/// Retrieved in INetworkCustomSpawnDataSynchronizer before instantiation,
/// and available to INetworkPrefabInstanceHandler.Instantiate() for custom handling by user code.
/// </summary>
internal FastBufferReader InstantiationPayload;
/// <summary>
/// Gets the Prefab Hash Id of this object if the object is registerd as a prefab otherwise it returns 0
/// </summary>
[HideInInspector]
public uint PrefabIdHash
{
get
{
return GlobalObjectIdHash;
}
}
/// <summary>
/// All <see cref="NetworkTransform"/> component instances associated with a <see cref="NetworkObject"/> component instance.
/// </summary>
/// <remarks>
/// When parented, all child <see cref="NetworkTransform"/> component instances under a <see cref="NetworkObject"/> component instance that do not have
/// another <see cref="NetworkObject"/> component instance will be associated with the initial component instance. This list does not contain any parented
/// children <see cref="NetworkObject"/> instances with one or more <see cref="NetworkTransform"/> component instance(s).
/// </remarks>
public List<NetworkTransform> NetworkTransforms { get; private set; }
#if COM_UNITY_MODULES_PHYSICS
/// <summary>
/// All <see cref="NetworkRigidbodyBase"></see> component instances associated with a <see cref="NetworkObject"/> component instance.
/// NOTE: This is only available if a physics package is included. If not, then this will not be available!
/// </summary>
/// <remarks>
/// When parented, all child <see cref="NetworkRigidbodyBase"/> component instances under a <see cref="NetworkObject"/> component instance that do not have
/// another <see cref="NetworkObject"/> component instance will be associated with the initial component instance. This list does not contain any parented
/// child <see cref="NetworkObject"/> instances with one or more <see cref="NetworkTransform"/> component instance(s).
/// </remarks>
public List<NetworkRigidbodyBase> NetworkRigidbodies { get; private set; }
#endif
/// <summary>
/// The current parent <see cref="NetworkObject"/> component instance to this <see cref="NetworkObject"/> component instance. When there is no parent then
/// this will be <see cref="null"/>.
/// </summary>
public NetworkObject CurrentParent { get; private set; }
#if UNITY_EDITOR
private const string k_GlobalIdTemplate = "GlobalObjectId_V1-{0}-{1}-{2}-{3}";
/// <summary>
/// Object Types <see href="https://docs.unity3d.com/ScriptReference/GlobalObjectId.html"/>
/// Parameter 0 of <see cref="k_GlobalIdTemplate"/>
/// </summary>
// 0 = Null (when considered a null object type we can ignore)
// 1 = Imported Asset
// 2 = Scene Object
// 3 = Source Asset.
private const int k_NullObjectType = 0;
private const int k_ImportedAssetObjectType = 1;
private const int k_SceneObjectType = 2;
private const int k_SourceAssetObjectType = 3;
// Used to track any InContext or InIsolation prefab being edited.
private static PrefabStage s_PrefabStage;
// The network prefab asset that the edit mode scene has created an instance of (s_PrefabInstance).
private static NetworkObject s_PrefabAsset;
// The InContext or InIsolation edit mode network prefab scene instance of the prefab asset (s_PrefabAsset).
private static NetworkObject s_PrefabInstance;
private static bool s_DebugPrefabIdGeneration;
[ContextMenu("Refresh In-Scene Prefab Instances")]
internal void RefreshAllPrefabInstances()
{
var instanceGlobalId = GlobalObjectId.GetGlobalObjectIdSlow(this);
// Assign the currently selected instance to be updated
NetworkObjectRefreshTool.PrefabNetworkObject = this;
if (!PrefabUtility.IsPartOfAnyPrefab(this) || instanceGlobalId.identifierType != k_ImportedAssetObjectType)
{
EditorUtility.DisplayDialog("Network Prefab Assets Only", "This action can only be performed on a network prefab asset.", "Ok");
return;
}
// Handle updating the currently active scene
NetworkObjectRefreshTool.ProcessActiveScene();
// Refresh all build settings scenes
var activeScene = SceneManager.GetActiveScene();
foreach (var editorScene in EditorBuildSettings.scenes)
{
// skip disabled scenes and the currently active scene
if (!editorScene.enabled || activeScene.path == editorScene.path)
{
continue;
}
// Add the scene to be processed
NetworkObjectRefreshTool.ProcessScene(editorScene.path, true);
}
// Process all added scenes
NetworkObjectRefreshTool.ProcessScenes();
}
/// <summary>
/// Register for <see cref="PrefabStage"/> opened and closing event notifications.
/// </summary>
[InitializeOnLoadMethod]
private static void OnApplicationStart()
{
PrefabStage.prefabStageOpened -= PrefabStageOpened;
PrefabStage.prefabStageOpened += PrefabStageOpened;
PrefabStage.prefabStageClosing -= PrefabStageClosing;
PrefabStage.prefabStageClosing += PrefabStageClosing;
}
private static void PrefabStageClosing(PrefabStage prefabStage)
{
// If domain reloading is enabled, then this will be null when we return from playmode.
if (s_PrefabStage == null)
{
// Determine if we have a network prefab opened in edit mode or not.
CheckPrefabStage(prefabStage);
}
s_PrefabStage = null;
s_PrefabInstance = null;
s_PrefabAsset = null;
}
private static void PrefabStageOpened(PrefabStage prefabStage)
{
// Determine if we have a network prefab opened in edit mode or not.
CheckPrefabStage(prefabStage);
}
/// <summary>
/// Determines if we have opened a network prefab in edit mode (InContext or InIsolation)
/// </summary>
/// <remarks>
/// InContext: Typically means a are in prefab edit mode for an in-scene placed network prefab instance.
/// (currently no such thing as a network prefab with nested network prefab instances)
///
/// InIsolation: Typically means we are in prefb edit mode for a prefab asset.
/// </remarks>
/// <param name="prefabStage"></param>
private static void CheckPrefabStage(PrefabStage prefabStage)
{
s_PrefabStage = prefabStage;
s_PrefabInstance = prefabStage.prefabContentsRoot?.GetComponent<NetworkObject>();
if (s_PrefabInstance)
{
// We acquire the source prefab that the prefab edit mode scene instance was instantiated from differently for InContext than InSolation.
if (s_PrefabStage.mode == PrefabStage.Mode.InContext && s_PrefabStage.openedFromInstanceRoot != null)
{
// This is needed to handle the scenario where a user completely loads a new scene while in an InContext prefab edit mode.
try
{
s_PrefabAsset = s_PrefabStage.openedFromInstanceRoot?.GetComponent<NetworkObject>();
}
catch
{
s_PrefabAsset = null;
}
}
else
{
// When editing in InIsolation mode, load the original prefab asset from the provided path.
s_PrefabAsset = AssetDatabase.LoadAssetAtPath<NetworkObject>(s_PrefabStage.assetPath);
}
if (s_PrefabInstance.GlobalObjectIdHash != s_PrefabAsset.GlobalObjectIdHash)
{
s_PrefabInstance.GlobalObjectIdHash = s_PrefabAsset.GlobalObjectIdHash;
// For InContext mode, we don't want to record these modifications (the in-scene GlobalObjectIdHash is serialized with the scene).
if (s_PrefabStage.mode == PrefabStage.Mode.InIsolation)
{
PrefabUtility.RecordPrefabInstancePropertyModifications(s_PrefabAsset);
}
}
}
else
{
s_PrefabStage = null;
s_PrefabInstance = null;
s_PrefabAsset = null;
}
}
/// <summary>
/// GlobalObjectIdHash values are generated during validation.
/// </summary>
internal void OnValidate()
{
// Always exit early if we are in prefab edit mode and this instance is the
// prefab instance within the InContext or InIsolation edit scene.
if (s_PrefabInstance == this)
{
return;
}
// Do not regenerate GlobalObjectIdHash for NetworkPrefabs while Editor is in play mode.
if (EditorApplication.isPlaying && !string.IsNullOrEmpty(gameObject.scene.name))
{
return;
}
// Do not regenerate GlobalObjectIdHash if Editor is transitioning into or out of play mode.
if (!EditorApplication.isPlaying && EditorApplication.isPlayingOrWillChangePlaymode)
{
return;
}
// Get a global object identifier for this network prefab.
var globalId = GlobalObjectId.GetGlobalObjectIdSlow(this);
// if the identifier type is 0, then don't update the GlobalObjectIdHash.
if (globalId.identifierType == k_NullObjectType)
{
return;
}
var oldValue = GlobalObjectIdHash;
GlobalObjectIdHash = globalId.ToString().Hash32();
// Always check for in-scene placed to assure any previous version scene assets with in-scene place NetworkObjects gets updated.
CheckForInScenePlaced();
// If the GlobalObjectIdHash value changed, then mark the asset dirty.
if (GlobalObjectIdHash != oldValue)
{
// Check if this is an in-scnee placed NetworkObject (Special Case for In-Scene Placed).
if (IsSceneObject.HasValue && IsSceneObject.Value)
{
// Sanity check to make sure this is a scene placed object.
if (globalId.identifierType != k_SceneObjectType)
{
// This should never happen, but in the event it does throw and error.
Debug.LogError($"[{gameObject.name}] is detected as an in-scene placed object but its identifier is of type {globalId.identifierType}! **Report this error**");
}
// If this is a prefab instance, then we want to mark it as having been updated in order for the udpated GlobalObjectIdHash value to be saved.
if (PrefabUtility.IsPartOfAnyPrefab(this))
{
// We must invoke this in order for the modifications to get saved with the scene (does not mark scene as dirty).
PrefabUtility.RecordPrefabInstancePropertyModifications(this);
}
}
else // Otherwise, this is a standard network prefab asset so we just mark it dirty for the AssetDatabase to update it.
{
EditorUtility.SetDirty(this);
}
}
}
/// <summary>
/// This checks to see if this NetworkObject is an in-scene placed prefab instance. If so it will
/// automatically find the source prefab asset's GlobalObjectIdHash value, assign it to
/// InScenePlacedSourceGlobalObjectIdHash and mark this as being in-scene placed.
/// </summary>
/// <remarks>
/// This NetworkObject is considered an in-scene placed prefab asset instance if it is:
/// - Part of a prefab
/// - Within a valid scene that is part of the scenes in build list
/// (In-scene defined NetworkObjects that are not part of a prefab instance are excluded.)
/// </remarks>
private void CheckForInScenePlaced()
{
if (gameObject.scene.IsValid() && gameObject.scene.isLoaded && gameObject.scene.buildIndex >= 0)
{
if (PrefabUtility.IsPartOfAnyPrefab(this))
{
var prefab = PrefabUtility.GetCorrespondingObjectFromSource(gameObject);
var assetPath = AssetDatabase.GetAssetPath(prefab);
var sourceAsset = AssetDatabase.LoadAssetAtPath<NetworkObject>(assetPath);
if (sourceAsset != null && sourceAsset.GlobalObjectIdHash != 0 && InScenePlacedSourceGlobalObjectIdHash != sourceAsset.GlobalObjectIdHash)
{
InScenePlacedSourceGlobalObjectIdHash = sourceAsset.GlobalObjectIdHash;
EditorUtility.SetDirty(this);
}
}
IsSceneObject = true;
// Default scene migration synchronization to false for in-scene placed NetworkObjects
SceneMigrationSynchronization = false;
}
}
#endif // UNITY_EDITOR
internal bool HasParentNetworkObject(Transform transform)
{
if (transform.parent != null)
{
var networkObject = transform.parent.GetComponent<NetworkObject>();
if (networkObject != null && networkObject != this)
{
return true;
}
if (transform.parent.parent != null)
{
return HasParentNetworkObject(transform.parent);
}
}
return false;
}
/// <summary>
/// Gets the NetworkManager that owns this NetworkObject instance
/// </summary>
public NetworkManager NetworkManager => NetworkManagerOwner ? NetworkManagerOwner : NetworkManager.Singleton;
/// <summary>
/// Useful to know if we should or should not send a message
/// </summary>
internal bool HasRemoteObservers => !(Observers.Count() == 0 || (Observers.Contains(NetworkManager.LocalClientId) && Observers.Count() == 1));
/// <summary>
/// Distributed Authority Mode Only
/// When set, NetworkObjects despawned remotely will be delayed until the tick count specified is reached on all non-owner instances.
/// It will still despawn immediately on the owner-local side.
/// </summary>
[HideInInspector]
public int DeferredDespawnTick;
/// <summary>
/// Distributed Authority Mode Only
/// The delegate handler declaration for <see cref="OnDeferedDespawnComplete"/>.
/// </summary>
/// <returns>true (despawn) or false (do not despawn)</returns>
public delegate bool OnDeferedDespawnCompleteDelegateHandler();
/// <summary>
/// If assigned, this callback will be invoked each frame update to determine if a <see cref="NetworkObject"/> that has had its despawn deferred
/// should despawn. Use this callback to handle scenarios where you might have additional changes in state that could vindicate despawning earlier
/// than the deferred despawn targeted future network tick.
/// </summary>
public OnDeferedDespawnCompleteDelegateHandler OnDeferredDespawnComplete;
/// <summary>
/// Distributed Authority Mode Only
/// When invoked by the authority of the <see cref="NetworkObject"/>, this will locally despawn the <see cref="NetworkObject"/> while
/// sending a delayed despawn to all non-authority instances. The tick offset + the authority's current known network tick (ServerTime.Tick)
/// is when non-authority instances will despawn this <see cref="NetworkObject"/> instance.
/// </summary>
/// <param name="tickOffset">The number of ticks from the authority's currently known <see cref="NetworkManager.ServerTime.Tick"/> to delay the despawn.</param>
/// <param name="destroy">Defaults to true, determines whether the <see cref="NetworkObject"/> will be destroyed.</param>
public void DeferDespawn(int tickOffset, bool destroy = true)
{
if (!NetworkManager.DistributedAuthorityMode)
{
NetworkLog.LogError($"This method is only available in distributed authority mode.");
return;
}
if (!IsSpawned)
{
NetworkLog.LogError($"Cannot defer despawning {name} because it is not spawned!");
return;
}
if (!HasAuthority)
{
NetworkLog.LogError($"Only the authority can invoke {nameof(DeferDespawn)} and local Client-{NetworkManager.LocalClientId} is not the authority of {name}!");
return;
}
// Apply the relative tick offset for when this NetworkObject should be despawned on
// non-authoritative instances.
DeferredDespawnTick = NetworkManager.ServerTime.Tick + tickOffset;
var connectionManager = NetworkManager.ConnectionManager;
for (int i = 0; i < ChildNetworkBehaviours.Count; i++)
{
ChildNetworkBehaviours[i].PreVariableUpdate();
// Notify all NetworkBehaviours that the authority is performing a deferred despawn.
// This is when user script would update NetworkVariable states that might be needed
// for the deferred despawn sequence on non-authoritative instances.
ChildNetworkBehaviours[i].OnDeferringDespawn(DeferredDespawnTick);
}
// DAHost handles sending updates to all clients
if (NetworkManager.DAHost)
{
for (int i = 0; i < connectionManager.ConnectedClientsList.Count; i++)
{
var client = connectionManager.ConnectedClientsList[i];
if (IsNetworkVisibleTo(client.ClientId))
{
// Sync just the variables for just the objects this client sees
for (int k = 0; k < ChildNetworkBehaviours.Count; k++)
{
ChildNetworkBehaviours[k].NetworkVariableUpdate(client.ClientId);
}
}
}
}
else // Clients just send their deltas to the service or DAHost
{
for (int k = 0; k < ChildNetworkBehaviours.Count; k++)
{
ChildNetworkBehaviours[k].NetworkVariableUpdate(NetworkManager.ServerClientId);
}
}
// Now despawn the local authority instance
Despawn(destroy);
}
/// <summary>
/// When enabled, NetworkObject ownership is distributed amongst clients.
/// To set <see cref="OwnershipStatus.Distributable"/> during runtime, use <see cref="SetOwnershipStatus(OwnershipStatus, bool, OwnershipLockActions)"/>
/// </summary>
/// <remarks>
/// Scenarios of interest:
/// - If the <see cref="NetworkObject"/> is locked and the current owner is still connected, then it will not be redistributed upon a new client joining.
/// - If the <see cref="NetworkObject"/> has an ownership request in progress, then it will not be redistributed upon a new client joining.
/// - If the <see cref="NetworkObject"/> is locked but the owner is not longer connected, then it will be redistributed.
/// - If the <see cref="NetworkObject"/> has an ownership request in progress but the target client is no longer connected, then it will be redistributed.
/// </remarks>
public bool IsOwnershipDistributable => Ownership.HasFlag(OwnershipStatus.Distributable);
/// <summary>
/// When true, the <see cref="NetworkObject"/> can only be owned by the current Session Owner.
/// To set <see cref="OwnershipStatus.SessionOwner"/> during runtime, use <see cref="ChangeOwnership(ulong)"/> to ensure the session owner owns the object.
/// Once the session owner owns the object, then use <see cref="SetOwnershipStatus(OwnershipStatus, bool, OwnershipLockActions)"/>.
/// </summary>
public bool IsOwnershipSessionOwner => Ownership.HasFlag(OwnershipStatus.SessionOwner);
/// <summary>
/// Returns true if the <see cref="NetworkObject"/> is has ownership locked.
/// When locked, the <see cref="NetworkObject"/> cannot be redistributed nor can it be transferred by another client.
/// To toggle the ownership loked status during runtime, use <see cref="SetOwnershipLock(bool)"/>.
/// </summary>
public bool IsOwnershipLocked => ((OwnershipStatusExtended)Ownership).HasFlag(OwnershipStatusExtended.Locked);
/// <summary>
/// When true, the <see cref="NetworkObject"/>'s ownership can be acquired by any non-owner client.
/// To set <see cref="OwnershipStatus.Transferable"/> during runtime, use <see cref="SetOwnershipStatus(OwnershipStatus, bool, OwnershipLockActions)"/>.
/// </summary>
public bool IsOwnershipTransferable => Ownership.HasFlag(OwnershipStatus.Transferable);
/// <summary>
/// When true, the <see cref="NetworkObject"/>'s ownership can be acquired through non-owner client requesting ownership.
/// To set <see cref="OwnershipStatus.Transferable"/> during runtime, use <see cref="SetOwnershipStatus(OwnershipStatus, bool, OwnershipLockActions)"/>
/// To request ownership, use <see cref="RequestOwnership"/>.
/// </summary>
public bool IsOwnershipRequestRequired => Ownership.HasFlag(OwnershipStatus.RequestRequired);
/// <summary>
/// When true, the <see cref="NetworkObject"/>'s ownership cannot be acquired because an ownership request is underway.
/// In order for this status to be applied, the the <see cref="NetworkObject"/> must have the <see cref="OwnershipStatus.RequestRequired"/>
/// flag set and a non-owner client must have sent a request via <see cref="RequestOwnership"/>.
/// </summary>
public bool IsRequestInProgress => ((OwnershipStatusExtended)Ownership).HasFlag(OwnershipStatusExtended.Requested);
/// <summary>
/// Determines whether a NetworkObject can be distributed to other clients during
/// a <see cref="NetworkTopologyTypes.DistributedAuthority"/> session.
/// </summary>
#if !MULTIPLAYER_SERVICES_SDK_INSTALLED
[HideInInspector]
#endif
[SerializeField]
internal OwnershipStatus Ownership = OwnershipStatus.Distributable;
/// <summary>
/// Ownership status flags:
/// <see cref="None"/>: If nothing is set, then ownership is considered "static" and cannot be redistributed, requested, or transferred (i.e. a Player would have this).
/// <see cref="Distributable"/>: When set, this instance will be automatically redistributed when a client joins (if not locked or no request is pending) or leaves.
/// <see cref="Transferable"/>: When set, a non-owner can obtain ownership immediately (without requesting and as long as it is not locked).
/// <see cref="RequestRequired"/>: When set, a non-owner must request ownership from the owner (will always get locked once ownership is transferred).
/// <see cref="SessionOwner"/>: When set, only the current session owner may have ownership over this object.
/// <see cref="All"/>: Used within the inspector view only. When selected it will set the Distributable, Transferable, and RequestRequired flags or if those flags are already set it will select the SessionOwner flag by itself.
/// </summary>
// Ranges from 1 to 8 bits
[Flags]
public enum OwnershipStatus
{
/// <summary>
/// When set, this instance will have no permissions (i.e. cannot distribute, transfer, etc).
/// </summary>
None = 0,
/// <summary>
/// When set, this instance will be automatically redistributed when a client joins (if not locked or no request is pending) or leaves.
/// </summary>
Distributable = 1 << 0,
/// <summary>
/// When set, a non-owner can obtain ownership immediately (without requesting and as long as it is not locked).
/// </summary>
Transferable = 1 << 1,
/// <summary>
/// When set, a non-owner must request ownership from the owner (will always get locked once ownership is transferred).
/// </summary>
RequestRequired = 1 << 2,
/// <summary>
/// When set, only the current session owner may have ownership over this object.
/// </summary>
SessionOwner = 1 << 3,
/// <summary>
/// Used within the inspector view only. When selected it will set the Distributable, Transferable, and RequestRequired flags or if those flags are already set it will select the SessionOwner flag by itself.
/// </summary>
All = ~0,
}
/// <summary>
/// Intentionally internal
/// </summary>
// Ranges from 9 to 16 bits
[Flags]
internal enum OwnershipStatusExtended
{
// When locked and CanRequest is set, a non-owner can request ownership. If the owner responds by removing the Locked status, then ownership is transferred.
// If the owner responds by removing the Requested status only, then ownership is denied.
Requested = (1 << 8),
Locked = (1 << 9),
}
internal bool HasExtendedOwnershipStatus(OwnershipStatusExtended extended)
{
var extendedOwnership = (OwnershipStatusExtended)Ownership;
return extendedOwnership.HasFlag(extended);
}
internal void AddOwnershipExtended(OwnershipStatusExtended extended)
{
var extendedOwnership = (OwnershipStatusExtended)Ownership;
extendedOwnership |= extended;
Ownership = (OwnershipStatus)extendedOwnership;
}
internal void RemoveOwnershipExtended(OwnershipStatusExtended extended)
{
var extendedOwnership = (OwnershipStatusExtended)Ownership;
extendedOwnership &= ~extended;
Ownership = (OwnershipStatus)extendedOwnership;
}
/// <summary>
/// Distributed Authority Only
/// Locks ownership of a NetworkObject by the current owner.
/// </summary>
/// <param name="lockOwnership">defaults to lock (true) or unlock (false)</param>
/// <returns>true or false depending upon lock operation's success</returns>
public bool SetOwnershipLock(bool lockOwnership = true)
{
// If we are not in distributed autority mode, then exit early
if (!NetworkManager.DistributedAuthorityMode)
{
Debug.LogError($"[Feature Not Allowed In Client-Server Mode] Ownership flags are a distributed authority feature only!");
return false;
}
// If we don't have authority exit early
if (!HasAuthority)
{
NetworkLog.LogWarningServer($"[Attempted Lock Without Authority] Client-{NetworkManager.LocalClientId} is trying to lock ownership but does not have authority!");
return false;
}
// If we don't have the Transferable flag set and it is not a player object, then it is the same as having a static lock on ownership
if (!(IsOwnershipTransferable || IsPlayerObject) || IsOwnershipSessionOwner)
{
NetworkLog.LogWarning($"Trying to add or remove ownership lock on [{name}] which does not have the {nameof(OwnershipStatus.Transferable)} flag set!");
return false;
}
// If we are locking and are already locked or we are unlocking and are already unlocked exit early and return true
if (!(IsOwnershipLocked ^ lockOwnership))
{
return true;
}
if (lockOwnership)
{
AddOwnershipExtended(OwnershipStatusExtended.Locked);
}
else
{
RemoveOwnershipExtended(OwnershipStatusExtended.Locked);
}
SendOwnershipStatusUpdate();
return true;
}
/// <summary>
/// In the event of an immediate (local instance) failure to change ownership, the following ownership
/// permission failure status codes will be returned via <see cref="OnOwnershipPermissionsFailure"/>.
/// <see cref="Locked"/>: The <see cref="NetworkObject"/> is locked and ownership cannot be acquired.
/// <see cref="RequestRequired"/>: The <see cref="NetworkObject"/> requires an ownership request via <see cref="RequestOwnership"/>.
/// <see cref="RequestInProgress"/>: The <see cref="NetworkObject"/> is already processing an ownership request and ownership cannot be acquired at this time.
/// <see cref="NotTransferrable"/>: The <see cref="NetworkObject"/> does not have the <see cref="OwnershipStatus.Transferable"/> flag set and ownership cannot be acquired.
/// <see cref="SessionOwnerOnly"/>: The <see cref="NetworkObject"/> has the <see cref="OwnershipStatus.SessionOwner"/> flag set and ownership cannot be acquired.
/// </summary>
public enum OwnershipPermissionsFailureStatus
{
/// <summary>
/// The NetworkObject is locked and ownership cannot be acquired
/// </summary>
Locked,
/// <summary>
/// The NetworkObject requires an ownership request via RequestOwnership
/// </summary>
RequestRequired,
/// <summary>
/// The NetworkObject is already processing an ownership request and ownership cannot be acquired at this time
/// </summary>
RequestInProgress,
/// <summary>
/// The NetworkObject does not have the OwnershipStatus.Transferable flag set and ownership cannot be acquired
/// </summary>
NotTransferrable,
/// <summary>
/// The NetworkObject has the OwnershipStatus.SessionOwner flag set and ownership cannot be acquired
/// </summary>
SessionOwnerOnly
}
/// <summary>
/// <see cref="OnOwnershipPermissionsFailure"/>
/// </summary>
/// <param name="changeOwnershipFailure">The status indicating why the ownership change failed</param>
public delegate void OnOwnershipPermissionsFailureDelegateHandler(OwnershipPermissionsFailureStatus changeOwnershipFailure);
/// <summary>
/// If there is any callback assigned or subscriptions to this handler, then upon any ownership permissions failure that occurs during
/// the invocation of <see cref="ChangeOwnership(ulong)"/> will trigger this notification containing an <see cref="OwnershipPermissionsFailureStatus"/>.
/// </summary>
public OnOwnershipPermissionsFailureDelegateHandler OnOwnershipPermissionsFailure;
/// <summary>
/// Returned by <see cref="RequestOwnership"/> to signify w
/// <see cref="RequestSent"/>: The request for ownership was sent (does not mean it will be granted, but the request was sent).
/// <see cref="AlreadyOwner"/>: The current client is already the owner (no need to request ownership).
/// <see cref="RequestRequiredNotSet"/>: The <see cref="OwnershipStatus.RequestRequired"/> flag is not set on this <see cref="NetworkObject"/>
/// <see cref="Locked"/>: The current owner has locked ownership which means requests are not available at this time.
/// <see cref="RequestInProgress"/>: There is already a known request in progress. You can scan for ownership changes and try upon
/// <see cref="SessionOwnerOnly"/>: This object is marked as SessionOwnerOnly and therefore cannot be requested
/// a change in ownership or just try again after a specific period of time or no longer attempt to request ownership.
/// </summary>
public enum OwnershipRequestStatus
{
/// <summary>
/// The request for ownership was sent (does not mean it will be granted, but the request was sent)
/// </summary>
RequestSent,
/// <summary>
/// The current client is already the owner (no need to request ownership)
/// </summary>
AlreadyOwner,
/// <summary>
/// The OwnershipStatus.RequestRequired flag is not set on this NetworkObject
/// </summary>
RequestRequiredNotSet,
/// <summary>
/// The current owner has locked ownership which means requests are not available at this time
/// </summary>
Locked,
/// <summary>
/// There is already a known request in progress. You can scan for ownership changes and try again
/// after a specific period of time or no longer attempt to request ownership
/// </summary>
RequestInProgress,
/// <summary>
/// This object is marked as SessionOwnerOnly and therefore cannot be requested
/// </summary>
SessionOwnerOnly,
}
/// <summary>
/// Invoke this from a non-authority client to request ownership.
/// </summary>
/// <remarks>
/// The <see cref="OwnershipRequestStatus"/> results of requesting ownership:
/// <see cref="OwnershipRequestStatus.RequestSent"/>: The request for ownership was sent (does not mean it will be granted, but the request was sent).
/// <see cref="OwnershipRequestStatus.AlreadyOwner"/>: The current client is already the owner (no need to request ownership).
/// <see cref="OwnershipRequestStatus.RequestRequiredNotSet"/>: The <see cref="OwnershipStatus.RequestRequired"/> flag is not set on this <see cref="NetworkObject"/>
/// <see cref="OwnershipRequestStatus.Locked"/>: The current owner has locked ownership which means requests are not available at this time.
/// <see cref="OwnershipRequestStatus.RequestInProgress"/>: There is already a known request in progress. You can scan for ownership changes and try upon
/// <see cref="OwnershipRequestStatus.SessionOwnerOnly"/>: This object can only belong the the session owner and so cannot be requested
/// a change in ownership or just try again after a specific period of time or no longer attempt to request ownership.
/// </remarks>
/// <returns><see cref="OwnershipRequestStatus"/></returns>
public OwnershipRequestStatus RequestOwnership()
{
// Exit early the local client is already the owner
if (OwnerClientId == NetworkManager.LocalClientId)
{
return OwnershipRequestStatus.AlreadyOwner;
}
// Exit early if it doesn't have the RequestRequired flag
if (!IsOwnershipRequestRequired)
{
return OwnershipRequestStatus.RequestRequiredNotSet;
}
// Exit early if it is locked
if (IsOwnershipLocked)
{
return OwnershipRequestStatus.Locked;
}
// Exit early if there is already a request in progress
if (IsRequestInProgress)
{
return OwnershipRequestStatus.RequestInProgress;
}
// Exit early if it has the SessionOwner flag
if (IsOwnershipSessionOwner)
{
return OwnershipRequestStatus.SessionOwnerOnly;
}
// Otherwise, send the request ownership message
var changeOwnership = new ChangeOwnershipMessage
{
NetworkObjectId = NetworkObjectId,
OwnerClientId = OwnerClientId,
ClientIdCount = 1,
RequestClientId = NetworkManager.LocalClientId,
ClientIds = new ulong[1] { OwnerClientId },
DistributedAuthorityMode = true,
RequestOwnership = true,
OwnershipFlags = (ushort)Ownership,
};
var sendTarget = NetworkManager.DAHost ? OwnerClientId : NetworkManager.ServerClientId;
NetworkManager.ConnectionManager.SendMessage(ref changeOwnership, NetworkDelivery.Reliable, sendTarget);
return OwnershipRequestStatus.RequestSent;
}
/// <summary>
/// The delegate handler declaration used by <see cref="OnOwnershipRequested"/>.
/// </summary>
/// <param name="clientRequesting">The ClientId of the client requesting ownership</param>
/// <returns>True to approve the ownership request, false to deny the request and prevent ownership transfer</returns>
public delegate bool OnOwnershipRequestedDelegateHandler(ulong clientRequesting);
/// <summary>
/// The <see cref="OnOwnershipRequestedDelegateHandler"/> callback that can be used
/// to control when ownership can be transferred to a non-authority client.
/// </summary>
/// <remarks>
/// Requesting ownership requires the <see cref="Ownership"/> flags to have the <see cref="OwnershipStatus.RequestRequired"/> flag set.
/// </remarks>
public OnOwnershipRequestedDelegateHandler OnOwnershipRequested;
/// <summary>
/// Invoked by ChangeOwnershipMessage
/// </summary>
/// <param name="clientRequestingOwnership">the client requesting ownership</param>
internal void OwnershipRequest(ulong clientRequestingOwnership)
{
var response = OwnershipRequestResponseStatus.Approved;
// Do a last check to make sure this NetworkObject can be requested
// CMB-DANGO-TODO: We could help optimize this process and check the below flags on the service side.
// It wouldn't cover the scenario were an update was in-bound to the service from the owner, but it would
// handle the case where something had already changed and the service was already "aware" of the change.
if (IsOwnershipLocked)
{
response = OwnershipRequestResponseStatus.Locked;
}
else if (IsRequestInProgress)
{
response = OwnershipRequestResponseStatus.RequestInProgress;
}
else if (!(IsOwnershipRequestRequired || IsOwnershipTransferable) || IsOwnershipSessionOwner)
{
response = OwnershipRequestResponseStatus.CannotRequest;
}
// Finally, check to see if OnOwnershipRequested is registered and if user script is allowing
// this transfer of ownership
if (OnOwnershipRequested != null && !OnOwnershipRequested.Invoke(clientRequestingOwnership))
{
response = OwnershipRequestResponseStatus.Denied;
}
// If we made it here and the response is still approved, then change ownership
if (response == OwnershipRequestResponseStatus.Approved)
{
// When requested and approved, the owner immediately sets the Requested flag **prior to**
// changing the ownership. This prevents race conditions from happening.
// Until the ownership change has propagated out, requests can still flow through this owner,
// but by that time this owner's instance will have the extended Requested flag and will
// respond to any additional ownership request with OwnershipRequestResponseStatus.RequestInProgress.
AddOwnershipExtended(OwnershipStatusExtended.Requested);
// This action is always authorized as long as the client still has authority.
// We need to pass in that this is a request approval ownership change.
NetworkManager.SpawnManager.ChangeOwnership(this, clientRequestingOwnership, HasAuthority, true);
}
else
{
// Otherwise, send back the reason why the ownership request was denied for the clientRequestingOwnership
/// Notes:
/// We always apply the <see cref="NetworkManager.LocalClientId"/> as opposed to <see cref="OwnerClientId"/> to the
/// <see cref="ChangeOwnershipMessage.OwnerClientId"/> value as ownership could have changed and the denied requests
/// targeting this instance are because there is a request pending.
/// DANGO-TODO: What happens if the client requesting disconnects prior to responding with the update in request pending?
var changeOwnership = new ChangeOwnershipMessage
{
NetworkObjectId = NetworkObjectId,
OwnerClientId = NetworkManager.LocalClientId, // Always use the local clientId (see above notes)
RequestClientId = clientRequestingOwnership,
DistributedAuthorityMode = true,
RequestDenied = true,
OwnershipRequestResponseStatus = (byte)response,
OwnershipFlags = (ushort)Ownership,
};
var sendTarget = NetworkManager.DAHost ? clientRequestingOwnership : NetworkManager.ServerClientId;
NetworkManager.ConnectionManager.SendMessage(ref changeOwnership, NetworkDelivery.Reliable, sendTarget);
}
}
/// <summary>
/// What is returned via <see cref="OnOwnershipRequestResponse"/> after an ownership request has been sent via <see cref="RequestOwnership"/>
/// </summary>
public enum OwnershipRequestResponseStatus
{
/// <summary>
/// The ownership request was approved and the requesting client has gained ownership on the local instance
/// </summary>
Approved,
/// <summary>
/// The ownership request was denied because the object became locked after the request was sent
/// </summary>
Locked,
/// <summary>
/// The ownership request was denied because another request was already in progress when this request was received
/// </summary>
RequestInProgress,
/// <summary>
/// The ownership request was denied because the RequestRequired status changed while the request was in flight
/// </summary>
CannotRequest,
/// <summary>
/// The ownership request was denied by the authority instance (<see cref="OnOwnershipRequested"/> returned false)
/// </summary>
Denied,
}
/// <summary>
/// The delegate handler declaration used by <see cref="OnOwnershipRequestResponse"/>.
/// </summary>
/// <param name="ownershipRequestResponse">The status indicating whether the ownership request was approved or the reason for denial</param>
public delegate void OnOwnershipRequestResponseDelegateHandler(OwnershipRequestResponseStatus ownershipRequestResponse);
/// <summary>
/// The <see cref="OnOwnershipRequestedDelegateHandler"/> callback that can be used
/// to control when ownership can be transferred to a non-authority client.
/// </summary>
/// <remarks>
/// Requesting ownership requires the <see cref="Ownership"/> flags to have the <see cref="OwnershipStatus.RequestRequired"/> flag set.
/// </remarks>
public OnOwnershipRequestResponseDelegateHandler OnOwnershipRequestResponse;
/// <summary>
/// Invoked when a request is denied
/// </summary>
internal void OwnershipRequestResponse(OwnershipRequestResponseStatus ownershipRequestResponse)
{
OnOwnershipRequestResponse?.Invoke(ownershipRequestResponse);
}
/// <summary>
/// When passed as a parameter in <see cref="SetOwnershipStatus"/>, the following additional locking actions will occur:
/// - <see cref="None"/>: (default) No locking action
/// - <see cref="SetAndLock"/>: Will set the passed in flags and then lock the <see cref="NetworkObject"/>
/// - <see cref="SetAndUnlock"/>: Will set the passed in flags and then unlock the <see cref="NetworkObject"/>
/// </summary>
public enum OwnershipLockActions
{
/// <summary>
/// No additional locking action will be performed
/// </summary>
None,
/// <summary>
/// Sets the specified ownership flags and then locks the NetworkObject
/// </summary>
SetAndLock,
/// <summary>
/// Sets the specified ownership flags and then unlocks the NetworkObject
/// </summary>
SetAndUnlock
}
/// <summary>
/// Adds an <see cref="OwnershipStatus"/> flag to the <see cref="Ownership"/> flags
/// </summary>
/// <param name="status">flag(s) to update</param>
/// <param name="clearAndSet">defaults to false, but when true will clear the permissions and then set the permissions flags</param>
/// <param name="lockAction">defaults to <see cref="OwnershipLockActions.None"/>, but when set it to anther action type it will either lock or unlock ownership after setting the flags</param>
/// <returns>true (applied)/false (not applied)</returns>
/// <remarks>
/// If it returns false, then this means the flag(s) you are attempting to
/// set were already set on the <see cref="NetworkObject"/> instance.
/// If it returns true, then the flags were set and an ownership update message
/// was sent to all observers of the <see cref="NetworkObject"/> instance.
/// </remarks>
public bool SetOwnershipStatus(OwnershipStatus status, bool clearAndSet = false, OwnershipLockActions lockAction = OwnershipLockActions.None)
{
if (status.HasFlag(OwnershipStatus.SessionOwner) && !NetworkManager.LocalClient.IsSessionOwner)
{
NetworkLog.LogWarning("Only the session owner is allowed to set the ownership status to session owner only.");
return false;
}
// If it already has the flag do nothing
if (!clearAndSet && Ownership.HasFlag(status))
{
return false;
}
if (clearAndSet || status == OwnershipStatus.None)
{
Ownership = OwnershipStatus.None;
}
if (status.HasFlag(OwnershipStatus.SessionOwner))
{
Ownership = OwnershipStatus.SessionOwner;