SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
OpenGLRenderer.cpp
Go to the documentation of this file.
2
3#include <SDL3/SDL.h>
4
5#include <Camera/Camera.hpp>
7#include <Core/GameBase.hpp>
8#include <Core/SceneBase.hpp>
10#include <Runtime/MeshData.hpp>
11#include <Runtime/Skybox.hpp>
13#include <algorithm>
14#include <cstdint>
15#include <cstring>
16#include <vector>
17
27
28namespace Sleak {
29namespace RenderEngine {
30
31namespace {
32
33constexpr GLuint VERTEX_BUFFER_BINDING = 0;
34constexpr uint32_t DEFAULT_VERTEX_LAYOUT = 0;
35constexpr uint32_t ATTRIB_MASK_BITS = 32;
36
37// Default Vertex attribute locations
38constexpr GLuint ATTRIB_POSITION = 0;
39constexpr GLuint ATTRIB_NORMAL = 1;
40constexpr GLuint ATTRIB_TANGENT = 2;
41constexpr GLuint ATTRIB_COLOR = 3;
42constexpr GLuint ATTRIB_UV = 4;
43constexpr GLuint ATTRIB_BONE_IDS = 5;
44constexpr GLuint ATTRIB_BONE_WEIGHTS = 6;
45
46// Transform CB layout read by the shadow pass: [WVP][World]
47constexpr int MAT4_DIM = 4;
48constexpr size_t MAT4_FLOATS = MAT4_DIM * MAT4_DIM;
49constexpr size_t MAT4_BYTES = MAT4_FLOATS * sizeof(float);
50constexpr size_t TRANSFORM_CB_BYTES = 2 * MAT4_BYTES;
51
52/// Sets one attribute's format on vao and routes it to the shared binding.
53void SetAttribFormat(GLuint vao, GLuint location, GLint components, GLenum type,
54 bool integer, size_t offset) {
55 const GLuint relativeOffset = static_cast<GLuint>(offset);
56 if (integer)
57 glVertexArrayAttribIFormat(vao, location, components, type,
58 relativeOffset);
59 else
60 glVertexArrayAttribFormat(vao, location, components, type, GL_FALSE,
61 relativeOffset);
62 glVertexArrayAttribBinding(vao, location, VERTEX_BUFFER_BINDING);
63}
64
65} // namespace
66
67/// Registers this backend's buffer/shader/texture factories with ResourceManager.
90
94
96 if (m_Initialized) {
97 return true;
98 }
99
100 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
101 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
102 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,
103 SDL_GL_CONTEXT_PROFILE_CORE);
104 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
105 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
106
107 m_GLContext = SDL_GL_CreateContext(m_Window->GetSDLWindow());
108 if (!m_GLContext) {
109 SDL_Log("Failed to create OpenGL context: %s", SDL_GetError());
110 return false;
111 }
112
113 if (!gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress)) {
114 SDL_Log("Failed to initialize Glad (OpenGL loader)");
115 return false;
116 }
117
118 int width, height;
119 SDL_GetWindowSize(m_Window->GetSDLWindow(), &width, &height);
120 ApplyViewport(0, 0, width, height);
121
122 glEnable(GL_DEPTH_TEST);
123 glEnable(GL_BLEND);
124 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
125
126 // Apply initial VSync setting
127 SDL_GL_SetSwapInterval(m_vsync ? 1 : 0);
128
129 // Query max MSAA samples
130 GLint maxSamples = 1;
131 glGetIntegerv(GL_MAX_SAMPLES, &maxSamples);
133 if (maxSamples >= 8) m_maxMsaaSampleCount = 8;
134 else if (maxSamples >= 4) m_maxMsaaSampleCount = 4;
135 else if (maxSamples >= 2) m_maxMsaaSampleCount = 2;
136 SLEAK_INFO("OpenGL max MSAA samples: {}", m_maxMsaaSampleCount);
137
138 SetupVertexLayout();
139
140 m_Initialized = true;
142
143 // Create GBuffer resources (deferred rendering)
144 if (m_deferredEnabled) {
145 CreateGBufferResources();
146 }
147
148 SLEAK_INFO("OpenGL renderer has been initialized successfully!");
149 SLEAK_INFO("OpenGL Version: {}",
150 (const char*)glGetString(GL_VERSION));
151
152 return true;
153}
154
155void OpenGLRenderer::SetupVertexLayout() {
156 glCreateVertexArrays(1, &m_VAO);
157 m_configuredLayout = NO_CONFIGURED_LAYOUT;
158 m_configuredLayoutDesc = nullptr;
159 m_enabledAttribMask = 0;
160}
161
162void OpenGLRenderer::ConfigureVertexLayout(uint32_t layout,
163 const VertexLayoutDesc* desc) {
164 if (layout == m_configuredLayout) return;
165 m_configuredLayout = layout;
166 m_configuredLayoutDesc = desc;
167
168 uint32_t enabledMask = 0;
169 if (desc) {
170 for (const auto& attr : desc->attributes) {
171 switch (attr.format) {
173 SetAttribFormat(m_VAO, attr.location, 1, GL_FLOAT, false,
174 attr.offset);
175 break;
177 SetAttribFormat(m_VAO, attr.location, 2, GL_FLOAT, false,
178 attr.offset);
179 break;
181 SetAttribFormat(m_VAO, attr.location, 3, GL_FLOAT, false,
182 attr.offset);
183 break;
185 SetAttribFormat(m_VAO, attr.location, 4, GL_FLOAT, false,
186 attr.offset);
187 break;
189 SetAttribFormat(m_VAO, attr.location, 1, GL_UNSIGNED_INT,
190 true, attr.offset);
191 break;
193 SetAttribFormat(m_VAO, attr.location, 1, GL_INT, true,
194 attr.offset);
195 break;
196 }
197 if (attr.location < ATTRIB_MASK_BITS)
198 enabledMask |= (1u << attr.location);
199 else
200 glEnableVertexArrayAttrib(m_VAO, attr.location);
201 }
202 } else {
203 // Standard 96-byte Vertex layout: 7 attributes
204 SetAttribFormat(m_VAO, ATTRIB_POSITION, 3, GL_FLOAT, false,
205 offsetof(Vertex, px));
206 SetAttribFormat(m_VAO, ATTRIB_NORMAL, 3, GL_FLOAT, false,
207 offsetof(Vertex, nx));
208 SetAttribFormat(m_VAO, ATTRIB_TANGENT, 4, GL_FLOAT, false,
209 offsetof(Vertex, tx));
210 SetAttribFormat(m_VAO, ATTRIB_COLOR, 4, GL_FLOAT, false,
211 offsetof(Vertex, r));
212 SetAttribFormat(m_VAO, ATTRIB_UV, 2, GL_FLOAT, false,
213 offsetof(Vertex, u));
214 SetAttribFormat(m_VAO, ATTRIB_BONE_IDS, 4, GL_INT, true,
215 offsetof(Vertex, boneIDs));
216 SetAttribFormat(m_VAO, ATTRIB_BONE_WEIGHTS, 4, GL_FLOAT, false,
217 offsetof(Vertex, boneWeights));
218 for (GLuint loc = ATTRIB_POSITION; loc <= ATTRIB_BONE_WEIGHTS; ++loc)
219 enabledMask |= (1u << loc);
220 }
221
222 // Toggle only the slots whose enable state differs from the last layout
223 const uint32_t changed = enabledMask ^ m_enabledAttribMask;
224 for (uint32_t loc = 0; loc < ATTRIB_MASK_BITS; ++loc) {
225 const uint32_t bit = 1u << loc;
226 if (!(changed & bit)) continue;
227 if (enabledMask & bit)
228 glEnableVertexArrayAttrib(m_VAO, loc);
229 else
230 glDisableVertexArrayAttrib(m_VAO, loc);
231 }
232 m_enabledAttribMask = enabledMask;
233}
234
236 m_sceneReadPrepared = false;
241
242 // Commit staged lightVP before shadow pass so shadow + main agree.
243 if (m_hasPendingLightVP) {
244 memcpy(m_lightVP, m_pendingLightVP, sizeof(m_lightVP));
245 }
246
247 // Shadow pass before main rendering
249 RenderShadowPass();
250 }
251
252 if (m_gbufferCreated && m_deferredEnabled) {
253 // Deferred path: geometry pass writes to GBuffer
254 glBindFramebuffer(GL_FRAMEBUFFER, m_gbufferFBO);
255 GLenum drawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 };
256 glDrawBuffers(3, drawBuffers);
257 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
258 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
259 // Geometry pass must NOT blend — each pixel writes final GBuffer values
260 glDisable(GL_BLEND);
261 m_inGeometryPass = true;
262 } else {
263 // Forward path: bind MSAA FBO if active, else default FBO
264 if (m_msaaFBO != 0)
265 glBindFramebuffer(GL_FRAMEBUFFER, m_msaaFBO);
266 else
267 glBindFramebuffer(GL_FRAMEBUFFER, 0);
268
269 glClearColor(0.39f, 0.58f, 0.93f, 1.0f);
270 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
271 }
272
273 glBindVertexArray(m_VAO);
274
275 if (bImInitialized) {
276 ImGui_ImplOpenGL3_NewFrame();
277 ImGui_ImplSDL3_NewFrame();
278 ImGui::NewFrame();
279 }
280}
281
283 // Resolve MSAA FBO to default framebuffer before ImGui.
284 // Skip in deferred mode — we rendered directly to FBO 0.
285 if (m_msaaFBO != 0 && !IsDeferredEnabled()) {
286 int width, height;
287 SDL_GetWindowSize(m_Window->GetSDLWindow(), &width, &height);
288 glBindFramebuffer(GL_READ_FRAMEBUFFER, m_msaaFBO);
289 glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
290 glBlitFramebuffer(0, 0, width, height,
291 0, 0, width, height,
292 GL_COLOR_BUFFER_BIT, GL_NEAREST);
293 glBindFramebuffer(GL_FRAMEBUFFER, 0);
294 }
295
296 if (bImInitialized) {
297 ImGui::Render();
298 ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
299 }
300
301 glBindVertexArray(0);
302 SDL_GL_SwapWindow(m_Window->GetSDLWindow());
303
305}
306
308 if (m_Initialized) {
309 CleanupSceneRead();
310 CleanupGBufferResources();
311 if (m_shadowTransformUBO) { glDeleteBuffers(1, &m_shadowTransformUBO); m_shadowTransformUBO = 0; }
312 if (m_shadowUBO) { glDeleteBuffers(1, &m_shadowUBO); m_shadowUBO = 0; }
313 if (m_shadowDepthTex) { glDeleteTextures(1, &m_shadowDepthTex); m_shadowDepthTex = 0; }
314 if (m_shadowFBO) { glDeleteFramebuffers(1, &m_shadowFBO); m_shadowFBO = 0; }
315 m_shadowMapCreated = false;
316 m_shadowMapRendered = false;
317 m_shadowUBOCreated = false;
318 CleanupMSAAFramebuffer();
319 if (bImInitialized) {
320 ImGui_ImplOpenGL3_Shutdown();
321 ImGui_ImplSDL3_Shutdown();
322 ImGui::DestroyContext();
323 bImInitialized = false;
324 }
325 if (m_VAO != 0) {
326 glDeleteVertexArrays(1, &m_VAO);
327 m_VAO = 0;
328 }
329 if (m_GLContext) {
330 SDL_GL_DestroyContext(m_GLContext);
331 m_GLContext = nullptr;
332 }
333 m_Initialized = false;
334 }
335}
336
337#ifdef SLEAK_HOT_RELOAD
338bool OpenGLRenderer::ReloadShaders(const std::vector<std::string>& stems) {
339 for (OpenGLShader* shader : OpenGLShader::GetLiveShaders()) {
340 const bool changed =
341 std::ranges::any_of(stems, [shader](const std::string& stem) {
342 return shader->UsesStem(stem);
343 });
344 if (!changed) continue;
345 if (shader->Reload()) {
346 SLEAK_INFO("Reloaded OpenGL shader '{}'", shader->GetStem());
347 } else {
348 SLEAK_WARN("Shader '{}' failed to reload, keeping the old program",
349 shader->GetStem());
350 }
351 }
352 for (const std::string& stem : stems) {
353 const bool used =
354 std::ranges::any_of(OpenGLShader::GetLiveShaders(),
355 [&stem](const OpenGLShader* shader) {
356 return shader->UsesStem(stem);
357 });
358 if (!used)
359 SLEAK_WARN("Hot reload: no loaded OpenGL shader is built from '{}'",
360 stem);
361 }
362 return true;
363}
364#endif
365
366void OpenGLRenderer::Resize(uint32_t width, uint32_t height) {
367 ApplyViewport(0, 0, static_cast<GLsizei>(width),
368 static_cast<GLsizei>(height));
369 // Recreate MSAA FBO at new size
370 if (m_msaaFBO != 0) {
371 CleanupMSAAFramebuffer();
372 CreateMSAAFramebuffer();
373 }
374 // Resize GBuffer textures
375 if (m_gbufferCreated) {
376 RecreateGBufferOnResize(static_cast<int>(width), static_cast<int>(height));
377 }
378}
379
380void OpenGLRenderer::Draw(uint32_t vertexCount) { Draw(vertexCount, 0); }
381
382void OpenGLRenderer::Draw(uint32_t vertexCount, uint32_t firstVertex) {
383 GLenum mode = m_debugLineMode ? GL_LINES : GL_TRIANGLES;
384 glDrawArrays(mode, static_cast<GLint>(firstVertex), vertexCount);
385 DrawnVertices += vertexCount;
386 DrawnTriangles += vertexCount / 3;
387}
388
389void OpenGLRenderer::DrawIndexed(uint32_t indexCount) {
390 DrawIndexed(indexCount, 0, 0);
391}
392
393void OpenGLRenderer::DrawIndexed(uint32_t indexCount, uint32_t firstIndex,
394 int32_t baseVertex) {
395 GLenum mode = m_debugLineMode ? GL_LINES : GL_TRIANGLES;
396 const void* offset = reinterpret_cast<const void*>(
397 static_cast<uintptr_t>(firstIndex) * sizeof(uint32_t));
398 glDrawElementsBaseVertex(mode, indexCount, GL_UNSIGNED_INT, offset,
399 baseVertex);
400 DrawnVertices += indexCount;
401 DrawnTriangles += indexCount / 3;
402}
403
404void OpenGLRenderer::DrawInstance(uint32_t instanceCount,
405 uint32_t vertexPerInstance) {
406 GLenum mode = m_debugLineMode ? GL_LINES : GL_TRIANGLES;
407 glDrawArraysInstanced(mode, 0, vertexPerInstance,
408 instanceCount);
409 DrawnVertices += vertexPerInstance * instanceCount;
410 DrawnTriangles += (vertexPerInstance / 3) * instanceCount;
411}
412
413void OpenGLRenderer::DrawIndexedInstance(uint32_t instanceCount,
414 uint32_t indexPerInstance) {
415 DrawIndexedInstance(instanceCount, indexPerInstance, 0, 0);
416}
417
418void OpenGLRenderer::DrawIndexedInstance(uint32_t instanceCount,
419 uint32_t indexPerInstance,
420 uint32_t firstIndex,
421 int32_t baseVertex) {
422 GLenum mode = m_debugLineMode ? GL_LINES : GL_TRIANGLES;
423 const void* offset = reinterpret_cast<const void*>(
424 static_cast<uintptr_t>(firstIndex) * sizeof(uint32_t));
425 glDrawElementsInstancedBaseVertex(mode, indexPerInstance, GL_UNSIGNED_INT,
426 offset, instanceCount, baseVertex);
427 DrawnVertices += indexPerInstance * instanceCount;
428 DrawnTriangles += (indexPerInstance / 3) * instanceCount;
429}
430
432 m_debugLineMode = true;
433}
434
436 m_debugLineMode = false;
437}
438
440 Face = face;
441 ConfigureRenderFace();
442}
443
445 Mode = mode;
446 ConfigureRenderMode();
447}
448
449void OpenGLRenderer::SetViewport(float x, float y, float width,
450 float height, float minDepth,
451 float maxDepth) {
452 ApplyViewport(static_cast<GLint>(x), static_cast<GLint>(y),
453 static_cast<GLsizei>(width), static_cast<GLsizei>(height));
454 glDepthRangef(minDepth, maxDepth);
455}
456
457void OpenGLRenderer::ApplyViewport(GLint x, GLint y, GLsizei width,
458 GLsizei height) {
459 glViewport(x, y, width, height);
460 // GL rejects negative sizes and keeps the previous viewport
461 if (width >= 0 && height >= 0) m_viewport = {x, y, width, height};
462}
463
464void OpenGLRenderer::ClearRenderTarget(float r, float g, float b,
465 float a) {
466 glClearColor(r, g, b, a);
467 glClear(GL_COLOR_BUFFER_BIT);
468}
469
470void OpenGLRenderer::ClearDepthStencil(bool clearDepth, bool clearStencil,
471 float depth, uint8_t stencil) {
472 GLbitfield mask = 0;
473 if (clearDepth) {
474 glClearDepthf(depth);
475 mask |= GL_DEPTH_BUFFER_BIT;
476 }
477 if (clearStencil) {
478 glClearStencil(stencil);
479 mask |= GL_STENCIL_BUFFER_BIT;
480 }
481 if (mask) glClear(mask);
482}
483
485 glDepthMask(enabled ? GL_TRUE : GL_FALSE);
486}
487
489 GLenum glFunc = GL_LESS;
490 switch (compare) {
491 case DepthCompare::Less: glFunc = GL_LESS; break;
492 case DepthCompare::LessEqual: glFunc = GL_LEQUAL; break;
493 case DepthCompare::Greater: glFunc = GL_GREATER; break;
494 case DepthCompare::GreaterEqual: glFunc = GL_GEQUAL; break;
495 case DepthCompare::Equal: glFunc = GL_EQUAL; break;
496 case DepthCompare::NotEqual: glFunc = GL_NOTEQUAL; break;
497 case DepthCompare::Always: glFunc = GL_ALWAYS; break;
498 case DepthCompare::Never: glFunc = GL_NEVER; break;
499 }
500 glDepthFunc(glFunc);
501}
502
504 if (enabled)
505 glEnable(GL_CULL_FACE);
506 else
507 glDisable(GL_CULL_FACE);
508}
509
511 if (texture.IsValid())
512 texture->Bind(slot);
513}
514
516 uint32_t slot) {
517 auto* glBuf = dynamic_cast<OpenGLBuffer*>(buffer.get());
518 if (!glBuf) return;
519
520 // A registered layout drives the attribute formats; 0 means default Vertex
521 const uint32_t format = buffer->GetVertexFormat();
522 const VertexLayoutDesc* desc = m_configuredLayoutDesc;
523 if (format != m_configuredLayout) {
524 desc = format != 0 ? VertexFormatRegistry::Get(format) : nullptr;
525 ConfigureVertexLayout(desc ? format : DEFAULT_VERTEX_LAYOUT, desc);
526 }
527
528 if (desc && desc->transparentReadsScene && m_inForwardTransparentPass)
529 PrepareSceneRead();
530
531 const GLsizei stride = desc ? static_cast<GLsizei>(desc->stride)
532 : static_cast<GLsizei>(sizeof(Vertex));
533 glVertexArrayVertexBuffer(m_VAO, VERTEX_BUFFER_BINDING,
534 glBuf->GetGLBuffer(), 0, stride);
535}
536
538 uint32_t slot) {
539 auto* glBuf = dynamic_cast<OpenGLBuffer*>(buffer.get());
540 if (!glBuf) return;
541
542 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, glBuf->GetGLBuffer());
543}
544
546 uint32_t slot) {
547 auto* glBuf = dynamic_cast<OpenGLBuffer*>(buffer.get());
548 if (!glBuf) return;
549
550 // Shadow pass: use dedicated shadow CB with LightVP*World for slot 0
551 if (m_inShadowPass && slot == 0 &&
552 glBuf->GetCPUShadowCopySize() >= TRANSFORM_CB_BYTES) {
553 const float* srcWorld = reinterpret_cast<const float*>(
554 static_cast<const char*>(glBuf->GetCPUShadowCopy()) + MAT4_BYTES);
555
556 // Create dedicated shadow transform UBO on first use
557 if (m_shadowTransformUBO == 0) {
558 glCreateBuffers(1, &m_shadowTransformUBO);
559 glNamedBufferData(m_shadowTransformUBO, TRANSFORM_CB_BYTES, nullptr,
560 GL_DYNAMIC_DRAW);
561 m_shadowTransformCacheValid = false;
562 }
563
564 // LightVP is fixed for the pass, so only a new World needs an upload
565 static_assert(sizeof(m_shadowTransformCache) == TRANSFORM_CB_BYTES);
566 static_assert(sizeof(m_shadowWorldCache) == MAT4_BYTES);
567 if (!m_shadowTransformCacheValid ||
568 memcmp(srcWorld, m_shadowWorldCache, MAT4_BYTES) != 0) {
569 for (int r = 0; r < MAT4_DIM; ++r) {
570 for (int c = 0; c < MAT4_DIM; ++c) {
571 float sum = 0.0f;
572 for (int k = 0; k < MAT4_DIM; ++k) {
573 sum += srcWorld[r * MAT4_DIM + k] *
574 m_lightVP[k * MAT4_DIM + c];
575 }
576 m_shadowTransformCache[r * MAT4_DIM + c] = sum;
577 }
578 }
579 memcpy(&m_shadowTransformCache[MAT4_FLOATS], srcWorld, MAT4_BYTES);
580 memcpy(m_shadowWorldCache, srcWorld, MAT4_BYTES);
581 m_shadowTransformCacheValid = true;
582 glNamedBufferSubData(m_shadowTransformUBO, 0,
583 sizeof(m_shadowTransformCache),
584 m_shadowTransformCache);
585 }
586
587 glBindBufferBase(GL_UNIFORM_BUFFER, slot, m_shadowTransformUBO);
588 return;
589 }
590
591 glBindBufferBase(GL_UNIFORM_BUFFER, slot, glBuf->GetGLBuffer());
592}
593
597
599 void* data) {
600 auto* buffer = new OpenGLBuffer(size, type);
601 if (!buffer->Initialize(data)) {
602 delete buffer;
603 return nullptr;
604 }
605 return buffer;
606}
607
608Shader* OpenGLRenderer::CreateShader(const std::string& shaderSource) {
609 auto* shader = new OpenGLShader();
610 if (shader->compile(shaderSource)) {
611 return shader;
612 }
613 delete shader;
614 return nullptr;
615}
616
617Texture* OpenGLRenderer::CreateTexture(const std::string& TexturePath) {
618 auto* texture = new OpenGLTexture();
619 if (texture->LoadFromFile(TexturePath)) {
620 return texture;
621 }
622 delete texture;
623 return nullptr;
624}
625
627 uint32_t height,
628 void* data) {
629 auto* texture = new OpenGLTexture();
630 if (texture->LoadFromMemory(data, width, height,
632 return texture;
633 }
634 delete texture;
635 return nullptr;
636}
637
638void OpenGLRenderer::CreateMSAAFramebuffer() {
639 if (m_msaaSampleCount <= 1)
640 return;
641
642 int width, height;
643 SDL_GetWindowSize(m_Window->GetSDLWindow(), &width, &height);
644
645 glGenFramebuffers(1, &m_msaaFBO);
646 glBindFramebuffer(GL_FRAMEBUFFER, m_msaaFBO);
647
648 // Multisampled color renderbuffer
649 glGenRenderbuffers(1, &m_msaaColorRBO);
650 glBindRenderbuffer(GL_RENDERBUFFER, m_msaaColorRBO);
651 glRenderbufferStorageMultisample(GL_RENDERBUFFER, m_msaaSampleCount,
652 GL_RGBA8, width, height);
653 glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
654 GL_RENDERBUFFER, m_msaaColorRBO);
655
656 // Multisampled depth renderbuffer
657 glGenRenderbuffers(1, &m_msaaDepthRBO);
658 glBindRenderbuffer(GL_RENDERBUFFER, m_msaaDepthRBO);
659 glRenderbufferStorageMultisample(GL_RENDERBUFFER, m_msaaSampleCount,
660 GL_DEPTH24_STENCIL8, width, height);
661 glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
662 GL_RENDERBUFFER, m_msaaDepthRBO);
663
664 if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
665 SLEAK_ERROR("OpenGL MSAA framebuffer is not complete!");
666
667 glBindFramebuffer(GL_FRAMEBUFFER, 0);
668}
669
670void OpenGLRenderer::CleanupMSAAFramebuffer() {
671 if (m_msaaDepthRBO) { glDeleteRenderbuffers(1, &m_msaaDepthRBO); m_msaaDepthRBO = 0; }
672 if (m_msaaColorRBO) { glDeleteRenderbuffers(1, &m_msaaColorRBO); m_msaaColorRBO = 0; }
673 if (m_msaaFBO) { glDeleteFramebuffers(1, &m_msaaFBO); m_msaaFBO = 0; }
674}
675
678 return;
679 m_msaaChangeRequested = false;
681
682 CleanupMSAAFramebuffer();
683 CreateMSAAFramebuffer();
684
685 SLEAK_INFO("OpenGL MSAA changed to {}x", m_msaaSampleCount);
686}
687
690 return;
692 SDL_GL_SetSwapInterval(m_vsync ? 1 : 0);
693 SLEAK_INFO("OpenGL VSync {}", m_vsync ? "enabled" : "disabled");
694}
695
697 switch (Mode) {
698 case RenderMode::Fill:
699 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
700 break;
702 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
703 break;
705 glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);
706 break;
707 default:
708 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
709 break;
710 }
711}
712
714 switch (Face) {
715 case RenderFace::None:
716 glDisable(GL_CULL_FACE);
717 break;
718 case RenderFace::Back:
719 glEnable(GL_CULL_FACE);
720 glCullFace(GL_BACK);
721 break;
723 glEnable(GL_CULL_FACE);
724 glCullFace(GL_FRONT);
725 break;
726 default:
727 glDisable(GL_CULL_FACE);
728 break;
729 }
730}
731
732Texture* OpenGLRenderer::CreateCubemapTexture(const std::array<std::string, 6>& facePaths) {
733 auto* texture = new OpenGLCubemapTexture();
734 if (texture->LoadCubemap(facePaths)) {
735 return texture;
736 }
737 delete texture;
738 return nullptr;
739}
740
742 auto* texture = new OpenGLCubemapTexture();
743 if (texture->LoadEquirectangular(panoramaPath)) {
744 return texture;
745 }
746 delete texture;
747 return nullptr;
748}
749
751 IMGUI_CHECKVERSION();
752 ImGui::CreateContext();
753 ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
754 ImGui::StyleColorsDark();
755
756 if (!ImGui_ImplSDL3_InitForOpenGL(m_Window->GetSDLWindow(),
757 m_GLContext))
758 return false;
759
760 if (!ImGui_ImplOpenGL3_Init("#version 450"))
761 return false;
762
763 bImInitialized = true;
764 return true;
765}
766
767void OpenGLRenderer::SetLightVP(const float* mat) {
768 if (mat) {
769 memcpy(m_pendingLightVP, mat, sizeof(m_pendingLightVP));
770 m_hasPendingLightVP = true;
771 }
772}
773
774bool OpenGLRenderer::CreateShadowUBO() {
775 if (m_shadowUBOCreated) return true;
776 glGenBuffers(1, &m_shadowUBO);
777 glBindBuffer(GL_UNIFORM_BUFFER, m_shadowUBO);
778 glBufferData(GL_UNIFORM_BUFFER, sizeof(RenderEngine::PCSSShadowGPUData), nullptr, GL_DYNAMIC_DRAW);
779 glBindBuffer(GL_UNIFORM_BUFFER, 0);
780 m_shadowUBOCreated = true;
781 return true;
782}
783
784void OpenGLRenderer::UpdateShadowLightUBO(const void* data, uint32_t size) {
785 if (!m_shadowUBOCreated && !CreateShadowUBO()) return;
786 if (!data) return;
787
788 const auto* ubo = static_cast<const RenderEngine::ShadowLightUBO*>(data);
789
790 RenderEngine::PCSSShadowGPUData shadowData{};
791 // Sample with the map's own matrix
792 memcpy(shadowData.LightVP,
793 m_shadowMapRendered ? m_shadowMapLightVP : ubo->LightVP,
794 sizeof(shadowData.LightVP));
795 memcpy(shadowData.NdcToShadow, ubo->NdcToShadow, sizeof(float) * 16);
796 shadowData.ShadowBias = ubo->ShadowBias;
797 shadowData.ShadowStrength = ubo->ShadowStrength;
798 shadowData.ShadowTexelSize = ubo->ShadowTexelSize;
799 shadowData.ShadowLightSize = ubo->LightSize;
800 shadowData.PCSSEnabled = m_pcssEnabled ? 1 : 0;
801 shadowData.ShadowMapEnabled = m_shadowPassEnabled ? 1 : 0;
802
803 glBindBuffer(GL_UNIFORM_BUFFER, m_shadowUBO);
804 glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(shadowData), &shadowData);
805 glBindBuffer(GL_UNIFORM_BUFFER, 0);
806
807 // Bind shadow UBO at binding 5 (matches shader)
808 glBindBufferBase(GL_UNIFORM_BUFFER, 5, m_shadowUBO);
809}
810
811bool OpenGLRenderer::CreateShadowMapResources() {
812 if (m_shadowMapCreated) return true;
813
814 // Create depth texture
815 glGenTextures(1, &m_shadowDepthTex);
816 glBindTexture(GL_TEXTURE_2D, m_shadowDepthTex);
817 glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32F,
819 GL_DEPTH_COMPONENT, GL_FLOAT, nullptr);
820 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
821 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
822 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
823 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
824 float borderColor[] = {1.0f, 1.0f, 1.0f, 1.0f};
825 glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor);
826 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
827 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
828 glBindTexture(GL_TEXTURE_2D, 0);
829
830 // Create FBO
831 glGenFramebuffers(1, &m_shadowFBO);
832 glBindFramebuffer(GL_FRAMEBUFFER, m_shadowFBO);
833 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_shadowDepthTex, 0);
834 glDrawBuffer(GL_NONE);
835 glReadBuffer(GL_NONE);
836 if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
837 SLEAK_ERROR("OpenGL shadow FBO is not complete!");
838 glBindFramebuffer(GL_FRAMEBUFFER, 0);
839 return false;
840 }
841 glBindFramebuffer(GL_FRAMEBUFFER, 0);
842
843 m_shadowMapCreated = true;
845 SLEAK_INFO("OpenGL shadow map resources created ({}x{})", m_shadowMapResolution, m_shadowMapResolution);
846 return true;
847}
848
849void OpenGLRenderer::RenderShadowPass() {
850 // Skip if no cached draws — preserve previous frame's shadow map
851 auto* queue = RenderCommandQueue::GetInstance();
852 if (!queue || !queue->HasCachedShadowDraws()) return;
853
854 if (!m_shadowMapCreated) {
855 if (!CreateShadowMapResources()) return;
856 }
857
858 const std::array<GLint, 4> savedViewport = m_viewport;
859
860 // Bind shadow FBO
861 glBindFramebuffer(GL_FRAMEBUFFER, m_shadowFBO);
863 glClear(GL_DEPTH_BUFFER_BIT);
864
865 // Enable polygon offset for slope-scale depth bias
866 glEnable(GL_POLYGON_OFFSET_FILL);
867 glPolygonOffset(2.0f, 4.0f);
868
869 // Back-face cull: closed solid volumes always have the light-facing
870 // surface win — same depth result, half the raster.
871 // (FRONT culling stays wrong: it removed the outward-facing surfaces.)
872 glEnable(GL_CULL_FACE);
873 glCullFace(GL_BACK);
874
875 // Ensure VAO is bound for shadow pass draws
876 glBindVertexArray(m_VAO);
877
878 // Execute shadow draw commands
879 m_inShadowPass = true;
880 m_shadowTransformCacheValid = false;
881 if (queue) {
882 queue->ExecuteShadowPass(this);
883 }
884 m_inShadowPass = false;
885 memcpy(m_shadowMapLightVP, m_lightVP, sizeof(m_shadowMapLightVP));
886 m_shadowMapRendered = true;
887
888 // Restore state
889 glDisable(GL_POLYGON_OFFSET_FILL);
890 glEnable(GL_CULL_FACE); // re-enable culling for main pass
891 ConfigureRenderFace();
892
893 // Restore framebuffer
894 if (m_msaaFBO != 0)
895 glBindFramebuffer(GL_FRAMEBUFFER, m_msaaFBO);
896 else
897 glBindFramebuffer(GL_FRAMEBUFFER, 0);
898
899 ApplyViewport(savedViewport[0], savedViewport[1], savedViewport[2],
900 savedViewport[3]);
901
902 // Bind shadow map texture at unit 3
903 glActiveTexture(GL_TEXTURE3);
904 glBindTexture(GL_TEXTURE_2D, m_shadowDepthTex);
905 glActiveTexture(GL_TEXTURE0);
906}
907
908// ============================================================
909// Deferred rendering — GBuffer implementation
910// ============================================================
911
913 return m_deferredEnabled && m_gbufferCreated;
914}
915
916bool OpenGLRenderer::CreateGBufferResources() {
917 if (m_gbufferCreated) return true;
918
919 int w, h;
920 SDL_GetWindowSize(m_Window->GetSDLWindow(), &w, &h);
921 m_gbufferWidth = w;
922 m_gbufferHeight = h;
923
924 // ---- GBuffer FBO ----
925 glGenFramebuffers(1, &m_gbufferFBO);
926 glBindFramebuffer(GL_FRAMEBUFFER, m_gbufferFBO);
927
928 auto makeColorTex = [](GLuint& tex, GLenum internalFmt, int w, int h) {
929 glGenTextures(1, &tex);
930 glBindTexture(GL_TEXTURE_2D, tex);
931 GLenum fmt = GL_RGBA;
932 GLenum type = GL_UNSIGNED_BYTE;
933 if (internalFmt == GL_RGBA16F || internalFmt == GL_RGBA32F) {
934 type = GL_FLOAT;
935 }
936 glTexImage2D(GL_TEXTURE_2D, 0, internalFmt, w, h, 0, fmt, type, nullptr);
937 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
938 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
939 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
940 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
941 };
942
943 // RT0: Albedo + AO (RGBA8)
944 makeColorTex(m_gbufferAlbedoAO, GL_RGBA8, w, h);
945 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_gbufferAlbedoAO, 0);
946
947 // RT1: Normal + Roughness (RGBA16F)
948 makeColorTex(m_gbufferNormalRough, GL_RGBA16F, w, h);
949 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, m_gbufferNormalRough, 0);
950
951 // RT2: Metallic + Emissive (RGBA8)
952 makeColorTex(m_gbufferMetalEmit, GL_RGBA8, w, h);
953 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, m_gbufferMetalEmit, 0);
954
955 // World position is reconstructed from depth + InvViewProj in the
956 // lighting/SSAO passes (no RGBA32F worldpos RT) to cut GBuffer bandwidth.
957
958 // Depth texture (read back in lighting pass for world pos reconstruction)
959 glGenTextures(1, &m_gbufferDepth);
960 glBindTexture(GL_TEXTURE_2D, m_gbufferDepth);
961 glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32F, w, h, 0,
962 GL_DEPTH_COMPONENT, GL_FLOAT, nullptr);
963 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
964 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
965 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
966 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
967 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_gbufferDepth, 0);
968
969 GLenum drawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1,
970 GL_COLOR_ATTACHMENT2 };
971 glDrawBuffers(3, drawBuffers);
972
973 if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
974 SLEAK_ERROR("OpenGL GBuffer FBO is not complete!");
975 glBindFramebuffer(GL_FRAMEBUFFER, 0);
976 return false;
977 }
978 glBindFramebuffer(GL_FRAMEBUFFER, 0);
979
980 // ---- GBuffer geometry shader ----
981 m_gbufferShader = new OpenGLShader();
982 if (!m_gbufferShader->compile("assets/shaders/gbuffer_gl.vert",
983 "assets/shaders/gbuffer_gl.frag")) {
984 SLEAK_ERROR("Failed to compile GBuffer geometry shader!");
985 delete m_gbufferShader;
986 m_gbufferShader = nullptr;
987 CleanupGBufferResources();
988 return false;
989 }
990
991 // ---- Lighting pass shader ----
992 m_lightingShader = new OpenGLShader();
993 if (!m_lightingShader->compile("assets/shaders/lighting_pass_gl.vert",
994 "assets/shaders/lighting_pass_gl.frag")) {
995 SLEAK_ERROR("Failed to compile deferred lighting pass shader!");
996 delete m_lightingShader;
997 m_lightingShader = nullptr;
998 CleanupGBufferResources();
999 return false;
1000 }
1001
1002 // ---- Empty VAO for fullscreen triangle ----
1003 glGenVertexArrays(1, &m_lightingVAO);
1004
1005 // ---- Deferred CB UBO (binding 6) ----
1006 glGenBuffers(1, &m_deferredCBUBO);
1007 glBindBuffer(GL_UNIFORM_BUFFER, m_deferredCBUBO);
1008 glBufferData(GL_UNIFORM_BUFFER, sizeof(RenderEngine::DeferredCBData), nullptr, GL_DYNAMIC_DRAW);
1009 glBindBuffer(GL_UNIFORM_BUFFER, 0);
1010 glBindBufferBase(GL_UNIFORM_BUFFER, 6, m_deferredCBUBO);
1011 m_deferredCBCreated = true;
1012
1013 m_gbufferCreated = true;
1014 SLEAK_INFO("OpenGL GBuffer created ({}x{}) — deferred rendering active", w, h);
1015
1016 if (!CreateSSAOResources()) {
1017 SLEAK_WARN("OpenGL SSAO resources failed to initialize — SSAO disabled");
1018 }
1019 return true;
1020}
1021
1022void OpenGLRenderer::CleanupGBufferResources() {
1023 CleanupSSAOResources();
1024 CleanupIBL();
1025 if (m_gbufferAlbedoAO) { glDeleteTextures(1, &m_gbufferAlbedoAO); m_gbufferAlbedoAO = 0; }
1026 if (m_gbufferNormalRough) { glDeleteTextures(1, &m_gbufferNormalRough); m_gbufferNormalRough = 0; }
1027 if (m_gbufferMetalEmit) { glDeleteTextures(1, &m_gbufferMetalEmit); m_gbufferMetalEmit = 0; }
1028 if (m_gbufferDepth) { glDeleteTextures(1, &m_gbufferDepth); m_gbufferDepth = 0; }
1029 if (m_gbufferFBO) { glDeleteFramebuffers(1, &m_gbufferFBO); m_gbufferFBO = 0; }
1030 if (m_lightingVAO) { glDeleteVertexArrays(1, &m_lightingVAO); m_lightingVAO = 0; }
1031 if (m_deferredCBUBO) { glDeleteBuffers(1, &m_deferredCBUBO); m_deferredCBUBO = 0; }
1032 delete m_gbufferShader; m_gbufferShader = nullptr;
1033 delete m_lightingShader; m_lightingShader = nullptr;
1034 m_gbufferCreated = false;
1035 m_deferredCBCreated = false;
1036}
1037
1038// IBL — lazy bake from active scene's skybox cubemap.
1039// First call (or when the skybox cubemap changes) reruns the precompute.
1040void OpenGLRenderer::EnsureIBL() {
1041 GLuint cubeHandle = FindSkyboxCubemap();
1042 if (cubeHandle == 0) return;
1043
1044 if (!m_ibl) m_ibl = new OpenGLIBL();
1045 if (cubeHandle != m_iblBoundCubemap) {
1046 m_ibl->Cleanup();
1047 if (m_ibl->Initialize(cubeHandle)) {
1048 m_iblBoundCubemap = cubeHandle;
1049 } else {
1050 m_iblBoundCubemap = 0;
1051 }
1052 }
1053
1054 if (m_iblSettingsUBO == 0) {
1055 glGenBuffers(1, &m_iblSettingsUBO);
1056 glBindBuffer(GL_UNIFORM_BUFFER, m_iblSettingsUBO);
1057 glBufferData(GL_UNIFORM_BUFFER,
1058 sizeof(IBLSettingsGPUData),
1059 nullptr, GL_DYNAMIC_DRAW);
1060 glBindBuffer(GL_UNIFORM_BUFFER, 0);
1061 }
1062}
1063
1064void OpenGLRenderer::CleanupIBL() {
1065 if (m_ibl) { delete m_ibl; m_ibl = nullptr; }
1066 if (m_iblSettingsUBO) {
1067 glDeleteBuffers(1, &m_iblSettingsUBO);
1068 m_iblSettingsUBO = 0;
1069 }
1070 m_iblBoundCubemap = 0;
1071}
1072
1073void OpenGLRenderer::RecreateGBufferOnResize(int width, int height) {
1074 if (!m_gbufferCreated) return;
1075
1076 m_gbufferWidth = width;
1077 m_gbufferHeight = height;
1078
1079 // Resize AlbedoAO
1080 glBindTexture(GL_TEXTURE_2D, m_gbufferAlbedoAO);
1081 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
1082
1083 // Resize NormalRough
1084 glBindTexture(GL_TEXTURE_2D, m_gbufferNormalRough);
1085 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, width, height, 0, GL_RGBA, GL_FLOAT, nullptr);
1086
1087 // Resize MetalEmit
1088 glBindTexture(GL_TEXTURE_2D, m_gbufferMetalEmit);
1089 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
1090
1091 // Resize depth
1092 glBindTexture(GL_TEXTURE_2D, m_gbufferDepth);
1093 glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32F, width, height, 0,
1094 GL_DEPTH_COMPONENT, GL_FLOAT, nullptr);
1095
1096 glBindTexture(GL_TEXTURE_2D, 0);
1097
1098 RecreateSSAOOnResize(width, height);
1099
1100 SLEAK_INFO("OpenGL GBuffer resized to {}x{}", width, height);
1101}
1102
1104 if (m_gbufferShader) {
1105 // Ensure GBuffer FBO is active with all 3 color attachments
1106 // (RT0=AlbedoAO, RT1=NormalRough, RT2=MetalEmit)
1107 glBindFramebuffer(GL_FRAMEBUFFER, m_gbufferFBO);
1108 GLenum drawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1,
1109 GL_COLOR_ATTACHMENT2 };
1110 glDrawBuffers(3, drawBuffers);
1111 // Ensure depth writes are enabled for geometry pass
1112 glEnable(GL_DEPTH_TEST);
1113 glDepthMask(GL_TRUE);
1114
1115 // Clear stale shadow sampler from unit 3 — the shadow depth texture
1116 // has GL_TEXTURE_COMPARE_MODE enabled which conflicts with the GBuffer
1117 // shader's sampler2D declaration at binding 3 (roughnessTexture).
1118 glActiveTexture(GL_TEXTURE3);
1119 glBindTexture(GL_TEXTURE_2D, 0);
1120 glActiveTexture(GL_TEXTURE0);
1121
1122 m_gbufferShader->bind();
1123 glBindVertexArray(m_VAO);
1124 } else {
1125 static bool warned = false;
1126 if (!warned) {
1127 SLEAK_ERROR("BindGBufferShader: m_gbufferShader is NULL!");
1128 warned = true;
1129 }
1130 }
1131}
1132
1133void OpenGLRenderer::BindPBRMaterial(Sleak::Material* material) {
1134 // Deferred geometry-pass material bind (restores pre-rewrite OpenGL path):
1135 // bind the GBuffer shader + the material textures/CB. Without this, terrain
1136 // is drawn with the leftover water program (all-blue bug).
1137 BindGBufferShader();
1138 if (material) material->BindTexturesAndCB();
1139}
1140
1141void OpenGLRenderer::UpdateDeferredCB(const void* data, uint32_t size) {
1142 if (!m_deferredCBCreated) return;
1143 if (data && size >= sizeof(DeferredCBData)) {
1144 const auto* cb = static_cast<const DeferredCBData*>(data);
1145 memcpy(m_cachedInvViewProj, cb->InvViewProj,
1146 sizeof(m_cachedInvViewProj));
1147 m_cachedNearPlane = cb->NearPlane;
1148 m_cachedFarPlane = cb->FarPlane;
1149 }
1150 glBindBuffer(GL_UNIFORM_BUFFER, m_deferredCBUBO);
1151 glBufferSubData(GL_UNIFORM_BUFFER, 0, size, data);
1152 glBindBuffer(GL_UNIFORM_BUFFER, 0);
1153 glBindBufferBase(GL_UNIFORM_BUFFER, 6, m_deferredCBUBO);
1154}
1155
1157 m_inGeometryPass = false;
1158
1159 if (!m_gbufferCreated || !m_lightingShader) return;
1160
1161 // SSAO must run BEFORE the lighting pass so its blurred output is
1162 // available for the lighting shader to multiply against vertex AO.
1163 ExecuteSSAOPass();
1164
1165 // IBL precompute (cheap when already baked) — must happen before the
1166 // lighting shader binds units 14/15/16 and UBO 10.
1167 EnsureIBL();
1168
1169 // Deferred rendering always outputs to the default FBO (framebuffer 0).
1170 // MSAA is incompatible with deferred (multisampled GBuffer is too expensive),
1171 // so we skip the MSAA FBO and render directly to the default framebuffer.
1172 constexpr GLuint targetFBO = 0;
1173 glBindFramebuffer(GL_FRAMEBUFFER, targetFBO);
1174
1175 // Keep the sky color cleared
1176 glClearColor(0.39f, 0.58f, 0.93f, 1.0f);
1177 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1178
1179 // Enable depth writes so the lighting shader can output gl_FragDepth.
1180 // This replaces the old glBlitFramebuffer approach which silently failed
1181 // on some drivers when GBuffer depth (32F) differs from default FBO depth (24-bit).
1182 glEnable(GL_DEPTH_TEST);
1183 glDepthFunc(GL_ALWAYS); // fullscreen triangle must always pass
1184 glDepthMask(GL_TRUE); // allow depth writes
1185 glDisable(GL_BLEND);
1186
1187 // Bind lighting shader
1188 m_lightingShader->bind();
1189
1190 // Bind GBuffer textures at units 8-11
1191 glActiveTexture(GL_TEXTURE8); glBindTexture(GL_TEXTURE_2D, m_gbufferAlbedoAO);
1192 glActiveTexture(GL_TEXTURE9); glBindTexture(GL_TEXTURE_2D, m_gbufferNormalRough);
1193 glActiveTexture(GL_TEXTURE10); glBindTexture(GL_TEXTURE_2D, m_gbufferMetalEmit);
1194 glActiveTexture(GL_TEXTURE11); glBindTexture(GL_TEXTURE_2D, m_gbufferDepth);
1195 // SSAO result at unit 13 (default to 0 = "fully lit" if SSAO disabled)
1196 glActiveTexture(GL_TEXTURE13);
1197 glBindTexture(GL_TEXTURE_2D, m_ssaoCreated ? m_ssaoBlurTex : 0);
1198 // SSAO enable flag via plain uniform — avoids growing DeferredCBData
1199 GLint ssaoLoc = glGetUniformLocation(
1200 m_lightingShader->GetProgram(), "uSSAOEnabled");
1201 if (ssaoLoc >= 0) {
1202 glUniform1i(ssaoLoc, (m_ssaoEnabled && m_ssaoCreated) ? 1 : 0);
1203 }
1204 glActiveTexture(GL_TEXTURE0);
1205
1206 // Rebind shadow map at unit 3 — BindGBufferShader cleared it to avoid
1207 // sampler2DShadow/sampler2D conflict during the geometry pass.
1208 if (m_shadowMapCreated) {
1209 glActiveTexture(GL_TEXTURE3);
1210 glBindTexture(GL_TEXTURE_2D, m_shadowDepthTex);
1211 glActiveTexture(GL_TEXTURE0);
1212 }
1213
1214 // IBL — bind irradiance/prefilter/BRDF at units 14/15/16 and upload the
1215 // settings UBO at slot 10. Disabled if precompute hasn't completed.
1216 bool iblReady = (m_ibl && m_ibl->IsInitialized());
1217 if (iblReady) m_ibl->Bind();
1218 if (m_iblSettingsUBO) {
1219 IBLSettingsGPUData ibl{};
1220 ibl.IBLEnabled = (iblReady && m_iblEnabled) ? 1u : 0u;
1221 ibl.IBLIntensity = m_iblIntensity;
1222 ibl.MaxReflectionLOD = static_cast<float>(OpenGLIBL::PREFILTER_MIPS - 1);
1223 ibl._iblPad0 = 0;
1224 glBindBuffer(GL_UNIFORM_BUFFER, m_iblSettingsUBO);
1225 glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(ibl), &ibl);
1226 glBindBuffer(GL_UNIFORM_BUFFER, 0);
1227 glBindBufferBase(GL_UNIFORM_BUFFER, 10, m_iblSettingsUBO);
1228 }
1229
1230 // Draw fullscreen triangle — shader writes color + gl_FragDepth
1231 glBindVertexArray(m_lightingVAO);
1232 glDrawArrays(GL_TRIANGLES, 0, 3);
1233
1234 // Restore depth state for forward pass
1235 glDepthFunc(GL_LESS);
1236 glEnable(GL_BLEND);
1237 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1238
1239 // Rebind main VAO for forward pass
1240 glBindVertexArray(m_VAO);
1241}
1242
1244 m_inForwardTransparentPass = true;
1245 // Transparent objects need alpha blending
1246 glEnable(GL_BLEND);
1247 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1248}
1249
1251 m_inForwardTransparentPass = false;
1252}
1253
1254// ============================================================
1255// SSAO pass — runs between GBuffer write and deferred lighting
1256// Output: R8 half-or-full-res AO in m_ssaoBlurTex, sampled by
1257// lighting_pass_gl.frag at texture unit 13 and multiplied into ao.
1258// ============================================================
1259
1260bool OpenGLRenderer::CreateSSAOResources() {
1261 if (m_ssaoCreated) return true;
1262 if (!m_gbufferCreated) return false;
1263
1264 int w = m_gbufferWidth;
1265 int h = m_gbufferHeight;
1266
1267 auto makeR8Tex = [](GLuint& tex, int w, int h) {
1268 glGenTextures(1, &tex);
1269 glBindTexture(GL_TEXTURE_2D, tex);
1270 glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
1271 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1272 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1273 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1274 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1275 };
1276
1277 // ---- Raw SSAO FBO ----
1278 makeR8Tex(m_ssaoTexture, w, h);
1279 glGenFramebuffers(1, &m_ssaoFBO);
1280 glBindFramebuffer(GL_FRAMEBUFFER, m_ssaoFBO);
1281 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
1282 GL_TEXTURE_2D, m_ssaoTexture, 0);
1283 if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
1284 SLEAK_ERROR("OpenGL SSAO FBO incomplete");
1285 glBindFramebuffer(GL_FRAMEBUFFER, 0);
1286 CleanupSSAOResources();
1287 return false;
1288 }
1289
1290 // ---- Blur FBO ----
1291 makeR8Tex(m_ssaoBlurTex, w, h);
1292 glGenFramebuffers(1, &m_ssaoBlurFBO);
1293 glBindFramebuffer(GL_FRAMEBUFFER, m_ssaoBlurFBO);
1294 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
1295 GL_TEXTURE_2D, m_ssaoBlurTex, 0);
1296 if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
1297 SLEAK_ERROR("OpenGL SSAO blur FBO incomplete");
1298 glBindFramebuffer(GL_FRAMEBUFFER, 0);
1299 CleanupSSAOResources();
1300 return false;
1301 }
1302 glBindFramebuffer(GL_FRAMEBUFFER, 0);
1303
1304 // ---- 4x4 noise texture ----
1305 SSAOKernel kernelGen;
1306 kernelGen.Generate();
1307
1308 glGenTextures(1, &m_ssaoNoiseTex);
1309 glBindTexture(GL_TEXTURE_2D, m_ssaoNoiseTex);
1310 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F,
1312 GL_RGBA, GL_FLOAT, kernelGen.noiseData.data());
1313 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1314 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1315 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
1316 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
1317
1318 // ---- Shaders ----
1319 m_ssaoShader = new OpenGLShader();
1320 if (!m_ssaoShader->compile("assets/shaders/ssao_gl.vert",
1321 "assets/shaders/ssao_gl.frag")) {
1322 SLEAK_ERROR("Failed to compile SSAO shader");
1323 CleanupSSAOResources();
1324 return false;
1325 }
1326 m_ssaoBlurShader = new OpenGLShader();
1327 if (!m_ssaoBlurShader->compile("assets/shaders/ssao_blur_gl.vert",
1328 "assets/shaders/ssao_blur_gl.frag")) {
1329 SLEAK_ERROR("Failed to compile SSAO blur shader");
1330 CleanupSSAOResources();
1331 return false;
1332 }
1333
1334 // ---- UBOs ----
1335 // Settings (binding 0) — 64 bytes
1336 glGenBuffers(1, &m_ssaoSettingsUBO);
1337 glBindBuffer(GL_UNIFORM_BUFFER, m_ssaoSettingsUBO);
1338 glBufferData(GL_UNIFORM_BUFFER, sizeof(SSAOSettingsGPUData), nullptr, GL_DYNAMIC_DRAW);
1339
1340 // Kernel (binding 1) — 1024 bytes, upload once (deterministic seed)
1341 glGenBuffers(1, &m_ssaoKernelUBO);
1342 glBindBuffer(GL_UNIFORM_BUFFER, m_ssaoKernelUBO);
1343 glBufferData(GL_UNIFORM_BUFFER,
1344 sizeof(SSAOKernel::Sample) * SSAOKernel::MAX_KERNEL_SIZE,
1345 kernelGen.samples.data(), GL_STATIC_DRAW);
1346
1347 // Camera (binding 2) — Projection + View + InvViewProj = 3 * 64 = 192 bytes
1348 glGenBuffers(1, &m_ssaoCameraUBO);
1349 glBindBuffer(GL_UNIFORM_BUFFER, m_ssaoCameraUBO);
1350 glBufferData(GL_UNIFORM_BUFFER, sizeof(float) * 16 * 3, nullptr, GL_DYNAMIC_DRAW);
1351
1352 glBindBuffer(GL_UNIFORM_BUFFER, 0);
1353
1354 m_ssaoCreated = true;
1355 SLEAK_INFO("OpenGL SSAO ready ({}x{})", w, h);
1356 return true;
1357}
1358
1359void OpenGLRenderer::CleanupSSAOResources() {
1360 if (m_ssaoFBO) { glDeleteFramebuffers(1, &m_ssaoFBO); m_ssaoFBO = 0; }
1361 if (m_ssaoBlurFBO) { glDeleteFramebuffers(1, &m_ssaoBlurFBO); m_ssaoBlurFBO = 0; }
1362 if (m_ssaoTexture) { glDeleteTextures(1, &m_ssaoTexture); m_ssaoTexture = 0; }
1363 if (m_ssaoBlurTex) { glDeleteTextures(1, &m_ssaoBlurTex); m_ssaoBlurTex = 0; }
1364 if (m_ssaoNoiseTex) { glDeleteTextures(1, &m_ssaoNoiseTex); m_ssaoNoiseTex = 0; }
1365 if (m_ssaoSettingsUBO) { glDeleteBuffers(1, &m_ssaoSettingsUBO); m_ssaoSettingsUBO = 0; }
1366 if (m_ssaoKernelUBO) { glDeleteBuffers(1, &m_ssaoKernelUBO); m_ssaoKernelUBO = 0; }
1367 if (m_ssaoCameraUBO) { glDeleteBuffers(1, &m_ssaoCameraUBO); m_ssaoCameraUBO = 0; }
1368 delete m_ssaoShader; m_ssaoShader = nullptr;
1369 delete m_ssaoBlurShader; m_ssaoBlurShader = nullptr;
1370 m_ssaoCreated = false;
1371}
1372
1373void OpenGLRenderer::RecreateSSAOOnResize(int width, int height) {
1374 if (!m_ssaoCreated) return;
1375
1376 glBindTexture(GL_TEXTURE_2D, m_ssaoTexture);
1377 glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, width, height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
1378
1379 glBindTexture(GL_TEXTURE_2D, m_ssaoBlurTex);
1380 glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, width, height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
1381
1382 glBindTexture(GL_TEXTURE_2D, 0);
1383}
1384
1385void OpenGLRenderer::ExecuteSSAOPass() {
1386 if (!m_ssaoCreated || !m_ssaoShader || !m_ssaoBlurShader) return;
1387
1388 // Fast-path: if SSAO is disabled, clear the blur target to white so the
1389 // lighting shader's ao * ssao multiply is a no-op.
1390 if (!m_ssaoEnabled) {
1391 glBindFramebuffer(GL_FRAMEBUFFER, m_ssaoBlurFBO);
1392 glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
1393 glClear(GL_COLOR_BUFFER_BIT);
1394 glBindFramebuffer(GL_FRAMEBUFFER, 0);
1395 return;
1396 }
1397
1398 // ---- Upload per-frame settings UBO ----
1399 SSAOSettingsGPUData s{};
1400 s.Radius = m_ssaoRadius;
1401 s.Bias = m_ssaoBias;
1402 s.Power = m_ssaoPower;
1403 s.KernelSize = SSAOKernel::MAX_KERNEL_SIZE;
1404 s.ScreenWidth = static_cast<float>(m_gbufferWidth);
1405 s.ScreenHeight = static_cast<float>(m_gbufferHeight);
1406 s.SSAOEnabled = 1;
1407 s.NearPlane = 0.1f;
1408 s.FarPlane = 2000.0f;
1409
1410 glBindBuffer(GL_UNIFORM_BUFFER, m_ssaoSettingsUBO);
1411 glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(s), &s);
1412
1413 // ---- Upload Camera UBO (Projection, View, InvViewProj) ----
1416 float camData[16 * 3];
1417 std::memcpy(camData, &P(0,0), sizeof(float) * 16);
1418 std::memcpy(camData + 16, &V(0,0), sizeof(float) * 16);
1419 // InvViewProj = inverse(View * Proj) — reconstructs world pos from depth.
1420 // Row-vector engine convention: clip = world * (View * Proj).
1421 Math::Matrix4 VP = V * P;
1422 float invP[16];
1423 {
1424 // Inline determinant-based 4x4 inverse (Cramer). Returns identity if singular.
1425 const float* m = &VP(0,0);
1426 float i0 = m[5]*m[10]*m[15] - m[5]*m[11]*m[14] - m[9]*m[6]*m[15] + m[9]*m[7]*m[14] + m[13]*m[6]*m[11] - m[13]*m[7]*m[10];
1427 float i4 = -m[4]*m[10]*m[15] + m[4]*m[11]*m[14] + m[8]*m[6]*m[15] - m[8]*m[7]*m[14] - m[12]*m[6]*m[11] + m[12]*m[7]*m[10];
1428 float i8 = m[4]*m[9] *m[15] - m[4]*m[11]*m[13] - m[8]*m[5]*m[15] + m[8]*m[7]*m[13] + m[12]*m[5]*m[11] - m[12]*m[7]*m[9];
1429 float i12 = -m[4]*m[9] *m[14] + m[4]*m[10]*m[13] + m[8]*m[5]*m[14] - m[8]*m[6]*m[13] - m[12]*m[5]*m[10] + m[12]*m[6]*m[9];
1430 float det = m[0]*i0 + m[1]*i4 + m[2]*i8 + m[3]*i12;
1431 if (std::fabs(det) < 1e-8f) {
1432 std::memset(invP, 0, sizeof(invP));
1433 invP[0] = invP[5] = invP[10] = invP[15] = 1.0f;
1434 } else {
1435 float id = 1.0f / det;
1436 invP[0] = i0 * id; invP[4] = i4 * id; invP[8] = i8 * id; invP[12] = i12 * id;
1437 invP[1] = (-m[1]*m[10]*m[15] + m[1]*m[11]*m[14] + m[9]*m[2]*m[15] - m[9]*m[3]*m[14] - m[13]*m[2]*m[11] + m[13]*m[3]*m[10]) * id;
1438 invP[5] = ( m[0]*m[10]*m[15] - m[0]*m[11]*m[14] - m[8]*m[2]*m[15] + m[8]*m[3]*m[14] + m[12]*m[2]*m[11] - m[12]*m[3]*m[10]) * id;
1439 invP[9] = (-m[0]*m[9] *m[15] + m[0]*m[11]*m[13] + m[8]*m[1]*m[15] - m[8]*m[3]*m[13] - m[12]*m[1]*m[11] + m[12]*m[3]*m[9] ) * id;
1440 invP[13] = ( m[0]*m[9] *m[14] - m[0]*m[10]*m[13] - m[8]*m[1]*m[14] + m[8]*m[2]*m[13] + m[12]*m[1]*m[10] - m[12]*m[2]*m[9] ) * id;
1441 invP[2] = ( m[1]*m[6]*m[15] - m[1]*m[7]*m[14] - m[5]*m[2]*m[15] + m[5]*m[3]*m[14] + m[13]*m[2]*m[7] - m[13]*m[3]*m[6]) * id;
1442 invP[6] = (-m[0]*m[6]*m[15] + m[0]*m[7]*m[14] + m[4]*m[2]*m[15] - m[4]*m[3]*m[14] - m[12]*m[2]*m[7] + m[12]*m[3]*m[6]) * id;
1443 invP[10] = ( m[0]*m[5]*m[15] - m[0]*m[7]*m[13] - m[4]*m[1]*m[15] + m[4]*m[3]*m[13] + m[12]*m[1]*m[7] - m[12]*m[3]*m[5]) * id;
1444 invP[14] = (-m[0]*m[5]*m[14] + m[0]*m[6]*m[13] + m[4]*m[1]*m[14] - m[4]*m[2]*m[13] - m[12]*m[1]*m[6] + m[12]*m[2]*m[5]) * id;
1445 invP[3] = (-m[1]*m[6]*m[11] + m[1]*m[7]*m[10] + m[5]*m[2]*m[11] - m[5]*m[3]*m[10] - m[9]*m[2]*m[7] + m[9]*m[3]*m[6]) * id;
1446 invP[7] = ( m[0]*m[6]*m[11] - m[0]*m[7]*m[10] - m[4]*m[2]*m[11] + m[4]*m[3]*m[10] + m[8]*m[2]*m[7] - m[8]*m[3]*m[6]) * id;
1447 invP[11] = (-m[0]*m[5]*m[11] + m[0]*m[7]*m[9] + m[4]*m[1]*m[11] - m[4]*m[3]*m[9] - m[8]*m[1]*m[7] + m[8]*m[3]*m[5]) * id;
1448 invP[15] = ( m[0]*m[5]*m[10] - m[0]*m[6]*m[9] - m[4]*m[1]*m[10] + m[4]*m[2]*m[9] + m[8]*m[1]*m[6] - m[8]*m[2]*m[5]) * id;
1449 }
1450 }
1451 std::memcpy(camData + 32, invP, sizeof(float) * 16);
1452
1453 glBindBuffer(GL_UNIFORM_BUFFER, m_ssaoCameraUBO);
1454 glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(camData), camData);
1455 glBindBuffer(GL_UNIFORM_BUFFER, 0);
1456
1457 // Bind UBOs at private slots 7/8/9 — slots 0-6 are used by the lighting
1458 // pass (LightUBO=2, ShadowUBO=5, DeferredCB=6, material/transform=0,1,3).
1459 // Binding SSAO's UBOs to those would silently nuke the lighting pass.
1460 glBindBufferBase(GL_UNIFORM_BUFFER, 7, m_ssaoSettingsUBO);
1461 glBindBufferBase(GL_UNIFORM_BUFFER, 8, m_ssaoKernelUBO);
1462 glBindBufferBase(GL_UNIFORM_BUFFER, 9, m_ssaoCameraUBO);
1463
1464 // ---- Pass 1: SSAO ----
1465 glBindFramebuffer(GL_FRAMEBUFFER, m_ssaoFBO);
1466 ApplyViewport(0, 0, m_gbufferWidth, m_gbufferHeight);
1467 glDisable(GL_DEPTH_TEST);
1468 glDepthMask(GL_FALSE);
1469 glDisable(GL_BLEND);
1470 glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
1471 glClear(GL_COLOR_BUFFER_BIT);
1472
1473 m_ssaoShader->bind();
1474 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_gbufferDepth);
1475 glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, m_gbufferNormalRough);
1476 glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, m_ssaoNoiseTex);
1477 glActiveTexture(GL_TEXTURE0);
1478
1479 glBindVertexArray(m_lightingVAO);
1480 glDrawArrays(GL_TRIANGLES, 0, 3);
1481
1482 // ---- Pass 2: Blur ----
1483 glBindFramebuffer(GL_FRAMEBUFFER, m_ssaoBlurFBO);
1484 glClear(GL_COLOR_BUFFER_BIT);
1485
1486 m_ssaoBlurShader->bind();
1487 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_ssaoTexture);
1488
1489 glDrawArrays(GL_TRIANGLES, 0, 3);
1490
1491 // Restore depth/blend state for the upcoming lighting pass
1492 glEnable(GL_DEPTH_TEST);
1493 glDepthMask(GL_TRUE);
1494
1495 glBindFramebuffer(GL_FRAMEBUFFER, 0);
1496}
1497
1498} // namespace RenderEngine
1499} // namespace Sleak
int width
int height
#define SLEAK_ERROR(...)
Definition Logger.hpp:22
#define SLEAK_INFO(...)
Definition Logger.hpp:20
#define SLEAK_WARN(...)
Definition Logger.hpp:21
static const Math::Matrix4 & GetMainProjectionMatrix()
Definition Camera.hpp:107
static const Math::Matrix4 & GetMainViewMatrix()
Definition Camera.hpp:103
void BindTexturesAndCB()
Binds textures and uploads the material CB for the deferred geometry pass, skipping the shader bind.
Definition Material.cpp:114
T * get() const
Definition RefPtr.hpp:170
Backend-agnostic GPU buffer: vertex, index, constant, or resource view target.
OpenGL VBO/EBO/UBO wrapper; target is derived from BufferType at construction.
OpenGLBuffer(uint32_t size, BufferType type)
static constexpr uint32_t PREFILTER_MIPS
Definition OpenGLIBL.hpp:25
virtual void SetDepthWrite(bool enabled) override
virtual Texture * CreateTexture(const std::string &TexturePath) override
Loads a texture from disk.
virtual void SetRenderFace(RenderFace face) override
virtual void DrawInstance(uint32_t instanceCount, uint32_t vertexPerInstance) override
Non-indexed instanced draw.
virtual void BindIndexBuffer(RefPtr< BufferBase > buffer, uint32_t slot=0) override
virtual void SetCullEnabled(bool enabled) override
virtual Shader * CreateShader(const std::string &shaderSource) override
Compiles a shader program from source or a source-file path.
virtual Texture * CreateTextureFromData(uint32_t width, uint32_t height, void *data) override
Creates a texture from an in-memory pixel buffer.
virtual void SetViewport(float x, float y, float width, float height, float minDepth=0.0f, float maxDepth=1.0f) override
Sets the active viewport rect and depth range in pixel/NDC units.
OpenGLRenderer(Window *window)
Registers this backend's buffer/shader/texture factories with ResourceManager.
virtual BufferBase * CreateBuffer(BufferType Type, uint32_t size, void *data) override
Allocates a backend buffer, optionally seeded with initial data.
virtual void BeginDebugLinePass() override
void BeginRender() override
Acquires the next frame and prepares it for command recording.
virtual void DrawIndexedInstance(uint32_t instanceCount, uint32_t indexPerInstance) override
Indexed instanced draw.
void EndRender() override
Submits recorded commands and presents the frame.
virtual void BindTexture(RefPtr< Sleak::Texture > texture, uint32_t slot=0) override
virtual void Resize(uint32_t width, uint32_t height) override
Recreates swapchain-dependent resources for a new surface size.
virtual void BindConstantBuffer(RefPtr< BufferBase > buffer, uint32_t slot=0) override
virtual void ClearDepthStencil(bool clearDepth, bool clearStencil, float depth, uint8_t stencil) override
virtual bool CreateImGUI() override
Initializes ImGui integration for this backend.
virtual void DrawIndexed(uint32_t indexCount) override
Indexed draw from the currently bound vertex/index buffers.
virtual void ClearRenderTarget(float r, float g, float b, float a) override
virtual void SetDepthCompare(DepthCompare compare) override
bool Initialize() override
Creates the device, swapchain, and backend resources.
Texture * CreateCubemapTextureFromPanorama(const std::string &panoramaPath)
Loads a cubemap by converting a single equirectangular panorama.
virtual void SetRenderMode(RenderMode mode) override
virtual void BindVertexBuffer(RefPtr< BufferBase > buffer, uint32_t slot=0) override
virtual void BindBoneBuffer(RefPtr< BufferBase > buffer) override
virtual void EndDebugLinePass() override
virtual void Draw(uint32_t vertexCount) override
Non-indexed draw from the currently bound vertex buffer.
Texture * CreateCubemapTexture(const std::array< std::string, 6 > &facePaths)
Loads a cubemap from six face image paths.
GLSL shader program compiled from either a combined source file or separate vertex/fragment files.
static RenderCommandQueue * GetInstance()
Lazily creates and returns the process-wide singleton instance.
virtual void ConfigureRenderMode()=0
Applies the current RenderMode (fill/wireframe/points) to backend state.
virtual void ConfigureRenderFace()=0
Applies the current RenderFace (cull mode) to backend state.
void UpdateFrameMetrics()
Rolls up frame count into rate/time/triangle stats once per MetricUpdateInterval.
Definition Renderer.hpp:267
void SetPerformanceCounter(bool value)
Definition Renderer.hpp:149
virtual bool ReloadShaders(const std::vector< std::string > &stems)
Definition Renderer.hpp:56
static void RegisterCreateCubemapTextureFromPanorama(T *instance, Texture *(T::*method)(const std::string &))
static void RegisterCreateCubemapTexture(T *instance, Texture *(T::*method)(const std::array< std::string, 6 > &))
static void RegisterCreateBuffer(T *instance, BufferBase *(T::*method)(BufferType, uint32_t, void *))
static void RegisterCreateShader(T *instance, Shader *(T::*method)(const std::string &))
static void RegisterCreateTextureFromMemory(std::function< Texture *(const void *, uint32_t, uint32_t, TextureFormat, uint32_t)> func)
static void RegisterCreateTexture(T *instance, Texture *(T::*method)(const std::string &))
Backend-agnostic compiled shader program.
Definition Shader.hpp:11
virtual bool IsValid() const
True if the pointer is non-null.
static const VertexLayoutDesc * Get(VertexFormatHandle handle)
SDL_Window * GetSDLWindow()
Returns the underlying SDL window handle.
Definition Window.hpp:43
TextureFormat
Definition Texture.hpp:10
Matrix< float, 4, 4 > Matrix4
Definition Matrix.hpp:404
Backend-facing rendering layer shared by the four graphics backends.
DepthCompare
Depth test comparison function.
RenderMode
Rasterizer fill style for a draw.
BufferType
GPU buffer usage kind, drives backend binding flags and layout.
RenderFace
Which triangle winding gets culled.
Root namespace for everything the engine exposes.
Definition Camera.hpp:10
static constexpr uint32_t MAX_KERNEL_SIZE
static constexpr uint32_t NOISE_SIZE
std::vector< VertexAttribute > attributes