Compare commits

...

7 Commits

13 changed files with 222 additions and 306 deletions

10
.vscode/settings.json vendored
View File

@ -61,6 +61,14 @@
"typeindex": "cpp", "typeindex": "cpp",
"ranges": "cpp", "ranges": "cpp",
"list": "cpp", "list": "cpp",
"unordered_set": "cpp" "unordered_set": "cpp",
"bitset": "cpp",
"condition_variable": "cpp",
"map": "cpp",
"set": "cpp",
"regex": "cpp",
"semaphore": "cpp",
"shared_mutex": "cpp",
"stop_token": "cpp"
} }
} }

View File

@ -1,4 +1,4 @@
# Blender 4.3.2 MTL File: 'untitled.blend' # Blender 4.3.2 MTL File: 'None'
# www.blender.org # www.blender.org
newmtl Grass_Bottom newmtl Grass_Bottom

View File

@ -2,25 +2,25 @@
# www.blender.org # www.blender.org
mtllib grass_block.mtl mtllib grass_block.mtl
o Cube o Cube
v -1.000000 -1.000000 1.000000 v -0.389000 -0.389000 0.389000
v -1.000000 1.000000 1.000000 v -0.389000 0.389000 0.389000
v -1.000000 -1.000000 -1.000000 v -0.389000 -0.389000 -0.389000
v -1.000000 1.000000 -1.000000 v -0.389000 0.389000 -0.389000
v 1.000000 -1.000000 1.000000 v 0.389000 -0.389000 0.389000
v 1.000000 1.000000 1.000000 v 0.389000 0.389000 0.389000
v 1.000000 -1.000000 -1.000000 v 0.389000 -0.389000 -0.389000
v 1.000000 1.000000 -1.000000 v 0.389000 0.389000 -0.389000
vn -1.0000 -0.0000 -0.0000 vn -1.0000 -0.0000 -0.0000
vn -0.0000 -0.0000 -1.0000 vn -0.0000 -0.0000 -1.0000
vn 1.0000 -0.0000 -0.0000 vn 1.0000 -0.0000 -0.0000
vn -0.0000 -0.0000 1.0000 vn -0.0000 -0.0000 1.0000
vn -0.0000 -1.0000 -0.0000
vn -0.0000 1.0000 -0.0000 vn -0.0000 1.0000 -0.0000
vn -0.0000 -1.0000 -0.0000
vt 0.000000 1.000000 vt 0.000000 1.000000
vt 1.000000 0.000000 vt 1.000000 0.000000
vt 0.000000 0.000000 vt 0.000000 0.000000
vt 1.000000 1.000000 vt 1.000000 1.000000
s 0 s 1
usemtl Grass_Side usemtl Grass_Side
f 2/1/1 3/2/1 1/3/1 f 2/1/1 3/2/1 1/3/1
f 4/1/2 7/2/2 3/3/2 f 4/1/2 7/2/2 3/3/2
@ -31,8 +31,8 @@ f 4/1/2 8/4/2 7/2/2
f 8/4/3 6/1/3 5/3/3 f 8/4/3 6/1/3 5/3/3
f 6/4/4 2/1/4 1/3/4 f 6/4/4 2/1/4 1/3/4
usemtl Grass_Top usemtl Grass_Top
f 4/1/6 6/2/6 8/4/6 f 4/1/5 6/2/5 8/4/5
f 4/1/6 2/3/6 6/2/6 f 4/1/5 2/3/5 6/2/5
usemtl Grass_Bottom usemtl Grass_Bottom
f 7/4/5 1/3/5 3/1/5 f 7/4/6 1/3/6 3/1/6
f 7/4/5 5/2/5 1/3/5 f 7/4/6 5/2/6 1/3/6

View File

@ -2,10 +2,25 @@
#define COMPONENTS_LIGHT_H_ #define COMPONENTS_LIGHT_H_
#include <glm/glm.hpp> #include <glm/glm.hpp>
#include "renderer/renderer.h"
struct light { struct light {
friend class Renderer;
public:
enum LightType {
DIRECTIONAL = 0,
};
LightType type;
glm::vec3 color; glm::vec3 color;
float intensity; float intensity;
light(LightType t, const glm::vec3& c, float i)
: type(t), color(c), intensity(i),
shadowMap(0), fbo(0), lightSpace(1.0f) {}
private:
unsigned int shadowMap;
unsigned int fbo;
glm::mat4 lightSpace;
}; };
#endif // COMPONENTS_LIGHT_H_ #endif // COMPONENTS_LIGHT_H_

View File

