This file is indexed.

/usr/src/castle-game-engine-5.2.0/x3d/opengl/castlesceneinternalocclusion.pas is in castle-game-engine-src 5.2.0-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
{
  Copyright 2003-2014 Michalis Kamburelis.

  This file is part of "Castle Game Engine".

  "Castle Game Engine" is free software; see the file COPYING.txt,
  included in this distribution, for details about the copyright.

  "Castle Game Engine" is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

  ----------------------------------------------------------------------------
}

{ Rendering with occlusion query.
  @exclude Internal unit for CastleScene. }
unit CastleSceneInternalOcclusion;

{$I castleconf.inc}
{$modeswitch nestedprocvars}{$H+}

interface

uses CastleSceneCore, CastleSceneInternalShape, Castle3D, CastleFrustum;

type
  TShapeProcedure = procedure (Shape: TGLShape) is nested;

  THierarchicalOcclusionQueryRenderer = class
  private
    FrameId: Cardinal;
    Scene: TCastleSceneCore;
  public
    constructor Create(const AScene: TCastleSceneCore);
    procedure Render(const RenderShape: TShapeProcedure;
      const Frustum: TFrustum; const Params: TRenderParams);
    function WasLastVisible(const Shape: TGLShape): boolean;
  end;

var
  OcclusionBoxState: boolean;

procedure OcclusionBoxStateBegin;
procedure OcclusionBoxStateEnd;

procedure SimpleOcclusionQueryRender(const Shape: TGLShape;
  const RenderShape: TShapeProcedure; const Params: TRenderParams);

implementation

uses SysUtils, CastleClassUtils, CastleShapeOctree, CastleBoxes,
  CastleGLUtils, CastleGL;

{$ifndef OpenGLES} // TODO-es this whole unit

{ TOcclusionQuery ------------------------------------------------------------ }

type
  TOcclusionQuery = class
  public
    constructor Create;
    destructor Destroy; override;

  public
    Id: TGLuint;

    Node: TShapeOctreeNode;

    function Available: LongBool;
    function GetResult: TGLuint;
  end;

constructor TOcclusionQuery.Create;
begin
  inherited;
  glGenQueriesARB(1, @Id);
end;

destructor TOcclusionQuery.Destroy;
begin
  glDeleteQueriesARB(1, @Id);
  inherited;
end;

function TOcclusionQuery.Available: LongBool;
begin
  Assert(SizeOf(LongBool) = SizeOf(TGLuint));
  glGetQueryObjectuivARB(Id, GL_QUERY_RESULT_AVAILABLE_ARB, @Result);
end;

function TOcclusionQuery.GetResult: TGLuint;
begin
  glGetQueryObjectuivARB(Id, GL_QUERY_RESULT_ARB, @Result);
end;

{$endif}

{ THierarchicalOcclusionQueryRenderer ---------------------------------------- }

constructor THierarchicalOcclusionQueryRenderer.Create(
  const AScene: TCastleSceneCore);
begin
  inherited Create;
  Scene := AScene;
end;

