| 1 |
{ |
| 2 |
Copyright 2010-2024 Michalis Kamburelis. |
| 3 |
|
| 4 |
This file is part of "Castle Game Engine". |
| 5 |
|
| 6 |
"Castle Game Engine" is free software; see the file COPYING.txt, |
| 7 |
included in this distribution, for details about the copyright. |
| 8 |
|
| 9 |
"Castle Game Engine" is distributed in the hope that it will be useful, |
| 10 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 12 |
|
| 13 |
---------------------------------------------------------------------------- |
| 14 |
} |
| 15 |
|
| 16 |
{ Shadow maps internal utilities. } |
| 17 |
unit CastleInternalShadowMaps; |
| 18 |
|
| 19 |
{$I castleconf.inc} |
| 20 |
|
| 21 |
interface |
| 22 |
|
| 23 |
uses X3DNodes, CastleShapes; |
| 24 |
|
| 25 |
{ Automatically handle X3D "receiveShadows" field |
| 26 |
by inserting appropriate lower-level nodes. |
| 27 |
|
| 28 |
If Enable is @true, the appropriate lower-level nodes are added, |
| 29 |
or replaced (if they already existed, because you call |
| 30 |
ProcessShadowMapsReceivers again). |
| 31 |
If Enable is @false, the appropriate nodes (added by previous calls to |
| 32 |
ProcessShadowMapsReceivers) will be removed instead. |
| 33 |
|
| 34 |
This adds/removes by changing the TShape.InternalShadowMaps, |
| 35 |
nothing more (it does not modify textures in Appearance.textures, |
| 36 |
or any texture coordinates). } |
| 37 |
procedure ProcessShadowMapsReceivers(Model: TX3DNode; Shapes: TShapeTree; |
| 38 |
const Enable: boolean; |
| 39 |
const DefaultShadowMapSize: Cardinal); |
| 40 |
|
| 41 |
implementation |
| 42 |
|
| 43 |
uses SysUtils, Generics.Collections, |
| 44 |
CastleUtils, CastleStringUtils, CastleImages, |
| 45 |
CastleBoxes, CastleLog, CastleVectors, CastleRectangles; |
| 46 |
|
| 47 |
type |
| 48 |
{ Information about light source relevant for shadow maps. } |
| 49 |
TLight = record |
| 50 |
Light: TAbstractPunctualLightNode; |
| 51 |
ShadowMap: TGeneratedShadowMapNode; |
| 52 |
ShadowReceiversBox: TBox3D; |
| 53 |
end; |
| 54 |
PLight = ^TLight; |
| 55 |
|
| 56 |
TLightList = class({$ifdef FPC}specialize{$endif} TStructList<TLight>) |
| 57 |
public |
| 58 |
DefaultShadowMapSize: Cardinal; |
| 59 |
ShadowCastersBox: TBox3D; |
| 60 |
LightsCastingOnEverything: TX3DNodeList; |
| 61 |
|
| 62 |
{ Find existing or add new TLight record for this light node. |
| 63 |
This also creates shadow map for this light. } |
| 64 |
function FindLight(Light: TAbstractPunctualLightNode): PLight; |
| 65 |
|
| 66 |
procedure ShapeRemove(const Shape: TShape); |
| 67 |
procedure ShapeAdd(const Shape: TShape); |
| 68 |
|
| 69 |
{ Finish calculating light's projectionXxx parameters, |
| 70 |
and assign them to the light node. } |
| 71 |
procedure HandleLightAutomaticProjection(const Light: TLight); |
| 72 |
|
| 73 |
{ Add light node to LightsCastingOnEverything, if shadows=TRUE. } |
| 74 |
procedure HandleLightCastingOnEverything(Node: TX3DNode); |
| 75 |
end; |
| 76 |
|
| 77 |
function TLightList.FindLight(Light: TAbstractPunctualLightNode): PLight; |
| 78 |
var |
| 79 |
I: Integer; |
| 80 |
LightUniqueName: string; |
| 81 |
begin |
| 82 |
for I := 0 to Count - 1 do |
| 83 |
if L[I].Light = Light then |
| 84 |
Exit(PLight(Ptr(I))); |
| 85 |
|
| 86 |
{ add a new TLight record } |
| 87 |
Result := PLight(Add); |
| 88 |
Result^.Light := Light; |
| 89 |
Result^.ShadowReceiversBox := TBox3D.Empty; |
| 90 |
|
| 91 |
{ Assign unique nodenames to the created ShadowMap and TexGen nodes, |
| 92 |
this way when saving they will be shared by DEF/USE. |
| 93 |
Based on LightUniqueName. } |
| 94 |
LightUniqueName := Light.X3DName; |
| 95 |
if LightUniqueName = '' then |
| 96 |
LightUniqueName := 'Light' + IntToStr(Random(1000000)); |
| 97 |
|
| 98 |
{ create new (or use existing) GeneratedShadowMap node } |
| 99 |
|
| 100 |
if (Light.FdDefaultShadowMap.Value <> nil) and |
| 101 |
(Light.FdDefaultShadowMap.Value is TGeneratedShadowMapNode) then |
| 102 |
begin |
| 103 |
Result^.ShadowMap := TGeneratedShadowMapNode(Light.FdDefaultShadowMap.Value); |
| 104 |
end else |
| 105 |
begin |
| 106 |
Result^.ShadowMap := TGeneratedShadowMapNode.Create; |
| 107 |
{ Allows castle-model-viewer lights editor to easily configure this node. } |
| 108 |
Light.FdDefaultShadowMap.Value := Result^.ShadowMap; |
| 109 |
Result^.ShadowMap.Update := upAlways; |
| 110 |
Result^.ShadowMap.Size := DefaultShadowMapSize; |
| 111 |
end; |
| 112 |
|
| 113 |
{ Regardless if this is taken from defaultShadowMap or created, |
| 114 |
always set "light" to our light. This way user doesn't have to |
| 115 |
specify defaultShadowMap.light is the same light. } |
| 116 |
Result^.ShadowMap.FdLight.Value := Light; |
| 117 |
end; |
| 118 |
|
| 119 |
{ If this shape was processed by some ShapeAdd previously, |
| 120 |
make Shape.InternalShadowMaps empty. } |
| 121 |
procedure TLightList.ShapeRemove(const Shape: TShape); |
| 122 |
begin |
| 123 |
FreeAndNil(Shape.InternalShadowMaps); |
| 124 |
end; |
| 125 |
|
| 126 |
procedure TLightList.ShapeAdd(const Shape: TShape); |
| 127 |
|
| 128 |
{ Add given light to Shape. } |
| 129 |
procedure HandleLight(LightNode: TAbstractPunctualLightNode); |
| 130 |
var |
| 131 |
Light: PLight; |
| 132 |
begin |
| 133 |
// create Shape.InternalShadowMaps if necessary |
| 134 |
if Shape.InternalShadowMaps = nil then |
| 135 |
Shape.InternalShadowMaps := TX3DNodeList.Create(false); |
| 136 |
|
| 137 |
// add Light^.ShadowMap to Shape.InternalShadowMaps |
| 138 |
Light := FindLight(LightNode); |
| 139 |
if Shape.InternalShadowMaps.IndexOf(Light^.ShadowMap) = -1 then |
| 140 |
Shape.InternalShadowMaps.Add(Light^.ShadowMap); |
| 141 |
|
| 142 |
Light^.ShadowReceiversBox.Include(Shape.BoundingBox); |
| 143 |
end; |
| 144 |
|
| 145 |
{ Account for the fact Shape casts shadows. } |
| 146 |
procedure HandleShadowCaster; |
| 147 |
begin |
| 148 |
ShadowCastersBox.Include(Shape.BoundingBox); |
| 149 |
end; |
| 150 |
|
| 151 |
var |
| 152 |
I: Integer; |
| 153 |
App: TAppearanceNode; |
| 154 |
begin |
| 155 |
{ Handle VRML 1.0 nodes, without TShapeNode, early. |
| 156 |
They cannot be shadow maps receivers, but they can be shadow casters. } |
| 157 |
if Shape.Node = nil then |
| 158 |
begin |
| 159 |
HandleShadowCaster; |
| 160 |
Exit; { VRML <= 1.0 shapes } |
| 161 |
end; |
| 162 |
|
| 163 |
App := Shape.Node.Appearance; |
| 164 |
if (App = nil) or App.ShadowCaster then |
| 165 |
HandleShadowCaster; |
| 166 |
|
| 167 |
// handle Appearance.receiveShadows |
| 168 |
if App <> nil then |
| 169 |
begin |
| 170 |
for I := 0 to App.FdReceiveShadows.Count - 1 do |
| 171 |
if App.FdReceiveShadows[I] is TAbstractPunctualLightNode then |
| 172 |
HandleLight(TAbstractPunctualLightNode(App.FdReceiveShadows[I])); |
| 173 |
end; |
| 174 |
|
| 175 |
// add receiving shadows implied by shadows=TRUE on light sources |
| 176 |
for I := 0 to LightsCastingOnEverything.Count - 1 do |
| 177 |
HandleLight(TAbstractPunctualLightNode(LightsCastingOnEverything[I])); |
| 178 |
end; |
| 179 |
|
| 180 |
procedure TLightList.HandleLightAutomaticProjection(const Light: TLight); |
| 181 |
|
| 182 |
{ Auto-calculate projection near and far, knowing that light's |
| 183 |
projection location and direction are set now. } |
| 184 |
procedure AutoCalculateProjectionNearFar; |
| 185 |
var |
| 186 |
ProjectionNear, ProjectionFar: Single; |
| 187 |
MinReceiverDistance, MaxReceiverDistance: Single; |
| 188 |
begin |
| 189 |
if ShadowCastersBox.IsEmpty then |
| 190 |
begin |
| 191 |
{ No shadow casters? So any sensible values are fine. } |
| 192 |
ProjectionNear := 0.1; |
| 193 |
ProjectionFar := 1; |
| 194 |
end else |
| 195 |
begin |
| 196 |
{ Projection near/far must include all shadow casters between |
| 197 |
light source and the shadow receivers. } |
| 198 |
Light.Light.Box3DDistances(ShadowCastersBox, ProjectionNear, ProjectionFar); |
| 199 |
Light.Light.Box3DDistances(Light.ShadowReceiversBox, MinReceiverDistance, MaxReceiverDistance); |
| 200 |
// MinReceiverDistance is ignored |
| 201 |
|
| 202 |
MaxVar(ProjectionNear, 0); |
| 203 |
MinVar(ProjectionFar, MaxReceiverDistance); |
| 204 |
|
| 205 |
if ProjectionNear > ProjectionFar then |
| 206 |
begin |
| 207 |
{ No shadow casters that can cast shadows on our shadow receivers? |
| 208 |
So any sensible values are fine. } |
| 209 |
ProjectionNear := 0.1; |
| 210 |
ProjectionFar := 1; |
| 211 |
end else |
| 212 |
begin |
| 213 |
{ So we know now that ProjectionNear >= 0 and |
| 214 |
ProjectionFar >= ProjectionNear. } |
| 215 |
|
| 216 |
{ final correction of auto-calculated projectionFar: must be > 0 } |
| 217 |
if ProjectionFar <= 0 then |
| 218 |
ProjectionFar := 1; |
| 219 |
|
| 220 |
{ Make ProjectionFar larger and ProjectionNear smaller, since |
| 221 |
1. At the beginning of the projection range |
| 222 |
the depth texture has the best precision. |
| 223 |
2. The range should be slightly larger than ShadowCastersBox anyway, |
| 224 |
to be sure to capture shadow casters exactly at the begin/end |
| 225 |
of projection range (like a box side exactly at the beginning |
| 226 |
of ShadowCastersBox range in demo_models/shadow_spot_simple.wrl). } |
| 227 |
ProjectionFar := ProjectionFar * 2.0; |
| 228 |
ProjectionNear := ProjectionNear / 2.0; |
| 229 |
|
| 230 |
{ final correction of auto-calculated projectionNear: must be > 0, |
| 231 |
and preferably > some epsilon of projectionFar (to avoid depth |
| 232 |
precision problems). } |
| 233 |
MaxVar(ProjectionNear, ProjectionFar * 0.001); |
| 234 |
end; |
| 235 |
end; |
| 236 |
|
| 237 |
WritelnLog('Shadow Maps', Format('Auto-calculated light source "%s" projectionNear is %f, projectionFar is %f', |
| 238 |
[Light.Light.NiceName, ProjectionNear, ProjectionFar])); |
| 239 |
|
| 240 |
{ Set light node's projectionXxx values, if they are needed. } |
| 241 |
if Light.Light.FdProjectionNear.Value = 0 then |
| 242 |
Light.Light.FdProjectionNear.Value := ProjectionNear; |
| 243 |
if Light.Light.FdProjectionFar.Value = 0 then |
| 244 |
Light.Light.FdProjectionFar.Value := ProjectionFar; |
| 245 |
end; |
| 246 |
|
| 247 |
procedure AutoCalculateProjectionForDirectionalLight( |
| 248 |
const LightNode: TDirectionalLightNode); |
| 249 |
var |
| 250 |
Pos, Dir, Side, Up, MinCorner, MaxCorner: TVector3; |
| 251 |
ProjectionLocation: TVector3; |
| 252 |
ProjectionRectangle: TFloatRectangle; |
| 253 |
begin |
| 254 |
if LightNode.FdProjectionRectangle.Value.IsPerfectlyZero and |
| 255 |
(not ShadowCastersBox.IsEmpty) then |
| 256 |
begin |
| 257 |
LightNode.GetView(Pos, Dir, Side, Up); |
| 258 |
MinCorner := ShadowCastersBox.MinimumCorner(LightNode.ProjectionWorldDirection); |
| 259 |
MaxCorner := ShadowCastersBox.MaximumCorner(LightNode.ProjectionWorldDirection); |
| 260 |
{ do not place ProjectionLocation exactly at MinCorner, it would be too close |
| 261 |
to ShadowCastersBox, forcing projectionNear always almost zero. } |
| 262 |
ProjectionLocation := |
| 263 |
//MinCorner - (MaxCorner - MinCorner) |
| 264 |
MinCorner * 2 - MaxCorner; // same thing |
| 265 |
ProjectionRectangle := ShadowCastersBox.OrthoProject( |
| 266 |
ProjectionLocation, Dir, Side, Up); |
| 267 |
LightNode.FdProjectionRectangle.Value := ProjectionRectangle.ToX3DVector; |
| 268 |
LightNode.FdProjectionLocation.Value := |
| 269 |
LightNode.InverseTransform.MultPoint(ProjectionLocation); |
| 270 |
|
| 271 |
WritelnLog('Shadow Maps', Format('Auto-calculated directional light source "%s" projectionLocation as %s, projectionRectangle as %s', |
| 272 |
[Light.Light.NiceName, |
| 273 |
ProjectionLocation.ToString, |
| 274 |
ProjectionRectangle.ToString])); |
| 275 |
end; |
| 276 |
end; |
| 277 |
|
| 278 |
begin |
| 279 |
{ calculate projectionLocation/Rectangle first, |
| 280 |
since projectionLocation determines the right range for projectionNear/Far } |
| 281 |
if Light.Light is TDirectionalLightNode then |
| 282 |
AutoCalculateProjectionForDirectionalLight( |
| 283 |
TDirectionalLightNode(Light.Light)); |
| 284 |
AutoCalculateProjectionNearFar; |
| 285 |
end; |
| 286 |
|
| 287 |
procedure TLightList.HandleLightCastingOnEverything(Node: TX3DNode); |
| 288 |
begin |
| 289 |
if TAbstractPunctualLightNode(Node).Shadows then |
| 290 |
LightsCastingOnEverything.Add(Node); |
| 291 |
end; |
| 292 |
|
| 293 |
procedure ProcessShadowMapsReceivers(Model: TX3DNode; Shapes: TShapeTree; |
| 294 |
const Enable: boolean; |
| 295 |
const DefaultShadowMapSize: Cardinal); |
| 296 |
var |
| 297 |
Lights: TLightList; |
| 298 |
L: PLight; |
| 299 |
I: Integer; |
| 300 |
begin |
| 301 |
{ This is valid situation (TCastleSceneCore.RootNode may be nil). |
| 302 |
Nothing to do then. } |
| 303 |
if Model = nil then Exit; |
| 304 |
|
| 305 |
Lights := TLightList.Create; |
| 306 |
try |
| 307 |
{ Shapes.Traverse here enumerate all (active and not) shapes. |
| 308 |
In case a shape is not active, it may become active later |
| 309 |
(e.g. by Switch.whichChoice change), and ProcessShadowMapsReceivers |
| 310 |
will not necessarily be run again. So we better account for this |
| 311 |
shape already. } |
| 312 |
|
| 313 |
{ We first remove all old GeneratedShadowMap |
| 314 |
nodes, in one Shapes.Traverse run. Then, if Enable, |
| 315 |
we make another Shapes.Traverse run and only add necessary nodes. |
| 316 |
|
| 317 |
Previously I tried to do both (removal and addition) at the same time, |
| 318 |
but this was just too error-prone. Notice that multiple shapes may refer |
| 319 |
to the same light node. And shapes may have multiple GeneratedShadowMap, |
| 320 |
if they receive shadow from more then one light. So it was too easy |
| 321 |
to remove a shadow map (or projector) that we have just added... } |
| 322 |
Shapes.Traverse({$ifdef FPC}@{$endif} Lights.ShapeRemove, false); |
| 323 |
|
| 324 |
if Enable then |
| 325 |
begin |
| 326 |
Lights.DefaultShadowMapSize := DefaultShadowMapSize; |
| 327 |
Lights.ShadowCastersBox := TBox3D.Empty; |
| 328 |
|
| 329 |
{ calculate Lights.LightsCastingOnEverything first } |
| 330 |
Lights.LightsCastingOnEverything := TX3DNodeList.Create(false); |
| 331 |
Model.EnumerateNodes(TAbstractPunctualLightNode, |
| 332 |
{$ifdef FPC}@{$endif}Lights.HandleLightCastingOnEverything, |
| 333 |
false); |
| 334 |
|
| 335 |
Shapes.Traverse({$ifdef FPC}@{$endif} Lights.ShapeAdd, false); |
| 336 |
|
| 337 |
for I := 0 to Lights.Count - 1 do |
| 338 |
begin |
| 339 |
L := PLight(Lights.Ptr(I)); |
| 340 |
|
| 341 |
Lights.HandleLightAutomaticProjection(L^); |
| 342 |
|
| 343 |
{ Although we try to construct things only when they will be actually |
| 344 |
used (so no unused nodes should remain now for free), actually |
| 345 |
there is a chance something remained unused if HandleLight failed |
| 346 |
with WritelnWarning after FindLight. } |
| 347 |
L^.ShadowMap.FreeIfUnused; |
| 348 |
L^.ShadowMap := nil; |
| 349 |
end; |
| 350 |
|
| 351 |
FreeAndNil(Lights.LightsCastingOnEverything); |
| 352 |
end; |
| 353 |
finally FreeAndNil(Lights) end; |
| 354 |
end; |
| 355 |
|
| 356 |
end. |