using System;
using System.Collections.Generic;
using DefaultEcs;
using MagicThing.ECS.Core;
using MagicThing.ECS.Core.Camera;
using MagicThing.ECS.Core.Debug;
using MagicThing.ECS.Core.Events;
using MagicThing.ECS.Core.Parenting;
using MagicThing.ECS.Core.Physics;
using MagicThing.ECS.Core.Positioning;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using nkast.Aether.Physics2D.Controllers;
using ImGuiNET;
using MagicThing.ECS.Core.CoreSystems.EntitySystem;
using MagicThing.ECS.Core.CoreSystems.PrototypeComponentSystem;
using MagicThing.ECS.Core.Debug.Commands;
using MagicThing.ECS.Core.Debug.UI;
using MagicThing.ECS.Core.Input;
using MagicThing.ECS.Core.Physics.Behavior;
using MagicThing.ECS.Core.Physics.Bridge;
using MagicThing.ECS.Core.Session;
namespace MagicThing;
public class Game1 : Game
{
private GraphicsDeviceManager _graphics;
private SpriteBatch _spriteBatch;
private nkast.Aether.Physics2D.Dynamics.World _physicsWorld;
private VelocityLimitController _pvlc;
private Random _random;
code
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
private RenderTarget2D _renderTarget;
private const int VirtualWidth = 640;
private const int VirtualHeight = 360;
private const int PADDING = 2;
private Rectangle _destinationRectangle;
// --- ECS Fields ---
private World _world;
private SystemManager _systemManager;
private PrototypeManager _prototypeManager;
private EventManager _eventManager;
private bool _debugRender;
private int _debugRenderCooldown;
// Physics
private PhysicsBodyCreationSystem _bodyCreationSystem;
private PrePhysicsSyncSystem _prePhysicsSyncSystem;
private PostPhysicsSyncSystem _postPhysicsSyncSystem;
private nkast.Aether.Physics2D.Diagnostics.DebugView _debugView;
private PhysicsBodyDeletionSystem _bodyDeletionSystem;
// --- Fixed Update Loop Fields ---
private const float FixedTimeStep = 1f / 60f;
private float _timeAccumulator = 0f;
// --- Camera ---
private CameraSystem _cameraSystem;
private float _scale;
// --- ImGui Fields ---
private ImGuiRenderer _imGuiRenderer;
private bool _debugActive = false;
private SceneGraphPanel _scene;
private readonly ComponentViewerPanel _componentViewer = new();
private class InspectorWindowState
{
public Entity TargetEntity;
public bool IsOpen = true;
}
private readonly List<InspectorWindowState> _inspectorWindows = new();
private CommandManager _commandManager;
private DebugConsoleWindow _consoleWindow;
private ConsoleInterceptor _consoleInterceptor;
private bool _consoleActive = false;
// Crash inspector
private CrashInspectorPanel _crashInspectorPanel;
public Game1()
{
_graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IsMouseVisible = true;
}
protected override void Initialize()
{
_consoleInterceptor = new ConsoleInterceptor(Console.Out);
Console.SetOut(_consoleInterceptor);
Console.WriteLine("[Console] Output redirected to debug window.");
_world = new World();
_random = new Random();
_eventManager = new EventManager();
_prototypeManager = new PrototypeManager(_world, Content);
_cameraSystem = new CameraSystem();
_physicsWorld = new nkast.Aether.Physics2D.Dynamics.World(new Vector2(0, 0));
_pvlc = new VelocityLimitController(float.MaxValue, float.MaxValue);
_systemManager = new SystemManager(_world, _eventManager, _random, _prototypeManager, _cameraSystem, _physicsWorld);
_systemManager.Initialize();
_commandManager = new CommandManager(_systemManager, _world, _eventManager, _prototypeManager, _random, _cameraSystem, _physicsWorld);
_commandManager.Initialize();
_consoleWindow = new DebugConsoleWindow(_commandManager, _consoleInterceptor);
_debugView = new nkast.Aether.Physics2D.Diagnostics.DebugView(_physicsWorld);
_debugView.LoadContent(GraphicsDevice, Content);
_bodyDeletionSystem = new PhysicsBodyDeletionSystem(_world, _physicsWorld);
_bodyCreationSystem = new PhysicsBodyCreationSystem(_world, _physicsWorld, _pvlc);
_prePhysicsSyncSystem = new PrePhysicsSyncSystem(_world);
_postPhysicsSyncSystem = new PostPhysicsSyncSystem(_world, _physicsWorld, _eventManager);
_debugRender = false;
_debugRenderCooldown = 10;
_imGuiRenderer = new ImGuiRenderer(this);
_imGuiRenderer.RebuildFontAtlas();
_scene = new SceneGraphPanel(_world);
_crashInspectorPanel = new CrashInspectorPanel(this);
// --- BORDERLESS FULLSCREEN SETUP ---
_graphics.PreferredBackBufferWidth = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
_graphics.PreferredBackBufferHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;
_graphics.HardwareModeSwitch = false; // Important for fast switching
_graphics.IsFullScreen = true;
Window.IsBorderless = true;
_graphics.SynchronizeWithVerticalRetrace = true;
_graphics.ApplyChanges();
// --- RENDER TARGET SETUP ---
// Create the RenderTarget2D with our virtual resolution
_renderTarget = new RenderTarget2D(
GraphicsDevice,
VirtualWidth + PADDING * 2,
VirtualHeight + PADDING * 2);
_scale = (float)GraphicsDevice.Viewport.Width / VirtualWidth;
base.Initialize();
}
protected override void LoadContent()
{
_spriteBatch = new SpriteBatch(GraphicsDevice);
_prototypeManager.Initialize(); // This loads all YAML files
_prototypeManager.SpawnEntity("PlayerDrone", new Vector2(0, 0));
_prototypeManager.SpawnEntity("MasslessAttachmentDrone", new Vector2(150, 150));
_prototypeManager.SpawnEntity("DroneGrid", new Vector2(300, 300));
}
protected override void Update(GameTime gameTime)
{
try
{
#region Update loop
if (_crashInspectorPanel.IsActive)
{
base.Update(gameTime);
return;
}
// ========= Debug stuff start
if (Keyboard.GetState().IsKeyDown(Keys.F1) && _debugRenderCooldown <= 0)
{
_debugRender = !_debugRender;
_debugActive = true;
_debugRenderCooldown = 20;
}
if (Keyboard.GetState().IsKeyDown(Keys.F2) && _debugRenderCooldown <= 0)
{
_consoleActive = !_consoleActive;
_debugActive = true;
_debugRenderCooldown = 20;
}
_debugRenderCooldown--;
// ========= Debug stuff end
var deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
var preLoopTiming = new Timing(deltaTime, 0f);
_systemManager.RunFrameStart(preLoopTiming);
_systemManager.RunTransientUpdate(preLoopTiming);
// TODO: this is absolute fucking shitcode, refactor this
if (_systemManager.GetSystem<SessionManager>().IsPaused)
{
_systemManager.RunPausedUpdate(preLoopTiming);
}
else
{
_timeAccumulator += deltaTime * _systemManager.GetSystem<SessionManager>().GameSpeed;
var fixedTiming = new Timing(FixedTimeStep, 1.0f);
while (_timeAccumulator >= FixedTimeStep)
{
_systemManager.RunFixedUpdatePrePhysics(fixedTiming);
// Engine housekeeping
_systemManager.GetSystem<ProcessPositionRequestSystem>().ManualUpdate();
// Physics bridge and the system itself ---
_bodyCreationSystem.Update(FixedTimeStep);
_prePhysicsSyncSystem.Update(FixedTimeStep);
_physicsWorld.Step(FixedTimeStep);
_physicsWorld.ClearForces();
_postPhysicsSyncSystem.Update(FixedTimeStep);
_bodyDeletionSystem.Update(FixedTimeStep);
// WeldManagerSystem also runs in cleanup but let's run it here to ensure consistent state
_systemManager.GetSystem<WeldManagerSystem>().Update(fixedTiming);
// ----------------------------------------
_systemManager.RunFixedUpdatePostPhysics(fixedTiming);
_timeAccumulator -= FixedTimeStep;
}
var alpha = (float)(_timeAccumulator / FixedTimeStep);
var postLoopTiming = new Timing(deltaTime, alpha);
_systemManager.RunFrameLateUpdate(postLoopTiming);
// (Cleanup, Last)
_systemManager.RunFrameEnd(postLoopTiming);
}
// We can imagine Draw() being ran here.
#endregion
}
catch (Exception e)
{
if (!_crashInspectorPanel.IsActive)
{
Console.WriteLine(e);
EnterCrashInspector(e);
}
else
{
// The inspector's update code crashed. Let it terminate.
throw;
}
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
try
{
#region GAME draw loop
if (!_crashInspectorPanel.IsActive)
{
GraphicsDevice.SetRenderTarget(_renderTarget);
GraphicsDevice.Clear(Color.CornflowerBlue);
var deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
// camera stuff todo refactor
Vector2 cameraIntPosition = new Vector2((int)Math.Round(_cameraSystem.Position.X), (int)Math.Round(_cameraSystem.Position.Y));
Matrix transform = Matrix.CreateTranslation(-cameraIntPosition.X, -cameraIntPosition.Y, 0) *
Matrix.CreateTranslation(VirtualWidth / 2f + PADDING, VirtualHeight / 2f + PADDING, 0);
_spriteBatch.Begin(samplerState: SamplerState.PointClamp, transformMatrix: transform);
_systemManager.RunDraw(deltaTime, _spriteBatch);
_spriteBatch.End();
if (_debugRender)
{
Matrix projection = Matrix.CreateOrthographicOffCenter(
0,
_renderTarget.Width,
_renderTarget.Height,
0,
0,
1);
Matrix view = Matrix.CreateScale(PhysicsConstants.PixelsPerMeter) * transform;
_debugView.RenderDebugData(ref projection, ref view);
}
}
GraphicsDevice.SetRenderTarget(null);
GraphicsDevice.Clear(Color.Black);
// no clue what I'm doing
// but we are trying to upscale with subpixel movement smoothing
// the camera is only offset by integer values, but we move the final rendered image
// by the remainder of the floats.
float screenWidth = GraphicsDevice.Viewport.Width;
float screenHeight = GraphicsDevice.Viewport.Height;
float scaleX = screenWidth / VirtualWidth;
float scaleY = screenHeight / VirtualHeight;
float scale = Math.Min(scaleX, scaleY);
int scaledWidth = (int)(VirtualWidth * scale);
int scaledHeight = (int)(VirtualHeight * scale);
int posX = (int)((screenWidth - scaledWidth) / 2);
int posY = (int)((screenHeight - scaledHeight) / 2);
Vector2 subPixel = new Vector2((int)Math.Round(_cameraSystem.Position.X), (int)Math.Round(_cameraSystem.Position.Y)) - _cameraSystem.Position;
posX += (int)(subPixel.X * scale);
posY += (int)(subPixel.Y * scale);
Rectangle finalDestination = new Rectangle(posX, posY, scaledWidth, scaledHeight);
_spriteBatch.Begin(samplerState: SamplerState.PointClamp);
_spriteBatch.Draw(_renderTarget, finalDestination, new Rectangle(PADDING, PADDING, VirtualWidth, VirtualHeight), Color.White);
_spriteBatch.End();
#endregion
#region DEBUG render loop
if (_debugActive)
{
_imGuiRenderer.BeforeLayout(gameTime);
try
{
var inputManager = _systemManager.GetSystem<InputManagerSystem>();
var io = ImGui.GetIO();
inputManager.IsInputDisabled = _crashInspectorPanel.IsActive || io.WantCaptureKeyboard;
ImGui.GetForegroundDrawList().AddCircleFilled(io.MousePos, 5.0f, 0xFF0000FF);
_scene.Draw(ref _debugActive);
if (_scene.EntityToInspect.HasValue)
{
_inspectorWindows.Add(new InspectorWindowState
{
TargetEntity = _scene.EntityToInspect.Value
});
}
foreach (var windowState in _inspectorWindows)
{
_componentViewer.Draw(
windowState.TargetEntity,
ref windowState.IsOpen,
windowState.GetHashCode()
);
}
_inspectorWindows.RemoveAll(window => !window.IsOpen);
_consoleWindow.Draw(ref _consoleActive);
_crashInspectorPanel.Draw(gameTime);
}
finally
{
_imGuiRenderer.AfterLayout();
}
}
#endregion
}
catch (Exception e)
{
if (!_crashInspectorPanel.IsActive)
{
Console.WriteLine(e);
EnterCrashInspector(e);
}
else
{
// The inspector's drawing code crashed. Let it terminate.
throw;
}
}
base.Draw(gameTime);
}
protected override void UnloadContent()
{
// ...
_world?.Dispose();
base.UnloadContent();
}
public void EnterCrashInspector(Exception e)
{
Console.WriteLine("==== BEGIN FATAL CRASH ====");
_crashInspectorPanel.Activate(e);
_debugActive = true;
Console.WriteLine("Entering crash inspector.");
}
}
Don't generate code, just let's talk about how to refactor my game engine's (built on monogame + defaultecs) Game1.cs to avoid huge spaghetti files and to make it easy for developers using the engine to extend it.
Looking at your Game1.cs, it's a classic monolithic game class that's doing way too much. Here's how I'd approach refactoring it for better extensibility and maintainability:
Core Issues to Address
Too Many Responsibilities - Your Game1 handles rendering, physics, ECS management, debug UI, input, and crash handling all in one place
Hard-coded System Initialization - Systems are manually instantiated and configured
Tight Coupling - Everything knows about everything else
No Extension Points - Developers can't easily add features without modifying Game1
Suggested Architecture
1. Service Container Pattern
Create a central service container that manages all your core services:
The key is making Game1 (or GameEngine) just a thin coordinator that delegates to services, rather than the monolith it is now. This way developers can:
Replace any service with their own implementation
Add new systems without touching core code
Enable/disable features through configuration
Test components in isolation
Would you like me to elaborate on any of these patterns or discuss specific implementation strategies for your use case?