2024-07-15 17:00:04 +03:00
|
|
|
using System;
|
|
|
|
using System.Collections.Generic;
|
|
|
|
using System.Diagnostics;
|
|
|
|
using LiteNetLib;
|
|
|
|
using LiteNetLib.Utils;
|
|
|
|
|
|
|
|
using Syntriax.Engine.Core;
|
|
|
|
using Syntriax.Engine.Network.Abstract;
|
|
|
|
|
|
|
|
namespace Syntriax.Engine.Network;
|
|
|
|
|
|
|
|
public abstract class NetworkBase : BehaviourOverride, INetworkCommunicator
|
|
|
|
{
|
|
|
|
private readonly NetPacketProcessor netPacketProcessor = new();
|
|
|
|
|
|
|
|
private readonly Dictionary<uint, INetworkEntity> networkEntities = [];
|
|
|
|
|
|
|
|
private BehaviourCollector<INetworkEntity> networkEntityCollector = null!;
|
|
|
|
|
|
|
|
public EventBasedNetListener Listener { get; private set; } = null!;
|
|
|
|
public NetManager Manager { get; private set; } = null!;
|
|
|
|
|
|
|
|
public NetworkBase()
|
|
|
|
{
|
|
|
|
Priority = 10;
|
|
|
|
|
|
|
|
Listener = new EventBasedNetListener();
|
|
|
|
Manager = new NetManager(Listener);
|
|
|
|
|
|
|
|
Listener.NetworkReceiveEvent += NetworkReceiveEvent;
|
2024-07-16 22:50:16 +03:00
|
|
|
netPacketProcessor.SubscribeReusable<NetworkPacket<int>, NetPeer>(OnPacketArrived);
|
|
|
|
}
|
|
|
|
|
|
|
|
private void OnPacketArrived(NetworkPacket<int> packet, NetPeer peer)
|
|
|
|
{
|
|
|
|
Debug.WriteLine($"Packet Arrived for {packet.NetworkId}: {packet.Data}");
|
2024-07-15 17:00:04 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
protected override void OnInitialize()
|
|
|
|
{
|
|
|
|
base.OnInitialize();
|
|
|
|
|
|
|
|
networkEntityCollector = new(GameObject.GameManager);
|
|
|
|
networkEntityCollector.OnCollected += OnNetworkEntityCollected;
|
|
|
|
networkEntityCollector.OnRemoved += OnNetworkEntityRemoved;
|
|
|
|
}
|
2024-07-16 22:50:16 +03:00
|
|
|
|
2024-07-15 17:00:04 +03:00
|
|
|
protected override void OnFinalize()
|
|
|
|
{
|
|
|
|
networkEntityCollector.OnCollected -= OnNetworkEntityCollected;
|
|
|
|
networkEntityCollector.OnRemoved -= OnNetworkEntityRemoved;
|
|
|
|
Stop();
|
|
|
|
}
|
|
|
|
|
|
|
|
private void OnNetworkEntityCollected(BehaviourCollector<INetworkEntity> sender, INetworkEntity behaviourCollected)
|
|
|
|
=> networkEntities.Add(behaviourCollected.NetworkId, behaviourCollected);
|
|
|
|
|
|
|
|
private void OnNetworkEntityRemoved(BehaviourCollector<INetworkEntity> sender, INetworkEntity behaviourRemoved)
|
|
|
|
=> networkEntities.Remove(behaviourRemoved.NetworkId);
|
|
|
|
|
|
|
|
private void NetworkReceiveEvent(NetPeer peer, NetPacketReader reader, byte channel, DeliveryMethod deliveryMethod)
|
|
|
|
{
|
|
|
|
netPacketProcessor.ReadAllPackets(reader, peer);
|
|
|
|
}
|
|
|
|
|
|
|
|
public void PollEvents() => Manager.PollEvents();
|
|
|
|
public void Stop() => Manager.Stop();
|
|
|
|
|
|
|
|
protected override void OnUpdate() => PollEvents();
|
|
|
|
}
|