Added hard shadow mapping with static and dynamic casters

This commit is contained in:
dandovlatov 2026-11-25 02:00:19 +04:00
parent 4f0f7b27f4
commit 84562ba1ef
17 changed files with 457 additions and 10 deletions

View file

@ -77,6 +77,7 @@ add_executable(debris_test tests/debris_test.cpp
src/render/debris.cpp src/render/debris.cpp
src/render/box_batch.cpp src/render/box_batch.cpp
src/render/models.cpp src/render/models.cpp
src/render/shadow_map.cpp
src/render/profiler.cpp) src/render/profiler.cpp)
target_link_libraries(debris_test PRIVATE raylib level_core) target_link_libraries(debris_test PRIVATE raylib level_core)
add_dependencies(debris_test bake_level) add_dependencies(debris_test bake_level)
@ -135,6 +136,7 @@ add_executable(cntrl
src/render/box_batch.cpp src/render/box_batch.cpp
src/render/models.cpp src/render/models.cpp
src/render/concrete.cpp src/render/concrete.cpp
src/render/shadow_map.cpp
src/render/aura.cpp src/render/aura.cpp
src/render/profiler.cpp src/render/profiler.cpp
src/render/graphics_settings.cpp src/render/graphics_settings.cpp

View file

@ -73,7 +73,10 @@ The window defaults to **1400×900** for everyday development — it fits under
1080p desktop's top bar without being scaled down. `--720p` (1280×720) and 1080p desktop's top bar without being scaled down. `--720p` (1280×720) and
`--1080p` (1920×1080) are explicit test resolutions for perf/visual checks; `--1080p` (1920×1080) are explicit test resolutions for perf/visual checks;
`--dev` returns to the default. The scene is shown with its raw palette by `--dev` returns to the default. The scene is shown with its raw palette by
default; pass `--post-fx` for the graded/bloomed/VHS look. default; pass `--post-fx` for the graded/bloomed/VHS look. Hard directional
shadows (one 2048² depth-only pass over the concrete mesh, static props and
actors) are on by default; `--shadows off` compares against the old unshadowed
look.
Dev tools: `--bot` (kiting autopilot), `--no-damage` (stress mode), Dev tools: `--bot` (kiting autopilot), `--no-damage` (stress mode),
`--uncapped` (drop the 60 FPS target to measure headroom; F10 shows the profiler), `--uncapped` (drop the 60 FPS target to measure headroom; F10 shows the profiler),

View file

@ -25,6 +25,22 @@ uniform float uOutline = 0.0;
uniform float uGlow = 0.0; uniform float uGlow = 0.0;
uniform float uHiss = 0.0; uniform float uHiss = 0.0;
uniform mat4 uLightVP;
uniform sampler2D uShadowMap;
uniform float uShadowDarkness = 0.0;
float shadow_factor(vec3 n, vec3 light_dir)
{
if (uShadowDarkness <= 0.0) return 1.0;
vec4 q = uLightVP * vec4(vWorld, 1.0);
vec3 p = q.xyz / q.w * 0.5 + 0.5;
if (p.x < 0.0 || p.x > 1.0 || p.y < 0.0 || p.y > 1.0 || p.z >= 1.0)
return 1.0;
float bias = max(0.00034 * (1.0 - dot(n, light_dir)), 0.00007);
return texture(uShadowMap, p.xy).r < p.z - bias
? 1.0 - uShadowDarkness : 1.0;
}
// Cheap trig-free value noise (Dave Hoskins style hash). Two lookups feed a // Cheap trig-free value noise (Dave Hoskins style hash). Two lookups feed a
// domain warp, one more gives the filament field — no extra render targets. // domain warp, one more gives the filament field — no extra render targets.
float hash21(vec2 p) float hash21(vec2 p)
@ -64,8 +80,9 @@ void main()
vec3 ramp = texture(actorRamp, vec2(clamp(ndl, 0.0, 1.0), 0.5)).rgb * 1.7; vec3 ramp = texture(actorRamp, vec2(clamp(ndl, 0.0, 1.0), 0.5)).rgb * 1.7;
float fill = max(dot(n, fillDir), 0.0); float fill = max(dot(n, fillDir), 0.0);
float hemi = 0.5 + 0.5 * n.y; float hemi = 0.5 + 0.5 * n.y;
float shade = shadow_factor(n, keyDir);
vec3 lit = base * ramp * (0.88 + 0.12 * hemi); vec3 lit = base * ramp * (0.88 + 0.12 * hemi) * shade;
lit += base * fill * 0.13; lit += base * fill * 0.13;
// Two-tone rim: cold fluorescent in the House, faction hue on corrupted // Two-tone rim: cold fluorescent in the House, faction hue on corrupted
@ -89,7 +106,7 @@ void main()
vec3 halfDir = normalize(keyDir + viewDir); vec3 halfDir = normalize(keyDir + viewDir);
float spec = pow(max(dot(n, halfDir), 0.0), 42.0) float spec = pow(max(dot(n, halfDir), 0.0), 42.0)
* (0.06 + 0.10 * smoothstep(0.35, 0.8, bright)); * (0.06 + 0.10 * smoothstep(0.35, 0.8, bright));
lit += vec3(0.90, 0.88, 0.82) * spec; lit += vec3(0.90, 0.88, 0.82) * spec * shade;
// The House bleeds red into unlit faces as containment fails. // The House bleeds red into unlit faces as containment fails.
lit += vec3(0.26, 0.012, 0.018) * (1.0 - ndl) * uCorruption * 0.30; lit += vec3(0.26, 0.012, 0.018) * (1.0 - ndl) * uCorruption * 0.30;

View file

@ -19,6 +19,22 @@ uniform vec3 uCameraPos;
uniform float uScale = 0.42; uniform float uScale = 0.42;
uniform float uCorruption = 0.0; uniform float uCorruption = 0.0;
uniform mat4 uLightVP;
uniform sampler2D uShadowMap;
uniform float uShadowDarkness = 0.0;
float shadow_factor(vec3 n, vec3 light_dir)
{
if (uShadowDarkness <= 0.0) return 1.0;
vec4 q = uLightVP * vec4(vWorld, 1.0);
vec3 p = q.xyz / q.w * 0.5 + 0.5;
if (p.x < 0.0 || p.x > 1.0 || p.y < 0.0 || p.y > 1.0 || p.z >= 1.0)
return 1.0;
float bias = max(0.00034 * (1.0 - dot(n, light_dir)), 0.00007);
return texture(uShadowMap, p.xy).r < p.z - bias
? 1.0 - uShadowDarkness : 1.0;
}
// Floor 01 wayfinding: a low-strength tint per room, applied to up-facing // Floor 01 wayfinding: a low-strength tint per room, applied to up-facing
// concrete only. The PBR detail stays; this replaces the old opaque flat plates. // concrete only. The PBR detail stays; this replaces the old opaque flat plates.
#define MAX_ROOM_TINTS 10 #define MAX_ROOM_TINTS 10
@ -53,8 +69,9 @@ void main()
float ramp = mix(0.62, 1.30, smoothstep(0.06, 0.94, ndl)); float ramp = mix(0.62, 1.30, smoothstep(0.06, 0.94, ndl));
float fill = max(dot(n, fill_dir), 0.0); float fill = max(dot(n, fill_dir), 0.0);
float hemi = 0.5 + 0.5 * n.y; float hemi = 0.5 + 0.5 * n.y;
float shade = shadow_factor(n, key_dir);
vec3 lit = albedo * (ramp * (0.92 + 0.08 * hemi) + 0.16 * fill); vec3 lit = albedo * (ramp * shade * (0.92 + 0.08 * hemi) + 0.16 * fill);
float rim = pow(1.0 - max(dot(n, normalize(vec3(0.0, 0.6, 0.8))), 0.0), 3.0); float rim = pow(1.0 - max(dot(n, normalize(vec3(0.0, 0.6, 0.8))), 0.0), 3.0);
lit += vec3(0.05, 0.06, 0.07) * rim; lit += vec3(0.05, 0.06, 0.07) * rim;
@ -63,7 +80,7 @@ void main()
vec3 half_dir = normalize(key_dir + view_dir); vec3 half_dir = normalize(key_dir + view_dir);
float gloss = mix(48.0, 7.0, rough); float gloss = mix(48.0, 7.0, rough);
float spec = pow(max(dot(n, half_dir), 0.0), gloss) * (1.0 - rough) * 0.30; float spec = pow(max(dot(n, half_dir), 0.0), gloss) * (1.0 - rough) * 0.30;
lit += vec3(0.92, 0.90, 0.82) * spec; lit += vec3(0.92, 0.90, 0.82) * spec * shade;
// Hiss bleeding into the unlit side of the room as containment fails. // Hiss bleeding into the unlit side of the room as containment fails.
lit += vec3(0.12, 0.008, 0.012) * (1.0 - ndl) * uCorruption * 0.22; lit += vec3(0.12, 0.008, 0.012) * (1.0 - ndl) * uCorruption * 0.22;

View file

@ -0,0 +1,6 @@
#version 330
out vec4 finalColor;
void main()
{
finalColor = vec4(1.0);
}

View file

@ -24,6 +24,7 @@ committed. Continue with **P1** below if more headroom is wanted (e.g. for
| 1400x900 dev default, 17 enemies | 337 | 4.0 ms | 1.2 ms | | 1400x900 dev default, 17 enemies | 337 | 4.0 ms | 1.2 ms |
| 1920x1080 fullscreen, raw | 259 | 3.2 ms | 2.4 ms | | 1920x1080 fullscreen, raw | 259 | 3.2 ms | 2.4 ms |
| 1920x1080 fullscreen, `--post-fx` | 172 | 5.6 ms | 2.9 ms | | 1920x1080 fullscreen, `--post-fx` | 172 | 5.6 ms | 2.9 ms |
| 1920x1080 fullscreen, `--post-fx`, hard shadows | 524 | 1.9 ms | 5.2 ms |
The overlay title shows `UNCAPPED`; `Present` drops to ~0.3 ms because VSync The overlay title shows `UNCAPPED`; `Present` drops to ~0.3 ms because VSync
waiting is gone, so these numbers show real per-frame cost. Even with the full waiting is gone, so these numbers show real per-frame cost. Even with the full

View file

@ -82,8 +82,14 @@ src/
1 humanoid, 2 blob, 3 crystal) — no skeletons, no extra draw calls. The single 1 humanoid, 2 blob, 3 crystal) — no skeletons, no extra draw calls. The single
player agent instead has a Blender skeleton and baked actions, CPU-skinned by player agent instead has a Blender skeleton and baked actions, CPU-skinned by
raylib. Hiss actors and the agent get a cheap expanded-backface ink outline. raylib. Hiss actors and the agent get a cheap expanded-backface ink outline.
- **Blob shadows** (flattened cylinders) — no shadow maps in raylib core; they - **Hard shadow map** (`render/shadow_map.*`) — one 2048² depth-only FBO built
ground the puppets without cost. from rlgl primitives (raylib 6.2 has no shadow API). An orthographic light
camera follows the player with texel snapping; the caster pass reuses the
environment/actor vertex shaders with a depth-only fragment shader so the
procedural rigs match, and culls to the light frustum. `concrete.fs` and
`actor.fs` do a single NEAREST depth compare (no PCF) with a slope-scaled
bias, darkening only the direct term. Blob quads remain as contact shading.
`--shadows off` disables the pass and the receiver lookup.
- **Sparks / glows / world objects** are camera-facing billboards using one - **Sparks / glows / world objects** are camera-facing billboards using one
procedural glow sprite; damage numbers and health bars use `GetWorldToScreen`. procedural glow sprite; damage numbers and health bars use `GetWorldToScreen`.
- Post FX: scene into a full-res `RenderTexture`, half-res bright pass + separable - Post FX: scene into a full-res `RenderTexture`, half-res bright pass + separable

