SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
Application.cpp
Go to the documentation of this file.
2
4#include <Camera/Camera.hpp>
5#include <Core/GameObject.hpp>
7#include <Core/Window.hpp>
13#include <Math/Matrix.hpp>
14#include <Math/Quaternion.hpp>
15#include <Math/Random.hpp>
16#include <Memory/ObjectPtr.hpp>
17#include <Runtime/Material.hpp>
18#include <Runtime/MeshBatch.hpp>
19#include <Runtime/MeshData.hpp>
20#include <Runtime/Skybox.hpp>
21#include <UI/UI.hpp>
23#include <algorithm>
24#include <chrono>
25#include <cstring>
26#include <exception>
27#include <stdexcept>
28
32#include "Core/Logger.hpp"
38
39#define DEFAULT_CAPTURE_FRAME 600
40
41using namespace Sleak;
42using namespace Sleak::Math;
43
44int width = 1200;
45int height = 800;
46
47namespace Sleak {
48 Application* Application::Instance = nullptr;
49
50 Application::Application(const char* Name) :
52 {Name, Arguments(0, nullptr)}
53 )
54 {}
55
56 Application::Application(ApplicationDefaults Settings) : Specification(Settings) {
57 if (Instance) {
58 throw std::runtime_error("The Application is already running!");
59 }
60 Instance = this;
61
62 // Read all settings from CommandLine (parsed in main before Application)
63 {
64 const std::string wStr = CommandLine::GetValue("-w");
65 const std::string hStr = CommandLine::GetValue("-h");
66 if (!wStr.empty()) try { width = std::stoi(wStr); } catch (...) {}
67 if (!hStr.empty()) try { height = std::stoi(hStr); } catch (...) {}
68 }
69
70 {
71 std::string title = CommandLine::GetValue("-t");
72 if (!title.empty()) {
73 std::replace(title.begin(), title.end(), '_', ' ');
74 Specification.Name = title;
75 }
76 }
77
78 CoreWindow = new Window(width, height, Specification.Name);
79
80 try {
81 const std::string rendererArg = CommandLine::GetValue("-r");
82 if (!rendererArg.empty()) {
83 renderer = RenderEngine::RendererFactory::ParseArg(rendererArg, CoreWindow);
84 } else {
85 #ifdef PLATFORM_WIN
88 #else
91 #endif
92 }
93 }
94 catch (std::exception& e) {
95 SLEAK_ERROR(std::string(e.what()));
98 }
99
103
104 }
105
107 // Flush the GPU before tearing down any scene-owned resources (textures,
108 // meshes, materials) — the renderer's descriptor sets still reference
109 // samplers/image views owned by the game's scene objects. Without this
110 // wait, Texture destructors call vkDestroySampler while the descriptor
111 // set binding still has the sampler in use (VUID-vkDestroySampler-sampler-01082).
112 if (renderer) renderer->WaitIdle();
113
114 delete Game;
115 Sleak::UI::ShutdownTextureCache(); // frees cached VkImage/memory pre-device-teardown
117 delete m_benchmark;
118 m_benchmark = nullptr;
119 delete m_DebugOverlay;
120 m_DebugOverlay = nullptr;
121
122 if (renderer)
123 renderer->Cleanup();
124
125 delete renderer;
126 delete CoreWindow;
127 SLEAK_LOG("The application has been successfully closed, have a good day sir");
128 }
129
131 Game = game;
132
133 float lastTime = FrameTimer.Elapsed();
134
135 if(CoreWindow && CoreWindow->InitializeWindow()) {
136
137 if(renderer && renderer->Initialize()) {
138
139 renderer->CreateImGUI();
140 if (renderer->GetImGUIEnabled())
141 CoreWindow->SetImGuiReady(true);
142
143 m_DebugOverlay = new DebugOverlay();
144 m_DebugOverlay->Initialize(renderer, game);
145
146 m_benchmark = new Benchmark();
147 m_benchmark->Initialize(renderer);
148 renderer->RegisterBenchmarkMetrics(*m_benchmark);
149 m_benchmark->RegisterMetric("CPU_frame_ms",
150 [this]() { return m_cpuFrameMs; });
151 {
152 auto& cfg = m_DebugOverlay->GetConfig();
153 cfg.ShowCameraPanel = false;
154 cfg.ShowPerformancePanel = false;
155 }
156
157 auto context = renderer->GetContext();
159
160 float lastTime = FrameTimer.Elapsed();
161 float accumulator = 0.0f;
162 const float fixedTimestep = 1.0f / 60.0f;
163
164 // Frame capture
165 const std::string capturePath = CommandLine::GetValue("-capture");
166 const bool captureMode = !capturePath.empty();
167 uint64_t captureFrame = DEFAULT_CAPTURE_FRAME;
168 const std::string frameArg =
169 CommandLine::GetValue("-capture-frame");
170 if (!frameArg.empty()) {
171 try {
172 captureFrame = std::stoull(frameArg);
173 } catch (...) {
174 }
175 }
176 if (captureMode)
178 "Frame capture: frame {} -> {} (fixed 1/60 s step, "
179 "resizes ignored)",
180 captureFrame, capturePath);
181 uint64_t frameIndex = 0;
182 bool captureArmed = false;
183
184 Debug::ShaderHotReload::AddSourceDirectory(SLEAK_ENGINE_SHADER_DIR);
185
186 // Initialize and begin the game (and scene)
187 if (Game) {
188 if (!Game->Initialize()) {
189 SLEAK_FATAL("Game failed to initialize!");
190 return -1;
191 }
192
193 Game->Begin();
194
195 // Apply CLI graphics settings
196 {
197 if (CommandLine::HasFlag("--vsync")) renderer->SetVSync(true);
198 if (CommandLine::HasFlag("--no-vsync")) renderer->SetVSync(false);
199
200 const std::string msaaStr = CommandLine::GetValue("-msaa");
201 if (!msaaStr.empty()) {
202 try { renderer->SetMSAASampleCount(
203 static_cast<uint32_t>(std::stoi(msaaStr))); }
204 catch (...) {}
205 }
206
207 if (CommandLine::HasFlag("--fullscreen")) CoreWindow->ToggleFullScreen();
208 }
209
210 // Auto-start benchmark if --bench / --benchmark was passed
211 if ((CommandLine::HasFlag("--bench") || CommandLine::HasFlag("--benchmark"))
212 && m_benchmark)
213 m_benchmark->ToggleRecording();
214 }
215
216 while(!CoreWindow->ShouldClose()) {
217
218 float currentTime = FrameTimer.Elapsed();
219 DeltaTime =
220 captureMode ? fixedTimestep : currentTime - lastTime;
221 lastTime = currentTime;
222
223 #if defined(_DEBUG) && defined(COUNT_FRAME)
224 ScopedTimer("Frame Timer");
225 #endif
226
227 CoreWindow->Update();
228
229 // Apply any pending resize (deferred from event handler to avoid GPU hang)
230 if (m_pendingResize && !captureMode) {
231 renderer->Resize(m_pendingResizeW, m_pendingResizeH);
232 width = static_cast<int>(m_pendingResizeW);
233 height = static_cast<int>(m_pendingResizeH);
234 m_pendingResize = false;
235
236 // Update active camera's projection matrix for the new aspect ratio.
237 // Vulkan renderer ignores the width/height args to Resize() and uses
238 // the Vulkan surface caps, so the camera must be notified separately.
239 if (Game && Game->GetActiveScene()) {
240 if (auto* cam = Game->GetActiveScene()->GetActiveCamera())
241 cam->OnResize(m_pendingResizeW, m_pendingResizeH);
242 }
243 }
244
245 if (captureMode && !captureArmed &&
246 frameIndex >= captureFrame) {
247 captureArmed = true;
248 if (!renderer->RequestFrameCapture(capturePath)) {
249 SLEAK_ERROR("Frame capture unavailable on {}",
250 renderer->GetTypeStr());
251 CoreWindow->Close();
252 }
253 }
254
256
257 renderer->BeginRender();
258 const auto cpuFrameStart = std::chrono::steady_clock::now();
259
260 // Update active scene if present
261 if (Game && Game->GetActiveScene()) {
262 auto* activeScene = Game->GetActiveScene();
263
264 // Fixed timestep updates (physics, etc.)
265 accumulator += DeltaTime;
266 while (accumulator >= fixedTimestep) {
267 activeScene->FixedUpdate(fixedTimestep);
268 accumulator -= fixedTimestep;
269 }
270
271 // Per-frame update
272 activeScene->Update(DeltaTime);
273
274 // Late update (after all updates, e.g. camera follow)
275 activeScene->LateUpdate(DeltaTime);
276 }
277
278 // Per-frame game logic
279 if (Game)
280 Game->Loop(DeltaTime);
281 if (m_DebugOverlay)
282 m_DebugOverlay->Render(DeltaTime);
283
284 if (m_benchmark)
285 m_benchmark->Tick(DeltaTime);
286
287 renderer->FlushPendingTransfers();
288
289 if (queue && context)
290 queue->ExecuteCommands(context);
291
292 m_cpuFrameMs =
293 std::chrono::duration<float, std::milli>(
294 std::chrono::steady_clock::now() - cpuFrameStart)
295 .count();
296 renderer->EndRender();
297
298 if (captureArmed && !renderer->IsFrameCapturePending())
299 CoreWindow->Close();
300 ++frameIndex;
301 }
302 }
303 else{
304 SLEAK_FATAL("Unable to initialize graphics!");
305 return -1;
306 }
307
308 }
309 else {
310 SLEAK_FATAL("App cannot run without any window!");
311 return -2;
312 }
313
314 return 0;
315 }
316
318 // Store and defer — applying during event dispatch causes GPU hangs on rapid resize
319 m_pendingResizeW = e.GetWidth();
320 m_pendingResizeH = e.GetHeight();
321 m_pendingResize = true;
322 }
323
325 int w = Window::GetWidth();
326 int h = Window::GetHeight();
327 if (w > 0 && h > 0) {
328 m_pendingResizeW = static_cast<uint32_t>(w);
329 m_pendingResizeH = static_cast<uint32_t>(h);
330 m_pendingResize = true;
331 }
332 }
333
337
340
342
343 switch(e.GetKeyCode())
344 {
346 // Let the game handle ESC (e.g. return to menu)
347 // Only close window if no game is running
348 if (!Game)
349 GetWindow().Close();
350 break;
351
353 break;
354
356 break;
357
359 break;
360
362 {
363 if (Game && Game->GetActiveScene()) {
364 Camera* cam = Game->GetActiveScene()->GetActiveCamera();
365 if (cam) {
366 auto* fpc = cam->GetComponent<FirstPersonController>();
367 if (fpc) {
368 fpc->SetEnabled(!fpc->IsEnabled());
369 } else {
370 auto* ctrl = cam->GetComponent<FreeLookCameraController>();
371 if (ctrl)
372 ctrl->SetEnabled(!ctrl->IsEnabled());
373 }
374 }
375 }
376 }
377 break;
378
380 CoreWindow->ToggleFullScreen();
381 break;
382
384 if (m_benchmark)
385 m_benchmark->ToggleRecording();
386 break;
387
388 }
389
390 }
391
393 return *CoreWindow;
394 }
395
397 CoreWindow->Close();
398 }
399
401 if (renderer) renderer->WaitIdle();
402 }
403
404 void Application::SetCursorVisible(bool visible) {
405 if (visible)
406 SDL_ShowCursor();
407 else
408 SDL_HideCursor();
409 }
410
412 if (CoreWindow)
413 CoreWindow->SetRelativeMouseMode(enabled);
414 }
415
416 int Application::GetFPS() const { return renderer->GetFrameRate(); }
417 float Application::GetFrameTime() const { return renderer->GetFrameTime(); }
418 int Application::GetVertices() const { return renderer->GetVertices(); }
419 int Application::GetTriangles() const { return renderer->GetTriangles(); }
420 size_t Application::GetGPUMemoryUsed() const { return renderer->GetGPUMemoryUsed(); }
421 size_t Application::GetGPUMemoryBudget() const { return renderer->GetGPUMemoryBudget(); }
422 const char* Application::GetRendererTypeStr() const { return renderer->GetTypeStr(); }
423
424 void Application::GetRendererTypeColor(float& r, float& g, float& b) const {
425 switch (renderer->GetType()) {
426 case RenderEngine::RendererType::DirectX12: r = 0.0f; g = 0.5f; b = 1.0f; break;
427 case RenderEngine::RendererType::DirectX11: r = 0.2f; g = 0.6f; b = 0.8f; break;
428 case RenderEngine::RendererType::Vulkan: r = 0.8f; g = 0.2f; b = 0.0f; break;
429 case RenderEngine::RendererType::OpenGL: r = 0.0f; g = 0.8f; b = 0.2f; break;
430 default: r = 0.5f; g = 0.5f; b = 0.5f; break;
431 }
432 }
433
434 uint32_t Application::GetMSAASampleCount() const { return renderer->GetMSAASampleCount(); }
435 uint32_t Application::GetMaxMSAASampleCount() const { return renderer->GetMaxMSAASampleCount(); }
436 void Application::SetMSAASampleCount(uint32_t samples) { renderer->SetMSAASampleCount(samples); }
437
438 bool Application::GetVSync() const { return renderer->GetVSync(); }
439 void Application::SetVSync(bool enabled) { renderer->SetVSync(enabled); }
440
442 return renderer->GetDeferredEnabled();
443 }
445 renderer->SetDeferredEnabled(enable);
446 }
447
448 bool Application::IsSSAOEnabled() const { return renderer->IsSSAOEnabled(); }
449 void Application::SetSSAOEnabled(bool e) { renderer->SetSSAOEnabled(e); }
450 float Application::GetSSAORadius() const { return renderer->GetSSAORadius(); }
451 void Application::SetSSAORadius(float r) { renderer->SetSSAORadius(r); }
452 float Application::GetSSAOBias() const { return renderer->GetSSAOBias(); }
453 void Application::SetSSAOBias(float b) { renderer->SetSSAOBias(b); }
454 float Application::GetSSAOPower() const { return renderer->GetSSAOPower(); }
455 void Application::SetSSAOPower(float p) { renderer->SetSSAOPower(p); }
456
457 bool Application::IsIBLEnabled() const { return renderer->IsIBLEnabled(); }
458 void Application::SetIBLEnabled(bool e) { renderer->SetIBLEnabled(e); }
459 float Application::GetIBLIntensity() const { return renderer->GetIBLIntensity(); }
460 void Application::SetIBLIntensity(float i){ renderer->SetIBLIntensity(i); }
461
462 bool Application::IsSSREnabled() const { return renderer->IsSSREnabled(); }
463 void Application::SetSSREnabled(bool e) { renderer->SetSSREnabled(e); }
464
465 bool Application::IsTAAEnabled() const { return renderer->IsTAAEnabled(); }
466 void Application::SetTAAEnabled(bool e) { renderer->SetTAAEnabled(e); }
467
469 return renderer->GetSharpenStrength();
470 }
472 renderer->SetSharpenStrength(s);
473 }
474
475 bool Application::IsBloomEnabled() const { return renderer->IsBloomEnabled(); }
476 void Application::SetBloomEnabled(bool e) { renderer->SetBloomEnabled(e); }
477
479 m_graphicsConfig = cfg;
480 renderer->SetSSAOEnabled(cfg.ssaoEnabled);
481 renderer->SetSSAORadius(cfg.ssaoRadius);
482 renderer->SetSSAOBias(cfg.ssaoBias);
483 renderer->SetSSAOPower(cfg.ssaoPower);
484 renderer->SetSSREnabled(cfg.ssrEnabled);
485 renderer->SetBloomEnabled(cfg.bloomEnabled);
486 renderer->SetIBLEnabled(cfg.iblEnabled);
487 renderer->SetIBLIntensity(cfg.iblIntensity);
488 renderer->SetTAAEnabled(cfg.taaEnabled);
489 renderer->SetSharpenStrength(cfg.sharpenStrength);
490 renderer->SetShadowMapResolution(cfg.shadowMapResolution);
491 renderer->SetMSAASampleCount(cfg.msaaSamples);
492 renderer->SetTonemappingEnabled(cfg.tonemapEnabled);
493 renderer->SetExposure(cfg.exposure);
494 renderer->SetGamma(cfg.gamma);
495 renderer->SetPCSSEnabled(cfg.pcssEnabled);
496 }
497
499 return m_graphicsConfig;
500 }
501
503 return renderer->GetFeatureCaps();
504 }
505
506}
int width
int height
#define DEFAULT_CAPTURE_FRAME
#define SLEAK_ERROR(...)
Definition Logger.hpp:22
#define SLEAK_FATAL(...)
Definition Logger.hpp:23
#define SLEAK_INFO(...)
Definition Logger.hpp:20
#define SLEAK_LOG(...)
Definition Logger.hpp:19
bool GetVSync() const
Application(const char *ProjectName)
void SetVSync(bool enabled)
void SetDeferredEnabled(bool enabled)
uint32_t GetMSAASampleCount() const
void OnWindowResize(const Sleak::Events::WindowResizeEvent &e)
Stashes the new size; the resize is applied at the start of the next frame.
void SetSSAOPower(float power)
void SetSSREnabled(bool enabled)
int GetFPS() const
Frames rendered in the last second.
void SetBloomEnabled(bool enabled)
float GetSharpenStrength() const
Post-TAA contrast-adaptive sharpening strength, 0 = off, 1 = strongest.
void onMouseClick(const Sleak::Events::Input::MouseButtonPressedEvent &e)
void OnKeyPressed(const Sleak::Events::Input::KeyPressedEvent &e)
Handles engine-level hotkeys (F9 camera toggle, F11 fullscreen, F12 benchmark, Esc).
bool IsBloomEnabled() const
void SetSharpenStrength(float strength)
Sets post-TAA sharpening strength; only applied on frames TAA resolves.
void SetIBLEnabled(bool enabled)
const bool GetIsDeferredEnabled() const
Deferred rendering.
void SetIBLIntensity(float intensity)
const char * GetRendererTypeStr() const
Human-readable name of the active backend (e.g. "Vulkan").
float GetIBLIntensity() const
void OnWindowFullScreen(const Sleak::Events::WindowFullScreen &e)
Treats entering/leaving fullscreen as a resize to the current window size.
int GetVertices() const
Vertices submitted in the last frame.
void SetSSAORadius(float radius)
void SetMSAASampleCount(uint32_t samples)
size_t GetGPUMemoryBudget() const
void onMouseMove(const Sleak::Events::Input::MouseMovedEvent &e)
float GetFrameTime() const
Duration of the last frame, in seconds.
const GraphicsConfig & GetGraphicsConfig() const
Config last passed to ApplyGraphicsConfig().
void GetRendererTypeColor(float &r, float &g, float &b) const
UI accent color associated with the active backend.
bool IsSSAOEnabled() const
void WaitGPUIdle()
Blocks until the GPU finishes all in-flight work. Call before tearing down scene resources.
void ApplyGraphicsConfig(const GraphicsConfig &cfg)
Pushes every field of cfg onto the active renderer in one call.
float GetSSAORadius() const
void SetSSAOBias(float bias)
void SetMouseRelativeMode(bool enabled)
size_t GetGPUMemoryUsed() const
bool IsIBLEnabled() const
int GetTriangles() const
Triangles submitted in the last frame.
bool IsSSREnabled() const
int Run(GameBase *game)
Drives the game loop until the window closes; returns the process exit code.
float GetSSAOPower() const
void SetCursorVisible(bool visible)
uint32_t GetGraphicsCaps() const
float GetSSAOBias() const
uint32_t GetMaxMSAASampleCount() const
bool IsTAAEnabled() const
void SetTAAEnabled(bool enabled)
void SetSSAOEnabled(bool enabled)
Benchmark()=default
static std::string GetValue(const std::string &flag, const std::string &defaultVal="")
Returns the raw string value stored for -flag, or defaultVal if it was not passed.
static bool HasFlag(const std::string &flag)
True if --flag was present on the command line.
DebugOverlay()=default
static void AddSourceDirectory(const std::string &dir)
Watches a shader source folder. Later folders override earlier ones.
static void Poll()
Rebuilds changed shaders. Called once per frame by Application.
static std::string RegisterEventHandler(T *instance, void(T::*memberFunction)(const EventT &))
Registers a member-function handler bound to instance, returning an ID for later unregistration.
Definition Event.hpp:149
std::string ToString() const override
void SetEnabled(bool enabled) override
Toggles relative mouse mode and, when re-enabling, resets velocity and re-syncs yaw/pitch.
T * GetComponent()
Finds the first attached component of type T, or nullptr.
static void Shutdown()
Release static resources before renderer cleanup.
static RenderCommandQueue * GetInstance()
Lazily creates and returns the process-wide singleton instance.
static Renderer * ParseArg(std::string arg, Window *window)
Resolves a CLI backend name (e.g. "-vulkan") to a Renderer instance.
static Renderer * CreateRenderer(RendererType type, Window *window)
Instantiates and returns the Renderer for the given backend, bound to a window.
ScopedTimer(const std::string &name)
static int GetHeight()
Returns the current window height in pixels.
Definition Window.hpp:63
Window()
Constructs a window with the default size and no title.
Definition Window.cpp:44
static int GetWidth()
Returns the current window width in pixels.
Definition Window.hpp:61
void Close()
Marks the window for close; actual teardown happens in the destructor.
Definition Window.cpp:233
Vectors, matrices, quaternions, colors, AABBs, and random helpers.
ENGINE_API void ShutdownTextureCache()
Definition UI.cpp:305
Root namespace for everything the engine exposes.
Definition Camera.hpp:10
Arguments(int argc, char **argv)