This commit is contained in:
2024-09-28 20:11:56 +03:00
parent 5136f08dab
commit 672bb1ff6d
95 changed files with 741 additions and 601 deletions
+6 -6
View File
@@ -12,7 +12,7 @@ public class RagonData
{
}
public void Read(RagonBuffer buffer)
public void Read(RagonStream buffer)
{
var len = buffer.ReadUShort();
for (int i = 0; i < len; i++)
@@ -21,7 +21,7 @@ public class RagonData
var valueSize = buffer.ReadUShort();
if (valueSize > 0)
{
var value = buffer.ReadBytes(valueSize);
var value = buffer.ReadBinary(valueSize);
_data[key] = value;
}
else
@@ -31,14 +31,14 @@ public class RagonData
}
}
public void Write(RagonBuffer buffer)
public void Write(RagonStream buffer)
{
buffer.WriteUShort((ushort)_data.Count);
foreach (var prop in _data)
{
buffer.WriteString(prop.Key);
buffer.WriteUShort((ushort)prop.Value.Length);
buffer.WriteBytes(prop.Value);
buffer.WriteBinary(prop.Value);
}
var toDelete = _data
@@ -51,14 +51,14 @@ public class RagonData
IsDirty = false;
}
public void Snapshot(RagonBuffer buffer)
public void Snapshot(RagonStream buffer)
{
buffer.WriteUShort((ushort)_data.Count);
foreach (var prop in _data)
{
buffer.WriteString(prop.Key);
buffer.WriteUShort((ushort)prop.Value.Length);
buffer.WriteBytes(prop.Value);
buffer.WriteBinary(prop.Value);
Console.WriteLine($"Key: {prop.Key} Value: {prop.Value.Length}");
}
@@ -1,16 +0,0 @@
using Ragon.Protocol;
using Ragon.Server.Room;
namespace Ragon.Server.Entity;
public interface IRagonEntity
{
public ushort Id { get; }
public ushort Type { get; }
public ushort StaticId { get; }
public ushort AttachId { get; }
public RagonRoomPlayer Owner { get; }
public RagonAuthority Authority { get; }
public RagonPayload Payload { get; }
public IRagonEntityState State { get; }
}
@@ -1,8 +0,0 @@
using Ragon.Protocol;
namespace Ragon.Server.Entity;
public interface IRagonEntityState
{
}
-246
View File
@@ -1,246 +0,0 @@
/*
* Copyright 2023-2024 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;
using Ragon.Server.Event;
using Ragon.Server.Room;
namespace Ragon.Server.Entity;
public class RagonEntity : IRagonEntity
{
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 IRagonEntityState State => _state;
private readonly List<RagonEvent> _bufferedEvents;
private readonly int _limitBufferedEvents;
private readonly RagonEntityState _state;
public RagonEntity(RagonEntityParameters parameters)
{
Id = _idGenerator++;
StaticId = parameters.StaticId;
Type = parameters.Type;
AttachId = parameters.AttachId;
Authority = parameters.Authority;
Payload = new RagonPayload();
_state = new RagonEntityState(this);
_bufferedEvents = new List<RagonEvent>();
_limitBufferedEvents = parameters.BufferedEvents;
}
public void Attach(RagonRoomPlayer owner)
{
Owner = owner;
}
public void Detach()
{
}
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.REMOVE_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 invoker,
RagonEvent evnt,
RagonReplicationMode eventMode,
RagonRoomPlayer targetPlayer
)
{
if (Authority == RagonAuthority.OwnerOnly && invoker.Connection.Id != Owner.Connection.Id)
{
return;
}
var room = Owner.Room;
var buffer = room.Writer;
buffer.Clear();
buffer.WriteOperation(RagonOperation.REPLICATE_ENTITY_EVENT);
buffer.WriteUShort(evnt.EventCode);
buffer.WriteUShort(invoker.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 invoker,
RagonEvent evnt,
RagonReplicationMode eventMode,
RagonTarget targetMode
)
{
if (Authority == RagonAuthority.OwnerOnly && invoker.Connection.Id != Owner.Connection.Id)
{
return;
}
if (eventMode == RagonReplicationMode.Buffered && targetMode != RagonTarget.Owner && _bufferedEvents.Count < _limitBufferedEvents)
{
_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(invoker.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 != invoker.Connection.Id)
roomPlayer.Connection.Reliable.Send(sendData);
}
break;
}
case RagonTarget.All:
{
foreach (var roomPlayer in room.ReadyPlayersList)
roomPlayer.Connection.Reliable.Send(sendData);
break;
}
}
}
public void AddProperty(RagonProperty property)
{
_state.AddProperty(property);
}
public void WriteState(RagonBuffer writer)
{
_state.Write(writer);
}
public bool TryReadState(RagonRoomPlayer player, RagonBuffer reader)
{
if (Owner.Connection.Id != player.Connection.Id)
return false;
_state.Read(reader);
return true;
}
}
@@ -1,28 +0,0 @@
/*
* Copyright 2023-2024 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.Entity;
public ref struct RagonEntityParameters
{
public ushort Type;
public ushort StaticId;
public ushort AttachId;
public RagonAuthority Authority;
public int BufferedEvents;
}
@@ -1,77 +0,0 @@
/*
* Copyright 2023-2024 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.Entity;
public class RagonEntityState: IRagonEntityState
{
private readonly List<RagonProperty> _properties;
private readonly RagonEntity _entity;
public RagonEntityState(RagonEntity entity, int capacity = 10)
{
_entity = entity;
_properties = new List<RagonProperty>(capacity);
}
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)
{
if (property.HasData)
{
buffer.WriteBool(true);
property.Write(buffer);
continue;
}
buffer.WriteBool(false);
}
}
}
@@ -1,40 +0,0 @@
/*
* Copyright 2023-2024 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.Entity;
public class RagonPayload
{
private uint[] _data = new uint[128];
private int _size = 0;
public ushort Size => (ushort) _size;
public void Read(RagonBuffer buffer)
{
_size = buffer.Capacity;
buffer.ReadArray(_data, _size);
}
public void Write(RagonBuffer buffer)
{
if (_size == 0) return;
buffer.WriteArray(_data, _size);
}
}
@@ -1,76 +0,0 @@
/*
* Copyright 2023-2024 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.Entity;
public class RagonProperty : RagonPayload
{
public int Size { get; set; }
public bool IsDirty { get; private set; }
public bool IsFixed { get; private set; }
public bool HasData { get; private set; }
private uint[] _data;
public RagonProperty(int size, bool isFixed, int limit)
{
Size = size;
IsFixed = isFixed;
IsDirty = false;
_data = new uint[limit / 4 + 1];
}
public void Read(RagonBuffer buffer)
{
if (IsFixed)
{
buffer.ReadArray(_data, Size);
}
else
{
Size = (int) buffer.Read();
buffer.ReadArray(_data, Size);
}
HasData = true;
IsDirty = true;
}
public void Write(RagonBuffer buffer)
{
if (IsFixed)
{
buffer.WriteArray(_data, Size);
return;
}
buffer.Write((ushort) Size);
buffer.WriteArray(_data, 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')))}");
}
}
+6 -6
View File
@@ -37,15 +37,15 @@ public class RagonEvent
EventCode = eventCode;
}
public void Read(RagonBuffer buffer)
public void Read(RagonStream buffer)
{
_size = buffer.Capacity;
buffer.ReadArray(_data, _size);
// _size = buffer.Capacity;
// buffer.ReadArray(_data, _size);
}
public void Write(RagonBuffer buffer)
public void Write(RagonStream buffer)
{
if (_size <= 0) return;
buffer.WriteArray(_data, _size);
// if (_size <= 0) return;
// buffer.WriteArray(_data, _size);
}
}
@@ -29,10 +29,10 @@ namespace Ragon.Server.Handler
private readonly IRagonServer _server;
private readonly RagonContextObserver _observer;
private readonly RagonServerConfiguration _configuration;
private readonly RagonBuffer _writer;
private readonly RagonStream _writer;
public AuthorizationOperation(RagonBuffer reader,
RagonBuffer writer,
public AuthorizationOperation(RagonStream reader,
RagonStream writer,
IRagonServer server,
IServerPlugin serverPlugin,
RagonContextObserver observer,
@@ -21,10 +21,10 @@ namespace Ragon.Server.Handler;
public abstract class BaseOperation
{
protected readonly RagonBuffer Reader;
protected readonly RagonBuffer Writer;
protected readonly RagonStream Reader;
protected readonly RagonStream Writer;
public BaseOperation(RagonBuffer reader, RagonBuffer writer)
public BaseOperation(RagonStream reader, RagonStream writer)
{
Reader = reader;
Writer = writer;
@@ -1,79 +0,0 @@
/*
* Copyright 2023-2024 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;
using Ragon.Server.Entity;
using Ragon.Server.IO;
using Ragon.Server.Logging;
namespace Ragon.Server.Handler;
public sealed class EntityCreateOperation : BaseOperation
{
private readonly IRagonLogger _logger = LoggerManager.GetLogger(nameof(EntityCreateOperation));
private RagonServerConfiguration _configuration;
public EntityCreateOperation(RagonBuffer reader, RagonBuffer writer, RagonServerConfiguration configuration) :
base(reader, writer)
{
_configuration = configuration;
}
public override void Handle(RagonContext context, NetworkChannel channel)
{
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 entityParameters = new RagonEntityParameters()
{
Type = entityType,
Authority = eventAuthority,
AttachId = attachId,
StaticId = 0,
BufferedEvents = context.LimitBufferedEvents,
};
var entity = new RagonEntity(entityParameters);
for (var i = 0; i < propertiesCount; i++)
{
var propertyType = Reader.ReadBool();
var propertySize = Reader.ReadUShort();
entity.AddProperty(new RagonProperty(propertySize, propertyType, _configuration.LimitPropertySize));
}
if (Reader.Capacity > 0)
entity.Payload.Read(Reader);
var plugin = room.Plugin;
if (!plugin.OnEntityCreate(player, entity))
return;
entity.Attach(player);
room.AttachEntity(entity);
player.AttachEntity(entity);
entity.Create();
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} created entity {entity.Id}:{entity.Type}");
}
}
@@ -1,63 +0,0 @@
/*
* Copyright 2023-2024 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;
using Ragon.Server.Event;
using Ragon.Server.IO;
using Ragon.Server.Logging;
namespace Ragon.Server.Handler;
public sealed class EntityEventOperation : BaseOperation
{
private readonly IRagonLogger _logger = LoggerManager.GetLogger(nameof(EntityEventOperation));
public EntityEventOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
{
}
public override void Handle(RagonContext context, NetworkChannel channel)
{
var player = context.RoomPlayer;
var room = context.Room;
var entityId = Reader.ReadUShort();
if (!room.Entities.TryGetValue(entityId, out var ent))
{
_logger.Warning($"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 @event = new RagonEvent(player, eventId);
@event.Read(Reader);
if (targetMode == RagonTarget.Player && room.Players.TryGetValue(targetPlayerPeerId, out var targetPlayer))
{
ent.ReplicateEvent(player, @event, eventMode, targetPlayer);
return;
}
ent.ReplicateEvent(player, @event, eventMode, targetMode);
}
}
@@ -1,75 +0,0 @@
/*
* Copyright 2023-2024 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;
using Ragon.Server.IO;
using Ragon.Server.Logging;
namespace Ragon.Server.Handler;
public sealed class EntityOwnershipOperation : BaseOperation
{
private readonly IRagonLogger _logger = LoggerManager.GetLogger(nameof(EntityOwnershipOperation));
public EntityOwnershipOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
{
}
public override void Handle(RagonContext context, NetworkChannel channel)
{
var currentOwner = context.RoomPlayer;
var room = context.Room;
var entityId = Reader.ReadUShort();
var playerPeerId = Reader.ReadUShort();
if (!room.Entities.TryGetValue(entityId, out var entity))
{
_logger.Error($"Entity not found with id {entityId}");
return;
}
if (entity.Owner.Connection.Id != currentOwner.Connection.Id)
{
_logger.Error($"Player not owner of entity with id {entityId}");
return;
}
if (!room.Players.TryGetValue(playerPeerId, out var nextOwner))
{
_logger.Error($"Player not found with id {playerPeerId}");
return;
}
currentOwner.Entities.Remove(entity);
nextOwner.Entities.Add(entity);
entity.Attach(nextOwner);
_logger.Trace($"Entity {entity.Id} next owner {nextOwner.Connection.Id}");
Writer.Clear();
Writer.WriteOperation(RagonOperation.OWNERSHIP_ENTITY_CHANGED);
Writer.WriteUShort(playerPeerId);
Writer.WriteUShort(1);
Writer.WriteUShort(entity.Id);
var sendData = Writer.ToArray();
foreach (var player in room.PlayerList)
player.Connection.Reliable.Send(sendData);
}
}
@@ -1,55 +0,0 @@
/*
* Copyright 2023-2024 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;
using Ragon.Server.Entity;
using Ragon.Server.IO;
using Ragon.Server.Logging;
namespace Ragon.Server.Handler;
public sealed class EntityDestroyOperation: BaseOperation
{
private readonly IRagonLogger _logger = LoggerManager.GetLogger(nameof(EntityDestroyOperation));
public EntityDestroyOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
{
}
public override void Handle(RagonContext context, NetworkChannel channel)
{
var player = context.RoomPlayer;
var room = context.Room;
var entityId = Reader.ReadUShort();
if (room.Entities.TryGetValue(entityId, out var entity) && entity.Owner.Connection.Id == player.Connection.Id)
{
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}");
}
else
{
_logger.Trace($"Entity {entity.Id} not found or Player {context.Connection.Id}|{context.LobbyPlayer.Name} have not authority");
}
}
}
@@ -1,50 +0,0 @@
/*
* Copyright 2023-2024 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;
using Ragon.Server.IO;
using Ragon.Server.Logging;
namespace Ragon.Server.Handler;
public sealed class EntityStateOperation: BaseOperation
{
private readonly IRagonLogger _logger = LoggerManager.GetLogger(nameof(EntityStateOperation));
public EntityStateOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
{
}
public override void Handle(RagonContext context, NetworkChannel channel)
{
var room = context.Room;
var player = context.RoomPlayer;
var entitiesCount = Reader.ReadUShort();
for (var entityIndex = 0; entityIndex < entitiesCount; entityIndex++)
{
var entityId = Reader.ReadUShort();
if (room.Entities.TryGetValue(entityId, out var entity) && entity.TryReadState(player, Reader))
{
room.Track(entity);
}
else
{
_logger.Error($"Entity with Id {entityId} not found, replication interrupted");
}
}
}
}
@@ -11,8 +11,8 @@ namespace Ragon.Server.Handler
private readonly int _userDataLimit;
public PlayerUserDataOperation(
RagonBuffer reader,
RagonBuffer writer,
RagonStream reader,
RagonStream writer,
int userDataLimit
) : base(reader, writer)
{
@@ -32,8 +32,8 @@ namespace Ragon.Server.Handler
private readonly RagonServerConfiguration _configuration;
public RoomCreateOperation(
RagonBuffer reader,
RagonBuffer writer,
RagonStream reader,
RagonStream writer,
IServerPlugin serverPlugin,
RagonServerConfiguration configuration
) : base(reader,
@@ -107,7 +107,7 @@ namespace Ragon.Server.Handler
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} joined to room {room.Id}");
}
private void JoinSuccess(RagonRoomPlayer player, RagonRoom room, RagonBuffer writer)
private void JoinSuccess(RagonRoomPlayer player, RagonRoom room, RagonStream writer)
{
writer.Clear();
writer.WriteOperation(RagonOperation.JOIN_SUCCESS);
@@ -21,7 +21,7 @@ namespace Ragon.Server.Handler;
public sealed class RoomDataOperation : BaseOperation
{
public RoomDataOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
public RoomDataOperation(RagonStream reader, RagonStream writer) : base(reader, writer)
{
}
@@ -29,8 +29,8 @@ public sealed class RoomDataOperation : BaseOperation
{
var player = context.RoomPlayer;
var room = context.Room;
var data = Reader.RawData;
var data = Reader.ReadBinary(Reader.Lenght);
var dataSize = data.Length - 1;
var headerSize = 3;
var size = headerSize + dataSize;
@@ -10,7 +10,7 @@ public class RoomEventOperation : BaseOperation
{
private readonly IRagonLogger _logger = LoggerManager.GetLogger(nameof(RoomEventOperation));
public RoomEventOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
public RoomEventOperation(RagonStream reader, RagonStream writer) : base(reader, writer)
{
}
@@ -26,7 +26,7 @@ public sealed class RoomJoinOperation : BaseOperation
{
private readonly IRagonLogger _logger = LoggerManager.GetLogger(nameof(RoomJoinOperation));
public RoomJoinOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
public RoomJoinOperation(RagonStream reader, RagonStream writer) : base(reader, writer)
{
}
@@ -54,7 +54,7 @@ public sealed class RoomJoinOperation : BaseOperation
_logger.Trace($"Player {context.Connection.Id}|{context.LobbyPlayer.Name} joined to {existsRoom.Id}");
}
private void JoinSuccess(RagonContext context, RagonRoom room, RagonBuffer writer)
private void JoinSuccess(RagonContext context, RagonRoom room, RagonStream writer)
{
writer.Clear();
writer.WriteOperation(RagonOperation.JOIN_SUCCESS);
@@ -81,7 +81,7 @@ public sealed class RoomJoinOperation : BaseOperation
context.Connection.Reliable.Send(sendData);
}
private void JoinFailed(RagonContext context, RagonBuffer writer)
private void JoinFailed(RagonContext context, RagonStream writer)
{
writer.Clear();
writer.WriteOperation(RagonOperation.JOIN_FAILED);
@@ -32,8 +32,8 @@ public sealed class RoomJoinOrCreateOperation : BaseOperation
private readonly RagonServerConfiguration _configuration;
public RoomJoinOrCreateOperation(
RagonBuffer reader,
RagonBuffer writer,
RagonStream reader,
RagonStream writer,
IServerPlugin serverPlugin,
RagonServerConfiguration configuration
) : base(reader, writer)
@@ -100,7 +100,7 @@ public sealed class RoomJoinOrCreateOperation : BaseOperation
}
}
private void JoinSuccess(RagonRoomPlayer player, RagonRoom room, RagonBuffer writer)
private void JoinSuccess(RagonRoomPlayer player, RagonRoom room, RagonStream writer)
{
writer.Clear();
writer.WriteOperation(RagonOperation.JOIN_SUCCESS);
@@ -24,7 +24,7 @@ public sealed class RoomLeaveOperation: BaseOperation
{
private readonly IRagonLogger _logger = LoggerManager.GetLogger(nameof(RoomLeaveOperation));
public RoomLeaveOperation(RagonBuffer reader, RagonBuffer writer): base(reader, writer)
public RoomLeaveOperation(RagonStream reader, RagonStream writer): base(reader, writer)
{
}
@@ -23,7 +23,7 @@ public sealed class RoomOwnershipOperation : BaseOperation
{
private readonly IRagonLogger _logger = LoggerManager.GetLogger(nameof(RoomOwnershipOperation));
public RoomOwnershipOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
public RoomOwnershipOperation(RagonStream reader, RagonStream writer) : base(reader, writer)
{
}
@@ -27,8 +27,8 @@ public sealed class RoomUserDataOperation : BaseOperation
private readonly int _userDataLimit;
public RoomUserDataOperation(
RagonBuffer reader,
RagonBuffer writer,
RagonStream reader,
RagonStream writer,
int userDataLimit
) : base(reader, writer)
{
@@ -1,52 +0,0 @@
/*
* Copyright 2023-2024 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;
using Ragon.Server.IO;
using Ragon.Server.Logging;
namespace Ragon.Server.Handler;
public class SceneLoadOperation: BaseOperation
{
private readonly IRagonLogger _logger = LoggerManager.GetLogger(nameof(SceneLoadOperation));
public SceneLoadOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer) {}
public override void Handle(RagonContext context, NetworkChannel channel)
{
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.Warning("Only owner can change scene!");
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);
}
}
@@ -1,168 +0,0 @@
/*
* Copyright 2023-2024 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;
using Ragon.Server.Entity;
using Ragon.Server.IO;
using Ragon.Server.Lobby;
using Ragon.Server.Logging;
using Ragon.Server.Room;
namespace Ragon.Server.Handler
{
public sealed class SceneLoadedOperation : BaseOperation
{
private readonly IRagonLogger _logger = LoggerManager.GetLogger(nameof(SceneLoadedOperation));
private RagonServerConfiguration _configuration;
public SceneLoadedOperation(RagonBuffer reader, RagonBuffer writer, RagonServerConfiguration serverConfiguration) : base(reader, writer)
{
_configuration = serverConfiguration;
}
public override void Handle(RagonContext context, NetworkChannel channel)
{
if (context.ConnectionStatus == ConnectionStatus.Unauthorized)
return;
var owner = context.Room.Owner;
var player = context.RoomPlayer;
var room = context.Room;
if (player.IsLoaded)
{
_logger.Warning($"Player {player.Name}:{player.Connection.Id} already ready");
return;
}
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 entityParameters = new RagonEntityParameters()
{
Type = entityType,
Authority = eventAuthority,
AttachId = 0,
StaticId = staticId,
BufferedEvents = context.LimitBufferedEvents,
};
var entity = new RagonEntity(entityParameters);
for (var propertyIndex = 0; propertyIndex < propertiesCount; propertyIndex++)
{
var propertyType = Reader.ReadBool();
var propertySize = Reader.ReadUShort();
entity.AddProperty(new RagonProperty(propertySize, propertyType, _configuration.LimitPropertySize));
}
var roomPlugin = room.Plugin;
if (!roomPlugin.OnEntityCreate(player, entity)) continue;
var playerInfo = $"Player {context.Connection.Id}|{context.LobbyPlayer.Name}";
var entityInfo = $"{entity.Id}:{entity.Type}";
_logger.Trace($"{playerInfo} created static entity {entityInfo}");
entity.Attach(player);
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);
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);
}
}
}
@@ -19,18 +19,18 @@ using Ragon.Server.IO;
namespace Ragon.Server.Handler;
public class TimestampSyncOperation: BaseOperation
public class TimestampSyncOperation : BaseOperation
{
public TimestampSyncOperation(RagonBuffer reader, RagonBuffer writer) : base(reader, writer)
public TimestampSyncOperation(RagonStream reader, RagonStream writer) : base(reader, writer)
{
}
public override void Handle(RagonContext context, NetworkChannel channel)
{
var timestamp0 = Reader.Read(32);
var timestamp1 = Reader.Read(32);
var timestamp0 = (uint)Reader.ReadInt();
var timestamp1 = (uint)Reader.ReadInt();
var value = new DoubleToUInt() { Int0 = timestamp0, Int1 = timestamp1 };
context.RoomPlayer?.SetTimestamp(value.Double);
}
}
@@ -12,7 +12,7 @@ public class RagonLobbyDispatcher
_lobby = lobby;
}
public void Write(RagonBuffer writer)
public void Write(RagonStream writer)
{
writer.Clear();
writer.WriteOperation(RagonOperation.ROOM_LIST_UPDATED);
@@ -81,7 +81,7 @@ public class LobbyInMemory : IRagonLobby
_logger.Trace($"New room: {room.Id}");
foreach (var r in _rooms)
_logger.Trace($"Room: {r.Id} Scene: {r.Scene} Players: {r.Players.Count} Entities: {r.Entities.Count}");
_logger.Trace($"Room: {r.Id} Scene: {r.Scene} Players: {r.Players.Count}");
}
public bool RemoveIfEmpty(RagonRoom room)
@@ -98,7 +98,7 @@ public class LobbyInMemory : IRagonLobby
}
foreach (var r in _rooms)
_logger.Trace($"Room: {r.Id} Scene: {r.Scene} Players: {r.Players.Count} Entities: {r.Entities.Count}");
_logger.Trace($"Room: {r.Id} Scene: {r.Scene} Players: {r.Players.Count}");
return result;
}
@@ -14,8 +14,6 @@
* limitations under the License.
*/
using Ragon.Server.Entity;
using Ragon.Server.IO;
using Ragon.Server.Room;
namespace Ragon.Server.Plugin;
@@ -50,18 +48,6 @@ public class BaseRoomPlugin: IRoomPlugin
{
}
public virtual bool OnEntityCreate(RagonRoomPlayer creator, IRagonEntity entity)
{
return true;
}
public virtual bool OnEntityRemove(RagonRoomPlayer remover, IRagonEntity entity)
{
return true;
}
public virtual bool OnData(RagonRoomPlayer player, byte[] data)
{
@@ -14,7 +14,6 @@
* limitations under the License.
*/
using Ragon.Server.Entity;
using Ragon.Server.Room;
namespace Ragon.Server.Plugin;
@@ -26,7 +25,5 @@ public interface IRoomPlugin
void OnDetached(IRagonRoom room);
bool OnPlayerJoined(RagonRoomPlayer player);
bool OnPlayerLeaved(RagonRoomPlayer player);
bool OnEntityCreate(RagonRoomPlayer player, IRagonEntity entity);
bool OnEntityRemove(RagonRoomPlayer player, IRagonEntity entity);
bool OnData(RagonRoomPlayer player, byte[] data);
}
-52
View File
@@ -1,52 +0,0 @@
/*
* Copyright 2023-2024 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.Server.Entity;
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;
}
}
+11 -17
View File
@@ -35,8 +35,8 @@ public class RagonServer : IRagonServer, INetworkListener
private readonly IRagonLobby _lobby;
private readonly IServerPlugin _serverPlugin;
private readonly RagonServerConfiguration _configuration;
private readonly RagonBuffer _reader;
private readonly RagonBuffer _writer;
private readonly RagonStream _reader;
private readonly RagonStream _writer;
private readonly RagonScheduler _scheduler;
private readonly Dictionary<ushort, RagonContext> _contextsByConnection;
private readonly Dictionary<string, RagonContext> _contextsByPlayerId;
@@ -60,8 +60,8 @@ public class RagonServer : IRagonServer, INetworkListener
_lobby = new LobbyInMemory();
_lobbySerializer = new RagonLobbyDispatcher(_lobby);
_scheduler = new RagonScheduler();
_reader = new RagonBuffer();
_writer = new RagonBuffer();
_reader = new RagonStream();
_writer = new RagonStream();
_tickRate = 1000 / _configuration.ServerTickRate;
_timer = new Stopwatch();
@@ -78,14 +78,6 @@ public class RagonServer : IRagonServer, INetworkListener
_handlers[(byte)RagonOperation.CREATE_ROOM] = new RoomCreateOperation(_reader, _writer, plugin, _configuration);
_handlers[(byte)RagonOperation.JOIN_ROOM] = new RoomJoinOperation(_reader, _writer);
_handlers[(byte)RagonOperation.LEAVE_ROOM] = new RoomLeaveOperation(_reader, _writer);
_handlers[(byte)RagonOperation.LOAD_SCENE] = new SceneLoadOperation(_reader, _writer);
_handlers[(byte)RagonOperation.SCENE_LOADED] = new SceneLoadedOperation(_reader, _writer, _configuration);
_handlers[(byte)RagonOperation.CREATE_ENTITY] = new EntityCreateOperation(_reader, _writer, _configuration);
_handlers[(byte)RagonOperation.REMOVE_ENTITY] = new EntityDestroyOperation(_reader, _writer);
_handlers[(byte)RagonOperation.REPLICATE_ENTITY_EVENT] = new EntityEventOperation(_reader, _writer);
_handlers[(byte)RagonOperation.REPLICATE_ENTITY_STATE] = new EntityStateOperation(_reader, _writer);
_handlers[(byte)RagonOperation.TRANSFER_ROOM_OWNERSHIP] = new EntityOwnershipOperation(_reader, _writer);
_handlers[(byte)RagonOperation.TRANSFER_ENTITY_OWNERSHIP] = new EntityOwnershipOperation(_reader, _writer);
_handlers[(byte)RagonOperation.TIMESTAMP_SYNCHRONIZATION] = new TimestampSyncOperation(_reader, _writer);
_handlers[(byte)RagonOperation.REPLICATE_ROOM_EVENT] = new RoomEventOperation(_reader, _writer);
_handlers[(byte)RagonOperation.REPLICATE_RAW_DATA] = new RoomDataOperation(_reader, _writer);
@@ -101,11 +93,13 @@ public class RagonServer : IRagonServer, INetworkListener
if (_timer.ElapsedMilliseconds > _tickRate)
{
_scheduler.Update(_timer.ElapsedMilliseconds);
_timer.Restart();
_scheduler.Update(_timer.ElapsedMilliseconds / 1000.0f);
SendTimestamp();
}
SendTimestamp();
_server.Update();
}
@@ -219,8 +213,8 @@ public class RagonServer : IRagonServer, INetworkListener
_writer.Clear();
_writer.WriteOperation(RagonOperation.TIMESTAMP_SYNCHRONIZATION);
_writer.Write(value.Int0, 32);
_writer.Write(value.Int1, 32);
_writer.WriteInt((int)value.Int0);
_writer.WriteInt((int)value.Int1);
var sendData = _writer.ToArray();
_server.Broadcast(sendData, NetworkChannel.UNRELIABLE);
-3
View File
@@ -15,7 +15,6 @@
*/
using Ragon.Server.Data;
using Ragon.Server.Entity;
using Ragon.Server.IO;
namespace Ragon.Server.Room;
@@ -36,6 +35,4 @@ public interface IRagonRoom
RagonRoomPlayer GetPlayerByConnection(INetworkConnection connection);
RagonRoomPlayer GetPlayerById(string id);
IRagonEntity GetEntityById(ushort id);
IRagonEntity[] GetEntitiesOfPlayer(RagonRoomPlayer id);
}
+7 -113
View File
@@ -16,7 +16,6 @@
using Ragon.Protocol;
using Ragon.Server.Data;
using Ragon.Server.Entity;
using Ragon.Server.Event;
using Ragon.Server.IO;
using Ragon.Server.Plugin;
@@ -36,7 +35,7 @@ public class RagonRoom : IRagonRoom, IRagonAction
public RagonData UserData { get; set; }
public RagonRoomPlayer Owner { get; private set; }
public RagonBuffer Writer { get; }
public RagonStream Writer { get; }
public IRoomPlugin Plugin { get; private set; }
public Dictionary<ushort, RagonRoomPlayer> Players { get; private set; }
@@ -44,12 +43,6 @@ public class RagonRoom : IRagonRoom, IRagonAction
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;
private readonly List<RagonEvent> _bufferedEvents;
private readonly int _limitBufferedEvents;
@@ -66,39 +59,14 @@ public class RagonRoom : IRagonRoom, IRagonAction
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>();
_bufferedEvents = new List<RagonEvent>();
_limitBufferedEvents = 1000;
UserData = new RagonData();
Writer = new RagonBuffer();
Writer = new RagonStream();
}
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 RestoreBufferedEvents(RagonRoomPlayer roomPlayer)
{
@@ -238,22 +206,7 @@ public class RagonRoom : IRagonRoom, IRagonAction
public void Tick(float dt)
{
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.WriteState(Writer);
_entitiesDirtySet.Clear();
var sendData = Writer.ToArray();
foreach (var roomPlayer in ReadyPlayersList)
roomPlayer.Connection.Unreliable.Send(sendData);
}
}
public void AttachPlayer(RagonRoomPlayer player)
@@ -277,43 +230,9 @@ public class RagonRoom : IRagonRoom, IRagonAction
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_ENTITY_CHANGED);
Writer.WriteUShort(Owner.Connection.Id);
Writer.WriteUShort((ushort)entitiesToUpdate.Count);
foreach (var entity in entitiesToUpdate)
{
Writer.WriteUShort(entity.Id);
entity.Attach(nextOwner);
nextOwner.Entities.Add(entity);
}
var sendData = Writer.ToArray();
Broadcast(sendData);
}
player.OnDetached();
@@ -331,23 +250,13 @@ public class RagonRoom : IRagonRoom, IRagonAction
public void UpdateMap(string sceneName)
{
Scene = 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, NetworkChannel channel = NetworkChannel.RELIABLE)
{
if (channel == NetworkChannel.RELIABLE)
@@ -386,16 +295,7 @@ public class RagonRoom : IRagonRoom, IRagonAction
return PlayerList.FirstOrDefault(p => p.Id == id);
}
public IRagonEntity? GetEntityById(ushort id)
{
return Entities.TryGetValue(id, out var entity) ? entity : null;
}
public IRagonEntity[] GetEntitiesOfPlayer(RagonRoomPlayer player)
{
return EntityList.Where(e => e.Owner.Connection.Id == player.Connection.Id).ToArray();
}
public void Attach()
{
Plugin.OnAttached(this);
@@ -410,12 +310,6 @@ public class RagonRoom : IRagonRoom, IRagonAction
ReadyPlayersList.Clear();
PlayerList.Clear();
Entities.Clear();
DynamicEntitiesList.Clear();
StaticEntitiesList.Clear();
EntityList.Clear();
_entitiesDirtySet.Clear();
_bufferedEvents.Clear();
IsDone = true;
@@ -14,8 +14,6 @@
* limitations under the License.
*/
using Ragon.Server.Data;
using Ragon.Server.Entity;
using Ragon.Server.IO;
namespace Ragon.Server.Room;
@@ -29,7 +27,6 @@ public class RagonRoomPlayer
public bool IsLoaded { get; private set; }
public double Timestamp { get; private set; }
public RagonRoom Room { get; private set; }
public RagonEntityCache Entities { get; private set; }
public RagonRoomPlayer(RagonContext context, string id, string name)
{
@@ -37,19 +34,8 @@ public class RagonRoomPlayer
Name = name;
Context = context;
Connection = context.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;