using FishNet.Documenting; using FishNet.Object; using FishNet.Serializing.Helping; using FishNet.Transporting; using System; using System.Collections.Generic; using UnityEngine; using UnityScene = UnityEngine.SceneManagement.Scene; namespace FishNet.Managing.Predicting { /// /// Additional options for managing the observer system. /// [DisallowMultipleComponent] [AddComponentMenu("FishNet/Manager/PredictionManager")] public sealed class PredictionManager : MonoBehaviour { #region Public. /// /// Called before performing a reconcile on NetworkBehaviour. /// public event Action OnPreReconcile; /// /// Called after performing a reconcile on a NetworkBehaviour. /// public event Action OnPostReconcile; /// /// Called before physics is simulated when replaying a replicate method. /// Contains the PhysicsScene and PhysicsScene2D which was simulated. /// public event Action OnPreReplicateReplay; /// /// Called after physics is simulated when replaying a replicate method. /// Contains the PhysicsScene and PhysicsScene2D which was simulated. /// public event Action OnPostReplicateReplay; /// /// Called before the server sends a reconcile. /// public event Action OnPreServerReconcile; /// /// Called after the server sends a reconcile. /// public event Action OnPostServerReconcile; /// /// Last tick any object reconciled. /// public uint LastReconcileTick { get; internal set; } /// /// Last tick any object replicated. /// public uint LastReplicateTick { get; internal set; } /// /// True if rigidbodies are being predicted. /// internal bool UsingRigidbodies => (_rigidbodies.Count > 0); /// /// Returns if any prediction is replaying. /// /// public bool IsReplaying() => _isReplaying; private bool _isReplaying; /// /// Returns if scene is replaying. /// /// /// public bool IsReplaying(UnityScene scene) => _replayingScenes.Contains(scene); #endregion #region Serialized. /// /// /// [Tooltip("True to drop replicates from clients which are being received excessively. This can help with attacks but may cause client to temporarily desynchronize during connectivity issues. When false the server will hold at most up to 3 seconds worth of replicates, consuming multiple per tick to clear out the buffer quicker. This is good to ensure all inputs are executed but potentially could allow speed hacking.")] [SerializeField] private bool _dropExcessiveReplicates = true; /// /// True to drop replicates from clients which are being received excessively. This can help with attacks but may cause client to temporarily desynchronize during connectivity issues. /// When false the server will hold at most up to 3 seconds worth of replicates, consuming multiple per tick to clear out the buffer quicker. This is good to ensure all inputs are executed but potentially could allow speed hacking. /// internal bool DropExcessiveReplicates => _dropExcessiveReplicates; /// /// /// [Tooltip("Maximum number of replicates a server can queue per object. Higher values will put more load on the server and add replicate latency for the client.")] [SerializeField] private ushort _maximumServerReplicates = 15; /// /// Maximum number of replicates a server can queue per object. Higher values will put more load on the server and add replicate latency for the client. /// public ushort GetMaximumServerReplicates() => _maximumServerReplicates; /// /// Sets the maximum number of replicates a server can queue per object. /// /// public void SetMaximumServerReplicates(ushort value) { _maximumServerReplicates = (ushort)Mathf.Clamp(value, MINIMUM_REPLICATE_QUEUE_SIZE, MAXIMUM_REPLICATE_QUEUE_SIZE); } /// /// /// [Tooltip("Maximum number of excessive replicates which can be consumed per tick. Consumption count will scale up to this value automatically.")] [SerializeField] private byte _maximumConsumeCount = 4; /// /// Maximum number of excessive replicates which can be consumed per tick. Consumption count will scale up to this value automatically. /// internal byte GetMaximumConsumeCount() => _maximumConsumeCount; /// /// /// [Tooltip("Maximum number of past inputs which may send.")] [Range(MINIMUM_PAST_INPUTS, MAXIMUM_PAST_INPUTS)] [SerializeField] private byte _redundancyCount = 3; /// /// Maximum number of past inputs which may send and resend redundancy. /// #if UNITY_WEBGL //WebGL uses reliable so no reason to use redundancy. internal byte GetRedundancyCount() => 1; #else internal byte GetRedundancyCount() => _redundancyCount; #endif /// /// True to allow clients to use predicted spawning. While true, each NetworkObject prefab you wish to predicted spawn must be marked as to allow this feature. /// internal bool GetAllowPredictedSpawning() => _allowPredictedSpawning; [Tooltip("True to allow clients to use predicted spawning and despawning. While true, each NetworkObject prefab you wish to predicted spawn must be marked as to allow this feature.")] [SerializeField] private bool _allowPredictedSpawning = false; /// /// /// [Tooltip("Maximum number of Ids to reserve on clients for predicted spawning. Higher values will allow clients to send more predicted spawns per second but may reduce availability of ObjectIds with high player counts.")] [Range(1, 100)] [SerializeField] private byte _reservedObjectIds = 15; /// /// Maximum number of Ids to reserve on clients for predicted spawning. Higher values will allow clients to send more predicted spawns per second but may reduce availability of ObjectIds with high player counts. /// /// internal byte GetReservedObjectIds() => _reservedObjectIds; #endregion #region Private. /// /// Number of active predicted rigidbodies. /// [System.NonSerialized] private HashSet _rigidbodies = new HashSet(); /// /// Cache to remove null entries from _rigidbodies. /// [System.NonSerialized] private HashSet _componentCache = new HashSet(); /// /// NetworkManager used with this. /// private NetworkManager _networkManager; /// /// Scenes which are currently replaying prediction. /// private HashSet _replayingScenes = new HashSet(new SceneHandleEqualityComparer()); #endregion #region Const. /// /// Minimum number of past inputs which can be sent. /// private const byte MINIMUM_PAST_INPUTS = 2; /// /// Maximum number of past inputs which can be sent. /// internal const byte MAXIMUM_PAST_INPUTS = 15; /// /// Minimum amount of replicate queue size. /// private const ushort MINIMUM_REPLICATE_QUEUE_SIZE = 10; /// /// Maxmimum amount of replicate queue size. /// private const ushort MAXIMUM_REPLICATE_QUEUE_SIZE = 500; #endregion private void OnEnable() { UnityEngine.SceneManagement.SceneManager.sceneUnloaded += SceneManager_sceneUnloaded; } private void OnDisable() { UnityEngine.SceneManagement.SceneManager.sceneUnloaded -= SceneManager_sceneUnloaded; } internal void InitializeOnce_Internal(NetworkManager manager) { _networkManager = manager; _networkManager.ClientManager.OnClientConnectionState += ClientManager_OnClientConnectionState; } /// /// Called after the local client connection state changes. /// private void ClientManager_OnClientConnectionState(ClientConnectionStateArgs obj) { if (obj.ConnectionState != LocalConnectionState.Started) _replayingScenes.Clear(); _isReplaying = false; } /// /// Called before and after server sends a reconcile. /// /// True if before the reconcile is sent. internal void InvokeServerReconcile(NetworkBehaviour caller, bool before) { if (before) OnPreServerReconcile?.Invoke(caller); else OnPostServerReconcile?.Invoke(caller); } /// /// Increases Rigidbodies count by 1. /// [APIExclude] public void AddRigidbodyCount(UnityEngine.Component c) { _rigidbodies.Add(c); } /// /// Dencreases Rigidbodies count by 1. /// [APIExclude] public void RemoveRigidbodyCount(UnityEngine.Component c) { bool removed = _rigidbodies.Remove(c); /* If remove failed the rigidbodies may need to be rebuild. * This might happen when an object is destroyed as * the referenced is passed. Could be any number of things * but it seems to occur frequently enough in Unity, * especially when testing in editor. * * This operation is not ideal in the hot path but * the odds of it happening are pretty slim and * it ensures stability against user error. */ if (!removed) { //Cannt remove null entries from a hashset so have to rebuild. _componentCache.Clear(); foreach (UnityEngine.Component item in _rigidbodies) { if (item != null) _componentCache.Add(item); } //Apply to rigidbodies. _rigidbodies.Clear(); foreach (UnityEngine.Component item in _componentCache) _rigidbodies.Add(item); } } /// /// Invokes OnPre/PostReconcile events. /// Internal use. /// [APIExclude] [CodegenMakePublic] //To internal. public void InvokeOnReconcile_Internal(NetworkBehaviour nb, bool before) { nb.IsReconciling = before; if (before) OnPreReconcile?.Invoke(nb); else OnPostReconcile?.Invoke(nb); } /// /// Invokes OnReplicateReplay. /// Internal use. /// [APIExclude] [CodegenMakePublic] //To internal. public void InvokeOnReplicateReplay_Internal(UnityScene scene, uint tick, PhysicsScene ps, PhysicsScene2D ps2d, bool before) { _isReplaying = before; if (before) { _replayingScenes.Add(scene); OnPreReplicateReplay?.Invoke(tick, ps, ps2d); } else { _replayingScenes.Remove(scene); OnPostReplicateReplay?.Invoke(tick, ps, ps2d); } } /// /// Called when a scene unloads. /// /// private void SceneManager_sceneUnloaded(UnityScene s) { _replayingScenes.Remove(s); } } }