cntrl/src/render/shadow_map.cpp

106 lines
3.1 KiB
C++

#include "render/shadow_map.hpp"
#include "raymath.h"
#include "rlgl.h"
#include <cmath>
namespace {
constexpr float kLightDistance = 60.0f;
constexpr double kNear = 0.5;
constexpr double kFar = 300.0;
Vector3 light_dir() {
return Vector3Normalize(Vector3{-0.42f, 0.86f, 0.30f});
}
} // namespace
bool ShadowMap::init(int size) {
size_ = size;
target_ = RenderTexture2D{};
target_.id = rlLoadFramebuffer();
if (target_.id == 0) {
TraceLog(LOG_WARNING, "SHADOW: framebuffer creation failed");
return false;
}
rlEnableFramebuffer(target_.id);
target_.texture.width = size;
target_.texture.height = size;
target_.depth.id = rlLoadTextureDepth(size, size, false);
target_.depth.width = size;
target_.depth.height = size;
target_.depth.format = 19;
target_.depth.mipmaps = 1;
rlFramebufferAttach(target_.id, target_.depth.id, RL_ATTACHMENT_DEPTH,
RL_ATTACHMENT_TEXTURE2D, 0);
const bool complete = rlFramebufferComplete(target_.id);
rlDisableFramebuffer();
if (!complete || target_.depth.id == 0) {
TraceLog(LOG_WARNING, "SHADOW: depth-texture framebuffer incomplete");
rlUnloadFramebuffer(target_.id);
target_ = RenderTexture2D{};
return false;
}
rlSetClipPlanes(kNear, kFar);
camera_.projection = CAMERA_ORTHOGRAPHIC;
camera_.up = Vector3{0.0f, 1.0f, 0.0f};
camera_.fovy = ShadowMap::kExtent;
ready_ = true;
TraceLog(LOG_INFO, "SHADOW: %dx%d depth texture, hard filter", size, size);
return true;
}
void ShadowMap::shutdown() {
if (target_.id != 0) rlUnloadFramebuffer(target_.id);
target_ = RenderTexture2D{};
ready_ = false;
}
void ShadowMap::update(Vec2 focus) {
if (!ready_) return;
const Vector3 dir = light_dir();
const Vector3 forward = Vector3Scale(dir, -1.0f);
const Vector3 right = Vector3Normalize(
Vector3CrossProduct(forward, Vector3{0.0f, 1.0f, 0.0f}));
const Vector3 up = Vector3Normalize(Vector3CrossProduct(right, forward));
const Vector3 center{focus.x, 0.0f, focus.y};
const float texel = ShadowMap::kExtent / static_cast<float>(size_);
const float along_right = Vector3DotProduct(center, right);
const float along_up = Vector3DotProduct(center, up);
const float snap_right =
std::round(along_right / texel) * texel - along_right;
const float snap_up = std::round(along_up / texel) * texel - along_up;
const Vector3 snapped = center + Vector3Scale(right, snap_right)
+ Vector3Scale(up, snap_up);
camera_.position = snapped + Vector3Scale(dir, kLightDistance);
camera_.target = snapped;
}
void ShadowMap::begin() {
if (!ready_) return;
BeginTextureMode(target_);
ClearBackground(BLACK);
BeginMode3D(camera_);
view_ = rlGetMatrixModelview();
proj_ = rlGetMatrixProjection();
vp_ = MatrixMultiply(view_, proj_);
}
void ShadowMap::end() {
if (!ready_) return;
EndMode3D();
EndTextureMode();
}
void ShadowMap::bind() const {
if (!ready_) return;
rlActiveTextureSlot(kTextureSlot);
rlEnableTexture(target_.depth.id);
}