procedure THierarchicalOcclusionQueryRenderer.Render(
  const RenderShape: TShapeProcedure;
  const Frustum: TFrustum; const Params: TRenderParams);
{$ifndef OpenGLES}
var
  { Stack of TShapeOctreeNode.

    Although queue would also work not so bad, stack is better.
    The idea is that it should try to keep front-to-back order,
    assuming that Node.PushChildren* keeps this order.
    Stack gives more chance to process front shapes first. }
  TraversalStack: TCastleObjectStack;

  procedure TraverseNode(Node: TShapeOctreeNode);
  var
    I: Integer;
    Shape: TGLShape;
  begin
    if Node.IsLeaf then
    begin
      { Render all shapes within this leaf, taking care to render
        shape only once within this frame (FrameId is useful here). }
      for I := 0 to Node.ItemsIndices.Count - 1 do
      begin
        Shape := TGLShape(Scene.OctreeRendering.ShapesList[Node.ItemsIndices.L[I]]);
        if Shape.RenderedFrameId <> FrameId then
        begin
          RenderShape(Shape);
          Shape.RenderedFrameId := FrameId;
        end;
      end;
    end else
    begin
      { Push Node children onto TraversalStack.
        We want to Pop them front-first, to (since this is a stack)
        we want to push back first. }
      if Scene.CameraViewKnown then
        Node.PushChildrenBackToFront(TraversalStack, Scene.CameraPosition) else
        Node.PushChildren(TraversalStack);
    end;
  end;

  procedure PullUpVisibility(Node: TShapeOctreeNode);
  begin
    while not Node.Visible do
    begin
      Node.Visible := true;
      Node := Node.ParentNode;
      if Node = nil then Break;
    end;
  end;

  procedure RenderLeafNodeVolume(Node: TShapeOctreeNode);
  var
    I: Integer;
    Shape: TGLShape;
    Box: TBox3D;
  begin
    OcclusionBoxStateBegin;

    { How to render bounding volume of leaf for occlusion query?

      - Simple version is just to render Node.Box. But this may be
        much greater than actual box of shapes inside, Box of our
        octree node is not adjusted to be tight.

      - Another version is to render boxes of all shapes within this leaf.
        This is much tighter than Node.Box, and results in much less
        shapes quialified as visible. (See e.g. bzwgen city view behind
        building 1 when trying to walk towards the city center.)
        Unfortunately, this produces really a lot of boxes, so the
        overhead of drawing glDrawBox3DSimple becomes large then.

      - Compromise: calculate tight bounding box here, and use it.
        Works best: number of both visible shapes and cull boxes
        is small.

      Note that we can render here boxes of only non-rendered shapes,
      that's Ok and may actually speed up. }
    Box := EmptyBox3D;

    for I := 0 to Node.ItemsIndices.Count - 1 do
    begin
      Shape := TGLShape(Scene.OctreeRendering.ShapesList[Node.ItemsIndices.L[I]]);
      if Shape.RenderedFrameId <> FrameId then
        Box.Add(Shape.BoundingBox);
    end;

    glDrawBox3DSimple(Box);
    if Params.Pass = 0 then Inc(Params.Statistics.BoxesOcclusionQueriedCount);
  end;

const
  VisibilityThreshold = 0;
{ $define VISIBILITY_KEEP_FRAMES}
{$ifdef VISIBILITY_KEEP_FRAMES}
  VisibilityKeepFrames = 10;
{$endif}
var
  { queue of TOcclusionQuery }
  QueryQueue: TCastleObjectQueue;
  Q: TOcclusionQuery;
  Node: TShapeOctreeNode;
  WasVisible, LeafOrWasInvisible: boolean;
begin
  {$include norqcheckbegin.inc}
  Inc(FrameId);
  {$include norqcheckend.inc}

  TraversalStack := TCastleObjectStack.Create;
  TraversalStack.Capacity := Scene.OctreeRendering.ShapesList.Count;

  QueryQueue := TCastleObjectQueue.Create;
  QueryQueue.Capacity := Scene.OctreeRendering.ShapesList.Count;

  try
    TraversalStack.Push(Scene.OctreeRendering.TreeRoot);

    repeat
      if (QueryQueue.Count <> 0) and
         ( (TOcclusionQuery(QueryQueue.Peek).Available) or
           (TraversalStack.Count = 0) ) then
      begin
        Q := TOcclusionQuery(QueryQueue.Pop);
        if Q.GetResult > VisibilityThreshold then
        begin
          PullUpVisibility(Q.Node);
          TraverseNode(Q.Node);
        end;
        FreeAndNil(Q);
      end;

      if TraversalStack.Count <> 0 then
      begin
        Node := TShapeOctreeNode(TraversalStack.Pop);
        if Node.FrustumCollisionPossible(Frustum) then
        begin
          {$ifdef VISIBILITY_KEEP_FRAMES}
          { There was a resigned idea below (maybe useful later) to do
            "or (Node.Depth >= 5)", to assume visible = true below some
            octree depth. }

          if (Node.Visible and (Node.LastVisitedFrameId >= FrameId - VisibilityKeepFrames)) then
          begin
            { Visible somewhere during VisibilityKeepFrames.
              Just assume it's still visible.
              (This is the optimization described in 6.6.4
              "Conservative Visibility Testing") }
            TraverseNode(Node);
          end else
          {$endif VISIBILITY_KEEP_FRAMES}
          begin
            WasVisible := Node.Visible and (Node.LastVisitedFrameId = FrameId - 1);
            LeafOrWasInvisible := (not WasVisible) or Node.IsLeaf;

            Node.Visible := false;
            Node.LastVisitedFrameId := FrameId;

            { Original logic goes like:

                if LeafOrWasInvisible then
                  Add query with Node.Box;
                if WasVisible then
                  TraverseNode(Node);

              But this is not optimal: it would always query using bounding
              boxes. Even for the case when we have a visible leaf,
              then the above version would query using box of this leaf
              and then render this leaf.
              But in this case we can query using actual geometry.

              So a modification is to do

                if LeafOrWasInvisible then
                begin
                  if Leaf and WasVisible then
                    Add query for Node and render the leaf else
                    Add query with Node.Box;
                end else
                if WasVisible then
                  TraverseNode(Node);

              This exhausts all possibilities, since if
              LeafOrWasInvisible and WasVisible then only leaf nodes
              could satisfy this.

              There's additional note about this:
              rendering inside TraverseNode may render
              only part of the leaf's items (or even none at all).
              This is needed (although in original paper they write
              about rendering single shape there, unline my many-shapes-in-leaf
              approach, but still they have to safeguard against rendering
              the same node many times, since visible leaf confirmed to
              be visible may be passed twice to Render).

              But this means that object may be classified as invisible
              (because it didn't have any unrendered shapes), while in fact
              it's visible. That's not a problem, since we check our
              query in the next frame, and the object will be found
              then visible again (or again invisible if other leafs
              will render it's shapes, but then it's not a problem). }

            if LeafOrWasInvisible then
            begin
              Q := TOcclusionQuery.Create;
              Q.Node := Node;

              glBeginQueryARB(GL_SAMPLES_PASSED_ARB, Q.Id);
                if Node.IsLeaf and WasVisible then
                  TraverseNode(Node) else
                if Node.IsLeaf then
                  { Leaf nodes have optimized version of rendering their
                    bounding volume for occlusion query. }
                  RenderLeafNodeVolume(Node) else
                begin
                  OcclusionBoxStateBegin;
                  glDrawBox3DSimple(Node.Box);
                  if Params.Pass = 0 then Inc(Params.Statistics.BoxesOcclusionQueriedCount);
                end;
              glEndQueryARB(GL_SAMPLES_PASSED_ARB);

              QueryQueue.Push(Q);
            end else
            if WasVisible then
              TraverseNode(Node);
          end;
        end;
      end;

    until (TraversalStack.Count = 0) and (QueryQueue.Count = 0);
  finally
    FreeAndNil(TraversalStack);
    FreeAndNil(QueryQueue);
  end;
{$else}
begin
{$endif}
end;

function THierarchicalOcclusionQueryRenderer.WasLastVisible(const Shape: TGLShape): boolean;
begin
  Result := Shape.RenderedFrameId = FrameId
end;

{ routines ------------------------------------------------------------------- }

procedure OcclusionBoxStateBegin;
begin
  if not OcclusionBoxState then
  begin
    {$ifndef OpenGLES}
    glPushAttrib(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT or
      GL_ENABLE_BIT or GL_LIGHTING_BIT);

    glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); { saved by GL_COLOR_BUFFER_BIT }
    glDepthMask(GL_FALSE); { saved by GL_DEPTH_BUFFER_BIT }

    { A lot of state should be disabled. Remember that this is done
      in the middle of TGLRenderer rendering, between
      RenderBegin/End, and TGLRenderer doesn't need to
      restore state after each shape render. So e.g. texturing
      and alpha test may be enabled, which could lead to very
      strange effects (box would be rendered with random texel,
      possibly alpha tested and rejected...).

      Also, some state should be disabled just to speed up
      rendering. E.g. lighting is totally not needed here. }

    glDisable(GL_LIGHTING); { saved by GL_ENABLE_BIT }
    glDisable(GL_CULL_FACE); { saved by GL_ENABLE_BIT }
    glDisable(GL_COLOR_MATERIAL); { saved by GL_ENABLE_BIT }
    glDisable(GL_ALPHA_TEST); { saved by GL_ENABLE_BIT }
    glDisable(GL_FOG); { saved by GL_ENABLE_BIT }
    GLEnableTexture(etNone); { saved by GL_ENABLE_BIT }

    glShadeModel(GL_FLAT); { saved by GL_LIGHTING_BIT }

    glEnableClientState(GL_VERTEX_ARRAY);

    {$endif}

    OcclusionBoxState := true;
  end;
end;

procedure OcclusionBoxStateEnd;
begin
  if OcclusionBoxState then
  begin
    {$ifndef OpenGLES}
    glDisableClientState(GL_VERTEX_ARRAY);
    glPopAttrib;
    {$endif}
    OcclusionBoxState := false;
  end;
end;

procedure SimpleOcclusionQueryRender(const Shape: TGLShape;
  const RenderShape: TShapeProcedure; const Params: TRenderParams);
{$ifndef OpenGLES}
var
  SampleCount: TGLuint;
begin
  Assert(Shape.OcclusionQueryId <> 0);
  if Shape.OcclusionQueryAsked then
    glGetQueryObjectuivARB(Shape.OcclusionQueryId, GL_QUERY_RESULT_ARB,
      @SampleCount) else
    SampleCount := 1; { if not asked, assume it's visible }

  { Do not do occlusion query (although still use results from previous
    query) if we're within stencil test (like in InShadow = false pass
    of shadow volumes). This would incorrectly mark some shapes
    as non-visible (just because they don't pass stencil test on any pixel),
    while in fact they should be visible in the very next
    (with InShadow = true) render pass. }

  if Params.StencilTest = 0 then
    glBeginQueryARB(GL_SAMPLES_PASSED_ARB, Shape.OcclusionQueryId);

    if SampleCount > 0 then
    begin
      RenderShape(Shape);
    end else
    begin
      { Object was not visible in the last frame.
        In this frame, only render it's bounding box, to test
        occlusion query. This is the speedup of using occlusion query:
        we render only bbox. }

      OcclusionBoxStateBegin;
      glDrawBox3DSimple(Shape.BoundingBox);
      if Params.Pass = 0 then Inc(Params.Statistics.BoxesOcclusionQueriedCount);
    end;

  if Params.StencilTest = 0 then
  begin
    glEndQueryARB(GL_SAMPLES_PASSED_ARB);
    Shape.OcclusionQueryAsked := true;
  end;
{$else}
begin
{$endif}
end;

end.