@ -16,18 +16,15 @@ public:
void OnWindowResized(int w, int h); void OnWindowResized(int w, int h);
private: private:
void ApplyLights(entt::registry& registry); void ApplyLights(entt::registry& registry, Shader &shader);
void UpdateView(entt::registry& registry); void UpdateView(entt::registry& registry, Shader &shader);
void RenderScene(entt::registry& registry); void RenderScene(entt::registry& registry, Shader &shader);
void SwitchShader(Shader* newShader);
private: private:
Shader m_shader; Shader m_shader;
Shader m_depthShader; Shader m_depthShader;
Shader* m_currentShader; // unsigned int m_depth_fbo;
unsigned int m_depth_fbo; // unsigned int m_depthMap;
unsigned int m_depthMap;
glm::mat4 m_model; glm::mat4 m_model;
glm::mat4 m_proj; glm::mat4 m_proj;

66
out.txt
View File

@ -1,66 +0,0 @@
GL_VENDOR: NVIDIA Corporation
GL_RENDERER: NVIDIA GeForce RTX 3050 Ti Laptop GPU/PCIe/SSE2
GL_VERSION: 4.6.0 NVIDIA 550.163.01
Object name: Sphere
Vertices count: 482
Normals count: 530
TexCoords count: 559
Meshes count: 2
Materials count: 2
GL CALLBACK: type = 0x33361, severity = 0x33387, message = Buffer detailed info: Buffer object 3 (bound to GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB (0), GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB (1), GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB (2), and GL_ARRAY_BUFFER_ARB, usage hint is GL_STATIC_DRAW) will use VIDEO memory as the source for buffer object operations.
GL CALLBACK: type = 0x33361, severity = 0x33387, message = Buffer detailed info: Buffer object 4 (bound to GL_ELEMENT_ARRAY_BUFFER_ARB, usage hint is GL_STATIC_DRAW) will use VIDEO memory as the source for buffer object operations.
Object name: Cube
Vertices count: 8
Normals count: 6
TexCoords count: 14
Meshes count: 1
Materials count: 1
GL CALLBACK: type = 0x33361, severity = 0x33387, message = Buffer detailed info: Buffer object 5 (bound to GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB (0), GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB (1), GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB (2), and GL_ARRAY_BUFFER_ARB, usage hint is GL_STATIC_DRAW) will use VIDEO memory as the source for buffer object operations.
GL CALLBACK: type = 0x33361, severity = 0x33387, message = Buffer detailed info: Buffer object 6 (bound to GL_ELEMENT_ARRAY_BUFFER_ARB, usage hint is GL_STATIC_DRAW) will use VIDEO memory as the source for buffer object operations.
Object name: Plane
Vertices count: 4
Normals count: 1
TexCoords count: 4
Meshes count: 1
Materials count: 1
GL CALLBACK: type = 0x33361, severity = 0x33387, message = Buffer detailed info: Buffer object 7 (bound to GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB (0), GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB (1), GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB (2), and GL_ARRAY_BUFFER_ARB, usage hint is GL_STATIC_DRAW) will use VIDEO memory as the source for buffer object operations.
GL CALLBACK: type = 0x33361, severity = 0x33387, message = Buffer detailed info: Buffer object 8 (bound to GL_ELEMENT_ARRAY_BUFFER_ARB, usage hint is GL_STATIC_DRAW) will use VIDEO memory as the source for buffer object operations.
Game initialized
GL CALLBACK: ** GL ERROR ** type = 0x33356, severity = 0x37190, message = GL_INVALID_OPERATION error generated. <location> is invalid.
GL CALLBACK: ** GL ERROR ** type = 0x33356, severity = 0x37190, message = GL_INVALID_OPERATION error generated. <location> is invalid.
GL CALLBACK: ** GL ERROR ** type = 0x33356, severity = 0x37190, message = GL_INVALID_OPERATION error generated. <location> is invalid.
GL CALLBACK: ** GL ERROR ** type = 0x33356, severity = 0x37190, message = GL_INVALID_OPERATION error generated. <location> is invalid.
GL CALLBACK: ** GL ERROR ** type = 0x33356, severity = 0x37190, message = GL_INVALID_OPERATION error generated. <location> is invalid.
GL CALLBACK: ** GL ERROR ** type = 0x33356, severity = 0x37190, message = GL_INVALID_OPERATION error generated. <location> is invalid.
GL CALLBACK: ** GL ERROR ** type = 0x33356, severity = 0x37190, message = GL_INVALID_OPERATION error generated. <location> is invalid.
GL CALLBACK: type = 0x33360, severity = 0x37191, message = Program/shader state performance warning: Vertex shader in program 6 is being recompiled based on GL state.
GL CALLBACK: type = 0x33360, severity = 0x37191, message = Program/shader state performance warning: Vertex shader in program 3 is being recompiled based on GL state.
FPS: 160.359
FPS: 165
FPS: 165
FPS: 165
FPS: 165
FPS: 165
FPS: 165
FPS: 165.01
FPS: 165
FPS: 164.835
FPS: 165.01
FPS: 165
FPS: 165.174
FPS: 165
FPS: 165
FPS: 165
FPS: 165
FPS: 165
FPS: 165
FPS: 165.174
FPS: 164.835
FPS: 165.174
FPS: 164.835
FPS: 165
FPS: 165
FPS: 165
FPS: 165.01
FPS: 165
FPS: 165.174

