quantum-space-buddies/QSB/AuthoritySync/AuthorityManager.cs

89 lines
2.1 KiB
C#
Raw Normal View History

2022-01-15 05:18:05 +00:00
using Mirror;
using QSB.Messaging;
2021-12-02 01:50:56 +00:00
using QSB.Utility;
2021-12-07 15:56:08 +00:00
using System.Collections.Generic;
2021-12-02 01:50:56 +00:00
namespace QSB.AuthoritySync;
public static class AuthorityManager
2021-12-02 01:50:56 +00:00
{
#region host only
2022-01-15 05:18:05 +00:00
/// <summary>
/// whoever is first gets authority
/// </summary>
private static readonly Dictionary<NetworkIdentity, List<uint>> _authQueue = new();
2022-01-15 05:18:05 +00:00
public static void RegisterAuthQueue(this NetworkIdentity identity) => _authQueue.Add(identity, new List<uint>());
public static void UnregisterAuthQueue(this NetworkIdentity identity) => _authQueue.Remove(identity);
public static void ServerUpdateAuthQueue(this NetworkIdentity identity, uint id, AuthQueueAction action)
{
var authQueue = _authQueue[identity];
var oldOwner = authQueue.Count != 0 ? authQueue[0] : uint.MaxValue;
2022-01-15 05:18:05 +00:00
switch (action)
2022-01-15 05:18:05 +00:00
{
case AuthQueueAction.Add:
authQueue.SafeAdd(id);
break;
case AuthQueueAction.Remove:
authQueue.Remove(id);
break;
case AuthQueueAction.Force:
authQueue.Remove(id);
authQueue.Insert(0, id);
break;
2022-01-15 05:18:05 +00:00
}
var newOwner = authQueue.Count != 0 ? authQueue[0] : uint.MaxValue;
if (oldOwner != newOwner)
2022-01-15 05:18:05 +00:00
{
SetAuthority(identity, newOwner);
2022-01-15 05:18:05 +00:00
}
}
2022-01-15 05:18:05 +00:00
/// <summary>
/// transfer authority to a different client
/// </summary>
public static void OnDisconnect(NetworkConnectionToClient conn)
{
var id = conn.GetPlayerId();
foreach (var identity in _authQueue.Keys)
2022-01-15 05:18:05 +00:00
{
identity.ServerUpdateAuthQueue(id, AuthQueueAction.Remove);
}
}
2022-01-15 05:18:05 +00:00
public static void SetAuthority(this NetworkIdentity identity, uint id)
{
var oldConn = identity.connectionToClient;
var newConn = id != uint.MaxValue ? id.GetNetworkConnection() : null;
2022-01-15 05:18:05 +00:00
if (oldConn == newConn)
{
return;
}
2022-01-15 05:18:05 +00:00
identity.RemoveClientAuthority();
2022-01-15 05:18:05 +00:00
if (newConn != null)
{
identity.AssignClientAuthority(newConn);
2022-01-15 05:18:05 +00:00
}
// DebugLog.DebugWrite($"{identity.NetId}:{identity.gameObject.name} - "
// + $"set authority to {id}");
}
2022-01-15 05:18:05 +00:00
#endregion
2022-01-15 05:18:05 +00:00
#region any client
2022-01-15 05:18:05 +00:00
public static void UpdateAuthQueue(this NetworkIdentity identity, AuthQueueAction action) =>
new AuthQueueMessage(identity.netId, action).Send();
#endregion
}