Compare commits

..

20 Commits

Author SHA1 Message Date
edmand46 b8fe2bb13f 🐛 wrong condition in lobby in memory on finding room by id 2024-02-04 20:06:07 +03:00
edmand46 89d130a193 🐛 fixed double call on invoke local flag in ragon property 2024-01-21 12:20:47 +03:00
edmand46 0cd912a1aa 🎨 added null checks 2024-01-13 15:15:29 +03:00
edmand46 c64cc61c78 🐛 prediction spawning for wrong connection, payload capacity 2024-01-04 23:29:35 +03:00
edmand46 2dcb047014 chore: added logging 2023-11-05 22:19:55 +03:00
edmand46 33f8bba2ed fixed: remove exception on non exists player 2023-11-05 22:08:41 +03:00
edmand46 5aa159ed2f fixed: custom property wrong size 2023-11-05 21:53:57 +03:00
edmand46 892558ab16 chore: update version 2023-10-22 21:10:31 +03:00
edmand46 f55634877a 📝 update readme.md 2023-10-21 23:10:41 +03:00
edmand46 8b3a29a750 📝 update readme.md 2023-10-21 23:09:49 +03:00
edmand46 6a50bffe1e 📝 update readme.md 2023-10-21 23:03:55 +03:00
edmand46 9144ad58ef 📝 update readme.md 2023-10-21 23:03:37 +03:00
edmand46 ee9f3fbe3a 🐛 crash on abnormal disconnecting from websocket server 2023-10-19 20:20:40 +03:00
edmand46 893c73512a feat: allow control replication via code, fix null owner on OnEntityCreated 2023-10-16 23:37:35 +03:00
edmand46 e7dd693147 🐛 Event Payload 2023-10-14 23:50:25 +03:00
edmand46 fef1007c8c 🔖 update version 2023-10-14 21:48:33 +03:00
edmand46 e33c442a18 🐛 WebSocket buffer size 2023-10-14 21:35:51 +03:00
edmand46 09b185a3ad 🐛 checking size event 2023-10-13 12:10:46 +03:00
edmand46 7d154ea4d4 🎨 cleanup 2023-10-13 11:02:56 +03:00
edmand46 d2577e5d1f remove allocation on raw data replication 2023-10-13 10:58:15 +03:00
41 changed files with 361 additions and 187 deletions
+25
View File
@@ -0,0 +1,25 @@
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/.idea
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
+1
View File
@@ -1,6 +1,7 @@
.DS_Store .DS_Store
.idea .idea
.vs .vs
.vscode
obj obj
bin bin
*.user *.user
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

