Skip to content

Commit

Permalink
Merge pull request #13 from thiagomvas/improved-event-system
Browse files Browse the repository at this point in the history
Improved event system
  • Loading branch information
thiagomvas authored May 24, 2024
2 parents 755cfe3 + b8deb8e commit f8f5725
Show file tree
Hide file tree
Showing 22 changed files with 155 additions and 172 deletions.
2 changes: 1 addition & 1 deletion Basalt.Core/Basalt.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Version>1.4.0</Version>
<Version>1.5.0</Version>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<PackageIcon>BasaltLogoBg.png</PackageIcon>
<PackageReadmeFile>README.md</PackageReadmeFile>
Expand Down
38 changes: 10 additions & 28 deletions Basalt.Core/Common/Abstractions/Engine/IEventBus.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,40 +9,22 @@ public interface IEventBus : IEngineComponent
/// <summary>
/// Subscribes an observer to the event bus.
/// </summary>
/// <param name="observer">The observer to subscribe.</param>
void Subscribe(IObserver observer);
/// <param name="eventName">The name of the event to subscribe to.</param>
/// <param name="handler">The handler to call when the event is raised.</param>
void Subscribe(string eventName, EventHandler handler);

/// <summary>
/// Unsubscribes an observer from the event bus.
/// </summary>
/// <param name="observer">The observer to unsubscribe.</param>
void Unsubscribe(IObserver observer);

/// <summary>
/// Notifies the event bus that the engine has started.
/// </summary>
void NotifyStart();

/// <summary>
/// Notifies the event bus of an engine update.
/// </summary>
void NotifyUpdate();

/// <summary>
/// Notifies the event bus of a physics update.
/// </summary>
void NotifyPhysicsUpdate();

/// <param name="eventName">The name of the event to unsubscribe from.</param>
/// <param name="handler">The handler to remove from the event.</param>
void Unsubscribe(string eventName, EventHandler handler);

/// <summary>
/// Notifies the event bus to render the scene.
/// Triggers an event on the event bus.
/// </summary>
void NotifyRender();
/// <param name="eventName">The name of the event to trigger.</param>
void TriggerEvent(string eventName);

/// <summary>
/// Checks if an observer is subscribed to the event bus.
/// </summary>
/// <param name="observer">The observer to check.</param>
/// <returns>True if the observer is subscribed, false otherwise.</returns>
bool IsSubscribed(IObserver observer);
}
}
2 changes: 1 addition & 1 deletion Basalt.Raylib/Basalt.Raylib.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Version>1.4.0</Version>
<Version>1.5.0</Version>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<PackageIcon>BasaltLogoBg.png</PackageIcon>
<PackageReadmeFile>README.md</PackageReadmeFile>
Expand Down
1 change: 0 additions & 1 deletion Basalt.Raylib/Components/BoxRenderer.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using Basalt.Common.Components;
using Basalt.Common.Entities;
using Basalt.Common.Utils;
using Basalt.Raylib.Graphics;
using Raylib_cs;
using System.Numerics;
using static Raylib_cs.Raylib;
Expand Down
3 changes: 1 addition & 2 deletions Basalt.Raylib/Graphics/RaylibCache.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using Basalt.Common.Utils;
using Raylib_cs;
using System.Net.NetworkInformation;