View File

@ -28,15 +28,10 @@ class Game : public IApplication {
public: public:
Game() { Game() {
Object* lightObj = Object::LoadFile("./assets/sphere.obj"); Object* lightObj = Object::LoadFile("./assets/sphere.obj");
// const auto lightEntity = m_registry.create(); const auto lght = m_registry.create();
// m_registry.emplace<transform>(lightEntity, glm::vec3(-5.f, 5.f, 5.f), glm::vec3(0.f)); m_registry.emplace<transform>(lght, glm::vec3(5.f, 5.f, 5.f), glm::vec3(0.f));
// m_registry.emplace<light>(lightEntity, glm::vec3(1.f, 0.f, 0.f), 1.f); m_registry.emplace<light>(lght, light::LightType::DIRECTIONAL, glm::vec3(1.f, 1.f, 1.f), 1.5f);
// m_registry.emplace<mesh>(lightEntity, std::unique_ptr<Object>(lightObj)); m_registry.emplace<mesh>(lght, std::unique_ptr<Object>(lightObj));
const auto lEntt2 = m_registry.create();
m_registry.emplace<transform>(lEntt2, glm::vec3(5.f, 5.f, 5.f), glm::vec3(0.f));
m_registry.emplace<light>(lEntt2, glm::vec3(1.f, 1.f, 1.f), 1.5f);
m_registry.emplace<mesh>(lEntt2, std::unique_ptr<Object>(lightObj));
const auto cameraEntity = m_registry.create(); const auto cameraEntity = m_registry.create();
m_registry.emplace<transform>(cameraEntity, glm::vec3(0.f, 2.f, 2.f)); m_registry.emplace<transform>(cameraEntity, glm::vec3(0.f, 2.f, 2.f));
@ -44,9 +39,14 @@ public:
Object* targetObj = Object::LoadFile("./assets/wizard/wizard.obj"); Object* targetObj = Object::LoadFile("./assets/wizard/wizard.obj");
const auto targetEntity = m_registry.create(); const auto targetEntity = m_registry.create();
m_registry.emplace<transform>(targetEntity, glm::vec3(0.f, 0.5f, 0.f)); m_registry.emplace<transform>(targetEntity, glm::vec3(0.f, 0.0f, 0.f));
m_registry.emplace<mesh>(targetEntity, std::unique_ptr<Object>(targetObj)); m_registry.emplace<mesh>(targetEntity, std::unique_ptr<Object>(targetObj));
Object* cubeObj = Object::LoadFile("./assets/grass_block/grass_block.obj");
const auto cubeEntity = m_registry.create();
m_registry.emplace<transform>(cubeEntity, glm::vec3(-1.5f, 0.4f, 0.f));
m_registry.emplace<mesh>(cubeEntity, std::unique_ptr<Object>(cubeObj));
Object* floorObj = Object::LoadFile("./assets/plane.obj"); Object* floorObj = Object::LoadFile("./assets/plane.obj");
const auto floorEntt = m_registry.create(); const auto floorEntt = m_registry.create();
m_registry.emplace<transform>(floorEntt, glm::vec3(0.f)); m_registry.emplace<transform>(floorEntt, glm::vec3(0.f));
@ -131,6 +131,40 @@ public:
} }
} }
// ---- Day-night simulation ----
m_dayTime += deltaTime;
if (m_dayTime > m_dayLength)
m_dayTime -= m_dayLength; // loop every "day"
float dayProgress = m_dayTime / m_dayLength; // 0.0 -> 1.0
float sunAngle = dayProgress * glm::two_pi<float>(); // radians through the sky
// Compute sun direction (rotating around X axis)
// At t=0.0 sun at east horizon, at π/2 overhead, at π west horizon
glm::vec3 sunDir = glm::normalize(glm::vec3(0.0f, sin(sunAngle), cos(sunAngle)));
// Compute intensity: bright at noon, dim at dusk/dawn, dark at night
float intensity = glm::max(sin(sunAngle), (double)0.0f); // 0 at night, 1 at noon
intensity = glm::mix(0.05f, 1.5f, intensity); // keep some ambient even at night
// Optional: tint color (warm at sunrise/sunset)
glm::vec3 dayColor = glm::vec3(1.0f, 0.95f, 0.9f);
glm::vec3 sunsetColor= glm::vec3(1.0f, 0.6f, 0.3f);
float sunsetFactor = glm::clamp(1.0f - abs(sin(sunAngle)) * 2.0f, 0.0f, 1.0f);
glm::vec3 sunColor = glm::mix(dayColor, sunsetColor, sunsetFactor);
// Update the directional light in the registry
auto lightsView = m_registry.view<light, transform>();
for (auto [entity, l, t] : lightsView.each()) {
if (l.type == light::LightType::DIRECTIONAL) {
// "position" for directional light often stores direction vector
// If your system instead uses transform.rotation, adjust accordingly
t.position = sunDir * 15.f; // use this as light direction
l.color = sunColor;
l.intensity = intensity;
}
}
// auto rotateEntts = m_registry.view<transform, const mesh>(); // auto rotateEntts = m_registry.view<transform, const mesh>();
// for (auto [entity, transform, mesh] : rotateEntts.each()) { // for (auto [entity, transform, mesh] : rotateEntts.each()) {
// // auto targetTransform = rotateEntts.get<transform>(entity); // // auto targetTransform = rotateEntts.get<transform>(entity);
@ -161,6 +195,9 @@ private:
float m_angle; float m_angle;
Uint64 m_lastTicks; Uint64 m_lastTicks;
float m_dayTime = 0.0f; // accumulates time for day-night cycle
float m_dayLength = 60.0f; // seconds per full day cycle
bool m_paused = false; bool m_paused = false;
float m_yaw = -90.0f; // looking along -Z initially float m_yaw = -90.0f; // looking along -Z initially

