Files

302 lines
10 KiB
C#
Raw Permalink Normal View History

2023-03-06 10:06:43 +04:00
/*
2024-05-19 12:26:42 +03:00
* Copyright 2023-2024 Eduard Kargin <kargin.eduard@gmail.com>
2023-03-06 10:06:43 +04:00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Diagnostics;
using Ragon.Protocol;
2023-04-09 11:06:52 +04:00
using Ragon.Server.Handler;
using Ragon.Server.IO;
using Ragon.Server.Lobby;
using Ragon.Server.Logging;
2023-04-09 10:52:18 +04:00
using Ragon.Server.Plugin;
2025-10-04 15:08:53 +03:00
using Ragon.Server.Project;
2023-04-09 10:52:18 +04:00
using Ragon.Server.Time;
2023-03-06 10:06:43 +04:00
namespace Ragon.Server;
2023-04-13 20:42:05 +04:00
public class RagonServer : IRagonServer, INetworkListener
2023-03-06 10:06:43 +04:00
{
2025-10-04 17:33:58 +03:00
private const string ServerVersion = "1.4.3";
2025-10-04 15:08:53 +03:00
private readonly IRagonLogger _logger = LoggerManager.GetLogger(nameof(RagonServer));
2023-03-06 10:06:43 +04:00
private readonly INetworkServer _server;
2023-10-07 19:30:52 +03:00
private readonly BaseOperation[] _handlers;
2023-04-13 20:42:05 +04:00
private readonly IRagonLobby _lobby;
private readonly IServerPlugin _serverPlugin;
2023-07-01 07:47:57 +03:00
private readonly RagonServerConfiguration _configuration;
2023-03-06 10:06:43 +04:00
private readonly RagonBuffer _reader;
private readonly RagonBuffer _writer;
private readonly RagonScheduler _scheduler;
2023-04-13 20:42:05 +04:00
private readonly Dictionary<ushort, RagonContext> _contextsByConnection;
private readonly Dictionary<string, RagonContext> _contextsByPlayerId;
2025-10-04 15:08:53 +03:00
private readonly ProjectRegistry _projectRegistry;
2024-04-13 16:17:31 +03:00
private readonly RagonLobbyDispatcher _lobbySerializer;
private bool _isRunning = false;
public bool IsRunning => _isRunning;
2025-10-04 15:08:53 +03:00
public ProjectRegistry ProjectRegistry => _projectRegistry;
2023-10-07 19:30:52 +03:00
2023-04-09 10:52:18 +04:00
public RagonServer(
INetworkServer server,
IServerPlugin plugin,
2023-07-01 07:47:57 +03:00
RagonServerConfiguration configuration)
2023-03-06 10:06:43 +04:00
{
_server = server;
_configuration = configuration;
2023-04-13 20:42:05 +04:00
_serverPlugin = plugin;
_contextsByConnection = new Dictionary<ushort, RagonContext>();
_contextsByPlayerId = new Dictionary<string, RagonContext>();
2025-10-04 15:08:53 +03:00
_projectRegistry = new ProjectRegistry(configuration.LimitConnectionsPerProject);
2023-03-06 10:06:43 +04:00
_lobby = new LobbyInMemory();
2024-04-13 16:17:31 +03:00
_lobbySerializer = new RagonLobbyDispatcher(_lobby);
2023-03-06 10:06:43 +04:00
_scheduler = new RagonScheduler();
_reader = new RagonBuffer();
_writer = new RagonBuffer();
2023-04-13 20:42:05 +04:00
var contextObserver = new RagonContextObserver(_contextsByPlayerId);
_scheduler.Run(new RagonActionTimer(SendRoomList, 2.0f));
_scheduler.Run(new RagonActionTimer(SendPlayerUserData, 0.1f));
_scheduler.Run(new RagonActionTimer(SendRoomUserData, 0.1f));
_scheduler.Run(new RagonActionTimer(SendTimestamp, 1.0f / _configuration.ServerTickRate));
2024-04-13 16:17:31 +03:00
2023-04-13 20:42:05 +04:00
_serverPlugin.OnAttached(this);
2023-10-07 19:30:52 +03:00
_handlers = new BaseOperation[byte.MaxValue];
2025-10-04 15:08:53 +03:00
_handlers[(byte)RagonOperation.AUTHORIZE] = new AuthorizationOperation(_reader, _writer, this, _serverPlugin, contextObserver, configuration, _projectRegistry);
_handlers[(byte)RagonOperation.JOIN_OR_CREATE_ROOM] = new RoomJoinOrCreateOperation(_reader, _writer, plugin, _configuration);
_handlers[(byte)RagonOperation.CREATE_ROOM] = new RoomCreateOperation(_reader, _writer, plugin, _configuration);
_handlers[(byte)RagonOperation.JOIN_ROOM] = new RoomJoinOperation(_reader, _writer);
_handlers[(byte)RagonOperation.LEAVE_ROOM] = new RoomLeaveOperation(_reader, _writer);
2023-10-07 19:30:52 +03:00
_handlers[(byte)RagonOperation.LOAD_SCENE] = new SceneLoadOperation(_reader, _writer);
2024-08-17 10:29:27 +03:00
_handlers[(byte)RagonOperation.SCENE_LOADED] = new SceneLoadedOperation(_reader, _writer, _configuration);
_handlers[(byte)RagonOperation.CREATE_ENTITY] = new EntityCreateOperation(_reader, _writer, _configuration);
2023-10-07 19:30:52 +03:00
_handlers[(byte)RagonOperation.REMOVE_ENTITY] = new EntityDestroyOperation(_reader, _writer);
_handlers[(byte)RagonOperation.REPLICATE_ENTITY_EVENT] = new EntityEventOperation(_reader, _writer);
_handlers[(byte)RagonOperation.REPLICATE_ENTITY_STATE] = new EntityStateOperation(_reader, _writer);
_handlers[(byte)RagonOperation.TRANSFER_ROOM_OWNERSHIP] = new EntityOwnershipOperation(_reader, _writer);
_handlers[(byte)RagonOperation.TRANSFER_ENTITY_OWNERSHIP] = new EntityOwnershipOperation(_reader, _writer);
_handlers[(byte)RagonOperation.TIMESTAMP_SYNCHRONIZATION] = new TimestampSyncOperation(_reader, _writer);
_handlers[(byte)RagonOperation.REPLICATE_ROOM_EVENT] = new RoomEventOperation(_reader, _writer);
_handlers[(byte)RagonOperation.REPLICATE_RAW_DATA] = new RoomDataOperation(_reader, _writer);
2024-08-17 10:29:27 +03:00
_handlers[(byte)RagonOperation.ROOM_DATA_UPDATED] = new RoomUserDataOperation(_reader, _writer, _configuration.LimitUserDataSize);
_handlers[(byte)RagonOperation.PLAYER_DATA_UPDATED] = new PlayerUserDataOperation(_reader, _writer, _configuration.LimitUserDataSize);
2023-03-06 10:06:43 +04:00
}
public void Tick()
2023-03-06 10:06:43 +04:00
{
var deltaTime = 1.0f / _configuration.ServerTickRate;
_scheduler.Update(deltaTime);
_server.Update();
2023-03-06 10:06:43 +04:00
}
public void Start(bool executeInDedicatedThread = false)
{
CopyrightInfo();
2023-03-06 10:06:43 +04:00
var networkConfiguration = new NetworkConfiguration()
{
LimitConnections = _configuration.LimitConnections,
Protocol = RagonVersion.Parse(_configuration.Protocol),
Address = _configuration.ServerAddress,
2023-03-06 10:06:43 +04:00
Port = _configuration.Port,
};
2023-10-07 19:30:52 +03:00
_server.Listen(this, networkConfiguration);
_serverPlugin.OnAttached(this);
_isRunning = true;
2023-03-06 10:06:43 +04:00
}
public void Dispose()
{
2023-04-13 20:42:05 +04:00
_serverPlugin.OnDetached();
2023-03-06 10:06:43 +04:00
_server.Stop();
}
public void OnConnected(INetworkConnection connection)
{
var context = new RagonContext(connection, _lobby, _scheduler, _configuration.LimitBufferedEvents);
2023-10-07 19:30:52 +03:00
2023-03-06 10:06:43 +04:00
_logger.Trace($"Connected: {connection.Id}");
2023-04-13 20:42:05 +04:00
_contextsByConnection.Add(connection.Id, context);
2023-03-06 10:06:43 +04:00
}
public void OnDisconnected(INetworkConnection connection)
{
2023-04-13 20:42:05 +04:00
if (_contextsByConnection.Remove(connection.Id, out var context))
2023-03-06 10:06:43 +04:00
{
var room = context.Room;
if (room != null)
{
room.DetachPlayer(context.RoomPlayer);
2025-10-04 15:08:53 +03:00
_lobby.RemoveIfEmpty(room);
2023-03-06 10:06:43 +04:00
}
2025-10-04 15:08:53 +03:00
2024-07-21 09:46:01 +03:00
if (context.ConnectionStatus == ConnectionStatus.Authorized)
2025-10-04 15:08:53 +03:00
{
2024-07-21 09:46:01 +03:00
_contextsByPlayerId.Remove(context.LobbyPlayer.Id);
2025-10-04 15:08:53 +03:00
_projectRegistry.UnregisterConnection(context.LobbyPlayer.ProjectId);
}
2023-10-07 19:30:52 +03:00
2023-04-09 10:52:18 +04:00
_logger.Trace($"Disconnected: {connection.Id}");
2023-03-06 10:06:43 +04:00
}
else
{
2023-10-04 14:42:59 +03:00
_logger.Trace($"Disconnected without context: {connection.Id}");
2023-03-06 10:06:43 +04:00
}
}
public void OnTimeout(INetworkConnection connection)
{
2023-10-12 16:09:24 +03:00
if (_contextsByConnection.Remove(connection.Id, out var context) && context.ConnectionStatus == ConnectionStatus.Authorized)
2023-03-06 10:06:43 +04:00
{
var room = context.Room;
if (room != null)
{
room.DetachPlayer(context.RoomPlayer);
_lobby.RemoveIfEmpty(room);
}
2025-10-04 15:08:53 +03:00
2024-07-21 09:46:01 +03:00
if (context.ConnectionStatus == ConnectionStatus.Authorized)
2025-10-04 15:08:53 +03:00
{
2024-07-21 09:46:01 +03:00
_contextsByPlayerId.Remove(context.LobbyPlayer.Id);
2025-10-04 15:08:53 +03:00
_projectRegistry.UnregisterConnection(context.LobbyPlayer.ProjectId);
}
2023-03-06 10:06:43 +04:00
_logger.Trace($"Timeout: {connection.Id}|{context.LobbyPlayer.Name}|{context.LobbyPlayer.Id}");
}
else
{
_logger.Trace($"Timeout: {connection.Id}");
}
}
2023-10-07 19:30:52 +03:00
public void OnData(INetworkConnection connection, NetworkChannel channel, byte[] data)
2023-03-06 10:06:43 +04:00
{
try
{
2023-04-13 20:42:05 +04:00
if (_contextsByConnection.TryGetValue(connection.Id, out var context))
2023-03-06 10:06:43 +04:00
{
_writer.Clear();
_reader.Clear();
2023-10-07 19:30:52 +03:00
_reader.FromArray(data);
2025-10-04 15:08:53 +03:00
2023-03-06 10:06:43 +04:00
var operation = _reader.ReadByte();
2025-10-04 15:08:53 +03:00
if (operation >= _handlers.Length || _handlers[operation] == null)
{
_logger.Warning($"Invalid operation code: {operation} from connection {connection.Id}");
return;
}
_handlers[operation].Handle(context, channel);
2023-03-06 10:06:43 +04:00
}
}
catch (Exception ex)
{
_logger.Error(ex);
}
}
2023-04-14 14:32:04 +04:00
2023-10-04 14:42:59 +03:00
public void SendTimestamp()
{
var timestamp = RagonTime.CurrentTimestamp();
var value = new DoubleToUInt
{
Double = timestamp,
};
2023-10-07 19:30:52 +03:00
2023-10-04 14:42:59 +03:00
_writer.Clear();
_writer.WriteOperation(RagonOperation.TIMESTAMP_SYNCHRONIZATION);
_writer.Write(value.Int0, 32);
_writer.Write(value.Int1, 32);
var sendData = _writer.ToArray();
2023-10-11 19:37:50 +03:00
_server.Broadcast(sendData, NetworkChannel.UNRELIABLE);
2023-10-04 14:42:59 +03:00
}
2023-10-07 19:30:52 +03:00
2024-04-13 16:17:31 +03:00
public void SendRoomList()
{
2025-10-04 15:08:53 +03:00
foreach (var (_, context) in _contextsByPlayerId)
2024-04-13 16:17:31 +03:00
{
2025-10-04 15:08:53 +03:00
if (context.Room == null) // If only in lobby, then send room list data
{
_lobbySerializer.Write(_writer, context.LobbyPlayer.ProjectId);
var sendData = _writer.ToArray();
context.Connection.Reliable.Send(sendData);
}
2024-04-13 16:17:31 +03:00
}
}
2024-05-09 10:50:59 +03:00
public void SendPlayerUserData()
2024-04-29 09:12:42 +03:00
{
foreach (var (_, value) in _contextsByPlayerId)
{
if (value.UserData.IsDirty)
{
_writer.Clear();
2024-05-09 10:50:59 +03:00
_writer.WriteOperation(RagonOperation.PLAYER_DATA_UPDATED);
2024-04-29 09:12:42 +03:00
_writer.WriteUShort(value.Connection.Id);
value.UserData.Write(_writer);
2024-04-29 09:12:42 +03:00
var sendData = _writer.ToArray();
_server.Broadcast(sendData, NetworkChannel.RELIABLE);
}
}
}
2024-05-09 10:50:59 +03:00
public void SendRoomUserData()
{
foreach (var room in _lobby.Rooms)
{
if (room.UserData.IsDirty)
{
_writer.Clear();
2024-05-09 10:50:59 +03:00
_writer.WriteOperation(RagonOperation.ROOM_DATA_UPDATED);
room.UserData.Write(_writer);
var sendData = _writer.ToArray();
_server.Broadcast(sendData, NetworkChannel.RELIABLE);
2024-04-29 09:12:42 +03:00
}
}
}
public BaseOperation ResolveHandler(RagonOperation operation)
2023-04-14 14:32:04 +04:00
{
return _handlers[(byte)operation];
}
2024-05-19 11:28:36 +03:00
public RagonContext? GetContextByConnectionId(ushort peerId)
2023-04-14 14:32:04 +04:00
{
2024-05-19 11:28:36 +03:00
return _contextsByConnection.TryGetValue(peerId, out var context) ? context : null;
2023-04-14 14:32:04 +04:00
}
2024-05-19 11:28:36 +03:00
public RagonContext? GetContextById(string playerId)
2023-04-14 14:32:04 +04:00
{
2024-05-19 11:28:36 +03:00
return _contextsByPlayerId.TryGetValue(playerId, out var context) ? context : null;
2023-04-14 14:32:04 +04:00
}
2025-10-04 15:08:53 +03:00
private void CopyrightInfo()
{
_logger.Info($"Server Version: {ServerVersion}");
_logger.Info($"Machine Name: {Environment.MachineName}");
_logger.Info($"OS: {Environment.OSVersion}");
_logger.Info($"Processors: {Environment.ProcessorCount}");
_logger.Info($"Runtime Version: {Environment.Version}");
_logger.Info($"Server Tick Rate: {_configuration.ServerTickRate}");
}
2023-03-06 10:06:43 +04:00
}