namespace Basalt.Raylib.Graphics
{
Expand Down Expand Up @@ -254,7 +253,7 @@ internal static void LoadRaylibPrimitives(this ResourceCache cache)
Model knot = Raylib_cs.Raylib.LoadModelFromMesh(Raylib_cs.Raylib.GenMeshKnot(1, 1, 16, 128));

// Add shader if found
if(ResourceCache.TryGetResource("basalt.shaders.defaultlight", out Shader shader))
if (ResourceCache.TryGetResource("basalt.shaders.defaultlight", out Shader shader))
{
cube.Materials[0].Shader = shader;
sphere.Materials[0].Shader = shader;
Expand Down
8 changes: 2 additions & 6 deletions Basalt.Raylib/Graphics/RaylibGraphicsEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using Basalt.Common.Entities;
using Basalt.Common.Utils;
using Basalt.Core.Common.Abstractions.Engine;
using Basalt.Core.Common.Abstractions.Input;
using Basalt.Core.Common.Abstractions.Sound;
using Basalt.Raylib.Components;
using Basalt.Raylib.Utils;
Expand All @@ -29,7 +28,6 @@ public class RaylibGraphicsEngine : IGraphicsEngine

private EntityManager entityManager;
private ISoundSystem? soundSystem;
private IInputSystem? inputSystem;
private IEventBus eventBus;

Shader PostProcessShader, LightShader;
Expand All @@ -50,7 +48,6 @@ public RaylibGraphicsEngine(WindowInitParams initConfig, ILogger? logger = null)
public unsafe void Initialize()
{
soundSystem = Engine.Instance.GetEngineComponent<ISoundSystem>();
inputSystem = Engine.Instance.GetEngineComponent<IInputSystem>();
eventBus = Engine.Instance.GetEngineComponent<IEventBus>()!;
entityManager = Engine.Instance.EntityManager;
logger = Engine.Instance.Logger;
Expand Down Expand Up @@ -157,8 +154,7 @@ public unsafe void Render()
}
// Update
//----------------------------------------------------------------------------------
eventBus?.NotifyUpdate();
inputSystem?.Update();
eventBus?.TriggerEvent(BasaltConstants.UpdateEventKey);



Expand Down Expand Up @@ -192,7 +188,7 @@ public unsafe void Render()

BeginMode3D(control.camera);

eventBus?.NotifyRender();
eventBus?.TriggerEvent(BasaltConstants.RenderEventKey);


EndMode3D();
Expand Down
6 changes: 4 additions & 2 deletions Basalt.Raylib/Input/RaylibInputSystem.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using Basalt.Core.Common.Abstractions.Input;
using Basalt.Common.Utils;
using Basalt.Core.Common.Abstractions.Engine;
using Basalt.Core.Common.Abstractions.Input;
using Raylib_cs;
using static Raylib_cs.Raylib;
namespace Basalt.Raylib.Input
Expand All @@ -15,7 +17,7 @@ public class RaylibInputSystem : IInputSystem
/// <inheritdoc/>
public void Initialize()
{
// TODO: Implement initialization logic
Engine.Instance.GetEngineComponent<IEventBus>()!.Subscribe(BasaltConstants.UpdateEventKey, (_, _) => Update());
}

/// <inheritdoc/>
Expand Down
6 changes: 3 additions & 3 deletions Basalt.TestField/Components/PlayerController.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
using Basalt.Common;
using Basalt.Common.Components;
using Basalt.Common.Entities;
using Basalt.Common.Physics;
using Basalt.Common.Utils.Extensions;
using Basalt.Core.Common.Abstractions.Engine;
using Basalt.Core.Common.Abstractions.Input;
using Basalt.Core.Common.Types;
using System.Numerics;
Expand All @@ -17,6 +15,7 @@ public class PlayerController : Component
public PlayerController(Entity entity) : base(entity)
{


}
public override void OnStart()
{
Expand Down Expand Up @@ -50,6 +49,7 @@ public override void OnStart()
InputKey.Space,
ActionType.Press),
() => Entity.Rigidbody.Velocity += Vector3.UnitY * 5);

}

//((Engine.Instance.GetEngineComponent<IPhysicsEngine>() as PhysicsEngine).chunking as Grid).player = this.Entity ;
Expand All @@ -59,7 +59,7 @@ public override void OnStart()

