SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
OpenGLRenderer.hpp
Go to the documentation of this file.
1#ifndef _OPENGLRENDERER_H
2#define _OPENGLRENDERER_H
3
4#include <SDL3/SDL.h>
5#include <backends/imgui_impl_opengl3.h>
6#include <glad/glad.h>
7#include <imgui.h>
8
9#include <Core/OSDef.hpp>
10#include <array>
11#include <cstdint>
12
13#include "../../Core/Window.hpp"
16
17namespace Sleak {
18
19struct VertexLayoutDesc;
20
21namespace RenderEngine {
22
23/// OpenGL 3.3+ backend: deferred GBuffer pipeline, SSAO, shadow mapping, and baked IBL.
24class ENGINE_API OpenGLRenderer : public Renderer, public RenderContext {
25public:
26 OpenGLRenderer(Window* window);
27 virtual ~OpenGLRenderer();
28
29 bool Initialize() override;
30 void BeginRender() override;
31 void EndRender() override;
32 void Cleanup() override;
33#ifdef SLEAK_HOT_RELOAD
34 /// Relinks every live shader built from one of the given stems.
35 bool ReloadShaders(const std::vector<std::string>& stems) override;
36#endif
37
38 virtual uint32_t GetFeatureCaps() const override {
40 }
41
42 virtual void Resize(uint32_t width, uint32_t height) override;
43
44 virtual bool CreateImGUI() override;
45
46 void ApplyMSAAChange() override;
47 void ApplyVSyncChange() override;
48
49 virtual RenderContext* GetContext() override { return this; }
50
51 // RenderContext interface
52 virtual void Draw(uint32_t vertexCount) override;
53 virtual void Draw(uint32_t vertexCount, uint32_t firstVertex) override;
54 virtual void DrawIndexed(uint32_t indexCount) override;
55 virtual void DrawIndexed(uint32_t indexCount, uint32_t firstIndex,
56 int32_t baseVertex) override;
57 virtual void DrawInstance(uint32_t instanceCount,
58 uint32_t vertexPerInstance) override;
59 virtual void DrawIndexedInstance(uint32_t instanceCount,
60 uint32_t indexPerInstance) override;
61 virtual void DrawIndexedInstance(uint32_t instanceCount,
62 uint32_t indexPerInstance,
63 uint32_t firstIndex,
64 int32_t baseVertex) override;
65
66 virtual void SetRenderFace(RenderFace face) override;
67 virtual void SetRenderMode(RenderMode mode) override;
68 virtual void SetViewport(float x, float y, float width, float height,
69 float minDepth = 0.0f,
70 float maxDepth = 1.0f) override;
71 virtual void ClearRenderTarget(float r, float g, float b,
72 float a) override;
73 virtual void ClearDepthStencil(bool clearDepth, bool clearStencil,
74 float depth, uint8_t stencil) override;
75
76 virtual void SetDepthWrite(bool enabled) override;
77 virtual void SetDepthCompare(DepthCompare compare) override;
78 virtual void SetCullEnabled(bool enabled) override;
79 virtual void BindTexture(RefPtr<Sleak::Texture> texture, uint32_t slot = 0) override;
80
81 virtual void BindVertexBuffer(RefPtr<BufferBase> buffer,
82 uint32_t slot = 0) override;
83 virtual void BindIndexBuffer(RefPtr<BufferBase> buffer,
84 uint32_t slot = 0) override;
85 virtual void BindConstantBuffer(RefPtr<BufferBase> buffer,
86 uint32_t slot = 0) override;
87 virtual void BindBoneBuffer(RefPtr<BufferBase> buffer) override;
88
89 virtual void BeginDebugLinePass() override;
90 virtual void EndDebugLinePass() override;
91
92 virtual BufferBase* CreateBuffer(BufferType Type, uint32_t size,
93 void* data) override;
94 virtual Shader* CreateShader(const std::string& shaderSource) override;
95 virtual Texture* CreateTexture(const std::string& TexturePath) override;
96 virtual Texture* CreateTextureFromData(uint32_t width, uint32_t height,
97 void* data) override;
98
99 /// Loads a cubemap from six face image paths.
100 Texture* CreateCubemapTexture(const std::array<std::string, 6>& facePaths);
101 /// Loads a cubemap by converting a single equirectangular panorama.
102 Texture* CreateCubemapTextureFromPanorama(const std::string& panoramaPath);
103
104private:
105 Window* m_Window;
106 SDL_GLContext m_GLContext = nullptr;
107 bool m_Initialized = false;
108
109 GLuint m_VAO = 0;
110 bool m_debugLineMode = false;
111
112 // Vertex layout currently applied to m_VAO
113 static constexpr uint32_t NO_CONFIGURED_LAYOUT = UINT32_MAX;
114 uint32_t m_configuredLayout = NO_CONFIGURED_LAYOUT;
115 const VertexLayoutDesc* m_configuredLayoutDesc = nullptr;
116 uint32_t m_enabledAttribMask = 0;
117
118 // Last viewport set outside the shadow pass (x, y, width, height)
119 std::array<GLint, 4> m_viewport = {};
120 /// Sets the GL viewport and records it so passes can restore it later.
121 void ApplyViewport(GLint x, GLint y, GLsizei width, GLsizei height);
122
123 // MSAA FBO resources
124 GLuint m_msaaFBO = 0;
125 GLuint m_msaaColorRBO = 0;
126 GLuint m_msaaDepthRBO = 0;
127 /// Allocates the multisampled color/depth renderbuffers sized to the current swapchain.
128 void CreateMSAAFramebuffer();
129 void CleanupMSAAFramebuffer();
130
131 virtual void ConfigureRenderMode() override;
132 virtual void ConfigureRenderFace() override;
133
134 /// Creates the shared mesh VAO and resets its cached attribute layout.
135 void SetupVertexLayout();
136 /// Applies a vertex layout's attribute formats to m_VAO unless it is
137 /// already the active one; a null desc selects the default Vertex.
138 void ConfigureVertexLayout(uint32_t layout, const VertexLayoutDesc* desc);
139
140 // Shadow mapping
141 GLuint m_shadowFBO = 0;
142 GLuint m_shadowDepthTex = 0;
143 GLuint m_shadowUBO = 0;
144 bool m_shadowMapCreated = false;
145 bool m_shadowUBOCreated = false;
146 float m_lightVP[16] = {};
147 float m_pendingLightVP[16] = {};
148 bool m_hasPendingLightVP = false;
149 // Matrix the shadow map was last rendered with
150 float m_shadowMapLightVP[16] = {};
151 bool m_shadowMapRendered = false;
152 bool m_inShadowPass = false;
153 GLuint m_shadowTransformUBO = 0;
154 // Last shadow transform uploaded: [LightVP*World][World], keyed on World
155 float m_shadowTransformCache[32] = {};
156 float m_shadowWorldCache[16] = {};
157 bool m_shadowTransformCacheValid = false;
158 void SetLightVP(const float* mat) override;
159 /// Uploads light and shadow data, sampling with the matrix the shadow
160 /// map was rendered with.
161 void UpdateShadowLightUBO(const void* data, uint32_t size) override;
162 /// Allocates the shadow-pass depth FBO and texture at the configured resolution.
163 bool CreateShadowMapResources();
164 /// Allocates the UBO backing ShadowLightUBO.
165 bool CreateShadowUBO();
166 /// Replays cached shadow-caster draws into the depth-only shadow FBO.
167 void RenderShadowPass();
168
169 // ---- Deferred rendering (GBuffer) ----
170 // Deferred mode overrides
171 virtual bool IsDeferredEnabled() const override;
172 virtual bool IsInGeometryPass() const override { return m_inGeometryPass; }
173 virtual void BindGBufferShader() override;
174 virtual void BindPBRMaterial(Sleak::Material* material) override;
175 virtual void ExecuteDeferredLightingPass() override;
176 virtual void BeginForwardTransparentPass() override;
177 virtual void EndForwardTransparentPass() override;
178 virtual void UpdateDeferredCB(const void* data, uint32_t size) override;
179
180 // GBuffer FBO + textures
181 GLuint m_gbufferFBO = 0;
182 GLuint m_gbufferAlbedoAO = 0; // RT0: RGBA8 — Albedo + AO
183 GLuint m_gbufferNormalRough = 0; // RT1: RGBA16F — Normal + Roughness
184 GLuint m_gbufferMetalEmit = 0; // RT2: RGBA8 — Metallic + EmissiveScale
185 GLuint m_gbufferDepth = 0; // Depth texture (world pos reconstructed)
186 bool m_gbufferCreated = false;
187 int m_gbufferWidth = 0;
188 int m_gbufferHeight = 0;
189
190 // GBuffer + lighting pass shaders
191 class OpenGLShader* m_gbufferShader = nullptr; // geometry pass shader
192 class OpenGLShader* m_lightingShader = nullptr; // lighting pass shader
193 GLuint m_lightingVAO = 0; // empty VAO for fullscreen triangle
194
195 // Deferred CB UBO (InvViewProj + screen size; bound at slot 6)
196 GLuint m_deferredCBUBO = 0;
197 bool m_deferredCBCreated = false;
198
199 bool m_inGeometryPass = false;
200 bool m_inForwardTransparentPass = false;
201
202 /// Allocates the GBuffer FBO and its albedo/normal/metal-emit/depth attachments.
203 bool CreateGBufferResources();
204 void CleanupGBufferResources();
205 /// Tears down and reallocates the GBuffer at a new swapchain size.
206 void RecreateGBufferOnResize(int width, int height);
207
208 // ---- SSAO ----
209 GLuint m_ssaoFBO = 0;
210 GLuint m_ssaoTexture = 0; // R8: raw AO
211 GLuint m_ssaoBlurFBO = 0;
212 GLuint m_ssaoBlurTex = 0; // R8: blurred AO (consumed by lighting)
213 GLuint m_ssaoNoiseTex = 0; // 4x4 RGBA16F
214 GLuint m_ssaoSettingsUBO = 0; // binding 0
215 GLuint m_ssaoKernelUBO = 0; // binding 1
216 GLuint m_ssaoCameraUBO = 0; // binding 2 (Projection/View/InvProjection)
217 class OpenGLShader* m_ssaoShader = nullptr;
218 class OpenGLShader* m_ssaoBlurShader = nullptr;
219 bool m_ssaoCreated = false;
220
221 /// Allocates the SSAO/blur FBOs, noise texture, and kernel/settings UBOs.
222 bool CreateSSAOResources();
223 void CleanupSSAOResources();
224 /// Tears down and reallocates SSAO targets at a new swapchain size.
225 void RecreateSSAOOnResize(int width, int height);
226 /// Runs the SSAO sample pass followed by the blur pass into m_ssaoBlurTex.
227 void ExecuteSSAOPass();
228
229 // ---- IBL (Image-Based Lighting) ----
230 class OpenGLIBL* m_ibl = nullptr;
231 GLuint m_iblSettingsUBO = 0; // binding 10 in lighting_pass_gl.frag
232 GLuint m_iblBoundCubemap = 0; // last skybox cubemap we baked from
233 /// Lazily (re)bakes IBL data when the bound skybox cubemap changes.
234 void EnsureIBL();
235 void CleanupIBL();
236
237 // ---- Scene read for transparent formats ----
238 static constexpr GLuint SCENE_COLOR_UNIT = 4;
239 static constexpr GLuint SCENE_DEPTH_UNIT = 5;
240 static constexpr GLuint SCENE_SKY_UNIT = 6;
241 static constexpr GLuint SCENE_READ_UBO_BINDING = 4;
242 GLuint m_sceneCopyTex = 0; // RGBA8 snapshot of the default framebuffer
243 int m_sceneCopyWidth = 0;
244 int m_sceneCopyHeight = 0;
245 GLuint m_sceneReadUBO = 0;
246 GLuint m_sceneFallbackCube = 0;
247 GLuint m_sceneSkyCube = 0; // skybox cubemap found this frame, 0 if none
248 bool m_sceneReadPrepared = false; // snapshot taken this frame
249 float m_cachedInvViewProj[16] = {};
250 float m_cachedNearPlane = 0.0f;
251 float m_cachedFarPlane = 0.0f;
252 /// Returns the active scene's skybox cubemap, or 0 when there is none.
253 GLuint FindSkyboxCubemap() const;
254 /// Snapshots the scene once per frame on the first scene-reading draw
255 /// and binds the snapshot, depth, sky, and SceneReadUBO.
256 void PrepareSceneRead();
257 /// Deletes the snapshot texture, stand-in cubemap, and UBO.
258 void CleanupSceneRead();
259};
260
261} // namespace RenderEngine
262} // namespace Sleak
263
264#endif // _OPENGLRENDERER_H
int width
int height
Backend-agnostic GPU buffer: vertex, index, constant, or resource view target.
virtual RenderContext * GetContext() override
Returns the backend's command-recording interface.
virtual uint32_t GetFeatureCaps() const override
Feature capability mask; backends override with the audited truth.
OpenGLRenderer(Window *window)
Registers this backend's buffer/shader/texture factories with ResourceManager.
void BeginRender() override
Acquires the next frame and prepares it for command recording.
void EndRender() override
Submits recorded commands and presents the frame.
bool Initialize() override
Creates the device, swapchain, and backend resources.
Abstract interface for high-level graphics command execution and resource management.
Abstract render backend: swapchain, frame lifecycle, and post-effect toggles.
Definition Renderer.hpp:41
virtual bool ReloadShaders(const std::vector< std::string > &stems)
Definition Renderer.hpp:56
Backend-agnostic compiled shader program.
Definition Shader.hpp:11
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