engine/src/engine.cpp

97 lines
1.9 KiB
C++
Raw Normal View History

2022-09-13 18:25:18 +00:00
#include "engine.hpp"
2022-10-27 16:58:30 +00:00
#include "log.hpp"
2022-10-04 10:54:23 +00:00
#include "window.hpp"
2022-10-27 16:58:30 +00:00
#include "input.hpp"
#include "resource_manager.hpp"
2022-10-27 16:58:30 +00:00
#include "sceneroot.hpp"
#include "gfx_device.hpp"
2022-09-17 00:22:35 +00:00
// To allow the FPS-limiter to put the thread to sleep
#include <thread>
2022-09-13 18:25:18 +00:00
namespace engine {
2022-10-04 10:54:23 +00:00
Application::Application(const char* appName, const char* appVersion)
{
2022-10-31 16:21:07 +00:00
m_win = new Window(appName, true);
2022-10-22 12:15:25 +00:00
2022-10-27 16:58:30 +00:00
gfxdev = new GFXDevice(appName, appVersion, m_win->getHandle());
2022-10-31 16:21:07 +00:00
m_input = new Input(*m_win);
m_res = new ResourceManager();
GameIO things{
m_win,
m_input,
m_res
};
m_scene = new SceneRoot(things);
2022-10-04 10:54:23 +00:00
}
Application::~Application()
{
2022-10-31 16:21:07 +00:00
delete m_scene;
delete m_res;
delete m_input;
2022-10-27 16:58:30 +00:00
delete gfxdev;
2022-10-31 16:21:07 +00:00
delete m_win;
2022-10-04 10:54:23 +00:00
}
void Application::gameLoop()
{
2022-10-22 12:15:25 +00:00
TRACE("Begin game loop...");
2022-10-04 10:54:23 +00:00
uint64_t lastTick = m_win->getNanos();
constexpr int TICKFREQ = 1; // in hz
2022-10-04 10:54:23 +00:00
constexpr int FPS_LIMIT = 240;
constexpr auto FRAMETIME_LIMIT = std::chrono::nanoseconds(1000000000 / FPS_LIMIT);
auto beginFrame = std::chrono::steady_clock::now();
auto endFrame = beginFrame + FRAMETIME_LIMIT;
2022-10-04 10:54:23 +00:00
// single-threaded game loop
while (m_win->isRunning()) {
/* logic */
if (m_win->getLastFrameStamp() >= lastTick + (BILLION / TICKFREQ)) {
lastTick = m_win->getLastFrameStamp();
// do tick stuff here
2022-10-23 11:05:09 +00:00
m_win->setTitle("frame time: " + std::to_string(m_win->dt() * 1000.0f) + " ms, " + std::to_string(m_win->getAvgFPS()) + " fps");
m_win->resetAvgFPS();
2022-10-04 10:54:23 +00:00
}
if (m_win->getKeyPress(inputs::Key::F11)) {
2022-10-06 10:30:44 +00:00
m_win->toggleFullscreen();
2022-10-04 10:54:23 +00:00
}
if (m_win->getKeyPress(inputs::Key::ESCAPE)) {
m_win->setCloseFlag();
}
2022-10-27 16:58:30 +00:00
m_scene->updateStuff();
2022-10-22 12:15:25 +00:00
2022-10-27 16:58:30 +00:00
/* draw */
gfxdev->renderFrame();
2022-10-04 10:54:23 +00:00
/* poll events */
m_win->getInputAndEvents();
/* fps limiter */
std::this_thread::sleep_until(endFrame);
beginFrame = endFrame;
endFrame = beginFrame + FRAMETIME_LIMIT;
2022-10-04 10:54:23 +00:00
}
2022-10-27 16:58:30 +00:00
gfxdev->waitIdle();
2022-11-15 19:53:40 +00:00
2022-09-13 18:25:18 +00:00
}
}