View file

@ -42,6 +42,7 @@ struct Options {
bool bot = false; // --bot: kiting autopilot (M6 balance-bot seed) bool bot = false; // --bot: kiting autopilot (M6 balance-bot seed)
bool no_damage = false; // --no-damage: stress-test mode bool no_damage = false; // --no-damage: stress-test mode
bool post_fx = false; // --post-fx: opt into graded/bloomed look bool post_fx = false; // --post-fx: opt into graded/bloomed look
bool shadows = true; // --shadows off|hard: hard depth-map shadows
bool uncapped = false; // --uncapped: remove the 60 FPS target for headroom tests bool uncapped = false; // --uncapped: remove the 60 FPS target for headroom tests
bool hiss_test = false; // --hiss-test: close-up of one Hiss Brute bool hiss_test = false; // --hiss-test: close-up of one Hiss Brute
bool room_test = false; // --room-test: frozen look at the open-plan room bool room_test = false; // --room-test: frozen look at the open-plan room
@ -88,6 +89,9 @@ Options parse_options(int argc, char** argv) {
opts.height = k720pHeight; opts.height = k720pHeight;
} else if (std::strcmp(argv[i], "--post-fx") == 0) { } else if (std::strcmp(argv[i], "--post-fx") == 0) {
opts.post_fx = true; opts.post_fx = true;
} else if (std::strcmp(argv[i], "--shadows") == 0 && i + 1 < argc) {
const char* value = argv[++i];
opts.shadows = std::strcmp(value, "off") != 0;
} else if (std::strcmp(argv[i], "--uncapped") == 0) { } else if (std::strcmp(argv[i], "--uncapped") == 0) {
opts.uncapped = true; opts.uncapped = true;
} else if (std::strcmp(argv[i], "--hiss-test") == 0) { } else if (std::strcmp(argv[i], "--hiss-test") == 0) {
@ -258,6 +262,8 @@ int main(int argc, char** argv) {
// The future graphics menu writes this same setting; --aniso lets us // The future graphics menu writes this same setting; --aniso lets us
// exercise it from the CLI until that menu exists. // exercise it from the CLI until that menu exists.
gfx::graphics_settings().concrete_filter = gfx::filtering_from_aniso(opts.aniso); gfx::graphics_settings().concrete_filter = gfx::filtering_from_aniso(opts.aniso);
gfx::graphics_settings().shadows = opts.shadows ? gfx::ShadowQuality::Hard
: gfx::ShadowQuality::Off;
InitWindow(opts.width, opts.height, "FBC: NIGHT SHIFT — pre-alpha"); InitWindow(opts.width, opts.height, "FBC: NIGHT SHIFT — pre-alpha");
const int monitor = GetCurrentMonitor(); const int monitor = GetCurrentMonitor();
if (opts.fullscreen) { if (opts.fullscreen) {
@ -454,6 +460,11 @@ int main(int argc, char** argv) {
PROF_BEGIN_GPU(); PROF_BEGIN_GPU();
PROF_BEGIN_CPU(profiler::Sec_Scene);
presenter.draw_shadow_map(
game, gfx::graphics_settings().shadows == gfx::ShadowQuality::Hard);
PROF_END_CPU(profiler::Sec_Scene);
// Only the scene renders into the post-FX target: bloom, corruption and // Only the scene renders into the post-FX target: bloom, corruption and
// the damage flash must never tint the HUD. The default raw palette // the damage flash must never tint the HUD. The default raw palette
// draws straight to the backbuffer — no full-res render target or blit. // draws straight to the backbuffer — no full-res render target or blit.

View file

@ -3,6 +3,7 @@
#include "render/layout.hpp" #include "render/layout.hpp"
#include "render/profiler.hpp" #include "render/profiler.hpp"
#include "render/graphics_settings.hpp" #include "render/graphics_settings.hpp"
#include "render/shadow_map.hpp"
#include "raymath.h" #include "raymath.h"
@ -161,6 +162,22 @@ void ConcreteMaterial::init(float arena, const Floor* floor) {
loc_room_rect_ = GetShaderLocation(shader_, "uRoomRect[0]"); loc_room_rect_ = GetShaderLocation(shader_, "uRoomRect[0]");
loc_room_tint_ = GetShaderLocation(shader_, "uRoomTint[0]"); loc_room_tint_ = GetShaderLocation(shader_, "uRoomTint[0]");
loc_room_count_ = GetShaderLocation(shader_, "uRoomCount"); loc_room_count_ = GetShaderLocation(shader_, "uRoomCount");
loc_light_vp_ = GetShaderLocation(shader_, "uLightVP");
loc_shadow_map_ = GetShaderLocation(shader_, "uShadowMap");
loc_shadow_darkness_ = GetShaderLocation(shader_, "uShadowDarkness");
if (loc_shadow_map_ >= 0) {
const int slot = ShadowMap::kTextureSlot;
SetShaderValue(shader_, loc_shadow_map_, &slot, SHADER_UNIFORM_INT);
}
if (const std::string depth_fs = resolve("assets/shaders/shadow_depth.fs");
!depth_fs.empty()) {
depth_shader_ = LoadShader(vs.c_str(), depth_fs.c_str());
depth_ok_ = depth_shader_.id != 0;
if (depth_ok_) {
depth_material_ = LoadMaterialDefault();
depth_material_.shader = depth_shader_;
}
}
if (floor != nullptr) load_room_tints(*floor); if (floor != nullptr) load_room_tints(*floor);
// The floor is sealed and glossier than the raw walls/pillars; vertex alpha // The floor is sealed and glossier than the raw walls/pillars; vertex alpha
@ -243,15 +260,18 @@ void ConcreteMaterial::apply_texture_filter() {
void ConcreteMaterial::shutdown() { void ConcreteMaterial::shutdown() {
if (mesh_ok_) UnloadMesh(mesh_); if (mesh_ok_) UnloadMesh(mesh_);
if (shader_ok_) UnloadMaterial(material_); // also releases shader_ if (shader_ok_) UnloadMaterial(material_); // also releases shader_
if (depth_ok_) UnloadMaterial(depth_material_);
if (albedo_.id != 0) UnloadTexture(albedo_); if (albedo_.id != 0) UnloadTexture(albedo_);
if (normal_.id != 0) UnloadTexture(normal_); if (normal_.id != 0) UnloadTexture(normal_);
if (roughness_.id != 0) UnloadTexture(roughness_); if (roughness_.id != 0) UnloadTexture(roughness_);
mesh_ok_ = false; mesh_ok_ = false;
shader_ok_ = false; shader_ok_ = false;
depth_ok_ = false;
ready_ = false; ready_ = false;
} }
void ConcreteMaterial::draw(float corruption, Vector3 camera_pos) { void ConcreteMaterial::draw(float corruption, Vector3 camera_pos) {
if (depth_pass_) { draw_shadow(); return; }
if (!ready_) return; if (!ready_) return;
SetShaderValue(shader_, loc_corruption_, &corruption, SHADER_UNIFORM_FLOAT); SetShaderValue(shader_, loc_corruption_, &corruption, SHADER_UNIFORM_FLOAT);
if (loc_camera_ >= 0) { if (loc_camera_ >= 0) {
@ -271,3 +291,20 @@ void ConcreteMaterial::draw(float corruption, Vector3 camera_pos) {
PROF_DRAW_CALL(); PROF_DRAW_CALL();
DrawMesh(mesh_, material_, MatrixIdentity()); DrawMesh(mesh_, material_, MatrixIdentity());
} }
void ConcreteMaterial::set_shadow(const ShadowMap& shadow, bool enabled) {
if (!shader_ok_) return;
const float darkness = enabled && shadow.ready() ? ShadowMap::kDarkness : 0.0f;
if (loc_shadow_darkness_ >= 0)
SetShaderValue(shader_, loc_shadow_darkness_, &darkness, SHADER_UNIFORM_FLOAT);
if (!enabled || !shadow.ready()) return;
if (loc_light_vp_ >= 0)
SetShaderValueMatrix(shader_, loc_light_vp_, shadow.light_vp());
shadow.bind();
}
void ConcreteMaterial::draw_shadow() {
if (!depth_ok_ || !mesh_ok_) return;
PROF_DRAW_CALL();
DrawMesh(mesh_, depth_material_, MatrixIdentity());
}

View file

@ -7,6 +7,7 @@
// One tileable concrete material shared by floor, curbs and pillars. // One tileable concrete material shared by floor, curbs and pillars.
// All concrete geometry is merged into a single static mesh and drawn once. // All concrete geometry is merged into a single static mesh and drawn once.
class Floor; class Floor;
class ShadowMap;
class ConcreteMaterial { class ConcreteMaterial {
public: public:
@ -15,6 +16,9 @@ public:
bool ready() const { return ready_; } bool ready() const { return ready_; }
void draw(float corruption, Vector3 camera_pos); void draw(float corruption, Vector3 camera_pos);
void set_shadow(const ShadowMap& shadow, bool enabled);
void draw_shadow();
void set_depth_pass(bool on) { depth_pass_ = on; }
// Re-applies the current graphics-settings filter to all three maps. // Re-applies the current graphics-settings filter to all three maps.
// The future graphics menu calls this after changing the option. // The future graphics menu calls this after changing the option.
@ -33,6 +37,8 @@ private:
Shader shader_{}; Shader shader_{};
Material material_{}; Material material_{};
Shader depth_shader_{};
Material depth_material_{};
Texture2D albedo_{}; Texture2D albedo_{};
Texture2D normal_{}; Texture2D normal_{};
Texture2D roughness_{}; Texture2D roughness_{};
@ -45,7 +51,12 @@ private:
int loc_room_rect_ = -1; int loc_room_rect_ = -1;
int loc_room_tint_ = -1; int loc_room_tint_ = -1;
int loc_room_count_ = -1; int loc_room_count_ = -1;
int loc_light_vp_ = -1;
int loc_shadow_map_ = -1;
int loc_shadow_darkness_ = -1;
bool shader_ok_ = false; bool shader_ok_ = false;
bool depth_ok_ = false;
bool depth_pass_ = false;
bool mesh_ok_ = false; bool mesh_ok_ = false;
bool ready_ = false; bool ready_ = false;
}; };

View file

@ -11,11 +11,17 @@ enum class TextureFiltering {
Anisotropic8X, Anisotropic8X,
}; };
enum class ShadowQuality {
Off,
Hard,
};
struct GraphicsSettings { struct GraphicsSettings {
// 8x aniso looks crisper on the floor at grazing angles but is expensive // 8x aniso looks crisper on the floor at grazing angles but is expensive
// on the integrated GPU, so the safe default stays trilinear. // on the integrated GPU, so the safe default stays trilinear.
TextureFiltering concrete_filter = TextureFiltering::Trilinear; TextureFiltering concrete_filter = TextureFiltering::Trilinear;
// Future phases: bloom quality, render scale, Hiss detail, shadow quality. ShadowQuality shadows = ShadowQuality::Hard;
// Future phases: bloom quality, render scale, Hiss detail.
}; };
GraphicsSettings& graphics_settings(); GraphicsSettings& graphics_settings();

View file

@ -1,6 +1,7 @@
#include "render/models.hpp" #include "render/models.hpp"
#include "render/profiler.hpp" #include "render/profiler.hpp"
#include "render/shadow_map.hpp"
#include "raymath.h" #include "raymath.h"
#include "rlgl.h" #include "rlgl.h"
@ -13,6 +14,7 @@
#include <cmath> #include <cmath>
#include <cstdio> #include <cstdio>
#include <cstring> #include <cstring>
#include <iterator>
#include <string> #include <string>
namespace { namespace {
@ -87,6 +89,13 @@ void ModelBank::init() {
loc_rig_scale_ = GetShaderLocation(shader_, "uRigScale"); loc_rig_scale_ = GetShaderLocation(shader_, "uRigScale");
loc_rig_mode_ = GetShaderLocation(shader_, "uRigMode"); loc_rig_mode_ = GetShaderLocation(shader_, "uRigMode");
loc_hiss_ = GetShaderLocation(shader_, "uHiss"); loc_hiss_ = GetShaderLocation(shader_, "uHiss");
loc_light_vp_ = GetShaderLocation(shader_, "uLightVP");
loc_shadow_map_ = GetShaderLocation(shader_, "uShadowMap");
loc_shadow_darkness_ = GetShaderLocation(shader_, "uShadowDarkness");
if (loc_shadow_map_ >= 0) {
const int slot = ShadowMap::kTextureSlot;
SetShaderValue(shader_, loc_shadow_map_, &slot, SHADER_UNIFORM_INT);
}
const std::string ramp = resolve("assets/textures/actor/actor_ramp.png"); const std::string ramp = resolve("assets/textures/actor/actor_ramp.png");
if (!ramp.empty() && loc_ramp_ >= 0) { if (!ramp.empty() && loc_ramp_ >= 0) {
ramp_ = LoadTexture(ramp.c_str()); ramp_ = LoadTexture(ramp.c_str());
@ -107,6 +116,23 @@ void ModelBank::init() {
TraceLog(LOG_WARNING, "ACTOR: shader files missing, using flat shading"); TraceLog(LOG_WARNING, "ACTOR: shader files missing, using flat shading");
} }
if (!vs.empty()) {
const std::string depth_fs = resolve("assets/shaders/shadow_depth.fs");
if (!depth_fs.empty()) {
depth_shader_ = LoadShader(vs.c_str(), depth_fs.c_str());
depth_ok_ = depth_shader_.id != 0;
if (depth_ok_) {
loc_depth_time_ = GetShaderLocation(depth_shader_, "uTime");
loc_depth_walk_ = GetShaderLocation(depth_shader_, "uWalk");
loc_depth_stagger_ = GetShaderLocation(depth_shader_, "uStagger");
loc_depth_phase_ = GetShaderLocation(depth_shader_, "uPhase");
loc_depth_rig_ = GetShaderLocation(depth_shader_, "uRig");
loc_depth_rig_scale_ = GetShaderLocation(depth_shader_, "uRigScale");
loc_depth_rig_mode_ = GetShaderLocation(depth_shader_, "uRigMode");
}
}
}
for (int i = 0; i < static_cast<int>(ActorModel::Count); ++i) { for (int i = 0; i < static_cast<int>(ActorModel::Count); ++i) {
const ActorModel id = static_cast<ActorModel>(i); const ActorModel id = static_cast<ActorModel>(i);
const std::string path = resolve(file_name(id)); const std::string path = resolve(file_name(id));
@ -162,7 +188,9 @@ void ModelBank::shutdown() {
if (ramp_.id != 0) UnloadTexture(ramp_); if (ramp_.id != 0) UnloadTexture(ramp_);
ramp_.id = 0; ramp_.id = 0;
if (shader_ok_) UnloadShader(shader_); if (shader_ok_) UnloadShader(shader_);
if (depth_ok_) UnloadShader(depth_shader_);
shader_ok_ = false; shader_ok_ = false;
depth_ok_ = false;
ready_ = false; ready_ = false;
} }
@ -180,6 +208,65 @@ void ModelBank::begin_frame(float time, float corruption, Vector3 camera_pos) {
} }
} }
void ModelBank::set_shadow(const ShadowMap& shadow, bool enabled) {
if (!shader_ok_) return;
const float darkness = enabled && shadow.ready() ? ShadowMap::kDarkness : 0.0f;
if (loc_shadow_darkness_ >= 0)
SetShaderValue(shader_, loc_shadow_darkness_, &darkness, SHADER_UNIFORM_FLOAT);
if (!enabled || !shadow.ready()) return;
if (loc_light_vp_ >= 0)
SetShaderValueMatrix(shader_, loc_light_vp_, shadow.light_vp());
shadow.bind();
}
void ModelBank::begin_shadow_frame(float time) {
if (!depth_ok_) return;
if (loc_depth_time_ >= 0)
SetShaderValue(depth_shader_, loc_depth_time_, &time, SHADER_UNIFORM_FLOAT);
}
void ModelBank::draw_shadow(ActorModel id, Vector3 pos, float yaw, float scale,
float walk, float stagger, float phase,
Vector3 stretch) {
if (!depth_ok_) return;
const int index = static_cast<int>(id);
if (index < 0 || index >= static_cast<int>(ActorModel::Count)) return;
if (!entries_[index].loaded) return;
const Vector3 draw_scale = stretch.x > 0.0f
? stretch : Vector3{scale, scale, scale};
const Rig rig = rig_for(id);
const float r[4] = {rig.hip_y, rig.shoulder_y, rig.leg_x, rig.arm_x};
if (loc_depth_rig_ >= 0)
SetShaderValue(depth_shader_, loc_depth_rig_, r, SHADER_UNIFORM_VEC4);
if (loc_depth_rig_scale_ >= 0)
SetShaderValue(depth_shader_, loc_depth_rig_scale_, &rig.scale,
SHADER_UNIFORM_FLOAT);
if (loc_depth_rig_mode_ >= 0)
SetShaderValue(depth_shader_, loc_depth_rig_mode_, &rig.mode,
SHADER_UNIFORM_FLOAT);
if (loc_depth_walk_ >= 0)
SetShaderValue(depth_shader_, loc_depth_walk_, &walk, SHADER_UNIFORM_FLOAT);
if (loc_depth_stagger_ >= 0)
SetShaderValue(depth_shader_, loc_depth_stagger_, &stagger,
SHADER_UNIFORM_FLOAT);
if (loc_depth_phase_ >= 0)
SetShaderValue(depth_shader_, loc_depth_phase_, &phase,
SHADER_UNIFORM_FLOAT);
Model& model = entries_[index].model;
Shader saved[16];
if (model.materialCount > static_cast<int>(std::size(saved))) return;
for (int m = 0; m < model.materialCount; ++m) {
saved[m] = model.materials[m].shader;
model.materials[m].shader = depth_shader_;
}
DrawModelEx(model, pos, Vector3{0.0f, 1.0f, 0.0f}, yaw * RAD2DEG,
draw_scale, WHITE);
for (int m = 0; m < model.materialCount; ++m) {
model.materials[m].shader = saved[m];
}
}
void ModelBank::draw(ActorModel id, Vector3 pos, float yaw, float scale, void ModelBank::draw(ActorModel id, Vector3 pos, float yaw, float scale,
Color tint, float flash, bool outline, float walk, Color tint, float flash, bool outline, float walk,
float stagger, float phase, float hiss, Vector3 stretch, float stagger, float phase, float hiss, Vector3 stretch,
@ -189,6 +276,10 @@ void ModelBank::draw(ActorModel id, Vector3 pos, float yaw, float scale,
const float yaw_degrees = yaw * RAD2DEG; const float yaw_degrees = yaw * RAD2DEG;
const int index = static_cast<int>(id); const int index = static_cast<int>(id);
if (index < 0 || index >= static_cast<int>(ActorModel::Count)) return; if (index < 0 || index >= static_cast<int>(ActorModel::Count)) return;
if (depth_pass_) {
draw_shadow(id, pos, yaw, scale, walk, stagger, phase, stretch);
return;
}
if (!entries_[index].loaded) { if (!entries_[index].loaded) {
draw_fallback(id, pos, yaw, scale, tint); draw_fallback(id, pos, yaw, scale, tint);
return; return;

View file

@ -4,6 +4,8 @@
#include "raylib.h" #include "raylib.h"
class ShadowMap;
// Low-poly GLB actors authored in Blender (tools/blender/build_enemies.py). // Low-poly GLB actors authored in Blender (tools/blender/build_enemies.py).
// All models are metres, origin at the feet, facing +Z (the game camera). // All models are metres, origin at the feet, facing +Z (the game camera).
// The set-dressing models share the same one-mesh / painted-vertex pipeline. // The set-dressing models share the same one-mesh / painted-vertex pipeline.
@ -28,6 +30,13 @@ public:
// Frame-wide shader uniforms (time / corruption / camera). // Frame-wide shader uniforms (time / corruption / camera).
void begin_frame(float time, float corruption, Vector3 camera_pos); void begin_frame(float time, float corruption, Vector3 camera_pos);
void set_shadow(const ShadowMap& shadow, bool enabled);
void begin_shadow_frame(float time);
void set_depth_pass(bool on) { depth_pass_ = on; }
void draw_shadow(ActorModel id, Vector3 pos, float yaw, float scale,
float walk = 0.0f, float stagger = 0.0f,
float phase = 0.0f, Vector3 stretch = {0.0f, 0.0f, 0.0f});
// Draws one actor. `flash` is a 0..1 hit flash; `yaw` rotates around Y. // Draws one actor. `flash` is a 0..1 hit flash; `yaw` rotates around Y.
// `outline` adds a back-face ink silhouette (guard / bosses, not the horde). // `outline` adds a back-face ink silhouette (guard / bosses, not the horde).
// `stretch` overrides the uniform scale per axis when non-zero (thermo // `stretch` overrides the uniform scale per axis when non-zero (thermo
@ -67,6 +76,7 @@ private:
Entry entries_[static_cast<int>(ActorModel::Count)]; Entry entries_[static_cast<int>(ActorModel::Count)];
Shader shader_{}; Shader shader_{};
Shader depth_shader_{};
Texture2D ramp_{}; Texture2D ramp_{};
int loc_time_ = -1; int loc_time_ = -1;
int loc_alpha_ = -1; int loc_alpha_ = -1;
@ -83,6 +93,18 @@ private:
int loc_rig_scale_ = -1; int loc_rig_scale_ = -1;
int loc_rig_mode_ = -1; int loc_rig_mode_ = -1;
int loc_hiss_ = -1; int loc_hiss_ = -1;
int loc_light_vp_ = -1;
int loc_shadow_map_ = -1;
int loc_shadow_darkness_ = -1;
int loc_depth_time_ = -1;
int loc_depth_walk_ = -1;
int loc_depth_stagger_ = -1;
int loc_depth_phase_ = -1;
int loc_depth_rig_ = -1;
int loc_depth_rig_scale_ = -1;
int loc_depth_rig_mode_ = -1;
bool shader_ok_ = false; bool shader_ok_ = false;
bool depth_ok_ = false;
bool depth_pass_ = false;
bool ready_ = false; bool ready_ = false;
}; };

View file

@ -56,7 +56,25 @@ float actor_flash(float timer, float scale) {
class ViewCull { class ViewCull {
public: public:
void disable() { all_ = true; }
void init_ortho(const Camera3D& camera, float extent, float max_depth) {
all_ = false;
ortho_ = true;
cam_ = camera.position;
max_depth_ = max_depth;
forward_ = Vector3Normalize(
Vector3Subtract(camera.target, camera.position));
right_ = Vector3CrossProduct(forward_, Vector3{0.0f, 1.0f, 0.0f});
if (Vector3LengthSqr(right_) < 1e-6f) right_ = Vector3{1.0f, 0.0f, 0.0f};
right_ = Vector3Normalize(right_);
up_ = Vector3Normalize(Vector3CrossProduct(right_, forward_));
extent_ = extent * 0.5f;
}
void init(const Camera3D& camera, float aspect, float max_depth = 180.0f) { void init(const Camera3D& camera, float aspect, float max_depth = 180.0f) {
all_ = false;
ortho_ = false;
cam_ = camera.position; cam_ = camera.position;
max_depth_ = max_depth; max_depth_ = max_depth;
forward_ = Vector3Normalize( forward_ = Vector3Normalize(
@ -71,14 +89,21 @@ public:
} }
bool visible(float x, float y, float z, float radius) const { bool visible(float x, float y, float z, float radius) const {
if (all_) return true;
const Vector3 d{x - cam_.x, y - cam_.y, z - cam_.z}; const Vector3 d{x - cam_.x, y - cam_.y, z - cam_.z};
const float depth = Vector3DotProduct(d, forward_); const float depth = Vector3DotProduct(d, forward_);
if (depth < -radius || depth > max_depth_ + radius) return false; if (depth < -radius || depth > max_depth_ + radius) return false;
if (ortho_) {
return std::abs(Vector3DotProduct(d, right_)) <= extent_ + radius
&& std::abs(Vector3DotProduct(d, up_)) <= extent_ + radius;
}
return std::abs(Vector3DotProduct(d, right_)) <= depth * tan_x_ + radius return std::abs(Vector3DotProduct(d, right_)) <= depth * tan_x_ + radius
&& std::abs(Vector3DotProduct(d, up_)) <= depth * tan_y_ + radius; && std::abs(Vector3DotProduct(d, up_)) <= depth * tan_y_ + radius;
} }
private: private:
bool all_ = false;
bool ortho_ = false;
Vector3 cam_{}; Vector3 cam_{};
float max_depth_ = 180.0f; float max_depth_ = 180.0f;
Vector3 forward_{}; Vector3 forward_{};
@ -86,6 +111,7 @@ private:
Vector3 up_{}; Vector3 up_{};
float tan_x_ = 1.0f; float tan_x_ = 1.0f;
float tan_y_ = 1.0f; float tan_y_ = 1.0f;
float extent_ = 1.0f;
}; };
namespace { namespace {
@ -332,6 +358,7 @@ void Presenter::init(float arena_half, const Floor& floor) {
spr_glow_ = load_glow_sprite(); spr_glow_ = load_glow_sprite();
models_.init(); models_.init();
concrete_.init(arena_half, &floor); concrete_.init(arena_half, &floor);
if (!shadow_map_.init(2048)) shadow_map_.init(1024);
// Phase 1 batching: bake the repeated outer service-band plant blocks, // Phase 1 batching: bake the repeated outer service-band plant blocks,
// tops and spill cylinders into one mesh (one draw call). // tops and spill cylinders into one mesh (one draw call).
@ -511,6 +538,7 @@ void Presenter::shutdown() {
concrete_debris_.clear(); concrete_debris_.clear();
scorch_.clear(); scorch_.clear();
aura_.shutdown(); aura_.shutdown();
shadow_map_.shutdown();
concrete_.shutdown(); concrete_.shutdown();
models_.shutdown(); models_.shutdown();
if (static_env_ready_) { if (static_env_ready_) {
@ -601,7 +629,7 @@ void Presenter::draw_office_suite(const Game& game, const ViewCull& cull) {
} }
void Presenter::draw_floor_environment(const Game& game, const ViewCull& cull) { void Presenter::draw_floor_environment(const Game& game, const ViewCull& cull) {
if (static_env_ready_) { if (!shadow_pass_ && static_env_ready_) {
// Winding was baked outward in StaticMeshBuilder, so back faces can be // Winding was baked outward in StaticMeshBuilder, so back faces can be
// culled like every other mesh instead of shading both sides. // culled like every other mesh instead of shading both sides.
rlEnableBackfaceCulling(); rlEnableBackfaceCulling();
@ -903,7 +931,7 @@ void Presenter::draw_environment(const Game& game, const ViewCull& cull) {
// Outer service band: the textured floor continues past the play curb, so // Outer service band: the textured floor continues past the play curb, so
// dress it with dark plant blocks and dim spill. A player hugging a wall // dress it with dark plant blocks and dim spill. A player hugging a wall
// then sees more facility instead of an empty unlit void. // then sees more facility instead of an empty unlit void.
if (static_env_ready_) { if (!shadow_pass_ && static_env_ready_) {
// Winding was baked outward in StaticMeshBuilder, so back faces can be // Winding was baked outward in StaticMeshBuilder, so back faces can be
// culled like every other mesh instead of shading both sides. // culled like every other mesh instead of shading both sides.
rlEnableBackfaceCulling(); rlEnableBackfaceCulling();
@ -1213,6 +1241,46 @@ void Presenter::draw_blackout(Game& game) {
glow_batch.draw(); glow_batch.draw();
} }
void Presenter::draw_shadow_map(const Game& game, bool enabled) {
shadows_active_ = enabled && shadow_map_.ready() && !game.blackout.active();
if (!shadows_active_) return;
const Vec2 focus = game.player.pos;
shadow_map_.update(focus);
shadow_map_.begin();
models_.begin_shadow_frame(anim_time_);
models_.set_depth_pass(true);
concrete_.set_depth_pass(true);
shadow_pass_ = true;
ViewCull cull;
cull.init_ortho(shadow_map_.camera(), ShadowMap::kExtent, 200.0f);
draw_environment(game, cull);
dressing_.draw(models_, anim_time_, focus);
models_.draw_shadow(ActorModel::Guard, {focus.x, 0.0f, focus.y},
player_yaw_, 1.0f, player_walk_, 0.0f, anim_time_);
for (const Enemy& e : game.enemy_system.enemies) {
const float dx = e.pos.x - focus.x;
const float dz = e.pos.y - focus.y;
if (dx * dx + dz * dz > 45.0f * 45.0f) continue;
const Vec2 dir = focus - e.pos;
const bool mold = e.type == EnemyType::MoldSpore;
float yaw = std::atan2(dir.x, dir.y);
if (!mold) yaw += std::sin(e.bob_phase * 3.0f) * 0.11f;
const float bob = std::sin(e.bob_phase) * (mold ? 0.02f : 0.08f);
const ActorModel model = mold ? ActorModel::MoldSpore
: (e.type == EnemyType::HissBrute ? ActorModel::HissBrute
: (e.type == EnemyType::HissGhost ? ActorModel::HissGhost
: ActorModel::HissStaff));
models_.draw_shadow(model, {e.pos.x, bob, e.pos.y}, yaw, 1.0f,
std::min(1.0f, e.speed / 4.5f),
actor_flash(e.hit_flash, 6.0f), e.bob_phase);
}
shadow_pass_ = false;
concrete_.set_depth_pass(false);
models_.set_depth_pass(false);
shadow_map_.end();
}
void Presenter::draw_scene(Game& game) { void Presenter::draw_scene(Game& game) {
for (int i = 0; i < game.events.count; ++i) { for (int i = 0; i < game.events.count; ++i) {
const GameEvent& e = game.events.items[i]; const GameEvent& e = game.events.items[i];
@ -1408,6 +1476,8 @@ void Presenter::draw_scene(Game& game) {
models_.begin_frame(anim_time_, game.corruption.value(), camera_.position); models_.begin_frame(anim_time_, game.corruption.value(), camera_.position);
aura_.begin_frame(anim_time_, game.corruption.value()); aura_.begin_frame(anim_time_, game.corruption.value());
concrete_.set_shadow(shadow_map_, shadows_active_);
models_.set_shadow(shadow_map_, shadows_active_);
BeginMode3D(camera_); BeginMode3D(camera_);

View file

@ -11,6 +11,7 @@
#include "render/debris.hpp" #include "render/debris.hpp"
#include "render/dressing.hpp" #include "render/dressing.hpp"
#include "render/models.hpp" #include "render/models.hpp"
#include "render/shadow_map.hpp"
// The hybrid look: brutalist 3D diorama + low-poly Blender actors. // The hybrid look: brutalist 3D diorama + low-poly Blender actors.
// This is the only place that knows how the sim is drawn (ART_DIRECTION.md). // This is the only place that knows how the sim is drawn (ART_DIRECTION.md).
@ -50,6 +51,8 @@ public:
// (main.cpp renders into a texture first so post FX can run over the frame). // (main.cpp renders into a texture first so post FX can run over the frame).
void draw_scene(Game& game); void draw_scene(Game& game);
void draw_shadow_map(const Game& game, bool enabled);
void set_hiss_test(bool on) { hiss_test_ = on; } void set_hiss_test(bool on) { hiss_test_ = on; }
void set_floor_overview(bool on) { floor_overview_ = on; } void set_floor_overview(bool on) { floor_overview_ = on; }
@ -86,6 +89,8 @@ private:
Texture2D spr_glow_{}; // projectile glow sprite Texture2D spr_glow_{}; // projectile glow sprite
ModelBank models_; ModelBank models_;
ConcreteMaterial concrete_; ConcreteMaterial concrete_;
ShadowMap shadow_map_;
bool shadows_active_ = false;
CorruptionAura aura_; CorruptionAura aura_;
Dressing dressing_; Dressing dressing_;
PaperDebris debris_; PaperDebris debris_;
@ -110,6 +115,7 @@ private:
bool hiss_test_ = false; bool hiss_test_ = false;
bool floor_mode_ = false; bool floor_mode_ = false;
bool floor_overview_ = false; bool floor_overview_ = false;
bool shadow_pass_ = false;
bool tier_wave_pending_ = false; bool tier_wave_pending_ = false;
Vec2 last_player_pos_{}; Vec2 last_player_pos_{};
std::vector<DamageNumber> damage_numbers_; std::vector<DamageNumber> damage_numbers_;

106
src/render/shadow_map.cpp Normal file
View file

@ -0,0 +1,106 @@
#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);
}

35
src/render/shadow_map.hpp Normal file
View file

@ -0,0 +1,35 @@
#pragma once
#include "raylib.h"
#include "core/math.hpp"
class ShadowMap {
public:
static constexpr int kTextureSlot = 12;
static constexpr float kDarkness = 0.55f;
static constexpr float kExtent = 44.0f;
bool init(int size);
void shutdown();
bool ready() const { return ready_; }
void update(Vec2 focus);
void begin();
void end();
void bind() const;
RenderTexture2D& target() { return target_; }
Camera3D& camera() { return camera_; }
const Matrix& light_vp() const { return vp_; }
unsigned int depth_id() const { return target_.depth.id; }
private:
RenderTexture2D target_{};
Camera3D camera_{};
Matrix view_{};
Matrix proj_{};
Matrix vp_{};
int size_ = 0;
bool ready_ = false;
};