Skip to content

Commit

Permalink
Merge pull request #70 from psu-de/feature/events
Browse files Browse the repository at this point in the history
Feature/events
  • Loading branch information
psu-de authored Jul 25, 2024
2 parents 8d63be9 + bee1e56 commit aa1c48d
Show file tree
Hide file tree
Showing 15 changed files with 626 additions and 160 deletions.
16 changes: 6 additions & 10 deletions Components/MineSharp.Physics/PlayerPhysics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using MineSharp.Core.Common.Effects;
using MineSharp.Core.Common.Entities;
using MineSharp.Core.Common.Entities.Attributes;
using MineSharp.Core.Events;
using MineSharp.Core.Geometry;
using MineSharp.Data;
using MineSharp.Physics.Components;
Expand All @@ -18,11 +19,6 @@ namespace MineSharp.Physics;
/// </summary>
public class PlayerPhysics
{
/// <summary>
/// Event with PlayerPhysics and a boolean value
/// </summary>
public delegate void PlayerPhysicsBooleanEvent(PlayerPhysics sender, bool value);

private static readonly Vector3[] XzAxisVectors = { Vector3.West, Vector3.East, Vector3.North, Vector3.South };

/// <summary>
Expand Down Expand Up @@ -97,12 +93,12 @@ public PlayerPhysics(MinecraftData data, MinecraftPlayer player, IWorld world, I
/// <summary>
/// Fired when the player starts or stops crouching
/// </summary>
public event PlayerPhysicsBooleanEvent? OnCrouchingChanged;
public AsyncEvent<PlayerPhysics, bool> OnCrouchingChanged = new();

/// <summary>
/// Fired when the player starts or stops sprinting
/// </summary>
public event PlayerPhysicsBooleanEvent? OnSprintingChanged;
public AsyncEvent<PlayerPhysics, bool> OnSprintingChanged = new();

/// <summary>
/// Simulate a single tick
Expand Down Expand Up @@ -149,7 +145,7 @@ private void MovementTick()

if (State.IsCrouching != crouchedBefore)
{
Task.Run(() => OnCrouchingChanged?.Invoke(this, State.IsCrouching));
OnCrouchingChanged.Dispatch(this, State.IsCrouching);
}

var crouchSpeedFactor = (float)Math.Clamp(0.3f + 0.0, 0.0f, 1.0f); // Enchantment Soul Speed factor
Expand Down Expand Up @@ -704,7 +700,7 @@ private void UpdateSprinting()
// TODO: Prob add sprinting attribute
speedAttribute.AddModifier(sprintingModifier);
State.IsSprinting = true;
Task.Run(() => OnSprintingChanged?.Invoke(this, State.IsSprinting));
OnSprintingChanged.Dispatch(this, State.IsSprinting);
}

if (State.IsSprinting)
Expand All @@ -720,7 +716,7 @@ private void UpdateSprinting()
{
speedAttribute.RemoveModifier(sprintingModifier.Uuid);
State.IsSprinting = false;
Task.Run(() => OnSprintingChanged?.Invoke(this, State.IsSprinting));
OnSprintingChanged.Dispatch(this, State.IsSprinting);
}
}
}
Expand Down
76 changes: 25 additions & 51 deletions Components/MineSharp.Protocol/MinecraftClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@
using System.Net;
using System.Net.Sockets;
using MineSharp.Auth;
using MineSharp.ChatComponent;
using MineSharp.ChatComponent.Components;
using MineSharp.Core;
using MineSharp.Core.Common;
using MineSharp.Core.Common.Protocol;
using MineSharp.Core.Events;
using MineSharp.Data;
using MineSharp.Data.Protocol;
using MineSharp.Protocol.Connection;
Expand Down Expand Up @@ -79,6 +82,11 @@ public sealed class MinecraftClient : IDisposable
/// The clients settings
/// </summary>
public readonly ClientSettings Settings;

/// <summary>
/// Fires when the client disconnected from the server
/// </summary>
public AsyncEvent<MinecraftClient, Chat> OnDisconnected = new();

private readonly IConnectionFactory tcpTcpFactory;

Expand Down Expand Up @@ -136,21 +144,6 @@ public void Dispose()
stream?.Close();
}

/// <summary>
/// Fires whenever the client received a known Packet
/// </summary>
public event Events.ClientPacketEvent? OnPacketReceived;

/// <summary>
/// Fires whenever the client has sent a packet
/// </summary>
public event Events.ClientPacketEvent? OnPacketSent;

