major update

This commit is contained in:
2023-03-06 10:06:43 +04:00
parent e84511e1ae
commit cbda5e9974
174 changed files with 7441 additions and 1975 deletions
+212
View File
@@ -0,0 +1,212 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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 Ragon.Protocol;
namespace Ragon.Server;
public class RagonEntity
{
private static ushort _idGenerator = 100;
public ushort Id { get; private set; }
public ushort Type { get; private set; }
public ushort StaticId { get; private set; }
public ushort AttachId { get; private set; }
public RagonRoomPlayer Owner { get; private set; }
public RagonAuthority Authority { get; private set; }
public RagonPayload Payload { get; private set; }
public RagonEntityState State { get; private set; }
private readonly List<RagonEvent> _bufferedEvents;
public RagonEntity(RagonRoomPlayer owner, ushort type, ushort staticId, ushort attachId, RagonAuthority eventAuthority)
{
Owner = owner;
StaticId = staticId;
Type = type;
AttachId = attachId;
Id = _idGenerator++;
Authority = eventAuthority;
State = new RagonEntityState(this);
Payload = new RagonPayload();
_bufferedEvents = new List<RagonEvent>();
}
public void SetOwner(RagonRoomPlayer owner)
{
Owner = owner;
}
public void RestoreBufferedEvents(RagonRoomPlayer roomPlayer, RagonBuffer writer)
{
foreach (var evnt in _bufferedEvents)
{
writer.Clear();
writer.WriteOperation(RagonOperation.REPLICATE_ENTITY_EVENT);
writer.WriteUShort(evnt.EventCode);
writer.WriteUShort(evnt.Invoker.Connection.Id);
writer.WriteByte((byte)RagonReplicationMode.Server);
writer.WriteUShort(Id);
evnt.Write(writer);
var sendData = writer.ToArray();
roomPlayer.Connection.Reliable.Send(sendData);
}
}
public void Create()
{
var room = Owner.Room;
var buffer = room.Writer;
buffer.Clear();
buffer.WriteOperation(RagonOperation.CREATE_ENTITY);
buffer.WriteUShort(AttachId);
buffer.WriteUShort(Type);
buffer.WriteUShort(Id);
buffer.WriteUShort(Owner.Connection.Id);
Payload.Write(buffer);
var sendData = buffer.ToArray();
foreach (var player in room.ReadyPlayersList)
player.Connection.Reliable.Send(sendData);
}
public void Destroy()
{
var room = Owner.Room;
var buffer = room.Writer;
buffer.Clear();
buffer.WriteOperation(RagonOperation.DESTROY_ENTITY);
buffer.WriteUShort(Id);
Payload.Write(buffer);
var sendData = buffer.ToArray();
foreach (var player in room.ReadyPlayersList)
player.Connection.Reliable.Send(sendData);
}
public void Snapshot(RagonBuffer buffer)
{
buffer.WriteUShort(Type);
buffer.WriteUShort(Id);
if (StaticId != 0)
buffer.WriteUShort(StaticId);
buffer.WriteUShort(Owner.Connection.Id);
buffer.WriteUShort(Payload.Size);
Payload.Write(buffer);
State.Snapshot(buffer);
}
public void ReplicateEvent(
RagonRoomPlayer caller,
RagonEvent evnt,
RagonReplicationMode eventMode,
RagonRoomPlayer targetPlayer
)
{
var room = Owner.Room;
var buffer = room.Writer;
buffer.Clear();
buffer.WriteOperation(RagonOperation.REPLICATE_ENTITY_EVENT);
buffer.WriteUShort(evnt.EventCode);
buffer.WriteUShort(caller.Connection.Id);
buffer.WriteByte((byte)eventMode);
buffer.WriteUShort(Id);
evnt.Write(buffer);
var sendData = buffer.ToArray();
targetPlayer.Connection.Reliable.Send(sendData);
}
public void ReplicateEvent(
RagonRoomPlayer caller,
RagonEvent evnt,
RagonReplicationMode eventMode,
RagonTarget targetMode
)
{
if (Authority == RagonAuthority.OwnerOnly &&
Owner.Connection.Id != caller.Connection.Id)
{
Console.WriteLine($"Player have not enough authority for event with Id {evnt.EventCode}");
return;
}
if (eventMode == RagonReplicationMode.Buffered && targetMode != RagonTarget.Owner)
{
_bufferedEvents.Add(evnt);
}
var room = Owner.Room;
var buffer = room.Writer;
buffer.Clear();
buffer.WriteOperation(RagonOperation.REPLICATE_ENTITY_EVENT);
buffer.WriteUShort(evnt.EventCode);
buffer.WriteUShort(caller.Connection.Id);
buffer.WriteByte((byte)eventMode);
buffer.WriteUShort(Id);
evnt.Write(buffer);
var sendData = buffer.ToArray();
switch (targetMode)
{
case RagonTarget.Owner:
{
Owner.Connection.Reliable.Send(sendData);
break;
}
case RagonTarget.ExceptOwner:
{
foreach (var roomPlayer in room.ReadyPlayersList)
{
if (roomPlayer.Connection.Id != Owner.Connection.Id)
roomPlayer.Connection.Reliable.Send(sendData);
}
break;
}
case RagonTarget.ExceptInvoker:
{
foreach (var roomPlayer in room.ReadyPlayersList)
{
if (roomPlayer.Connection.Id != caller.Connection.Id)
roomPlayer.Connection.Reliable.Send(sendData);
}
break;
}
case RagonTarget.All:
{
foreach (var roomPlayer in room.ReadyPlayersList)
roomPlayer.Connection.Reliable.Send(sendData);
break;
}
}
}
}
@@ -0,0 +1,79 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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 Ragon.Protocol;
namespace Ragon.Server;
public class RagonEntityState
{
private List<RagonProperty> _properties;
private RagonEntity _entity;
public RagonEntityState(RagonEntity entity, int capacity = 10)
{
_entity = entity;
_properties = new List<RagonProperty>(10);
}
public void AddProperty(RagonProperty property)
{
_properties.Add(property);
}
public void Write(RagonBuffer buffer)
{
buffer.WriteUShort(_entity.Id);
foreach (var property in _properties)
{
if (property.IsDirty)
{
buffer.WriteBool(true);
property.Write(buffer);
property.Clear();
continue;
}
buffer.WriteBool(false);
}
}
public void Read(RagonBuffer buffer)
{
foreach (var property in _properties)
{
if (buffer.ReadBool())
property.Read(buffer);
}
}
public void Snapshot(RagonBuffer buffer)
{
foreach (var property in _properties)
{
var hasPayload = property.IsFixed || !property.IsFixed && property.Size > 0;
if (hasPayload)
{
buffer.WriteBool(true);
property.Write(buffer);
continue;
}
buffer.WriteBool(false);
}
}
}
+53
View File
@@ -0,0 +1,53 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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 Ragon.Protocol;
namespace Ragon.Server;
public class RagonEvent
{
public RagonRoomPlayer Invoker { get; private set; }
public ushort EventCode { get; private set; }
public ushort Size => (ushort) _size;
private uint[] _data = new uint[128];
private int _size = 0;
public RagonEvent(
RagonRoomPlayer invoker,
ushort eventCode
)
{
Invoker = invoker;
EventCode = eventCode;
}
public void Read(RagonBuffer buffer)
{
var readOnlySpan = _data.AsSpan();
_size = buffer.Capacity;
buffer.ReadSpan(ref readOnlySpan, _size);
}
public void Write(RagonBuffer buffer)
{
if (_size == 0) return;
ReadOnlySpan<uint> readOnlySpan = _data.AsSpan();
buffer.WriteSpan(ref readOnlySpan, _size);
}
}
@@ -0,0 +1,46 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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 Ragon.Protocol;
namespace Ragon.Server;
public class RagonPayload
{
private uint[] _data = new uint[128];
private int _size = 0;
public ushort Size => (ushort) _size;
public void Read(RagonBuffer buffer)
{
var readOnlySpan = _data.AsSpan();
_size = buffer.Capacity;
buffer.ReadSpan(ref readOnlySpan, _size);
}
public void Write(RagonBuffer buffer)
{
if (_size == 0) return;
ReadOnlySpan<uint> readOnlySpan = _data.AsSpan();
buffer.WriteSpan(ref readOnlySpan, _size);
}
}
@@ -0,0 +1,71 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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.ComponentModel;
using Ragon.Protocol;
namespace Ragon.Server;
public class RagonProperty : RagonPayload
{
public int Size { get; set; }
public bool IsDirty { get; private set; }
public bool IsFixed { get; private set; }
private uint[] _data;
public RagonProperty(int size, bool isFixed)
{
Size = size;
IsFixed = isFixed;
IsDirty = false;
_data = new uint[128];
}
public void Read(RagonBuffer buffer)
{
var readOnlySpan = _data.AsSpan();
if (IsFixed)
{
buffer.ReadSpan(ref readOnlySpan, Size);
}
else
{
Size = (int) buffer.Read();
buffer.ReadSpan(ref readOnlySpan, Size);
}
IsDirty = true;
}
public void Write(RagonBuffer buffer)
{
ReadOnlySpan<uint> readOnlySpan = _data.AsSpan();
buffer.WriteSpan(ref readOnlySpan, Size);
}
public void Clear()
{
IsDirty = false;
}
public void Dump()
{
Console.WriteLine( $"[{Size.ToString("00")}] {string.Join("", _data.Take(8).Reverse().Select(b => Convert.ToString(b, 2).PadLeft(32, '0')))}");
}
}
@@ -0,0 +1,55 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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 NLog;
using Ragon.Protocol;
namespace Ragon.Server;
public sealed class AuthorizationOperation: IRagonOperation
{
private Logger _logger = LogManager.GetCurrentClassLogger();
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer)
{
if (context.LobbyPlayer.Status == LobbyPlayerStatus.Authorized)
{
_logger.Warn("Player already authorized");
return;
}
var key = reader.ReadString();
var playerName = reader.ReadString();
var additionalPayload = new RagonPayload();
additionalPayload.Read(reader);
context.LobbyPlayer.Name = playerName;
context.LobbyPlayer.AdditionalData = Array.Empty<byte>();
context.LobbyPlayer.Status = LobbyPlayerStatus.Authorized;
var playerId = context.LobbyPlayer.Id;
writer.Clear();
writer.WriteOperation(RagonOperation.AUTHORIZED_SUCCESS);
writer.WriteString(playerId);
writer.WriteString(playerName);
var sendData = writer.ToArray();
context.Connection.Reliable.Send(sendData);
_logger.Trace($"Connection {context.Connection.Id} as {playerId}|{context.LobbyPlayer.Name} authorized");
}
}
@@ -0,0 +1,54 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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 NLog;
using Ragon.Protocol;
namespace Ragon.Server;
public sealed class EntityCreateOperation : IRagonOperation
{
private Logger _logger = LogManager.GetCurrentClassLogger();
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer)
{
var player = context.RoomPlayer;
var room = context.Room;
var attachId = reader.ReadUShort();
var entityType = reader.ReadUShort();
var eventAuthority = (RagonAuthority) reader.ReadByte();
var propertiesCount = reader.ReadUShort();
var entity = new RagonEntity(player, entityType, 0, attachId, eventAuthority);
for (var i = 0; i < propertiesCount; i++)
{
var propertyType = reader.ReadBool();
var propertySize = reader.ReadUShort();
entity.State.AddProperty(new RagonProperty(propertySize, propertyType));
}
if (reader.Capacity > 0)
entity.Payload.Read(reader);
room.AttachEntity(entity);
player.AttachEntity(entity);
entity.Create();
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} created entity {entity.Id}:{entity.Type}");
}
}
@@ -0,0 +1,45 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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 NLog;
using Ragon.Protocol;
namespace Ragon.Server;
public sealed class EntityDestroyOperation: IRagonOperation
{
private Logger _logger = LogManager.GetCurrentClassLogger();
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer)
{
var player = context.RoomPlayer;
var room = context.Room;
var entityId = reader.ReadUShort();
if (room.Entities.TryGetValue(entityId, out var entity))
{
var payload = new RagonPayload();
payload.Read(reader);
room.DetachEntity(entity);
player.DetachEntity(entity);
entity.Destroy();
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} destoyed entity {entity.Id}");
}
}
}
@@ -0,0 +1,58 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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 NLog;
using Ragon.Protocol;
namespace Ragon.Server;
public sealed class EntityEventOperation : IRagonOperation
{
private Logger _logger = LogManager.GetCurrentClassLogger();
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer)
{
var player = context.RoomPlayer;
var room = context.Room;
var entityId = reader.ReadUShort();
if (!room.Entities.TryGetValue(entityId, out var ent))
{
_logger.Warn($"Entity not found for event with Id {entityId}");
return;
}
var eventId = reader.ReadUShort();
var eventMode = (RagonReplicationMode)reader.ReadByte();
var targetMode = (RagonTarget)reader.ReadByte();
var targetPlayerPeerId = (ushort)0;
if (targetMode == RagonTarget.Player)
targetPlayerPeerId = reader.ReadUShort();
var ragonEvent = new RagonEvent(player, eventId);
ragonEvent.Read(reader);
if (targetMode == RagonTarget.Player &&
context.Room.Players.TryGetValue(targetPlayerPeerId, out var targetPlayer))
{
ent.ReplicateEvent(player, ragonEvent, eventMode, targetPlayer);
return;
}
ent.ReplicateEvent(player, ragonEvent, eventMode, targetMode);
}
}
@@ -0,0 +1,45 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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 NLog;
using Ragon.Protocol;
namespace Ragon.Server;
public sealed class EntityStateOperation: IRagonOperation
{
private ILogger _logger = LogManager.GetCurrentClassLogger();
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer)
{
var room = context.Room;
var entitiesCount = reader.ReadUShort();
for (var entityIndex = 0; entityIndex < entitiesCount; entityIndex++)
{
var entityId = reader.ReadUShort();
if (room.Entities.TryGetValue(entityId, out var entity))
{
entity.State.Read(reader);
room.Track(entity);
}
else
{
_logger.Error($"Entity with Id {entityId} not found, replication interrupted");
}
}
}
}
@@ -0,0 +1,94 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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 NLog;
using Ragon.Protocol;
namespace Ragon.Server;
public sealed class RoomCreateOperation: IRagonOperation
{
private RagonRoomParameters _roomParameters = new();
private Logger _logger = LogManager.GetCurrentClassLogger();
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer)
{
if (context.LobbyPlayer.Status == LobbyPlayerStatus.Unauthorized)
{
_logger.Warn($"Player {context.Connection.Id} not authorized for this request");
return;
}
var custom = reader.ReadBool();
var roomId = Guid.NewGuid().ToString();
if (custom)
{
roomId = reader.ReadString();
if (context.Lobby.FindRoomById(roomId, out _))
{
writer.Clear();
writer.WriteOperation(RagonOperation.JOIN_FAILED);
writer.WriteString($"Room with id {roomId} already exists");
var sendData = writer.ToArray();
context.Connection.Reliable.Send(sendData);
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} join failed to room {roomId}, room already exist");
return;
}
}
_roomParameters.Deserialize(reader);
var information = new RoomInformation()
{
Map = _roomParameters.Map,
Max = _roomParameters.Max,
Min = _roomParameters.Min,
};
var lobbyPlayer = context.LobbyPlayer;
var room = new RagonRoom(roomId, information);
context.Scheduler.Run(room);
context.Lobby.Persist(room);
var player = new RagonRoomPlayer(lobbyPlayer.Connection, lobbyPlayer.Id, lobbyPlayer.Name);
context.SetRoom(room, player);
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} create room {room.Id} {information}");
JoinSuccess(player, room, writer);
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} joined to room {room.Id}");
}
private void JoinSuccess(RagonRoomPlayer player, RagonRoom room, RagonBuffer writer)
{
writer.Clear();
writer.WriteOperation(RagonOperation.JOIN_SUCCESS);
writer.WriteString(room.Id);
writer.WriteString(player.Id);
writer.WriteString(room.Owner.Id);
writer.WriteUShort((ushort) room.Info.Min);
writer.WriteUShort((ushort) room.Info.Max);
writer.WriteString(room.Info.Map);
var sendData = writer.ToArray();
player.Connection.Reliable.Send(sendData);
}
}
@@ -0,0 +1,71 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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 NLog;
using Ragon.Protocol;
namespace Ragon.Server;
public sealed class RoomJoinOperation : IRagonOperation
{
private Logger _logger = LogManager.GetCurrentClassLogger();
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer)
{
var roomId = reader.ReadString();
var lobbyPlayer = context.LobbyPlayer;
if (!context.Lobby.FindRoomById(roomId, out var existsRoom))
{
JoinFailed(lobbyPlayer, writer);
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} failed to join room {roomId}");
return;
}
var player = new RagonRoomPlayer(lobbyPlayer.Connection, lobbyPlayer.Id, lobbyPlayer.Name);
context.SetRoom(existsRoom, player);
JoinSuccess(player, existsRoom, writer);
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} joined to {existsRoom.Id}");
}
private void JoinSuccess(RagonRoomPlayer player, RagonRoom room, RagonBuffer writer)
{
writer.Clear();
writer.WriteOperation(RagonOperation.JOIN_SUCCESS);
writer.WriteString(room.Id);
writer.WriteString(player.Id);
writer.WriteString(room.Owner.Id);
writer.WriteUShort((ushort) room.Info.Min);
writer.WriteUShort((ushort) room.Info.Max);
writer.WriteString(room.Info.Map);
var sendData = writer.ToArray();
player.Connection.Reliable.Send(sendData);
}
private void JoinFailed(RagonLobbyPlayer player, RagonBuffer writer)
{
writer.Clear();
writer.WriteOperation(RagonOperation.JOIN_FAILED);
writer.WriteString($"Room not exists");
var sendData = writer.ToArray();
player.Connection.Reliable.Send(sendData);
}
}
@@ -0,0 +1,85 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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 NLog;
using Ragon.Protocol;
namespace Ragon.Server;
public sealed class RoomJoinOrCreateOperation : IRagonOperation
{
private RagonRoomParameters _roomParameters = new();
private Logger _logger = LogManager.GetCurrentClassLogger();
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer)
{
if (context.LobbyPlayer.Status == LobbyPlayerStatus.Unauthorized)
{
_logger.Warn("Player not authorized for this request");
return;
}
var roomId = Guid.NewGuid().ToString();
var lobbyPlayer = context.LobbyPlayer;
_roomParameters.Deserialize(reader);
if (context.Lobby.FindRoomByMap(_roomParameters.Map, out var existsRoom))
{
var player = new RagonRoomPlayer(lobbyPlayer.Connection, lobbyPlayer.Id, lobbyPlayer.Name);
context.SetRoom(existsRoom, player);
JoinSuccess(player, existsRoom, writer);
}
else
{
var information = new RoomInformation()
{
Map = _roomParameters.Map,
Max = _roomParameters.Max,
Min = _roomParameters.Min,
};
var room = new RagonRoom(roomId, information);
context.Lobby.Persist(room);
context.Scheduler.Run(room);
var roomPlayer = new RagonRoomPlayer(lobbyPlayer.Connection, lobbyPlayer.Id, lobbyPlayer.Name);
context.SetRoom(room, roomPlayer);
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} create room {room.Id} {information}");
JoinSuccess(roomPlayer, room, writer);
}
}
private void JoinSuccess(RagonRoomPlayer player, RagonRoom room, RagonBuffer writer)
{
writer.Clear();
writer.WriteOperation(RagonOperation.JOIN_SUCCESS);
writer.WriteString(room.Id);
writer.WriteString(player.Id);
writer.WriteString(room.Owner.Id);
writer.WriteUShort((ushort) room.Info.Min);
writer.WriteUShort((ushort) room.Info.Max);
writer.WriteString(room.Info.Map);
var sendData = writer.ToArray();
player.Connection.Reliable.Send(sendData);
_logger.Trace($"{player.Connection.Id}|{player.Name} joined to room {room.Id}");
}
}
@@ -0,0 +1,35 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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 NLog;
using Ragon.Protocol;
namespace Ragon.Server;
public sealed class RoomLeaveOperation: IRagonOperation
{
private Logger _logger = LogManager.GetCurrentClassLogger();
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer)
{
var room = context.Room;
var roomPlayer = context.RoomPlayer;
if (room != null)
{
context.Room?.DetachPlayer(roomPlayer);
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} leaved from {room.Id}");
}
}
}
@@ -0,0 +1,50 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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 NLog;
using Ragon.Protocol;
namespace Ragon.Server;
public class SceneLoadOperation: IRagonOperation
{
private Logger _logger = LogManager.GetCurrentClassLogger();
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer)
{
var roomOwner = context.Room.Owner;
var currentPlayer = context.RoomPlayer;
var room = context.Room;
var sceneName = reader.ReadString();
if (roomOwner.Connection.Id != currentPlayer.Connection.Id)
{
_logger.Warn("Only owner can change map!");
return;
}
room.UpdateMap(sceneName);
writer.Clear();
writer.WriteOperation(RagonOperation.LOAD_SCENE);
writer.WriteString(sceneName);
var sendData = writer.ToArray();
foreach (var player in room.PlayerList)
player.Connection.Reliable.Send(sendData);
}
}
@@ -0,0 +1,143 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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 NLog;
using Ragon.Protocol;
namespace Ragon.Server;
public sealed class SceneLoadedOperation : IRagonOperation
{
private Logger _logger = LogManager.GetCurrentClassLogger();
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer)
{
if (context.LobbyPlayer.Status == LobbyPlayerStatus.Unauthorized)
return;
var owner = context.Room.Owner;
var player = context.RoomPlayer;
var room = context.Room;
if (player == owner)
{
var statics = reader.ReadUShort();
for (var staticIndex = 0; staticIndex < statics; staticIndex++)
{
var entityType = reader.ReadUShort();
var eventAuthority = (RagonAuthority)reader.ReadByte();
var staticId = reader.ReadUShort();
var propertiesCount = reader.ReadUShort();
var entity = new RagonEntity(player, entityType, staticId, 0, eventAuthority);
for (var propertyIndex = 0; propertyIndex < propertiesCount; propertyIndex++)
{
var propertyType = reader.ReadBool();
var propertySize = reader.ReadUShort();
entity.State.AddProperty(new RagonProperty(propertySize, propertyType));
}
var playerInfo = $"Player {context.Connection.Id}|{context.LobbyPlayer.Name}";
var entityInfo = $"{entity.Id}:{entity.Type}";
_logger.Trace($"{playerInfo} created entity {entityInfo}");
room.AttachEntity(entity);
player.AttachEntity(entity);
}
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} loaded");
room.WaitPlayersList.Add(player);
foreach (var roomPlayer in room.WaitPlayersList)
{
DispatchPlayerJoinExcludePlayer(room, roomPlayer, writer);
roomPlayer.SetReady();
}
room.UpdateReadyPlayerList();
DispatchSnapshot(room, room.WaitPlayersList, writer);
room.WaitPlayersList.Clear();
}
else if (owner.IsLoaded)
{
player.SetReady();
DispatchPlayerJoinExcludePlayer(room, player, writer);
room.UpdateReadyPlayerList();
DispatchSnapshot(room, new List<RagonRoomPlayer>() { player }, writer);
foreach (var entity in room.EntityList)
entity.RestoreBufferedEvents(player, writer);
}
else
{
_logger.Trace($"Player {player.Connection.Id}|{context.LobbyPlayer.Name} waiting owner of room");
room.WaitPlayersList.Add(player);
}
}
private void DispatchPlayerJoinExcludePlayer(RagonRoom room, RagonRoomPlayer roomPlayer, RagonBuffer writer)
{
writer.Clear();
writer.WriteOperation(RagonOperation.PLAYER_JOINED);
writer.WriteUShort(roomPlayer.Connection.Id);
writer.WriteString(roomPlayer.Id);
writer.WriteString(roomPlayer.Name);
var sendData = writer.ToArray();
foreach (var awaiter in room.ReadyPlayersList)
{
if (awaiter != roomPlayer)
awaiter.Connection.Reliable.Send(sendData);
}
}
private void DispatchSnapshot(RagonRoom room, List<RagonRoomPlayer> receviersList, RagonBuffer writer)
{
writer.Clear();
writer.WriteOperation(RagonOperation.SNAPSHOT);
writer.WriteUShort((ushort)room.ReadyPlayersList.Count);
foreach (var roomPlayer in room.ReadyPlayersList)
{
writer.WriteUShort(roomPlayer.Connection.Id);
writer.WriteString(roomPlayer.Id);
writer.WriteString(roomPlayer.Name);
}
var dynamicEntities = room.DynamicEntitiesList;
var dynamicEntitiesCount = (ushort)dynamicEntities.Count;
writer.WriteUShort(dynamicEntitiesCount);
foreach (var entity in dynamicEntities)
entity.Snapshot(writer);
var staticEntities = room.StaticEntitiesList;
var staticEntitiesCount = (ushort)staticEntities.Count;
writer.WriteUShort(staticEntitiesCount);
foreach (var entity in staticEntities)
entity.Snapshot(writer);
var sendData = writer.ToArray();
foreach (var player in receviersList)
player.Connection.Reliable.Send(sendData);
}
}
+71
View File
@@ -0,0 +1,71 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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.Threading.Channels;
namespace Ragon.Server;
public class Executor: TaskScheduler, IExecutor
{
private ChannelReader<Task> _reader;
private ChannelWriter<Task> _writer;
private Queue<Task> _pendingTasks;
private TaskFactory _taskFactory;
public void Run(Action action)
{
_taskFactory.StartNew(action);
}
public Executor()
{
var channel = Channel.CreateUnbounded<Task>();
_reader = channel.Reader;
_writer = channel.Writer;
_taskFactory = new TaskFactory(this);
_pendingTasks = new Queue<Task>();
}
protected override IEnumerable<Task>? GetScheduledTasks()
{
throw new NotSupportedException();
}
protected override void QueueTask(Task task)
{
_writer.TryWrite(task);
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
return false;
}
public void Update()
{
while (_reader.TryRead(out var task))
{
TryExecuteTask(task);
if (task.Status == TaskStatus.Running)
_pendingTasks.Enqueue(task);
}
while (_pendingTasks.TryDequeue(out var task))
_writer.TryWrite(task);
}
}
+22
View File
@@ -0,0 +1,22 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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.
*/
namespace Ragon.Server;
public interface IExecutor
{
public void Run(Action action);
}
@@ -0,0 +1,22 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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.
*/
namespace Ragon.Server;
public interface INetworkChannel
{
void Send(byte[] data);
}
@@ -0,0 +1,24 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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.
*/
namespace Ragon.Server;
public interface INetworkConnection
{
public ushort Id { get; }
public INetworkChannel Reliable { get; }
public INetworkChannel Unreliable { get; }
}
@@ -0,0 +1,25 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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.
*/
namespace Ragon.Server;
public interface INetworkListener
{
void OnConnected(INetworkConnection connection);
void OnDisconnected(INetworkConnection connection);
void OnTimeout(INetworkConnection connection);
void OnData(INetworkConnection connection, byte[] data);
}
+25
View File
@@ -0,0 +1,25 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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.
*/
namespace Ragon.Server;
public interface INetworkServer
{
public Executor Executor { get; }
public void Stop();
public void Update();
public void Start(INetworkListener listener, NetworkConfiguration configuration);
}
@@ -0,0 +1,25 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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.
*/
namespace Ragon.Server;
public struct NetworkConfiguration
{
public int LimitConnections { get; set; }
public int Port { get; set; }
public uint Protocol { get; set; }
public string Address { get; set; }
}
+24
View File
@@ -0,0 +1,24 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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 Ragon.Protocol;
namespace Ragon.Server;
public interface IRagonOperation
{
public void Handle(RagonContext context, RagonBuffer reader, RagonBuffer writer);
}
+27
View File
@@ -0,0 +1,27 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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.CodeAnalysis;
namespace Ragon.Server;
public interface IRagonLobby
{
public bool FindRoomById(string roomId, [MaybeNullWhen(false)] out RagonRoom room);
public bool FindRoomByMap(string map, [MaybeNullWhen(false)] out RagonRoom room);
public void Persist(RagonRoom room);
public void RemoveIfEmpty(RagonRoom room);
}
@@ -0,0 +1,79 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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.CodeAnalysis;
using NLog;
namespace Ragon.Server;
public class LobbyInMemory : IRagonLobby
{
private readonly List<RagonRoom> _rooms = new();
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public bool FindRoomById(string RagonRoomId, [MaybeNullWhen(false)] out RagonRoom room)
{
foreach (var existRagonRoom in _rooms)
{
var info = existRagonRoom.Info;
if (existRagonRoom.Id == RagonRoomId && info.Min < info.Max)
{
room = existRagonRoom;
return true;
}
}
room = default;
return false;
}
public bool FindRoomByMap(string map, [MaybeNullWhen(false)] out RagonRoom room)
{
foreach (var existsRoom in _rooms)
{
var info = existsRoom.Info;
if (info.Map == map && existsRoom.Players.Count < info.Max)
{
room = existsRoom;
return true;
}
}
room = default;
return false;
}
public void Persist(RagonRoom room)
{
_rooms.Add(room);
_logger.Trace($"New room: {room.Id}");
foreach (var r in _rooms)
_logger.Trace($"Room: {r.Id} {r.Info} Players: {r.Players.Count} Entities: {r.Entities.Count}");
}
public void RemoveIfEmpty(RagonRoom room)
{
if (room.Players.Count == 0)
{
_rooms.Remove(room);
_logger.Trace($"Room {room.Id} removed");
}
foreach (var r in _rooms)
_logger.Trace($"Room: {r.Id} {r.Info} Players: {r.Players.Count} Entities: {r.Entities.Count}");
}
}
@@ -0,0 +1,41 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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.
*/
namespace Ragon.Server;
public enum LobbyPlayerStatus
{
Unauthorized,
Authorized,
}
public class RagonLobbyPlayer
{
public string Id { get; private set; }
public string Name { get; set; }
public byte[] AdditionalData { get; set; }
public LobbyPlayerStatus Status { get; set; }
public INetworkConnection Connection { get; private set; }
public RagonLobbyPlayer(INetworkConnection connection)
{
Id = Guid.NewGuid().ToString();
Connection = connection;
Status = LobbyPlayerStatus.Unauthorized;
Name = "None";
AdditionalData = Array.Empty<byte>();
}
}
+54
View File
@@ -0,0 +1,54 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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 Ragon.Core.Time;
using Ragon.Server;
namespace Ragon.Server;
public class RagonContext
{
public INetworkConnection Connection { get; }
public IExecutor Executor { get; private set; }
public IRagonLobby Lobby { get; private set; }
public RagonLobbyPlayer LobbyPlayer { get; private set; }
public RagonRoom? Room { get; private set; }
public RagonRoomPlayer? RoomPlayer { get; private set; }
public RagonScheduler Scheduler { get; private set; }
public RagonContext(INetworkConnection connection, IExecutor executor, IRagonLobby lobby, RagonScheduler scheduler, RagonLobbyPlayer lobbyPlayer)
{
Connection = connection;
Executor = executor;
Lobby = lobby;
Scheduler = scheduler;
LobbyPlayer = lobbyPlayer;
}
internal void SetRoom(RagonRoom room, RagonRoomPlayer player)
{
Room?.DetachPlayer(RoomPlayer);
Room = room;
RoomPlayer = player;
Room.AttachPlayer(RoomPlayer);
}
}
+50
View File
@@ -0,0 +1,50 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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.
*/
namespace Ragon.Server;
public class RagonEntityCache
{
private readonly List<RagonEntity> _dynamicEntitiesList = new List<RagonEntity>();
private readonly List<RagonEntity> _staticEntitiesList = new List<RagonEntity>();
private readonly Dictionary<ushort, RagonEntity> _entitiesMap = new Dictionary<ushort, RagonEntity>();
public IReadOnlyList<RagonEntity> StaticList => _staticEntitiesList;
public IReadOnlyList<RagonEntity> DynamicList => _dynamicEntitiesList;
public IReadOnlyDictionary<ushort, RagonEntity> Map => _entitiesMap;
public void Add(RagonEntity entity)
{
if (entity.StaticId != 0)
_staticEntitiesList.Add(entity);
else
_dynamicEntitiesList.Add(entity);
_entitiesMap.Add(entity.Id, entity);
}
public bool Remove(RagonEntity entity)
{
if (_entitiesMap.Remove(entity.Id, out var existEntity))
{
_staticEntitiesList.Remove(entity);
_dynamicEntitiesList.Remove(entity);
return true;
}
return false;
}
}
+180
View File
@@ -0,0 +1,180 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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 NLog;
using Ragon.Core.Time;
using Ragon.Protocol;
using Ragon.Server;
namespace Ragon.Server;
public class RagonServer : INetworkListener
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
private readonly INetworkServer _server;
private readonly Thread _dedicatedThread;
private readonly Executor _executor;
private readonly Configuration _configuration;
private readonly IRagonOperation[] _handlers;
private readonly RagonBuffer _reader;
private readonly RagonBuffer _writer;
private readonly IRagonLobby _lobby;
private readonly RagonScheduler _scheduler;
private readonly Dictionary<ushort, RagonContext> _contexts;
private long _tickrate = 0;
private Stopwatch _timer;
public RagonServer(INetworkServer server, Configuration configuration)
{
_server = server;
_executor = _server.Executor;
_configuration = configuration;
_dedicatedThread = new Thread(Execute);
_dedicatedThread.IsBackground = true;
_contexts = new Dictionary<ushort, RagonContext>();
_lobby = new LobbyInMemory();
_scheduler = new RagonScheduler();
_reader = new RagonBuffer();
_writer = new RagonBuffer();
_tickrate = _configuration.ServerTickRate;
_timer = new Stopwatch();
_handlers = new IRagonOperation[byte.MaxValue];
_handlers[(byte) RagonOperation.AUTHORIZE] = new AuthorizationOperation();
_handlers[(byte) RagonOperation.JOIN_OR_CREATE_ROOM] = new RoomJoinOrCreateOperation();
_handlers[(byte) RagonOperation.CREATE_ROOM] = new RoomCreateOperation();
_handlers[(byte) RagonOperation.JOIN_ROOM] = new RoomJoinOperation();
_handlers[(byte) RagonOperation.LEAVE_ROOM] = new RoomLeaveOperation();
_handlers[(byte) RagonOperation.LOAD_SCENE] = new SceneLoadOperation();
_handlers[(byte) RagonOperation.SCENE_LOADED] = new SceneLoadedOperation();
_handlers[(byte) RagonOperation.CREATE_ENTITY] = new EntityCreateOperation();
_handlers[(byte) RagonOperation.DESTROY_ENTITY] = new EntityDestroyOperation();
_handlers[(byte) RagonOperation.REPLICATE_ENTITY_EVENT] = new EntityEventOperation();
_handlers[(byte) RagonOperation.REPLICATE_ENTITY_STATE] = new EntityStateOperation();
}
public void Execute()
{
_timer.Start();
while (true)
{
if (_timer.ElapsedMilliseconds > _tickrate)
{
_executor.Update();
_timer.Restart();
}
_scheduler.Update();
_server.Update();
Thread.Sleep(1);
}
}
public void Start(bool executeInDedicatedThread = false)
{
var networkConfiguration = new NetworkConfiguration()
{
LimitConnections = _configuration.LimitConnections,
Protocol = RagonVersion.Parse(_configuration.GameProtocol),
Address = "0.0.0.0",
Port = _configuration.Port,
};
_server.Start(this, networkConfiguration);
if (executeInDedicatedThread)
_dedicatedThread.Start();
else
Execute();
}
public void Dispose()
{
_server.Stop();
_dedicatedThread.Interrupt();
}
public void OnConnected(INetworkConnection connection)
{
var lobbyPlayer = new RagonLobbyPlayer(connection);
var context = new RagonContext(connection, _executor, _lobby, _scheduler, lobbyPlayer);
_logger.Trace($"Connected: {connection.Id}");
_contexts.Add(connection.Id, context);
}
public void OnDisconnected(INetworkConnection connection)
{
if (_contexts.Remove(connection.Id, out var context))
{
var room = context.Room;
if (room != null)
{
room.DetachPlayer(context.RoomPlayer);
_lobby.RemoveIfEmpty(room);
}
_logger.Trace($"Disconnected: {connection.Id}|{context.LobbyPlayer.Name}|{context.LobbyPlayer.Id}");
}
else
{
_logger.Trace($"Disconnected: {connection.Id}");
}
}
public void OnTimeout(INetworkConnection connection)
{
if (_contexts.Remove(connection.Id, out var context))
{
var room = context.Room;
if (room != null)
{
room.DetachPlayer(context.RoomPlayer);
_lobby.RemoveIfEmpty(room);
}
_logger.Trace($"Timeout: {connection.Id}|{context.LobbyPlayer.Name}|{context.LobbyPlayer.Id}");
}
else
{
_logger.Trace($"Timeout: {connection.Id}");
}
}
public void OnData(INetworkConnection connection, byte[] data)
{
try
{
if (_contexts.TryGetValue(connection.Id, out var context))
{
_writer.Clear();
_reader.Clear();
_reader.FromArray(data);
// Console.WriteLine($"{string.Join(",", data.Select(d => d.ToString()))}");
var operation = _reader.ReadByte();
_handlers[operation].Handle(context, _reader, _writer);
}
}
catch (Exception ex)
{
_logger.Error(ex);
}
}
}
@@ -0,0 +1,72 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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 Newtonsoft.Json;
using NLog;
namespace Ragon.Server;
public enum ServerType
{
ENET,
WEBSOCKET,
}
[Serializable]
public struct Configuration
{
public string ServerKey;
public string ServerType;
public ushort ServerTickRate;
public string GameProtocol;
public ushort Port;
public int LimitConnections;
public int LimitPlayersPerRoom;
public int LimitRooms;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private static readonly string ServerVersion = "1.1.0-rc";
private static Dictionary<string, ServerType> _serverTypes = new Dictionary<string, ServerType>()
{
{"enet", Server.ServerType.ENET},
{"websocket", Server.ServerType.WEBSOCKET}
};
private static 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("==================================");
Logger.Info("| |");
Logger.Info("| Ragon |");
Logger.Info("| |");
Logger.Info("==================================");
}
public static Configuration Load(string filePath)
{
CopyrightInfo();
var data = File.ReadAllText(filePath);
var configuration = JsonConvert.DeserializeObject<Configuration>(data);
return configuration;
}
public static ServerType GetServerType(string type) => _serverTypes[type];
}
+201
View File
@@ -0,0 +1,201 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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 Ragon.Core.Time;
using Ragon.Protocol;
namespace Ragon.Server;
public class RagonRoom: IRagonAction
{
public string Id { get; private set; }
public RoomInformation Info { get; private set; }
public RagonRoomPlayer Owner { get; private set; }
public RagonBuffer Writer { get; }
public Dictionary<ushort, RagonRoomPlayer> Players { get; private set; }
public List<RagonRoomPlayer> WaitPlayersList { get; private set; }
public List<RagonRoomPlayer> ReadyPlayersList { get; private set; }
public List<RagonRoomPlayer> PlayerList { get; private set; }
public Dictionary<ushort, RagonEntity> Entities { get; private set; }
public List<RagonEntity> DynamicEntitiesList { get; private set; }
public List<RagonEntity> StaticEntitiesList { get; private set; }
public List<RagonEntity> EntityList { get; private set; }
private readonly HashSet<RagonEntity> _entitiesDirtySet;
public RagonRoom(string roomId, RoomInformation info)
{
Id = roomId;
Info = info;
Players = new Dictionary<ushort, RagonRoomPlayer>(info.Max);
WaitPlayersList = new List<RagonRoomPlayer>(info.Max);
ReadyPlayersList = new List<RagonRoomPlayer>(info.Max);
PlayerList = new List<RagonRoomPlayer>(info.Max);
Entities = new Dictionary<ushort, RagonEntity>();
DynamicEntitiesList = new List<RagonEntity>();
StaticEntitiesList = new List<RagonEntity>();
EntityList = new List<RagonEntity>();
_entitiesDirtySet = new HashSet<RagonEntity>();
Writer = new RagonBuffer();
}
public void AttachEntity(RagonEntity entity)
{
Entities.Add(entity.Id, entity);
EntityList.Add(entity);
if (entity.StaticId == 0)
DynamicEntitiesList.Add(entity);
else
StaticEntitiesList.Add(entity);
}
public void DetachEntity(RagonEntity entity)
{
Entities.Remove(entity.Id);
EntityList.Remove(entity);
StaticEntitiesList.Remove(entity);
DynamicEntitiesList.Remove(entity);
_entitiesDirtySet.Remove(entity);
}
public void Tick()
{
var entities = (ushort) _entitiesDirtySet.Count;
if (entities > 0)
{
Writer.Clear();
Writer.WriteOperation(RagonOperation.REPLICATE_ENTITY_STATE);
Writer.WriteUShort(entities);
foreach (var entity in _entitiesDirtySet)
entity.State.Write(Writer);
_entitiesDirtySet.Clear();
var sendData = Writer.ToArray();
foreach (var roomPlayer in ReadyPlayersList)
roomPlayer.Connection.Unreliable.Send(sendData);
}
}
public void AttachPlayer(RagonRoomPlayer player)
{
if (Players.Count == 0)
Owner = player;
player.OnAttached(this);
PlayerList.Add(player);
Players.Add(player.Connection.Id, player);
}
public void DetachPlayer(RagonRoomPlayer roomPlayer)
{
if (Players.Remove(roomPlayer.Connection.Id, out var player))
{
PlayerList.Remove(player);
{
Writer.Clear();
Writer.WriteOperation(RagonOperation.PLAYER_LEAVED);
Writer.WriteString(player.Id);
var entitiesToDelete = player.Entities.DynamicList;
Writer.WriteUShort((ushort) entitiesToDelete.Count);
foreach (var entity in entitiesToDelete)
{
Writer.WriteUShort(entity.Id);
DetachEntity(entity);
}
var sendData = Writer.ToArray();
Broadcast(sendData);
}
if (roomPlayer.Connection.Id == Owner.Connection.Id && PlayerList.Count > 0)
{
var nextOwner = PlayerList[0];
Owner = nextOwner;
var entitiesToUpdate = roomPlayer.Entities.StaticList;
Writer.Clear();
Writer.WriteOperation(RagonOperation.OWNERSHIP_CHANGED);
Writer.WriteString(Owner.Id);
Writer.WriteUShort((ushort) entitiesToUpdate.Count);
foreach (var entity in entitiesToUpdate)
{
Writer.WriteUShort(entity.Id);
entity.SetOwner(nextOwner);
nextOwner.Entities.Add(entity);
}
var sendData = Writer.ToArray();
Broadcast(sendData);
}
player.OnDetached();
UpdateReadyPlayerList();
}
}
public void UpdateReadyPlayerList()
{
ReadyPlayersList = PlayerList.Where(p => p.IsLoaded).ToList();
}
public void UpdateMap(string sceneName)
{
Info = new RoomInformation()
{
Max = Info.Max,
Min = Info.Min,
Map = sceneName,
};
DynamicEntitiesList.Clear();
StaticEntitiesList.Clear();
Entities.Clear();
EntityList.Clear();
foreach (var player in PlayerList)
player.UnsetReady();
UpdateReadyPlayerList();
}
public void Track(RagonEntity entity)
{
_entitiesDirtySet.Add(entity);
}
public void Broadcast(byte[] data)
{
foreach (var readyPlayer in ReadyPlayersList)
readyPlayer.Connection.Reliable.Send(data);
}
}
@@ -0,0 +1,29 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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.
*/
namespace Ragon.Server;
public class RoomInformation
{
public string Map { get; init; } = "none";
public int Min { get; init; }
public int Max { get; init; }
public override string ToString()
{
return $"Map: {Map} Count: {Min}/{Max}";
}
}
@@ -0,0 +1,65 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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.
*/
namespace Ragon.Server;
public class RagonRoomPlayer
{
public INetworkConnection Connection { get; }
public string Id { get; }
public string Name { get; }
public bool IsLoaded { get; private set; }
public RagonRoom Room { get; private set; }
public RagonEntityCache Entities { get; private set; }
public RagonRoomPlayer(INetworkConnection connection, string id, string name)
{
Id = id;
Name = name;
Connection = connection;
Entities = new RagonEntityCache();
}
public void AttachEntity(RagonEntity entity)
{
Entities.Add(entity);
}
public void DetachEntity(RagonEntity entity)
{
Entities.Remove(entity);
}
internal void OnAttached(RagonRoom room)
{
Room = room;
}
internal void OnDetached()
{
Room = null!;
}
internal void SetReady()
{
IsLoaded = true;
}
internal void UnsetReady()
{
IsLoaded = false;
}
}
+22
View File
@@ -0,0 +1,22 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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.
*/
namespace Ragon.Core.Time;
public interface IRagonAction
{
public void Tick();
}
@@ -0,0 +1,43 @@
/*
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
*
* 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.
*/
namespace Ragon.Core.Time;
public class RagonScheduler
{
private List<IRagonAction> _tasks;
public RagonScheduler()
{
_tasks = new List<IRagonAction>(35);
}
public void Run(IRagonAction task)
{
_tasks.Add(task);
}
public void Stop(IRagonAction task)
{
_tasks.Remove(task);
}
public void Update()
{
foreach (var task in _tasks)
task.Tick();
}
}