Gorilla.Controller.Passes.CascadedShadows

Overview

This unit implements Gorilla3D's modern shadow system: Cascaded Shadow Maps (CSM) with support for directional, spot and point lights. Every shadow-casting light on a viewport is captured into a shared depth atlas before the main scene renders; the default material then samples that atlas (plus a per-light uniform buffer) to filter the shadow contribution of each fragment.

Unlike the other render passes you create manually, the cascaded shadow pass is an internal pass driven by the viewport. You enable and tune it through TGorillaViewport.Shadows — you do not normally construct TGorillaRenderPassCascadedShadows yourself.

This is the recommended shadow path. It supersedes the older smShadowMapping / smVSM material flags noted as incomplete in Materials → Shadow Mapping.

Enabling Shadows

// Turn the CSM system on and configure it
GorillaViewport1.Shadows.Enabled       := True;
GorillaViewport1.Shadows.CascadeCount  := 4;
GorillaViewport1.Shadows.MapResolution := 2048;
GorillaViewport1.Shadows.MaxDirLights  := 1;
GorillaViewport1.Shadows.Filter        := TGorillaShadowFilter.PCF3;

// Mark the lights that should cast shadows
MyDirLight.CastShadow := True;

Viewport.Shadows is a published TGorillaShadowSystemSettings instance owned by the viewport. The embedded pass automatically gathers every TGorillaLight with CastShadow := True, honouring the per-kind budgets.

Excluding objects from casting

The depth pass renders the whole scene into the shadow atlas, so by default every mesh casts a shadow. To stop a specific object from casting — typically a surface that sits between the light and the rest of the scene, such as a water plane or a transparent wall, which would otherwise shadow everything beneath it — set its CastShadows property to False:

WaterSurface.CastShadows := False;   // still visible & still receives shadows, but throws none

CastShadows (default True) is independent of Shadows (which controls whether the object receives shadows). The cascaded-shadow pass skips any TGorillaMesh with CastShadows = False via its IsControlIgnored override.

TGorillaShadowSystemSettings

The user-facing configuration object (Gorilla.Context.ShadowSettings).

Property Type Default Description
Enabled Boolean False Activates the embedded shadow pass on the viewport.
CascadeCount Integer 4 Cascade slices per directional light. Clamped to [1..GORILLA_SHADOW_MAX_CASCADES].
MapResolution Integer 2048 Shadow map side length in texels (per atlas layer).
Strength Single 1.0 Global shadow darkness multiplier [0..1], applied on top of every caster's per-light ShadowStrength. 1.0 = full, 0.0 = shadows off. This is the discoverable single knob for shadow darkness — see the note below.
CascadeSplitLambda Single 0.75 Blend between uniform (0) and logarithmic (1) cascade splits. Higher = more detail near the camera.
StabilizeCascades Boolean True Snap cascades to texel boundaries to suppress shimmering when the camera moves.
AutoFitCascades Boolean True Fit the directional cascade range to the scene's shadow-casting geometry instead of spreading it over the whole camera frustum. Keeps shadow-texel density high for small casters without a manual ShadowNearFar. Never widens past the camera frustum — see Cascade Fitting.
Filter TGorillaShadowFilter PCF3 Shadow softening kernel evaluated by the default material.
PointLightMethod TGorillaPointShadowMethod CubeMap Algorithm for omnidirectional point-light shadows.
MaxDirLights Integer 1 Directional lights allowed to cast shadows per frame.
MaxSpotLights Integer 0 Spot lights allowed to cast shadows per frame.
MaxPointLights Integer 0 Point lights allowed to cast shadows per frame.
Bias Single 0.0005 Global constant depth bias (fallback when a light has no override).
SlopeBias Single 0.001 Global slope-scaled depth bias (fallback).
NormalOffset Single 0.02 Global normal-offset bias in world units (fallback).
FrontFaceCulling Boolean True Render back-faces only into the atlas. Removes acne on rounded geometry but can cause Peter-Panning on thin meshes.
DebugAtlasLayer Integer -1 Diagnostic: -1 = normal; a non-negative atlas-layer index makes the material sample that layer's raw depth for visualisation.