/// <summary>
/// Fires when the client disconnected from the server
/// </summary>
public event Events.ClientStringEvent? OnDisconnected;

/// <summary>
/// Connects to the minecraft sever.
/// </summary>
Expand Down Expand Up @@ -203,13 +196,15 @@ public Task SendPacket(IPacket packet, CancellationToken cancellation = default)
/// </summary>
/// <param name="reason">The reason the client disconnected. Only used for the <see cref="OnDisconnected" /> event.</param>
/// <exception cref="InvalidOperationException"></exception>
public async Task Disconnect(string reason = "disconnect.quitting")
public async Task Disconnect(Chat? reason = null)
{
Logger.Info($"Disconnecting: {reason}");
reason ??= new TranslatableComponent("disconnect.quitting");

Logger.Info($"Disconnecting: {reason.GetMessage(this.Data)}");

if (!gameJoinedTsc.Task.IsCompleted)
{
gameJoinedTsc.SetException(new DisconnectedException("Client has been disconnected", reason));
gameJoinedTsc.SetException(new DisconnectedException("Client has been disconnected", reason.GetMessage(this.Data)));
}

if (client is null || !client.Connected)
Expand All @@ -221,7 +216,7 @@ public async Task Disconnect(string reason = "disconnect.quitting")
await (streamLoop ?? Task.CompletedTask);

client?.Close();
OnDisconnected?.Invoke(this, reason);
await OnDisconnected.Dispatch(this, reason);
}

/// <summary>
Expand Down Expand Up @@ -289,15 +284,17 @@ internal void UpdateGameState(GameState next)
{
if (Data.Version.Protocol <= ProtocolVersion.V_1_20)
{
SendPacket(new Packets.Serverbound.Play.ClientInformationPacket(
Settings.Locale,
Settings.ViewDistance,
(int)Settings.ChatMode,
Settings.ColoredChat,
Settings.DisplayedSkinParts,
(int)Settings.MainHand,
Settings.EnableTextFiltering,
Settings.AllowServerListings));
Task.Delay(10)
.ContinueWith(x =>
SendPacket(new Packets.Serverbound.Play.ClientInformationPacket(
Settings.Locale,
Settings.ViewDistance,
(int)Settings.ChatMode,
Settings.ColoredChat,
Settings.DisplayedSkinParts,
(int)Settings.MainHand,
Settings.EnableTextFiltering,
Settings.AllowServerListings)));
}
gameJoinedTsc.TrySetResult();
}
Expand Down Expand Up @@ -456,12 +453,6 @@ private async Task HandleIncomingPacket(PacketType packetType, PacketBuffer buff
handlers.AddRange(customHandlers);
}

// Forces all packets to be read
if (null != OnPacketReceived)
{
handlers.Add(InvokeReceivePacketAsync);
}

packetWaiters.TryGetValue(packetType, out var tsc);