View File

@ -29,9 +29,6 @@ void Engine::Run(std::unique_ptr<IApplication> app) {
s_app->OnUpdate(); s_app->OnUpdate();
glClearColor(0x18/255.0f, 0x18/255.0f, 0x18/255.0f, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
s_app->OnRender(); s_app->OnRender();
s_window->SwapBuffers(); s_window->SwapBuffers();

View File

@ -38,16 +38,10 @@ Renderer::Renderer()
m_model = glm::mat4(1.f); m_model = glm::mat4(1.f);
SwitchShader(&m_shader); m_shader.use();
m_shader.setMat4("u_projection", m_proj); m_shader.setMat4("u_projection", m_proj);
} }
void Renderer::SwitchShader(Shader *newShader) {
m_currentShader = newShader;
m_currentShader->use();
}
void Renderer::OnWindowResized(int w, int h) { void Renderer::OnWindowResized(int w, int h) {
m_proj = glm::perspective( m_proj = glm::perspective(
static_cast<float>(M_PI_2), static_cast<float>(M_PI_2),
@ -59,24 +53,29 @@ void Renderer::OnWindowResized(int w, int h) {
m_depthShader.setMat4("u_projection", m_proj); m_depthShader.setMat4("u_projection", m_proj);
} }
void Renderer::ApplyLights(entt::registry& registry) { void Renderer::ApplyLights(entt::registry& registry, Shader &shader) {
auto lights = registry.view<light>(); auto lights = registry.view<light>();
// TODO: Pass Lights Data to depth shader as well // TODO: Pass Lights Data to depth shader as well
m_shader.setInt("lightsCount", static_cast<int>(lights.size())); shader.setInt("lightsCount", static_cast<int>(lights.size()));
size_t lightIndex = 0; size_t lightIndex = 0;
for (auto entity : lights) { for (auto entity : lights) {
auto &comp = registry.get<light>(entity); auto &l = registry.get<light>(entity);
auto &transf = registry.get<transform>(entity); auto &transf = registry.get<transform>(entity);
m_shader.setVec3("lights[" + std::to_string(lightIndex) + "].position", transf.position); shader.setInt("lights[" + std::to_string(lightIndex) + "].type", static_cast<int>(l.type));
m_shader.setVec3("lights[" + std::to_string(lightIndex) + "].color", comp.color); shader.setVec3("lights[" + std::to_string(lightIndex) + "].position", transf.position);
m_shader.setFloat("lights[" + std::to_string(lightIndex) + "].intensity", comp.intensity); shader.setVec3("lights[" + std::to_string(lightIndex) + "].color", l.color);
shader.setFloat("lights[" + std::to_string(lightIndex) + "].intensity", l.intensity);
shader.setMat4("lights[" + std::to_string(lightIndex) + "].lightSpace", l.lightSpace);
shader.setInt("lights[" + std::to_string(lightIndex) + "].shadowMap", 10 + lightIndex);
glActiveTexture(GL_TEXTURE10 + lightIndex);
glBindTexture(GL_TEXTURE_2D, l.shadowMap);
++lightIndex; ++lightIndex;
} }
} }
void Renderer::UpdateView(entt::registry& registry) { void Renderer::UpdateView(entt::registry& registry, Shader &shader) {
auto cam = registry.view<transform, camera>().back(); auto cam = registry.view<transform, camera>().back();
auto camTransform = registry.get<transform>(cam); auto camTransform = registry.get<transform>(cam);
@ -85,12 +84,12 @@ void Renderer::UpdateView(entt::registry& registry) {
camTransform.position + camTransform.rotation, camTransform.position + camTransform.rotation,
glm::vec3(0.f, 1.f, 0.f) glm::vec3(0.f, 1.f, 0.f)
); );
m_shader.setMat4("u_view", m_view); shader.setMat4("u_view", m_view);
m_shader.setVec3("viewPos", camTransform.position); shader.setVec3("viewPos", camTransform.position);
} }
void Renderer::RenderScene(entt::registry& registry) { void Renderer::RenderScene(entt::registry& registry, Shader &shader) {
auto view = registry.view<transform, mesh>(); auto view = registry.view<transform, mesh>();
for (auto [entity, transf, mesh] : view.each()) { for (auto [entity, transf, mesh] : view.each()) {
@ -100,110 +99,99 @@ void Renderer::RenderScene(entt::registry& registry) {
} }
if (registry.all_of<light>(entity)) { if (registry.all_of<light>(entity)) {
auto &comp = registry.get<light>(entity); auto &l = registry.get<light>(entity);
m_currentShader->setBool("isLight", true); shader.setBool("isLight", true);
m_currentShader->setVec3("currentLightColor", comp.color); shader.setVec3("currentLightColor", l.color);
} else { } else {
m_currentShader->setBool("isLight", false); shader.setBool("isLight", false);
m_currentShader->setVec3("currentLightColor", glm::vec3(0.f)); shader.setVec3("currentLightColor", glm::vec3(0.f));
} }
glm::mat4 rotation = glm::yawPitchRoll(transf.rotation.y, transf.rotation.x, transf.rotation.z); glm::mat4 rotation = glm::yawPitchRoll(transf.rotation.y, transf.rotation.x, transf.rotation.z);
m_model = glm::translate(glm::mat4(1.f), transf.position) * rotation; m_model = glm::translate(glm::mat4(1.f), transf.position) * rotation;
m_currentShader->setMat4("u_model", m_model); shader.setMat4("u_model", m_model);
mesh.object->Render(*m_currentShader); mesh.object->Render(shader);
} }
} }
void Renderer::GenerateShadowMaps(entt::registry& registry) { void Renderer::GenerateShadowMaps(entt::registry& registry) {
SwitchShader(&m_depthShader);
ApplyLights(registry);
UpdateView(registry);
glGenFramebuffers(1, &m_depth_fbo);
const unsigned int SHADOW_WIDTH = 1024, SHADOW_HEIGHT = 1024; const unsigned int SHADOW_WIDTH = 1024, SHADOW_HEIGHT = 1024;
glGenTextures(1, &m_depthMap); m_depthShader.use();
glBindTexture(GL_TEXTURE_2D, m_depthMap);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24,
SHADOW_WIDTH, SHADOW_HEIGHT, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); auto lights = registry.view<light>();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
float borderColor[] = {1.0f, 1.0f, 1.0f, 1.0f}; for (auto [lEntt, l] : lights.each()) {
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor); // TODO: support other light types when ready
if (l.type != light::LightType::DIRECTIONAL) return;
glBindFramebuffer(GL_FRAMEBUFFER, m_depth_fbo); glGenFramebuffers(1, &l.fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depthMap, 0); glGenTextures(1, &l.shadowMap);
glDrawBuffer(GL_NONE); glBindTexture(GL_TEXTURE_2D, l.shadowMap);
glReadBuffer(GL_NONE); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24,
glBindFramebuffer(GL_FRAMEBUFFER, 0); SHADOW_WIDTH, SHADOW_HEIGHT, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
m_shader.setInt("shadowMap", 31); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
float borderColor[] = {1.0f, 1.0f, 1.0f, 1.0f};
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor);
glBindFramebuffer(GL_FRAMEBUFFER, l.fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, l.shadowMap, 0);
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
} }
void Renderer::Render(entt::registry& registry) { void Renderer::Render(entt::registry& registry) {
const unsigned int SHADOW_WIDTH = 1024, SHADOW_HEIGHT = 1024; const unsigned int SHADOW_WIDTH = 1024, SHADOW_HEIGHT = 1024;
glClearColor(0.1f, 0.1f, 0.1f, 1.0f); m_depthShader.use();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
auto shadowLight = registry.view<light, transform>().back(); auto lights = registry.view<light, transform>();
auto &comp = registry.get<transform>(shadowLight);
float near_plane = 0.1f, far_plane = 50.0f; // pick bounds that cover your scene for (auto [lEntt, l, t] : lights.each()) {
glm::vec3 lightPos = comp.position; // TODO: support other light types when ready
glm::vec3 target = glm::vec3(0.0f, 0.5f, 0.0f); if (l.type != light::LightType::DIRECTIONAL) return;
glm::mat4 lightView = glm::lookAt(lightPos, target, glm::vec3(0.0f, 1.0f, 0.0f));
glm::mat4 lightProjection = glm::ortho(-6.0f, 6.0f, -6.0f, 6.0f, 1.0f, 20.0f);
glm::mat4 lightSpaceMatrix = lightProjection * lightView;
// lightView = glm::lookAt(/*eye*/ -lightDir * distance, /*center*/ vec3(0), up) glClearColor(0x18/255.0f, 0x18/255.0f, 0x18/255.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// glm::mat4 lightSpaceMatrix = lightProjection * lightView; float near_plane = 0.1f, far_plane = 50.0f;
SwitchShader(&m_depthShader); glm::vec3 target = glm::vec3(0.0f, 0.5f, 0.0f);
m_currentShader->setMat4("u_lightSpace", lightSpaceMatrix); glm::mat4 lightView = glm::lookAt(t.position, target, glm::vec3(0.0f, 1.0f, 0.0f));
glm::mat4 lightProjection = glm::ortho(-6.0f, 6.0f, -6.0f, 6.0f, 1.0f, 20.0f);
glm::mat4 lightSpaceMatrix = lightProjection * lightView;
// enable culling and render front faces to the shadow map m_depthShader.setMat4("u_lightSpace", lightSpaceMatrix);
glEnable(GL_CULL_FACE); l.lightSpace = lightSpaceMatrix;
glCullFace(GL_FRONT); // only for the depth pass
// or use polygon offset:
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(2.0f, 4.0f);
glViewport(0, 0, SHADOW_WIDTH, SHADOW_HEIGHT); glCullFace(GL_FRONT);
glBindFramebuffer(GL_FRAMEBUFFER, m_depth_fbo); glViewport(0, 0, SHADOW_WIDTH, SHADOW_HEIGHT);
glClear(GL_DEPTH_BUFFER_BIT); glBindFramebuffer(GL_FRAMEBUFFER, l.fbo);
RenderScene(registry); glClear(GL_DEPTH_BUFFER_BIT);
glBindFramebuffer(GL_FRAMEBUFFER, 0); RenderScene(registry, m_depthShader);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glCullFace(GL_BACK);
}
// enable culling and render front faces to the shadow map // actual rendering
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK); // only for the depth pass
// or use polygon offset:
glDisable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(0.f, 1.f);
glViewport(0, 0, Window::GetWidth(), Window::GetHeight()); glViewport(0, 0, Window::GetWidth(), Window::GetHeight());
glClearColor(0x18/255.0f, 0x18/255.0f, 0x18/255.0f, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
SwitchShader(&m_shader); m_shader.use();
ApplyLights(registry); ApplyLights(registry, m_shader);
UpdateView(registry, m_shader);
UpdateView(registry); RenderScene(registry, m_shader);
m_currentShader->setMat4("u_lightSpace", lightSpaceMatrix);
glActiveTexture(GL_TEXTURE31);
glBindTexture(GL_TEXTURE_2D, m_depthMap);
RenderScene(registry);
} }

