multiplayer refactor
This commit is contained in:
@@ -1,68 +0,0 @@
|
||||
using RebootKit.Engine.Foundation;
|
||||
using RebootKit.Engine.Simulation;
|
||||
using Unity.Netcode;
|
||||
|
||||
namespace RebootKit.Engine.Main {
|
||||
public abstract class NetworkPlayerController : NetworkBehaviour {
|
||||
static readonly Logger s_Logger = new Logger(nameof(NetworkPlayerController));
|
||||
|
||||
public Actor PossessedActor { get; private set; }
|
||||
|
||||
public void PossessActor(Actor actor) {
|
||||
if (!IsServer) {
|
||||
s_Logger.Error("PossessActor can only be called on the server.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (actor == null) {
|
||||
s_Logger.Error("Cannot possess a null actor.");
|
||||
return;
|
||||
}
|
||||
|
||||
PossessActorRpc(actor.ActorID, RpcTarget.Everyone);
|
||||
}
|
||||
|
||||
[Rpc(SendTo.SpecifiedInParams)]
|
||||
void PossessActorRpc(ulong actorID, RpcParams rpcParams) {
|
||||
Actor actor = RR.FindSpawnedActor(actorID);
|
||||
if (actor == null) {
|
||||
s_Logger.Error($"Actor with ID {actorID} not found.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (PossessedActor is not null) {
|
||||
OnUnpossessActor(PossessedActor);
|
||||
}
|
||||
|
||||
PossessedActor = actor;
|
||||
OnPossessActor(actor);
|
||||
}
|
||||
|
||||
public void UnPossessActor() {
|
||||
if (!IsServer) {
|
||||
s_Logger.Error("UnPossessActor can only be called on the server.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (PossessedActor == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
UnPossessActorRpc(RpcTarget.Everyone);
|
||||
}
|
||||
|
||||
[Rpc(SendTo.SpecifiedInParams)]
|
||||
void UnPossessActorRpc(RpcParams rpcParams) {
|
||||
if (PossessedActor is not null) {
|
||||
OnUnpossessActor(PossessedActor);
|
||||
PossessedActor = null;
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void OnPossessActor(Actor actor) {
|
||||
}
|
||||
|
||||
protected virtual void OnUnpossessActor(Actor actor) {
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2010b0aabd68415bb4aea2846d2c59b1
|
||||
timeCreated: 1751208839
|
||||
@@ -1,273 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
using Cysharp.Threading.Tasks;
|
||||
using NUnit.Framework;
|
||||
using RebootKit.Engine.Simulation;
|
||||
using Unity.Collections;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
using Logger = RebootKit.Engine.Foundation.Logger;
|
||||
|
||||
namespace RebootKit.Engine.Main {
|
||||
enum NetworkClientSyncState {
|
||||
NotReady,
|
||||
LoadingWorld,
|
||||
PreparingForActorsSync,
|
||||
SyncingActors,
|
||||
Ready
|
||||
}
|
||||
|
||||
struct NetworkClientState : INetworkSerializable {
|
||||
public ulong ClientID;
|
||||
public NetworkClientSyncState SyncState;
|
||||
public int ActorsSyncPacketsLeft;
|
||||
|
||||
public bool IsReady {
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
get {
|
||||
return SyncState == NetworkClientSyncState.Ready;
|
||||
}
|
||||
}
|
||||
|
||||
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter {
|
||||
serializer.SerializeValue(ref ClientID);
|
||||
serializer.SerializeValue(ref SyncState);
|
||||
serializer.SerializeValue(ref ActorsSyncPacketsLeft);
|
||||
}
|
||||
}
|
||||
|
||||
public class NetworkSystem : NetworkBehaviour {
|
||||
static readonly Logger s_Logger = new Logger(nameof(NetworkSystem));
|
||||
|
||||
[field: SerializeField] public ActorsManager Actors { get; private set; }
|
||||
|
||||
internal readonly Dictionary<ulong, NetworkClientState> Clients = new Dictionary<ulong, NetworkClientState>();
|
||||
|
||||
public FixedString512Bytes WorldID { get; private set; } = new FixedString512Bytes("");
|
||||
bool m_IsChangingWorld = false;
|
||||
|
||||
public ulong LocalClientID {
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
get {
|
||||
return NetworkManager.Singleton.LocalClientId;
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// @MARK: Unity callbacks
|
||||
//
|
||||
void Awake() {
|
||||
RR.NetworkSystemInstance = this;
|
||||
}
|
||||
|
||||
//
|
||||
// @MARK: NetworkBehaviour callbacks
|
||||
//
|
||||
public override void OnNetworkSpawn() {
|
||||
base.OnNetworkSpawn();
|
||||
|
||||
NetworkManager.Singleton.OnClientConnectedCallback += OnClientConnected;
|
||||
NetworkManager.Singleton.OnClientDisconnectCallback += OnClientDisconnect;
|
||||
}
|
||||
|
||||
public override void OnNetworkDespawn() {
|
||||
base.OnNetworkDespawn();
|
||||
|
||||
NetworkManager.Singleton.OnClientConnectedCallback -= OnClientConnected;
|
||||
NetworkManager.Singleton.OnClientDisconnectCallback -= OnClientDisconnect;
|
||||
}
|
||||
|
||||
void OnClientConnected(ulong clientID) {
|
||||
if (!IsServer) {
|
||||
return;
|
||||
}
|
||||
|
||||
s_Logger.Info($"OnClientConnected: {clientID}");
|
||||
|
||||
NetworkClientState newClientState = new NetworkClientState {
|
||||
ClientID = clientID,
|
||||
SyncState = NetworkClientSyncState.NotReady
|
||||
};
|
||||
Clients.Add(clientID, newClientState);
|
||||
|
||||
if (clientID != NetworkManager.Singleton.LocalClientId) {
|
||||
foreach (NetworkClientState state in Clients.Values) {
|
||||
UpdateClientStateRpc(state, RpcTarget.Single(clientID, RpcTargetUse.Temp));
|
||||
}
|
||||
}
|
||||
|
||||
if (!WorldID.IsEmpty) {
|
||||
s_Logger.Info($"Synchronizing world load for client {clientID} with world ID '{WorldID}'");
|
||||
ClientLoadWorldRpc(WorldID.ToString(), RpcTarget.Single(clientID, RpcTargetUse.Temp));
|
||||
}
|
||||
}
|
||||
|
||||
void OnClientDisconnect(ulong clientID) {
|
||||
s_Logger.Info($"OnClientDisconnect: {clientID}");
|
||||
Clients.Remove(clientID);
|
||||
}
|
||||
|
||||
//
|
||||
// @MARK: Server API
|
||||
//
|
||||
public void KickClient(ulong clientID, string reason = "Kicked by server") {
|
||||
if (!IsServer) {
|
||||
s_Logger.Error("Only server can kick clients.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (NetworkManager.Singleton.ConnectedClients.TryGetValue(clientID, out NetworkClient client)) {
|
||||
NetworkManager.Singleton.DisconnectClient(clientID, reason);
|
||||
s_Logger.Info($"Kicked client {clientID}: {reason}");
|
||||
} else {
|
||||
s_Logger.Error($"Client {clientID} not found.");
|
||||
}
|
||||
}
|
||||
|
||||
public void SetCurrentWorld(string worldID) {
|
||||
if (!IsServer) {
|
||||
s_Logger.Error("Only server can set the current world.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (m_IsChangingWorld) {
|
||||
s_Logger.Error($"Already changing world to '{WorldID}'. Please wait until the current world change is complete.");
|
||||
return;
|
||||
}
|
||||
|
||||
WorldConfigAsset worldConfigAsset = RR.GetWorldConfigAsset(worldID);
|
||||
if (worldConfigAsset is null) {
|
||||
s_Logger.Error($"Failed to set current world: World config asset for '{worldID}' not found.");
|
||||
return;
|
||||
}
|
||||
|
||||
WorldID = worldID;
|
||||
|
||||
foreach ((ulong _, NetworkClientState clientState) in Clients.ToList()) {
|
||||
NetworkClientState state = clientState;
|
||||
state.SyncState = NetworkClientSyncState.LoadingWorld;
|
||||
UpdateClientState(state);
|
||||
}
|
||||
|
||||
ServerLoadWorldAsync(worldConfigAsset, destroyCancellationToken).Forget();
|
||||
}
|
||||
|
||||
async UniTask ServerLoadWorldAsync(WorldConfigAsset asset, CancellationToken cancellationToken) {
|
||||
s_Logger.Info($"ServerLoadWorldAsync: {asset.Config.name}");
|
||||
|
||||
m_IsChangingWorld = true;
|
||||
|
||||
RR.World.Unload();
|
||||
RR.CloseMainMenu();
|
||||
|
||||
await RR.World.LoadAsync(asset.Config, cancellationToken);
|
||||
|
||||
m_IsChangingWorld = false;
|
||||
|
||||
if (!TryGetClientState(NetworkManager.Singleton.LocalClientId, out NetworkClientState localClientState)) {
|
||||
s_Logger.Error($"Local client state not found for client ID {NetworkManager.Singleton.LocalClientId}.");
|
||||
RR.Disconnect();
|
||||
return;
|
||||
}
|
||||
|
||||
localClientState.SyncState = NetworkClientSyncState.Ready;
|
||||
UpdateClientState(localClientState);
|
||||
|
||||
RR.GameInstance.PlayerBecameReady(localClientState.ClientID);
|
||||
|
||||
ClientLoadWorldRpc(asset.name, RpcTarget.NotMe);
|
||||
}
|
||||
|
||||
[Rpc(SendTo.SpecifiedInParams, Delivery = RpcDelivery.Reliable)]
|
||||
void ClientLoadWorldRpc(string worldID, RpcParams rpcParams) {
|
||||
WorldConfigAsset worldConfigAsset = RR.GetWorldConfigAsset(worldID);
|
||||
if (worldConfigAsset is null) {
|
||||
s_Logger.Error($"World config asset for '{worldID}' not found.");
|
||||
RR.Disconnect();
|
||||
return;
|
||||
}
|
||||
|
||||
ClientLoadWorldAsync(worldID, destroyCancellationToken).Forget();
|
||||
}
|
||||
|
||||
async UniTask ClientLoadWorldAsync(string worldID, CancellationToken cancellationToken) {
|
||||
s_Logger.Info($"ClientLoadWorldAsync: {worldID}");
|
||||
|
||||
WorldConfigAsset worldConfigAsset = RR.GetWorldConfigAsset(worldID);
|
||||
if (worldConfigAsset is null) {
|
||||
s_Logger.Error($"World config asset for '{worldID}' not found.");
|
||||
return;
|
||||
}
|
||||
|
||||
RR.World.Unload();
|
||||
RR.CloseMainMenu();
|
||||
|
||||
await RR.World.LoadAsync(worldConfigAsset.Config, cancellationToken);
|
||||
|
||||
WorldID = worldID;
|
||||
ClientLoadedWorldRpc(worldID);
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Server, Delivery = RpcDelivery.Reliable)]
|
||||
void ClientLoadedWorldRpc(string worldID, RpcParams rpcParams = default) {
|
||||
ulong clientID = rpcParams.Receive.SenderClientId;
|
||||
|
||||
if (!WorldID.Equals(worldID)) {
|
||||
s_Logger.Error($"Client {clientID} tried to load world '{worldID}', but server is in world '{WorldID}'.");
|
||||
NetworkManager.Singleton.DisconnectClient(clientID, "World mismatch!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (Clients.TryGetValue(clientID, out NetworkClientState clientState)) {
|
||||
Actors.InitializeActorsForClient(clientID);
|
||||
} else {
|
||||
NetworkManager.Singleton.DisconnectClient(clientID, "Client is not registered!");
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// @MARK: Internal
|
||||
//
|
||||
internal bool TryGetClientState(ulong clientID, out NetworkClientState clientState) {
|
||||
return Clients.TryGetValue(clientID, out clientState);
|
||||
}
|
||||
|
||||
internal void UpdateClientState(NetworkClientState clientState) {
|
||||
if (!IsServer) {
|
||||
s_Logger.Error("UpdateClientState can only be called on the server.");
|
||||
return;
|
||||
}
|
||||
|
||||
Clients[clientState.ClientID] = clientState;
|
||||
UpdateClientStateRpc(clientState, RpcTarget.NotServer);
|
||||
}
|
||||
|
||||
[Rpc(SendTo.SpecifiedInParams, Delivery = RpcDelivery.Reliable)]
|
||||
void UpdateClientStateRpc(NetworkClientState newState, RpcParams rpcParams) {
|
||||
Clients[newState.ClientID] = newState;
|
||||
}
|
||||
|
||||
internal void ClientSynchronizedActors(ulong clientID) {
|
||||
if (TryGetClientState(clientID, out NetworkClientState state)) {
|
||||
state.SyncState = NetworkClientSyncState.Ready;
|
||||
UpdateClientState(state);
|
||||
|
||||
RR.GameInstance.PlayerBecameReady(clientID);
|
||||
} else {
|
||||
s_Logger.Error($"Client state for {clientID} not found.");
|
||||
}
|
||||
}
|
||||
|
||||
internal int GetReadyClientsCount() {
|
||||
int count = 0;
|
||||
foreach (NetworkClientState clientState in Clients.Values) {
|
||||
if (clientState.IsReady) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 1f967d37c17e4704b80849c305a53be9
|
||||
timeCreated: 1751411566
|
||||
@@ -1,6 +0,0 @@
|
||||
using Unity.Netcode;
|
||||
|
||||
namespace RebootKit.Engine.Main {
|
||||
public abstract class NetworkWorldController : NetworkBehaviour {
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: edd521a69a6f4e43b97ec258adf499a6
|
||||
timeCreated: 1751377120
|
||||
@@ -7,6 +7,7 @@ using R3;
|
||||
using RebootKit.Engine.Console;
|
||||
using RebootKit.Engine.Foundation;
|
||||
using RebootKit.Engine.Input;
|
||||
using RebootKit.Engine.Network;
|
||||
using RebootKit.Engine.Simulation;
|
||||
using RebootKit.Engine.Steam;
|
||||
using Unity.Netcode;
|
||||
@@ -26,19 +27,16 @@ namespace RebootKit.Engine.Main {
|
||||
static readonly Logger s_Logger = new Logger("RR");
|
||||
|
||||
[ConfigVar("con.write_log", 1, "Enables writing game log to console output")]
|
||||
static ConfigVar s_writeLogToConsole;
|
||||
|
||||
[ConfigVar("sv.tick_rate", 24, "Server tick rate in Hz")]
|
||||
public static ConfigVar TickRate;
|
||||
|
||||
static ConfigVar s_WriteLogToConsole;
|
||||
|
||||
internal static EngineConfigAsset EngineConfig;
|
||||
|
||||
static DisposableBag s_disposableBag;
|
||||
static DisposableBag s_servicesBag;
|
||||
static DisposableBag s_DisposableBag;
|
||||
static DisposableBag s_ServicesBag;
|
||||
|
||||
static AsyncOperationHandle<SceneInstance> s_mainMenuSceneHandle;
|
||||
static AsyncOperationHandle<SceneInstance> s_MainMenuSceneHandle;
|
||||
|
||||
static NetworkSystem s_networkSystemPrefab;
|
||||
static NetworkSystem s_NetworkSystemPrefab;
|
||||
internal static NetworkSystem NetworkSystemInstance;
|
||||
|
||||
internal static ConsoleService Console { get; private set; }
|
||||
@@ -49,10 +47,6 @@ namespace RebootKit.Engine.Main {
|
||||
|
||||
public static Game GameInstance { get; internal set; }
|
||||
|
||||
public static ulong TickCount { get; private set; }
|
||||
public static event Action<ulong> ServerTick = delegate { };
|
||||
public static event Action ClientTick = delegate { };
|
||||
|
||||
// Lifecycle API
|
||||
|
||||
// @NOTE: This method is called at the very start of the game, when boot scene loaded.
|
||||
@@ -62,13 +56,13 @@ namespace RebootKit.Engine.Main {
|
||||
EngineConfig = configAsset;
|
||||
|
||||
s_Logger.Info("Initializing");
|
||||
s_servicesBag = new DisposableBag();
|
||||
s_disposableBag = new DisposableBag();
|
||||
s_ServicesBag = new DisposableBag();
|
||||
s_DisposableBag = new DisposableBag();
|
||||
|
||||
s_Logger.Info("Registering core services");
|
||||
Console = CreateService<ConsoleService>();
|
||||
Input = new InputService(EngineConfig.inputConfig);
|
||||
s_servicesBag.Add(Input);
|
||||
s_ServicesBag.Add(Input);
|
||||
World = CreateService<WorldService>();
|
||||
|
||||
await InitializeAssetsAsync(cancellationToken);
|
||||
@@ -80,7 +74,7 @@ namespace RebootKit.Engine.Main {
|
||||
|
||||
// @NOTE: This method is called after the main scene is loaded.
|
||||
internal static async UniTask RunAsync(CancellationToken cancellationToken) {
|
||||
s_networkSystemPrefab =
|
||||
s_NetworkSystemPrefab =
|
||||
Resources.Load<NetworkSystem>(RConsts.k_CoreNetworkGameSystemsResourcesPath);
|
||||
|
||||
NetworkManager.Singleton.OnConnectionEvent += OnConnectionEvent;
|
||||
@@ -97,7 +91,7 @@ namespace RebootKit.Engine.Main {
|
||||
|
||||
Observable.EveryUpdate()
|
||||
.Subscribe(_ => Tick())
|
||||
.AddTo(ref s_disposableBag);
|
||||
.AddTo(ref s_DisposableBag);
|
||||
|
||||
await OpenMainMenuAsync(cancellationToken);
|
||||
|
||||
@@ -133,8 +127,8 @@ namespace RebootKit.Engine.Main {
|
||||
SteamManager.Shutdown();
|
||||
#endif
|
||||
|
||||
s_servicesBag.Dispose();
|
||||
s_disposableBag.Dispose();
|
||||
s_ServicesBag.Dispose();
|
||||
s_DisposableBag.Dispose();
|
||||
}
|
||||
|
||||
// Assets API
|
||||
@@ -176,16 +170,16 @@ namespace RebootKit.Engine.Main {
|
||||
return;
|
||||
}
|
||||
|
||||
s_mainMenuSceneHandle = Addressables.LoadSceneAsync(EngineConfig.mainMenuScene, LoadSceneMode.Additive);
|
||||
await s_mainMenuSceneHandle;
|
||||
s_MainMenuSceneHandle = Addressables.LoadSceneAsync(EngineConfig.mainMenuScene, LoadSceneMode.Additive);
|
||||
await s_MainMenuSceneHandle;
|
||||
}
|
||||
|
||||
internal static void CloseMainMenu() {
|
||||
if (!s_mainMenuSceneHandle.IsValid()) {
|
||||
if (!s_MainMenuSceneHandle.IsValid()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Addressables.UnloadSceneAsync(s_mainMenuSceneHandle);
|
||||
Addressables.UnloadSceneAsync(s_MainMenuSceneHandle);
|
||||
}
|
||||
|
||||
public static void SetServerWorld(string worldID) {
|
||||
@@ -253,13 +247,13 @@ namespace RebootKit.Engine.Main {
|
||||
}
|
||||
|
||||
TService service = asset.Create();
|
||||
s_servicesBag.Add(service);
|
||||
s_ServicesBag.Add(service);
|
||||
return service;
|
||||
}
|
||||
|
||||
public static TService CreateService<TService>() where TService : class, IService {
|
||||
TService service = Activator.CreateInstance<TService>();
|
||||
s_servicesBag.Add(service);
|
||||
s_ServicesBag.Add(service);
|
||||
return service;
|
||||
}
|
||||
|
||||
@@ -382,28 +376,8 @@ namespace RebootKit.Engine.Main {
|
||||
|
||||
GameInstance.SendChatMessageRpc(message);
|
||||
}
|
||||
|
||||
static float s_tickTimer;
|
||||
|
||||
|
||||
static void Tick() {
|
||||
float deltaTime = Time.deltaTime;
|
||||
|
||||
float minTickTime = 1.0f / TickRate.IndexValue;
|
||||
s_tickTimer += deltaTime;
|
||||
|
||||
while (s_tickTimer >= minTickTime) {
|
||||
s_tickTimer -= minTickTime;
|
||||
|
||||
if (IsServer()) {
|
||||
ServerTick?.Invoke(TickCount);
|
||||
}
|
||||
|
||||
if (IsClient()) {
|
||||
ClientTick?.Invoke();
|
||||
}
|
||||
|
||||
TickCount++;
|
||||
}
|
||||
}
|
||||
|
||||
static void OnConnectionEvent(NetworkManager network, ConnectionEventData data) {
|
||||
@@ -416,7 +390,7 @@ namespace RebootKit.Engine.Main {
|
||||
GameInstance = Object.Instantiate(EngineConfig.gamePrefab);
|
||||
GameInstance.NetworkObject.Spawn();
|
||||
|
||||
NetworkSystemInstance = Object.Instantiate(s_networkSystemPrefab);
|
||||
NetworkSystemInstance = Object.Instantiate(s_NetworkSystemPrefab);
|
||||
NetworkSystemInstance.NetworkObject.Spawn();
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user