Methods

function ComputeAtlasLayerCount() : Integer;

Returns the total atlas-layer budget: MaxDirLights × CascadeCount (directional) + MaxSpotLights × 1 (spot) + MaxPointLights × 6 (point cube faces).

TGorillaShadowFilter

TGorillaShadowFilter = (None, PCF3, PCF5, Poisson, PCSS);
Value Description
None Hard shadows — a single hardware-compared depth tap.
PCF3 3×3 percentage-closer filter (default).
PCF5 5×5 percentage-closer filter.
Poisson 12-tap Poisson-disk with rotation noise.
PCSS Percentage-Closer Soft Shadows (most expensive).

TGorillaPointShadowMethod

TGorillaPointShadowMethod = (CubeMap, DualParaboloid);

CubeMap (default) records six perspective faces; DualParaboloid uses two hemispheres as a fallback for restricted GPUs.

TGorillaShadowResolution

TGorillaShadowResolution = (Res512 = 512, Res1024 = 1024, Res2048 = 2048, Res4096 = 4096);

Shadow Darkness

Use Viewport.Shadows.Strength to control how dark cascaded shadows are:

GorillaViewport1.Shadows.Strength := 0.5;   // half-strength shadows

It is a [0..1] multiplier applied on top of each caster's per-light ShadowStrength, so the two compose (final darkness = light.ShadowStrength × Shadows.Strength). Per-light values let one caster be lighter than another; the global value is the single scene-wide dial.

Do not confuse this with Viewport.ShadowStrength (no Shadows. prefix). That legacy property only affects the Global Illumination pass and has no effect on cascaded shadow maps.

Note that the shadow only attenuates direct lighting — it does not darken the ambient / image-based-lighting term. In a bright skybox/IBL environment shadows therefore cannot get darker than the ambient floor allows, regardless of Strength.

Cascade Fitting

By default a directional light spreads its cascades across the whole camera frustum (camera near .. camera far). When the far plane sits well beyond the actual geometry — e.g. a small model (< 1 unit) in a scene with a large far plane — even the tightest cascade covers many world units, so a single shadow texel is larger than the caster and the shadow looks coarse or disappears.

Two mechanisms tighten the cascade depth band so the Practical Split Scheme concentrates texels where the geometry actually is. In increasing priority:

  1. Auto-fit (Shadows.AutoFitCascades, default True) — the eight corners of the viewport's SceneBounds are projected onto the camera view axis; the cascade band is clamped to that span (intersected with the camera frustum). It can only ever narrow the range, so it never reduces quality. Because SceneBounds is the union of all renderable geometry, large ground planes pull the far end out — for a tightly-cropped result on one small caster, prefer the manual override below.
  2. Manual override (TGorillaLight.ShadowNearFar) — set an explicit (near, far) to clamp the band yourself; each component > 0 wins over auto-fit. Ideal for a small caster the camera sits close to:
MyDirLight.ShadowNearFar := PointF(0.1, 8);   // crisp shadows in a tight depth band

Per-Light Shadow Properties (TGorillaLight)

Bias values default to the same numbers as the global settings, but each light may override them.

Property Type Default Description
CastShadow Boolean False Enables shadow casting; the pass picks the light up automatically when Viewport.Shadows.Enabled.
ShadowBias Single 0.0005 Constant depth bias during the shadow comparison.
ShadowSlopeBias Single 0.001 Slope-scaled bias, multiplied by (1 - dot(N, L)) to fight acne on grazing surfaces.
ShadowNormalOffset Single 0.02 Shifts the sample position along the surface normal (world units) to reduce self-shadowing.
ShadowStrength Single 1.0 Per-light shadow opacity [0..1]; 1.0 = fully opaque, 0.0 = no shadow. Multiplied by the global Shadows.Strength.
ShadowNearFar TPointF (0, 0) Shadow projection near/far override (X = near, Y = far); only components > 0 apply. Spot/point: (0, 0) auto-derives from attenuation. Directional: an explicit range clamps the cascade band (overrides auto-fit per component); (0, 0) keeps auto-fit / camera-frustum behaviour.

