Debian Codegraph @

src/scene/castleshapeinternalrendershadowvolumes.pas

raw
1 {
2 Copyright 2003-2023 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 { Internal functions for rendering shadow volumes of shapes. }
16 unit CastleShapeInternalRenderShadowVolumes;
17
18 {$I castleconf.inc}
19
20 interface
21
22 uses CastleVectors, CastleShapeInternalShadowVolumes,
23 CastleTriangles, CastleTransform, CastleRenderPrimitives;
24
25 type
26 TRenderShapeShadowVolumes = class helper for TShapeShadowVolumes
27 { Rendering shadow volumes with silhouette optimization.
28
29 This renders shadow quads of silhouette edge. Edges from ManifoldEdges
30 list are used to find silhouette edge. Additionally edges from
31 BorderEdges always produce shadow quads, i.e. we treat them
32 like they would always be silhouette edges.
33
34 The very idea of this optimization is that most edges are in
35 ManifoldEdges and so only real silhouette edges produce shadow quads.
36 In other words, BorderEdges list should not contain too many items.
37 When BorderEdges contains all edges (ManifoldEdges is empty), then
38 this method degenerates to a naive rendering without silhouette
39 optimization. So you should try to make your models as much as
40 possible resembling nice 2-manifolds. Ideally, if your mesh
41 is a number of perfectly closed manifolds, and vertex ordering
42 is consistent, then BorderEdges is empty, and this works perfect.
43
44 Usually, most models are mostly 2-manifold (only the real border
45 edges are, well, in BorderEdges), and this works great.
46 See "VRML engine documentation" on
47 [https://castle-engine.io/engine_doc.php],
48 chapter "Shadows", for description and pictures of possible artifacts
49 when trying to use this on models that are not 2-manifold.)
50
51 LightCap and DarkCap say whether you want to cap your shadow volume.
52 LightCap is the cap at the caster position, DarkCap is the cap in infinity.
53 This is needed by z-fail method, you should set them both to @true.
54 To be more optimal, you can request LightCap only if z-fail @italic(and
55 the caster is inside camera frustum). For directional lights, DarkCap is
56 ignored, since the volume is always closed by a single point in infinity.
57 }
58 procedure RenderSilhouetteShadowVolume(
59 const Params: TRenderParams;
60 const Mesh: TCastleRenderUnlitMesh;
61 const LightPos: TVector4;
62 const Transform: TMatrix4;
63 const LightCap, DarkCap: boolean;
64 const ForceOpaque, WholeSceneManifold: Boolean);
65 end;
66
67 implementation
68
69 uses SysUtils,
70 {$ifdef OpenGLES} CastleGLES, {$else} CastleGL, {$endif}
71 CastleGLUtils, CastleUtils, CastleShapes, CastleImages, CastleRenderContext;
72
73 { Return vertex Original extruded into infinity, as seen from light
74 at position LightPos.
75
76 This is designed to work only with LightPos[3] = 1. In the future, when
77 need arises, this may be improved to work with any LightPos[3] <> 0.
78
79 For LightPos[3] = 0, i.e. directional light,
80 don't use this, and there's no need to do it,
81 since then the extruded point is just LightPos (for any vertex).
82 RenderXxxShadowVolume want to treat it specially anyway (to optimize
83 drawing, since then quads degenerate to triangles).
84
85 Note: this cannot be moved to a local function inside
86 TCastleScene.RenderSilhouetteShadowVolume, as FPC 2.6.4 and 2.6.2 on Win32 (but not on Linux
87 i386) generates then bad code, the loop to ManifoldEdgesNow.Count doesn't finish OK,
88 the index goes beyond ManifoldEdgesNow.Count-1. }
89 function ExtrudeVertex(
90 const Original: TVector3;
91 const LightPos: TVector4): TVector4;
92 var
93 LightPos3: TVector3 absolute LightPos;
94 begin
95 { Below is the moment when we require that
96 if LightPos.W <> 0 then LightPos.W = 1 (not any other non-zero value).
97 Otherwise we would have to divide here LightPos3 by LightPos.W.
98 Maybe in the future this requirement will be removed and we'll work
99 for any LightPos in homogeneous coordinates, for now it's not really
100 needed. }
101 Result.X := Original.X - LightPos3.X;
102 Result.Y := Original.Y - LightPos3.Y;
103 Result.Z := Original.Z - LightPos3.Z;
104 Result.W := 0;
105 end;
106
107 procedure TRenderShapeShadowVolumes.RenderSilhouetteShadowVolume(
108 const Params: TRenderParams;
109 const Mesh: TCastleRenderUnlitMesh;
110 const LightPos: TVector4;
111 const Transform: TMatrix4;
112 const LightCap, DarkCap: boolean;
113 const ForceOpaque, WholeSceneManifold: boolean);
114
115 { Is it worth preparing ManifoldEdges list: yes.
116
117 At the beginning we used here the simple algorithm from
118 [http://www.gamedev.net/reference/articles/article1873.asp].
119 For each triangle with dot > 0, add it to the Edges list
120 --- unless it's already there, in which case remove it.
121 This way, at the end Edges contain all edges that have on one
122 side triangle with dot > 0 and on the other side triangle with dot <= 0.
123 In other words, all sihouette edges.
124 (This is all assuming that model is 2-manifold,
125 so each edge has exactly 2 neighbor triangles).
126
127 But this algorithm proved to be unacceptably slow for many cases.
128 While it generated much less shadow quads than naive
129 RenderAllShadowVolume, the time spent in detecting the silhouette edges
130 made the total time even worse than RenderAllShadowVolume.
131 Obviously, that's because we started from the list of triangles,
132 without any explicit information about the edges.
133 The time of this algorithm was n*m, if n is the number of triangles
134 and m the number of edges, and on 2-manifold n*3/2 = m so
135 the time is n^2. Terrible, if you take complicated shadow caster.
136
137 To make this faster, we have to know the connections inside the model:
138 that's what ManifoldEdges list is all about. It allows us to
139 implement this in time proportional to the number of edges.
140 }
141
142 var
143 Triangles: TTrianglesShadowCastersList;
144 Vertexes: TVector4List;
145
146 { Render shadow quad from edge given by 2 points. }
147 procedure RenderShadowQuad_Edge(const EdgeV0, EdgeV1: TVector3);
148 var
149 V0_3D, V1_3D: TVector3;
150 V0, V1, V2, V3: TVector4;
151 begin
152 V0_3D := Transform.MultPoint(EdgeV0);
153 V1_3D := Transform.MultPoint(EdgeV1);
154 V0 := Vector4(V0_3D, 1);
155 V1 := Vector4(V1_3D, 1);
156
157 Vertexes.Add(V0);
158 Vertexes.Add(V1);
159
160 if LightPos[3] <> 0 then
161 begin
162 V2 := ExtrudeVertex(V1_3D, LightPos);
163 V3 := ExtrudeVertex(V0_3D, LightPos);
164
165 { Render quad V0..V3 (as 2 triangles, as modern OpenGL doesn't have quads). }
166 Vertexes.Add(V2);
167
168 Vertexes.Add(V0);
169 Vertexes.Add(V2);
170 Vertexes.Add(V3);
171 end else
172 { finish triangle }
173 Vertexes.Add(LightPos);
174 end;
175
176 { Render shadow quad from edge given by PManifoldEdge. }
177 procedure RenderShadowQuad_ManifoldEdge(const EdgePtr: PManifoldEdge;
178 const P0Index, P1Index: Cardinal);
179 var
180 TrianglePtr: PTriangle3;
181 begin
182 TrianglePtr := PTriangle3(Triangles.Ptr(EdgePtr^.Triangles[0]));
183 RenderShadowQuad_Edge(
184 TrianglePtr^.Data[(EdgePtr^.VertexIndex + P0Index) mod 3],
185 TrianglePtr^.Data[(EdgePtr^.VertexIndex + P1Index) mod 3]
186 );
187 end;
188
189 { Render shadow quad from edge given by PBorderEdge. }
190 procedure RenderShadowQuad_BorderEdge(const EdgePtr: PBorderEdge;
191 const P0Index, P1Index: Cardinal);
192 var
193 TrianglePtr: PTriangle3;
194 begin
195 TrianglePtr := PTriangle3(Triangles.Ptr(EdgePtr^.TriangleIndex));
196 RenderShadowQuad_Edge(
197 TrianglePtr^.Data[(EdgePtr^.VertexIndex + P0Index) mod 3],
198 TrianglePtr^.Data[(EdgePtr^.VertexIndex + P1Index) mod 3]
199 );
200 end;
201
202 { Render remaining Vertexes, if any.
203 The Vertexes list is always empty after this. }
204 procedure FlushVertexes;
205 begin
206 if Vertexes.Count <> 0 then
207 begin
208 Mesh.SetVertexes(Vertexes, true);
209 Mesh.Render(pmTriangles);
210 Vertexes.Clear;
211 end;
212 end;
213
214 { We initialize TrianglesPlaneSide and render caps in one step,
215 this way we have to iterate over Triangles only once, and in case
216 of PlaneSide_NotIdentity and rendering caps --- we have to transform
217 each triangle only once. }
218 procedure InitializeTrianglesPlaneSideAndRenderCaps(
219 TrianglesPlaneSide: TBooleanList;
220 LightCap, DarkCap: boolean);
221
222 procedure RenderCaps(const T: TTriangle3);
223 begin
224 if LightCap then
225 begin
226 Vertexes.Add(Vector4(T.Data[0], 1));
227 Vertexes.Add(Vector4(T.Data[1], 1));
228 Vertexes.Add(Vector4(T.Data[2], 1));
229 end;
230
231 if DarkCap then
232 begin
233 Vertexes.Add(ExtrudeVertex(T.Data[2], LightPos));
234 Vertexes.Add(ExtrudeVertex(T.Data[1], LightPos));
235 Vertexes.Add(ExtrudeVertex(T.Data[0], LightPos));
236 end;
237 end;
238
239 function PlaneSide(const T: TTriangle3): boolean;
240 var
241 Plane: TVector4;
242 TriangleTransformed: TTriangle3;
243 begin
244 TriangleTransformed.Data[0] := Transform.MultPoint(T.Data[0]);
245 TriangleTransformed.Data[1] := Transform.MultPoint(T.Data[1]);
246 TriangleTransformed.Data[2] := Transform.MultPoint(T.Data[2]);
247 Plane := TriangleTransformed.Plane;
248 Result := (Plane.X * LightPos.X +
249 Plane.Y * LightPos.Y +
250 Plane.Z * LightPos.Z +
251 Plane.W * LightPos.W) > 0;
252 if Result then RenderCaps(TriangleTransformed);
253 end;
254
255 { Comments for Opaque/TransparentTrianglesBegin/End:
256
257 It's crucial to set glDepthFunc(GL_NEVER) for LightCap.
258 This way we get proper self-shadowing. Otherwise, LightCap would
259 collide in z buffer with the object itself.
260
261 Setting glDepthFunc(GL_NEVER) for DarkCap also is harmless and OK.
262 Proof: if there's anything on this pixel, then indeed the depth test
263 would fail. If the pixel is empty (nothing was rasterized there),
264 then the depth test wouldn't fail... but also, in this case value in
265 stencil buffer will not matter, it doesn't matter if this pixel
266 is in shadow or not because there's simply nothing there.
267
268 And it allows us to render both LightCap and DarkCap in one
269 GL_TRIANGLES pass, in one iteration over Triangles list, which is
270 good for speed.
271
272 Some papers propose other solution:
273 RenderContext.PolygonOffsetEnable(1, 1);
274 but this is no good for use, because it cannot be applied
275 to DarkCap (otherwise DarkCap in infinity (as done by ExtrudeVertex)
276 would go outside of depth range (even for infinite projection,
277 as glPolygonOffset works already after the vertex is transformed
278 by projection), and this would make DarkCap not rendered
279 (outside of depth range)).
280
281 If you consider that some shadow casters and receivers may
282 be partially transparent (that is, rendered without writing
283 to depth buffer) then the above reasoning is not so simple:
284
285 - There's no way to handle transparent
286 objects (that are not recorded in depth buffer) as shadow receivers.
287 Rendering them twice with blending would result in wrong blending
288 modes applied anyway. So TGLShadowVolumeRenderer.Render renders them
289 at the end, as last pass.
290
291 This means that "glDepthFunc(GL_NEVER) for DarkCap" is still
292 Ok: if on some pixel there was only transparent object visible,
293 then stencil value of this pixel is wrong, but transparent object
294 will never be rendered in shadowed state --- so it will not
295 look at stencil value.
296
297 For LightCap, situation is worse. Even if the transparent
298 object is only shadow caster (not receiver), still problems
299 may arise due to glDepthFunc(GL_NEVER): imagine you have
300 a transparent object casting shadow on non-transparent object
301 (see e.g. demo_models/shadow_volumes/ghost_shadow.wrl).
302 This means that you can look through the shadow casting
303 (transp) object and see shadow receiving (opaque) object,
304 that may or may not be in shadow on speciic pixel.
305 Which means that glDepthFunc(GL_NEVER) is wrong for LightCap:
306 the transparent object doesn't hide the shadow on the screen,
307 and the depth test shouldn't fail. Which means that for transparent
308 objects, we cannot do glDepthFunc(GL_NEVER).
309
310 - What to do?
311
312 The trick
313 RenderContext.PolygonOffsetEnable(1, 1);
314 makes light cap rendering working for both transparent and opaque
315 objects, but it's not applicable to dark cap. Moreover,
316 using glPolygonOffset always feels dirty.
317
318 Solution: we decide to handle transparent objects separately.
319 We note that for transparent shadow casters
320 actually no tweaks to caps rendering should be done.
321 No glPolygonOffset, no glDepthFunc(GL_NEVER) needed: light cap
322 should be tested as usual. (Since transparent object is not written
323 to depth buffer, it will not collide in depth buffer with it's
324 light cap).
325
326 This means that is we'll just split triangles list into
327 transparent and opaque ones, then the only complication needed
328 is to switch glDepthFunc(GL_NEVER) trick *off* for transparent
329 triangles. And all works fast.
330
331 - There's actually one more note: for transparent objects,
332 caps are always needed (even with zpass).
333 Note that this means that whole 2-manifold part must have
334 caps.
335
336 This also means that joining one 2-manifold path from some transparent
337 and some opaque triangles will not work. (as then some parts
338 may have caps (like transparent ones) and some note
339 (like opaque ones with zpass)).
340
341 TODO: implement above.
342 }
343
344 var
345 SavedDepthFunc: TDepthFunction;
346
347 procedure OpaqueTrianglesBegin;
348 begin
349 if LightCap or DarkCap then
350 begin
351 FlushVertexes;
352
353 SavedDepthFunc := RenderContext.DepthFunc;
354 RenderContext.DepthFunc := dfNever;
355 end;
356 end;
357
358 procedure OpaqueTrianglesEnd;
359 begin
360 if LightCap or DarkCap then
361 begin
362 FlushVertexes;
363
364 RenderContext.DepthFunc := SavedDepthFunc;
365 end;
366 end;
367
368 procedure TransparentTrianglesBegin;
369 begin
370 { Caps are always needed, doesn't depend on zpass/zfail.
371 Well, for dark cap we can avoid them if the light is directional. }
372 LightCap := true;
373 DarkCap := LightPos.W <> 0;
374 end;
375
376 procedure TransparentTrianglesEnd;
377 begin
378 end;
379
380 var
381 TrianglePtr: PTriangle3;
382 I: Integer;
383 begin
384 TrianglesPlaneSide.Count := Triangles.Count;
385 TrianglePtr := PTriangle3(Triangles.L);
386
387 { If light is directional, no need to render dark cap }
388 DarkCap := DarkCap and (LightPos.W <> 0);
389
390 if ForceOpaque or not (TShape(FShape).AlphaChannel = acBlending) then
391 OpaqueTrianglesBegin
392 else
393 TransparentTrianglesBegin;
394
395 for I := 0 to Triangles.Count - 1 do
396 begin
397 TrianglesPlaneSide.L[I] := PlaneSide(TrianglePtr^);
398 Inc(TrianglePtr);
399 end;
400
401 if ForceOpaque or not (TShape(FShape).AlphaChannel = acBlending) then
402 OpaqueTrianglesEnd
403 else
404 TransparentTrianglesEnd;
405 end;
406
407 var
408 I: Integer;
409 PlaneSide0, PlaneSide1: boolean;
410 TrianglesPlaneSide: TBooleanList;
411 ManifoldEdgesNow: TManifoldEdgeList;
412 ManifoldEdgePtr: PManifoldEdge;
413 BorderEdgesNow: TBorderEdgeList;
414 BorderEdgePtr: PBorderEdge;
415 begin
416 Assert(ManifoldEdges <> nil);
417
418 { If the model is not perfect 2-manifold, do not render it's shadow volumes.
419 This is good default behavior, as shadow volumes on non-manifolds
420 make weird artifacts.
421
422 Developer can override it with WholeSceneManifold though. }
423 if (BorderEdges.Count <> 0) and
424 (not WholeSceneManifold) then
425 Exit;
426
427 Mesh.ModelViewProjection := RenderContext.ProjectionMatrix * Params.RenderingCamera.CurrentMatrix;
428
429 Triangles := TrianglesListShadowCasters;
430
431 { Nil local variables, to later free by one finally clause. }
432 TrianglesPlaneSide := nil;
433 Vertexes := nil;
434
435 try
436 TrianglesPlaneSide := TBooleanList.Create;
437 Vertexes := TVector4List.Create;
438
439 InitializeTrianglesPlaneSideAndRenderCaps(TrianglesPlaneSide,
440 LightCap, DarkCap);
441
442 { for each 2-manifold edge, possibly render it's shadow quad }
443 ManifoldEdgesNow := ManifoldEdges;
444 ManifoldEdgePtr := PManifoldEdge(ManifoldEdgesNow.L);
445 for I := 0 to ManifoldEdgesNow.Count - 1 do
446 begin
447 PlaneSide0 := TrianglesPlaneSide.L[ManifoldEdgePtr^.Triangles[0]];
448 PlaneSide1 := TrianglesPlaneSide.L[ManifoldEdgePtr^.Triangles[1]];
449
450 { Only if PlaneSide0 <> PlaneSide1 it's a silhouette edge,
451 so only then render it's shadow quad.
452
453 We want to have consistent CCW orientation of shadow quads faces,
454 so that face is oriented CCW <=> you're looking at it from outside
455 (i.e. it's considered front face of this shadow quad).
456 This is needed, since user of this method may want to do culling
457 to eliminate back or front faces.
458
459 TriangleDirection(T) indicates direction that goes from CCW triangle side
460 (that's guaranteed by the way TriangleDir calculates plane dir).
461 So PlaneSideX is @true if LightPos is on CCW side of appropriate
462 triangle. So if PlaneSide0 the shadow quad is extended
463 in reversed Triangles[0] order, i.e. like 1, 0, Extruded0, Extruded1.
464 Otherwise, in normal Triangles[0], i.e. 0, 1, Extruded1, Extruded0.
465
466 Just draw it, the triangle corners numbered with 0,1,2 in CCW and
467 imagine that you want the shadow quad to be also CCW on the outside,
468 it will make sense then :) }
469 if PlaneSide0 and not PlaneSide1 then
470 RenderShadowQuad_ManifoldEdge(ManifoldEdgePtr, 1, 0)
471 else
472 if PlaneSide1 and not PlaneSide0 then
473 RenderShadowQuad_ManifoldEdge(ManifoldEdgePtr, 0, 1);
474
475 Inc(ManifoldEdgePtr);
476 end;
477
478 { For each border edge, always render it's shadow quad.
479 This is used now only if WholeSceneManifold
480 (otherwise at the beginning of this method,
481 we exit if BorderEdges.Count <> 0). }
482 BorderEdgesNow := BorderEdges;
483 BorderEdgePtr := PBorderEdge(BorderEdgesNow.L);
484 for I := 0 to BorderEdgesNow.Count - 1 do
485 begin
486 PlaneSide0 := TrianglesPlaneSide.L[BorderEdgePtr^.TriangleIndex];
487
488 { We want to have consistent CCW orientation of shadow quads faces,
489 so that face is oriented CCW <=> you're looking at it from outside
490 (i.e. it's considered front face of this shadow quad).
491 This is needed, since user of this method may want to do culling
492 to eliminate back or front faces.
493
494 TriangleDirection(T) indicates direction that goes from CCW triangle side
495 (that's guaranteed by the way TriangleDir calculates plane dir).
496 So PlaneSide0 is true if LightPos is on CCW side of appropriate
497 triangle. So if PlaneSide0, the shadow quad is extended
498 in the direction of TriangleIndex, like 1, 0, Extruded0, Extruded1. }
499 if PlaneSide0 then
500 RenderShadowQuad_BorderEdge(BorderEdgePtr, 1, 0)
501 {
502 // Do not render shadow quad from other border edge, this would break rendering
503 // (testcase: examples/viewport_and_scenes/shadow_volumes_whole_scene_manifold/ ).
504 // The other shape, that shares this manifold edge, will render the corresponding shadow quad for it.
505 else
506 RenderShadowQuad_BorderEdge(BorderEdgePtr, 0, 1)};
507
508 Inc(BorderEdgePtr);
509 end;
510
511 FlushVertexes;
512 finally
513 FreeAndNil(TrianglesPlaneSide);
514 FreeAndNil(Vertexes);
515 end;
516 end;
517
518 end.