NoJobEngine 2.0.7
Loading...
Searching...
No Matches
SceneRenderer.cpp
Go to the documentation of this file.
2#include "Engine/Core/Log.h"
13
14#include <glad/gl.h>
15#include <glm/gtc/matrix_transform.hpp>
16#include <algorithm>
17#include <array>
18#include <cmath>
19#include <string>
20#include <filesystem>
21#include <iostream>
22#include <chrono>
23#include <cstddef>
24#include <vector>
25#include <unordered_map>
26#include <stb_image.h>
27
28namespace NoJob
29{
30 namespace
31 {
32 struct ShadowResources
33 {
34 GLuint FBO = 0;
35 GLuint Directional = 0;
36 GLuint Spot = 0;
37 GLuint Point = 0;
38 GLuint SkyVAO = 0;
39 std::shared_ptr<Shader> DepthShader;
40 std::shared_ptr<Shader> SkyShader;
41
42 // Renderer V3 environment resources.
43 GLuint Environment = 0;
44 GLuint Irradiance = 0;
45 GLuint Prefilter = 0;
46 GLuint BRDFLUT = 0;
47 GLuint CaptureFBO = 0;
48 GLuint CaptureRBO = 0;
49 std::string LoadedEnvironmentPath;
50 std::uint32_t LoadedEnvironmentResolution = 0;
51 bool EnvironmentReady = false;
52
53 int AllocatedShadowQuality = -1;
54 GLuint GPUQueries[3]{0,0,0};
55 std::uint32_t GPUQueryWrite = 0;
56 bool GPUQueryIssued[3]{false,false,false};
57 glm::mat4 DirectionalMatrix{1.0f};
58 glm::mat4 SpotMatrix{1.0f};
59 glm::vec3 PointPosition{0.0f};
60 float PointFar = 25.0f;
61 bool HasDirectional = false;
62 bool HasSpot = false;
63 bool HasPoint = false;
64 };
65
66 ShadowResources& Shadows()
67 {
68 static ShadowResources resources;
69 return resources;
70 }
71
72 FramebufferSpecification& RendererSettings()
73 {
74 static FramebufferSpecification settings;
75 return settings;
76 }
77
78
79 RendererStatistics& Statistics()
80 {
81 static RendererStatistics statistics;
82 return statistics;
83 }
84
85 std::uint64_t MeshIndexCount(const std::shared_ptr<Mesh>& mesh)
86 {
87 if (!mesh || !mesh->GetVertexArray() ||
88 !mesh->GetVertexArray()->GetIndexBuffer())
89 return 0;
90 return mesh->GetVertexArray()->GetIndexBuffer()->GetCount();
91 }
92
93 void BeginGPUFrameQuery()
94 {
95 auto& r = Shadows();
96 if (r.GPUQueries[0] == 0)
97 glGenQueries(3, r.GPUQueries);
98
99 // Read a result only when OpenGL says it is ready. This avoids
100 // stalling the CPU just to display profiler information.
101 const std::uint32_t read = (r.GPUQueryWrite + 1) % 3;
102 if (r.GPUQueryIssued[read])
103 {
104 GLint available = GL_FALSE;
105 glGetQueryObjectiv(
106 r.GPUQueries[read], GL_QUERY_RESULT_AVAILABLE, &available);
107 if (available == GL_TRUE)
108 {
109 GLuint64 nanoseconds = 0;
110 glGetQueryObjectui64v(
111 r.GPUQueries[read], GL_QUERY_RESULT, &nanoseconds);
112 Statistics().GPUTimeMs =
113 static_cast<float>(nanoseconds) / 1000000.0f;
114 Statistics().GPUTimeValid = true;
115 r.GPUQueryIssued[read] = false;
116 }
117 }
118 glBeginQuery(GL_TIME_ELAPSED, r.GPUQueries[r.GPUQueryWrite]);
119 }
120
121 void EndGPUFrameQuery()
122 {
123 auto& r = Shadows();
124 glEndQuery(GL_TIME_ELAPSED);
125 r.GPUQueryIssued[r.GPUQueryWrite] = true;
126 r.GPUQueryWrite = (r.GPUQueryWrite + 1) % 3;
127 }
128
129 glm::vec3 WorldPosition(const glm::mat4& world)
130 {
131 return glm::vec3(world[3]);
132 }
133
134 glm::vec3 WorldForward(const glm::mat4& world)
135 {
136 glm::vec3 forward = -glm::vec3(world[2]);
137 const float length = glm::length(forward);
138 return length > 0.0001f ? forward / length
139 : glm::vec3(0.0f, 0.0f, -1.0f);
140 }
141
142
143 GLuint CompileEnvironmentProgram(
144 const char* vertexSource, const char* fragmentSource)
145 {
146 auto compile=[](GLenum type,const char* source)->GLuint
147 {
148 GLuint shader=glCreateShader(type);
149 glShaderSource(shader,1,&source,nullptr);
150 glCompileShader(shader);
151 GLint ok=GL_FALSE;
152 glGetShaderiv(shader,GL_COMPILE_STATUS,&ok);
153 if(ok!=GL_TRUE)
154 {
155 GLint length=0;
156 glGetShaderiv(shader,GL_INFO_LOG_LENGTH,&length);
157 std::string log(static_cast<std::size_t>(length),'\0');
158 glGetShaderInfoLog(shader,length,nullptr,log.data());
159 glDeleteShader(shader);
160 throw std::runtime_error(
161 "Renderer V3 environment shader compile failed: "+log);
162 }
163 return shader;
164 };
165 GLuint vs=compile(GL_VERTEX_SHADER,vertexSource);
166 GLuint fs=compile(GL_FRAGMENT_SHADER,fragmentSource);
167 GLuint program=glCreateProgram();
168 glAttachShader(program,vs);glAttachShader(program,fs);
169 glLinkProgram(program);
170 glDeleteShader(vs);glDeleteShader(fs);
171 GLint ok=GL_FALSE;glGetProgramiv(program,GL_LINK_STATUS,&ok);
172 if(ok!=GL_TRUE)
173 {
174 GLint length=0;glGetProgramiv(program,GL_INFO_LOG_LENGTH,&length);
175 std::string log(static_cast<std::size_t>(length),'\0');
176 glGetProgramInfoLog(program,length,nullptr,log.data());
177 glDeleteProgram(program);
178 throw std::runtime_error(
179 "Renderer V3 environment shader link failed: "+log);
180 }
181 return program;
182 }
183
184 void DrawCaptureCube()
185 {
186 static GLuint vao=0;
187 if(!vao) glCreateVertexArrays(1,&vao);
188 glBindVertexArray(vao);
189 glDrawArrays(GL_TRIANGLES,0,36);
190 }
191
192 void DeleteEnvironmentTextures(ShadowResources& r)
193 {
194 if(r.Environment) glDeleteTextures(1,&r.Environment);
195 if(r.Irradiance) glDeleteTextures(1,&r.Irradiance);
196 if(r.Prefilter) glDeleteTextures(1,&r.Prefilter);
197 if(r.BRDFLUT) glDeleteTextures(1,&r.BRDFLUT);
198 r.Environment=r.Irradiance=r.Prefilter=r.BRDFLUT=0;
199 r.EnvironmentReady=false;
200 }
201
202 const char* CaptureCubeVS=R"(
203 #version 460 core
204 out vec3 v_Direction;
205 uniform mat4 u_ViewProjection;
206 const vec3 P[36]=vec3[](
207 vec3(-1,-1,-1),vec3(-1,-1, 1),vec3(-1, 1, 1),vec3(-1,-1,-1),vec3(-1, 1, 1),vec3(-1, 1,-1),
208 vec3( 1,-1, 1),vec3( 1,-1,-1),vec3( 1, 1,-1),vec3( 1,-1, 1),vec3( 1, 1,-1),vec3( 1, 1, 1),
209 vec3(-1,-1, 1),vec3( 1,-1, 1),vec3( 1, 1, 1),vec3(-1,-1, 1),vec3( 1, 1, 1),vec3(-1, 1, 1),
210 vec3( 1,-1,-1),vec3(-1,-1,-1),vec3(-1, 1,-1),vec3( 1,-1,-1),vec3(-1, 1,-1),vec3( 1, 1,-1),
211 vec3(-1, 1, 1),vec3( 1, 1, 1),vec3( 1, 1,-1),vec3(-1, 1, 1),vec3( 1, 1,-1),vec3(-1, 1,-1),
212 vec3(-1,-1,-1),vec3( 1,-1,-1),vec3( 1,-1, 1),vec3(-1,-1,-1),vec3( 1,-1, 1),vec3(-1,-1, 1));
213 void main(){v_Direction=P[gl_VertexID];gl_Position=u_ViewProjection*vec4(v_Direction,1.0);}
214 )";
215
216 void EnsureEnvironmentResources()
217 {
218 auto& r=Shadows();
219 const auto& settings=RendererSettings();
220 const std::string& configuredPath=settings.EnvironmentHDRIPath;
221 const std::filesystem::path environmentPath =
222 AssetManager::ResolveProjectPath(configuredPath);
223 const std::string path = environmentPath.string();
224
225 if(configuredPath.empty())
226 {
227 if(r.EnvironmentReady) DeleteEnvironmentTextures(r);
228 r.LoadedEnvironmentPath.clear();
229 return;
230 }
231 if(r.EnvironmentReady &&
232 r.LoadedEnvironmentPath==path &&
233 r.LoadedEnvironmentResolution==settings.EnvironmentResolution)
234 return;
235
236 int width=0,height=0,channels=0;
237 stbi_set_flip_vertically_on_load(1);
238 float* pixels=stbi_loadf(path.c_str(),&width,&height,&channels,3);
239 stbi_set_flip_vertically_on_load(0);
240 if(!pixels)
241 {
242 if(r.LoadedEnvironmentPath!=path)
243 std::cerr<<"[Renderer V3] Could not load HDRI: "<<path<<"\n";
244 r.LoadedEnvironmentPath=path;
245 r.EnvironmentReady=false;
246 return;
247 }
248
249 GLint previousViewport[4]{};
250 GLint previousFramebuffer = 0;
251 glGetIntegerv(GL_VIEWPORT, previousViewport);
252 glGetIntegerv(GL_FRAMEBUFFER_BINDING, &previousFramebuffer);
253
254 DeleteEnvironmentTextures(r);
255 if(!r.CaptureFBO) glCreateFramebuffers(1,&r.CaptureFBO);
256 if(!r.CaptureRBO) glCreateRenderbuffers(1,&r.CaptureRBO);
257
258 GLuint hdr=0;
259 glCreateTextures(GL_TEXTURE_2D,1,&hdr);
260 glTextureStorage2D(hdr,1,GL_RGB16F,width,height);
261 glTextureSubImage2D(
262 hdr,0,0,0,width,height,GL_RGB,GL_FLOAT,pixels);
263 glTextureParameteri(hdr,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
264 glTextureParameteri(hdr,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
265 glTextureParameteri(hdr,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
266 glTextureParameteri(hdr,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
267 stbi_image_free(pixels);
268
269 const std::uint32_t size=
270 std::clamp(settings.EnvironmentResolution,128u,1024u);
271 int mipLevels=1;
272 for(std::uint32_t v=size;v>1;v/=2) ++mipLevels;
273
274 auto makeCube=[](GLuint& id,int resolution,int levels)
275 {
276 glCreateTextures(GL_TEXTURE_CUBE_MAP,1,&id);
277 glTextureStorage2D(
278 id,levels,GL_RGB16F,resolution,resolution);
279 glTextureParameteri(
280 id,GL_TEXTURE_MIN_FILTER,
281 levels>1?GL_LINEAR_MIPMAP_LINEAR:GL_LINEAR);
282 glTextureParameteri(id,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
283 glTextureParameteri(id,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
284 glTextureParameteri(id,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
285 glTextureParameteri(id,GL_TEXTURE_WRAP_R,GL_CLAMP_TO_EDGE);
286 };
287 makeCube(r.Environment,size,mipLevels);
288 makeCube(r.Irradiance,32,1);
289 makeCube(r.Prefilter,128,5);
290
291 glCreateTextures(GL_TEXTURE_2D,1,&r.BRDFLUT);
292 glTextureStorage2D(r.BRDFLUT,1,GL_RG16F,512,512);
293 glTextureParameteri(r.BRDFLUT,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
294 glTextureParameteri(r.BRDFLUT,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
295 glTextureParameteri(r.BRDFLUT,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
296 glTextureParameteri(r.BRDFLUT,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
297
298 const glm::mat4 projection=glm::perspective(
299 glm::radians(90.0f),1.0f,0.1f,10.0f);
300 const glm::mat4 views[]={
301 glm::lookAt(glm::vec3(0),glm::vec3( 1,0,0),glm::vec3(0,-1,0)),
302 glm::lookAt(glm::vec3(0),glm::vec3(-1,0,0),glm::vec3(0,-1,0)),
303 glm::lookAt(glm::vec3(0),glm::vec3(0, 1,0),glm::vec3(0,0, 1)),
304 glm::lookAt(glm::vec3(0),glm::vec3(0,-1,0),glm::vec3(0,0,-1)),
305 glm::lookAt(glm::vec3(0),glm::vec3(0,0, 1),glm::vec3(0,-1,0)),
306 glm::lookAt(glm::vec3(0),glm::vec3(0,0,-1),glm::vec3(0,-1,0))};
307
308 const char* equirectFS=R"(
309 #version 460 core
310 in vec3 v_Direction;out vec4 o_Color;
311 uniform sampler2D u_HDR;
312 const vec2 invAtan=vec2(0.159154943,0.318309886);
313 void main(){vec3 d=normalize(v_Direction);vec2 uv=vec2(atan(d.z,d.x),asin(d.y));uv*=invAtan;uv+=0.5;o_Color=vec4(texture(u_HDR,uv).rgb,1);}
314 )";
315 GLuint program=CompileEnvironmentProgram(CaptureCubeVS,equirectFS);
316 glUseProgram(program);glBindTextureUnit(0,hdr);
317 glUniform1i(glGetUniformLocation(program,"u_HDR"),0);
318 glNamedRenderbufferStorage(
319 r.CaptureRBO,GL_DEPTH_COMPONENT24,size,size);
320 glNamedFramebufferRenderbuffer(
321 r.CaptureFBO,GL_DEPTH_ATTACHMENT,GL_RENDERBUFFER,r.CaptureRBO);
322 glBindFramebuffer(GL_FRAMEBUFFER,r.CaptureFBO);
323 glViewport(0,0,size,size);
324 for(int face=0;face<6;++face)
325 {
326 glm::mat4 vp=projection*views[face];
327 glUniformMatrix4fv(
328 glGetUniformLocation(program,"u_ViewProjection"),
329 1,GL_FALSE,&vp[0][0]);
330 glNamedFramebufferTextureLayer(
331 r.CaptureFBO,GL_COLOR_ATTACHMENT0,r.Environment,0,face);
332 glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
333 DrawCaptureCube();
334 }
335 glGenerateTextureMipmap(r.Environment);
336 glDeleteProgram(program);glDeleteTextures(1,&hdr);
337
338 const char* irradianceFS=R"(
339 #version 460 core
340 in vec3 v_Direction;out vec4 o_Color;uniform samplerCube u_Environment;
341 const float PI=3.14159265359;
342 void main(){vec3 N=normalize(v_Direction);vec3 up=vec3(0,1,0);vec3 right=normalize(cross(up,N));up=normalize(cross(N,right));vec3 irradiance=vec3(0);float samples=0;
343 for(float phi=0;phi<2*PI;phi+=0.12)for(float theta=0;theta<0.5*PI;theta+=0.12){vec3 t=vec3(sin(theta)*cos(phi),sin(theta)*sin(phi),cos(theta));vec3 s=t.x*right+t.y*up+t.z*N;irradiance+=texture(u_Environment,s).rgb*cos(theta)*sin(theta);samples++;}
344 irradiance=PI*irradiance/max(samples,1.0);o_Color=vec4(irradiance,1);}
345 )";
346 program=CompileEnvironmentProgram(CaptureCubeVS,irradianceFS);
347 glUseProgram(program);glBindTextureUnit(0,r.Environment);
348 glUniform1i(glGetUniformLocation(program,"u_Environment"),0);
349 glNamedRenderbufferStorage(r.CaptureRBO,GL_DEPTH_COMPONENT24,32,32);
350 glViewport(0,0,32,32);
351 for(int face=0;face<6;++face)
352 {
353 glm::mat4 vp=projection*views[face];
354 glUniformMatrix4fv(glGetUniformLocation(program,"u_ViewProjection"),1,GL_FALSE,&vp[0][0]);
355 glNamedFramebufferTextureLayer(r.CaptureFBO,GL_COLOR_ATTACHMENT0,r.Irradiance,0,face);
356 glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);DrawCaptureCube();
357 }
358 glDeleteProgram(program);
359
360 const char* prefilterFS=R"(
361 #version 460 core
362 in vec3 v_Direction;out vec4 o_Color;uniform samplerCube u_Environment;uniform float u_Roughness;
363 const float PI=3.14159265359;
364 float RadicalInverse(uint bits){bits=(bits<<16u)|(bits>>16u);bits=((bits&0x55555555u)<<1u)|((bits&0xAAAAAAAAu)>>1u);bits=((bits&0x33333333u)<<2u)|((bits&0xCCCCCCCCu)>>2u);bits=((bits&0x0F0F0F0Fu)<<4u)|((bits&0xF0F0F0F0u)>>4u);bits=((bits&0x00FF00FFu)<<8u)|((bits&0xFF00FF00u)>>8u);return float(bits)*2.3283064365386963e-10;}
365 vec2 Hammersley(uint i,uint n){return vec2(float(i)/float(n),RadicalInverse(i));}
366 vec3 ImportanceGGX(vec2 Xi,vec3 N,float rough){float a=rough*rough;float phi=2*PI*Xi.x;float cosTheta=sqrt((1-Xi.y)/(1+(a*a-1)*Xi.y));float sinTheta=sqrt(max(0,1-cosTheta*cosTheta));vec3 H=vec3(cos(phi)*sinTheta,sin(phi)*sinTheta,cosTheta);vec3 up=abs(N.z)<0.999?vec3(0,0,1):vec3(1,0,0);vec3 tangent=normalize(cross(up,N));vec3 bitangent=cross(N,tangent);return normalize(tangent*H.x+bitangent*H.y+N*H.z);}
367 void main(){vec3 N=normalize(v_Direction),R=N,V=R;vec3 pre=vec3(0);float weight=0;const uint COUNT=256u;for(uint i=0u;i<COUNT;i++){vec3 H=ImportanceGGX(Hammersley(i,COUNT),N,u_Roughness);vec3 L=normalize(2*dot(V,H)*H-V);float NL=max(dot(N,L),0);if(NL>0){pre+=textureLod(u_Environment,L,u_Roughness*4.0).rgb*NL;weight+=NL;}}o_Color=vec4(pre/max(weight,0.001),1);}
368 )";
369 program=CompileEnvironmentProgram(CaptureCubeVS,prefilterFS);
370 glUseProgram(program);glBindTextureUnit(0,r.Environment);
371 glUniform1i(glGetUniformLocation(program,"u_Environment"),0);
372 for(int mip=0;mip<5;++mip)
373 {
374 int mipSize=128>>mip;
375 glNamedRenderbufferStorage(r.CaptureRBO,GL_DEPTH_COMPONENT24,mipSize,mipSize);
376 glViewport(0,0,mipSize,mipSize);
377 glUniform1f(glGetUniformLocation(program,"u_Roughness"),float(mip)/4.0f);
378 for(int face=0;face<6;++face)
379 {
380 glm::mat4 vp=projection*views[face];
381 glUniformMatrix4fv(glGetUniformLocation(program,"u_ViewProjection"),1,GL_FALSE,&vp[0][0]);
382 glNamedFramebufferTextureLayer(r.CaptureFBO,GL_COLOR_ATTACHMENT0,r.Prefilter,mip,face);
383 glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);DrawCaptureCube();
384 }
385 }
386 glDeleteProgram(program);
387
388 const char* fullscreenVS=R"(
389 #version 460 core
390 out vec2 v_UV;
391 void main(){vec2 p=vec2((gl_VertexID<<1)&2,gl_VertexID&2);v_UV=p;gl_Position=vec4(p*2.0-1.0,0,1);}
392 )";
393 const char* brdfFS=R"(
394 #version 460 core
395 in vec2 v_UV;out vec2 o_BRDF;const float PI=3.14159265359;
396 float RadicalInverse(uint bits){bits=(bits<<16u)|(bits>>16u);bits=((bits&0x55555555u)<<1u)|((bits&0xAAAAAAAAu)>>1u);bits=((bits&0x33333333u)<<2u)|((bits&0xCCCCCCCCu)>>2u);bits=((bits&0x0F0F0F0Fu)<<4u)|((bits&0xF0F0F0F0u)>>4u);bits=((bits&0x00FF00FFu)<<8u)|((bits&0xFF00FF00u)>>8u);return float(bits)*2.3283064365386963e-10;}
397 vec2 Hammersley(uint i,uint n){return vec2(float(i)/float(n),RadicalInverse(i));}
398 vec3 ImportanceGGX(vec2 Xi,vec3 N,float rough){float a=rough*rough;float phi=2*PI*Xi.x;float cosTheta=sqrt((1-Xi.y)/(1+(a*a-1)*Xi.y));float sinTheta=sqrt(max(0,1-cosTheta*cosTheta));vec3 H=vec3(cos(phi)*sinTheta,sin(phi)*sinTheta,cosTheta);return H;}
399 float G1(float NV,float rough){float k=(rough*rough)*0.5;return NV/(NV*(1-k)+k);}
400 vec2 Integrate(float NV,float rough){vec3 V=vec3(sqrt(max(0,1-NV*NV)),0,NV);float A=0,B=0;const uint COUNT=256u;for(uint i=0u;i<COUNT;i++){vec3 H=ImportanceGGX(Hammersley(i,COUNT),vec3(0,0,1),rough);vec3 L=normalize(2*dot(V,H)*H-V);float NL=max(L.z,0),NH=max(H.z,0),VH=max(dot(V,H),0);if(NL>0){float G=G1(NV,rough)*G1(NL,rough);float vis=(G*VH)/max(NH*NV,0.001);float Fc=pow(1-VH,5);A+=(1-Fc)*vis;B+=Fc*vis;}}return vec2(A,B)/float(COUNT);}
401 void main(){o_BRDF=Integrate(v_UV.x,v_UV.y);}
402 )";
403 program=CompileEnvironmentProgram(fullscreenVS,brdfFS);
404 glUseProgram(program);
405 glNamedFramebufferTexture(r.CaptureFBO,GL_COLOR_ATTACHMENT0,r.BRDFLUT,0);
406 glNamedRenderbufferStorage(r.CaptureRBO,GL_DEPTH_COMPONENT24,512,512);
407 glViewport(0,0,512,512);glClear(GL_COLOR_BUFFER_BIT);
408 static GLuint fsVao=0;if(!fsVao)glCreateVertexArrays(1,&fsVao);
409 glBindVertexArray(fsVao);glDrawArrays(GL_TRIANGLES,0,3);
410 glDeleteProgram(program);
411
412 glBindFramebuffer(
413 GL_FRAMEBUFFER, static_cast<GLuint>(previousFramebuffer));
414 glViewport(
415 previousViewport[0], previousViewport[1],
416 previousViewport[2], previousViewport[3]);
417 r.LoadedEnvironmentPath=path;
418 r.LoadedEnvironmentResolution=size;
419 r.EnvironmentReady=true;
420 std::cout<<"[Renderer V3] HDRI ready: "<<path<<"\n";
421 }
422
423 void EnsureShadowResources()
424 {
425 auto& s = Shadows();
426
427 if (s.FBO == 0)
428 glCreateFramebuffers(1, &s.FBO);
429
430 const int quality = std::clamp(RendererSettings().ShadowQuality, 0, 2);
431 if (s.AllocatedShadowQuality != quality)
432 {
433 if (s.Directional) glDeleteTextures(1, &s.Directional);
434 if (s.Spot) glDeleteTextures(1, &s.Spot);
435 if (s.Point) glDeleteTextures(1, &s.Point);
436 s.Directional = s.Spot = s.Point = 0;
437
438 const int directionalSizes[] = {1024, 2048, 4096};
439 const int spotSizes[] = {512, 1024, 2048};
440 const int pointSizes[] = {256, 512, 1024};
441
442 auto createDepth2D = [](GLuint& texture, int size)
443 {
444 glCreateTextures(GL_TEXTURE_2D, 1, &texture);
445 glTextureStorage2D(
446 texture, 1, GL_DEPTH_COMPONENT32F, size, size);
447 glTextureParameteri(
448 texture, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
449 glTextureParameteri(
450 texture, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
451 glTextureParameteri(
452 texture, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
453 glTextureParameteri(
454 texture, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
455 const float border[] = {1,1,1,1};
456 glTextureParameterfv(
457 texture, GL_TEXTURE_BORDER_COLOR, border);
458 };
459
460 createDepth2D(s.Directional, directionalSizes[quality]);
461 createDepth2D(s.Spot, spotSizes[quality]);
462
463 glCreateTextures(GL_TEXTURE_CUBE_MAP, 1, &s.Point);
464 glTextureStorage2D(
465 s.Point, 1, GL_DEPTH_COMPONENT32F,
466 pointSizes[quality], pointSizes[quality]);
467 glTextureParameteri(
468 s.Point, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
469 glTextureParameteri(
470 s.Point, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
471 glTextureParameteri(
472 s.Point, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
473 glTextureParameteri(
474 s.Point, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
475 glTextureParameteri(
476 s.Point, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
477
478 s.AllocatedShadowQuality = quality;
479 }
480
481 // Shader/VAO creation only happens once; texture resolution can be
482 // changed independently at runtime.
483 if (s.DepthShader)
484 return;
485
486 const std::string depthVS = R"(
487 #version 460 core
488 layout(location=0) in vec3 a_Position;
489 layout(location=2) in vec2 a_TexCoord;
490 layout(location=3) in vec4 a_BoneIDs;
491 layout(location=4) in vec4 a_BoneWeights;
492 uniform mat4 u_Transform;
493 uniform int u_UseSkinning;
494 uniform mat4 u_Bones[128];
495 uniform mat4 u_ViewProjection;
496 out vec3 v_WorldPosition;
497 out vec2 v_TexCoord;
498 void main(){
499 vec4 localPosition=vec4(a_Position,1.0);
500 if(u_UseSkinning==1){
501 ivec4 ids=ivec4(a_BoneIDs);
502 mat4 skin=u_Bones[ids.x]*a_BoneWeights.x+
503 u_Bones[ids.y]*a_BoneWeights.y+
504 u_Bones[ids.z]*a_BoneWeights.z+
505 u_Bones[ids.w]*a_BoneWeights.w;
506 if(dot(a_BoneWeights,vec4(1.0))>0.0) localPosition=skin*localPosition;
507 }
508 vec4 w = u_Transform * localPosition;
509 v_WorldPosition = w.xyz;
510 v_TexCoord = a_TexCoord;
511 gl_Position = u_ViewProjection * w;
512 })";
513 const std::string depthFS = R"(
514 #version 460 core
515 in vec3 v_WorldPosition;
516 in vec2 v_TexCoord;
517 uniform sampler2D u_AlphaTexture;
518 uniform int u_UseAlphaTexture;
519 uniform int u_AlphaClip;
520 uniform float u_AlphaCutoff;
521 uniform float u_BaseAlpha;
522 uniform int u_RadialDepth;
523 uniform vec3 u_LightPosition;
524 uniform float u_FarPlane;
525 void main(){
526 float alpha=u_BaseAlpha;
527 if(u_UseAlphaTexture==1) alpha*=texture(u_AlphaTexture,v_TexCoord).a;
528 if(u_AlphaClip==1 && alpha<u_AlphaCutoff) discard;
529 if(u_RadialDepth==1)
530 gl_FragDepth = length(v_WorldPosition-u_LightPosition)/u_FarPlane;
531 })";
532 s.DepthShader = Shader::Create(depthVS, depthFS);
533
534 const std::string skyVS = R"(
535 #version 460 core
536 const vec2 p[3]=vec2[3](vec2(-1.0,-1.0),vec2(3.0,-1.0),vec2(-1.0,3.0));
537 out vec2 v_UV;
538 void main(){ v_UV=p[gl_VertexID]*0.5+0.5; gl_Position=vec4(p[gl_VertexID],1.0,1.0); })";
539 const std::string skyFS = R"(
540 #version 460 core
541 in vec2 v_UV; out vec4 o_Color;
542 uniform mat4 u_InverseViewProjection;
543 uniform vec3 u_SunDirection;
544 uniform vec3 u_SunColor;
545 uniform vec3 u_CameraPosition;
546 uniform float u_EnvironmentIntensity;
547 uniform float u_EnvironmentRotation;
548 uniform int u_HasHDRI;
549 uniform samplerCube u_EnvironmentMap;
550 vec3 RotateY(vec3 d,float angle){
551 float c=cos(angle),s=sin(angle);
552 return vec3(c*d.x+s*d.z,d.y,-s*d.x+c*d.z);
553 }
554 void main(){
555 vec2 ndc=v_UV*2.0-1.0;
556 vec4 w=u_InverseViewProjection*vec4(ndc,1.0,1.0);
557 vec3 d=normalize(w.xyz/w.w-u_CameraPosition);
558 d=RotateY(d,u_EnvironmentRotation);
559 float h=clamp(d.y*0.5+0.5,0.0,1.0);
560 vec3 horizon=vec3(0.62,0.72,0.86);
561 vec3 zenith=vec3(0.08,0.22,0.48);
562 vec3 c=mix(horizon,zenith,pow(h,0.7));
563 float sun=pow(max(dot(d,normalize(-u_SunDirection)),0.0),512.0);
564 c+=u_SunColor*sun*3.0;
565 if(u_HasHDRI==1)
566 c=textureLod(u_EnvironmentMap,d,0.0).rgb;
567 o_Color=vec4(c*u_EnvironmentIntensity,1.0);
568 })";
569 s.SkyShader = Shader::Create(skyVS, skyFS);
570 glCreateVertexArrays(1, &s.SkyVAO);
571 }
572
573 void UploadSkinning(Entity entity, const std::shared_ptr<Mesh>& mesh,
574 const std::shared_ptr<Shader>& shader)
575 {
576 constexpr std::size_t MaxBones = 128;
577 const bool canSkin = mesh && mesh->HasSkinning() &&
578 entity.HasComponent<AnimatorComponent>() &&
579 entity.GetComponent<AnimatorComponent>().Animation;
580 shader->SetInt("u_UseSkinning", canSkin ? 1 : 0);
581 if (!canSkin) return;
582
583 const auto& animator = entity.GetComponent<AnimatorComponent>();
584 const auto palette = animator.Animation->EvaluatePose(
585 animator.ClipIndex, animator.TimeSeconds);
586 const std::size_t count = std::min(palette.size(), MaxBones);
587 for (std::size_t i=0;i<count;++i)
588 shader->SetMat4("u_Bones[" + std::to_string(i) + "]", palette[i]);
589 }
590
591 void RenderDepthScene(Scene& scene, const glm::mat4& lightVP,
592 bool radial, const glm::vec3& lightPos,
593 float farPlane)
594 {
595 auto& s = Shadows();
596 s.DepthShader->Bind();
597 s.DepthShader->SetInt("u_RadialDepth", radial ? 1 : 0);
598 s.DepthShader->SetFloat3("u_LightPosition", lightPos);
599 s.DepthShader->SetFloat("u_FarPlane", farPlane);
600 for (Entity entity : scene.GetEntities())
601 {
602 if (!entity.HasComponent<MeshComponent>() ||
603 !entity.HasComponent<MeshRendererComponent>()) continue;
604 const auto& mesh = entity.GetComponent<MeshComponent>();
605 const auto& renderer = entity.GetComponent<MeshRendererComponent>();
606 if (!mesh.MeshAsset) continue;
607
608 auto drawDepth = [&](const std::shared_ptr<Material>& material,
609 std::uint32_t count,
610 std::uint32_t offset)
611 {
612 const bool clip = material &&
613 material->SurfaceMode() == MaterialSurfaceMode::AlphaClip;
614 s.DepthShader->SetInt("u_AlphaClip", clip ? 1 : 0);
615 s.DepthShader->SetFloat("u_AlphaCutoff",
616 material ? material->AlphaCutoff() : 0.5f);
617 s.DepthShader->SetFloat("u_BaseAlpha",
618 material ? material->GetColor().a : 1.0f);
619 const bool textured = clip && material->IsUsingTexture();
620 s.DepthShader->SetInt("u_UseAlphaTexture", textured ? 1 : 0);
621 s.DepthShader->SetInt("u_AlphaTexture", 0);
622 if (textured) material->GetTexture()->Bind(0);
623
624 UploadSkinning(entity, mesh.MeshAsset, s.DepthShader);
625 auto& stats = Statistics();
626 ++stats.ShadowDrawCalls;
627 const std::uint64_t indexCount =
628 count ? count : MeshIndexCount(mesh.MeshAsset);
629 stats.ShadowTriangles += indexCount / 3;
630 if (count)
631 Renderer::SubmitRange(mesh.MeshAsset->GetVertexArray(),
632 s.DepthShader, count, offset,
633 scene.GetWorldTransform(entity), lightVP,
634 glm::vec4(1.0f), 0);
635 else
636 Renderer::Submit(mesh.MeshAsset->GetVertexArray(),
637 s.DepthShader, scene.GetWorldTransform(entity),
638 lightVP, glm::vec4(1.0f), 0);
639 };
640
641 const auto& subs = mesh.MeshAsset->GetSubmeshes();
642 if (!subs.empty() && !renderer.Materials.empty())
643 {
644 for (const auto& sub : subs)
645 {
646 auto mat = renderer.GetMaterial(sub.MaterialIndex);
647 if (!mat) mat = renderer.MaterialAsset;
648 drawDepth(mat, sub.IndexCount, sub.IndexOffset);
649 }
650 }
651 else drawDepth(renderer.MaterialAsset, 0, 0);
652 }
653 }
654
655 void BuildShadowMaps(Scene& scene)
656 {
657 EnsureShadowResources();
658 auto& s = Shadows();
659 s.HasDirectional = s.HasSpot = s.HasPoint = false;
660 if (!RendererSettings().Shadows)
661 return;
662
663 const int quality =
664 std::clamp(RendererSettings().ShadowQuality, 0, 2);
665 const int directionalSizes[] = {1024, 2048, 4096};
666 const int spotSizes[] = {512, 1024, 2048};
667 const int pointSizes[] = {256, 512, 1024};
668
669 GLint oldViewport[4];
670 GLint oldFramebuffer = 0;
671 glGetIntegerv(GL_VIEWPORT, oldViewport);
672 glGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldFramebuffer);
673 glBindFramebuffer(GL_FRAMEBUFFER, s.FBO);
674 glDrawBuffer(GL_NONE); glReadBuffer(GL_NONE);
675 glEnable(GL_DEPTH_TEST);
676 glCullFace(GL_FRONT);
677
678 for (Entity e : scene.GetEntities())
679 {
680 const glm::mat4 world = scene.GetWorldTransform(e);
681 if (!s.HasDirectional && e.HasComponent<DirectionalLightComponent>())
682 {
683 const auto& l=e.GetComponent<DirectionalLightComponent>();
684 if (l.CastShadows)
685 {
686 // A directional light has no position: its shadow camera is
687 // rebuilt every frame from the Sun world rotation and fitted
688 // around the renderable scene. This keeps the shadow projection
689 // coupled to the actual Directional Light instead of behaving
690 // like a fixed camera around the world origin.
691 const glm::vec3 dir = WorldForward(world);
692
693 glm::vec3 boundsMin( 1.0e30f);
694 glm::vec3 boundsMax(-1.0e30f);
695 bool hasCaster = false;
696 for (Entity caster : scene.GetEntities())
697 {
698 if (!caster.HasComponent<MeshComponent>() ||
699 !caster.HasComponent<MeshRendererComponent>())
700 continue;
701
702 const glm::mat4 casterWorld = scene.GetWorldTransform(caster);
703 const glm::vec3 p = WorldPosition(casterWorld);
704 // We do not have mesh AABBs in the engine yet, so use the
705 // transform scale as a conservative per-entity radius.
706 const glm::vec3 sx = glm::vec3(casterWorld[0]);
707 const glm::vec3 sy = glm::vec3(casterWorld[1]);
708 const glm::vec3 sz = glm::vec3(casterWorld[2]);
709 const float radius = std::max({glm::length(sx), glm::length(sy), glm::length(sz), 1.0f});
710 boundsMin = glm::min(boundsMin, p - glm::vec3(radius));
711 boundsMax = glm::max(boundsMax, p + glm::vec3(radius));
712 hasCaster = true;
713 }
714
715 const glm::vec3 center = hasCaster
716 ? (boundsMin + boundsMax) * 0.5f
717 : glm::vec3(0.0f);
718 const float sceneRadius = hasCaster
719 ? std::max(glm::length(boundsMax - boundsMin) * 0.5f, 5.0f)
720 : 10.0f;
721 const float orthoExtent = sceneRadius * 1.25f;
722 const float lightDistance = sceneRadius * 2.5f;
723 const glm::vec3 pos = center - dir * lightDistance;
724 const glm::vec3 up = std::abs(glm::dot(dir, glm::vec3(0,1,0))) > 0.95f
725 ? glm::vec3(0,0,1)
726 : glm::vec3(0,1,0);
727
728 const glm::mat4 lightView = glm::lookAt(pos, center, up);
729 const glm::mat4 lightProjection = glm::ortho(
730 -orthoExtent, orthoExtent,
731 -orthoExtent, orthoExtent,
732 0.1f, lightDistance + sceneRadius * 2.0f);
733 s.DirectionalMatrix = lightProjection * lightView;
734 glNamedFramebufferTexture(s.FBO,GL_DEPTH_ATTACHMENT,s.Directional,0);
735 glViewport(0,0,directionalSizes[quality],directionalSizes[quality]); glClear(GL_DEPTH_BUFFER_BIT);
736 ++Statistics().ShadowPasses;
737 RenderDepthScene(scene,s.DirectionalMatrix,false,pos,60.f);
738 s.HasDirectional=true;
739 }
740 }
741 if (!s.HasSpot && e.HasComponent<SpotLightComponent>())
742 {
743 const auto& l=e.GetComponent<SpotLightComponent>();
744 if (l.CastShadows)
745 {
746 const glm::vec3 pos=WorldPosition(world), dir=WorldForward(world);
747 glm::vec3 up=std::abs(glm::dot(dir,glm::vec3(0,1,0)))>0.95f?glm::vec3(0,0,1):glm::vec3(0,1,0);
748 s.SpotMatrix=glm::perspective(glm::radians(std::min(l.OuterAngle*2.f,175.f)),1.f,0.05f,std::max(l.Range,0.1f))*glm::lookAt(pos,pos+dir,up);
749 glNamedFramebufferTexture(s.FBO,GL_DEPTH_ATTACHMENT,s.Spot,0);
750 glViewport(0,0,spotSizes[quality],spotSizes[quality]); glClear(GL_DEPTH_BUFFER_BIT);
751 ++Statistics().ShadowPasses;
752 RenderDepthScene(scene,s.SpotMatrix,false,pos,l.Range);
753 s.HasSpot=true;
754 }
755 }
756 if (!s.HasPoint && e.HasComponent<PointLightComponent>())
757 {
758 const auto& l=e.GetComponent<PointLightComponent>();
759 if (l.CastShadows)
760 {
761 s.PointPosition=WorldPosition(world); s.PointFar=std::max(l.Range,0.1f);
762 const glm::mat4 proj=glm::perspective(glm::radians(90.f),1.f,0.05f,s.PointFar);
763 const std::array<glm::vec3,6> dirs={glm::vec3(1,0,0),{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};
764 const std::array<glm::vec3,6> ups={glm::vec3(0,-1,0),{0,-1,0},{0,0,1},{0,0,-1},{0,-1,0},{0,-1,0}};
765 glViewport(0,0,pointSizes[quality],pointSizes[quality]);
766 for(int face=0;face<6;++face)
767 {
768 ++Statistics().ShadowPasses;
769 glNamedFramebufferTextureLayer(s.FBO,GL_DEPTH_ATTACHMENT,s.Point,0,face);
770 glClear(GL_DEPTH_BUFFER_BIT);
771 RenderDepthScene(scene,proj*glm::lookAt(s.PointPosition,s.PointPosition+dirs[face],ups[face]),true,s.PointPosition,s.PointFar);
772 }
773 s.HasPoint=true;
774 }
775 }
776 }
777 glCullFace(GL_BACK);
778 glBindFramebuffer(GL_FRAMEBUFFER, static_cast<GLuint>(oldFramebuffer));
779 glViewport(oldViewport[0],oldViewport[1],oldViewport[2],oldViewport[3]);
780 }
781
782 void RenderSky(const glm::mat4& viewProjection, const glm::vec3& cameraPosition, Scene& scene)
783 {
784 auto& s=Shadows();
785 glm::vec3 sunDir(0.2f,-1.0f,0.2f), sunColor(1.0f,0.95f,0.85f);
786 for(Entity e:scene.GetEntities()) if(e.HasComponent<DirectionalLightComponent>())
787 { sunDir=WorldForward(scene.GetWorldTransform(e)); sunColor=e.GetComponent<DirectionalLightComponent>().Color; break; }
788 glEnable(GL_DEPTH_TEST);
789 glDepthFunc(GL_LEQUAL);
790 glDepthMask(GL_FALSE);
791 s.SkyShader->Bind();
792 s.SkyShader->SetMat4("u_InverseViewProjection",glm::inverse(viewProjection));
793 s.SkyShader->SetFloat3("u_SunDirection",sunDir);
794 s.SkyShader->SetFloat3("u_SunColor",sunColor);
795 s.SkyShader->SetFloat3("u_CameraPosition",cameraPosition);
796 const auto& graphics = RendererSettings();
797 s.SkyShader->SetFloat(
798 "u_EnvironmentIntensity", graphics.EnvironmentIntensity);
799 s.SkyShader->SetFloat(
800 "u_EnvironmentRotation",
801 glm::radians(graphics.EnvironmentRotation));
802 s.SkyShader->SetInt(
803 "u_HasHDRI", s.EnvironmentReady ? 1 : 0);
804 s.SkyShader->SetInt("u_EnvironmentMap", 12);
805 if (s.EnvironmentReady)
806 glBindTextureUnit(12, s.Environment);
807 glBindVertexArray(s.SkyVAO); glDrawArrays(GL_TRIANGLES,0,3); glBindVertexArray(0);
808 glDepthMask(GL_TRUE);
809 glDepthFunc(GL_LESS);
810 }
811
812 void UploadLighting(Scene& scene, const std::shared_ptr<Shader>& shader,
813 const glm::vec3& cameraPosition)
814 {
815 auto& s=Shadows();
816 shader->Bind();
817 shader->SetFloat3("u_ViewPosition",cameraPosition);
818 shader->SetFloat3("u_AmbientColor",{0.035f,0.045f,0.065f});
819 const auto& graphics = RendererSettings();
820 shader->SetInt("u_UseIBL", graphics.ImageBasedLighting ? 1 : 0);
821 shader->SetFloat(
822 "u_EnvironmentIntensity", graphics.EnvironmentIntensity);
823 shader->SetFloat(
824 "u_DiffuseIBLStrength", graphics.DiffuseIBLStrength);
825 shader->SetFloat(
826 "u_SpecularIBLStrength", graphics.SpecularIBLStrength);
827 shader->SetFloat(
828 "u_EnvironmentRotation",
829 glm::radians(graphics.EnvironmentRotation));
830 auto& environment = Shadows();
831 shader->SetInt(
832 "u_HasHDRI", environment.EnvironmentReady ? 1 : 0);
833 shader->SetInt("u_IrradianceMap", 9);
834 shader->SetInt("u_PrefilterMap", 10);
835 shader->SetInt("u_BRDFLUT", 11);
836 if (environment.EnvironmentReady)
837 {
838 glBindTextureUnit(9, environment.Irradiance);
839 glBindTextureUnit(10, environment.Prefilter);
840 glBindTextureUnit(11, environment.BRDFLUT);
841 }
842 bool hasDirectional=false; int pointCount=0,spotCount=0;
843 for(Entity e:scene.GetEntities())
844 {
845 const glm::mat4 world=scene.GetWorldTransform(e);
846 if(!hasDirectional && e.HasComponent<DirectionalLightComponent>())
847 {
848 const auto& l=e.GetComponent<DirectionalLightComponent>();
849 shader->SetInt("u_HasDirectionalLight",1);
850 shader->SetFloat3("u_DirectionalLight.direction",WorldForward(world));
851 shader->SetFloat3("u_DirectionalLight.color",l.Color);
852 shader->SetFloat("u_DirectionalLight.intensity",std::max(l.Intensity,0.f));
853 shader->SetFloat("u_DirectionalShadowBias",l.ShadowBias);
854 hasDirectional=true;
855 }
856 if(pointCount<4 && e.HasComponent<PointLightComponent>())
857 {
858 const auto& l=e.GetComponent<PointLightComponent>(); const std::string b="u_PointLights["+std::to_string(pointCount)+"]";
859 shader->SetFloat3(b+".position",WorldPosition(world)); shader->SetFloat3(b+".color",l.Color);
860 shader->SetFloat(b+".intensity",std::max(l.Intensity,0.f)); shader->SetFloat(b+".range",std::max(l.Range,0.01f));
861 shader->SetFloat("u_PointShadowBias",l.ShadowBias); ++pointCount;
862 }
863 if(spotCount<4 && e.HasComponent<SpotLightComponent>())
864 {
865 const auto& l=e.GetComponent<SpotLightComponent>(); const std::string b="u_SpotLights["+std::to_string(spotCount)+"]";
866 shader->SetFloat3(b+".position",WorldPosition(world)); shader->SetFloat3(b+".direction",WorldForward(world)); shader->SetFloat3(b+".color",l.Color);
867 shader->SetFloat(b+".intensity",std::max(l.Intensity,0.f)); shader->SetFloat(b+".range",std::max(l.Range,0.01f));
868 shader->SetFloat(b+".innerCos",std::cos(glm::radians(l.InnerAngle))); shader->SetFloat(b+".outerCos",std::cos(glm::radians(l.OuterAngle)));
869 shader->SetFloat("u_SpotShadowBias",l.ShadowBias); ++spotCount;
870 }
871 }
872 shader->SetInt("u_HasDirectionalLight",hasDirectional?1:0); shader->SetInt("u_PointLightCount",pointCount); shader->SetInt("u_SpotLightCount",spotCount);
873 shader->SetInt("u_HasDirectionalShadow",s.HasDirectional?1:0); shader->SetInt("u_HasPointShadow",s.HasPoint?1:0); shader->SetInt("u_HasSpotShadow",s.HasSpot?1:0);
874 shader->SetMat4("u_DirectionalLightSpace",s.DirectionalMatrix); shader->SetMat4("u_SpotLightSpace",s.SpotMatrix);
875 shader->SetFloat3("u_PointShadowPosition",s.PointPosition); shader->SetFloat("u_PointShadowFar",s.PointFar);
876 glBindTextureUnit(5,s.Directional); glBindTextureUnit(6,s.Point); glBindTextureUnit(7,s.Spot);
877 shader->SetInt("u_DirectionalShadowMap",5); shader->SetInt("u_PointShadowMap",6); shader->SetInt("u_SpotShadowMap",7);
878 }
879 }
880
881
882 namespace
883 {
884 struct ParticleInstanceGPU
885 {
886 glm::vec3 Position;
887 float Size;
888 glm::vec4 Color;
889 };
890
891 struct ParticleRenderResources
892 {
893 GLuint VAO = 0;
894 GLuint VBO = 0;
895 GLuint InstanceVBO = 0;
896 std::shared_ptr<Shader> ShaderProgram;
897 std::unordered_map<std::string, std::shared_ptr<Texture2D>> Textures;
898 };
899
900 ParticleRenderResources& ParticleResources()
901 {
902 static ParticleRenderResources r;
903 return r;
904 }
905
906 void EnsureParticleResources()
907 {
908 auto& r = ParticleResources();
909 if (r.VAO != 0) return;
910
911 // XY + UV unit quad. Per-particle position/size/color live in an
912 // instanced buffer, reducing an emitter to one draw call.
913 const float vertices[] = {
914 -0.5f,-0.5f, 0,0, 0.5f,-0.5f, 1,0, 0.5f, 0.5f, 1,1,
915 -0.5f,-0.5f, 0,0, 0.5f, 0.5f, 1,1, -0.5f, 0.5f, 0,1
916 };
917 glGenVertexArrays(1, &r.VAO);
918 glGenBuffers(1, &r.VBO);
919 glGenBuffers(1, &r.InstanceVBO);
920 glBindVertexArray(r.VAO);
921
922 glBindBuffer(GL_ARRAY_BUFFER, r.VBO);
923 glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
924 glEnableVertexAttribArray(0);
925 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), nullptr);
926 glEnableVertexAttribArray(1);
927 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float),
928 reinterpret_cast<void*>(2*sizeof(float)));
929
930 glBindBuffer(GL_ARRAY_BUFFER, r.InstanceVBO);
931 glBufferData(GL_ARRAY_BUFFER, sizeof(ParticleInstanceGPU), nullptr, GL_STREAM_DRAW);
932 glEnableVertexAttribArray(2);
933 glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(ParticleInstanceGPU),
934 reinterpret_cast<void*>(offsetof(ParticleInstanceGPU, Position)));
935 glVertexAttribDivisor(2, 1);
936 glEnableVertexAttribArray(3);
937 glVertexAttribPointer(3, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleInstanceGPU),
938 reinterpret_cast<void*>(offsetof(ParticleInstanceGPU, Size)));
939 glVertexAttribDivisor(3, 1);
940 glEnableVertexAttribArray(4);
941 glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, sizeof(ParticleInstanceGPU),
942 reinterpret_cast<void*>(offsetof(ParticleInstanceGPU, Color)));
943 glVertexAttribDivisor(4, 1);
944 glBindVertexArray(0);
945
946 const std::string vs = R"(
947 #version 460 core
948 layout(location=0) in vec2 a_Position;
949 layout(location=1) in vec2 a_UV;
950 layout(location=2) in vec3 i_WorldPosition;
951 layout(location=3) in float i_Size;
952 layout(location=4) in vec4 i_Color;
953 uniform mat4 u_ViewProjection;
954 uniform vec3 u_CameraRight;
955 uniform vec3 u_CameraUp;
956 out vec2 v_UV;
957 out vec4 v_Color;
958 void main() {
959 vec3 world = i_WorldPosition +
960 u_CameraRight * a_Position.x * i_Size +
961 u_CameraUp * a_Position.y * i_Size;
962 gl_Position = u_ViewProjection * vec4(world,1.0);
963 v_UV = a_UV;
964 v_Color = i_Color;
965 })";
966 const std::string fs = R"(
967 #version 460 core
968 layout(location=0) out vec4 o_Color;
969 in vec2 v_UV;
970 in vec4 v_Color;
971 uniform sampler2D u_Texture;
972 uniform int u_UseTexture;
973 void main() {
974 vec4 texel = u_UseTexture != 0 ? texture(u_Texture, v_UV) : vec4(1.0);
975 o_Color = texel * v_Color;
976 if (o_Color.a <= 0.003) discard;
977 })";
978 r.ShaderProgram = Shader::Create(vs, fs);
979 }
980
981 std::shared_ptr<Texture2D> ParticleTexture(const std::string& path)
982 {
983 if (path.empty()) return {};
984 auto& cache = ParticleResources().Textures;
985 auto it = cache.find(path);
986 if (it != cache.end()) return it->second;
987 try
988 {
989 auto texture = AssetManager::LoadTexture(path);
990 cache[path] = texture;
991 return texture;
992 }
993 catch (...) { Log::Warn("Particle texture load failed: " + path); return {}; }
994 }
995
996 void RenderParticles(Scene& scene, const glm::mat4& viewProjection,
997 RendererStatistics& stats)
998 {
999 EnsureParticleResources();
1000 auto& r = ParticleResources();
1001 if (!r.ShaderProgram) return;
1002
1003 const glm::mat4 inverseVP = glm::inverse(viewProjection);
1004 const glm::vec3 right = glm::normalize(glm::vec3(inverseVP[0]));
1005 const glm::vec3 up = glm::normalize(glm::vec3(inverseVP[1]));
1006
1007 glEnable(GL_BLEND);
1008 glDepthMask(GL_FALSE);
1009 r.ShaderProgram->Bind();
1010 r.ShaderProgram->SetMat4("u_ViewProjection", viewProjection);
1011 r.ShaderProgram->SetFloat3("u_CameraRight", right);
1012 r.ShaderProgram->SetFloat3("u_CameraUp", up);
1013 r.ShaderProgram->SetInt("u_Texture", 0);
1014 glBindVertexArray(r.VAO);
1015
1016 std::vector<ParticleInstanceGPU> instances;
1017 for (Entity entity : scene.GetEntities())
1018 {
1019 if (!entity.HasComponent<ParticleSystemComponent>()) continue;
1020 const auto& settings = entity.GetComponent<ParticleSystemComponent>();
1021 const auto& particles = scene.GetParticles(entity.GetHandle());
1022 if (particles.empty()) continue;
1023
1024 instances.clear();
1025 instances.reserve(particles.size());
1026 for (const auto& p : particles)
1027 instances.push_back({p.Position, p.Size, p.Color});
1028
1029 if (settings.BlendMode == ParticleBlendMode::Additive)
1030 glBlendFunc(GL_SRC_ALPHA, GL_ONE);
1031 else
1032 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1033
1034 auto texture = ParticleTexture(settings.TexturePath);
1035 r.ShaderProgram->SetInt("u_UseTexture", texture ? 1 : 0);
1036 if (texture) texture->Bind(0);
1037
1038 glBindBuffer(GL_ARRAY_BUFFER, r.InstanceVBO);
1039 glBufferData(GL_ARRAY_BUFFER,
1040 static_cast<GLsizeiptr>(instances.size() * sizeof(ParticleInstanceGPU)),
1041 instances.data(), GL_STREAM_DRAW);
1042 glDrawArraysInstanced(GL_TRIANGLES, 0, 6,
1043 static_cast<GLsizei>(instances.size()));
1044
1045 ++stats.DrawCalls;
1046 stats.Triangles += static_cast<std::uint64_t>(instances.size()) * 2;
1047 }
1048
1049 glBindVertexArray(0);
1050 glDepthMask(GL_TRUE);
1051 glDisable(GL_BLEND);
1052 }
1053 }
1054
1055 void SceneRenderer::Render(Scene& scene, const glm::mat4& viewProjection,
1056 const glm::vec3& cameraPosition,
1057 bool rebuildShadowMaps)
1058 {
1059 const auto cpuStart = std::chrono::steady_clock::now();
1060 auto& stats = Statistics();
1061 const float previousGPUTime = stats.GPUTimeMs;
1062 const bool previousGPUValid = stats.GPUTimeValid;
1063 stats = {};
1064 stats.GPUTimeMs = previousGPUTime;
1065 stats.GPUTimeValid = previousGPUValid;
1066 BeginGPUFrameQuery();
1067
1068 EnsureEnvironmentResources();
1069 if (rebuildShadowMaps)
1070 BuildShadowMaps(scene);
1071 RenderSky(viewProjection,cameraPosition,scene);
1072
1073 for(Entity entity:scene.GetEntities())
1074 {
1075 if(!entity.HasComponent<MeshComponent>() ||
1076 !entity.HasComponent<MeshRendererComponent>()) continue;
1077
1078 const auto& mesh=entity.GetComponent<MeshComponent>();
1079 const auto& renderer=entity.GetComponent<MeshRendererComponent>();
1080 if(!mesh.MeshAsset || !renderer.MaterialAsset) continue;
1081 const glm::mat4 entityWorld = scene.GetWorldTransform(entity);
1082
1083 auto drawMaterial=[&](const std::shared_ptr<Material>& material,
1084 std::uint32_t count,std::uint32_t offset)
1085 {
1086 if(!material || !material->GetShader()) return;
1087 const auto& shader=material->GetShader();
1088 UploadLighting(scene,shader,cameraPosition);
1089 shader->SetInt("u_SurfaceMode", static_cast<int>(material->SurfaceMode()));
1090 shader->SetFloat("u_AlphaCutoff", material->AlphaCutoff());
1091
1092 const bool transparent =
1093 material->SurfaceMode() == MaterialSurfaceMode::Transparent;
1094 if (transparent)
1095 {
1096 glEnable(GL_BLEND);
1097 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1098 glDepthMask(GL_FALSE);
1099 }
1100 else
1101 {
1102 glDisable(GL_BLEND);
1103 glDepthMask(GL_TRUE);
1104 }
1105
1106 shader->SetFloat("u_Metallic",glm::clamp(material->Metallic(),0.f,1.f));
1107 shader->SetFloat("u_Roughness",glm::clamp(material->Roughness(),0.04f,1.f));
1108 shader->SetFloat("u_AO",glm::clamp(material->AmbientOcclusion(),0.f,1.f));
1109 shader->SetFloat("u_NormalStrength",glm::max(material->NormalStrength(),0.f));
1110 shader->SetFloat3("u_EmissiveColor",material->EmissiveColor());
1111 shader->SetFloat("u_EmissiveStrength",glm::max(material->EmissiveStrength(),0.f));
1112 if(material->IsUsingTexture()) material->GetTexture()->Bind(0);
1113 shader->SetInt("u_Texture",0);
1114
1115 const auto bindMap=[&](const std::shared_ptr<Texture2D>& tex,
1116 const char* sampler,const char* enabled,int slot)
1117 {
1118 shader->SetInt(enabled,tex?1:0);shader->SetInt(sampler,slot);
1119 if(tex)tex->Bind(static_cast<std::uint32_t>(slot));
1120 };
1121 bindMap(material->GetNormalTexture(),"u_NormalMap","u_UseNormalMap",1);
1122 bindMap(material->GetMetallicTexture(),"u_MetallicMap","u_UseMetallicMap",2);
1123 bindMap(material->GetRoughnessTexture(),"u_RoughnessMap","u_UseRoughnessMap",3);
1124 bindMap(material->GetAOTexture(),"u_AOMap","u_UseAOMap",4);
1125 bindMap(material->GetEmissiveTexture(),"u_EmissiveMap","u_UseEmissiveMap",8);
1126
1127 UploadSkinning(entity, mesh.MeshAsset, shader);
1128 ++stats.DrawCalls;
1129 const std::uint64_t indexCount =
1130 count ? count : MeshIndexCount(mesh.MeshAsset);
1131 stats.Triangles += indexCount / 3;
1132 if(count)
1133 Renderer::SubmitRange(mesh.MeshAsset->GetVertexArray(),shader,
1134 count,offset,entityWorld,viewProjection,
1135 material->GetColor(),material->IsUsingTexture()?1:0);
1136 else
1137 Renderer::Submit(mesh.MeshAsset->GetVertexArray(),shader,
1138 entityWorld,viewProjection,
1139 material->GetColor(),material->IsUsingTexture()?1:0);
1140
1141 if (transparent)
1142 {
1143 glDepthMask(GL_TRUE);
1144 glDisable(GL_BLEND);
1145 }
1146 };
1147
1148 const auto& subs=mesh.MeshAsset->GetSubmeshes();
1149 if(!subs.empty() && !renderer.Materials.empty())
1150 {
1151 for(const auto& sub:subs)
1152 {
1153 auto mat=renderer.GetMaterial(sub.MaterialIndex);
1154 if(!mat)mat=renderer.MaterialAsset;
1155 drawMaterial(mat,sub.IndexCount,sub.IndexOffset);
1156 }
1157 }
1158 else drawMaterial(renderer.MaterialAsset,0,0);
1159 }
1160
1161 RenderParticles(scene, viewProjection, stats);
1162
1163 EndGPUFrameQuery();
1164 const auto cpuEnd = std::chrono::steady_clock::now();
1165 stats.CPUTimeMs =
1166 std::chrono::duration<float, std::milli>(
1167 cpuEnd - cpuStart).count();
1168 }
1169
1171 {
1172 // Explicitly release renderer-owned static GL resources before the
1173 // GLFW window/context disappears. Leaving shared_ptr<Shader> objects
1174 // in function statics until process teardown can invoke their OpenGL
1175 // destructors after the context has already been destroyed.
1176 auto& particles = ParticleResources();
1177 particles.ShaderProgram.reset();
1178 particles.Textures.clear();
1179 if (particles.InstanceVBO != 0)
1180 {
1181 glDeleteBuffers(1, &particles.InstanceVBO);
1182 particles.InstanceVBO = 0;
1183 }
1184 if (particles.VBO != 0)
1185 {
1186 glDeleteBuffers(1, &particles.VBO);
1187 particles.VBO = 0;
1188 }
1189 if (particles.VAO != 0)
1190 {
1191 glDeleteVertexArrays(1, &particles.VAO);
1192 particles.VAO = 0;
1193 }
1194 }
1195
1197 const FramebufferSpecification& settings)
1198 {
1199 RendererSettings() = settings;
1200 }
1201
1203 {
1204 return RendererSettings();
1205 }
1206
1208 {
1209 return Statistics();
1210 }
1211
1212}
Animation declarations for the Animation subsystem.
AssetManager declarations for the Asset subsystem.
Buffer declarations for the Rendering subsystem.
Log declarations for the Core subsystem.
Material declarations for the Rendering subsystem.
Mesh declarations for the Rendering subsystem.
Renderer declarations for the Rendering subsystem.
Scene declarations for the Scenes and Native Scripting subsystem.
SceneRenderer declarations for the Scenes and Native Scripting subsystem.
Shader declarations for the Rendering subsystem.
Texture declarations for the Rendering subsystem.
VertexArray declarations for the Rendering subsystem.
static std::shared_ptr< Texture2D > LoadTexture(const std::filesystem::path &path)
static std::filesystem::path ResolveProjectPath(const std::filesystem::path &path)
static void Warn(std::string_view message)
Definition Log.h:18
static void SubmitRange(const std::shared_ptr< VertexArray > &vertexArray, const std::shared_ptr< Shader > &shader, std::uint32_t indexCount, std::uint32_t indexOffset, const glm::mat4 &transform, const glm::mat4 &viewProjection, const glm::vec4 &color, int useTexture)
Definition Renderer.cpp:60
static void Submit(const std::shared_ptr< VertexArray > &vertexArray, const std::shared_ptr< Shader > &shader, const glm::mat4 &transform=glm::mat4(1.0f), const glm::mat4 &viewProjection=glm::mat4(1.0f), const glm::vec4 &color=glm::vec4(1.0f))
Definition Renderer.cpp:28
std::vector< Entity > GetEntities()
Definition Scene.cpp:231
glm::mat4 GetWorldTransform(Entity entity) const
Definition Scene.cpp:1736
static void Render(Scene &scene, const glm::mat4 &viewProjection, const glm::vec3 &cameraPosition=glm::vec3(0.0f), bool rebuildShadowMaps=true)
static const FramebufferSpecification & GetGraphicsSettings()
static void SetGraphicsSettings(const FramebufferSpecification &settings)
static const RendererStatistics & GetStatistics()
static std::shared_ptr< Shader > Create(const std::string &vertexSource, const std::string &fragmentSource)
Definition Shader.cpp:8
std::shared_ptr< AnimationAsset > Animation
Definition Components.h:325