Core Classes

TGorillaRenderPassCascadedShadows

Inherits from: TGorillaRenderPassCustomDepth

Default pass id: 'CascadedShadows'. IsInternalRenderPass() returns True — the pass is driven manually by the composite renderer (DoRenderShadowMaps), not by the automatic Pre-pass loop.

Notable Public Members

Member Type Description
CurrentInstance class var The most recently constructed pass; lit materials locate the shadow pass through it without coupling to viewport ownership.
Settings TGorillaShadowSystemSettings Read-only — the bound settings instance.
Lights TGorillaShadowLightEntryList Read-only — per-light bookkeeping gathered this frame.
ActiveEntryIdx Integer Light entry currently selected for rendering.
ActiveCascade Integer Slice within the active entry (cascade, cube face, or 0).
procedure SetSettings(const ASettings : TGorillaShadowSystemSettings);
procedure PrepareFrame();
procedure SetActiveLightSlice(const AEntryIdx, ASliceIdx : Integer);
function  GetViewMatrix(const AContext : TContext3D) : TMatrix3D; override;
function  GetProjectionMatrix(const AContext : TContext3D) : TMatrix3D; override;
function  GetShaderData() : PGorillaCSMShaderData;
function  GetShaderDataSize() : Integer;

PrepareFrame() performs the per-frame snapshot (gather casters → allocate/resize atlas → rebuild the GPU UBO). The host renderer calls it once per frame; then it iterates each gathered light entry, walking 0..Entry.LayerCount-1 via SetActiveLightSlice and dispatching a depth render per slice.

Supporting Types

Type Purpose
TGorillaShadowLightKind slkDirectional, slkSpot, slkPoint.
TGorillaShadowLightEntry Per-light frame data: kind, atlas layer, per-slice LightSpace/View/Proj matrices, split depths, cube-face matrices.
TGorillaCSMLightGPU std140 mirror of the GLSL CSMLight struct.
TGorillaCSMShaderData std140 mirror of the GLSL uShadowBlock UBO, bound by the default material on every shader-program swap.
TGorillaCascadeFrustumCorners The eight world-space corners of a cascade sub-frustum.

Technical Details

  • Pass type: Pre-pass (TRenderPassType.Pre), internal — RenderListToFBO + ListRendering (inherited from TGorillaRenderPassCustomDepth).
  • Atlas texture: R32F (dtFloat), Linear filtering, WrapS/WrapT = ClampToBorder with a white border (1,1,1,1) so off-cascade reads resolve to "no occluder". The atlas is a Texture2DArray sized by ComputeAtlasLayerCount(); the depth target is cleared to FAR (1.0) each slice.
  • Cascade splits: Practical Split Scheme (Zhang et al. 2006) — a CascadeSplitLambda mix of logarithmic and uniform spacing. Directional cascades fit a stabilised bounding-sphere ortho per slice. The split range is the camera frustum, optionally narrowed by AutoFitCascades (scene-bounds fit) and/or a per-light ShadowNearFar override.
  • Spot lights: single perspective slice, FOV derived from SpotCutOff.
  • Point lights: six cube faces rendered with a 100° FOV (not 90°) to avoid silhouette collapse at face boundaries.
  • Bias defense: constant Bias + SlopeBias + NormalOffset combine against acne; FrontFaceCulling trades acne for potential Peter-Panning.
  • Constants (Gorilla.Context.ShadowSettings): GORILLA_SHADOW_MAX_CASCADES = 4, GORILLA_SHADOW_MAX_LIGHTS = 16, GORILLA_SHADOW_LIGHTSPACE_SLOTS = 6.

See Also