Debian Codegraph @

src/scene/castleinternalocclusionculling.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
16 { Rendering with occlusion culling.
17 @exclude }
18 unit CastleInternalOcclusionCulling;
19
20 {$I castleconf.inc}
21
22 interface
23
24 uses
25 CastleVectors, CastleSceneCore, CastleSceneInternalShape,
26 {$ifdef OpenGLES} CastleGLES, {$else} CastleGL, {$endif}
27 CastleGLUtils, CastleRenderContext, CastleFrustum, CastleGLShaders,
28 CastleBoxes, CastleTransform, CastleRenderPrimitives, CastleRenderOptions;
29
30 type
31 TShapeRenderEvent = procedure (const Shape: TCollectedShape;
32 const Params: TRenderParams) of object;
33
34 TOcclusionCullingUtilsRenderer = class
35 strict private
36 RenderBox: TCastleRenderUnlitMesh;
37 OcclusionBoxState: boolean;
38 SavedDepthBufferUpdate: Boolean;
39 SavedColorChannels: TColorChannels;
40 SavedCullFace: Boolean;
41 procedure GLContextOpen;
42 procedure OcclusionBoxStateBegin;
43 private
44 procedure DrawBox(const Box: TBox3D);
45 public
46 ProjectionMatrix: TMatrix4;
47 CameraMatrix: TMatrix4;
48 SceneMatrix: TMatrix4;
49 procedure GLContextClose;
50 procedure OcclusionBoxStateEnd(const RestoreDefaults: Boolean);
51 end;
52
53 TOcclusionCullingRenderer = class
54 strict private
55 FUtils: TOcclusionCullingUtilsRenderer;
56 public
57 constructor Create;
58 destructor Destroy; override;
59 property Utils: TOcclusionCullingUtilsRenderer read FUtils;
60 procedure Render(const CollectedShape: TCollectedShape;
61 const Params: TRenderParams;
62 const RenderShape: TShapeRenderEvent);
63 end;
64
65 implementation
66
67 uses SysUtils,
68 CastleClassUtils, CastleInternalShapeOctree,
69 CastleUtils;
70
71 { TOcclusionCullingUtilsRenderer ------------------------------------------------- }
72
73 procedure TOcclusionCullingUtilsRenderer.GLContextOpen;
74 const
75 Indexes: array [0..35] of UInt16 =
76 (
77 // triangles: // quads:
78 0, 1, 3, 0, 3, 2, // 0, 1, 3, 2,
79 1, 5, 7, 1, 7, 3, // 1, 5, 7, 3,
80 5, 4, 6, 5, 6, 7, // 5, 4, 6, 7,
81 4, 0, 2, 4, 2, 6, // 4, 0, 2, 6,
82 2, 3, 7, 2, 7, 6, // 2, 3, 7, 6,
83 0, 4, 5, 0, 5, 1 // 0, 4, 5, 1
84 );
85 begin
86 RenderBox := TCastleRenderUnlitMesh.Create(false);
87 RenderBox.SetIndexes(Indexes);
88 end;
89
90 procedure TOcclusionCullingUtilsRenderer.GLContextClose;
91 begin
92 FreeAndNil(RenderBox);
93 end;
94
95 procedure TOcclusionCullingUtilsRenderer.OcclusionBoxStateBegin;
96 begin
97 if not OcclusionBoxState then
98 begin
99 if RenderBox = nil then
100 GLContextOpen;
101
102 SavedDepthBufferUpdate := RenderContext.DepthBufferUpdate;
103 RenderContext.DepthBufferUpdate := false;
104
105 SavedColorChannels := RenderContext.ColorChannels;
106 RenderContext.ColorChannels := [];
107
108 SavedCullFace := RenderContext.CullFace;
109 RenderContext.CullFace := false;
110
111 { Do not alpha test.
112 This also means that texture enabled for fixed-function will be meaningless,
113 it will not affect occlusion result, which is good.
114
115 Note that we don't care to save/restore this state,
116 as each state will reenable alpha test by RenderContext.FixedFunctionAlphaTestEnable
117 if necessary. }
118 RenderContext.FixedFunctionAlphaTestDisable;
119
120 OcclusionBoxState := true;
121 end;
122 end;
123
124 procedure TOcclusionCullingUtilsRenderer.OcclusionBoxStateEnd(const RestoreDefaults: Boolean);
125 begin
126 if OcclusionBoxState then
127 begin
128 if RestoreDefaults then
129 begin
130 RenderContext.DepthBufferUpdate := true;
131 RenderContext.ColorChannels := [0..3];
132 RenderContext.CullFace := false;
133 end else
134 begin
135 RenderContext.DepthBufferUpdate := SavedDepthBufferUpdate;
136 RenderContext.ColorChannels := SavedColorChannels;
137 RenderContext.CullFace := SavedCullFace;
138 end;
139
140 OcclusionBoxState := false;
141 end;
142 end;
143
144 procedure TOcclusionCullingUtilsRenderer.DrawBox(const Box: TBox3D);
145 var
146 Verts: array [0..7] of TVector4;
147 begin
148 if Box.IsEmpty then Exit;
149
150 OcclusionBoxStateBegin;
151
152 { Verts index in octal notation indicates which of 8 vertexes it is. }
153 Verts[0] := Vector4(Box.Data[0], 1);
154 Verts[1] := Vector4(Box.Data[0], 1); Verts[1].Data[0] := Box.Data[1][0];
155 Verts[2] := Vector4(Box.Data[0], 1); Verts[2].Data[1] := Box.Data[1][1];
156 Verts[4] := Vector4(Box.Data[0], 1); Verts[4].Data[2] := Box.Data[1][2];
157
158 Verts[3] := Vector4(Box.Data[1], 1); Verts[3].Data[2] := Box.Data[0][2];
159 Verts[5] := Vector4(Box.Data[1], 1); Verts[5].Data[1] := Box.Data[0][1];
160 Verts[6] := Vector4(Box.Data[1], 1); Verts[6].Data[0] := Box.Data[0][0];
161 Verts[7] := Vector4(Box.Data[1], 1);
162
163 RenderBox.ModelViewProjection := ProjectionMatrix * CameraMatrix * SceneMatrix;
164 RenderBox.SetVertexes(Verts, true);
165 RenderBox.Render(pmTriangles);
166 end;
167
168 { TOcclusionCullingRenderer ---------------------------------------------- }
169
170 const
171 QueryTarget =
172 {$ifndef OpenGLES} GL_SAMPLES_PASSED
173 { Following https://registry.khronos.org/OpenGL-Refpages/es3/html/glBeginQuery.xhtml
174 it seems better to use GL_ANY_SAMPLES_PASSED_CONSERVATIVE: it may sometimes return
175 that object is visible when it is not, but it is faster. }
176 {$else} GL_ANY_SAMPLES_PASSED_CONSERVATIVE
177 {$endif};
178
179 constructor TOcclusionCullingRenderer.Create;
180 begin
181 inherited Create;
182 FUtils := TOcclusionCullingUtilsRenderer.Create;
183 end;
184
185 destructor TOcclusionCullingRenderer.Destroy;
186 begin
187 FreeAndNil(FUtils);
188 inherited;
189 end;
190
191 procedure TOcclusionCullingRenderer.Render(const CollectedShape: TCollectedShape;
192 const Params: TRenderParams; const RenderShape: TShapeRenderEvent);
193
194 { Read OpenGL(ES) occlusion query result, return if hit > 0 samples
195 (was visible). }
196 function OcclusionQueryHit(const OcclusionQueryId: TGLint): Boolean;
197 var
198 SampleCount: TGLuint;
199 begin
200 glGetQueryObjectuiv(OcclusionQueryId, GL_QUERY_RESULT,
201 @SampleCount);
202 Result := SampleCount > 0;
203 end;
204
205 { We cannot trust the occlusion query results if the parent scene,
206 and so also CollectedShape, occur multiple times within the Viewport
207 under a different transformation.
208 Making multiple occlusion queries and using only the last one would be wrong.
209
210 Testcase: fps_game with OcclusionCulling - see at trees. }
211 function SceneMultipleInstances: Boolean;
212 begin
213 Result :=
214 { Note that Shape.ParentScene is useless when batching (always nil
215 for batched shapes)... but luckily, occlusion culling is never used
216 together with batching. }
217 (CollectedShape.Shape.ParentScene <> nil) and
218 (CollectedShape.Shape.ParentScene.InternalWorldReferences > 1);
219 end;
220
221 var
222 Shape: TGLShape;
223 WasVisible: Boolean;
224 begin
225 Shape := CollectedShape.Shape;
226
227 { Get occlusion query result from previous render. }
228 if Shape.OcclusionQueryAsked and
229 (Shape.OcclusionQueryId <> 0) then
230 begin
231 WasVisible := OcclusionQueryHit(Shape.OcclusionQueryId);
232 end else
233 WasVisible := true; // assume is visible
234
235 { Render shape, or shape box, possibly making new occlusion query. }
236 Shape.OcclusionQueryAsked :=
237 { Do not do occlusion query (although still use results from previous
238 query) if we're within stencil test (like in InShadow = false pass
239 of shadow volumes). This would incorrectly mark some shapes
240 as non-visible (just because they don't pass stencil test on any pixel),
241 while in fact they should be visible in the very next
242 (with InShadow = true) render pass. }
243 (Params.StencilTest = 0) and
244 (not SceneMultipleInstances);
245
246 if Shape.OcclusionQueryAsked then
247 begin
248 if Shape.OcclusionQueryId = 0 then
249 glGenQueries(1, @Shape.OcclusionQueryId);
250
251 glBeginQuery(QueryTarget, Shape.OcclusionQueryId);
252
253 if WasVisible then
254 begin
255 RenderShape(CollectedShape, Params);
256 end else
257 begin
258 { Object was not visible in the last frame.
259 In this frame, only render it's bounding box, to test
260 occlusion query. This is the speedup of using occlusion query:
261 we render only bbox. }
262
263 Utils.SceneMatrix := CollectedShape.SceneTransform;
264 Utils.DrawBox(Shape.BoundingBox);
265 if Params.InternalPass = 0 then
266 Inc(Params.Statistics.BoxesOcclusionQueriedCount);
267 end;
268
269 glEndQuery(QueryTarget);
270 end else
271 begin
272 if WasVisible then
273 RenderShape(CollectedShape, Params);
274 end;
275 end;
276
277 end.