public override void OnUpdate()
{
if(Entity.Transform.Position.Y < -10)
if (Entity.Transform.Position.Y < -10)
{
Entity.Transform.Position = new Vector3(Entity.Transform.Position.X, -10, Entity.Transform.Position.Z);
Entity.Rigidbody.Velocity = Vector3.Zero;
Expand Down
1 change: 0 additions & 1 deletion Basalt.TestField/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
using Basalt.Common.Utils;
using Basalt.Core.Common.Abstractions.Engine;
using Basalt.Core.Common.Abstractions.Input;
using Basalt.Math;
using Basalt.Raylib.Components;
using Basalt.Raylib.Graphics;
using Basalt.Raylib.Input;
Expand Down
2 changes: 1 addition & 1 deletion Basalt.TestField/TestingUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public static void SetupTestingScene(int boxCount = 10, int ropeLength = 20)
{
var box = new Entity();
box.Transform.Position = new Vector3(Random.Shared.Next(-30, 30), 25 + i, Random.Shared.Next(-30, 30));
box.AddComponent(new ModelRenderer(box) { ModelCacheKey = "robot", Size = new Vector3((float) (i+1) / 5f), Offset = -Vector3.UnitY * (float)(i + 1) / 2.5f });
box.AddComponent(new ModelRenderer(box) { ModelCacheKey = "robot", Size = new Vector3((float)(i + 1) / 5f), Offset = -Vector3.UnitY * (float)(i + 1) / 2.5f });
box.AddComponent(new BoxCollider(box) { Size = new Vector3(i) });
box.AddComponent(new Rigidbody(box) { IsKinematic = false, Mass = 1 });

Expand Down
13 changes: 10 additions & 3 deletions Basalt.Tests/Integration/ComponentIntegrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
using Basalt.Common.Components;
using Basalt.Common.Entities;
using Basalt.Common.Events;
using Basalt.Common.Utils;
using Basalt.Core.Common.Abstractions.Engine;
using Basalt.Tests.Common;
using Moq;
using System.Numerics;

namespace Basalt.Tests.Integration
{
Expand All @@ -22,7 +24,7 @@ public void Setup()
}

[Test]
public void ComponentAddedToEngine_ShouldBeSubscribedToEventBus()
public void ComponentAddedToEntity_ShouldBeSubscribedToEventBus()
{
// Arrange
var entity = new Entity();
Expand All @@ -32,9 +34,11 @@ public void ComponentAddedToEngine_ShouldBeSubscribedToEventBus()
Engine.Instance.Initialize();
Engine.CreateEntity(entity);
var component = entity.GetComponent<TestComponent>();
Engine.Instance.GetEngineComponent<IEventBus>()!.TriggerEvent(BasaltConstants.StartEventKey);


// Assert
Assert.IsTrue(Engine.Instance.GetEngineComponent<IEventBus>()!.IsSubscribed(component));
Assert.IsTrue(component.HasStarted);
}

[Test]
Expand Down Expand Up @@ -73,15 +77,18 @@ public void ComponentDestroy_ShouldUnsubscribe()
// Arrange
var entity = new Entity();
entity.AddComponent(new TestComponent(entity));
entity.AddComponent(new Rigidbody(entity));
IEqualityComparer<Vector3> comparer = new Vector3EqualityComparer();

// Act
Engine.Instance.Initialize();
Engine.CreateEntity(entity);
var component = entity.GetComponent<TestComponent>();
entity.Destroy();
Engine.Instance.GetEngineComponent<IEventBus>()!.TriggerEvent(BasaltConstants.PhysicsUpdateEventKey);

// Assert
Assert.IsFalse(Engine.Instance.GetEngineComponent<IEventBus>()!.IsSubscribed(component));
Assert.That(entity.Transform.Position, Is.EqualTo(Vector3.Zero).Using(comparer));
}

[Test]
Expand Down
15 changes: 7 additions & 8 deletions Basalt.Tests/Integration/EngineIntegrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Basalt.Common.Components;
using Basalt.Common.Entities;
using Basalt.Common.Events;
using Basalt.Common.Utils;
using Basalt.Core.Common.Abstractions.Engine;
using Basalt.Tests.Common;
using Moq;
Expand Down Expand Up @@ -125,16 +126,15 @@ public void EngineCreateEntity_WhenInitialized_ShouldCreateEntity()
public void EngineEventBus_WhenHasObservers_ShouldNotify()
{
// Arrange
var entity = new Entity();
entity.AddComponent(new TestComponent(entity));

var engine = new EngineBuilder()
.AddComponent<IGraphicsEngine>(() => Mock.Of<IGraphicsEngine>(), true)
.AddComponent<IEventBus, EventBus>()
.Build();

engine.Initialize();

var entity = new Entity();
entity.AddComponent(new TestComponent(entity));
Engine.CreateEntity(entity);

int physicsCalls = 10;
Expand All @@ -146,17 +146,17 @@ public void EngineEventBus_WhenHasObservers_ShouldNotify()
// Act
for (int i = 0; i < physicsCalls; i++)
{
eventBus?.NotifyPhysicsUpdate();
eventBus?.TriggerEvent(BasaltConstants.PhysicsUpdateEventKey);
}

for (int i = 0; i < updareCalls; i++)
{
eventBus?.NotifyUpdate();
eventBus?.TriggerEvent(BasaltConstants.UpdateEventKey);
}

for (int i = 0; i < renderCalls; i++)
{
eventBus?.NotifyRender();
eventBus?.TriggerEvent(BasaltConstants.RenderEventKey);
}

// Assert
Expand Down Expand Up @@ -204,12 +204,11 @@ public void EngineRemoveEntity_ShouldRemoveAnyReferences()

// Act
Engine.RemoveEntity(entity);
engine.GetEngineComponent<IEventBus>()!.NotifyPhysicsUpdate();
engine.GetEngineComponent<IEventBus>()!.TriggerEvent(BasaltConstants.PhysicsUpdateEventKey);

// Assert
Assert.That(engine.EntityManager.GetEntities().Count, Is.EqualTo(0));
Assert.IsNull(engine.EntityManager.GetEntity("entity1"));
Assert.That(engine.GetEngineComponent<IEventBus>()!.IsSubscribed(entity.Transform), Is.False);
Assert.That(entity.Transform.Position, Is.EqualTo(Vector3.Zero).Using(comparer));
}
}
Expand Down
30 changes: 8 additions & 22 deletions Basalt.Tests/Integration/EntityIntegrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Basalt.Common.Components;
using Basalt.Common.Entities;
using Basalt.Common.Events;
using Basalt.Common.Utils;
using Basalt.Core.Common.Abstractions.Engine;
using Basalt.Tests.Common;
using Moq;
Expand Down Expand Up @@ -38,22 +39,6 @@ public void EntityAddComponent_WhenAddingRigidbody_ShouldUpdateField()
Assert.That(entity.Rigidbody, Is.EqualTo(entity.GetComponent<Rigidbody>()));
}

