MoonWorks/src/Game.cs

117 lines
3.2 KiB
C#
Raw Normal View History

2021-01-20 03:34:26 +00:00
using System.Collections.Generic;
using SDL2;
2021-01-20 02:06:10 +00:00
using MoonWorks.Audio;
2021-01-20 03:34:26 +00:00
using MoonWorks.Graphics;
2021-01-19 07:29:07 +00:00
namespace MoonWorks
{
public abstract class Game
{
private bool quit = false;
private double timestep;
ulong currentTime = SDL.SDL_GetPerformanceCounter();
double accumulator = 0;
2021-01-19 19:24:23 +00:00
bool debugMode;
2021-01-19 07:29:07 +00:00
2021-01-19 19:24:23 +00:00
public Window Window { get; }
2021-01-19 07:29:07 +00:00
public GraphicsDevice GraphicsDevice { get; }
2021-01-20 02:06:10 +00:00
public AudioDevice AudioDevice { get; }
2021-01-19 07:29:07 +00:00
public Input Input { get; }
private Dictionary<PresentMode, RefreshCS.Refresh.PresentMode> moonWorksToRefreshPresentMode = new Dictionary<PresentMode, RefreshCS.Refresh.PresentMode>
{
{ PresentMode.Immediate, RefreshCS.Refresh.PresentMode.Immediate },
{ PresentMode.Mailbox, RefreshCS.Refresh.PresentMode.Mailbox },
{ PresentMode.FIFO, RefreshCS.Refresh.PresentMode.FIFO },
{ PresentMode.FIFORelaxed, RefreshCS.Refresh.PresentMode.FIFORelaxed }
};
2021-01-19 19:24:23 +00:00
public Game(
WindowCreateInfo windowCreateInfo,
PresentMode presentMode,
int targetTimestep = 60,
bool debugMode = false
) {
2021-01-19 07:29:07 +00:00
timestep = 1.0 / targetTimestep;
if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO | SDL.SDL_INIT_TIMER | SDL.SDL_INIT_GAMECONTROLLER) < 0)
{
System.Console.WriteLine("Failed to initialize SDL!");
return;
}
2021-01-20 02:06:10 +00:00
Logger.Initialize();
2021-01-19 19:24:23 +00:00
Input = new Input();
2021-01-19 07:29:07 +00:00
2021-01-19 19:24:23 +00:00
Window = new Window(windowCreateInfo);
2021-01-19 07:29:07 +00:00
2021-01-19 19:24:23 +00:00
GraphicsDevice = new GraphicsDevice(
Window.Handle,
moonWorksToRefreshPresentMode[presentMode],
debugMode
);
2021-01-20 02:06:10 +00:00
AudioDevice = new AudioDevice();
2021-01-19 19:24:23 +00:00
this.debugMode = debugMode;
2021-01-19 07:29:07 +00:00
}
public void Run()
{
while (!quit)
{
var newTime = SDL.SDL_GetPerformanceCounter();
double frameTime = (newTime - currentTime) / (double)SDL.SDL_GetPerformanceFrequency();
if (frameTime > 0.25)
{
frameTime = 0.25;
}
currentTime = newTime;
accumulator += frameTime;
bool updateThisLoop = (accumulator >= timestep);
if (!quit)
{
while (accumulator >= timestep)
{
2021-01-20 04:23:09 +00:00
HandleSDLEvents();
2021-01-19 07:29:07 +00:00
Input.Update();
Update(timestep);
accumulator -= timestep;
}
if (updateThisLoop)
{
Draw();
}
}
}
}
2021-01-20 04:23:09 +00:00
private void HandleSDLEvents()
{
while (SDL.SDL_PollEvent(out var _event) == 1)
{
switch (_event.type)
{
case SDL.SDL_EventType.SDL_QUIT:
quit = true;
break;
}
}
}
2021-01-19 07:29:07 +00:00
protected abstract void Update(double dt);
protected abstract void Draw();
}
}