64-bit hashes (#126)

- ContactEvent sample
- Improved shadows
- #120 
- Triangle collision fixes
This commit is contained in:
Erin Catto 2026-08-11 18:08:34 -07:00 • committed by GitHub
commit f42be210a2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
49 changed files with 19835 additions and 17544 deletions

View file

@ -6,6 +6,7 @@
#include "gfx/qsort.h"
#include <assert.h>
#include <inttypes.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
@ -301,7 +302,7 @@ static MeshHandle BuildHull( const b3HullData* hull )
const b3Plane* planes = b3GetHullPlanes( hull );
if ( !points || !edges || !faces || !planes )
{
fprintf( stderr, "error: hull missing arrays (hash=0x%08x)\n", hull->hash );
fprintf( stderr, "error: hull missing arrays (hash=0x%016" PRIx64 ")\n", hull->hash );
return InvalidMeshHandle();
}
@ -330,7 +331,7 @@ static MeshHandle BuildHull( const b3HullData* hull )
e = edges[e].next;
if ( loopLen > 256 )
{
fprintf( stderr, "error: hull face loop runaway (hash=0x%08x)\n", hull->hash );
fprintf( stderr, "error: hull face loop runaway (hash=0x%016" PRIx64 ")\n", hull->hash );
BufferFree( &buf );
return InvalidMeshHandle();
}
@ -426,7 +427,7 @@ static MeshHandle BuildMeshData( const b3MeshData* meshData )
const uint8_t* flags = b3GetMeshFlags( meshData );
if ( !verts || !tris || meshData->triangleCount <= 0 )
{
fprintf( stderr, "error: mesh missing arrays or empty (hash=0x%08x)\n", meshData->hash );
fprintf( stderr, "error: mesh missing arrays or empty (hash=0x%016" PRIx64 ")\n", meshData->hash );
return InvalidMeshHandle();
}
@ -559,7 +560,7 @@ static MeshHandle BuildHeightField( const b3HeightFieldData* hf )
{
if ( hf->columnCount < 2 || hf->rowCount < 2 )
{
fprintf( stderr, "error: heightfield degenerate (hash=0x%08x)\n", hf->hash );
fprintf( stderr, "error: heightfield degenerate (hash=0x%016" PRIx64 ")\n", hf->hash );
return InvalidMeshHandle();
}
@ -791,7 +792,7 @@ static MeshHandle BuildHeightField( const b3HeightFieldData* hf )
MeshHandle FindOrAddHull( const b3HullData* hull )
{
if ( !hull || hull->hash == 0u )
if ( !hull || hull->hash == 0 )
{
return InvalidMeshHandle();
}
@ -808,7 +809,7 @@ MeshHandle FindOrAddHull( const b3HullData* hull )
MeshHandle FindOrAddMesh( const b3MeshData* meshData )
{
if ( !meshData || meshData->hash == 0u )
if ( !meshData || meshData->hash == 0 )
{
return InvalidMeshHandle();
}
@ -825,7 +826,7 @@ MeshHandle FindOrAddMesh( const b3MeshData* meshData )
MeshHandle FindOrAddHeightField( const b3HeightFieldData* heightField )
{
if ( !heightField || heightField->hash == 0u )
if ( !heightField || heightField->hash == 0 )
{
return InvalidMeshHandle();
}

View file

@ -16,7 +16,7 @@
typedef struct Entry
{
uint32_t hash;
uint64_t hash;
int refCount; // 0 means free
sg_buffer vbo;
sg_buffer ibo;
@ -164,7 +164,7 @@ void DestroyMeshRegistry( void )
sg_destroy_buffer( s_geom.instBuf );
}
MeshHandle FindMesh( uint32_t hash )
MeshHandle FindMesh( uint64_t hash )
{
if ( hash == 0u )
{
@ -200,10 +200,10 @@ static int FindFreeSlot( void )
return s_geom.entryCount++;
}
MeshHandle RegisterMesh( uint32_t hash, const MeshVertex* vertices, int vertexCount, const uint32_t* indices,
MeshHandle RegisterMesh( uint64_t hash, const MeshVertex* vertices, int vertexCount, const uint32_t* indices,
int indexCount, const char* debugLabel )
{
assert( hash != 0u );
assert( hash != 0 );
assert( vertexCount > 0 );
assert( indexCount > 0 );
@ -428,7 +428,7 @@ void ReleaseMeshReference( MeshHandle h )
sg_destroy_view( e->edgeStorageView );
sg_destroy_buffer( e->edgeBuf );
}
e->hash = 0u;
e->hash = 0;
e->indexCount = 0;
e->edgeBuf.id = SG_INVALID_ID;
e->edgeStorageView.id = SG_INVALID_ID;

View file

@ -52,12 +52,12 @@ extern "C"
typedef struct MeshHandle
{
int index; // -1 means invalid
uint32_t hash; // for cheap validation against index reuse
uint64_t hash; // for cheap validation against index reuse
} MeshHandle;
static inline MeshHandle InvalidMeshHandle( void )
{
MeshHandle h = { -1, 0u };
MeshHandle h = { -1, 0ull };
return h;
}
@ -142,9 +142,9 @@ typedef struct MeshXpInstance
void CreateMeshRegistry( void );
void DestroyMeshRegistry( void );
MeshHandle FindMesh( uint32_t hash );
MeshHandle FindMesh( uint64_t hash );
MeshHandle RegisterMesh( uint32_t hash, const MeshVertex* vertices, int vertexCount, const uint32_t* indices,
MeshHandle RegisterMesh( uint64_t hash, const MeshVertex* vertices, int vertexCount, const uint32_t* indices,
int indexCount, const char* debugLabel );
// Optional: register an edge list for a geometry already registered via

View file

@ -88,24 +88,12 @@ static struct
sg_pipeline shadowGeomPipeline;
sg_pipeline shadowGeomPipelineMirror;
// Shadow caster pipeline (sphere). The lit sphere pipeline is an
// analytic impostor, too expensive for the shadow pass, so the
// caster rasterizes a low-poly icosphere proxy generated at InitRenderer.
// The icosphere vbo/ibo live here, the sphere instance buffer is
// shared with the lit pipeline.
sg_buffer icosphereVbuf;
sg_buffer icosphereIbuf;
int icosphereIndexCount;
// Shadow caster pipelines (sphere, capsule). Both rasterize the same
// bounding proxy the lit impostor uses and ray-cast the exact surface,
// so they borrow the cube's vbuf/ibuf and share the lit pipeline's
// instance buffers.
sg_shader shadowSphereShader;
sg_pipeline shadowSpherePipeline;
// Shadow caster pipeline (capsule). Cylinder-plus-caps proxy mesh
// built once at InitRenderer, the capsule instance buffer is shared with
// the lit pipeline. Per-vertex format is two vec3s: in_axis (scaled
// by halfLength) + in_radial (scaled by radius).
sg_buffer capsuleProxyVbuf;
sg_buffer capsuleProxyIbuf;
int capsuleProxyIndexCount;
sg_shader shadowCapsuleShader;
sg_pipeline shadowCapsulePipeline;
@ -254,307 +242,6 @@ static const uint16_t CUBE_INDICES[36] = {
4, 5, 7, 4, 7, 6, // +Z
};
// Ico-sphere shadow proxy
// N-level subdivided ico-sphere built from a 12-vert icosahedron: each
// subdivision step splits every face into 4 by inserting edge midpoints,
// then renormalizes every new vertex to the unit sphere. After L levels:
// verts = 10 * 4^L + 2, tris = 20 * 4^L. Built once at InitRenderer and uploaded
// to dedicated vbuf/ibuf for the shadow_caster_sphere pipeline.
//
// We use L=2 (162 verts, 320 tris), subdiv-1 gave visibly polygonal
// shadow silhouettes when the sun grazed a sphere, subdiv-2 reads as
// round at any zoom we're likely to use. Subdiv-3 (1280 tris) is overkill.
//
// The icosahedron's golden-ratio coordinates produce a remarkably even
// vertex distribution, better silhouette quality than a UV sphere
// comparable triangle count.
#define ICO_SPHERE_SUBDIV_LEVEL 2
#define ICO_SPHERE_VERTICES 162 // 10 * 4^L + 2 for L=2
#define ICO_SPHERE_INDICES ( 320 * 3 ) // 20 * 4^L for L=2
static void BuildIcosphere( float ( *outVerts )[3], uint32_t* outIndices )
{
const float phi = ( 1.0f + sqrtf( 5.0f ) ) * 0.5f;
const float invLen = 1.0f / sqrtf( 1.0f + phi * phi );
// 12 icosahedron vertices, normalized to the unit sphere.
const float baseVerts[12][3] = {
{ -1.0f, phi, 0.0f }, { 1.0f, phi, 0.0f }, { -1.0f, -phi, 0.0f }, { 1.0f, -phi, 0.0f },
{ 0.0f, -1.0f, phi }, { 0.0f, 1.0f, phi }, { 0.0f, -1.0f, -phi }, { 0.0f, 1.0f, -phi },
{ phi, 0.0f, -1.0f }, { phi, 0.0f, 1.0f }, { -phi, 0.0f, -1.0f }, { -phi, 0.0f, 1.0f },
};
for ( int i = 0; i < 12; ++i )
{
outVerts[i][0] = baseVerts[i][0] * invLen;
outVerts[i][1] = baseVerts[i][1] * invLen;
outVerts[i][2] = baseVerts[i][2] * invLen;
}
// 20 base faces, CCW from outside.
static const uint32_t baseTris[20 * 3] = {
0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1,
};
// Ping-pong tri buffers. Each level reads `cur` and writes `nxt`, then
// swaps. Static so the ~7.5 KB doesn't pressure the call-site stack.
static uint32_t triA[ICO_SPHERE_INDICES];
static uint32_t triB[ICO_SPHERE_INDICES];
uint32_t* cur = triA;
uint32_t* nxt = triB;
int triCount = 20;
for ( int i = 0; i < 20 * 3; ++i )
cur[i] = baseTris[i];
int vertCount = 12;
// Edge midpoint cache, sized for the final vertex count. Each edge
// the *current* tri set pairs exactly two faces, so a midpoint computed
// for one face is reused by exactly one other. Cleared per level so
// midpoint indices from earlier levels don't leak in. ~104 KB static.
static int midCache[ICO_SPHERE_VERTICES][ICO_SPHERE_VERTICES];
for ( int L = 0; L < ICO_SPHERE_SUBDIV_LEVEL; ++L )
{
for ( int i = 0; i < ICO_SPHERE_VERTICES; ++i )
{
for ( int j = 0; j < ICO_SPHERE_VERTICES; ++j )
{
midCache[i][j] = -1;
}
}
int nxtCount = 0;
for ( int t = 0; t < triCount; ++t )
{
const uint32_t v[3] = { cur[t * 3 + 0], cur[t * 3 + 1], cur[t * 3 + 2] };
uint32_t mid[3];
for ( int e = 0; e < 3; ++e )
{
uint32_t a = v[e];
uint32_t b = v[( e + 1 ) % 3];
if ( a > b )
{
uint32_t tmp = a;
a = b;
b = tmp;
}
if ( midCache[a][b] < 0 )
{
const int index = vertCount++;
float mx = 0.5f * ( outVerts[a][0] + outVerts[b][0] );
float my = 0.5f * ( outVerts[a][1] + outVerts[b][1] );
float mz = 0.5f * ( outVerts[a][2] + outVerts[b][2] );
const float len = sqrtf( mx * mx + my * my + mz * mz );
if ( len > 0.0f )
{
mx /= len;
my /= len;
mz /= len;
}
outVerts[index][0] = mx;
outVerts[index][1] = my;
outVerts[index][2] = mz;
midCache[a][b] = index;
}
mid[e] = (uint32_t)midCache[a][b];
}
// Subdivide one tri (v0,v1,v2) into four:
// (v0, m01, m20), (v1, m12, m01), (v2, m20, m12), (m01, m12, m20).
// mid[0] = m01, mid[1] = m12, mid[2] = m20.
nxt[nxtCount++] = v[0];
nxt[nxtCount++] = mid[0];
nxt[nxtCount++] = mid[2];
nxt[nxtCount++] = v[1];
nxt[nxtCount++] = mid[1];
nxt[nxtCount++] = mid[0];
nxt[nxtCount++] = v[2];
nxt[nxtCount++] = mid[2];
nxt[nxtCount++] = mid[1];
nxt[nxtCount++] = mid[0];
nxt[nxtCount++] = mid[1];
nxt[nxtCount++] = mid[2];
}
triCount = nxtCount / 3;
uint32_t* tmp = cur;
cur = nxt;
nxt = tmp;
}
for ( int i = 0; i < triCount * 3; ++i )
outIndices[i] = cur[i];
}
// Capsule proxy for shadows
// Lat/long mesh: CAPSULE_SLICES azimuthal slices around the long axis, a
// cylinder body, and two hemispherical caps with CAPSULE_CAP_RINGS interior
// latitude rings plus a pole each. Verts are encoded with two vec3s, in_axis
// (scaled by halfLength) and in_radial (scaled by radius), so the same proxy
// mesh works for any (halfLength, radius) pair.
//
// An inscribed facet mesh casts a shadow up to 1 - cos(halfAz) cos(halfLat)
// too small and its outline shows the slices. Scaling the radial vectors so
// facets straddle the true surface halves the max silhouette error, at 32
// slices it lands under 0.5% of radius, below a cascade texel.
//
// Vertex layout:
// - body ring -X, then body ring +X (these double as the caps' equators)
// - +X cap: interior rings equator->pole order, then the pole
// - -X cap: same
//
// Caps share their equator ring with the body's end ring, saves a ring of
// verts per cap and avoids any seam in the depth render.
#define CAPSULE_SLICES 32
#define CAPSULE_CAP_RINGS 7
#define CAPSULE_VERTICES ( 2 * CAPSULE_SLICES + 2 * ( CAPSULE_CAP_RINGS * CAPSULE_SLICES + 1 ) )
#define CAPSULE_INDICES ( 12 * CAPSULE_SLICES * ( CAPSULE_CAP_RINGS + 1 ) )
typedef struct CapsuleVertex
{
float axis[3];
float radial[3];
} CapsuleVertex;
// Helper macro: emit two triangles for a quad with corners
// bl, br, tr, tl (CCW outside-front).
#define CAPSULE_QUAD( bl, br, tr, tl ) \
do \
{ \
outIndices[index++] = (uint32_t)( bl ); \
outIndices[index++] = (uint32_t)( br ); \
outIndices[index++] = (uint32_t)( tr ); \
outIndices[index++] = (uint32_t)( bl ); \
outIndices[index++] = (uint32_t)( tr ); \
outIndices[index++] = (uint32_t)( tl ); \
} \
while ( 0 )
static void BuildCapsuleProxy( CapsuleVertex* outVerts, uint32_t* outIndices )
{
const float TWO_PI = 6.28318530717958647692f;
// Quad centers of an inscribed lat/long mesh dip below the true surface
// by cos(halfAz) cos(halfLat). Scale all radials so facets straddle the
// surface, halving the max silhouette error. Uniform scale keeps the
// proxy a true capsule of radius scale * r, no seam at the equators.
const float halfAz = B3_PI / (float)CAPSULE_SLICES;
const float halfLat = 0.25f * B3_PI / (float)( CAPSULE_CAP_RINGS + 1 );
const float scale = 2.0f / ( 1.0f + cosf( halfAz ) * cosf( halfLat ) );
// Vertices
int v = 0;
// Body rings, -X then +X. These double as the caps' equators.
for ( int side = 0; side < 2; ++side )
{
const float sx = ( side == 0 ) ? -1.0f : +1.0f;
for ( int i = 0; i < CAPSULE_SLICES; ++i, ++v )
{
const float beta = TWO_PI * (float)i / (float)CAPSULE_SLICES;
outVerts[v].axis[0] = sx;
outVerts[v].axis[1] = 0.0f;
outVerts[v].axis[2] = 0.0f;
outVerts[v].radial[0] = 0.0f;
outVerts[v].radial[1] = scale * cosf( beta );
outVerts[v].radial[2] = scale * sinf( beta );
}
}
// Caps, +X then -X: interior latitude rings equator->pole, then the pole.
// Ring r sits at latitude alpha = r * (pi/2) / (rings + 1).
for ( int side = 0; side < 2; ++side )
{
const float sx = ( side == 0 ) ? +1.0f : -1.0f;
for ( int r = 1; r <= CAPSULE_CAP_RINGS; ++r )
{
const float alpha = 0.5f * B3_PI * (float)r / (float)( CAPSULE_CAP_RINGS + 1 );
for ( int i = 0; i < CAPSULE_SLICES; ++i, ++v )
{
const float beta = TWO_PI * (float)i / (float)CAPSULE_SLICES;
outVerts[v].axis[0] = sx;
outVerts[v].axis[1] = 0.0f;
outVerts[v].axis[2] = 0.0f;
outVerts[v].radial[0] = scale * sx * sinf( alpha );
outVerts[v].radial[1] = scale * cosf( alpha ) * cosf( beta );
outVerts[v].radial[2] = scale * cosf( alpha ) * sinf( beta );
}
}
outVerts[v].axis[0] = sx;
outVerts[v].axis[1] = 0.0f;
outVerts[v].axis[2] = 0.0f;
outVerts[v].radial[0] = scale * sx;
outVerts[v].radial[1] = 0.0f;
outVerts[v].radial[2] = 0.0f;
++v;
}
// Indices
int index = 0;
// Body: ring -X to ring +X. For slice i and i+1, the outward face winds
// from -X[i] up the slice direction (beta increasing) to -X[i+1], across
// to +X[i+1], down to +X[i].
for ( int i = 0; i < CAPSULE_SLICES; ++i )
{
const int next = ( i + 1 ) % CAPSULE_SLICES;
CAPSULE_QUAD( i, next, CAPSULE_SLICES + next, CAPSULE_SLICES + i );
}
// +X cap: quad bands march outward from the equator (the +X body ring)
// through the latitude rings, then a fan to the pole. Going outward the
// face winds prev[i] -> prev[i+1] -> cur[i+1] -> cur[i].
{
int prev = CAPSULE_SLICES;
int cur = 2 * CAPSULE_SLICES;
for ( int r = 0; r < CAPSULE_CAP_RINGS; ++r )
{
for ( int i = 0; i < CAPSULE_SLICES; ++i )
{
const int next = ( i + 1 ) % CAPSULE_SLICES;
CAPSULE_QUAD( prev + i, prev + next, cur + next, cur + i );
}
prev = cur;
cur += CAPSULE_SLICES;
}
const int pole = cur;
for ( int i = 0; i < CAPSULE_SLICES; ++i )
{
const int next = ( i + 1 ) % CAPSULE_SLICES;
outIndices[index++] = (uint32_t)( prev + i );
outIndices[index++] = (uint32_t)( prev + next );
outIndices[index++] = (uint32_t)pole;
}
}
// -X cap: winding flipped relative to +X because the outward normal
// points toward -X, the "outside-front" side of each quad swaps slice
// order.
{
int prev = 0;
int cur = 2 * CAPSULE_SLICES + CAPSULE_CAP_RINGS * CAPSULE_SLICES + 1;
for ( int r = 0; r < CAPSULE_CAP_RINGS; ++r )
{
for ( int i = 0; i < CAPSULE_SLICES; ++i )
{
const int next = ( i + 1 ) % CAPSULE_SLICES;
CAPSULE_QUAD( prev + next, prev + i, cur + i, cur + next );
}
prev = cur;
cur += CAPSULE_SLICES;
}
const int pole = cur;
for ( int i = 0; i < CAPSULE_SLICES; ++i )
{
const int next = ( i + 1 ) % CAPSULE_SLICES;
outIndices[index++] = (uint32_t)( prev + next );
outIndices[index++] = (uint32_t)( prev + i );
outIndices[index++] = (uint32_t)pole;
}
}
}
#undef CAPSULE_QUAD
// On the GL backend, set clip-space Z to [0,1] so the rasterizer's
// gl_FragCoord.z matches what the impostor shaders write into gl_FragDepth
// (hit_clip.z / hit_clip.w). Default GL clip space is [-1,1], remapped by
@ -888,30 +575,10 @@ void InitRenderer( const sg_environment* env )
s_gfx.shadowGeomPipelineMirror = sg_make_pipeline( &shadowGeomMirrorPdesc );
// Shadow caster pipeline: spheres
// Build the ico-sphere proxy once and upload to a
// dedicated vbo/ibo. Position-only vertex layout (no normals, the
// caster shader never reads them).
{
float icoVerts[ICO_SPHERE_VERTICES][3];
uint32_t icoIndices[ICO_SPHERE_INDICES];
BuildIcosphere( icoVerts, icoIndices );
s_gfx.icosphereIndexCount = ICO_SPHERE_INDICES;
sg_buffer_desc ivdesc = { 0 };
ivdesc.usage.vertex_buffer = true;
ivdesc.data.ptr = icoVerts;
ivdesc.data.size = sizeof( icoVerts );
ivdesc.label = "icosphere_verts";
s_gfx.icosphereVbuf = sg_make_buffer( &ivdesc );
sg_buffer_desc iidesc = { 0 };
iidesc.usage.index_buffer = true;
iidesc.data.ptr = icoIndices;
iidesc.data.size = sizeof( icoIndices );
iidesc.label = "icosphere_indices";
s_gfx.icosphereIbuf = sg_make_buffer( &iidesc );
}
// Rasterizes the bounding cube the lit impostor uses, so it borrows the
// cube's buffers and vertex format. Culling stays on back faces: the
// shader's conservative-depth promise only holds while the rasterized
// surface is the light-facing one.
s_gfx.shadowSphereShader = sg_make_shader( shadow_sphere_caster_shader_desc( sg_query_backend() ) );
sg_pipeline_desc shadowSpherePdesc = { 0 };
@ -919,7 +586,7 @@ void InitRenderer( const sg_environment* env )
shadowSpherePdesc.layout.buffers[0].stride = sizeof( float ) * 3;
shadowSpherePdesc.layout.attrs[ATTR_shadow_sphere_caster_in_pos].format = SG_VERTEXFORMAT_FLOAT3;
shadowSpherePdesc.layout.attrs[ATTR_shadow_sphere_caster_in_pos].buffer_index = 0;
shadowSpherePdesc.index_type = SG_INDEXTYPE_UINT32;
shadowSpherePdesc.index_type = SG_INDEXTYPE_UINT16;
shadowSpherePdesc.colors[0].pixel_format = SG_PIXELFORMAT_NONE;
shadowSpherePdesc.depth.pixel_format = SG_PIXELFORMAT_DEPTH;
shadowSpherePdesc.depth.compare = SG_COMPAREFUNC_LESS;
@ -930,40 +597,16 @@ void InitRenderer( const sg_environment* env )
shadowSpherePdesc.label = "shadow_sphere_pipeline";
s_gfx.shadowSpherePipeline = sg_make_pipeline( &shadowSpherePdesc );
// Shadow caster pipeline: capsules
{
CapsuleVertex capsVerts[CAPSULE_VERTICES];
uint32_t capsIndices[CAPSULE_INDICES];
BuildCapsuleProxy( capsVerts, capsIndices );
s_gfx.capsuleProxyIndexCount = CAPSULE_INDICES;
sg_buffer_desc cvdesc = { 0 };
cvdesc.usage.vertex_buffer = true;
cvdesc.data.ptr = capsVerts;
cvdesc.data.size = sizeof( capsVerts );
cvdesc.label = "capsule_proxy_verts";
s_gfx.capsuleProxyVbuf = sg_make_buffer( &cvdesc );
sg_buffer_desc cidesc = { 0 };
cidesc.usage.index_buffer = true;
cidesc.data.ptr = capsIndices;
cidesc.data.size = sizeof( capsIndices );
cidesc.label = "capsule_proxy_indices";
s_gfx.capsuleProxyIbuf = sg_make_buffer( &cidesc );
}
// Shadow caster pipeline: capsules, see the sphere caster above. The
// OBB comes from the same cube buffers.
s_gfx.shadowCapsuleShader = sg_make_shader( shadow_capsule_caster_shader_desc( sg_query_backend() ) );
sg_pipeline_desc shadowCapsulePdesc = { 0 };
shadowCapsulePdesc.shader = s_gfx.shadowCapsuleShader;
shadowCapsulePdesc.layout.buffers[0].stride = sizeof( float ) * 6;
shadowCapsulePdesc.layout.attrs[ATTR_shadow_capsule_caster_in_axis].format = SG_VERTEXFORMAT_FLOAT3;
shadowCapsulePdesc.layout.attrs[ATTR_shadow_capsule_caster_in_axis].buffer_index = 0;
shadowCapsulePdesc.layout.attrs[ATTR_shadow_capsule_caster_in_axis].offset = 0;
shadowCapsulePdesc.layout.attrs[ATTR_shadow_capsule_caster_in_radial].format = SG_VERTEXFORMAT_FLOAT3;
shadowCapsulePdesc.layout.attrs[ATTR_shadow_capsule_caster_in_radial].buffer_index = 0;
shadowCapsulePdesc.layout.attrs[ATTR_shadow_capsule_caster_in_radial].offset = sizeof( float ) * 3;
shadowCapsulePdesc.index_type = SG_INDEXTYPE_UINT32;
shadowCapsulePdesc.layout.buffers[0].stride = sizeof( float ) * 3;
shadowCapsulePdesc.layout.attrs[ATTR_shadow_capsule_caster_in_pos].format = SG_VERTEXFORMAT_FLOAT3;
shadowCapsulePdesc.layout.attrs[ATTR_shadow_capsule_caster_in_pos].buffer_index = 0;
shadowCapsulePdesc.index_type = SG_INDEXTYPE_UINT16;
shadowCapsulePdesc.colors[0].pixel_format = SG_PIXELFORMAT_NONE;
shadowCapsulePdesc.depth.pixel_format = SG_PIXELFORMAT_DEPTH;
shadowCapsulePdesc.depth.compare = SG_COMPAREFUNC_LESS;
@ -1291,6 +934,35 @@ static b3Vec3 TransformDir( Mat4 m, b3Vec3 v )
return (b3Vec3){ r.x, r.y, r.z };
}
// The lit shaders carry their own SHADOW_CASCADE_COUNT, and nothing links it
// to the one here. Check the generated layout instead, so a half-finished
// change is a build error rather than a cascade that silently never receives
// its matrix, or a fill loop that runs off the end of the array into the
// uniforms behind it. Every shader that takes cascades needs its own check,
// since they are generated one at a time. Tripping this means regenerating
// the shaders.
_Static_assert( sizeof( ( (ub_pass_t*)0 )->cascade_matrices ) / sizeof( Mat4 ) == SHADOW_CASCADE_COUNT,
"cube shader cascade count differs from SHADOW_CASCADE_COUNT" );
_Static_assert( sizeof( ( (sphere_ub_pass_t*)0 )->cascade_matrices ) / sizeof( Mat4 ) == SHADOW_CASCADE_COUNT,
"sphere shader cascade count differs from SHADOW_CASCADE_COUNT" );
_Static_assert( sizeof( ( (capsule_ub_pass_t*)0 )->cascade_matrices ) / sizeof( Mat4 ) == SHADOW_CASCADE_COUNT,
"capsule shader cascade count differs from SHADOW_CASCADE_COUNT" );
_Static_assert( sizeof( ( (geom_ub_pass_t*)0 )->cascade_matrices ) / sizeof( Mat4 ) == SHADOW_CASCADE_COUNT,
"geom shader cascade count differs from SHADOW_CASCADE_COUNT" );
// One vec4 lane per cascade, which is what caps the count at four. Lanes past
// the count stay zero, so a shader built for more would read unlit rather than
// garbage.
static Vec4 PackCascades( float ( *get )( int cascade ) )
{
float lanes[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
for ( int i = 0; i < SHADOW_CASCADE_COUNT; ++i )
{
lanes[i] = get( i );
}
return MakeVec4( lanes[0], lanes[1], lanes[2], lanes[3] );
}
static sg_pass_action MakeSceneClear( void )
{
sg_pass_action a = { 0 };
@ -1366,6 +1038,17 @@ static void DrawShadowCascade( int cascade )
const Mat4 lightVP = GetCascadeMatrix( cascade );
bool viewportApplied = false;
// Impostor casters march along the light from the proxy face they
// rasterized, then turn the hit into clip depth themselves. Both
// quantities come out of the projection's depth row, which under an
// orthographic light varies only along the light axis: its gradient
// is the direction light travels, and it is the row that maps a
// world position to depth. Reading the direction back off the matrix
// rather than off the sun keeps the two from drifting apart.
const Vec4 lightDepthRow = MakeVec4( lightVP.cx.z, lightVP.cy.z, lightVP.cz.z, lightVP.cw.z );
const b3Vec3 lightDir = b3Normalize( ( b3Vec3 ){ lightDepthRow.x, lightDepthRow.y, lightDepthRow.z } );
const Vec4 lightDirPacked = MakeVec4( lightDir.x, lightDir.y, lightDir.z, 0.0f );
// Cubes
if ( s_gfx.cubeCount > 0 )
{
@ -1392,7 +1075,7 @@ static void DrawShadowCascade( int cascade )
sg_pop_debug_group();
}
// Spheres (low-poly icosphere proxy)
// Spheres
if ( s_gfx.sphereCount > 0 )
{
sg_push_debug_group( "caster_sphere" );
@ -1403,22 +1086,26 @@ static void DrawShadowCascade( int cascade )
}
sg_apply_pipeline( s_gfx.shadowSpherePipeline );
sg_bindings bindings = { 0 };
bindings.vertex_buffers[0] = s_gfx.icosphereVbuf;
bindings.index_buffer = s_gfx.icosphereIbuf;
bindings.vertex_buffers[0] = s_gfx.vbuf;
bindings.index_buffer = s_gfx.ibuf;
bindings.views[VIEW_shadow_sphere_instances] = s_gfx.sphereInstView;
sg_apply_bindings( &bindings );
shadow_sphere_ub_frame_t sub = { 0 };
sub.light_view_proj = lightVP;
sg_apply_uniforms( UB_shadow_sphere_ub_frame, &SG_RANGE( sub ) );
shadow_sphere_ub_pass_t supass = { 0 };
supass.light_dir = lightDirPacked;
supass.depth_row = lightDepthRow;
sg_apply_uniforms( UB_shadow_sphere_ub_pass, &SG_RANGE( supass ) );
shadow_sphere_ub_draw_t sudraw = { 0 };
sg_apply_uniforms( UB_shadow_sphere_ub_draw, &SG_RANGE( sudraw ) );
sg_draw( 0, s_gfx.icosphereIndexCount, (int)s_gfx.sphereCount );
sg_draw( 0, (int)( sizeof( CUBE_INDICES ) / sizeof( CUBE_INDICES[0] ) ), (int)s_gfx.sphereCount );
sg_pop_debug_group();
}
// Capsules (cylinder + caps proxy)
// Capsules
if ( s_gfx.capsuleCount > 0 )
{
sg_push_debug_group( "caster_capsule" );
@ -1429,18 +1116,22 @@ static void DrawShadowCascade( int cascade )
}
sg_apply_pipeline( s_gfx.shadowCapsulePipeline );
sg_bindings bindings = { 0 };
bindings.vertex_buffers[0] = s_gfx.capsuleProxyVbuf;
bindings.index_buffer = s_gfx.capsuleProxyIbuf;
bindings.vertex_buffers[0] = s_gfx.vbuf;
bindings.index_buffer = s_gfx.ibuf;
bindings.views[VIEW_shadow_capsule_instances] = s_gfx.capsuleInstView;
sg_apply_bindings( &bindings );
shadow_capsule_ub_frame_t cub = { 0 };
cub.light_view_proj = lightVP;
sg_apply_uniforms( UB_shadow_capsule_ub_frame, &SG_RANGE( cub ) );
shadow_capsule_ub_pass_t cupass = { 0 };
cupass.light_dir = lightDirPacked;
cupass.depth_row = lightDepthRow;
sg_apply_uniforms( UB_shadow_capsule_ub_pass, &SG_RANGE( cupass ) );
shadow_capsule_ub_draw_t cudraw = { 0 };
sg_apply_uniforms( UB_shadow_capsule_ub_draw, &SG_RANGE( cudraw ) );
sg_draw( 0, s_gfx.capsuleProxyIndexCount, (int)s_gfx.capsuleCount );
sg_draw( 0, (int)( sizeof( CUBE_INDICES ) / sizeof( CUBE_INDICES[0] ) ), (int)s_gfx.capsuleCount );
sg_pop_debug_group();
}
@ -1539,14 +1230,18 @@ static void DrawShadowCascade( int cascade )
}
sg_apply_pipeline( s_gfx.shadowSpherePipeline );
sg_bindings bindings = { 0 };
bindings.vertex_buffers[0] = s_gfx.icosphereVbuf;
bindings.index_buffer = s_gfx.icosphereIbuf;
bindings.vertex_buffers[0] = s_gfx.vbuf;
bindings.index_buffer = s_gfx.ibuf;
bindings.views[VIEW_shadow_sphere_instances] = s_gfx.sphereInstViewXp;
sg_apply_bindings( &bindings );
shadow_sphere_ub_frame_t sub = { 0 };
sub.light_view_proj = lightVP;
sg_apply_uniforms( UB_shadow_sphere_ub_frame, &SG_RANGE( sub ) );
shadow_sphere_ub_pass_t supass = { 0 };
supass.light_dir = lightDirPacked;
supass.depth_row = lightDepthRow;
sg_apply_uniforms( UB_shadow_sphere_ub_pass, &SG_RANGE( supass ) );
for ( size_t i = 0; i < s_gfx.sphereCountXp; ++i )
{
@ -1555,7 +1250,7 @@ static void DrawShadowCascade( int cascade )
shadow_sphere_ub_draw_t sudraw = { 0 };
sudraw.inst_base[0] = (int)i;
sg_apply_uniforms( UB_shadow_sphere_ub_draw, &SG_RANGE( sudraw ) );
sg_draw( 0, s_gfx.icosphereIndexCount, 1 );
sg_draw( 0, (int)( sizeof( CUBE_INDICES ) / sizeof( CUBE_INDICES[0] ) ), 1 );
}
sg_pop_debug_group();
}
@ -1570,14 +1265,18 @@ static void DrawShadowCascade( int cascade )
}
sg_apply_pipeline( s_gfx.shadowCapsulePipeline );
sg_bindings bindings = { 0 };
bindings.vertex_buffers[0] = s_gfx.capsuleProxyVbuf;
bindings.index_buffer = s_gfx.capsuleProxyIbuf;
bindings.vertex_buffers[0] = s_gfx.vbuf;
bindings.index_buffer = s_gfx.ibuf;
bindings.views[VIEW_shadow_capsule_instances] = s_gfx.capsuleInstViewXp;
sg_apply_bindings( &bindings );
shadow_capsule_ub_frame_t cub = { 0 };
cub.light_view_proj = lightVP;
sg_apply_uniforms( UB_shadow_capsule_ub_frame, &SG_RANGE( cub ) );
shadow_capsule_ub_pass_t cupass = { 0 };
cupass.light_dir = lightDirPacked;
cupass.depth_row = lightDepthRow;
sg_apply_uniforms( UB_shadow_capsule_ub_pass, &SG_RANGE( cupass ) );
for ( size_t i = 0; i < s_gfx.capsuleCountXp; ++i )
{
@ -1586,7 +1285,7 @@ static void DrawShadowCascade( int cascade )
shadow_capsule_ub_draw_t cudraw = { 0 };
cudraw.inst_base[0] = (int)i;
sg_apply_uniforms( UB_shadow_capsule_ub_draw, &SG_RANGE( cudraw ) );
sg_draw( 0, s_gfx.capsuleProxyIndexCount, 1 );
sg_draw( 0, (int)( sizeof( CUBE_INDICES ) / sizeof( CUBE_INDICES[0] ) ), 1 );
}
sg_pop_debug_group();
}
@ -1669,10 +1368,12 @@ static void DrawScene( int targetWidth, int targetHeight, const FrameInput* fram
// flip). The shader multiplies NDC.y by this before mapping to UV.y.
const sg_backend backend = sg_query_backend();
const float uvYSign = ( backend == SG_BACKEND_GLCORE || backend == SG_BACKEND_GLES3 ) ? 1.0f : -1.0f;
const Vec4 cascadeFarViewZ = MakeVec4( GetCascadeFarViewZ( 0 ), GetCascadeFarViewZ( 1 ), GetCascadeFarViewZ( 2 ), uvYSign );
const Vec4 cascadePcfScale = MakeVec4( GetCascadePcfScale( 0 ), GetCascadePcfScale( 1 ), GetCascadePcfScale( 2 ), 0.0f );
Mat4 cascadeMatrices[3];
for ( int i = 0; i < 3; ++i )
const Vec4 shadowParams = MakeVec4( uvYSign, GetShadowTexelSize(), 0.0f, 0.0f );
const Vec4 cascadeFarViewZ = PackCascades( GetCascadeFarViewZ );
const Vec4 cascadeTexelWorld = PackCascades( GetCascadeTexelWorld );
const Vec4 cascadeDepthBias = PackCascades( GetCascadeDepthBias );
Mat4 cascadeMatrices[SHADOW_CASCADE_COUNT];
for ( int i = 0; i < SHADOW_CASCADE_COUNT; ++i )
{
cascadeMatrices[i] = GetCascadeMatrix( i );
}
@ -1716,8 +1417,10 @@ static void DrawScene( int targetWidth, int targetHeight, const FrameInput* fram
up.sun_color = sunColor;
up.flags[0] = frame->debugMode;
up.cascade_far_view_z = cascadeFarViewZ;
up.cascade_pcf_scale = cascadePcfScale;
for ( int i = 0; i < 3; ++i )
up.cascade_texel_world = cascadeTexelWorld;
up.cascade_depth_bias = cascadeDepthBias;
up.shadow_params = shadowParams;
for ( int i = 0; i < SHADOW_CASCADE_COUNT; ++i )
up.cascade_matrices[i] = cascadeMatrices[i];
up.view = frame->view;
up.camera_pos_world = MakeVec4( frame->cameraPosition.x, frame->cameraPosition.y, frame->cameraPosition.z, 0.0f );
@ -1765,8 +1468,10 @@ static void DrawScene( int targetWidth, int targetHeight, const FrameInput* fram
sup.view_proj = viewProj;
sup.view = frame->view;
sup.cascade_far_view_z = cascadeFarViewZ;
sup.cascade_pcf_scale = cascadePcfScale;
for ( int i = 0; i < 3; ++i )
sup.cascade_texel_world = cascadeTexelWorld;
sup.cascade_depth_bias = cascadeDepthBias;
sup.shadow_params = shadowParams;
for ( int i = 0; i < SHADOW_CASCADE_COUNT; ++i )
sup.cascade_matrices[i] = cascadeMatrices[i];
for ( int i = 0; i < 9; ++i )
{
@ -1809,8 +1514,10 @@ static void DrawScene( int targetWidth, int targetHeight, const FrameInput* fram
cup.view_proj = viewProj;
cup.view = frame->view;
cup.cascade_far_view_z = cascadeFarViewZ;
cup.cascade_pcf_scale = cascadePcfScale;
for ( int i = 0; i < 3; ++i )
cup.cascade_texel_world = cascadeTexelWorld;
cup.cascade_depth_bias = cascadeDepthBias;
cup.shadow_params = shadowParams;
for ( int i = 0; i < SHADOW_CASCADE_COUNT; ++i )
cup.cascade_matrices[i] = cascadeMatrices[i];
for ( int i = 0; i < 9; ++i )
{
@ -1862,8 +1569,10 @@ static void DrawScene( int targetWidth, int targetHeight, const FrameInput* fram
gup.grid_offset = MakeVec4( frame->gridWrap.x, frame->gridWrap.y, frame->drawOrigin.x, frame->drawOrigin.z );
gup.view = frame->view;
gup.cascade_far_view_z = cascadeFarViewZ;
gup.cascade_pcf_scale = cascadePcfScale;
for ( int i = 0; i < 3; ++i )
gup.cascade_texel_world = cascadeTexelWorld;
gup.cascade_depth_bias = cascadeDepthBias;
gup.shadow_params = shadowParams;
for ( int i = 0; i < SHADOW_CASCADE_COUNT; ++i )
gup.cascade_matrices[i] = cascadeMatrices[i];
for ( int i = 0; i < 9; ++i )
{
@ -2272,10 +1981,12 @@ static void DrawTransparentIntoResolve( int width, int height, const FrameInput*
const sg_backend backend = sg_query_backend();
const float uvYSign = ( backend == SG_BACKEND_GLCORE || backend == SG_BACKEND_GLES3 ) ? 1.0f : -1.0f;
const Vec4 cascadeFarViewZ = MakeVec4( GetCascadeFarViewZ( 0 ), GetCascadeFarViewZ( 1 ), GetCascadeFarViewZ( 2 ), uvYSign );
const Vec4 cascadePcfScale = MakeVec4( GetCascadePcfScale( 0 ), GetCascadePcfScale( 1 ), GetCascadePcfScale( 2 ), 0.0f );
Mat4 cascadeMatrices[3];
for ( int i = 0; i < 3; ++i )
const Vec4 shadowParams = MakeVec4( uvYSign, GetShadowTexelSize(), 0.0f, 0.0f );
const Vec4 cascadeFarViewZ = PackCascades( GetCascadeFarViewZ );
const Vec4 cascadeTexelWorld = PackCascades( GetCascadeTexelWorld );
const Vec4 cascadeDepthBias = PackCascades( GetCascadeDepthBias );
Mat4 cascadeMatrices[SHADOW_CASCADE_COUNT];
for ( int i = 0; i < SHADOW_CASCADE_COUNT; ++i )
{
cascadeMatrices[i] = GetCascadeMatrix( i );
}
@ -2308,8 +2019,10 @@ static void DrawTransparentIntoResolve( int width, int height, const FrameInput*
cubePass.sun_color = sunColor;
cubePass.flags[0] = frame->debugMode;
cubePass.cascade_far_view_z = cascadeFarViewZ;
cubePass.cascade_pcf_scale = cascadePcfScale;
for ( int i = 0; i < 3; ++i )
cubePass.cascade_texel_world = cascadeTexelWorld;
cubePass.cascade_depth_bias = cascadeDepthBias;
cubePass.shadow_params = shadowParams;
for ( int i = 0; i < SHADOW_CASCADE_COUNT; ++i )
{
cubePass.cascade_matrices[i] = cascadeMatrices[i];
}
@ -2331,8 +2044,10 @@ static void DrawTransparentIntoResolve( int width, int height, const FrameInput*
spherePass.view_proj = view_proj;
spherePass.view = frame->view;
spherePass.cascade_far_view_z = cascadeFarViewZ;
spherePass.cascade_pcf_scale = cascadePcfScale;
for ( int i = 0; i < 3; ++i )
spherePass.cascade_texel_world = cascadeTexelWorld;
spherePass.cascade_depth_bias = cascadeDepthBias;
spherePass.shadow_params = shadowParams;
for ( int i = 0; i < SHADOW_CASCADE_COUNT; ++i )
spherePass.cascade_matrices[i] = cascadeMatrices[i];
for ( int i = 0; i < 9; ++i )
spherePass.sh[i] = MakeVec4( iblSh[i].x, iblSh[i].y, iblSh[i].z, 0.0f );
@ -2348,8 +2063,10 @@ static void DrawTransparentIntoResolve( int width, int height, const FrameInput*
capsulePass.view_proj = view_proj;
capsulePass.view = frame->view;
capsulePass.cascade_far_view_z = cascadeFarViewZ;
capsulePass.cascade_pcf_scale = cascadePcfScale;
for ( int i = 0; i < 3; ++i )
capsulePass.cascade_texel_world = cascadeTexelWorld;
capsulePass.cascade_depth_bias = cascadeDepthBias;
capsulePass.shadow_params = shadowParams;
for ( int i = 0; i < SHADOW_CASCADE_COUNT; ++i )
capsulePass.cascade_matrices[i] = cascadeMatrices[i];
for ( int i = 0; i < 9; ++i )
capsulePass.sh[i] = MakeVec4( iblSh[i].x, iblSh[i].y, iblSh[i].z, 0.0f );
@ -2366,8 +2083,10 @@ static void DrawTransparentIntoResolve( int width, int height, const FrameInput*
geomPass.grid_offset = MakeVec4( frame->gridWrap.x, frame->gridWrap.y, frame->drawOrigin.x, frame->drawOrigin.z );
geomPass.view = frame->view;
geomPass.cascade_far_view_z = cascadeFarViewZ;
geomPass.cascade_pcf_scale = cascadePcfScale;
for ( int i = 0; i < 3; ++i )
geomPass.cascade_texel_world = cascadeTexelWorld;
geomPass.cascade_depth_bias = cascadeDepthBias;
geomPass.shadow_params = shadowParams;
for ( int i = 0; i < SHADOW_CASCADE_COUNT; ++i )
geomPass.cascade_matrices[i] = cascadeMatrices[i];
for ( int i = 0; i < 9; ++i )
geomPass.sh[i] = MakeVec4( iblSh[i].x, iblSh[i].y, iblSh[i].z, 0.0f );
@ -2870,12 +2589,8 @@ void ShutdownRenderer( void )
ShutdownSky();
sg_destroy_pipeline( s_gfx.shadowCapsulePipeline );
sg_destroy_shader( s_gfx.shadowCapsuleShader );
sg_destroy_buffer( s_gfx.capsuleProxyIbuf );
sg_destroy_buffer( s_gfx.capsuleProxyVbuf );
sg_destroy_pipeline( s_gfx.shadowSpherePipeline );
sg_destroy_shader( s_gfx.shadowSphereShader );
sg_destroy_buffer( s_gfx.icosphereIbuf );
sg_destroy_buffer( s_gfx.icosphereVbuf );
sg_destroy_pipeline( s_gfx.shadowGeomPipelineMirror );
sg_destroy_pipeline( s_gfx.shadowGeomPipeline );
sg_destroy_shader( s_gfx.shadowGeomShader );

View file

@ -3,44 +3,52 @@
#include "gfx/shadow.h"
#include "gfx/draw.h"
#include <float.h>
#include <math.h>
#include <stdio.h>
// Cascade fitting parameters. SHADOW_SPLIT_NEAR and the default far
// (SHADOW_SPLIT_FAR, in shadow.h) are *view-space* distances from the camera
// Cascade fitting parameters. The split range defaults (SHADOW_SPLIT_NEAR /
// SHADOW_SPLIT_FAR, in shadow.h) are *view-space* distances from the camera
// (positive). CSM quality at distance falls off fast, so cascades focus on
// near content.
//
// PSSM_LAMBDA blends the uniform split scheme (each cascade covers an
// equal slice of view-space distance) and the logarithmic scheme (each
// cascade covers an equal multiplicative range). 0 = pure uniform,
// 1 = pure log. 0.5 is the sweet spot at the default range. The blend is
// pushed toward log up to PSSM_LAMBDA_MAX as the range widens, otherwise a
// large far would balloon the near cascade and coarsen close-up shadows.
// 1 = pure log, 0.5 is the standard sweet spot. Raising it tightens the
// near cascades but drags the boundaries inward, so the last cascade
// takes over closer to the camera where its coarser texels show. This is
// the starting value, SetShadowSplitLambda overrides it.
//
// CASTER_MARGIN_M expands the orthographic light frustum's near edge
// toward the sun so casters above the camera frustum slice (e.g. the
// building roof at y=3 when the slice itself only reaches y=1) still cast
// onto receivers inside the slice.
#define SHADOW_SPLIT_NEAR 0.1f
// DEPTH_BIAS_TEXELS is what remains of the comparison bias once the lit
// shaders offset the lookup along the surface normal. It only has to
// cover depth quantization, so it is measured in texels of the cascade
// that owns it rather than in a fixed world size that would be wrong at
// one end or the other of a wide split range.
#define PSSM_LAMBDA 0.5f
#define PSSM_LAMBDA_MAX 0.9f
#define CASTER_MARGIN_M 50.0f
#define DEPTH_BIAS_TEXELS 0.5f
static struct
{
b3Vec3 sunDir; // world-space dir TO sun, normalized
float splitNear; // PSSM split range near (positive view-Z)
float splitFar; // PSSM split range far (positive view-Z)
float splitLambda; // uniform/log split blend, widens with range
float splitLambda; // uniform/log blend for the split scheme
sg_image depthArray; // D32F, cascade layers
sg_view cascadeAttachmentViews[SHADOW_CASCADE_COUNT]; // depth-stencil view per cascade
sg_view sampleView; // full-array texture-sample view
sg_sampler sampler; // comparison sampler (LESS_EQUAL, linear PCF)
Mat4 cascadeMatrices[SHADOW_CASCADE_COUNT]; // light-space view-proj per cascade
float cascadeFarViewZ[SHADOW_CASCADE_COUNT]; // far end (positive view-Z) per cascade
float cascadeRadius[SHADOW_CASCADE_COUNT]; // bounding-sphere radius = ortho half-extent
float cascadeTexelWorld[SHADOW_CASCADE_COUNT]; // one shadow texel in world length units
float cascadeDepthBias[SHADOW_CASCADE_COUNT]; // residual bias in shadow clip-Z units
bool inPass; // safety against unbalanced begin/end
} s_shadow;
@ -52,16 +60,24 @@ static inline float ComputeSplitDistance( int i, int cascadeCount, float nearZ,
const float fi = (float)i / (float)cascadeCount;
const float u = nearZ + ( farZ - nearZ ) * fi;
const float l = nearZ * powf( farZ / nearZ, fi );
return s_shadow.splitLambda * l + ( 1.0f - s_shadow.splitLambda ) * u;
const float lambda = s_shadow.splitLambda;
return lambda * l + ( 1.0f - lambda ) * u;
}
// Push the uniform/log blend toward log as the split range widens, so the near
// cascade stays tight when far is large. Anchored at the default range so the
// reference scenes keep the 0.5 sweet spot.
static inline float SplitLambdaForRange( float nearZ, float farZ )
// MakePerspectiveAndInverse puts proj[1][1] = 1/tan(fovY/2) and
// proj[0][0] = proj[1][1] / aspect. The analytic inverse stores both
// quantities directly, so callers holding either matrix can recover the
// frustum shape.
static inline void PerspectiveShape( const Mat4* proj, float* tanHalfFovY, float* aspect )
{
float decades = log10f( ( farZ / nearZ ) / ( SHADOW_SPLIT_FAR / SHADOW_SPLIT_NEAR ) );
return b3ClampFloat( PSSM_LAMBDA + 0.4f * decades, PSSM_LAMBDA, PSSM_LAMBDA_MAX );
*tanHalfFovY = ( proj->cy.y != 0.0f ) ? ( 1.0f / proj->cy.y ) : 1.0f;
*aspect = ( proj->cx.x != 0.0f ) ? ( proj->cy.y / proj->cx.x ) : 1.0f;
}
static inline void PerspectiveShapeFromInverse( const Mat4* projInv, float* tanHalfFovY, float* aspect )
{
*tanHalfFovY = projInv->cy.y;
*aspect = ( projInv->cy.y != 0.0f ) ? ( projInv->cx.x / projInv->cy.y ) : 1.0f;
}
// Fill cornersOut with the 8 world-space corners of the camera frustum
@ -71,18 +87,14 @@ static inline float SplitLambdaForRange( float nearZ, float farZ )
// Camera basis comes straight from `viewInv` (the camera's world matrix
// produced by mat4ViewAndInverse): column 0 is right, column 1 is up,
// column 2 is back (i.e., -forward), column 3 is eye, no inversion.
// FovY and aspect are read from the projection matrix: mat4Perspective
// puts proj[1][1] = 1/tan(fovY/2) and proj[0][0] = proj[1][1] / aspect.
static void FrustumSliceCornersWorld( const Mat4* viewInv, const Mat4* proj, float nearZ, float farZ, b3Vec3 cornersOut[8] )
static void FrustumSliceCornersWorld( const Mat4* viewInv, float tanHalfFovY, float aspect, float nearZ, float farZ,
b3Vec3 cornersOut[8] )
{
const b3Vec3 eye = { viewInv->cw.x, viewInv->cw.y, viewInv->cw.z };
const b3Vec3 right = { viewInv->cx.x, viewInv->cx.y, viewInv->cx.z };
const b3Vec3 up = { viewInv->cy.x, viewInv->cy.y, viewInv->cy.z };
const b3Vec3 forward = { -viewInv->cz.x, -viewInv->cz.y, -viewInv->cz.z };
const float tanHalfFovY = ( proj->cy.y != 0.0f ) ? ( 1.0f / proj->cy.y ) : 1.0f;
const float aspect = ( proj->cx.x != 0.0f ) ? ( proj->cy.y / proj->cx.x ) : 1.0f;
const float distances[2] = { nearZ, farZ };
for ( int s = 0; s < 2; ++s )
{
@ -101,29 +113,16 @@ static void FrustumSliceCornersWorld( const Mat4* viewInv, const Mat4* proj, flo
}
}
// Fit one cascade's light-space view-projection matrix to the camera
// frustum slice [nearZ, farZ] for the configured sun direction.
//
// The slice is bounded by a *world-space sphere* (centroid + max radius
// from centroid to any slice corner). The sphere is rotation-invariant.
// Rotating the camera around its eye doesn't move it, which is the key
// property that lets the texel-snap stabilization avoid swimming edges.
//
// Light view: orthonormal frame whose -Z axis points toward the sun.
// Light proj: orthographic, sized to enclose the sphere. The near plane
// is pushed back along +sun by CASTER_MARGIN_M so casters between the
// slice and the sun are not clipped.
//
// Texel-snap: after the unsnapped lightVP is built, transform the slice
// center through it to clip space, round the resulting clip-space xy to
// the nearest texel grid step, and apply the rounding delta as a
// post-translation. This pins the cascade to a fixed grid in light
// space, small camera motions no longer cause the shadow texels to
// drift relative to the casters.
static Mat4 FitCascade( const Mat4* viewInv, const Mat4* proj, b3Vec3 dirToSun, float nearZ, float farZ, float* radiusOut )
// Bound a frustum slice by a world-space sphere: centroid of the 8
// corners, plus the max distance from it to any of them. The sphere is
// rotation-invariant. Rotating the camera around its eye doesn't change
// the radius, which is the key property that lets the texel-snap
// stabilization avoid swimming edges.
static void SliceBoundingSphere( const Mat4* viewInv, float tanHalfFovY, float aspect, float nearZ, float farZ,
b3Vec3* centerOut, float* radiusOut )
{
b3Vec3 corners[8];
FrustumSliceCornersWorld( viewInv, proj, nearZ, farZ, corners );
FrustumSliceCornersWorld( viewInv, tanHalfFovY, aspect, nearZ, farZ, corners );
b3Vec3 center = b3Vec3_zero;
for ( int i = 0; i < 8; ++i )
@ -146,7 +145,34 @@ static Mat4 FitCascade( const Mat4* viewInv, const Mat4* proj, b3Vec3 dirToSun,
{
radius = 0.01f;
}
*centerOut = center;
*radiusOut = radius;
}
// Fit one cascade's light-space view-projection matrix to the camera
// frustum slice [nearZ, farZ] for the configured sun direction.
//
// Light view: orthonormal frame whose -Z axis points toward the sun.
// Light proj: orthographic, sized to enclose the sphere. The near plane
// is pushed back along +sun by CASTER_MARGIN_M so casters between the
// slice and the sun are not clipped.
//
// Texel-snap: quantize the sphere center onto a world-anchored lattice
// aligned with the light's own axes, one texel of world per step, then
// build the light matrices around the snapped center. Camera motion now
// slides the cascade in whole texels, so shadow edges step instead of
// crawling.
//
// It has to happen here, on the center, and not by projecting the center
// through the finished lightVP: the center is the look-at target, so it
// lands on clip (0, 0) by construction and rounding it is a no-op.
static Mat4 FitCascade( const Mat4* viewInv, float tanHalfFovY, float aspect, b3Vec3 dirToSun, float nearZ, float farZ,
float* radiusOut )
{
b3Vec3 center;
float radius;
SliceBoundingSphere( viewInv, tanHalfFovY, aspect, nearZ, farZ, &center, &radius );
// Avoid a degenerate up vector when the sun is straight up/down.
b3Vec3 up = b3Vec3_axisY;
@ -155,28 +181,47 @@ static Mat4 FitCascade( const Mat4* viewInv, const Mat4* proj, b3Vec3 dirToSun,
up = b3Vec3_axisZ;
}
// Light axes, matching the basis MakeLookAt derives below. The eye sits
// along +sun from the target, so the light looks along -sun. These
// depend only on the sun and the up choice, never on the camera, which
// is what makes the lattice hold still.
const b3Vec3 forward = { -dirToSun.x, -dirToSun.y, -dirToSun.z };
const b3Vec3 lightRight = b3Normalize( b3Cross( forward, up ) );
const b3Vec3 lightUp = b3Cross( lightRight, forward );
// Radius is fixed for a given split, field of view and aspect, so the
// lattice step is fixed too and the same world points keep landing on
// the same texels frame to frame.
const float texelWorld = 2.0f * radius / (float)SHADOW_RESOLUTION;
// Geometry reaches the GPU shifted against the draw origin, which
// tracks the camera, so the eye sits at this frame's origin and the
// frame slides whenever the camera does. Anchoring the lattice here
// would drag it along and quantize against a moving reference, which
// is the crawl the snap exists to remove. Fold the draw origin back in
// and snap the absolute coordinate, in double so the fractional part
// within a texel survives far from the origin.
const b3Pos drawOrigin = GetDrawOrigin();
const double ox = (double)lightRight.x * (double)drawOrigin.x + (double)lightRight.y * (double)drawOrigin.y +
(double)lightRight.z * (double)drawOrigin.z;
const double oy = (double)lightUp.x * (double)drawOrigin.x + (double)lightUp.y * (double)drawOrigin.y +
(double)lightUp.z * (double)drawOrigin.z;
const double step = (double)texelWorld;
const double ax = ox + (double)b3Dot( lightRight, center );
const double ay = oy + (double)b3Dot( lightUp, center );
center = b3MulAdd( center, (float)( round( ax / step ) * step - ax ), lightRight );
center = b3MulAdd( center, (float)( round( ay / step ) * step - ay ), lightUp );
// Place the light eye behind the sphere along +sun. Far clip extends
// past the sphere's back face. Near clip pulls forward by
// CASTER_MARGIN_M to admit casters above the slice.
const b3Vec3 eyeWorld = b3MulAdd( center, radius + CASTER_MARGIN_M, dirToSun );
const Mat4 lightView = MakeLookAt( eyeWorld, center, up );
const Mat4 lightProj = MakeOrthographic( -radius, radius, -radius, radius, 0.0f, 2.0f * radius + CASTER_MARGIN_M );
Mat4 lightVP = MulMM4( lightProj, lightView );
// Texel-snap stabilization. Transform the sphere center through the
// unsnapped lightVP. Project to texel coords, round, convert the
// delta back to clip space, and add as a post-translation.
const Vec4 centerClip = MulMV4( lightVP, MakeVec4( center.x, center.y, center.z, 1.0f ) );
const float halfRes = (float)SHADOW_RESOLUTION * 0.5f;
const float texX = centerClip.x * halfRes;
const float texY = centerClip.y * halfRes;
const float dx = ( roundf( texX ) - texX ) / halfRes;
const float dy = ( roundf( texY ) - texY ) / halfRes;
Mat4 snapMat = MakeIdentity();
snapMat.cw.x = dx;
snapMat.cw.y = dy;
return MulMM4( snapMat, lightVP );
*radiusOut = radius;
return MulMM4( lightProj, lightView );
}
void InitShadows( void )
@ -184,12 +229,15 @@ void InitShadows( void )
s_shadow.sunDir = b3Normalize( (b3Vec3){ 0.5f, 0.8f, 0.4f } );
s_shadow.splitNear = SHADOW_SPLIT_NEAR;
s_shadow.splitFar = SHADOW_SPLIT_FAR;
s_shadow.splitLambda = SplitLambdaForRange( s_shadow.splitNear, s_shadow.splitFar );
s_shadow.splitLambda = PSSM_LAMBDA;
// Sane ratios if a getter runs before the first FitShadows
// The lit shaders divide by the texel size to scale the filter against
// cascade zero, so leaving these zero until the first FitShadows would
// render a frame of NaN. This is what a unit cascade radius works out to,
// which makes every ratio one.
for ( int i = 0; i < SHADOW_CASCADE_COUNT; ++i )
{
s_shadow.cascadeRadius[i] = 1.0f;
s_shadow.cascadeTexelWorld[i] = 2.0f / (float)SHADOW_RESOLUTION;
}
sg_image_desc desc = { 0 };
@ -228,13 +276,22 @@ void InitShadows( void )
// the receiver's reference depth is <= the stored depth, i.e., the
// receiver is the closest surface to the light. Linear PCF: each
// texture call returns a 2x2 weighted compare-result mix.
//
// White border means taps past a cascade edge compare against the far
// plane and come back lit, which dissolves the boundary across the
// filter kernel. That is what lets the lit shaders drop their hard
// bounds test, and the hard test is what used to flip whole pixels
// between sampled and lit as the texel snap stepped the map. Clamping
// to edge instead would smear the border texel outward and streak
// shadows across everything past the cascade.
sg_sampler_desc sdesc = { 0 };
sdesc.min_filter = SG_FILTER_LINEAR;
sdesc.mag_filter = SG_FILTER_LINEAR;
sdesc.mipmap_filter = SG_FILTER_NEAREST;
sdesc.wrap_u = SG_WRAP_CLAMP_TO_EDGE;
sdesc.wrap_v = SG_WRAP_CLAMP_TO_EDGE;
sdesc.wrap_u = SG_WRAP_CLAMP_TO_BORDER;
sdesc.wrap_v = SG_WRAP_CLAMP_TO_BORDER;
sdesc.wrap_w = SG_WRAP_CLAMP_TO_EDGE;
sdesc.border_color = SG_BORDERCOLOR_OPAQUE_WHITE;
sdesc.compare = SG_COMPAREFUNC_LESS_EQUAL;
sdesc.label = "shadow_compare_sampler";
s_shadow.sampler = sg_make_sampler( &sdesc );
@ -264,7 +321,6 @@ void SetShadowSplits( float nearViewZ, float farViewZ )
s_shadow.splitNear = nearViewZ;
s_shadow.splitFar = farViewZ;
s_shadow.splitLambda = SplitLambdaForRange( nearViewZ, farViewZ );
}
void SetShadowSplitFar( float farViewZ )
@ -272,6 +328,26 @@ void SetShadowSplitFar( float farViewZ )
SetShadowSplits( s_shadow.splitNear, farViewZ );
}
float GetShadowSplitNear( void )
{
return s_shadow.splitNear;
}
float GetShadowSplitFar( void )
{
return s_shadow.splitFar;
}
void SetShadowSplitLambda( float lambda )
{
s_shadow.splitLambda = b3ClampFloat( lambda, 0.0f, 1.0f );
}
float GetShadowSplitLambda( void )
{
return s_shadow.splitLambda;
}
void SetShadowSunDir( b3Vec3 dirToSun )
{
const float lenSq = dirToSun.x * dirToSun.x + dirToSun.y * dirToSun.y + dirToSun.z * dirToSun.z;
@ -291,13 +367,65 @@ void FitShadows( const Mat4* viewInv, const Mat4* proj )
splits[i] = ComputeSplitDistance( i, SHADOW_CASCADE_COUNT, s_shadow.splitNear, s_shadow.splitFar );
}
float tanHalfFovY, aspect;
PerspectiveShape( proj, &tanHalfFovY, &aspect );
for ( int i = 0; i < SHADOW_CASCADE_COUNT; ++i )
{
s_shadow.cascadeMatrices[i] = FitCascade( viewInv, proj, s_shadow.sunDir, splits[i], splits[i + 1], &s_shadow.cascadeRadius[i] );
float radius = 0.0f;
s_shadow.cascadeMatrices[i] =
FitCascade( viewInv, tanHalfFovY, aspect, s_shadow.sunDir, splits[i], splits[i + 1], &radius );
s_shadow.cascadeFarViewZ[i] = splits[i + 1];
// The ortho half-extent is the sphere radius, so the map covers
// 2 * radius of world across its resolution.
const float texelWorld = 2.0f * radius / (float)SHADOW_RESOLUTION;
s_shadow.cascadeTexelWorld[i] = texelWorld;
// Shadow clip-Z spans the whole orthographic depth range, and the
// caster margin inflates that range without covering any more
// receiver. Sizing the bias in world units here decouples it, so
// the margin costs caster headroom and nothing else.
const float depthRange = 2.0f * radius + CASTER_MARGIN_M;
s_shadow.cascadeDepthBias[i] = ( DEPTH_BIAS_TEXELS * texelWorld ) / depthRange;
}
}
void GetShadowCasterBounds( const Mat4* viewInv, const Mat4* projInv, b3Vec3* loOut, b3Vec3* hiOut )
{
float tanHalfFovY, aspect;
PerspectiveShapeFromInverse( projInv, &tanHalfFovY, &aspect );
b3Vec3 lo = { FLT_MAX, FLT_MAX, FLT_MAX };
b3Vec3 hi = { -FLT_MAX, -FLT_MAX, -FLT_MAX };
for ( int i = 0; i < SHADOW_CASCADE_COUNT; ++i )
{
const float nearZ = ComputeSplitDistance( i, SHADOW_CASCADE_COUNT, s_shadow.splitNear, s_shadow.splitFar );
const float farZ = ComputeSplitDistance( i + 1, SHADOW_CASCADE_COUNT, s_shadow.splitNear, s_shadow.splitFar );
b3Vec3 center;
float radius;
SliceBoundingSphere( viewInv, tanHalfFovY, aspect, nearZ, farZ, &center, &radius );
// A caster can only darken a receiver in this sphere if it sits
// between the two, so sweep the sphere toward the sun rather than
// growing it in every direction. Sweeping by the caster margin
// lands the front face exactly on the cascade's near plane.
const b3Vec3 swept = b3MulAdd( center, CASTER_MARGIN_M, s_shadow.sunDir );
lo.x = b3MinFloat( lo.x, b3MinFloat( center.x, swept.x ) - radius );
lo.y = b3MinFloat( lo.y, b3MinFloat( center.y, swept.y ) - radius );
lo.z = b3MinFloat( lo.z, b3MinFloat( center.z, swept.z ) - radius );
hi.x = b3MaxFloat( hi.x, b3MaxFloat( center.x, swept.x ) + radius );
hi.y = b3MaxFloat( hi.y, b3MaxFloat( center.y, swept.y ) + radius );
hi.z = b3MaxFloat( hi.z, b3MaxFloat( center.z, swept.z ) + radius );
}
*loOut = lo;
*hiOut = hi;
}
void BeginShadowPass( int cascade )
{
if ( cascade < 0 || cascade >= SHADOW_CASCADE_COUNT )
@ -342,18 +470,22 @@ float GetCascadeFarViewZ( int cascade )
return s_shadow.cascadeFarViewZ[cascade];
}
float GetCascadePcfScale( int cascade )
float GetCascadeTexelWorld( int cascade )
{
if ( cascade < 0 || cascade >= SHADOW_CASCADE_COUNT )
{
return 1.0f;
return 0.0f;
}
// Texel world size is proportional to the cascade's ortho half-extent,
// so the radius ratio is the texel-size ratio. The floor keeps the
// shrunken kernel at least ~2 texels wide so bilinear smoothing still
// gets some support in the far cascades.
const float scale = s_shadow.cascadeRadius[0] / s_shadow.cascadeRadius[cascade];
return b3ClampFloat( scale, 0.25f, 1.0f );
return s_shadow.cascadeTexelWorld[cascade];
}
float GetCascadeDepthBias( int cascade )
{
if ( cascade < 0 || cascade >= SHADOW_CASCADE_COUNT )
{
return 0.0f;
}
return s_shadow.cascadeDepthBias[cascade];
}
sg_view GetShadowSampleView( void )

View file

@ -42,13 +42,41 @@ extern "C"
{
#endif
#define SHADOW_CASCADE_COUNT 3
// Must match SHADOW_CASCADE_COUNT in shaders/common/shadow_cascade.glsl,
// which the renderer static asserts against the generated uniform layout.
// Changing it needs a shader regen (BOX3D_BUILD_SHADERS=ON) to reach the
// committed headers. Four is the ceiling: per-cascade values ride in vec4
// lanes and a fifth would need a second vec4 for each of them.
//
// More cascades cannot sharpen the last one. It always has to reach the far
// split, so its texel is pinned near 2 * k * far / resolution with k set by
// the field of view. What they buy is a finer near cascade and a smaller
// step at each boundary, both at the cost of another shadow pass.
#define SHADOW_CASCADE_COUNT 4
#define SHADOW_RESOLUTION 4096
// Default cascade far split, view-space distance from the camera. Scenes
// smaller than this keep the default range, larger ones widen it.
// Default cascade split range, view-space distance from the camera. Scenes
// smaller than the far end keep the default range, larger ones widen it.
//
// The near end sits nowhere near the camera near plane on purpose. It says
// where the split distribution starts, not where shadows start: the first
// cascade's bounding sphere reaches back past the eye whatever this is, so
// close content is covered either way. Starting out at working distance is
// what puts the whole volume being looked at inside the first cascade,
// rather than spending it on the metre in front of the lens and leaving two
// boundaries sitting in the middle of the scene. The cost is a first cascade
// stretched to reach that far, so it trades sharpness for uniformity.
#define SHADOW_SPLIT_NEAR 10.0f
#define SHADOW_SPLIT_FAR 50.0f
// Ceiling on that widening. The last cascade always has to reach the far
// split, so its texel size is set by this number alone and nothing else
// in the fit affects it. Letting a scene push it out coarsens the far
// cascade until its shadows read as blocks, and widens the step from the
// cascade before it. A scene that genuinely needs more reach should ask
// for it rather than have it inferred from how big its ground is.
#define SHADOW_SPLIT_FAR_MAX 80.0f
void InitShadows( void );
void ShutdownShadows( void );
@ -56,15 +84,26 @@ void ShutdownShadows( void );
void SetShadowSunDir( b3Vec3 dirToSun );
// Override the view-space distance range PSSM splits over. Defaults to
// (0.1, SHADOW_SPLIT_FAR), sufficient for the reference scenes but too short
// for larger ones. The split blend is derived from the range, so a wider far
// keeps the near cascade tight. Pass (0, 0) to restore defaults.
// (SHADOW_SPLIT_NEAR, SHADOW_SPLIT_FAR), sufficient for the reference scenes
// but wrong for a scene watched from far off, where the near end wastes whole
// cascades on the empty space in front of the camera. Pass (0, 0) to restore
// defaults.
void SetShadowSplits( float nearViewZ, float farViewZ );
// Fit the cascade far split to a scene of this view-space depth, keeping the
// current near and recomputing the split blend.
// current near.
void SetShadowSplitFar( float farViewZ );
float GetShadowSplitNear( void );
float GetShadowSplitFar( void );
// Blend between the two PSSM split schemes. 0 puts every boundary at an
// equal slice of distance, 1 at an equal multiplicative step. Raising it
// tightens the near cascades at the cost of dragging every boundary toward
// the camera, so the coarse far cascade takes over sooner.
void SetShadowSplitLambda( float lambda );
float GetShadowSplitLambda( void );
// Recompute per-cascade light-space matrices and split distances for the
// camera frustum described by viewInv + proj. viewInv (the camera's world
// matrix) supplies eye + basis directly, so the slice-corner walk does no
@ -73,6 +112,18 @@ void SetShadowSplitFar( float farViewZ );
// boundaries to avoid swimming edges as the camera moves.
void FitShadows( const Mat4* viewInv, const Mat4* proj );
// World-space AABB enclosing every shape that can cast into the cascades:
// each slice's bounding sphere swept toward the sun by the caster margin.
// It reaches well outside the camera frustum, which is the point. A host
// culling its draw submission to the visible volume drops casters that
// belong in the shadow map, and their shadows vanish.
//
// Derived from the camera alone, so it can be queried before FitShadows
// runs for the frame. Takes projInv because that is what the draw path
// already carries. Bounds come back in the same frame viewInv maps into,
// so a caller working against a shifted draw origin must offset them.
void GetShadowCasterBounds( const Mat4* viewInv, const Mat4* projInv, b3Vec3* loOut, b3Vec3* hiOut );
// Begin / end the depth-only render pass for a cascade. Bind this as
// the surrounding pass before issuing caster draws into the cascade.
void BeginShadowPass( int cascade );
@ -87,12 +138,19 @@ Mat4 GetCascadeMatrix( int cascade );
// these to pick which cascade to sample.
float GetCascadeFarViewZ( int cascade );
// PCF tap-offset multiplier for a cascade, in (0, 1]. The kernel is
// authored in texels of cascade 0, farther cascades cover more world per
// texel, so their tap offsets shrink by the texel-size ratio. This keeps
// the penumbra a constant world width, without it the shadow edge blur
// visibly jumps at every cascade boundary.
float GetCascadePcfScale( int cascade );
// One shadow texel measured in world length units for a cascade. Lit
// shaders scale the normal offset by this so every cascade biases by the
// same visual amount regardless of how much world it covers. The ratio
// against cascade 0 also shrinks the PCF kernel in the coarser cascades,
// which keeps the penumbra a constant world width instead of jumping at
// every cascade boundary.
float GetCascadeTexelWorld( int cascade );
// Residual comparison bias for a cascade, in shadow clip-Z units. The
// normal offset carries the slope term, this only has to cover depth
// quantization. Sized on the CPU because shadow clip-Z spans the whole
// orthographic range, which differs per cascade.
float GetCascadeDepthBias( int cascade );
// Bound by lit pipelines once for sampling across all cascades. The view
// is the depth array's full-array sampling view. Per-cascade selection
@ -100,8 +158,8 @@ float GetCascadePcfScale( int cascade );
sg_view GetShadowSampleView( void );
sg_sampler GetShadowSampler( void );
// One-texel size in shadow space (1 / SHADOW_RESOLUTION). Lit shaders
// use this to size PCF taps and slope-scale bias.
// One-texel size in shadow UV space (1 / SHADOW_RESOLUTION). Lit shaders
// use this to size PCF taps and the cascade-edge reject.
float GetShadowTexelSize( void );
#ifdef __cplusplus