Compare commits
9 Commits
feat/liten
...
fe5a08840c
| Author | SHA1 | Date | |
|---|---|---|---|
| fe5a08840c | |||
| 1c7b1cb78a | |||
| 78010c266e | |||
| ef8b04648c | |||
| d4c57c0153 | |||
| 0e198afeab | |||
| de267a9d0f | |||
| 977a2abdd7 | |||
| 91e88bbff8 |
46
.vscode/launch.json
vendored
46
.vscode/launch.json
vendored
@@ -1,46 +0,0 @@
|
||||
{
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Start Client",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "build",
|
||||
// If you have changed target frameworks, make sure to update the program path.
|
||||
"program": "${workspaceFolder}/Game/bin/Debug/net8.0/Game.dll",
|
||||
"args": ["127.0.0.1"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
|
||||
"console": "internalConsole",
|
||||
"stopAtEntry": false
|
||||
},
|
||||
{
|
||||
"name": ".NET Core Attach",
|
||||
"type": "coreclr",
|
||||
"request": "attach",
|
||||
"processId": "${command:pickProcess}"
|
||||
},
|
||||
{
|
||||
"name": "Start Server",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "build",
|
||||
// If you have changed target frameworks, make sure to update the program path.
|
||||
"program": "${workspaceFolder}/Game/bin/Debug/net8.0/Game.dll",
|
||||
"args": ["server"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
|
||||
"console": "internalConsole",
|
||||
"stopAtEntry": false
|
||||
},
|
||||
{
|
||||
"name": ".NET Core Attach",
|
||||
"type": "coreclr",
|
||||
"request": "attach",
|
||||
"processId": "${command:pickProcess}"
|
||||
}
|
||||
]
|
||||
}
|
||||
2
Engine
2
Engine
Submodule Engine updated: ef21cdf213...dbb263ebed
27
Game/.vscode/launch.json
vendored
Normal file
27
Game/.vscode/launch.json
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": ".NET Core Launch (console)",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "build",
|
||||
// If you have changed target frameworks, make sure to update the program path.
|
||||
"program": "${workspaceFolder}/bin/Debug/net8.0/${workspaceFolderBasename}.dll",
|
||||
"args": [],
|
||||
"cwd": "${workspaceFolder}",
|
||||
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
|
||||
"console": "internalConsole",
|
||||
"stopAtEntry": false
|
||||
},
|
||||
{
|
||||
"name": ".NET Core Attach",
|
||||
"type": "coreclr",
|
||||
"request": "attach",
|
||||
"processId": "${command:pickProcess}"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
|
||||
using LiteNetLib;
|
||||
using Pong.Network;
|
||||
using Syntriax.Engine.Core;
|
||||
using Syntriax.Engine.Physics2D;
|
||||
using Syntriax.Engine.Physics2D.Abstract;
|
||||
@@ -14,6 +15,7 @@ public class BallBehaviour : BehaviourOverride
|
||||
|
||||
private readonly Random random = new();
|
||||
private IRigidBody2D rigidBody = null!;
|
||||
private INetworkCommunicator communicator = null!;
|
||||
|
||||
protected override void OnFirstActiveFrame()
|
||||
{
|
||||
@@ -21,11 +23,14 @@ public class BallBehaviour : BehaviourOverride
|
||||
throw new Exception($"{nameof(IRigidBody2D)} is missing on {GameObject.Name}.");
|
||||
if (!BehaviourController.TryGetBehaviour(out ICollider2D? foundCollider))
|
||||
throw new Exception($"{nameof(ICollider2D)} is missing on {GameObject.Name}.");
|
||||
if (!GameObject.GameManager.TryFindBehaviour(out INetworkCommunicator? foundCommunicator))
|
||||
throw new Exception($"{nameof(INetworkCommunicator)} is missing on GameManager.");
|
||||
|
||||
foundCollider.OnCollisionDetected += OnCollisionDetected;
|
||||
|
||||
rigidBody = foundRigidBody;
|
||||
|
||||
communicator = foundCommunicator;
|
||||
communicator.RegisterEntityListener(this, OnDataReceived);
|
||||
if (GameObject.GameManager.TryFindBehaviour(out PongManagerBehaviour? pongManager))
|
||||
{
|
||||
pongManager.OnReset += ResetBall;
|
||||
@@ -34,6 +39,12 @@ public class BallBehaviour : BehaviourOverride
|
||||
}
|
||||
}
|
||||
|
||||
private void OnDataReceived(NetPacketReader reader)
|
||||
{
|
||||
rigidBody.Transform.Position = reader.GetVector2D();
|
||||
rigidBody.Velocity = reader.GetVector2D();
|
||||
}
|
||||
|
||||
private void DisableBall(PongManagerBehaviour pongManager)
|
||||
{
|
||||
BehaviourController.GameObject.Transform.Position = Vector2D.Zero;
|
||||
@@ -45,6 +56,8 @@ public class BallBehaviour : BehaviourOverride
|
||||
StateEnable.Enabled = true;
|
||||
BehaviourController.GameObject.Transform.Position = Vector2D.Zero;
|
||||
rigidBody.Velocity = GetRandomDirection() * Speed;
|
||||
|
||||
SendBallData();
|
||||
}
|
||||
|
||||
private Vector2D GetRandomDirection()
|
||||
@@ -70,6 +83,19 @@ public class BallBehaviour : BehaviourOverride
|
||||
rigidBody.Velocity = information.Left.Transform.Position.FromTo(information.Right.Transform.Position).Normalized * rigidBody.Velocity.Magnitude;
|
||||
else
|
||||
rigidBody.Velocity = rigidBody.Velocity.Reflect(information.Normal);
|
||||
|
||||
SendBallData();
|
||||
}
|
||||
|
||||
private void SendBallData()
|
||||
{
|
||||
if (communicator is not INetworkServer server)
|
||||
return;
|
||||
|
||||
LiteNetLib.Utils.NetDataWriter dataWriter = communicator.GetEntityWriter(this);
|
||||
dataWriter.Put(rigidBody.Transform.Position);
|
||||
dataWriter.Put(rigidBody.Velocity);
|
||||
server.Manager.SendToAll(dataWriter, LiteNetLib.DeliveryMethod.ReliableOrdered);
|
||||
}
|
||||
|
||||
public BallBehaviour() { }
|
||||
|
||||
@@ -8,9 +8,9 @@ namespace Pong.Behaviours;
|
||||
|
||||
public class MonoGameCamera2DBehaviour(GraphicsDeviceManager Graphics) : BehaviourOverride, ICamera2D
|
||||
{
|
||||
public event OnMatrixTransformChangedDelegate? OnMatrixTransformChanged = null;
|
||||
public event OnViewportChangedDelegate? OnViewportChanged = null;
|
||||
public event OnZoomChangedDelegate? OnZoomChanged = null;
|
||||
public System.Action<MonoGameCamera2DBehaviour>? OnMatrixTransformChanged { get; set; } = null;
|
||||
public System.Action<MonoGameCamera2DBehaviour>? OnViewportChanged { get; set; } = null;
|
||||
public System.Action<MonoGameCamera2DBehaviour>? OnZoomChanged { get; set; } = null;
|
||||
|
||||
private Matrix _matrixTransform = Matrix.Identity;
|
||||
|
||||
@@ -72,7 +72,7 @@ public class MonoGameCamera2DBehaviour(GraphicsDeviceManager Graphics) : Behavio
|
||||
set => Transform.Rotation = value;
|
||||
}
|
||||
|
||||
public event IAssignableTransform.OnTransformAssignedDelegate? OnTransformAssigned { add => GameObject.OnTransformAssigned += value; remove => GameObject.OnTransformAssigned -= value; }
|
||||
System.Action<IAssignableTransform>? IAssignableTransform.OnTransformAssigned { get => GameObject.OnTransformAssigned; set => GameObject.OnTransformAssigned = value; }
|
||||
ITransform IAssignableTransform.Transform => GameObject.Transform;
|
||||
bool IAssignableTransform.Assign(ITransform transform) => GameObject.Assign(transform);
|
||||
|
||||
@@ -99,8 +99,4 @@ public class MonoGameCamera2DBehaviour(GraphicsDeviceManager Graphics) : Behavio
|
||||
Matrix.CreateScale(Zoom) *
|
||||
Matrix.CreateTranslation(new Vector3(_viewport.Width * .5f, _viewport.Height * .5f, 0f));
|
||||
}
|
||||
|
||||
public delegate void OnMatrixTransformChangedDelegate(MonoGameCamera2DBehaviour sender);
|
||||
public delegate void OnViewportChangedDelegate(MonoGameCamera2DBehaviour sender);
|
||||
public delegate void OnZoomChangedDelegate(MonoGameCamera2DBehaviour sender);
|
||||
}
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
using System;
|
||||
using LiteNetLib.Utils;
|
||||
|
||||
using Microsoft.Xna.Framework.Input;
|
||||
|
||||
using LiteNetLib;
|
||||
using LiteNetLib.Utils;
|
||||
|
||||
using Pong.Network;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
using Syntriax.Engine.Input;
|
||||
using Syntriax.Engine.Network;
|
||||
using Syntriax.Engine.Network.Abstract;
|
||||
|
||||
namespace Pong.Behaviours;
|
||||
|
||||
public class PaddleBehaviour(Keys Up, Keys Down, float High, float Low, float Speed) : NetworkBehaviour
|
||||
public class PaddleBehaviour(Keys Up, Keys Down, float High, float Low, float Speed) : BehaviourOverride
|
||||
{
|
||||
private Keys Up { get; } = Up;
|
||||
private Keys Down { get; } = Down;
|
||||
@@ -21,6 +24,7 @@ public class PaddleBehaviour(Keys Up, Keys Down, float High, float Low, float Sp
|
||||
private bool isDownPressed = false;
|
||||
|
||||
private IButtonInputs<Keys> inputs = null!;
|
||||
private INetworkCommunicator communicator = null!;
|
||||
|
||||
protected override void OnUpdate()
|
||||
{
|
||||
@@ -28,15 +32,20 @@ public class PaddleBehaviour(Keys Up, Keys Down, float High, float Low, float Sp
|
||||
return;
|
||||
|
||||
if (isUpPressed)
|
||||
Move(Vector2D.Up);
|
||||
MovePaddle(Vector2D.Up * (float)Time.Elapsed.TotalSeconds * Speed);
|
||||
else if (isDownPressed)
|
||||
Move(-Vector2D.Up);
|
||||
MovePaddle(-Vector2D.Up * (float)Time.Elapsed.TotalSeconds * Speed);
|
||||
|
||||
GameObject.Transform.Position = new Vector2D(GameObject.Transform.Position.X, MathF.Max(MathF.Min(GameObject.Transform.Position.Y, High), Low));
|
||||
}
|
||||
|
||||
private void Move(Vector2D vectorToMove)
|
||||
private void MovePaddle(Vector2D vectorToAdd)
|
||||
{
|
||||
GameObject.Transform.Position = GameObject.Transform.Position + vectorToMove * (float)Time.Elapsed.TotalSeconds * Speed;
|
||||
GameObject.Transform.Position = new Vector2D(GameObject.Transform.Position.X, MathF.Max(MathF.Min(GameObject.Transform.Position.Y, High), Low));
|
||||
GameObject.Transform.Position += vectorToAdd;
|
||||
|
||||
NetDataWriter dataWriter = communicator.GetEntityWriter(this);
|
||||
dataWriter.Put(Transform.Position);
|
||||
communicator.Manager.SendToAll(dataWriter, LiteNetLib.DeliveryMethod.Unreliable);
|
||||
}
|
||||
|
||||
protected override void OnFirstActiveFrame()
|
||||
@@ -44,11 +53,22 @@ public class PaddleBehaviour(Keys Up, Keys Down, float High, float Low, float Sp
|
||||
if (!BehaviourController.TryGetBehaviour<IButtonInputs<Keys>>(out var behaviourResult))
|
||||
inputs = behaviourResult ?? BehaviourController.AddBehaviour<KeyboardInputsBehaviour>();
|
||||
|
||||
if (!GameObject.GameManager.TryFindBehaviour(out INetworkCommunicator? foundCommunicator))
|
||||
throw new Exception($"{nameof(INetworkCommunicator)} is missing on GameManager.");
|
||||
|
||||
inputs.RegisterOnPress(Up, OnUpPressed);
|
||||
inputs.RegisterOnRelease(Up, OnUpReleased);
|
||||
|
||||
inputs.RegisterOnPress(Down, OnDownPressed);
|
||||
inputs.RegisterOnRelease(Down, OnDownReleased);
|
||||
|
||||
communicator = foundCommunicator;
|
||||
communicator.RegisterEntityListener(this, OnDataReceived);
|
||||
}
|
||||
|
||||
private void OnDataReceived(NetPacketReader reader)
|
||||
{
|
||||
Transform.Position = reader.GetVector2D();
|
||||
}
|
||||
|
||||
protected override void OnFinalize()
|
||||
@@ -60,40 +80,8 @@ public class PaddleBehaviour(Keys Up, Keys Down, float High, float Low, float Sp
|
||||
inputs.UnregisterOnRelease(Down, OnDownReleased);
|
||||
}
|
||||
|
||||
private void OnUpPressed(IButtonInputs<Keys> inputs, Keys keys) { isUpPressed = true; SendData(new PaddleInputs() { IsUpPressed = isUpPressed, IsDownPressed = isDownPressed, PositionY = Transform.Position.Y }); }
|
||||
private void OnUpReleased(IButtonInputs<Keys> inputs, Keys keys) { isUpPressed = false; SendData(new PaddleInputs() { IsUpPressed = isUpPressed, IsDownPressed = isDownPressed, PositionY = Transform.Position.Y }); }
|
||||
private void OnDownPressed(IButtonInputs<Keys> inputs, Keys keys) { isDownPressed = true; SendData(new PaddleInputs() { IsUpPressed = isUpPressed, IsDownPressed = isDownPressed, PositionY = Transform.Position.Y }); }
|
||||
private void OnDownReleased(IButtonInputs<Keys> inputs, Keys keys) { isDownPressed = false; SendData(new PaddleInputs() { IsUpPressed = isUpPressed, IsDownPressed = isDownPressed, PositionY = Transform.Position.Y }); }
|
||||
|
||||
public override void ReceiveData<T>(T data)
|
||||
{
|
||||
if (data is not PaddleInputs paddleInputs)
|
||||
return;
|
||||
|
||||
Transform.Position = new(Transform.Position.X, paddleInputs.PositionY);
|
||||
isUpPressed = paddleInputs.IsUpPressed;
|
||||
isDownPressed = paddleInputs.IsDownPressed;
|
||||
}
|
||||
|
||||
[System.Serializable]
|
||||
public struct PaddleInputs : INetworkPacket
|
||||
{
|
||||
public float PositionY { get; set; }
|
||||
public bool IsUpPressed { get; set; }
|
||||
public bool IsDownPressed { get; set; }
|
||||
|
||||
public void Deserialize(NetDataReader reader)
|
||||
{
|
||||
PositionY = reader.GetFloat();
|
||||
IsUpPressed = reader.GetBool();
|
||||
IsDownPressed = reader.GetBool();
|
||||
}
|
||||
|
||||
public void Serialize(NetDataWriter writer)
|
||||
{
|
||||
writer.Put(PositionY);
|
||||
writer.Put(IsUpPressed);
|
||||
writer.Put(IsDownPressed);
|
||||
}
|
||||
}
|
||||
private void OnUpPressed(IButtonInputs<Keys> inputs, Keys keys) => isUpPressed = true;
|
||||
private void OnUpReleased(IButtonInputs<Keys> inputs, Keys keys) => isUpPressed = false;
|
||||
private void OnDownPressed(IButtonInputs<Keys> inputs, Keys keys) => isDownPressed = true;
|
||||
private void OnDownReleased(IButtonInputs<Keys> inputs, Keys keys) => isDownPressed = false;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,10 @@ using System;
|
||||
|
||||
using Microsoft.Xna.Framework.Input;
|
||||
|
||||
using LiteNetLib;
|
||||
|
||||
using Pong.Network;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
|
||||
namespace Pong.Behaviours;
|
||||
@@ -12,6 +16,8 @@ public class PongManagerBehaviour : BehaviourOverride
|
||||
public Action<PongManagerBehaviour>? OnFinished { get; set; } = null;
|
||||
public Action<PongManagerBehaviour>? OnScored { get; set; } = null;
|
||||
|
||||
private INetworkCommunicator communicator = null!;
|
||||
|
||||
public int ScoreLeft { get; private set; } = 0;
|
||||
public int ScoreRight { get; private set; } = 0;
|
||||
public int ScoreSum => ScoreLeft + ScoreRight;
|
||||
@@ -28,15 +34,31 @@ public class PongManagerBehaviour : BehaviourOverride
|
||||
if (!BehaviourController.TryGetBehaviour(out buttonInputs))
|
||||
buttonInputs = BehaviourController.AddBehaviour<KeyboardInputsBehaviour>();
|
||||
|
||||
if (!GameObject.GameManager.TryFindBehaviour(out INetworkCommunicator? foundCommunicator))
|
||||
throw new Exception($"{nameof(INetworkCommunicator)} is missing on GameManager.");
|
||||
|
||||
buttonInputs.RegisterOnRelease(Keys.Space, (_, _1) => Reset());
|
||||
|
||||
communicator = foundCommunicator;
|
||||
communicator.RegisterEntityListener(this, OnMessageReceived);
|
||||
}
|
||||
|
||||
private void OnMessageReceived(NetPacketReader reader)
|
||||
{
|
||||
ScoreLeft = reader.GetInt();
|
||||
ScoreRight = reader.GetInt();
|
||||
OnScored?.Invoke(this);
|
||||
|
||||
CheckFinish();
|
||||
}
|
||||
|
||||
public void ScoreToLeft()
|
||||
{
|
||||
ScoreLeft++;
|
||||
OnScored?.Invoke(this);
|
||||
|
||||
SendData();
|
||||
|
||||
CheckFinish();
|
||||
}
|
||||
|
||||
@@ -45,6 +67,8 @@ public class PongManagerBehaviour : BehaviourOverride
|
||||
ScoreRight++;
|
||||
OnScored?.Invoke(this);
|
||||
|
||||
SendData();
|
||||
|
||||
CheckFinish();
|
||||
}
|
||||
|
||||
@@ -52,6 +76,8 @@ public class PongManagerBehaviour : BehaviourOverride
|
||||
{
|
||||
ScoreLeft = ScoreRight = 0;
|
||||
OnReset?.Invoke(this);
|
||||
|
||||
SendData();
|
||||
}
|
||||
|
||||
private void CheckFinish()
|
||||
@@ -61,4 +87,15 @@ public class PongManagerBehaviour : BehaviourOverride
|
||||
if (ScoreLeft > halfwayScore || ScoreRight > halfwayScore)
|
||||
OnFinished?.Invoke(this);
|
||||
}
|
||||
|
||||
private void SendData()
|
||||
{
|
||||
if (communicator is not INetworkServer server)
|
||||
return;
|
||||
|
||||
LiteNetLib.Utils.NetDataWriter dataWriter = communicator.GetEntityWriter(this);
|
||||
dataWriter.Put(ScoreLeft);
|
||||
dataWriter.Put(ScoreRight);
|
||||
server.Manager.SendToAll(dataWriter, LiteNetLib.DeliveryMethod.ReliableOrdered);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ public class TextScoreBehaviour : TextBehaviour
|
||||
if (!GameObject.GameManager.TryFindBehaviour(out pongManager))
|
||||
return;
|
||||
|
||||
pongManager.OnFinished += UpdateScores;
|
||||
pongManager.OnScored += UpdateScores;
|
||||
pongManager.OnReset += UpdateScores;
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ using Microsoft.Xna.Framework.Input;
|
||||
using Apos.Shapes;
|
||||
|
||||
using Pong.Behaviours;
|
||||
using Syntriax.Engine.Network;
|
||||
using Pong.Network;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
using Syntriax.Engine.Core.Abstract;
|
||||
@@ -25,8 +25,8 @@ public class GamePong : Game
|
||||
private ShapeBatch shapeBatch = null!;
|
||||
|
||||
private GameManager gameManager = null!;
|
||||
private BehaviourCollector<IDisplayableSprite> displayableCollector = null!;
|
||||
private BehaviourCollector<IDisplayableShape> displayableShapeCollector = null!;
|
||||
private BehaviourCacher<IDisplayableSprite> displayableCacher = null!;
|
||||
private BehaviourCacher<IDisplayableShape> displayableShapeCacher = null!;
|
||||
private MonoGameCamera2DBehaviour cameraBehaviour = null!;
|
||||
|
||||
private PongManagerBehaviour pongManager = null!;
|
||||
@@ -50,9 +50,9 @@ public class GamePong : Game
|
||||
{
|
||||
// TODO: Add your initialization logic here
|
||||
gameManager = new();
|
||||
displayableCollector = new(gameManager);
|
||||
displayableShapeCollector = new(gameManager);
|
||||
physicsEngine = new PhysicsEngine2DCollector(gameManager) { IterationPerStep = 3 };
|
||||
displayableCacher = new(gameManager);
|
||||
displayableShapeCacher = new(gameManager);
|
||||
physicsEngine = new PhysicsEngine2DCacher(gameManager) { IterationPerStep = 3 };
|
||||
|
||||
gameManager.Initialize();
|
||||
|
||||
@@ -67,44 +67,18 @@ public class GamePong : Game
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
string[] commandLineArguments = Environment.GetCommandLineArgs();
|
||||
if (commandLineArguments.Length != 1)
|
||||
{
|
||||
if (commandLineArguments[1].Equals("server", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
gameManager.InstantiateGameObject().BehaviourController.AddBehaviour<NetworkServer>().Start(8888, 2);
|
||||
Window.Title = "Pong - Server";
|
||||
}
|
||||
else
|
||||
{
|
||||
Window.Title = $"Pong - Client -> {commandLineArguments[1]}";
|
||||
gameManager.InstantiateGameObject().BehaviourController.AddBehaviour<NetworkClient>().Connect(commandLineArguments[1], 8888);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
gameManager.InstantiateGameObject().BehaviourController.AddBehaviour<NetworkClient>().Connect("127.0.0.1", 8888);
|
||||
Window.Title = $"Pong - Client -> 127.0.0.1";
|
||||
}
|
||||
|
||||
IGameObject gameObjectNetworkManager = gameManager.InstantiateGameObject().SetGameObject("Network Manager"); ;
|
||||
gameObjectNetworkManager.BehaviourController.AddBehaviour<NetworkManager>();
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
IGameObject gameObjectCamera = gameManager.InstantiateGameObject().SetGameObject("Camera"); ;
|
||||
IGameObject gameObjectCamera = gameManager.InstantiateGameObject<GameObject>().SetGameObject("Camera"); ;
|
||||
gameObjectCamera.BehaviourController.AddBehaviour<CameraController>();
|
||||
cameraBehaviour = gameObjectCamera.BehaviourController.AddBehaviour<MonoGameCamera2DBehaviour>(graphics);
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
IGameObject gameObjectPongManager = gameManager.InstantiateGameObject().SetGameObject("Pong Game Manager");
|
||||
IGameObject gameObjectPongManager = gameManager.InstantiateGameObject<GameObject>().SetGameObject("Pong Game Manager");
|
||||
pongManager = gameObjectPongManager.BehaviourController.AddBehaviour<PongManagerBehaviour>(5);
|
||||
pongManager.Id = "pongManager";
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
IGameObject gameObjectBall = gameManager.InstantiateGameObject().SetGameObject("Ball");
|
||||
IGameObject gameObjectBall = gameManager.InstantiateGameObject<GameObject>().SetGameObject("Ball");
|
||||
gameObjectBall.Transform.SetTransform(position: new Vector2D(0, 0f), scale: new Vector2D(10f, 10f));
|
||||
|
||||
gameObjectBall.BehaviourController.AddBehaviour<CircleBehaviour>(new Circle(Vector2D.Zero, 1f));
|
||||
@@ -113,38 +87,38 @@ public class GamePong : Game
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
IGameObject gameObjectLeftPaddle = gameManager.InstantiateGameObject().SetGameObject("Left Paddle");
|
||||
IGameObject gameObjectLeftPaddle = gameManager.InstantiateGameObject<GameObject>().SetGameObject("Left Paddle");
|
||||
gameObjectLeftPaddle.Transform.SetTransform(position: new Vector2D(-468f, 0f), scale: new Vector2D(15f, 60f));
|
||||
|
||||
gameObjectLeftPaddle.BehaviourController.AddBehaviour<PaddleBehaviour>(Keys.W, Keys.S, 228f, -228f, 400f).Id = "leftPaddle";
|
||||
gameObjectLeftPaddle.BehaviourController.AddBehaviour<PaddleBehaviour>(Keys.W, Keys.S, 228f, -228f, 400f).Id = "leftPaddle"; ;
|
||||
gameObjectLeftPaddle.BehaviourController.AddBehaviour<ShapeBehaviour>(Shape.Box);
|
||||
gameObjectLeftPaddle.BehaviourController.AddBehaviour<RigidBody2D>().IsStatic = true;
|
||||
|
||||
IGameObject gameObjectRightPaddle = gameManager.InstantiateGameObject().SetGameObject("Right Paddle");
|
||||
IGameObject gameObjectRightPaddle = gameManager.InstantiateGameObject<GameObject>().SetGameObject("Right Paddle");
|
||||
gameObjectRightPaddle.Transform.SetTransform(position: new Vector2D(468f, 0f), scale: new Vector2D(15f, 60f));
|
||||
gameObjectRightPaddle.BehaviourController.AddBehaviour<PaddleBehaviour>(Keys.Up, Keys.Down, 228f, -228f, 400f).Id = "rightPaddle";
|
||||
gameObjectRightPaddle.BehaviourController.AddBehaviour<PaddleBehaviour>(Keys.Up, Keys.Down, 228f, -228f, 400f).Id = "rightPaddle"; ;
|
||||
gameObjectRightPaddle.BehaviourController.AddBehaviour<ShapeBehaviour>(Shape.Box);
|
||||
gameObjectRightPaddle.BehaviourController.AddBehaviour<RigidBody2D>().IsStatic = true;
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
IGameObject gameObjectWallTop = gameManager.InstantiateGameObject().SetGameObject("Wall Top");
|
||||
IGameObject gameObjectWallTop = gameManager.InstantiateGameObject<GameObject>().SetGameObject("Wall Top");
|
||||
gameObjectWallTop.Transform.SetTransform(position: new Vector2D(0f, 308f), scale: new Vector2D(552f, 20f));
|
||||
gameObjectWallTop.BehaviourController.AddBehaviour<ShapeBehaviour>(Shape.Box);
|
||||
gameObjectWallTop.BehaviourController.AddBehaviour<RigidBody2D>().IsStatic = true;
|
||||
|
||||
IGameObject gameObjectWallBottom = gameManager.InstantiateGameObject().SetGameObject("Wall Bottom");
|
||||
IGameObject gameObjectWallBottom = gameManager.InstantiateGameObject<GameObject>().SetGameObject("Wall Bottom");
|
||||
gameObjectWallBottom.Transform.SetTransform(position: new Vector2D(0f, -308f), scale: new Vector2D(552f, 20f));
|
||||
gameObjectWallBottom.BehaviourController.AddBehaviour<ShapeBehaviour>(Shape.Box);
|
||||
gameObjectWallBottom.BehaviourController.AddBehaviour<RigidBody2D>().IsStatic = true;
|
||||
|
||||
IGameObject gameObjectWallRight = gameManager.InstantiateGameObject().SetGameObject("Wall Right");
|
||||
IGameObject gameObjectWallRight = gameManager.InstantiateGameObject<GameObject>().SetGameObject("Wall Right");
|
||||
gameObjectWallRight.Transform.SetTransform(position: new Vector2D(532f, 0f), scale: new Vector2D(20f, 328f));
|
||||
gameObjectWallRight.BehaviourController.AddBehaviour<WallScoreBehaviour>((Action)pongManager.ScoreToLeft);
|
||||
gameObjectWallRight.BehaviourController.AddBehaviour<ShapeBehaviour>(Shape.Box);
|
||||
gameObjectWallRight.BehaviourController.AddBehaviour<RigidBody2D>().IsStatic = true;
|
||||
|
||||
IGameObject gameObjectWallLeft = gameManager.InstantiateGameObject().SetGameObject("Wall Left");
|
||||
IGameObject gameObjectWallLeft = gameManager.InstantiateGameObject<GameObject>().SetGameObject("Wall Left");
|
||||
gameObjectWallLeft.Transform.SetTransform(position: new Vector2D(-532f, 0f), scale: new Vector2D(20f, 328f));
|
||||
gameObjectWallLeft.BehaviourController.AddBehaviour<WallScoreBehaviour>((Action)pongManager.ScoreToRight);
|
||||
gameObjectWallLeft.BehaviourController.AddBehaviour<ShapeBehaviour>(Shape.Box);
|
||||
@@ -152,13 +126,25 @@ public class GamePong : Game
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
IGameObject gameObjectLeftScoreText = gameManager.InstantiateGameObject().SetGameObject("Score Left");
|
||||
IGameObject gameObjectLeftScoreText = gameManager.InstantiateGameObject<GameObject>().SetGameObject("Score Left");
|
||||
gameObjectLeftScoreText.Transform.SetTransform(position: new Vector2D(-250f, 250f), scale: Vector2D.One * .25f);
|
||||
gameObjectLeftScoreText.BehaviourController.AddBehaviour<TextScoreBehaviour>(true, spriteFont);
|
||||
|
||||
IGameObject gameObjectRightScoreText = gameManager.InstantiateGameObject().SetGameObject("Score Right");
|
||||
IGameObject gameObjectRightScoreText = gameManager.InstantiateGameObject<GameObject>().SetGameObject("Score Right");
|
||||
gameObjectRightScoreText.Transform.SetTransform(position: new Vector2D(250f, 250f), scale: Vector2D.One * .25f);
|
||||
gameObjectRightScoreText.BehaviourController.AddBehaviour<TextScoreBehaviour>(false, spriteFont);
|
||||
|
||||
string[] commandLineArguments = Environment.GetCommandLineArgs();
|
||||
if (commandLineArguments.Length != 1)
|
||||
{
|
||||
if (commandLineArguments[1].Equals("server", StringComparison.OrdinalIgnoreCase))
|
||||
pongManager.BehaviourController.AddBehaviour<NetworkServer>().Start(8888, 2);
|
||||
else
|
||||
pongManager.BehaviourController.AddBehaviour<NetworkClient>().Connect(commandLineArguments[1], 8888);
|
||||
|
||||
}
|
||||
else
|
||||
pongManager.BehaviourController.AddBehaviour<NetworkClient>().Connect("127.0.0.1", 8888);
|
||||
}
|
||||
|
||||
protected override void Update(GameTime gameTime)
|
||||
@@ -183,12 +169,12 @@ public class GamePong : Game
|
||||
gameManager.PreDraw();
|
||||
|
||||
spriteBatch.Begin(SpriteSortMode.Deferred, transformMatrix: cameraBehaviour.MatrixTransform);
|
||||
foreach (var displayable in displayableCollector)
|
||||
foreach (var displayable in displayableCacher)
|
||||
displayable.Draw(spriteBatch);
|
||||
spriteBatch.End();
|
||||
|
||||
shapeBatch.Begin(cameraBehaviour.MatrixTransform);
|
||||
foreach (var displayableShape in displayableShapeCollector)
|
||||
foreach (var displayableShape in displayableShapeCacher)
|
||||
displayableShape.Draw(shapeBatch);
|
||||
shapeBatch.End();
|
||||
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
using Syntriax.Engine.Core.Abstract;
|
||||
|
||||
namespace Syntriax.Engine.Network.Abstract;
|
||||
|
||||
public interface INetworkBehaviour : IBehaviour, INetworkEntity
|
||||
{
|
||||
bool IsServer { get; }
|
||||
bool IsClient { get; }
|
||||
|
||||
INetworkCommunicator NetworkCommunicator { get; }
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
using LiteNetLib;
|
||||
|
||||
namespace Syntriax.Engine.Network.Abstract;
|
||||
|
||||
public interface INetworkCommunicator
|
||||
{
|
||||
event OnPacketReceivedDelegate? OnPacketReceived;
|
||||
|
||||
EventBasedNetListener Listener { get; }
|
||||
NetManager Manager { get; }
|
||||
|
||||
void PollEvents();
|
||||
void Stop();
|
||||
|
||||
void Send<T>(NetworkPacket<T> Data);
|
||||
|
||||
delegate void OnPacketReceivedDelegate(INetworkCommunicator sender, object packet);
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
namespace Syntriax.Engine.Network.Abstract;
|
||||
|
||||
public interface INetworkCommunicatorClient : INetworkCommunicator
|
||||
{
|
||||
void Connect(string address, int port, string? password = null);
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
namespace Syntriax.Engine.Network.Abstract;
|
||||
|
||||
public interface INetworkEntity
|
||||
{
|
||||
event OnNetworkIdChangedDelegate? OnNetworkIdChanged;
|
||||
|
||||
uint NetworkId { get; set; }
|
||||
|
||||
void ReceiveData<T>(T data);
|
||||
|
||||
delegate void OnNetworkIdChangedDelegate(INetworkEntity sender, uint previousId);
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
namespace Syntriax.Engine.Network.Abstract;
|
||||
|
||||
public interface INetworkManager
|
||||
{
|
||||
// Action<IGameObject>? OnNetworkGameObjectInstantiated { get; set; }
|
||||
|
||||
INetworkCommunicator NetworkCommunicator { get; }
|
||||
|
||||
// Task<T> Instantiate<T>(params object?[]? args) where T : class, IGameObject;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
using LiteNetLib.Utils;
|
||||
|
||||
namespace Syntriax.Engine.Network.Abstract;
|
||||
|
||||
public interface INetworkPacket : INetSerializable;
|
||||
@@ -1,7 +0,0 @@
|
||||
namespace Syntriax.Engine.Network.Abstract;
|
||||
|
||||
public class NetworkPacket<T>
|
||||
{
|
||||
public uint NetworkId { get; set; } = 0;
|
||||
public T Data { get; set; } = default!;
|
||||
}
|
||||
6
Game/Network/INetworkClient.cs
Normal file
6
Game/Network/INetworkClient.cs
Normal file
@@ -0,0 +1,6 @@
|
||||
namespace Pong.Network;
|
||||
|
||||
public interface INetworkClient : INetworkCommunicator
|
||||
{
|
||||
void Connect(string address, int port, string? password = null);
|
||||
}
|
||||
19
Game/Network/INetworkCommunicator.cs
Normal file
19
Game/Network/INetworkCommunicator.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
using System;
|
||||
using LiteNetLib;
|
||||
using LiteNetLib.Utils;
|
||||
using Syntriax.Engine.Core.Abstract;
|
||||
|
||||
namespace Pong.Network;
|
||||
|
||||
public interface INetworkCommunicator
|
||||
{
|
||||
EventBasedNetListener Listener { get; }
|
||||
NetManager Manager { get; }
|
||||
|
||||
void PollEvents();
|
||||
void Stop();
|
||||
|
||||
void RegisterEntityListener(IEntity entity, Action<NetPacketReader> onDataReceived);
|
||||
void UnregisterEntityListener(IEntity entity);
|
||||
NetDataWriter GetEntityWriter(IEntity entity);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace Syntriax.Engine.Network.Abstract;
|
||||
namespace Pong.Network;
|
||||
|
||||
public interface INetworkCommunicatorServer : INetworkCommunicator
|
||||
public interface INetworkServer : INetworkCommunicator
|
||||
{
|
||||
string Password { get; }
|
||||
int MaxConnectionCount { get; }
|
||||
@@ -1,25 +1,16 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
|
||||
using LiteNetLib;
|
||||
using LiteNetLib.Utils;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
using Syntriax.Engine.Network.Abstract;
|
||||
using Syntriax.Engine.Core.Abstract;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
namespace Pong.Network;
|
||||
|
||||
public abstract class NetworkBase : BehaviourOverride, INetworkCommunicator
|
||||
{
|
||||
public event INetworkCommunicator.OnPacketReceivedDelegate? OnPacketReceived = null;
|
||||
|
||||
protected readonly NetPacketProcessor netPacketProcessor = new();
|
||||
|
||||
protected readonly Dictionary<uint, INetworkEntity> networkEntities = [];
|
||||
|
||||
protected BehaviourCollector<INetworkEntity> networkEntityCollector = null!;
|
||||
|
||||
public EventBasedNetListener Listener { get; private set; } = null!;
|
||||
public NetManager Manager { get; private set; } = null!;
|
||||
|
||||
@@ -31,110 +22,52 @@ public abstract class NetworkBase : BehaviourOverride, INetworkCommunicator
|
||||
Manager = new NetManager(Listener);
|
||||
|
||||
Listener.NetworkReceiveEvent += NetworkReceiveEvent;
|
||||
|
||||
netPacketProcessor.RegisterNestedType<Pong.Behaviours.PaddleBehaviour.PaddleInputs>();
|
||||
RegisterPackets();
|
||||
}
|
||||
|
||||
public void RegisterPackets()
|
||||
{
|
||||
var packetTypes = Assembly.GetExecutingAssembly().GetTypes()
|
||||
.Where(t => typeof(INetworkPacket).IsAssignableFrom(t) && !t.IsInterface)
|
||||
.ToList();
|
||||
|
||||
MethodInfo[] subscribeMethods = netPacketProcessor.GetType()
|
||||
.GetMethods()
|
||||
.Where(m => m.Name == nameof(NetPacketProcessor.SubscribeReusable))
|
||||
.ToArray();
|
||||
|
||||
MethodInfo subscribeMethod = subscribeMethods
|
||||
.FirstOrDefault(m =>
|
||||
m.GetParameters().Length == 1 &&
|
||||
m.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == typeof(Action<,>)
|
||||
) ?? throw new Exception();
|
||||
|
||||
MethodInfo[] methodInfos = typeof(NetworkBase)
|
||||
.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);
|
||||
|
||||
MethodInfo method = methodInfos
|
||||
.FirstOrDefault(
|
||||
m => m.Name == nameof(OnPacketArrived) &&
|
||||
m.IsGenericMethodDefinition
|
||||
) ?? throw new Exception();
|
||||
|
||||
foreach (var packetType in packetTypes)
|
||||
{
|
||||
var networkPacketType = typeof(NetworkPacket<>).MakeGenericType(packetType);
|
||||
MethodInfo genericSubscribe = subscribeMethod.MakeGenericMethod(networkPacketType, typeof(NetPeer));
|
||||
|
||||
Action<object, NetPeer> handler = (packet, peer) =>
|
||||
{
|
||||
MethodInfo handlerMethod = method.MakeGenericMethod(packetType);
|
||||
handlerMethod.Invoke(this, [packet, peer]);
|
||||
};
|
||||
genericSubscribe.Invoke(netPacketProcessor, [handler]);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnPacketArrived<T>(NetworkPacket<T> packet, NetPeer peer) where T : INetworkPacket
|
||||
{
|
||||
if (networkEntities.TryGetValue(packet.NetworkId, out INetworkEntity? entity))
|
||||
entity.ReceiveData(packet.Data);
|
||||
|
||||
OnPacketReceived?.Invoke(this, packet);
|
||||
}
|
||||
|
||||
protected override void OnInitialize()
|
||||
{
|
||||
base.OnInitialize();
|
||||
|
||||
networkEntityCollector = new(GameObject.GameManager);
|
||||
networkEntityCollector.OnCollected += OnNetworkEntityCollected;
|
||||
networkEntityCollector.OnRemoved += OnNetworkEntityRemoved;
|
||||
}
|
||||
|
||||
protected override void OnFinalize()
|
||||
{
|
||||
networkEntityCollector.OnCollected -= OnNetworkEntityCollected;
|
||||
networkEntityCollector.OnRemoved -= OnNetworkEntityRemoved;
|
||||
Stop();
|
||||
}
|
||||
|
||||
private void OnNetworkEntityCollected(BehaviourCollector<INetworkEntity> sender, INetworkEntity behaviourCollected)
|
||||
{
|
||||
if (behaviourCollected.NetworkId != 0)
|
||||
networkEntities.Add(behaviourCollected.NetworkId, behaviourCollected);
|
||||
|
||||
behaviourCollected.OnNetworkIdChanged += OnNetworkIdChanged;
|
||||
}
|
||||
|
||||
private void OnNetworkIdChanged(INetworkEntity sender, uint previousId)
|
||||
{
|
||||
if (networkEntities.TryGetValue(previousId, out INetworkEntity? networkEntity) && sender == networkEntity)
|
||||
networkEntities.Remove(previousId);
|
||||
|
||||
networkEntities.Add(sender.NetworkId, sender);
|
||||
}
|
||||
|
||||
private void OnNetworkEntityRemoved(BehaviourCollector<INetworkEntity> sender, INetworkEntity behaviourRemoved)
|
||||
{
|
||||
networkEntities.Remove(behaviourRemoved.NetworkId);
|
||||
behaviourRemoved.OnNetworkIdChanged -= OnNetworkIdChanged;
|
||||
}
|
||||
|
||||
private void NetworkReceiveEvent(NetPeer peer, NetPacketReader reader, byte channel, DeliveryMethod deliveryMethod)
|
||||
{
|
||||
try
|
||||
{
|
||||
netPacketProcessor.ReadAllPackets(reader, peer);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
public void PollEvents() => Manager.PollEvents();
|
||||
public void Stop() => Manager.Stop();
|
||||
|
||||
protected override void OnUpdate() => PollEvents();
|
||||
protected override void OnFinalize() => Stop();
|
||||
|
||||
public abstract void Send<T>(NetworkPacket<T> packet);
|
||||
private Dictionary<string, Action<NetPacketReader>> callbacks = new(32);
|
||||
|
||||
private void NetworkReceiveEvent(NetPeer peer, NetPacketReader reader, byte channel, DeliveryMethod deliveryMethod)
|
||||
{
|
||||
if (callbacks.TryGetValue(reader.GetString(), out var action))
|
||||
action?.Invoke(reader);
|
||||
|
||||
reader.Recycle();
|
||||
}
|
||||
|
||||
public void RegisterEntityListener(IEntity entity, Action<NetPacketReader> onDataReceived)
|
||||
{
|
||||
if (callbacks.ContainsKey(entity.Id))
|
||||
return;
|
||||
|
||||
callbacks.Add(entity.Id, onDataReceived);
|
||||
entity.OnIdChanged += OnEntityIdChanged;
|
||||
}
|
||||
|
||||
public void UnregisterEntityListener(IEntity entity)
|
||||
{
|
||||
if (!callbacks.Remove(entity.Id))
|
||||
return;
|
||||
|
||||
entity.OnIdChanged -= OnEntityIdChanged;
|
||||
}
|
||||
|
||||
public NetDataWriter GetEntityWriter(IEntity entity)
|
||||
{
|
||||
NetDataWriter netDataWriter = new();
|
||||
netDataWriter.Put(entity.Id);
|
||||
return netDataWriter;
|
||||
}
|
||||
|
||||
private void OnEntityIdChanged(IEntity entity, string previousId)
|
||||
{
|
||||
var action = callbacks[previousId];
|
||||
callbacks.Remove(previousId);
|
||||
callbacks.Add(entity.Id, action);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
using System;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
using Syntriax.Engine.Network.Abstract;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
public abstract class NetworkBehaviour : BehaviourOverride, INetworkBehaviour
|
||||
{
|
||||
public event INetworkEntity.OnNetworkIdChangedDelegate? OnNetworkIdChanged = null;
|
||||
|
||||
private uint _networkId = 0;
|
||||
public uint NetworkId
|
||||
{
|
||||
get => _networkId;
|
||||
set
|
||||
{
|
||||
if (value == _networkId)
|
||||
return;
|
||||
|
||||
uint previousNetworkId = _networkId;
|
||||
_networkId = value;
|
||||
OnNetworkIdChanged?.Invoke(this, previousNetworkId);
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsServer { get; private set; } = false;
|
||||
public bool IsClient { get; private set; } = false;
|
||||
|
||||
public INetworkCommunicator NetworkCommunicator { get; private set; } = null!;
|
||||
|
||||
|
||||
protected override void OnInitialize()
|
||||
{
|
||||
NetworkCommunicator = BehaviourController.GetBehaviourInParent<INetworkCommunicator>()
|
||||
?? GameObject.GameManager.FindBehaviour<INetworkCommunicator>()
|
||||
?? throw new Exception($"Could not find an {nameof(INetworkCommunicator)}.");
|
||||
|
||||
if (NetworkCommunicator is INetworkCommunicatorClient client)
|
||||
{
|
||||
IsClient = true;
|
||||
return;
|
||||
}
|
||||
|
||||
IsServer = true;
|
||||
}
|
||||
|
||||
public void SendData<T>(T data)
|
||||
=> NetworkCommunicator.Send(new NetworkPacket<T>() { NetworkId = _networkId, Data = data });
|
||||
|
||||
public abstract void ReceiveData<T>(T data);
|
||||
}
|
||||
@@ -1,23 +1,10 @@
|
||||
using LiteNetLib.Utils;
|
||||
namespace Pong.Network;
|
||||
|
||||
using Syntriax.Engine.Network.Abstract;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
public class NetworkClient : NetworkBase, INetworkCommunicatorClient
|
||||
public class NetworkClient : NetworkBase, INetworkClient
|
||||
{
|
||||
private readonly NetDataWriter netDataWriter = new();
|
||||
|
||||
public void Connect(string address, int port, string? password = null)
|
||||
{
|
||||
Manager.Start();
|
||||
Manager.Connect(address, port, password ?? string.Empty);
|
||||
}
|
||||
|
||||
public override void Send<T>(NetworkPacket<T> packet)
|
||||
{
|
||||
netDataWriter.Reset();
|
||||
netPacketProcessor.Write(netDataWriter, packet);
|
||||
Manager.FirstPeer.Send(netDataWriter, LiteNetLib.DeliveryMethod.ReliableOrdered);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,14 @@
|
||||
using LiteNetLib;
|
||||
using LiteNetLib.Utils;
|
||||
|
||||
using Syntriax.Engine.Core;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
namespace Pong.Network;
|
||||
|
||||
public static class NetworkExtensions
|
||||
{
|
||||
public static Vector2D GetVector2D(this NetPacketReader reader)
|
||||
=> new(reader.GetFloat(), reader.GetFloat());
|
||||
|
||||
public static void GetVector2D(this NetPacketReader reader, out Vector2D vector2D)
|
||||
=> vector2D = new(reader.GetFloat(), reader.GetFloat());
|
||||
|
||||
public static void Put(this NetDataWriter writer, Vector2D vector)
|
||||
{
|
||||
writer.Put(vector.X);
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
using Syntriax.Engine.Core;
|
||||
|
||||
using Syntriax.Engine.Network.Abstract;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
public class NetworkManager : NetworkBehaviour, INetworkManager
|
||||
{
|
||||
private BehaviourCollector<INetworkEntity> entities = null!;
|
||||
|
||||
private static uint networkIdIndex = 0;
|
||||
|
||||
protected override void OnInitialize()
|
||||
{
|
||||
base.OnInitialize();
|
||||
|
||||
NetworkId = networkIdIndex++;
|
||||
|
||||
entities = new(GameObject.GameManager);
|
||||
foreach (var entity in entities)
|
||||
entity.NetworkId = networkIdIndex++;
|
||||
|
||||
entities.OnCollected += OnCollected;
|
||||
}
|
||||
|
||||
private void OnCollected(BehaviourCollector<INetworkEntity> collector, INetworkEntity entity)
|
||||
=> entity.NetworkId = networkIdIndex++;
|
||||
|
||||
public override void ReceiveData<T>(T data) { }
|
||||
}
|
||||
@@ -1,35 +1,20 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using LiteNetLib.Utils;
|
||||
namespace Pong.Network;
|
||||
|
||||
using Syntriax.Engine.Network.Abstract;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
public class NetworkServer : NetworkBase, INetworkCommunicatorServer
|
||||
public class NetworkServer : NetworkBase, INetworkServer
|
||||
{
|
||||
public string Password { get; private set; } = string.Empty;
|
||||
public int MaxConnectionCount { get; private set; } = 2;
|
||||
public int MaxConnectionCount { get; private set; } = 0;
|
||||
public int Port { get; private set; } = 8888;
|
||||
|
||||
private readonly NetDataWriter netDataWriter = new();
|
||||
|
||||
public NetworkServer() : this(8888, 2) { }
|
||||
public NetworkServer(int port, int maxConnectionCount) : base()
|
||||
public NetworkServer() : base()
|
||||
{
|
||||
MaxConnectionCount = maxConnectionCount;
|
||||
Port = port;
|
||||
|
||||
Listener.ConnectionRequestEvent += request =>
|
||||
{
|
||||
if (Manager.ConnectedPeersCount < maxConnectionCount)
|
||||
if (Manager.ConnectedPeersCount < MaxConnectionCount)
|
||||
request.AcceptIfKey(Password);
|
||||
else
|
||||
request.Reject();
|
||||
};
|
||||
|
||||
OnPacketReceived += ServerOnPacketReceived;
|
||||
}
|
||||
|
||||
public void Start(int port, int maxConnectionCount, string? password = null)
|
||||
@@ -40,28 +25,4 @@ public class NetworkServer : NetworkBase, INetworkCommunicatorServer
|
||||
|
||||
Manager.Start(port);
|
||||
}
|
||||
|
||||
public override void Send<T>(NetworkPacket<T> packet)
|
||||
{
|
||||
netDataWriter.Reset();
|
||||
netPacketProcessor.Write(netDataWriter, packet);
|
||||
Manager.SendToAll(netDataWriter, LiteNetLib.DeliveryMethod.ReliableOrdered);
|
||||
}
|
||||
|
||||
private void ServerOnPacketReceived(INetworkCommunicator sender, object packet)
|
||||
{
|
||||
MethodInfo[] methodInfos = GetType()
|
||||
.GetMethods(BindingFlags.Public | BindingFlags.Instance);
|
||||
|
||||
MethodInfo method = methodInfos
|
||||
.FirstOrDefault(
|
||||
m => m.Name == nameof(Send) && m.IsGenericMethod
|
||||
) ?? throw new Exception();
|
||||
|
||||
Type typeArguments = packet.GetType().GetGenericArguments()[0];
|
||||
|
||||
MethodInfo methodInfo = method.MakeGenericMethod(typeArguments);
|
||||
|
||||
methodInfo.Invoke(this, [packet]);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user