Skip to content

Commit

Permalink
refactor: logger, fixed update, small changes
Browse files Browse the repository at this point in the history
  • Loading branch information
cherrynik committed Jul 6, 2024
1 parent e8bea3a commit e459b95
Show file tree
Hide file tree
Showing 8 changed files with 49 additions and 49 deletions.
1 change: 1 addition & 0 deletions src/Apps/GameDesktop/Builders/LoggerBuilder.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Microsoft.Extensions.Configuration;
using Serilog;
using Serilog.Core;
using Serilog.Sinks.SystemConsole.Themes;

namespace GameDesktop.Builders;

Expand Down
47 changes: 23 additions & 24 deletions src/Apps/GameDesktop/Game.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using Myra;
using Serilog;
using Myra.Graphics2D.UI;
using Serilog.Core;

namespace GameDesktop;

Expand All @@ -25,7 +26,6 @@ public class Game : Microsoft.Xna.Framework.Game
{
private const bool IsWindowResizable = true;

private readonly ILogger _logger;
private readonly IServiceContainer _container;

[CanBeNull] private ImGuiRenderer _imGuiRenderer;
Expand All @@ -38,40 +38,38 @@ public class Game : Microsoft.Xna.Framework.Game
// https://gafferongames.com/post/fix_your_timestep/
// https://lajbert.wordpress.com/2021/05/02/fix-your-timestep-in-monogame/
private RootFeature _rootFeature;
private float _fixedDeltaTime;
private float _passedSinceDeltaTime;

public Game(ILogger logger, IServiceContainer container)
public Game(IServiceContainer container)
{
_logger = logger;
_container = container;

_logger.ForContext<Game>().Verbose("ctor");
Log.Logger.ForContext<Game>().Verbose("ctor");
}

protected override void Initialize()
{
_logger.ForContext<Game>().Verbose($"Initialize(): start; available {GraphicsDevice}");
_logger.ForContext<Game>().Verbose("Circular dependencies (external) initialization...");
Log.Logger.ForContext<Game>().Verbose($"Initialize(): start; available {GraphicsDevice}");
Log.Logger.ForContext<Game>().Verbose("Circular dependencies (external) initialization...");
RegisterGraphicsDeviceManager();
RegisterSpriteBatch();
_logger.ForContext<Game>().Verbose("Circular dependencies (external) initialized");
Log.Logger.ForContext<Game>().Verbose("Circular dependencies (external) initialized");
RegisterWindowSettings();

_logger.ForContext<Game>().Verbose("Game services initialization...");
Log.Logger.ForContext<Game>().Verbose("Game services initialization...");
RegisterRootFeature();
_logger.ForContext<Game>().Verbose("Game services initialized");
Log.Logger.ForContext<Game>().Verbose("Game services initialized");

base.Initialize();

_logger.ForContext<Game>().Verbose("Initialize(): end");
Log.Logger.ForContext<Game>().Verbose("Initialize(): end");
}

protected override void LoadContent()
{
// TODO: Logging with game flags (like LOG_MOVEMENT, etc)?
// todo: pass tru logger & log places
// TODO: Error handling
_logger.ForContext<Game>().Verbose("LoadContent(): start");
Log.Logger.ForContext<Game>().Verbose("LoadContent(): start");

// Register UIs before systems onAwake, because we subscribe on systems' events:
// System ctor() -> UI ctor(System) -> System onAwake & event raise -> UI onEvent
Expand All @@ -83,26 +81,26 @@ protected override void LoadContent()

_rootFeature.OnAwake();

_logger.ForContext<Game>().Verbose("LoadContent(): end");
Log.Logger.ForContext<Game>().Verbose("LoadContent(): end");
}


protected override void BeginRun()
{
_logger.ForContext<Game>().Verbose("Beginning to run...");
Log.Logger.ForContext<Game>().Verbose("Beginning to run...");

base.BeginRun();

_logger.ForContext<Game>().Verbose("Running");
Log.Logger.ForContext<Game>().Verbose("Running");
}

protected override void EndRun()
{
_logger.ForContext<Game>().Verbose("Ending run...");
Log.Logger.ForContext<Game>().Verbose("Ending run...");

base.EndRun();

_logger.ForContext<Game>().Verbose("Ended");
Log.Logger.ForContext<Game>().Verbose("Ended");
}

protected override void Update(GameTime gameTime)
Expand All @@ -117,11 +115,12 @@ protected override void Update(GameTime gameTime)

private void FixedUpdate(float deltaTime)
{
_fixedDeltaTime += deltaTime;
while (_fixedDeltaTime >= TargetElapsedTime.TotalSeconds)
// Solution: https://stackoverflow.com/questions/55066052/frame-rate-independent-fixedupdate-vs-update
_passedSinceDeltaTime += deltaTime;
while (_passedSinceDeltaTime >= TargetElapsedTime.TotalSeconds)
{
_rootFeature.OnFixedUpdate(_fixedDeltaTime);
_fixedDeltaTime -= (float)TargetElapsedTime.TotalSeconds;
_rootFeature.OnFixedUpdate((float)TargetElapsedTime.TotalSeconds);
_passedSinceDeltaTime -= (float)TargetElapsedTime.TotalSeconds;
}
}

Expand All @@ -147,11 +146,11 @@ protected override void Draw(GameTime gameTime)

protected override void Dispose(bool disposing)
{
_logger.ForContext<Game>().Verbose("Disposing...");
Log.Logger.ForContext<Game>().Verbose("Disposing...");

base.Dispose(disposing);

_logger.ForContext<Game>().Verbose("Disposed");
Log.Logger.ForContext<Game>().Verbose("Disposed");
}

private void RegisterWindowSettings()
Expand Down
13 changes: 5 additions & 8 deletions src/Apps/GameDesktop/GameCompositionRoot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ namespace GameDesktop;
internal class GameCompositionRoot : ICompositionRoot
{
private const float SecondInMs = 1_000.0f;

private const float TargetFramesPerSecond = 120.0f;
private const float TargetFramesPerSecond = 60.0f; // Mainly used for FixedUpdate
private const bool IsFixedTimeStep = false;
private const bool IsVSyncOn = false;

Expand All @@ -25,14 +24,12 @@ internal class GameCompositionRoot : ICompositionRoot

public void Compose(IServiceRegistry serviceRegistry)
{
ServiceRegistration[] services = serviceRegistry.AvailableServices.ToArray();

var logger =
(ILogger)services.First(r => r.ServiceType == typeof(ILogger)).Value;
var container =
(IServiceContainer)services.First(r => r.ServiceType == typeof(IServiceContainer)).Value;
serviceRegistry
.AvailableServices
.First(r => r.ServiceType == typeof(IServiceContainer)).Value as IServiceContainer;

Game game = new(logger, container)
Game game = new(container)
{
IsMouseVisible = IsMouseVisible,
IsFixedTimeStep = IsFixedTimeStep,
Expand Down
14 changes: 6 additions & 8 deletions src/Apps/GameDesktop/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,20 @@
Directory.GetParent(AppContext.BaseDirectory)!.FullName);

using Logger logger = LoggerBuilder.Create(configuration);
Log.Logger = Logger.None;
// To disable logging, use this instead:
// ILogger logger = Logger.None;
Log.Logger = logger; // To disable logging, use this instead: Logger.None;

logger.ForContext<Program>().Verbose("Configuration & Logger (+ Sentry) initialized");
Log.Logger.ForContext<Program>().Verbose("Configuration & Logger (+ Sentry) initialized");

try
{
// "Using" keyword should be used either with the container, or with the game instance.
// Otherwise, you'll get the double-disposing behaviour.
// "Using" keyword should be used either with the container or with the game instance.
// Otherwise, you'll get the double-disposing behavior.
ServiceContainer container = new(
new ContainerOptions
{
EnablePropertyInjection = false,
EnableCurrentScope = false,
LogFactory = _ => entry => logger
LogFactory = _ => entry => Log.Logger
.ForContext<ServiceContainer>()
.Verbose($"{entry.Message}"),
});
Expand All @@ -51,6 +49,6 @@
if (e.Message.Contains(Errors.FailedToCreateGraphicsDevice)) Environment.Exit(0);
#endif

logger.ForContext<Program>().Fatal(e.ToString());
Log.Logger.ForContext<Program>().Fatal(e.ToString());
Environment.Exit(1);
}
18 changes: 11 additions & 7 deletions src/Libs/CompositionRoots/Entities/PlayerModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,41 @@
using Components.Render;
using Components.Tags;
using Constants;
using Entities.Characters;
using Entities;
using LightInject;
using Microsoft.Xna.Framework;
using MonoGame.Aseprite.Sprites;
using Services.Resolvers;
using Services.Math;
using Vector2 = System.Numerics.Vector2;

namespace CompositionRoots.Entities;

public class PlayerModule : ICompositionRoot
{
private const string AsepriteIdleTag = "Idle";
private const string AsepriteWalkingTag = "Walking";
private static readonly Vector2 DefaultPosition = new(316, 116); // Overwritten by Ldtk at the WorldInitializer
private static readonly Rectangle Collider = new(0, 0, 8, 8);
private const float MovementSpeed = 7.5f; // If 7.5f -> Math.Ceiling fixes this, else Math.Round
private const int InventorySlotsCount = 9;

public void Compose(IServiceRegistry serviceRegistry)
{
serviceRegistry.RegisterSingleton(_ => new InputMovableTagComponent(), DiContainerNames.Player);
serviceRegistry.RegisterSingleton(_ =>
new TransformComponent { Position = new(316, 116), Pivot = Sector.Up }, DiContainerNames.Player);
new TransformComponent { Position = DefaultPosition, Pivot = Sector.Up }, DiContainerNames.Player);
serviceRegistry.RegisterSingleton(_ =>
new TransformComponent { Position = new(0, 3) }, DiContainerNames.PlayerAnimationsOffset);
serviceRegistry.RegisterSingleton(_ =>
new MovableComponent(7f)); // If 7.5f -> Math.Ceiling fixes this, else Math.Round
new MovableComponent(MovementSpeed));
RegisterVisuals(serviceRegistry);
serviceRegistry.RegisterSingleton(_ =>
new RectangleColliderComponent { Size = new(0, 0, 8, 8) }, DiContainerNames.Player);
new RectangleColliderComponent { Size = Collider }, DiContainerNames.Player);
serviceRegistry.RegisterTransient(_ =>
{
const int count = 9;
Slot[] slots = new Slot[count];
Slot[] slots = new Slot[InventorySlotsCount];

// Put items in slots like that:
slots[3].Put(ItemId.Rock, 3);

return new InventoryComponent(slots);
Expand Down
1 change: 0 additions & 1 deletion src/Libs/Entities/EntitiesFactory.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Entities;
using Entities.Characters;
using Entities.Items.Rocks;
using Entities.Items.Trees;
using LDtk;
Expand Down
2 changes: 1 addition & 1 deletion src/Libs/Entities/PlayerFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
using Scellecs.Morpeh;
using Scellecs.Morpeh.Extended.Extensions;

namespace Entities.Characters;
namespace Entities;

public class PlayerFactory(IServiceFactory serviceFactory) : EntityFactory
{
Expand Down
2 changes: 2 additions & 0 deletions src/Libs/Systems/WorldInitializer.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using System.Numerics;
using Components.Data;
using Entities;
using Entities.Items.Trees;
using LDtk;
using LightInject;
using Scellecs.Morpeh;
using Services.Math;

Expand Down

0 comments on commit e459b95

Please sign in to comment.