View File

@ -1,18 +1,20 @@
#version 410 core #version 410 core
out vec4 FragColor; out vec4 FragColor;
in vec3 vertexPos; in vec3 vertexPos; // must be world-space position
in vec3 vertexNormal; in vec3 vertexNormal;
in vec2 TexCoords; in vec2 TexCoords;
in vec4 fragPosLightSpace;
uniform vec3 viewPos; uniform vec3 viewPos;
// Lights // Lights
struct Light { struct Light {
vec3 position; int type; // 0 = directional (shadowed), other = non-directional (no shadow)
vec3 position; // for directional: encode light direction (see note)
vec3 color; vec3 color;
float intensity; float intensity;
mat4 lightSpace;
sampler2D shadowMap;
}; };
#define MAX_LIGHTS 10 #define MAX_LIGHTS 10
uniform int lightsCount; uniform int lightsCount;
@ -36,50 +38,53 @@ uniform bool useMetallicMap;
uniform bool useRoughnessMap; uniform bool useRoughnessMap;
uniform bool useAoMap; uniform bool useAoMap;
// Shadows
uniform sampler2D shadowMap;
uniform float opacity; uniform float opacity;
// uniform int currentLight;
#define PI 3.14159265359 #define PI 3.14159265359
#define LIGHT_COLOR vec3(1.0, 1.0, 1.0) #define LIGHT_COLOR vec3(1.0, 1.0, 1.0)
float ShadowCalculation(vec4 fragPosLightSpace, vec3 N, vec3 L) // -------------------------------------------------------------
// Improved ShadowCalculation: returns [0,1] shadow factor (1 = fully in shadow)
float ShadowCalculation(sampler2D shadowMap, mat4 lightSpace, vec3 N, vec3 L)
{ {
// transform to [0,1] // Transform fragment position to light's clip / NDC space
vec4 fragPosLightSpace = lightSpace * vec4(vertexPos, 1.0);
// perspective divide
vec3 projCoords = fragPosLightSpace.xyz / fragPosLightSpace.w; vec3 projCoords = fragPosLightSpace.xyz / fragPosLightSpace.w;
// to [0,1]
projCoords = projCoords * 0.5 + 0.5; projCoords = projCoords * 0.5 + 0.5;
// if outside light's orthographic frustum => not in shadow // if outside the light's orthographic frustum (xy outside or z > 1), consider unshadowed
if (projCoords.z > 1.0 || projCoords.x < 0.0 || projCoords.x > 1.0 || projCoords.y < 0.0 || projCoords.y > 1.0) if (projCoords.z > 1.0) {
return 0.0; return 0.0;
}
if (projCoords.x < 0.0 || projCoords.x > 1.0 || projCoords.y < 0.0 || projCoords.y > 1.0) {
return 0.0;
}
// get depth from shadow map
float closestDepth = texture(shadowMap, projCoords.xy).r;
float currentDepth = projCoords.z; float currentDepth = projCoords.z;
// basic bias (slope-dependent)
// bias to prevent self-shadowing (depend on slope)
float bias = max(0.001 * (1.0 - dot(N, L)), 0.0005); float bias = max(0.001 * (1.0 - dot(N, L)), 0.0005);
// PCF (3x3) // PCF (3x3)
float shadow = 0.0; float shadow = 0.0;
vec2 texelSize = 1.0 / textureSize(shadowMap, 0); vec2 texelSize = 1.0 / textureSize(shadowMap, 0);
for(int x = -1; x <= 1; ++x) for (int x = -1; x <= 1; ++x) {
{ for (int y = -1; y <= 1; ++y) {
for(int y = -1; y <= 1; ++y)
{
float pcfDepth = texture(shadowMap, projCoords.xy + vec2(x, y) * texelSize).r; float pcfDepth = texture(shadowMap, projCoords.xy + vec2(x, y) * texelSize).r;
shadow += (currentDepth - bias > pcfDepth ? 1.0 : 0.0); shadow += (currentDepth - bias) > pcfDepth ? 1.0 : 0.0;
} }
} }
shadow /= 9.0; shadow /= 9.0;
// clamp to [0,1]
shadow = clamp(shadow, 0.0, 1.0);
return shadow; return shadow;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// Helper functions (GGX, Fresnel, Geometry) // PBR helpers (unchanged)
float DistributionGGX(vec3 N, vec3 H, float roughness) float DistributionGGX(vec3 N, vec3 H, float roughness)
{ {
float a = roughness * roughness; float a = roughness * roughness;
@ -137,22 +142,33 @@ void main()
vec3 F0 = mix(vec3(0.04), baseColor, metal); vec3 F0 = mix(vec3(0.04), baseColor, metal);
vec3 Lo = vec3(0.0); vec3 Lo = vec3(0.0);
// FragColor = vec4(1.0 - shadow, 1.0 - shadow, 1.0 - shadow, 1.0);
// return;
float shadow = 0.0;
// Loop over all lights // Loop over all lights
for (int i = 0; i < lightsCount; i++) for (int i = 0; i < lightsCount; i++)
{ {
vec3 L = normalize(lights[i].position - vertexPos); // compute light vector L depending on type
vec3 L;
if (lights[i].type == 0) {
// directional light: convention here is that lights[i].position stores the direction
// *towards* the light (for example, for sun direction you may upload -sunDir).
// Adjust according to your CPU-side convention.
L = normalize(lights[i].position); // expect this to be a direction
} else {
// point / spot style light: position is world-space point
L = normalize(lights[i].position - vertexPos);
}
vec3 H = normalize(V + L); vec3 H = normalize(V + L);
float NDF = DistributionGGX(N, H, rough); float NDF = DistributionGGX(N, H, rough);
float G = GeometrySmith(N, V, L, rough); float G = GeometrySmith(N, V, L, rough);
vec3 F = fresnelSchlick(max(dot(H,V),0.0), F0); vec3 F = fresnelSchlick(max(dot(H,V),0.0), F0);
shadow = ShadowCalculation(fragPosLightSpace, N, L); // compute shadow only for directional (type==0) lights that have shadow maps
float shadow_i = 0.0;
if (lights[i].type == 0) {
shadow_i = ShadowCalculation(lights[i].shadowMap, lights[i].lightSpace, N, L);
}
vec3 numerator = NDF * G * F; vec3 numerator = NDF * G * F;
float denominator = 4.0 * max(dot(N,V),0.0) * max(dot(N,L),0.0) + 0.001; float denominator = 4.0 * max(dot(N,V),0.0) * max(dot(N,L),0.0) + 0.001;
@ -165,14 +181,19 @@ void main()
float NdotL = max(dot(N,L), 0.0); float NdotL = max(dot(N,L), 0.0);
vec3 radiance = lights[i].color * lights[i].intensity; vec3 radiance = lights[i].color * lights[i].intensity;
Lo += (kD * baseColor / PI + specular) * radiance * NdotL;
// Apply shadow_i only to this light's contribution:
// when shadow_i == 1.0 -> this light contributes 0
// when shadow_i == 0.0 -> full contribution
vec3 contrib = (kD * baseColor / PI + specular) * radiance * NdotL * (1.0 - shadow_i);
Lo += contrib;
} }
// Ambient // Ambient (unshadowed by design)
vec3 ambient = vec3(0.03) * baseColor * aoValue; vec3 ambient = vec3(0.03) * baseColor * aoValue;
// TODO: apply shadow vec3 color = ambient + Lo;
vec3 color = ambient + (1.0 - shadow) * Lo;
// HDR tonemapping + gamma // HDR tonemapping + gamma
color = color / (color + vec3(1.0)); color = color / (color + vec3(1.0));

View File

@ -1,81 +0,0 @@
#version 410 core
// Output color of the fragment (pixel)
out vec4 FragColor; // RGBA color for the fragment, where A is the alpha (opacity)
in vec3 vertexPos;
in vec3 vertexNormal;
in vec2 TexCoords;
uniform vec3 viewPos;
// Lights
struct Light {
vec3 position;
vec3 color;
float intensity;
};
#define MAX_LIGHTS 10
uniform int lightsCount;
uniform Light lights[MAX_LIGHTS];
// From Object Renderer
uniform vec3 ambientColor;
uniform vec3 diffuseColor;
uniform vec3 specularColor;
uniform float ambientStrength;
uniform float specularStrength;
uniform float shininess;
uniform bool useSpecular;
uniform float opacity;
uniform sampler2D diffuseTex;
uniform bool useTexture;
uniform bool isLight;
void main()
{
// Lighting vectors
vec3 norm = normalize(vertexNormal);
vec3 viewDir = normalize(viewPos - vertexPos);
// vec3 viewDir = normalize(-vertexPos);
vec3 ambient = ambientStrength * ambientColor;
vec3 texColor = (useTexture)
? texture(diffuseTex, TexCoords).rgb
: diffuseColor;
vec3 result = ambient;
for (int i = 0; i < lightsCount; i++) {
vec3 lightDir = normalize(lights[i].position - vertexPos);
vec3 halfDir = normalize(lightDir + viewDir);
// Blinn Phong
float diff = max(dot(norm, lightDir), 0.0);
vec3 diffuse = diff * diffuseColor * lights[i].color * lights[i].intensity;
float spec = pow(max(dot(norm, halfDir), 0.0), clamp(shininess, 2.0, 256.0));
vec3 specular = (useSpecular) ?
specularStrength * spec * specularColor * lights[i].color * lights[i].intensity
: vec3(0.0);
result += (diffuse + specular);
}
result *= texColor;
if (isLight) {
vec3 emissive = vec3(1.0, 1.0, 1.0) * 10.0; // big intensity
FragColor = vec4(emissive, 1.0);
return;
}
FragColor = vec4(result, opacity);
}

View File

@ -15,7 +15,6 @@ out vec4 fragPosLightSpace;
uniform mat4 u_model; // Model matrix: transforms from local space to world space uniform mat4 u_model; // Model matrix: transforms from local space to world space
uniform mat4 u_view; // View matrix: transforms from world space to camera space (view space) uniform mat4 u_view; // View matrix: transforms from world space to camera space (view space)
uniform mat4 u_projection; // Projection matrix: transforms from camera space to clip space uniform mat4 u_projection; // Projection matrix: transforms from camera space to clip space
uniform mat4 u_lightSpace;
void main() void main()
{ {
@ -27,7 +26,7 @@ void main()
TexCoords = texCoord; TexCoords = texCoord;
fragPosLightSpace = u_lightSpace * vec4(vertexPos, 1.0); // fragPosLightSpace = u_lightSpace * vec4(vertexPos, 1.0);
gl_Position = u_projection * u_view * vec4(vertexPos, 1.0); gl_Position = u_projection * u_view * vec4(vertexPos, 1.0);
} }

View File

@ -54,6 +54,7 @@ Window::Window(const char* title, int width, int height) {
glEnable(GL_DEBUG_OUTPUT); glEnable(GL_DEBUG_OUTPUT);
glEnable(GL_DEPTH_TEST); glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glDebugMessageCallback(MessageCallback, nullptr); glDebugMessageCallback(MessageCallback, nullptr);
glViewport(0, 0, m_width, m_height); glViewport(0, 0, m_width, m_height);