Files
RebootKit/Runtime/Engine/Code/Main/RR.cs
2025-06-24 14:45:45 +02:00

279 lines
9.6 KiB
C#
Executable File

using System;
using System.Collections.Generic;
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 UnityEngine;
using UnityEngine.AddressableAssets;
using Assert = UnityEngine.Assertions.Assert;
using Logger = RebootKit.Engine.Foundation.Logger;
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;
internal static EngineConfigAsset EngineConfig;
static DisposableBag s_disposableBag;
static DisposableBag s_servicesBag;
public 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;
// Core
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;
s_Logger.Info("Initializing");
s_servicesBag = new DisposableBag();
s_disposableBag = new DisposableBag();
s_Logger.Debug("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;
}
s_Logger.Debug("Creating game");
s_game = EngineConfig.gameAsset.CreateGame();
await s_game.InitAsync(cancellationToken);
}
internal static void Shutdown() {
SteamManager.Shutdown();
s_Logger.Info("Shutting down");
s_servicesBag.Dispose();
s_disposableBag.Dispose();
}
internal static void Run() {
s_game.Run();
#if UNITY_EDITOR
string scriptContent = UnityEditor.EditorPrefs.GetString("RebootKitEditor.OnGameRunScriptContent", "");
s_Logger.Info($"Executing script: {scriptContent}");
if (!string.IsNullOrEmpty(scriptContent)) {
foreach (string cmd in scriptContent.Split('\n')) {
s_Logger.Info($"Executing command: {cmd}");
Console.Execute(cmd);
}
}
#endif
}
// 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();
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);
}
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));
if (!worldConfig) {
throw new KeyNotFoundException($"World config '{name}' not found");
}
return worldConfig;
}
// 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");
return;
}
s_Logger.Info($"Starting game mode: {gameMode.name} in world: {world.name}");
GameModes.Start(gameMode, world);
}
public static TGame Game<TGame>() where TGame : IGame {
if (s_game is TGame game) {
return game;
}
throw new InvalidOperationException($"Game is not of type {typeof(TGame)}");
}
// Service API
public static TService CreateService<TService>(ServiceAsset<TService> asset) where TService : class, IService {
if (asset is null) {
throw new ArgumentNullException($"Null asset of type {typeof(TService)}");
}
TService service = asset.Create();
s_servicesBag.Add(service);
return service;
}
public static TService CreateService<TService>() where TService : class, IService {
TService service = Activator.CreateInstance<TService>();
s_servicesBag.Add(service);
return service;
}
// General API
public static void Log(string message) {
Debug.Log(message);
Console?.WriteToOutput(message);
}
public static void LogWarning(string message) {
Debug.LogWarning(message);
Console?.WriteToOutput(message);
}
public static void LogError(string message) {
Debug.LogError(message);
Console?.WriteToOutput(message);
}
// CVar API
public static ConfigVar CVarIndex(string name, int defaultValue = -1) {
ConfigVar cvar = ConfigVarsContainer.Get(name);
if (cvar != null) {
return cvar;
}
cvar = new ConfigVar(name, defaultValue);
ConfigVarsContainer.Register(cvar);
return cvar;
}
public static ConfigVar CVarNumber(string name, double defaultValue = 0) {
ConfigVar cvar = ConfigVarsContainer.Get(name);
if (cvar != null) {
return cvar;
}
cvar = new ConfigVar(name, defaultValue);
ConfigVarsContainer.Register(cvar);
return cvar;
}
public static ConfigVar CVarString(string name, string defaultValue = "") {
ConfigVar cvar = ConfigVarsContainer.Get(name);
if (cvar != null) {
return cvar;
}
cvar = new ConfigVar(name, defaultValue);
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 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);
}
public static void Disconnect() {
s_networkTransport.Disconnect();
}
internal static void OnConnected(GameLobby lobby) {
}
internal static void OnDisconnected() {
}
internal static void OnServerDataReceived(byte[] data) {
s_Logger.Debug($"[SERVER] Data received: {data.Length} bytes");
}
internal static void OnClientDataReceived(byte[] data) {
s_Logger.Debug($"[CLIENT] Data received: {data.Length} bytes");
}
}
}