Gondwana Game Engine Development (master) - 2.7.0
Gondwana is a cross-platform 2.5D game and rendering engine written in C#/.NET 8. It provides fine-grained control over rendering, timing, and scene composition, with built-in support for parallax, z-ordering, pixel overhang, collision detection, and particle effects. Gondwana targets desktop and web platforms using SkiaSharp for graphics and pluggable audio backends for desktop and browser targets.
Loading...
Searching...
No Matches
Engine.cs
13using Gondwana.Timers;
14using Microsoft.Extensions.Logging;
16
17namespace Gondwana;
18
35public sealed class Engine : IDisposable
36{
37 #region static members
38
39 private static readonly Lazy<Engine> _instance = new(() => new Engine());
40
49 public static Engine Instance => _instance.Value;
50
59 public static ILogger<Engine> Logger => EngineLogger.GetLogger<Engine>();
60
61 #endregion
62
63 #region private fields
64
65 private long _startTick;
66 private long _lastCPSSamplingTick;
67 private long _lastBackgroundTick = HighResTimer.GetCurrentTick();
68 private long _lastForegroundTick = HighResTimer.GetCurrentTick();
69 private long _lastCycleTick = HighResTimer.GetCurrentTick();
70 private readonly FixedStepAccumulator _timerDrivenSteps = new();
71 private long _timerDrivenForegroundAccumulatedTicks;
72 private long _lastTimerDrivenForegroundDriverTick;
73 private int _timerDrivenForegroundTargetFps;
74 private bool _isTimerDriven;
75
76 private long _grossCyclesThisMeasure = 0;
77 private long _netCyclesThisMeasure = 0;
78 private double _grossCPS = 0;
79 private double _netFPS = 0;
80
81 private Task? _cycleTask;
82 private IEngineConfigurationStore? _configurationStore;
83 private bool _deferredDisposeScheduled;
84
85 #endregion private fields
86
87 #region events
88
103 public event Action? PreInitialization;
104
123 public event Action? PostInitialization;
124
138 public event Action? InitializationComplete;
139
151 public event Action<double>? SimulationUpdating;
152
162 public event Action? BeforeBackgroundTasksExecute;
163
173 public event Action? AfterBackgroundTasksExecute;
174
184 public event Action? BeforeFrameRender;
185
195 public event Action? AfterFrameRender;
196
210 [Obsolete(
211 "Legacy CPS/FPS notifications are deprecated. Use Engine.Profiler for runtime telemetry; ProfilerWidget provides an optional in-game display.",
212 DiagnosticId = "GOND0001")]
213 public event Action<CyclesPerSecondCalculatedEventArgs>? CPSCalculated;
214
223 public event Action? Disposing;
224
233 public event Action? Disposed;
234
235 #endregion events
236
237 private readonly Diagnostics.TelemetrySource _engineTelemetry;
238
241 public Diagnostics.RuntimeProfiler Profiler { get; } = new();
242
243 private Engine()
244 {
245 _engineTelemetry = Profiler.RegisterSource("Engine", "Core")!;
246 _engineTelemetry.Define("cycle.cpu.ms");
247 _engineTelemetry.Define("background.cpu.ms");
248 _engineTelemetry.Define("foreground.cpu.ms");
249 }
250
251 private volatile bool _isInitialized = false;
252 private volatile bool _isInitializing = false;
253 private readonly ManualResetEventSlim _initDone = new(false);
254
310 public void Initialize(
311 string? configFileName = null,
312 bool? autoSaveConfig = null,
313 IKeyboardAdapter? keyboardAdapter = null,
314 IMouseAdapter? mouseAdapter = null,
315 ITouchAdapter? touchAdapter = null,
316 IGamepadManager<IGamepadAdapter>? gamepadManager = null)
317 => InitializeCore(
318 configFileName,
319 autoSaveConfig,
320 keyboardAdapter,
321 mouseAdapter,
322 touchAdapter,
323 gamepadManager,
324 configurationStore: null);
325
338 IEngineConfigurationStore configurationStore,
339 bool? autoSaveConfig = null,
340 IKeyboardAdapter? keyboardAdapter = null,
341 IMouseAdapter? mouseAdapter = null,
342 ITouchAdapter? touchAdapter = null,
343 IGamepadManager<IGamepadAdapter>? gamepadManager = null)
344 {
345 ArgumentNullException.ThrowIfNull(configurationStore);
346
347 InitializeCore(
348 configFileName: null,
349 autoSaveConfig,
350 keyboardAdapter,
351 mouseAdapter,
352 touchAdapter,
353 gamepadManager,
354 configurationStore);
355 }
356
357 private void InitializeCore(
358 string? configFileName,
359 bool? autoSaveConfig,
360 IKeyboardAdapter? keyboardAdapter,
361 IMouseAdapter? mouseAdapter,
362 ITouchAdapter? touchAdapter,
363 IGamepadManager<IGamepadAdapter>? gamepadManager,
364 IEngineConfigurationStore? configurationStore)
365 {
366 if (_isInitialized || _isInitializing)
367 return;
368
369 // reset in case this instance has been initialized before
370 _initDone.Reset();
371
372 _isInitializing = true;
373
374 try
375 {
376 if (UiDispatcher == null)
377 PreInitialization?.Invoke();
378 else
379 UiDispatcher!.Post(() => PreInitialization?.Invoke());
380
381 try
382 {
383 _configurationStore?.Dispose();
384 }
385 catch (Exception ex)
386 {
387 Logger.LogError(ex, "Error saving the engine configuration during initialization.");
388 }
389
390 _configurationStore = configurationStore ?? EngineConfigurationFile.Load(configFileName, autoSaveConfig);
391
392 if (configurationStore is not null && autoSaveConfig.HasValue)
393 _configurationStore.AutoSave = autoSaveConfig.Value;
394
395 Configuration = _configurationStore.Configuration;
396
397 ConfigureLogging(Configuration);
398
399 if (Configuration.StateFiles?.Any() ?? false)
400 {
401 foreach (var stateFile in Configuration.StateFiles)
402 {
403 EngineState.MergeFromFile(
404 stateFile.File,
405 stateFile.IsCompressed,
406 stateFile.OverwriteExisting,
407 stateFile.EngineStateParts);
408 }
409 }
410
411 if (keyboardAdapter != null)
412 KeyboardEventPoller.Initialize(keyboardAdapter);
413
414 if (mouseAdapter != null)
415 MouseEventPoller.Initialize(mouseAdapter);
416
417 if (touchAdapter != null)
418 Input.TouchAdapter = touchAdapter;
419
420 if (gamepadManager is not null)
421 Input.GamepadManager = gamepadManager;
422
423 if (UiDispatcher == null)
424 PostInitialization?.Invoke();
425 else
426 UiDispatcher!.Post(() => PostInitialization?.Invoke());
427
428 EnginePluginRegistry.InvokeInitialize(this);
429
430 _isInitialized = true;
431
432 if (UiDispatcher == null)
433 InitializationComplete?.Invoke();
434 else
435 UiDispatcher!.Post(() => InitializationComplete?.Invoke());
436 }
437 finally
438 {
439 _isInitializing = false;
440 _initDone.Set();
441 }
442 }
443
450 public void SaveConfiguration()
451 {
452 var store = _configurationStore
453 ?? throw new InvalidOperationException("The engine has no initialized configuration store.");
454
455 store.Save();
456 }
457
479 public void Start()
480 {
481 if (SynchronizationContext.Current == null)
482 throw new InvalidOperationException("SynchronizationContext cannot be null.");
483
484 Start(SynchronizationContext.Current);
485 }
486
529 public void Start(SynchronizationContext uiContext)
530 {
531 if (IsRunning)
532 return;
533
534 UiDispatcher = new UiDispatcher(uiContext);
535
536 if (!IsInitialized)
537 {
538 if (IsInitializing)
539 {
540 var initializationWaitTimeoutSeconds = Configuration.StartInitializationWaitTimeout;
541 var initializationWaitTimeout = TimeSpan.FromSeconds(initializationWaitTimeoutSeconds);
542
543 if (!_initDone.Wait(initializationWaitTimeout))
544 throw new InvalidOperationException(
545 $"Engine initialization did not complete within {initializationWaitTimeoutSeconds:0.###} seconds.");
546
547 if (!IsInitialized)
548 throw new InvalidOperationException(
549 "Engine initialization failed on another thread. Call Initialize() again and resolve the initialization error.");
550 }
551 else
552 {
553 Initialize(); // we're the initializer—do it now
554 }
555
556 if (!IsInitialized)
557 throw new InvalidOperationException("Engine failed to initialize.");
558 }
559
560 _isTimerDriven = false;
561 EngineSimulationClock.UseWallClock();
562 IsRunning = true;
563
564 _startTick = HighResTimer.GetCurrentTick();
565 _lastCPSSamplingTick = _startTick;
566 _lastCycleTick = _startTick;
567
568 _cycleTask = Task.Run(() =>
569 {
570 EngineDispatcher.BindToCurrentThread();
571
572 while (Instance.IsRunning)
573 {
574 Instance.Cycle();
575 Thread.Yield(); // optional
576 }
577 });
578 }
579
613 public void StartTimerDriven(SynchronizationContext uiContext)
614 {
615 if (IsRunning)
616 return;
617
618 UiDispatcher = new UiDispatcher(uiContext);
619
620 if (!IsInitialized)
621 {
622 if (IsInitializing)
623 throw new InvalidOperationException(
624 "Engine initialization is already in progress on another thread. " +
625 "Blocking waits are not supported in timer-driven (single-threaded) mode.");
626
627 Initialize();
628 }
629
630 // Bind the dispatcher to the calling (UI) thread — Tick() will be called from here.
631 EngineDispatcher.BindToCurrentThread();
632
633 _startTick = HighResTimer.GetCurrentTick();
634 _lastCPSSamplingTick = _startTick;
635 _lastCycleTick = _startTick;
636 _lastBackgroundTick = _startTick;
637 _lastForegroundTick = _startTick;
638 _timerDrivenSteps.Reset(_startTick);
639 _timerDrivenForegroundAccumulatedTicks = 0;
640 _lastTimerDrivenForegroundDriverTick = _startTick;
641 _timerDrivenForegroundTargetFps = Configuration.TargetFPS;
642 EngineSimulationClock.BeginTimerDriven(_startTick);
643
644 _isTimerDriven = true;
645 IsRunning = true;
646
647 // _cycleTask is intentionally left null; the caller drives the loop via Tick().
648 }
649
669 public void Tick()
670 {
671 if (!IsRunning)
672 return;
673
674 if (!_isTimerDriven)
675 {
676 Cycle();
677 return;
678 }
679
680 lock (RenderStateSynchronization.SyncRoot)
681 {
682 EngineDispatcher.Drain();
683
684 long driverTick = HighResTimer.GetCurrentTick();
685
686 var batch = _timerDrivenSteps.Advance(
687 driverTick,
688 Configuration.TimerDrivenSimulationRate,
689 Configuration.MaxTimerDrivenSimulationSteps);
690
691 bool render = IsTimerDrivenForegroundDue(driverTick);
692 double frameDelta = HighResTimer.GetDuration(_lastForegroundTick, driverTick);
693
694 if (batch.StepCount == 0)
695 {
696 if (render)
697 RenderFrame(driverTick, frameDelta);
698
699 if (Configuration.LegacyCpsSamplingTime > 0)
700 CalculateCPS(driverTick);
701
702 return;
703 }
704
705 double fixedDelta = batch.StepTicks / (double)HighResTimer.TicksPerSecond;
706
707 for (int step = 0; step < batch.StepCount && IsRunning; step++)
708 {
709 long simulationTick = batch.GetStepTick(step);
710 EngineSimulationClock.SetTimerDrivenTick(simulationTick);
711
712 bool isLastStep = step == batch.StepCount - 1;
713
714 RunSimulationCycle(
715 simulationTick,
716 fixedDelta,
717 render && isLastStep,
718 driverTick,
719 frameDelta,
720 sampleCps: isLastStep);
721 }
722 }
723 }
724
751 public void Stop()
752 {
753 if (!IsRunning)
754 return;
755
756 IsRunning = false;
757 _isTimerDriven = false;
758 EngineSimulationClock.UseWallClock();
759 InvokeShutdownAfterCycleStops();
760 }
761
773 public void StopAndWait()
774 {
775 var cycleTask = _cycleTask;
776
777 if (cycleTask is not null && !cycleTask.IsCompleted && EngineDispatcher.IsOnEngineThread)
778 throw new InvalidOperationException("StopAndWait must be called outside the background engine thread.");
779
780 Stop();
781 cycleTask?.GetAwaiter().GetResult();
782 }
783
784 private void InvokeShutdownAfterCycleStops()
785 {
786 var cycleTask = _cycleTask;
787
788 if (cycleTask is not null && !cycleTask.IsCompleted)
789 {
790 cycleTask.ContinueWith(
791 _ => EnginePluginRegistry.InvokeShutdown(this),
792 System.Threading.CancellationToken.None,
793 System.Threading.Tasks.TaskContinuationOptions.ExecuteSynchronously,
794 System.Threading.Tasks.TaskScheduler.Default);
795
796 return;
797 }
798
799 EnginePluginRegistry.InvokeShutdown(this);
800 }
801
802 #region public properties
803
815 public IUiDispatcher? UiDispatcher { get; private set; }
816
827
836 public bool IsInitialized => _isInitialized;
837
846 public bool IsInitializing => _isInitializing;
847
856 public bool IsRunning { get; private set; }
857
866 public long TotalTicksEngineRunning => HighResTimer.GetCurrentTick() - _startTick;
867
876 public double TotalSecondsEngineRunning => TotalTicksEngineRunning / (double)HighResTimer.TicksPerSecond;
877
893 [Obsolete(
894 "Legacy CPS/FPS properties are deprecated. Use Engine.Profiler for runtime telemetry; ProfilerWidget provides an optional in-game display.",
895 DiagnosticId = "GOND0001")]
896 public double CyclesPerSecond => _grossCPS;
897
912 [Obsolete(
913 "Legacy CPS/FPS properties are deprecated. Use Engine.Profiler for runtime telemetry; ProfilerWidget provides an optional in-game display.",
914 DiagnosticId = "GOND0001")]
915 public double FramesPerSecond => _netFPS;
916
932 public EngineState State { get; } = new EngineState();
933
934 private EngineConfiguration? _config = new();
935
952 {
953 get => Volatile.Read(ref _config!);
954 private set => Volatile.Write(ref _config, value);
955 }
956
971 public EngineManagers Managers { get; } = new();
972
992 public EngineInputSystems Input { get; } = new();
993
1002 public bool IsDisposed { get; private set; } = false;
1003
1012 public bool IsDisposing { get; private set; }
1013
1014 #endregion public properties
1015
1016 #region private methods
1017
1018 private void Cycle()
1019 {
1020 // Give a GPU paint callback that is already waiting for live render state
1021 // a chance to acquire the shared gate before this unconstrained loop takes
1022 // another simulation cycle.
1023 RenderStateSynchronization.WaitForPendingGpuRenderers();
1024
1025 lock (RenderStateSynchronization.SyncRoot)
1026 {
1028
1029 long tick = HighResTimer.GetCurrentTick();
1030 var deltaSeconds = HighResTimer.GetDuration(_lastCycleTick, tick);
1031 _lastCycleTick = tick;
1032
1033 RunSimulationCycle(
1034 tick,
1035 deltaSeconds,
1036 IsForegroundDue(tick),
1037 tick,
1038 deltaSeconds,
1039 sampleCps: true);
1040 }
1041 }
1042
1043 private void RunSimulationCycle(
1044 long simulationTick,
1045 double simulationDelta,
1046 bool render,
1047 long renderTick,
1048 double frameDelta,
1049 bool sampleCps)
1050 {
1051 // Refresh native gamepad state before any simulation callbacks consume it.
1052 // Use the real driver/render tick rather than the fixed-step simulation clock so
1053 // timer-driven catch-up steps cannot compress or delay hardware polling cadence.
1054 Input.RefreshGamepads(renderTick, Configuration);
1055
1056 long telemetryGeneration = _engineTelemetry.BeginSample();
1057 long telemetryStarted = telemetryGeneration == 0 ? 0 : HighResTimer.GetCurrentTick();
1058 SimulationUpdating?.Invoke(simulationDelta);
1059 EnginePluginRegistry.InvokePreCycle(this, simulationDelta);
1060
1061 DoBackgroundTasks(simulationTick);
1062
1063 if (render)
1064 RenderFrame(renderTick, frameDelta);
1065
1066 _grossCyclesThisMeasure++;
1067
1068 if (sampleCps && Configuration.LegacyCpsSamplingTime > 0)
1069 CalculateCPS(renderTick);
1070
1071 EnginePluginRegistry.InvokePostCycle(this, simulationDelta);
1072
1073 if (telemetryGeneration != 0)
1074 _engineTelemetry.Record(
1075 telemetryGeneration,
1076 "cycle.cpu.ms",
1077 HighResTimer.GetDuration(telemetryStarted, HighResTimer.GetCurrentTick()) * 1000d);
1078 }
1079
1080 private bool IsForegroundDue(long tick) =>
1081 Configuration.TargetFPS <= 0
1082 || (tick - _lastForegroundTick) >= HighResTimer.TicksPerSecond / Configuration.TargetFPS;
1083
1084 private bool IsTimerDrivenForegroundDue(long tick)
1085 {
1086 int targetFps = Configuration.TargetFPS;
1087 long elapsedTicks = Math.Max(0, tick - _lastTimerDrivenForegroundDriverTick);
1088 _lastTimerDrivenForegroundDriverTick = tick;
1089
1090 if (targetFps <= 0)
1091 {
1092 _timerDrivenForegroundAccumulatedTicks = 0;
1093 _timerDrivenForegroundTargetFps = targetFps;
1094 return true;
1095 }
1096
1097 if (_timerDrivenForegroundTargetFps != targetFps)
1098 {
1099 _timerDrivenForegroundTargetFps = targetFps;
1100 _timerDrivenForegroundAccumulatedTicks = 0;
1101 }
1102
1103 _timerDrivenForegroundAccumulatedTicks += elapsedTicks;
1104
1105 long frameIntervalTicks = Math.Max(1, HighResTimer.TicksPerSecond / targetFps);
1106
1107 if (_timerDrivenForegroundAccumulatedTicks < frameIntervalTicks)
1108 return false;
1109
1110 // Render at most once per externally driven Tick(), but preserve the fractional
1111 // remainder so small requestAnimationFrame timing jitter cannot permanently lower
1112 // the effective render rate. Whole missed intervals are discarded rather than
1113 // causing an unbounded render catch-up sequence after a long browser stall.
1114 _timerDrivenForegroundAccumulatedTicks %= frameIntervalTicks;
1115 return true;
1116 }
1117
1118 private void RenderFrame(long tick, double delta)
1119 {
1120 long telemetryGeneration = _engineTelemetry.BeginSample();
1121 long telemetryStarted = telemetryGeneration == 0 ? 0 : HighResTimer.GetCurrentTick();
1122 EnginePluginRegistry.InvokePreFrameRender(this, delta);
1123
1124 DoForegroundTasks(tick);
1125
1126 EnginePluginRegistry.InvokePostFrameRender(this, delta);
1127
1128 _lastForegroundTick = tick;
1129 _netCyclesThisMeasure++;
1130
1131 if (telemetryGeneration != 0)
1132 _engineTelemetry.Record(
1133 telemetryGeneration,
1134 "foreground.cpu.ms",
1135 HighResTimer.GetDuration(telemetryStarted, HighResTimer.GetCurrentTick()) * 1000d);
1136 }
1137
1138 private void DoBackgroundTasks(long tick)
1139 {
1140 long telemetryGeneration = _engineTelemetry.BeginSample();
1141 long telemetryStarted = telemetryGeneration == 0 ? 0 : HighResTimer.GetCurrentTick();
1142 // find total real seconds passed since last background loop
1143 var deltaSeconds = HighResTimer.GetDuration(_lastBackgroundTick, tick);
1144
1146
1147 // raise pre-cycle timer events
1148 Timer.RaiseTimerEvents(TimerType.PreCycle, tick);
1149
1150 // check for keyboard events
1151 KeyboardEventPoller.Instance?.PollForEvents(tick);
1152
1153 // check for mouse events
1154 MouseEventPoller.Instance?.PollForEvents(tick);
1155
1156 // check for touch events
1157 TouchEventPoller.Instance?.PollForEvents(tick);
1158
1159 // check for gamepad events
1160 GamepadEventPoller.Instance?.PollForEvents(tick);
1161
1162 // cycle Animator frames
1163 for (int i = 0; i < Tile.TilesAnimating.Count; i++)
1164 Tile.TilesAnimating[i].TileAnimator.CycleAnimation(tick);
1165
1166 // advance Sprite Movement paths
1167 SpriteManager.Instance.MoveSprites(tick);
1168
1169 // resolve collisions after movement
1170 foreach (var scene in Scenes.Scene.GetAllScenes())
1171 {
1172 foreach (var layer in scene.SceneLayers)
1173 layer.CollisionResolver.Resolve();
1174 }
1175
1176 // update cameras so any movement can mark RefreshNeeded = All.
1177 foreach (var surface in RenderSurfaceHostRegistry.All)
1178 surface.ViewManager.UpdateCameras(deltaSeconds);
1179
1181
1182 _lastBackgroundTick = tick;
1183
1184 if (telemetryGeneration != 0)
1185 _engineTelemetry.Record(
1186 telemetryGeneration,
1187 "background.cpu.ms",
1188 HighResTimer.GetDuration(telemetryStarted, HighResTimer.GetCurrentTick()) * 1000d);
1189 }
1190
1191 private void DoForegroundTasks(long tick)
1192 {
1193 // raise event
1194 BeforeFrameRender?.Invoke();
1195
1196 // Effects are presentation state, so advance them on the foreground/render cadence.
1197 foreach (var surface in RenderSurfaceHostRegistry.All)
1198 surface.Effects.Update(tick);
1199
1200 // update the DirectDrawing instances' states
1201 DirectDrawingManager.Instance.UpdateAll(tick);
1202
1203 // Resolve desktop GPU visual state at foreground cadence before requesting repaint.
1204 foreach (var surface in RenderSurfaceHostRegistry.All)
1205 surface.ProduceRenderFrameSnapshot(tick);
1206
1207 // Bitmap rendering remains on the engine thread.
1208 foreach (var surface in RenderSurfaceHostRegistry.All)
1209 if (!surface.Backbuffer.IsGlThreadRendered)
1210 surface.RenderToBackbuffer(tick);
1211
1212 // render each Backbuffer to RenderSurfaceHost adapter (skip GL-thread surfaces)
1213 foreach (var surface in RenderSurfaceHostRegistry.All)
1214 if (!surface.Backbuffer.IsGlThreadRendered)
1215 surface.PresentBackbufferToAdapter();
1216
1217 // raise event
1218 // GL thread rendering is done as part of this invocation
1219 AfterFrameRender?.Invoke();
1220
1221 // raise post-cycle timer events
1222 Timer.RaiseTimerEvents(TimerType.PostCycle, tick);
1223 }
1224
1225 private void CalculateCPS(long tick)
1226 {
1227 // Has the sampling interval elapsed?
1228 long elapsedTicks = tick - _lastCPSSamplingTick;
1229
1230 if (elapsedTicks < Configuration.LegacyCpsSamplingTicks)
1231 return;
1232
1233 // SNAPSHOT the counters BEFORE resetting or posting
1234 long grossCycles = _grossCyclesThisMeasure;
1235 long netCycles = _netCyclesThisMeasure;
1236
1237 // Compute using the snapshot
1238 double elapsedSec = elapsedTicks / (double)HighResTimer.TicksPerSecond;
1239 double grossCps = grossCycles * HighResTimer.TicksPerSecond / (double)elapsedTicks;
1240 double netCps = netCycles * HighResTimer.TicksPerSecond / (double)elapsedTicks;
1241
1242 // Collect actual GPU FPS from all registered GPU-rendered backbuffers.
1243 long totalGpuFrames = 0;
1244 int gpuSurfaceCount = 0;
1245
1246 foreach (var surface in RenderSurfaceHostRegistry.All.ToArray())
1247 {
1248 if (surface.Backbuffer is GpuBackbuffer gpuBb)
1249 {
1250 totalGpuFrames += gpuBb.ConsumeFrameCount();
1251 gpuSurfaceCount++;
1252 }
1253 }
1254
1255 double? gpuFps = gpuSurfaceCount > 0
1256 ? totalGpuFrames * HighResTimer.TicksPerSecond / (double)elapsedTicks
1257 : null;
1258
1259 // Build immutable args NOW (so lambda doesn't read changing fields later)
1260 var args = new CyclesPerSecondCalculatedEventArgs(
1261 grossCycles,
1262 netCycles,
1263 grossCps,
1264 netCps,
1265 elapsedSec,
1266 gpuFps
1267 );
1268
1269 // Post the snapshot
1270 UiDispatcher!.Post(() => CPSCalculated?.Invoke(args));
1271
1272 _grossCPS = grossCps;
1273 _netFPS = netCps;
1274
1275 // Reset for next window
1276 _lastCPSSamplingTick = tick;
1277 _grossCyclesThisMeasure = 0;
1278 _netCyclesThisMeasure = 0;
1279 }
1280
1281 private static void ConfigureLogging(EngineConfiguration configuration)
1282 {
1283 // Logging may already be active because hosts can configure it before
1284 // Engine.Initialize. Recreate the async pipeline so its channel uses
1285 // the capacity loaded from this configuration.
1286 EngineLogger.StopAsyncLogging(flush: true);
1287
1288 if (configuration.LoggingMode == EngineLoggingMode.Asynchronous)
1289 {
1290 EngineLogger.SwitchToAsync(configuration.LoggingQueueCapacity);
1291 return;
1292 }
1293
1294 EngineLogger.Mode = EngineLoggingMode.Synchronous;
1295 }
1296
1297 #endregion private methods
1298
1299 #region IDisposable support
1300
1301 private void Dispose(bool disposing)
1302 {
1303 if (!IsDisposed)
1304 {
1305 if (disposing)
1306 {
1307 if (IsDisposing)
1308 return;
1309
1310 IsDisposing = true;
1311
1312 // stop the loop first so handlers don't race the cycle thread
1313 try
1314 {
1315 Stop();
1316 }
1317 catch (Exception ex)
1318 {
1319 Logger.LogError(ex, "Unhandled exception calling Stop()");
1320 }
1321
1322 // wait for the background loop to actually exit unless we're already on it
1323 try
1324 {
1325 var cycleTask = _cycleTask;
1326
1327 if (cycleTask is not null && EngineDispatcher.IsOnEngineThread && !cycleTask.IsCompleted)
1328 {
1329 if (!_deferredDisposeScheduled)
1330 {
1331 _deferredDisposeScheduled = true;
1332
1333 cycleTask.ContinueWith(
1334 _ => CompleteManagedDisposal(),
1335 System.Threading.CancellationToken.None,
1336 System.Threading.Tasks.TaskContinuationOptions.ExecuteSynchronously,
1337 System.Threading.Tasks.TaskScheduler.Default);
1338 }
1339
1340 return;
1341 }
1342
1343 if (cycleTask is not null && !EngineDispatcher.IsOnEngineThread)
1344 cycleTask.Wait();
1345 }
1346 catch (Exception ex)
1347 {
1348 Logger.LogError(ex, "Error waiting for engine loop to exit.");
1349 }
1350
1351 CompleteManagedDisposal();
1352 }
1353 else
1354 {
1355 // unmanaged cleanup...
1356 IsDisposed = true;
1357 }
1358 }
1359 }
1360
1361 private void CompleteManagedDisposal()
1362 {
1363 if (IsDisposed)
1364 return;
1365
1366 // raise Disposing on UI thread if possible; otherwise inline
1367 if (UiDispatcher is not null)
1368 UiDispatcher.Post(() => SafeInvoke(Disposing));
1369 else
1370 SafeInvoke(Disposing);
1371
1372 Profiler.Dispose();
1373
1374 // managed cleanup...
1375 Input.KeyboardEventPoller?.StopMonitoringAllKeys();
1376 MouseEventPoller.Reset();
1377 TouchEventPoller.Reset();
1378
1379 if (Input.GamepadManager is not null)
1380 foreach (var gamepadAdapter in Input.GamepadManager.ConnectedAdapters)
1381 Input.GamepadEventPoller?.StopMonitoringAllButtons(gamepadAdapter.GamepadId);
1382
1383 try
1384 {
1385 _configurationStore?.Dispose();
1386 }
1387 catch (Exception ex)
1388 {
1389 Logger.LogError(ex, "Error saving the engine configuration during disposal.");
1390 }
1391 finally
1392 {
1393 _configurationStore = null;
1394 }
1395
1396 if (EngineLogger.Mode == EngineLoggingMode.Asynchronous)
1397 EngineLogger.StopAsyncLogging(flush: Configuration.FlushAsyncLogsOnShutdown);
1398
1399 Timer.ClearAll();
1400 State.Clear();
1401
1402 // unmanaged cleanup...
1403 IsDisposed = true;
1404
1405 // now signal we're fully torn down
1406 if (UiDispatcher is not null)
1407 UiDispatcher.Post(() => SafeInvoke(Disposed));
1408 else
1409 SafeInvoke(Disposed);
1410 }
1411
1412 private static void SafeInvoke(Action? evnt)
1413 {
1414 try
1415 {
1416 evnt?.Invoke();
1417 }
1418 catch (Exception ex)
1419 {
1420 // Keep disposal robust; log and continue
1421 Logger.LogError(ex, "Unhandled exception in disposal event handler.");
1422 }
1423 }
1424
1447 public void Dispose()
1448 {
1449 Dispose(disposing: true);
1450 GC.SuppressFinalize(this);
1451 }
1452
1453 ~Engine()
1454 {
1455 // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
1456 Dispose(disposing: false);
1457 }
1458
1459 #endregion IDisposable support
1460}
Settings used by the engine when cycling.
int LoggingQueueCapacity
Maximum number of queued log events when LoggingMode is EngineLoggingMode.Asynchronous....
EngineLoggingMode LoggingMode
Controls whether engine logging operations are performed synchronously or asynchronously.
Opt-in, bounded runtime measurements independent of legacy CPS notifications.
Bounded extension source. Define measurements once, capture a generation before work,...
Provides thread-safe dispatching of actions to the engine's background thread. This dispatcher allows...
void Drain()
Executes all queued actions that have been posted to this dispatcher since the last call to Drain....
Provides centralized access to all the input systems of the engine, including gamepad,...
Provides centralized access to all engine resource managers.
Represents the complete serializable state of the game engine, including assets, scenes,...
Represents the core game engine singleton responsible for managing the main update loop,...
Definition Engine.cs:36
void Tick()
Advances the timer-driven engine by one externally presented frame.
Definition Engine.cs:669
Action? Disposed
Raised after the engine has completed explicit disposal.
Definition Engine.cs:233
Action? BeforeFrameRender
Occurs immediately before DoForegroundTasks(long) executes within each engine cycle.
Definition Engine.cs:184
void SaveConfiguration()
Persists the current engine configuration through the store supplied during initialization.
Definition Engine.cs:450
void Initialize(string? configFileName=null, bool? autoSaveConfig=null, IKeyboardAdapter? keyboardAdapter=null, IMouseAdapter? mouseAdapter=null, ITouchAdapter? touchAdapter=null, IGamepadManager< IGamepadAdapter >? gamepadManager=null)
Performs one-time or on-demand initialization of the Engine instance, loading configuration,...
double FramesPerSecond
Gets the current net frames per second rate.
Definition Engine.cs:915
static Engine Instance
Gets the singleton instance of the Engine.
Definition Engine.cs:49
bool IsInitialized
Gets a value indicating whether the engine has completed its initialization sequence.
Definition Engine.cs:836
void Start(SynchronizationContext uiContext)
Starts the Engine main loop using the provided SynchronizationContext, initializing the engine if it ...
Definition Engine.cs:529
long TotalTicksEngineRunning
Gets the total number of high-resolution timer ticks that have elapsed since the engine started.
Definition Engine.cs:866
void InitializeWithConfigurationStore(IEngineConfigurationStore configurationStore, bool? autoSaveConfig=null, IKeyboardAdapter? keyboardAdapter=null, IMouseAdapter? mouseAdapter=null, ITouchAdapter? touchAdapter=null, IGamepadManager< IGamepadAdapter >? gamepadManager=null)
Initializes the engine using a caller-supplied configuration persistence store.
Definition Engine.cs:337
EngineState State
Gets the engine's persistent state container for storing arbitrary key-value data.
Definition Engine.cs:932
Action? AfterFrameRender
Occurs immediately after DoForegroundTasks(long) completes within each engine cycle.
Definition Engine.cs:195
Action? PostInitialization
Occurs after all internal initialization routines have completed, but before InitializationComplete i...
Definition Engine.cs:123
void StartTimerDriven(SynchronizationContext uiContext)
Starts the Engine in timer-driven mode using the provided SynchronizationContext, without spawning a ...
Definition Engine.cs:613
Diagnostics.RuntimeProfiler Profiler
Opt-in runtime CPU measurements and bounded history, independent of CPS notifications.
Definition Engine.cs:241
Action< CyclesPerSecondCalculatedEventArgs >? CPSCalculated
Occurs whenever cycles-per-second (CPS) and frames-per-second (FPS) metrics are calculated.
Definition Engine.cs:213
static ILogger< Engine > Logger
Gets the logger instance used by the engine for diagnostic and informational messages.
Definition Engine.cs:59
void StopAndWait()
Stops the engine and waits for its background cycle to finish before returning. Resources used by ren...
Definition Engine.cs:773
IEngineDispatcher EngineDispatcher
Gets the engine dispatcher used for marshalling operations to the engine's background thread.
Definition Engine.cs:826
void Dispose()
Releases all resources used by the Engine and stops all subsystems.
Definition Engine.cs:1447
Action? InitializationComplete
Occurs after all initialization steps and post-initialization logic have completed.
Definition Engine.cs:138
bool IsRunning
Gets a value indicating whether the engine's main loop is currently executing.
Definition Engine.cs:856
EngineInputSystems Input
Gets the collection of input subsystems for keyboard, mouse, touch, and gamepad input.
Definition Engine.cs:992
Action? AfterBackgroundTasksExecute
Occurs immediately after DoBackgroundTasks(long) has completed.
Definition Engine.cs:173
double CyclesPerSecond
Gets the current gross cycles per second rate.
Definition Engine.cs:896
EngineManagers Managers
Gets the collection of resource managers for audio, SVG, sprites, fonts, tilesheets,...
Definition Engine.cs:971
Action< double >? SimulationUpdating
Occurs once at the start of each simulation cycle, after scheduled gamepad hardware polling and befor...
Definition Engine.cs:151
bool IsDisposed
Gets a value indicating whether the engine has been disposed.
Definition Engine.cs:1002
Action? PreInitialization
Occurs immediately before the engine begins its internal initialization sequence.
Definition Engine.cs:103
IUiDispatcher? UiDispatcher
Gets the UI dispatcher used for marshalling operations to the UI thread.
Definition Engine.cs:815
Action? Disposing
Raised when Dispose() begins the explicit disposal sequence.
Definition Engine.cs:223
Action? BeforeBackgroundTasksExecute
Occurs immediately before DoBackgroundTasks(long) executes within each engine cycle.
Definition Engine.cs:162
void Stop()
Stops the Engine main loop and halts all ongoing processing.
Definition Engine.cs:751
bool IsInitializing
Gets a value indicating whether the engine is currently in the process of initializing.
Definition Engine.cs:846
EngineConfiguration Configuration
Gets the current engine configuration settings.
Definition Engine.cs:952
bool IsDisposing
Gets a value indicating whether the engine is currently executing its disposal sequence.
Definition Engine.cs:1012
void Start()
Starts the Engine using the current thread's SynchronizationContext.
Definition Engine.cs:479
double TotalSecondsEngineRunning
Gets the total number of seconds that have elapsed since the engine started.
Definition Engine.cs:876
Represents a high-resolution timer that can trigger events at specified intervals and supports variou...
Definition Timer.cs:16
static void ClearAll()
Removes and disposes all active timers, clearing the entire timer collection.
Definition Timer.cs:231
Provides a concrete implementation of IUiDispatcher for dispatching actions to the UI thread using a ...
void Post(Action action)
Asynchronously posts an action to be executed on the UI thread. This method queues the action and ret...
Provides a persistence boundary for EngineConfiguration.
Defines a contract for dispatching actions to the engine's background thread in a thread-safe manner....
Defines a contract for dispatching actions to the UI thread in a thread-safe manner....
Represents an adapter for keyboard input, providing access to the currently pressed keys and active m...
Defines an adapter interface for accessing mouse device state, including cursor position,...
Defines a passive adapter interface for accessing touch device state. Implementations update their in...
EngineLoggingMode
Specifies the logging mode for the engine.
TimerType
Specifies when a Timer should have its Timer.Tick event raised relative to the engine's main update a...
Definition TimerType.cs:22
@ Scenes
Represents the scenes state, including scene definitions, layer configurations, entity placements,...