if (handlers.Count == 0 && tsc == null)
Expand Down Expand Up @@ -510,23 +501,6 @@ private async Task HandleIncomingPacket(PacketType packetType, PacketBuffer buff
private async Task HandleOutgoingPacket(IPacket packet)
{
await internalPacketHandler.HandleOutgoing(packet);

_ = Task.Run(() =>
{
try
{
OnPacketSent?.Invoke(this, packet);
}
catch (Exception e)
{
Logger.Warn($"Error in custom packet handling: {e}");
}
});
}

private Task InvokeReceivePacketAsync(IPacket packet)
{
return Task.Run(() => OnPacketReceived?.Invoke(this, packet));
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ or PacketType.CB_Configuration_KeepAlive

private Task HandleDisconnect(DisconnectPacket packet)
{
_ = Task.Run(() => client.Disconnect(packet.Reason.GetMessage(data)));
_ = Task.Run(() => client.Disconnect(packet.Reason));
return Task.CompletedTask;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ or PacketType.CB_Login_LoginPluginRequest

private Task HandleDisconnect(DisconnectPacket packet)
{
_ = Task.Run(() => client.Disconnect(packet.Reason.GetMessage(data)));
_ = Task.Run(() => client.Disconnect(packet.Reason));
return Task.CompletedTask;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ private Task HandlePing(PingPacket ping)

private Task HandleDisconnect(DisconnectPacket packet)
{
_ = Task.Run(() => client.Disconnect(packet.Reason.GetMessage(data)));
_ = Task.Run(() => client.Disconnect(packet.Reason));
return Task.CompletedTask;
}
}
5 changes: 3 additions & 2 deletions Components/MineSharp.Windows/Window.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using MineSharp.Core.Common;
using MineSharp.Core.Common.Items;
using MineSharp.Core.Events;
using MineSharp.Windows.Clicks;
using NLog;

Expand Down Expand Up @@ -109,7 +110,7 @@ public int TotalSlotCount
/// <summary>
/// Fired when a slot changed
/// </summary>
public event SlotChanged? OnSlotChanged;
public AsyncEvent<Window, short> OnSlotChanged = new();

private IDictionary<short, Item?> InitializeSlots(int count)
{
Expand Down Expand Up @@ -276,7 +277,7 @@ internal void UpdateSlot(Item? item, short slotIndex)
}
}

OnSlotChanged?.Invoke(this, slotIndex);
OnSlotChanged.Dispatch(this, slotIndex);
}

/// <summary>
Expand Down
15 changes: 8 additions & 7 deletions Components/MineSharp.World/AbstractWorld.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Diagnostics.Contracts;
using MineSharp.Core.Common.Biomes;
using MineSharp.Core.Common.Blocks;
using MineSharp.Core.Events;
using MineSharp.Core.Geometry;
using MineSharp.Data;
using MineSharp.World.Chunks;
Expand Down Expand Up @@ -40,13 +41,13 @@ public abstract class AbstractWorld(MinecraftData data) : IWorld


/// <inheritdoc />
public event Events.ChunkEvent? OnChunkLoaded;
public AsyncEvent<IWorld, IChunk> OnChunkLoaded { get; set; } = new();

/// <inheritdoc />
public event Events.ChunkEvent? OnChunkUnloaded;
public AsyncEvent<IWorld, IChunk> OnChunkUnloaded { get; set; } = new();

/// <inheritdoc />
public event Events.BlockEvent? OnBlockUpdated;
public AsyncEvent<IWorld, Block> OnBlockUpdated { get; set; } = new();

/// <inheritdoc />
[Pure]
Expand Down Expand Up @@ -110,7 +111,7 @@ public void LoadChunk(IChunk chunk)
}

chunk.OnBlockUpdated += OnChunkBlockUpdate;
OnChunkLoaded?.Invoke(this, chunk);
OnChunkLoaded.Dispatch(this, chunk);
}

/// <inheritdoc />
Expand All @@ -122,7 +123,7 @@ public void UnloadChunk(ChunkCoordinates coordinates)
return;
}

OnChunkUnloaded?.Invoke(this, chunk);
OnChunkUnloaded.Dispatch(this, chunk);
}

/// <inheritdoc />
Expand Down Expand Up @@ -243,8 +244,8 @@ protected bool IsChunkLoaded(ChunkCoordinates coordinates, [NotNullWhen(true)] o
private void OnChunkBlockUpdate(IChunk chunk, int state, Position position)
{
var worldPosition = ToWorldPosition(chunk.Coordinates, position);
OnBlockUpdated?.Invoke(this, new( // TODO: Hier jedes mal ein neuen block zu erstellen ist quatsch
Data.Blocks.ByState(state)!, state, worldPosition));
OnBlockUpdated.Dispatch(this, new( // TODO: Hier jedes mal ein neuen block zu erstellen ist quatsch
Data.Blocks.ByState(state)!, state, worldPosition));
}

private int NonNegativeMod(int x, int m)
Expand Down
7 changes: 4 additions & 3 deletions Components/MineSharp.World/IWorld.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Diagnostics.CodeAnalysis;
using MineSharp.Core.Common.Biomes;
using MineSharp.Core.Common.Blocks;
using MineSharp.Core.Events;
using MineSharp.Core.Geometry;
using MineSharp.World.Chunks;
using MineSharp.World.Iterators;
Expand Down Expand Up @@ -30,17 +31,17 @@ public interface IWorld
/// <summary>
/// Event fired when a chunk loaded
/// </summary>
public event Events.ChunkEvent OnChunkLoaded;
public AsyncEvent<IWorld, IChunk> OnChunkLoaded { get; set; }

/// <summary>
/// Fired when a was unloaded
/// </summary>
public event Events.ChunkEvent OnChunkUnloaded;
public AsyncEvent<IWorld, IChunk> OnChunkUnloaded { get; set; }

/// <summary>
/// Fired when a block was updated
/// </summary>
public event Events.BlockEvent OnBlockUpdated;
public AsyncEvent<IWorld, Block> OnBlockUpdated { get; set; }

/// <summary>
/// Converts a World position to chunk coordinates
Expand Down
Loading

0 comments on commit aa1c48d

Please sign in to comment.