adding multiplayer
This commit is contained in:
@@ -35,8 +35,12 @@ namespace RebootKit.Engine.Main {
|
||||
static async UniTask RunAsync(CancellationToken cancellationToken) {
|
||||
ConfigVarsContainer.Init();
|
||||
|
||||
// We are loading the boot scene only in the editor.
|
||||
// In the player, we assume that the boot scene is already loaded.
|
||||
#if UNITY_EDITOR
|
||||
s_logger.Info("Loading boot scene");
|
||||
SceneManager.LoadScene(RConsts.k_BootSceneBuildIndex, LoadSceneMode.Single);
|
||||
#endif
|
||||
|
||||
s_logger.Info("Loading engine config");
|
||||
EngineConfigAsset configAsset = Resources.Load<EngineConfigAsset>(RConsts.k_EngineConfigResourcesPath);
|
||||
@@ -53,10 +57,11 @@ namespace RebootKit.Engine.Main {
|
||||
await RR.InitAsync(configAsset, cancellationToken);
|
||||
|
||||
s_logger.Info("Loading main scene");
|
||||
await SceneManager.LoadSceneAsync(RConsts.k_MainSceneBuildIndex, LoadSceneMode.Single).ToUniTask(cancellationToken: cancellationToken);
|
||||
await SceneManager.LoadSceneAsync(RConsts.k_MainSceneBuildIndex, LoadSceneMode.Single)
|
||||
.ToUniTask(cancellationToken: cancellationToken);
|
||||
|
||||
s_logger.Info("Starting RR");
|
||||
RR.Run();
|
||||
await RR.RunAsync(cancellationToken);
|
||||
|
||||
await UniTask.WaitUntilCanceled(Application.exitCancellationToken);
|
||||
|
||||
|
||||
78
Runtime/Engine/Code/Main/Game.cs
Normal file
78
Runtime/Engine/Code/Main/Game.cs
Normal file
@@ -0,0 +1,78 @@
|
||||
using System;
|
||||
using Cysharp.Threading.Tasks;
|
||||
using RebootKit.Engine.Services.Simulation;
|
||||
using Unity.Collections;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
using Logger = RebootKit.Engine.Foundation.Logger;
|
||||
|
||||
namespace RebootKit.Engine.Main {
|
||||
public abstract class Game : NetworkBehaviour {
|
||||
static readonly Logger s_GameLogger = new Logger(nameof(Game));
|
||||
|
||||
protected NetworkVariable<FixedString128Bytes> m_CurrentWorldID =
|
||||
new NetworkVariable<FixedString128Bytes>(new FixedString128Bytes(""));
|
||||
|
||||
// Event callbacks
|
||||
public virtual void OnWorldLoaded() {
|
||||
}
|
||||
|
||||
public virtual void OnWorldUnload() {
|
||||
}
|
||||
|
||||
public virtual void OnChatMessage(string message) {
|
||||
s_GameLogger.Info($"Chat: {message}");
|
||||
}
|
||||
|
||||
// Network
|
||||
public override void OnNetworkSpawn() {
|
||||
base.OnNetworkSpawn();
|
||||
RR.GameInstance = this;
|
||||
|
||||
m_CurrentWorldID.OnValueChanged += OnCurrentWorldIDChanged;
|
||||
LoadWorld(m_CurrentWorldID.Value.Value);
|
||||
}
|
||||
|
||||
public override void OnNetworkDespawn() {
|
||||
base.OnNetworkDespawn();
|
||||
|
||||
m_CurrentWorldID.OnValueChanged -= OnCurrentWorldIDChanged;
|
||||
RR.GameInstance = null;
|
||||
}
|
||||
|
||||
[ServerRpc]
|
||||
public void SetCurrentWorldServerRpc(string worldID) {
|
||||
m_CurrentWorldID.Value = new FixedString128Bytes(worldID);
|
||||
}
|
||||
|
||||
// Chat
|
||||
[Rpc(SendTo.Server)]
|
||||
public void SendChatMessageRpc(string message) {
|
||||
PrintChatMessageClientRpc(message);
|
||||
}
|
||||
|
||||
[ClientRpc(Delivery = RpcDelivery.Reliable)]
|
||||
void PrintChatMessageClientRpc(string message) {
|
||||
OnChatMessage(message);
|
||||
}
|
||||
|
||||
void OnCurrentWorldIDChanged(FixedString128Bytes previousValue, FixedString128Bytes newValue) {
|
||||
string worldID = newValue.Value;
|
||||
LoadWorld(worldID);
|
||||
}
|
||||
|
||||
void LoadWorld(string worldID) {
|
||||
if (string.IsNullOrEmpty(worldID)) {
|
||||
RR.World.Unload();
|
||||
} else {
|
||||
WorldConfigAsset worldConfigAsset = RR.GetWorldConfigAsset(worldID);
|
||||
if (worldConfigAsset is not null) {
|
||||
RR.CloseMainMenu();
|
||||
RR.World.LoadAsync(worldConfigAsset.Config, Application.exitCancellationToken).Forget();
|
||||
} else {
|
||||
s_GameLogger.Error($"World config asset for '{worldID}' not found.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
3
Runtime/Engine/Code/Main/Game.cs.meta
Normal file
3
Runtime/Engine/Code/Main/Game.cs.meta
Normal file
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3c1089fa01934ad69bf229123b190c07
|
||||
timeCreated: 1750977602
|
||||
6
Runtime/Engine/Code/Main/NetworkPlayerController.cs
Normal file
6
Runtime/Engine/Code/Main/NetworkPlayerController.cs
Normal file
@@ -0,0 +1,6 @@
|
||||
using Unity.Netcode;
|
||||
|
||||
namespace RebootKit.Engine.Main {
|
||||
public abstract class NetworkPlayerController : NetworkBehaviour {
|
||||
}
|
||||
}
|
||||
3
Runtime/Engine/Code/Main/NetworkPlayerController.cs.meta
Normal file
3
Runtime/Engine/Code/Main/NetworkPlayerController.cs.meta
Normal file
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2010b0aabd68415bb4aea2846d2c59b1
|
||||
timeCreated: 1751208839
|
||||
@@ -4,52 +4,54 @@ using System.Threading;
|
||||
using Cysharp.Threading.Tasks;
|
||||
using R3;
|
||||
using RebootKit.Engine.Foundation;
|
||||
using RebootKit.Engine.Multiplayer;
|
||||
using RebootKit.Engine.Services.Console;
|
||||
using RebootKit.Engine.Services.GameMode;
|
||||
using RebootKit.Engine.Services.Input;
|
||||
using RebootKit.Engine.Services.Simulation;
|
||||
using RebootKit.Engine.Steam;
|
||||
using Unity.Collections;
|
||||
using RebootKit.Engine.Simulation;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
using UnityEngine.AddressableAssets;
|
||||
using UnityEngine.ResourceManagement.AsyncOperations;
|
||||
using UnityEngine.ResourceManagement.ResourceProviders;
|
||||
using UnityEngine.SceneManagement;
|
||||
using Assert = UnityEngine.Assertions.Assert;
|
||||
using Logger = RebootKit.Engine.Foundation.Logger;
|
||||
using Object = UnityEngine.Object;
|
||||
|
||||
namespace RebootKit.Engine.Main {
|
||||
public interface IGame : IDisposable {
|
||||
UniTask InitAsync(CancellationToken cancellationToken);
|
||||
void Run();
|
||||
}
|
||||
|
||||
public abstract class GameAsset : ScriptableObject {
|
||||
public abstract IGame CreateGame();
|
||||
}
|
||||
|
||||
public static class RR {
|
||||
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", 60, "Server tick rate in Hz")]
|
||||
public static ConfigVar TickRate;
|
||||
|
||||
internal static EngineConfigAsset EngineConfig;
|
||||
|
||||
static DisposableBag s_disposableBag;
|
||||
static DisposableBag s_servicesBag;
|
||||
|
||||
public static ConsoleService Console { get; private set; }
|
||||
static AsyncOperationHandle<SceneInstance> s_mainMenuSceneHandle;
|
||||
|
||||
internal static ConsoleService Console { get; private set; }
|
||||
public static InputService Input { get; private set; }
|
||||
public static WorldService World { get; private set; }
|
||||
public static GameModesService GameModes { get; private set; }
|
||||
|
||||
public static Camera MainCamera { get; internal set; }
|
||||
|
||||
static IGame s_game;
|
||||
internal static Game GameInstance;
|
||||
|
||||
// Core
|
||||
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.
|
||||
internal static async UniTask InitAsync(EngineConfigAsset configAsset, CancellationToken cancellationToken) {
|
||||
Assert.IsNotNull(configAsset, "Config asset is required");
|
||||
Assert.IsNotNull(configAsset.gameAsset, "Game asset is required");
|
||||
|
||||
EngineConfig = configAsset;
|
||||
|
||||
@@ -57,36 +59,31 @@ namespace RebootKit.Engine.Main {
|
||||
s_servicesBag = new DisposableBag();
|
||||
s_disposableBag = new DisposableBag();
|
||||
|
||||
s_Logger.Debug("Registering core services");
|
||||
s_Logger.Info("Registering core services");
|
||||
Console = CreateService(EngineConfig.coreServices.consoleService);
|
||||
Input = CreateService(EngineConfig.coreServices.inputService);
|
||||
World = CreateService(EngineConfig.coreServices.worldService);
|
||||
GameModes = CreateService<GameModesService>();
|
||||
|
||||
await InitializeAssetsAsync(cancellationToken);
|
||||
|
||||
await SteamManager.InitializeAsync(cancellationToken);
|
||||
|
||||
if (SteamManager.IsInitialized) {
|
||||
s_networkTransport = SteamManager.NetworkTransport;
|
||||
}
|
||||
// await SteamManager.InitializeAsync(cancellationToken);
|
||||
|
||||
s_Logger.Debug("Creating game");
|
||||
s_game = EngineConfig.gameAsset.CreateGame();
|
||||
|
||||
await s_game.InitAsync(cancellationToken);
|
||||
// if (SteamManager.IsInitialized) {
|
||||
// s_networkTransport = SteamManager.NetworkTransport;
|
||||
// }
|
||||
}
|
||||
|
||||
internal static void Shutdown() {
|
||||
SteamManager.Shutdown();
|
||||
|
||||
s_Logger.Info("Shutting down");
|
||||
s_servicesBag.Dispose();
|
||||
s_disposableBag.Dispose();
|
||||
}
|
||||
// @NOTE: This method is called after the main scene is loaded.
|
||||
internal static async UniTask RunAsync(CancellationToken cancellationToken) {
|
||||
NetworkManager.Singleton.OnConnectionEvent += OnConnectionEvent;
|
||||
NetworkManager.Singleton.OnServerStarted += OnServerStarted;
|
||||
NetworkManager.Singleton.OnServerStopped += OnServerStopped;
|
||||
|
||||
internal static void Run() {
|
||||
s_game.Run();
|
||||
Observable.EveryUpdate()
|
||||
.Subscribe(_ => Tick())
|
||||
.AddTo(ref s_disposableBag);
|
||||
|
||||
await OpenMainMenuAsync(cancellationToken);
|
||||
|
||||
#if UNITY_EDITOR
|
||||
string scriptContent = UnityEditor.EditorPrefs.GetString("RebootKitEditor.OnGameRunScriptContent", "");
|
||||
@@ -101,44 +98,49 @@ namespace RebootKit.Engine.Main {
|
||||
#endif
|
||||
}
|
||||
|
||||
internal static void Shutdown() {
|
||||
s_Logger.Info("Shutting down");
|
||||
|
||||
if (GameInstance is not null) {
|
||||
GameInstance.NetworkObject.Despawn();
|
||||
Object.Destroy(GameInstance);
|
||||
GameInstance = null;
|
||||
}
|
||||
|
||||
|
||||
if (NetworkManager.Singleton is not null) {
|
||||
NetworkManager.Singleton.OnConnectionEvent -= OnConnectionEvent;
|
||||
NetworkManager.Singleton.OnServerStarted -= OnServerStarted;
|
||||
NetworkManager.Singleton.OnServerStopped -= OnServerStopped;
|
||||
}
|
||||
|
||||
// SteamManager.Shutdown();
|
||||
|
||||
s_servicesBag.Dispose();
|
||||
s_disposableBag.Dispose();
|
||||
}
|
||||
|
||||
// Assets API
|
||||
static readonly List<GameModeAsset> s_GameModesAssets = new List<GameModeAsset>();
|
||||
static readonly List<WorldConfigAsset> s_WorldConfigsAssets = new List<WorldConfigAsset>();
|
||||
|
||||
public static IReadOnlyList<GameModeAsset> GameModesAssets => s_GameModesAssets;
|
||||
public static IReadOnlyList<WorldConfigAsset> WorldConfigsAssets => s_WorldConfigsAssets;
|
||||
|
||||
public static async UniTask InitializeAssetsAsync(CancellationToken cancellationToken) {
|
||||
s_GameModesAssets.Clear();
|
||||
static async UniTask InitializeAssetsAsync(CancellationToken cancellationToken) {
|
||||
s_WorldConfigsAssets.Clear();
|
||||
|
||||
s_Logger.Info("Loading game assets");
|
||||
|
||||
await Addressables.LoadAssetsAsync<GameModeAsset>("game_mode", asset => { s_GameModesAssets.Add(asset); }).ToUniTask(cancellationToken: cancellationToken);
|
||||
s_Logger.Info($"Loaded {s_GameModesAssets.Count} game modes");
|
||||
|
||||
await Addressables.LoadAssetsAsync<WorldConfigAsset>("world", asset => { s_WorldConfigsAssets.Add(asset); }).ToUniTask(cancellationToken: cancellationToken);
|
||||
await Addressables.LoadAssetsAsync<WorldConfigAsset>("world", asset => { s_WorldConfigsAssets.Add(asset); })
|
||||
.ToUniTask(cancellationToken: cancellationToken);
|
||||
}
|
||||
|
||||
public static GameModeAsset GetGameMode(string name) {
|
||||
if (string.IsNullOrEmpty(name)) {
|
||||
throw new ArgumentException("Game mode name cannot be null or empty", nameof(name));
|
||||
}
|
||||
|
||||
GameModeAsset gameMode = s_GameModesAssets.Find(asset => asset.name.Equals(name, StringComparison.Ordinal));
|
||||
if (!gameMode) {
|
||||
throw new KeyNotFoundException($"Game mode '{name}' not found");
|
||||
}
|
||||
|
||||
return gameMode;
|
||||
}
|
||||
|
||||
public static WorldConfigAsset GetWorldConfigAsset(string name) {
|
||||
if (string.IsNullOrEmpty(name)) {
|
||||
throw new ArgumentException("World config name cannot be null or empty", nameof(name));
|
||||
}
|
||||
|
||||
WorldConfigAsset worldConfig = s_WorldConfigsAssets.Find(asset => asset.Config.name.Equals(name, StringComparison.Ordinal));
|
||||
WorldConfigAsset worldConfig =
|
||||
s_WorldConfigsAssets.Find(asset => asset.Config.name.Equals(name, StringComparison.Ordinal));
|
||||
if (!worldConfig) {
|
||||
throw new KeyNotFoundException($"World config '{name}' not found");
|
||||
}
|
||||
@@ -147,22 +149,48 @@ namespace RebootKit.Engine.Main {
|
||||
}
|
||||
|
||||
// Game API
|
||||
public static void StartGameMode(GameModeAsset gameMode, WorldConfig world) {
|
||||
if (!IsClient() || !IsHost()) {
|
||||
s_Logger.Error("Cannot start game mode: you must be connected to a server and be the host");
|
||||
public static async UniTask OpenMainMenuAsync(CancellationToken cancellationToken) {
|
||||
s_Logger.Info("Opening main menu");
|
||||
|
||||
World.Unload();
|
||||
|
||||
if (!EngineConfig.mainMenuScene.RuntimeKeyIsValid()) {
|
||||
s_Logger.Error("Main menu scene is not set in EngineConfig");
|
||||
return;
|
||||
}
|
||||
|
||||
s_Logger.Info($"Starting game mode: {gameMode.name} in world: {world.name}");
|
||||
GameModes.Start(gameMode, world);
|
||||
s_mainMenuSceneHandle = Addressables.LoadSceneAsync(EngineConfig.mainMenuScene, LoadSceneMode.Additive);
|
||||
await s_mainMenuSceneHandle;
|
||||
}
|
||||
|
||||
public static TGame Game<TGame>() where TGame : IGame {
|
||||
if (s_game is TGame game) {
|
||||
return game;
|
||||
internal static void CloseMainMenu() {
|
||||
if (!s_mainMenuSceneHandle.IsValid()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Addressables.UnloadSceneAsync(s_mainMenuSceneHandle);
|
||||
}
|
||||
|
||||
public static void SetServerWorld(string worldID) {
|
||||
if (!IsServer()) {
|
||||
s_Logger.Error("Cannot set server world. Not a server instance.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (GameInstance is null) {
|
||||
s_Logger.Error("Game is not initialized. Cannot set server world.");
|
||||
return;
|
||||
}
|
||||
|
||||
throw new InvalidOperationException($"Game is not of type {typeof(TGame)}");
|
||||
s_Logger.Info($"Setting server world: {worldID}");
|
||||
|
||||
WorldConfigAsset worldConfigAsset = GetWorldConfigAsset(worldID);
|
||||
if (worldConfigAsset is null) {
|
||||
s_Logger.Error($"World '{worldID}' not found");
|
||||
return;
|
||||
}
|
||||
|
||||
GameInstance.SetCurrentWorldServerRpc(worldID);
|
||||
}
|
||||
|
||||
// Service API
|
||||
@@ -170,7 +198,7 @@ namespace RebootKit.Engine.Main {
|
||||
if (asset is null) {
|
||||
throw new ArgumentNullException($"Null asset of type {typeof(TService)}");
|
||||
}
|
||||
|
||||
|
||||
TService service = asset.Create();
|
||||
s_servicesBag.Add(service);
|
||||
return service;
|
||||
@@ -182,10 +210,9 @@ namespace RebootKit.Engine.Main {
|
||||
return service;
|
||||
}
|
||||
|
||||
// General API
|
||||
// Logging API
|
||||
public static void Log(string message) {
|
||||
Debug.Log(message);
|
||||
|
||||
Console?.WriteToOutput(message);
|
||||
}
|
||||
|
||||
@@ -199,6 +226,10 @@ namespace RebootKit.Engine.Main {
|
||||
Console?.WriteToOutput(message);
|
||||
}
|
||||
|
||||
public static void WriteToConsole(string message) {
|
||||
Console?.WriteToOutput(message);
|
||||
}
|
||||
|
||||
// CVar API
|
||||
public static ConfigVar CVarIndex(string name, int defaultValue = -1) {
|
||||
ConfigVar cvar = ConfigVarsContainer.Get(name);
|
||||
@@ -232,48 +263,112 @@ namespace RebootKit.Engine.Main {
|
||||
ConfigVarsContainer.Register(cvar);
|
||||
return cvar;
|
||||
}
|
||||
|
||||
|
||||
// Network API
|
||||
static GameLobby s_gameLobby;
|
||||
static INetworkTransport s_networkTransport;
|
||||
|
||||
public static bool IsHost() {
|
||||
return s_networkTransport.IsServer();
|
||||
public static bool IsServer() {
|
||||
return NetworkManager.Singleton.IsServer;
|
||||
}
|
||||
|
||||
public static bool IsClient() {
|
||||
return s_networkTransport.IsClient();
|
||||
}
|
||||
|
||||
public static int GetPing() {
|
||||
return -1;
|
||||
}
|
||||
|
||||
public static void HostServer(bool offline = false) {
|
||||
s_networkTransport.StartServer();
|
||||
}
|
||||
|
||||
public static void ConnectToLobby() {
|
||||
s_networkTransport.Connect(Steamworks.SteamNetworkingSockets.Identity.SteamId);
|
||||
return NetworkManager.Singleton.IsClient;
|
||||
}
|
||||
|
||||
public static void StartHost() {
|
||||
if (NetworkManager.Singleton.IsHost) {
|
||||
s_Logger.Error("Already hosting a server");
|
||||
return;
|
||||
}
|
||||
|
||||
s_Logger.Info("Starting host");
|
||||
NetworkManager.Singleton.StartHost();
|
||||
}
|
||||
|
||||
public static void StopServer() {
|
||||
}
|
||||
|
||||
public static void Connect() {
|
||||
if (NetworkManager.Singleton.IsClient) {
|
||||
s_Logger.Error("Already connected to a server");
|
||||
return;
|
||||
}
|
||||
|
||||
s_Logger.Info($"Connecting to server.");
|
||||
NetworkManager.Singleton.StartClient();
|
||||
}
|
||||
|
||||
public static void Disconnect() {
|
||||
s_networkTransport.Disconnect();
|
||||
}
|
||||
|
||||
internal static void OnConnected(GameLobby lobby) {
|
||||
public static void SendChatMessage(string message) {
|
||||
if (!IsClient()) {
|
||||
s_Logger.Error("Cannot send chat message. Not connected to a server.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(message)) {
|
||||
return;
|
||||
}
|
||||
|
||||
GameInstance.SendChatMessageRpc(message);
|
||||
}
|
||||
|
||||
internal static void OnDisconnected() {
|
||||
}
|
||||
|
||||
internal static void OnServerDataReceived(byte[] data) {
|
||||
s_Logger.Debug($"[SERVER] Data received: {data.Length} bytes");
|
||||
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++;
|
||||
}
|
||||
|
||||
World.Tick(deltaTime);
|
||||
}
|
||||
|
||||
internal static void OnClientDataReceived(byte[] data) {
|
||||
s_Logger.Debug($"[CLIENT] Data received: {data.Length} bytes");
|
||||
static void OnConnectionEvent(NetworkManager network, ConnectionEventData data) {
|
||||
s_Logger.Info("Connection event: " + data.EventType);
|
||||
}
|
||||
|
||||
static void OnServerStarted() {
|
||||
s_Logger.Info("Server started");
|
||||
|
||||
GameInstance = Object.Instantiate(EngineConfig.gamePrefab);
|
||||
GameInstance.NetworkObject.Spawn();
|
||||
}
|
||||
|
||||
static void OnServerStopped(bool obj) {
|
||||
s_Logger.Info("Server stopped");
|
||||
|
||||
if (GameInstance is not null) {
|
||||
GameInstance.NetworkObject.Despawn();
|
||||
Object.Destroy(GameInstance.gameObject);
|
||||
}
|
||||
|
||||
GameInstance = null;
|
||||
}
|
||||
|
||||
// Console Commands
|
||||
[RCCMD("say", "Sends chat message")]
|
||||
static void Say(string[] args) {
|
||||
if (args.Length < 2) {
|
||||
Console.WriteToOutput("Usage: say <message>");
|
||||
return;
|
||||
}
|
||||
|
||||
string message = string.Join(" ", args, 1, args.Length - 1);
|
||||
SendChatMessage(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user