[Test]
public void EntityRemoveComponent_ShouldRemoveFromEventBus()
{
// Arrange
var entity = new Entity();
entity.AddComponent(new TestComponent(entity));

// Act
Engine.Instance.Initialize();
Engine.CreateEntity(entity);
var component = entity.GetComponent<TestComponent>()!;
entity.RemoveComponent(component);

// Assert
Assert.IsFalse(Engine.Instance.GetEngineComponent<IEventBus>()!.IsSubscribed(component));
}

[Test]
public void EntityRemoveComponent_WhenRemovingRigidbody_ShouldUpdateField()
Expand Down Expand Up @@ -85,9 +70,10 @@ public void EntityDestroy_ShouldUnsubscribeAllComponents()
Engine.CreateEntity(entity);
entity.Destroy();


// Assert
Assert.IsFalse(Engine.Instance.GetEngineComponent<IEventBus>()!.IsSubscribed(entity.GetComponent<TestComponent>()!));
Assert.IsFalse(Engine.Instance.GetEngineComponent<IEventBus>()!.IsSubscribed(entity.GetComponent<Rigidbody>()!));
//Assert.IsFalse(Engine.Instance.GetEngineComponent<IEventBus>()!.IsSubscribed(entity.GetComponent<TestComponent>()!));
//Assert.IsFalse(Engine.Instance.GetEngineComponent<IEventBus>()!.IsSubscribed(entity.GetComponent<Rigidbody>()!));
}

[Test]
Expand Down Expand Up @@ -320,10 +306,10 @@ public void EntityEnabled_WhenDisabled_ShouldNotCallEvents()
Engine.Instance.Initialize();
Engine.CreateEntity(entity);

bus.NotifyStart();
bus.NotifyRender();
bus.NotifyPhysicsUpdate();
bus.NotifyUpdate();
bus.TriggerEvent(BasaltConstants.StartEventKey);
bus.TriggerEvent(BasaltConstants.RenderEventKey);
bus.TriggerEvent(BasaltConstants.PhysicsUpdateEventKey);
bus.TriggerEvent(BasaltConstants.StartEventKey);

// Assert
Assert.That(entity.GetComponent<TestComponent>()!.OnUpdateCount, Is.EqualTo(0), "Update was called");
Expand Down
2 changes: 1 addition & 1 deletion Basalt/Basalt.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Version>1.4.0</Version>
<Version>1.5.0</Version>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<Title>Basalt</Title>
<PackageIcon>BasaltLogoBg.png</PackageIcon>
Expand Down
Loading

0 comments on commit f8f5725

Please sign in to comment.