+1 -1
View File
@@ -1,5 +1,5 @@
<p align="center"> <p align="center">
<img src="Images/ragon-logo.png" width="200" > <img src="Images/logo.png">
</p> </p>
## Ragon Server ## Ragon Server
+1 -1
View File
@@ -12,7 +12,7 @@
<PropertyGroup Condition=" '$(Configuration)' == 'Release' "> <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<DebugType>none</DebugType> <DebugType>none</DebugType>
<OutputPath>/Users/edmand46/RagonProjects/ragon-oss-examples/Assets/Ragon/Runtime/Plugins</OutputPath> <OutputPath>/Users/edmand46/UnityProjects/itd-client/Assets/Ragon/Runtime/Plugins/</OutputPath>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> <PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
+48 -29
View File
@@ -21,18 +21,47 @@ namespace Ragon.Client
{ {
public sealed class RagonEntity : IDisposable public sealed class RagonEntity : IDisposable
{ {
private class EventSubscription : IDisposable
{
private List<Action<RagonPlayer, IRagonEvent>> _callbacks;
private List<Action<RagonPlayer, IRagonEvent>> _localCallbacks;
private Action<RagonPlayer, IRagonEvent> _callback;
public EventSubscription(
List<Action<RagonPlayer, IRagonEvent>> callbacks,
List<Action<RagonPlayer, IRagonEvent>> localCallbacks,
Action<RagonPlayer, IRagonEvent> callback)
{
_callbacks = callbacks;
_localCallbacks = localCallbacks;
_callback = callback;
}
public void Dispose()
{
_callbacks?.Remove(_callback);
_localCallbacks?.Remove(_callback);
_callbacks = null!;
_localCallbacks = null!;
_callback = null!;
}
}
private delegate void OnEventDelegate(RagonPlayer player, RagonBuffer serializer); private delegate void OnEventDelegate(RagonPlayer player, RagonBuffer serializer);
private RagonClient _client; private RagonClient _client;
public ushort Id { get; private set; } public ushort Id { get; private set; }
public ushort Type { get; private set; } public ushort Type { get; private set; }
public bool Replication { get; private set; }
public RagonAuthority Authority { get; private set; } public RagonAuthority Authority { get; private set; }
public RagonPlayer Owner { get; private set; } public RagonPlayer Owner { get; private set; }
public RagonEntityState State { get; private set; } public RagonEntityState State { get; private set; }
public bool IsStatic => SceneId > 0;
public bool IsReplicated { get; private set; }
public bool IsAttached { get; private set; } public bool IsAttached { get; private set; }
public bool HasAuthority { get; private set; } public bool HasAuthority { get; private set; }
@@ -53,33 +82,27 @@ namespace Ragon.Client
private readonly Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>> _localListeners = new Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>>(); private readonly Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>> _localListeners = new Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>>();
private readonly Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>> _listeners = new Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>>(); private readonly Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>> _listeners = new Dictionary<int, List<Action<RagonPlayer, IRagonEvent>>>();
public RagonEntity(ushort type = 0, ushort sceneId = 0) public RagonEntity(ushort type = 0, ushort sceneId = 0, bool replicated = true)
{ {
State = new RagonEntityState(this); State = new RagonEntityState(this);
Type = type; Type = type;
IsReplicated = replicated;
_spawnPayload = new RagonPayload(0); _spawnPayload = new RagonPayload(0);
_destroyPayload = new RagonPayload(0); _destroyPayload = new RagonPayload(0);
_sceneId = sceneId; _sceneId = sceneId;
} }
internal void Attach(RagonClient client, ushort entityId, ushort entityType, bool hasAuthority, RagonPlayer owner) internal void Attach()
{ {
Type = entityType;
Id = entityId;
Owner = owner;
IsAttached = true; IsAttached = true;
Replication = true;
HasAuthority = hasAuthority;
_client = client;
Attached?.Invoke(this); Attached?.Invoke(this);
} }
internal void SetReplication(bool enabled) public void SetReplication(bool enabled)
{ {
Replication = enabled; IsReplicated = enabled;
} }
internal void Detach(RagonPayload payload) internal void Detach(RagonPayload payload)
@@ -103,9 +126,16 @@ namespace Ragon.Client
return payload; return payload;
} }
public void AttachPayload(RagonPayload payload) public void Prepare(RagonClient client, ushort entityId, ushort entityType, bool hasAuthority, RagonPlayer player, RagonPayload payload)
{ {
Type = entityType;
Id = entityId;
HasAuthority = hasAuthority;
_client = client;
_spawnPayload = payload; _spawnPayload = payload;
Owner = player;
} }
public T GetAttachPayload<T>() where T : IRagonPayload, new() public T GetAttachPayload<T>() where T : IRagonPayload, new()
@@ -166,6 +196,7 @@ namespace Ragon.Client
listener.Invoke(_client.Room.Local, evnt); listener.Invoke(_client.Room.Local, evnt);
return; return;
} }
if (replicationMode == RagonReplicationMode.LocalAndServer) if (replicationMode == RagonReplicationMode.LocalAndServer)
{ {
var localListeners = _localListeners[eventCode]; var localListeners = _localListeners[eventCode];
@@ -189,11 +220,10 @@ namespace Ragon.Client
_client.Reliable.Send(sendData); _client.Reliable.Send(sendData);
} }
public Action<RagonPlayer, IRagonEvent> OnEvent<TEvent>(Action<RagonPlayer, TEvent> callback) where TEvent : IRagonEvent, new() public IDisposable OnEvent<TEvent>(Action<RagonPlayer, TEvent> callback) where TEvent : IRagonEvent, new()
{ {
var t = new TEvent(); var t = new TEvent();
var eventCode = _client.Event.GetEventCode(t); var eventCode = _client.Event.GetEventCode(t);
var action = (RagonPlayer player, IRagonEvent eventData) => callback.Invoke(player, (TEvent)eventData); var action = (RagonPlayer player, IRagonEvent eventData) => callback.Invoke(player, (TEvent)eventData);
if (!_listeners.TryGetValue(eventCode, out var callbacks)) if (!_listeners.TryGetValue(eventCode, out var callbacks))
@@ -222,19 +252,7 @@ namespace Ragon.Client
}); });
} }
return action; return new EventSubscription(callbacks, localCallbacks, action);
}
public void OffEvent<TEvent>(Action<RagonPlayer, IRagonEvent> callback) where TEvent : IRagonEvent, new()
{
var t = new TEvent();
var eventCode = _client.Event.GetEventCode(t);
if (_listeners.TryGetValue(eventCode, out var callbacks))
callbacks.Remove(callback);
if (_localListeners.TryGetValue(eventCode, out var localCallbacks))
localCallbacks.Remove(callback);
} }
internal void Write(RagonBuffer buffer) internal void Write(RagonBuffer buffer)
@@ -246,7 +264,6 @@ namespace Ragon.Client
_propertiesChanged = false; _propertiesChanged = false;
} }
internal void Read(RagonBuffer buffer) internal void Read(RagonBuffer buffer)
{ {
State.ReadState(buffer); State.ReadState(buffer);
@@ -254,6 +271,8 @@ namespace Ragon.Client
internal void Event(ushort eventCode, RagonPlayer caller, RagonBuffer buffer) internal void Event(ushort eventCode, RagonPlayer caller, RagonBuffer buffer)
{ {
if (!IsReplicated) return;
if (_events.TryGetValue(eventCode, out var evnt)) if (_events.TryGetValue(eventCode, out var evnt))
evnt?.Invoke(caller, buffer); evnt?.Invoke(caller, buffer);
else else
@@ -21,6 +21,8 @@ namespace Ragon.Client;
public class RagonPayload public class RagonPayload
{ {
public static RagonPayload Empty = new RagonPayload(0);
private readonly uint[] _data = new uint[128]; private readonly uint[] _data = new uint[128];
private readonly int _size = 0; private readonly int _size = 0;
+6 -5
View File
@@ -63,7 +63,7 @@ namespace Ragon.Client
protected void InvokeChanged() protected void InvokeChanged()
{ {
if (!InvokeLocal) if (_entity.HasAuthority)
return; return;
Changed?.Invoke(); Changed?.Invoke();
@@ -71,7 +71,8 @@ namespace Ragon.Client
protected void MarkAsChanged() protected void MarkAsChanged()
{ {
InvokeChanged(); if (InvokeLocal)
Changed?.Invoke();
if (_dirty || _entity == null) if (_dirty || _entity == null)
return; return;
@@ -106,15 +107,15 @@ namespace Ragon.Client
{ {
Serialize(_propertyBuffer); Serialize(_propertyBuffer);
buffer.FromBuffer(_propertyBuffer, _size); buffer.CopyFrom(_propertyBuffer, _size);
return; return;
} }
Serialize(_propertyBuffer); Serialize(_propertyBuffer);
var propertySize = (ushort)_propertyBuffer.WriteOffset; var propertySize = (ushort)_propertyBuffer.WriteOffset;
buffer.WriteUShort(propertySize);; buffer.WriteUShort(propertySize);
buffer.FromBuffer(_propertyBuffer, propertySize); buffer.CopyFrom(_propertyBuffer, propertySize);
} }
internal void Read(RagonBuffer buffer) internal void Read(RagonBuffer buffer)
@@ -51,17 +51,19 @@ internal class EntityCreateHandler : IHandler
if (player == null) if (player == null)
{ {
RagonLog.Warn($"Owner {ownerId}|{player.Name} not found in players"); RagonLog.Warn($"Owner {ownerId}|{player.Name} not found in players");
_playerCache.Dump();
return; return;
} }
var hasAuthority = _playerCache.Local.Id == player.Id; var hasAuthority = _playerCache.Local.Id == player.Id;
var entity = _entityCache.TryGetEntity(attachId, entityType, 0, entityId, hasAuthority, out var hasCreated); var entity = _entityCache.TryGetEntity(attachId, entityType, 0, entityId, hasAuthority, out var hasCreated);
entity.AttachPayload(payload); entity.Prepare(_client, entityId, entityType, hasAuthority, player, payload);
if (hasCreated) if (hasCreated)
_entityListener.OnEntityCreated(entity); _entityListener.OnEntityCreated(entity);
entity.Attach(_client, entityId, entityType, hasAuthority, player); entity.Attach();
} }
} }
@@ -42,7 +42,9 @@ internal class EntityEventHandler : IHandler
var player = _playerCache.GetPlayerByPeer(peerId); var player = _playerCache.GetPlayerByPeer(peerId);
if (player == null) if (player == null)
{ {
RagonLog.Warn($"Player not found for event {eventCode}"); RagonLog.Error($"Player with peerId:{peerId} not found as owner of event with code:{eventCode}");
_playerCache.Dump();
return; return;
} }
@@ -41,6 +41,14 @@ internal class EntityOwnershipHandler: IHandler
var entities = reader.ReadUShort(); var entities = reader.ReadUShort();
var player = _playerCache.GetPlayerByPeer(newOwnerId); var player = _playerCache.GetPlayerByPeer(newOwnerId);
if (player == null)
{
RagonLog.Error($"Player with Id:{newOwnerId} not found in cache");
_playerCache.Dump();
return;
}
for (var i = 0; i < entities; i++) for (var i = 0; i < entities; i++)
{ {
var entityId = reader.ReadUShort(); var entityId = reader.ReadUShort();
@@ -39,6 +39,13 @@ internal class OwnershipRoomHandler: IHandler
{ {
var newOwnerId = reader.ReadUShort(); var newOwnerId = reader.ReadUShort();
var player = _playerCache.GetPlayerByPeer(newOwnerId); var player = _playerCache.GetPlayerByPeer(newOwnerId);
if (player == null)
{
RagonLog.Warn($"Player with peerId:{newOwnerId} not found in cache");
_playerCache.Dump();
return;
}
_playerCache.OnOwnershipChanged(newOwnerId); _playerCache.OnOwnershipChanged(newOwnerId);
_listenerList.OnOwnershipChanged(player); _listenerList.OnOwnershipChanged(player);
@@ -45,6 +45,6 @@ internal class PlayerJoinHandler : IHandler
if (player != null) if (player != null)
_listenerList.OnPlayerJoined(player); _listenerList.OnPlayerJoined(player);
else else
RagonLog.Trace($"[Joined] {playerId}"); RagonLog.Warn($"Player with Id:{playerId} not found in cache");
} }
} }
@@ -57,5 +57,9 @@ internal class PlayerLeftHandler : IHandler
foreach (var id in toDeleteIds) foreach (var id in toDeleteIds)
_entityCache.OnDestroy(id, emptyPayload); _entityCache.OnDestroy(id, emptyPayload);
} }
else
{
RagonLog.Warn($"Player with Id:{playerId} not found in cache");
}
} }
} }
@@ -37,6 +37,15 @@ internal class RoomDataHandler: IHandler
var rawData = reader.RawData; var rawData = reader.RawData;
var peerId = (ushort)(rawData[1] + (rawData[2] << 8)); var peerId = (ushort)(rawData[1] + (rawData[2] << 8));
var player = _playerCache.GetPlayerByPeer(peerId); var player = _playerCache.GetPlayerByPeer(peerId);
if (player == null)
{
RagonLog.Error($"Player with peerId:{peerId} not found");
_playerCache.Dump();
return;
}
var headerSize = 3; var headerSize = 3;
var payload = new byte[rawData.Length - headerSize]; var payload = new byte[rawData.Length - headerSize];
@@ -41,7 +41,9 @@ public class RoomEventHandler: IHandler
var player = _playerCache.GetPlayerByPeer(peerId); var player = _playerCache.GetPlayerByPeer(peerId);
if (player == null) if (player == null)
{ {
RagonLog.Warn($"Player not found for event {eventCode}"); RagonLog.Error($"Player with peerId:{peerId} not found as owner of event with code:{eventCode}");
_playerCache.Dump();
return; return;
} }
@@ -45,6 +45,7 @@ internal class SnapshotHandler : IHandler
public void Handle(RagonBuffer buffer) public void Handle(RagonBuffer buffer)
{ {
var entities = new List<RagonEntity>();
var playersCount = buffer.ReadUShort(); var playersCount = buffer.ReadUShort();
RagonLog.Trace("Players: " + playersCount); RagonLog.Trace("Players: " + playersCount);
for (var i = 0; i < playersCount; i++) for (var i = 0; i < playersCount; i++)
@@ -70,25 +71,28 @@ internal class SnapshotHandler : IHandler
var player = _playerCache.GetPlayerByPeer(ownerPeerId); var player = _playerCache.GetPlayerByPeer(ownerPeerId);
if (player == null) if (player == null)
{ {
RagonLog.Error($"Player not found with peerId: ${ownerPeerId}"); RagonLog.Error($"Player not found with peerId: {ownerPeerId}");
_playerCache.Dump();
return; return;
} }
var hasAuthority = _playerCache.Local.Id == player.Id; var hasAuthority = _playerCache.Local.Id == player.Id;
var entity = _entityCache.TryGetEntity(0, entityType, 0, entityId, hasAuthority, out _); var entity = _entityCache.TryGetEntity(0, entityType, 0, entityId, hasAuthority, out _);
var payload = RagonPayload.Empty;
if (payloadSize > 0) if (payloadSize > 0)
{ {
var payload = new RagonPayload(payloadSize); payload = new RagonPayload(payloadSize);
payload.Read(buffer); payload.Read(buffer);
entity.AttachPayload(payload);
} }
entity.Prepare(_client, entityId, entityType, hasAuthority, player, payload);
_entityListener.OnEntityCreated(entity); _entityListener.OnEntityCreated(entity);
entity.Read(buffer); entity.Read(buffer);
entity.Attach(_client, entityId, entityType, hasAuthority, player);
entities.Add(entity);
} }
var staticEntities = buffer.ReadUShort(); var staticEntities = buffer.ReadUShort();
@@ -104,15 +108,19 @@ internal class SnapshotHandler : IHandler
var player = _playerCache.GetPlayerByPeer(ownerPeerId); var player = _playerCache.GetPlayerByPeer(ownerPeerId);
if (player == null) if (player == null)
{ {
RagonLog.Error($"Player not found with peerId: ${ownerPeerId}"); RagonLog.Error($"Player not found with peerId: {ownerPeerId}");
_playerCache.Dump();
return; return;
} }
var hasAuthority = _playerCache.Local.Id == player.Id; var hasAuthority = _playerCache.Local.Id == player.Id;
var entity = _entityCache.TryGetEntity(0, entityType, staticId, entityId, hasAuthority, out _); var entity = _entityCache.TryGetEntity(0, entityType, staticId, entityId, hasAuthority, out _);
entity.Prepare(_client, entityId, entityType, hasAuthority, player, RagonPayload.Empty);
entity.Read(buffer); entity.Read(buffer);
entity.Attach(_client, entityId, entityType, hasAuthority, player);
entities.Add(entity);
} }
if (_client.Status == RagonStatus.LOBBY) if (_client.Status == RagonStatus.LOBBY)
@@ -121,6 +129,9 @@ internal class SnapshotHandler : IHandler
_listenerList.OnJoined(); _listenerList.OnJoined();
} }
foreach (var entity in entities)
entity.Attach();
_listenerList.OnSceneLoaded(); _listenerList.OnSceneLoaded();
} }
} }
-1
View File
@@ -48,7 +48,6 @@ namespace Ragon.Client
public NetworkStatistics Statistics => _stats; public NetworkStatistics Statistics => _stats;
public RagonRoom Room => _room; public RagonRoom Room => _room;
internal RagonBuffer Buffer => _writeBuffer; internal RagonBuffer Buffer => _writeBuffer;
internal INetworkChannel Reliable => _connection.Reliable; internal INetworkChannel Reliable => _connection.Reliable;
internal INetworkChannel Unreliable => _connection.Unreliable; internal INetworkChannel Unreliable => _connection.Unreliable;
+2 -6
View File
@@ -116,7 +116,7 @@ public sealed class RagonEntityCache
foreach (var ent in _entityList) foreach (var ent in _entityList)
{ {
if (!ent.IsAttached || if (!ent.IsAttached ||
!ent.Replication || !ent.IsReplicated ||
!ent.PropertiesChanged) continue; !ent.PropertiesChanged) continue;
ent.Write(buffer); ent.Write(buffer);
@@ -186,12 +186,10 @@ public sealed class RagonEntityCache
} }
} }
if (_pendingEntities.TryGetValue(attachId, out var pendingEntity)) if (_pendingEntities.TryGetValue(attachId, out var pendingEntity) && hasAuthority)
{ {
_pendingEntities.Remove(attachId); _pendingEntities.Remove(attachId);
_entityMap.Add(entityId, pendingEntity); _entityMap.Add(entityId, pendingEntity);
if (hasAuthority)
_entityList.Add(pendingEntity); _entityList.Add(pendingEntity);
hasCreated = false; hasCreated = false;
@@ -199,7 +197,6 @@ public sealed class RagonEntityCache
return pendingEntity; return pendingEntity;
} }
var entity = new RagonEntity(entityType, sceneId); var entity = new RagonEntity(entityType, sceneId);
_entityMap.Add(entityId, entity); _entityMap.Add(entityId, entity);
@@ -217,7 +214,6 @@ public sealed class RagonEntityCache
{ {
if (_entityMap.TryGetValue(entityId, out var entity)) if (_entityMap.TryGetValue(entityId, out var entity))
{ {
_entityMap.Remove(entityId); _entityMap.Remove(entityId);
_entityList.Remove(entity); _entityList.Remove(entity);
+25 -2
View File
@@ -27,8 +27,21 @@ public sealed class RagonPlayerCache
public RagonPlayer Local { get; private set; } public RagonPlayer Local { get; private set; }
public bool IsRoomOwner => _ownerId == _localId; public bool IsRoomOwner => _ownerId == _localId;
public RagonPlayer? GetPlayerById(string playerId) => _playersById[playerId]; public RagonPlayer? GetPlayerById(string playerId)
public RagonPlayer? GetPlayerByPeer(ushort peerId) => _playersByConnection[peerId]; {
if (_playersById.TryGetValue(playerId, out var player))
return player;
return null;
}
public RagonPlayer? GetPlayerByPeer(ushort peerId)
{
if (_playersByConnection.TryGetValue(peerId, out var player))
return player;
return null;
}
private string _ownerId; private string _ownerId;
private string _localId; private string _localId;
@@ -91,4 +104,14 @@ public sealed class RagonPlayerCache
_playersByConnection.Clear(); _playersByConnection.Clear();
_playersById.Clear(); _playersById.Clear();
} }
public void Dump()
{
RagonLog.Trace("Players: ");
RagonLog.Trace("[Connection] [ID] [Name]");
foreach (var player in _players)
{
RagonLog.Trace($"[{player.PeerId}] {player.Id} {player.Name}");
}
}
} }
+2 -2
View File
@@ -51,9 +51,9 @@ namespace Ragon.Client
Create(null, new RagonRoomParameters() {Scene = sceneName, Min = minPlayers, Max = maxPlayers}); Create(null, new RagonRoomParameters() {Scene = sceneName, Min = minPlayers, Max = maxPlayers});
} }
public void Create(string roomId, string sceneNa, int minPlayers, int maxPlayers) public void Create(string roomId, string sceneName, int minPlayers, int maxPlayers)
{ {
Create(roomId, new RagonRoomParameters() {Scene = sceneNa, Min = minPlayers, Max = maxPlayers}); Create(roomId, new RagonRoomParameters() {Scene = sceneName, Min = minPlayers, Max = maxPlayers});
} }
public void Create(string roomId, RagonRoomParameters parameters) public void Create(string roomId, RagonRoomParameters parameters)
-1
View File
@@ -6,7 +6,6 @@
<LangVersion>8</LangVersion> <LangVersion>8</LangVersion>
<RootNamespace>Ragon.Common</RootNamespace> <RootNamespace>Ragon.Common</RootNamespace>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild> <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Version>1.2.4-rc</Version>
<Title>Ragon.Protocol</Title> <Title>Ragon.Protocol</Title>
<Copyright>Eduard Kargin</Copyright> <Copyright>Eduard Kargin</Copyright>
<PackageProjectUrl>https://ragon-server.com</PackageProjectUrl> <PackageProjectUrl>https://ragon-server.com</PackageProjectUrl>
+3 -6
View File
@@ -75,7 +75,7 @@ namespace Ragon.Protocol
public int ReadOffset => _read; public int ReadOffset => _read;
public int WriteOffset => _write; public int WriteOffset => _write;
public int Length => ((_write - 1) >> 3) + 1; public int Length => ((_write - 1) >> 3) + 1;
public int Capacity => _write - _read; public int Capacity => _write - _read - 1;
public RagonBuffer(int capacity = 128) public RagonBuffer(int capacity = 128)
{ {
@@ -236,9 +236,6 @@ namespace Ragon.Protocol
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(uint value, int numBits = 16) public void Write(uint value, int numBits = 16)
{ {
Debug.Assert(!(numBits < 0));
Debug.Assert(!(numBits > 32));
var currentBucketIndex = _write >> 5; var currentBucketIndex = _write >> 5;
var used = _write & 0x0000001F; var used = _write & 0x0000001F;
var mask = (1UL << used) - 1; var mask = (1UL << used) - 1;
@@ -357,7 +354,7 @@ namespace Ragon.Protocol
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public void FromBuffer(RagonBuffer buffer, int size) public void CopyFrom(RagonBuffer buffer, int size)
{ {
WriteArray(buffer._buckets, size); WriteArray(buffer._buckets, size);
} }
@@ -434,7 +431,7 @@ namespace Ragon.Protocol
public void ToArray(byte[] outData) public void ToArray(byte[] outData)
{ {
Debug.Assert(outData.Length >= Length); Write(1, 1);
var bucketsCount = (_write >> 5) + 1; var bucketsCount = (_write >> 5) + 1;
var length = Length; var length = Length;
+6
View File
@@ -1,5 +1,6 @@
using System; using System;
using Newtonsoft.Json; using Newtonsoft.Json;
using Ragon.Server;
using Ragon.Server.Plugin; using Ragon.Server.Plugin;
namespace Ragon.Relay; namespace Ragon.Relay;
@@ -21,4 +22,9 @@ public class RelayServerPlugin: BaseServerPlugin
return true; return true;
} }
public override IRoomPlugin CreateRoomPlugin(RoomInformation information)
{
return new RelayRoomPlugin();
}
} }
@@ -46,6 +46,9 @@ public class WebSocketServer : INetworkServer
public async void StartAccept(CancellationToken cancellationToken) public async void StartAccept(CancellationToken cancellationToken)
{ {
while (!cancellationToken.IsCancellationRequested) while (!cancellationToken.IsCancellationRequested)
{
WebSocketConnection connection = null!;
try
{ {
var context = await _httpListener.GetContextAsync(); var context = await _httpListener.GetContextAsync();
if (!context.Request.IsWebSocketRequest) if (!context.Request.IsWebSocketRequest)
@@ -58,11 +61,18 @@ public class WebSocketServer : INetworkServer
var webSocketContext = await context.AcceptWebSocketAsync(null); var webSocketContext = await context.AcceptWebSocketAsync(null);
var webSocket = webSocketContext.WebSocket; var webSocket = webSocketContext.WebSocket;
var peerId = _sequencer.Pop(); var peerId = _sequencer.Pop();
var connection = new WebSocketConnection(webSocket, peerId);
_connections[peerId] = connection; connection = new WebSocketConnection(webSocket, peerId);
}
catch (Exception ex)
{
_logger.Warn(ex);
continue;
}
_connections[connection.Id] = connection;
StartListen(connection, cancellationToken); StartListen(connection, cancellationToken);
} }
} }
@@ -75,6 +85,7 @@ public class WebSocketServer : INetworkServer
var webSocket = connection.Socket; var webSocket = connection.Socket;
var bytes = new byte[2048]; var bytes = new byte[2048];
var buffer = new Memory<byte>(bytes); var buffer = new Memory<byte>(bytes);
while ( while (
webSocket.State == WebSocketState.Open || webSocket.State == WebSocketState.Open ||
!cancellationToken.IsCancellationRequested) !cancellationToken.IsCancellationRequested)
@@ -84,7 +95,7 @@ public class WebSocketServer : INetworkServer
var result = await webSocket.ReceiveAsync(buffer, cancellationToken); var result = await webSocket.ReceiveAsync(buffer, cancellationToken);
if (result.Count > 0) if (result.Count > 0)
{ {
var payload = buffer.Slice(0, buffer.Length); var payload = buffer.Slice(0, result.Count);
_networkListener.OnData(connection, NetworkChannel.RELIABLE, payload.ToArray()); _networkListener.OnData(connection, NetworkChannel.RELIABLE, payload.ToArray());
} }
} }
@@ -96,6 +107,7 @@ public class WebSocketServer : INetworkServer
_sequencer.Push(connection.Id); _sequencer.Push(connection.Id);
_activeConnections.Remove(connection); _activeConnections.Remove(connection);
_networkListener.OnDisconnected(connection); _networkListener.OnDisconnected(connection);
} }
+1 -1
View File
@@ -5,7 +5,7 @@
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<RootNamespace>Ragon.Core</RootNamespace> <RootNamespace>Ragon.Core</RootNamespace>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild> <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Version>1.2.4-rc</Version> <Version>1.3.1</Version>
<Title>Ragon.Server</Title> <Title>Ragon.Server</Title>
<Copyright>Eduard Kargin</Copyright> <Copyright>Eduard Kargin</Copyright>
<PackageProjectUrl>https://ragon-server.com</PackageProjectUrl> <PackageProjectUrl>https://ragon-server.com</PackageProjectUrl>
@@ -14,7 +14,6 @@
* limitations under the License. * limitations under the License.
*/ */
using Ragon.Protocol; using Ragon.Protocol;
namespace Ragon.Server.Entity; namespace Ragon.Server.Entity;
@@ -54,6 +54,13 @@ public class RagonProperty : RagonPayload
public void Write(RagonBuffer buffer) public void Write(RagonBuffer buffer)
{ {
if (IsFixed)
{
buffer.WriteArray(_data, Size);
return;
}
buffer.Write((ushort) Size);
buffer.WriteArray(_data, Size); buffer.WriteArray(_data, Size);
} }
+2 -2
View File
@@ -39,13 +39,13 @@ public class RagonEvent
public void Read(RagonBuffer buffer) public void Read(RagonBuffer buffer)
{ {
_size = buffer.Capacity - 1; _size = buffer.Capacity;
buffer.ReadArray(_data, _size); buffer.ReadArray(_data, _size);
} }
public void Write(RagonBuffer buffer) public void Write(RagonBuffer buffer)
{ {
if (_size == 0) return; if (_size <= 0) return;
buffer.WriteArray(_data, _size); buffer.WriteArray(_data, _size);
} }
} }
@@ -32,18 +32,17 @@ public sealed class RoomDataOperation : BaseOperation
var room = context.Room; var room = context.Room;
var data = Reader.RawData; var data = Reader.RawData;
var dataSize = data.Length - 1;
Writer.Clear(); var headerSize = 3;
Writer.WriteOperation(RagonOperation.REPLICATE_RAW_DATA); var size = headerSize + dataSize;
Writer.WriteUShort(player.Connection.Id);
var playerData = Writer.ToArray();
var payloadData = data;
var size = playerData.Length + payloadData.Length;
var sendData = new byte[size]; var sendData = new byte[size];
var peerId = player.Connection.Id;
Array.Copy(playerData, 0, sendData, 0, playerData.Length); sendData[0] = (byte)RagonOperation.REPLICATE_RAW_DATA;
Array.Copy(payloadData, 1, sendData, playerData.Length, payloadData.Length - 1); sendData[1] = (byte)peerId;
sendData[2] = (byte)(peerId >> 8);
Array.Copy(data, 1, sendData, headerSize, dataSize);
room.Broadcast(sendData, channel); room.Broadcast(sendData, channel);
} }
+3
View File
@@ -14,6 +14,8 @@
* limitations under the License. * limitations under the License.
*/ */
using Ragon.Protocol;
using Ragon.Server.Handler;
using Ragon.Server.IO; using Ragon.Server.IO;
using Ragon.Server.Lobby; using Ragon.Server.Lobby;
@@ -21,6 +23,7 @@ namespace Ragon.Server;
public interface IRagonServer public interface IRagonServer
{ {
BaseOperation ResolveHandler(RagonOperation operation);
RagonLobbyPlayer? GetPlayerByConnection(INetworkConnection connection); RagonLobbyPlayer? GetPlayerByConnection(INetworkConnection connection);
RagonLobbyPlayer? GetPlayerById(string id); RagonLobbyPlayer? GetPlayerById(string id);
} }
@@ -25,12 +25,20 @@ public class LobbyInMemory : IRagonLobby
private readonly List<RagonRoom> _rooms = new(); private readonly List<RagonRoom> _rooms = new();
private readonly Logger _logger = LogManager.GetCurrentClassLogger(); private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public bool FindRoomById(string RagonRoomId, [MaybeNullWhen(false)] out RagonRoom room) public bool FindRoomById(string roomId, [MaybeNullWhen(false)] out RagonRoom room)
{ {
foreach (var existRagonRoom in _rooms) foreach (var existRagonRoom in _rooms)
{ {
if (existRagonRoom.Id == RagonRoomId && existRagonRoom.PlayerMin < existRagonRoom.PlayerMax) if (existRagonRoom.Id == roomId)
{ {
if (existRagonRoom.PlayerCount >= existRagonRoom.PlayerMax)
{
_logger.Warn($"Room with id {roomId} fulfilled");
room = default;
return false;
}
room = existRagonRoom; room = existRagonRoom;
return true; return true;
} }
@@ -44,8 +52,16 @@ public class LobbyInMemory : IRagonLobby
{ {
foreach (var existsRoom in _rooms) foreach (var existsRoom in _rooms)
{ {
if (existsRoom.Scene == sceneName && existsRoom.PlayerCount < existsRoom.PlayerMax) if (existsRoom.Scene == sceneName)
{ {
if (existsRoom.PlayerCount >= existsRoom.PlayerMax)
{
_logger.Warn($"Room with scene {sceneName} fulfilled");
room = default;
return false;
}
room = existsRoom; room = existsRoom;
return true; return true;
} }
@@ -0,0 +1,9 @@
namespace Ragon.Server.Logging;
public interface IRagonLogger
{
public void Warning(string tag, string message);
public void Info(string tag, string message);
public void Error(string tag, string message);
public void Trace(string tag, string message);
}
@@ -49,7 +49,7 @@ public class BaseServerPlugin: IServerPlugin
return true; return true;
} }
public IRoomPlugin CreateRoomPlugin(RoomInformation information) public virtual IRoomPlugin CreateRoomPlugin(RoomInformation information)
{ {
return new BaseRoomPlugin(); return new BaseRoomPlugin();
} }
@@ -28,10 +28,10 @@ public class RagonWebHookPlugin
{ {
private Dictionary<string, string> _webHooks; private Dictionary<string, string> _webHooks;
private RagonServer _server; private IRagonServer _server;
private HttpClient _httpClient; private HttpClient _httpClient;
public RagonWebHookPlugin(RagonServer server, RagonServerConfiguration configuration) public RagonWebHookPlugin(IRagonServer server, RagonServerConfiguration configuration)
{ {
_webHooks = new Dictionary<string, string>(configuration.WebHooks); _webHooks = new Dictionary<string, string>(configuration.WebHooks);
_httpClient = new HttpClient(); _httpClient = new HttpClient();
@@ -46,7 +46,7 @@ public class RagonWebHookPlugin
var executor = context.Executor; var executor = context.Executor;
executor.Run(async () => executor.Run(async () =>
{ {
var authorizationOperation = (AuthorizationOperation) _server.ResolveOperation(RagonOperation.AUTHORIZE); var authorizationOperation = (AuthorizationOperation) _server.ResolveHandler(RagonOperation.AUTHORIZE);
var response = await _httpClient.PostAsync(new Uri(value), httpContent); var response = await _httpClient.PostAsync(new Uri(value), httpContent);
if (response.StatusCode != HttpStatusCode.OK) if (response.StatusCode != HttpStatusCode.OK)
{ {
+7 -2
View File
@@ -99,6 +99,11 @@ public class RagonServer : IRagonServer, INetworkListener
_timer.Start(); _timer.Start();
while (true) while (true)
{ {
if (_timer.ElapsedMilliseconds > _tickRate * 2)
{
_logger.Warn($"Slow perfomance: {_timer.ElapsedMilliseconds}");
}
if (_timer.ElapsedMilliseconds > _tickRate) if (_timer.ElapsedMilliseconds > _tickRate)
{ {
_timer.Restart(); _timer.Restart();
@@ -197,7 +202,7 @@ public class RagonServer : IRagonServer, INetworkListener
_reader.FromArray(data); _reader.FromArray(data);
var operation = _reader.ReadByte(); var operation = _reader.ReadByte();
_handlers[operation].Handle(context, channel); _handlers[operation]?.Handle(context, channel);
} }
} }
catch (Exception ex) catch (Exception ex)
@@ -223,7 +228,7 @@ public class RagonServer : IRagonServer, INetworkListener
_server.Broadcast(sendData, NetworkChannel.UNRELIABLE); _server.Broadcast(sendData, NetworkChannel.UNRELIABLE);
} }
public BaseOperation ResolveOperation(RagonOperation operation) public BaseOperation ResolveHandler(RagonOperation operation)
{ {
return _handlers[(byte)operation]; return _handlers[(byte)operation];
} }
@@ -25,11 +25,6 @@ public enum ServerType
WEBSOCKET, WEBSOCKET,
} }
public class WebHook
{
}
[Serializable] [Serializable]
public struct RagonServerConfiguration public struct RagonServerConfiguration
{ {
@@ -47,7 +42,7 @@ public struct RagonServerConfiguration
public Dictionary<string, string> WebHooks; public Dictionary<string, string> WebHooks;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private static readonly string ServerVersion = "1.2.9-rc"; private static readonly string ServerVersion = "1.3.2";
private static Dictionary<string, ServerType> _serverTypes = new Dictionary<string, ServerType>() private static Dictionary<string, ServerType> _serverTypes = new Dictionary<string, ServerType>()
{ {
{"enet", Server.ServerType.ENET}, {"enet", Server.ServerType.ENET},
@@ -127,5 +127,10 @@ namespace Ragon.Client
if (_libraryLoaded) if (_libraryLoaded)
Library.Deinitialize(); Library.Deinitialize();
} }
public void Close()
{
}
} }
} }
@@ -128,5 +128,10 @@ namespace Ragon.Client
if (_libraryLoaded) if (_libraryLoaded)
Library.Deinitialize(); Library.Deinitialize();
} }
public void Close()
{
}
} }
} }
+1 -2
View File
@@ -1,5 +1,4 @@
 using Ragon.Client.Property;
using Ragon.Protocol; using Ragon.Protocol;
namespace Ragon.Client.Simulation; namespace Ragon.Client.Simulation;
+7
View File
@@ -0,0 +1,7 @@
{
"sdk": {
"version": "7.0.0",
"rollForward": "latestMajor",
"allowPrerelease": false
}
}