vtkDualDepthPeelingPass.cxx 37.6 KB
Newer Older
David C. Lonie's avatar
David C. Lonie committed
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
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkDualDepthPeelingPass.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkDualDepthPeelingPass.h"

#include "vtkFrameBufferObject2.h"
#include "vtkInformation.h"
#include "vtkInformationKey.h"
#include "vtkNew.h"
#include "vtkObjectFactory.h"
#include "vtkOpenGLActor.h"
#include "vtkOpenGLBufferObject.h"
#include "vtkOpenGLError.h"
26
#include "vtkOpenGLRenderUtilities.h"
David C. Lonie's avatar
David C. Lonie committed
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include "vtkOpenGLRenderWindow.h"
#include "vtkOpenGLShaderCache.h"
#include "vtkOpenGLVertexArrayObject.h"
#include "vtkRenderer.h"
#include "vtkRenderState.h"
#include "vtkShaderProgram.h"
#include "vtkTextureObject.h"
#include "vtkTypeTraits.h"

#include <algorithm>

// Define to print debug statements to the OpenGL CS stream (useful for e.g.
// apitrace debugging):
//#define ANNOTATE_STREAM

// Define to output details about each peel:
//#define DEBUG_PEEL

// Define to output details about each frame:
//#define DEBUG_FRAME

48
49
50
51
52
53
54
55
56
57
58
// Recent OSX/ATI drivers perform some out-of-order execution that's causing
// the dFdx/dFdy calls to be conditionally executed. Specifically, it looks
// like the early returns when the depth is not on a current peel layer
// (Peeling pass, VTK::PreColor::Impl hook) are moved before the dFdx/dFdy
// calls used to compute normals. Disable the early returns on apple for now, I
// don't think most GPUs really benefit from them anyway at this point.
#ifdef __APPLE__
#define NO_PRECOLOR_EARLY_RETURN
#endif


David C. Lonie's avatar
David C. Lonie committed
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
vtkStandardNewMacro(vtkDualDepthPeelingPass)

namespace
{
void annotate(const std::string &str)
{
#ifdef ANNOTATE_STREAM
  vtkOpenGLStaticCheckErrorMacro("Error before glDebug.")
  glDebugMessageInsert(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_OTHER,
                       GL_DEBUG_SEVERITY_NOTIFICATION,
                       0, str.size(), str.c_str());
  vtkOpenGLClearErrorMacro();
#else // ANNOTATE_STREAM
  (void)str;
#endif // ANNOTATE_STREAM
}
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::PrintSelf(std::ostream &os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::Render(const vtkRenderState *s)
{
  // Setup vtkOpenGLRenderPass
  this->PreRender(s);

  this->Initialize(s);
  this->Prepare();

  while (!this->PeelingDone())
93
  {
David C. Lonie's avatar
David C. Lonie committed
94
    this->Peel();
95
  }
David C. Lonie's avatar
David C. Lonie committed
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115

  this->Finalize();

  this->PostRender(s);
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::ReleaseGraphicsResources(vtkWindow *)
{
  this->FreeGLObjects();
}

//------------------------------------------------------------------------------
bool vtkDualDepthPeelingPass::ReplaceShaderValues(std::string &,
                                                  std::string &,
                                                  std::string &fragmentShader,
                                                  vtkAbstractMapper *,
                                                  vtkProp *)
{
  switch (this->CurrentStage)
116
  {
David C. Lonie's avatar
David C. Lonie committed
117
    case vtkDualDepthPeelingPass::InitializingDepth:
118
119
120
121
122
123
      // Set gl_FragDepth if it isn't set already. It may have already been
      // replaced by the mapper, in which case the substitution will fail and
      // the previously set depth value will be used.
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::Depth::Impl",
            "gl_FragDepth = gl_FragCoord.z;");
David C. Lonie's avatar
David C. Lonie committed
124
125
126
127
128
129
130
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::DepthPeeling::Dec",
            "uniform sampler2D opaqueDepth;\n");
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::DepthPeeling::PreColor",
            "ivec2 pixel = ivec2(gl_FragCoord.xy);\n"
            "  float oDepth = texelFetch(opaqueDepth, pixel, 0).y;\n"
131
            "  if (oDepth != -1. && gl_FragDepth > oDepth)\n"
David C. Lonie's avatar
David C. Lonie committed
132
133
134
135
            "    { // Ignore fragments that are occluded by opaque geometry:\n"
            "    gl_FragData[1].xy = vec2(-1., oDepth);\n"
            "    return;\n"
            "    }\n"
136
            "  else\n"
David C. Lonie's avatar
David C. Lonie committed
137
            "    {\n"
138
            "    gl_FragData[1].xy = vec2(-gl_FragDepth, gl_FragDepth);\n"
David C. Lonie's avatar
David C. Lonie committed
139
140
141
142
143
144
            "    return;\n"
            "    }\n"
            );
      break;

    case vtkDualDepthPeelingPass::Peeling:
145
146
147
148
149
150
      // Set gl_FragDepth if it isn't set already. It may have already been
      // replaced by the mapper, in which case the substitution will fail and
      // the previously set depth value will be used.
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::Depth::Impl",
            "gl_FragDepth = gl_FragCoord.z;");
David C. Lonie's avatar
David C. Lonie committed
151
152
153
154
155
156
157
158
159
160
161
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::DepthPeeling::Dec",
            "uniform sampler2D lastFrontPeel;\n"
            "uniform sampler2D lastDepthPeel;\n");
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::DepthPeeling::PreColor",
            "  ivec2 pixelCoord = ivec2(gl_FragCoord.xy);\n"
            "  vec4 front = texelFetch(lastFrontPeel, pixelCoord, 0);\n"
            "  vec2 minMaxDepth = texelFetch(lastDepthPeel, pixelCoord, 0).xy;\n"
            "  float minDepth = -minMaxDepth.x;\n"
            "  float maxDepth = minMaxDepth.y;\n"
162
163
164
165
166
167
168
            "  // Use a tolerance when checking if we're on a current peel.\n"
            "  // Some OSX drivers compute slightly different fragment depths\n"
            "  // from one pass to the next. This value was determined\n"
            "  // through trial-and-error -- it may need to be increased at\n"
            "  // some point. See also the comment in vtkDepthPeelingPass's\n"
            "  // shader.\n"
            "  float epsilon = 0.000001;\n"
David C. Lonie's avatar
David C. Lonie committed
169
170
171
172
173
174
175
            "\n"
            "  // Default outputs (no data/change):\n"
            "  gl_FragData[0] = vec4(0.);\n"
            "  gl_FragData[1] = front;\n"
            "  gl_FragData[2].xy = vec2(-1.);\n"
            "\n"
            "  // Is this fragment outside the current peels?\n"
176
177
            "  if (gl_FragDepth < minDepth - epsilon ||\n"
            "      gl_FragDepth > maxDepth + epsilon)\n"
David C. Lonie's avatar
David C. Lonie committed
178
            "    {\n"
179
#ifndef NO_PRECOLOR_EARLY_RETURN
David C. Lonie's avatar
David C. Lonie committed
180
            "    return;\n"
181
182
183
184
185
#else
            "    // Early return removed to avoid instruction-reordering bug\n"
            "    // with dFdx/dFdy on OSX drivers.\n"
            "    // return;\n"
#endif
David C. Lonie's avatar
David C. Lonie committed
186
187
188
            "    }\n"
            "\n"
            "  // Is this fragment inside the current peels?\n"
189
190
            "  if (gl_FragDepth > minDepth + epsilon &&\n"
            "      gl_FragDepth < maxDepth - epsilon)\n"
David C. Lonie's avatar
David C. Lonie committed
191
192
            "    {\n"
            "    // Write out depth so this frag will be peeled later:\n"
193
            "    gl_FragData[2].xy = vec2(-gl_FragDepth, gl_FragDepth);\n"
194
#ifndef NO_PRECOLOR_EARLY_RETURN
David C. Lonie's avatar
David C. Lonie committed
195
            "    return;\n"
196
197
198
199
200
#else
            "    // Early return removed to avoid instruction-reordering bug\n"
            "    // with dFdx/dFdy on OSX drivers.\n"
            "    // return;\n"
#endif
David C. Lonie's avatar
David C. Lonie committed
201
202
203
204
205
206
207
208
209
210
            "    }\n"
            "\n"
            "  // Continue processing for fragments on the current peel:\n"
            );
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::DepthPeeling::Impl",
            "vec4 frag = gl_FragData[0];\n"
            "  // Default outputs (no data/change):\n"
            "\n"
            "  // This fragment is on a current peel:\n"
211
212
            "  if (gl_FragDepth >= minDepth - epsilon &&\n"
            "      gl_FragDepth <= minDepth + epsilon)\n"
David C. Lonie's avatar
David C. Lonie committed
213
214
215
216
217
218
219
220
221
222
223
224
225
226
            "    { // Front peel:\n"
            "    // Clear the back color:\n"
            "    gl_FragData[0] = vec4(0.);\n"
            "\n"
            "    // We store the front alpha value as (1-alpha) to allow MAX\n"
            "    // blending. This also means it is really initialized to 1,\n"
            "    // as it should be for under-blending.\n"
            "    front.a = 1. - front.a;\n"
            "\n"
            "    // Use under-blending to combine fragment with front color:\n"
            "    gl_FragData[1].rgb = front.a * frag.a * frag.rgb + front.rgb;\n"
            "    // Write out (1-alpha):\n"
            "    gl_FragData[1].a = 1. - (front.a * (1. - frag.a));\n"
            "    }\n"
227
228
#ifndef NO_PRECOLOR_EARLY_RETURN
            // just 'else' is ok. We'd return earlier in this case.
229
            "  else // (gl_FragDepth == maxDepth)\n"
230
231
232
233
234
235
#else
            // Need to explicitly test if this is the back peel, since early
            // returns are removed.
            "  else if (gl_FragDepth >= maxDepth - epsilon &&\n"
            "           gl_FragDepth <= maxDepth + epsilon)\n"
#endif
David C. Lonie's avatar
David C. Lonie committed
236
237
238
239
240
            "    { // Back peel:\n"
            "    // Dump premultiplied fragment, it will be blended later:\n"
            "    frag.rgb *= frag.a;\n"
            "    gl_FragData[0] = frag;\n"
            "    }\n"
241
242
243
244
245
246
247
248
249
#ifdef NO_PRECOLOR_EARLY_RETURN
            // Since the color outputs now get clobbered without the early
            // returns, reset them here.
            "  else\n"
            "    { // Need to clear the colors if not on a current peel.\n"
            "    gl_FragData[0] = vec4(0.);\n"
            "    gl_FragData[1] = front;\n"
            "    }\n"
#endif
David C. Lonie's avatar
David C. Lonie committed
250
251
252
253
            );
      break;

    case vtkDualDepthPeelingPass::AlphaBlending:
254
255
256
257
258
259
      // Set gl_FragDepth if it isn't set already. It may have already been
      // replaced by the mapper, in which case the substitution will fail and
      // the previously set depth value will be used.
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::Depth::Impl",
            "gl_FragDepth = gl_FragCoord.z;");
David C. Lonie's avatar
David C. Lonie committed
260
261
262
263
264
265
266
267
268
269
270
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::DepthPeeling::Dec",
            "uniform sampler2D lastDepthPeel;\n");
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::DepthPeeling::PreColor",
            "  ivec2 pixelCoord = ivec2(gl_FragCoord.xy);\n"
            "  vec2 minMaxDepth = texelFetch(lastDepthPeel, pixelCoord, 0).xy;\n"
            "  float minDepth = -minMaxDepth.x;\n"
            "  float maxDepth = minMaxDepth.y;\n"
            "\n"
            "  // Discard all fragments outside of the last set of peels:\n"
271
            "  if (gl_FragDepth < minDepth || gl_FragDepth > maxDepth)\n"
David C. Lonie's avatar
David C. Lonie committed
272
273
274
275
276
277
278
279
280
281
282
283
284
285
            "    {\n"
            "    discard;\n"
            "    }\n"
            );
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::DepthPeeling::Impl",
            "\n"
            "  // Pre-multiply alpha for depth peeling:\n"
            "  gl_FragData[0].rgb *= gl_FragData[0].a;\n"
            );
      break;

    default:
      break;
286
  }
David C. Lonie's avatar
David C. Lonie committed
287
288
289
290
291
292
293
294
295
296

  return true;
}

//------------------------------------------------------------------------------
bool vtkDualDepthPeelingPass::SetShaderParameters(vtkShaderProgram *program,
                                                  vtkAbstractMapper *,
                                                  vtkProp *)
{
  switch (this->CurrentStage)
297
  {
David C. Lonie's avatar
David C. Lonie committed
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
    case vtkDualDepthPeelingPass::InitializingDepth:
      program->SetUniformi(
            "opaqueDepth",
            this->Textures[this->DepthDestination]->GetTextureUnit());
      break;

    case vtkDualDepthPeelingPass::Peeling:
      program->SetUniformi(
            "lastDepthPeel",
            this->Textures[this->DepthSource]->GetTextureUnit());
      program->SetUniformi(
            "frontDepthPeel",
            this->Textures[this->FrontSource]->GetTextureUnit());
      break;

    case vtkDualDepthPeelingPass::AlphaBlending:
      program->SetUniformi(
            "lastDepthPeel",
            this->Textures[this->DepthSource]->GetTextureUnit());
      break;

    default:
      break;
321
  }
David C. Lonie's avatar
David C. Lonie committed
322
323
324
325
326

  return true;
}

//------------------------------------------------------------------------------
Bill Lorensen's avatar
Bill Lorensen committed
327
vtkMTimeType vtkDualDepthPeelingPass::GetShaderStageMTime()
David C. Lonie's avatar
David C. Lonie committed
328
329
330
331
332
333
334
335
336
{
  return this->CurrentStageTimeStamp.GetMTime();
}

//------------------------------------------------------------------------------
vtkDualDepthPeelingPass::vtkDualDepthPeelingPass()
  : RenderState(NULL),
    CopyDepthProgram(NULL),
    CopyDepthVAO(NULL),
337
    CopyDepthVBO(NULL),
David C. Lonie's avatar
David C. Lonie committed
338
339
    BackBlendProgram(NULL),
    BackBlendVAO(NULL),
340
    BackBlendVBO(NULL),
David C. Lonie's avatar
David C. Lonie committed
341
342
    BlendProgram(NULL),
    BlendVAO(NULL),
343
    BlendVBO(NULL),
David C. Lonie's avatar
David C. Lonie committed
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
    Framebuffer(NULL),
    FrontSource(FrontA),
    FrontDestination(FrontB),
    DepthSource(DepthA),
    DepthDestination(DepthB),
    CurrentStage(Inactive),
    CurrentPeel(0),
    OcclusionQueryId(0),
    WrittenPixels(0),
    OcclusionThreshold(0),
    RenderCount(0)
{
  std::fill(this->Textures, this->Textures + static_cast<int>(NumberOfTextures),
            static_cast<vtkTextureObject*>(NULL));
}

//------------------------------------------------------------------------------
vtkDualDepthPeelingPass::~vtkDualDepthPeelingPass()
{
  this->FreeGLObjects();
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::SetCurrentStage(ShaderStage stage)
{
  if (stage != this->CurrentStage)
370
  {
David C. Lonie's avatar
David C. Lonie committed
371
372
    this->CurrentStage = stage;
    this->CurrentStageTimeStamp.Modified();
373
  }
David C. Lonie's avatar
David C. Lonie committed
374
375
376
377
378
379
380
381
}

//------------------------------------------------------------------------------
// Delete the vtkObject subclass pointed at by ptr if it is set.
namespace {
template <typename T> void DeleteHelper(T *& ptr)
{
  if (ptr)
382
  {
David C. Lonie's avatar
David C. Lonie committed
383
384
    ptr->Delete();
    ptr = NULL;
385
  }
David C. Lonie's avatar
David C. Lonie committed
386
387
388
389
390
391
392
}
} // end anon namespace

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::FreeGLObjects()
{
  if (this->Framebuffer)
393
  {
David C. Lonie's avatar
David C. Lonie committed
394
395
396
397
    this->Framebuffer->Delete();
    this->Framebuffer = NULL;

    for (int i = 0; i < static_cast<int>(NumberOfTextures); ++i)
398
    {
David C. Lonie's avatar
David C. Lonie committed
399
400
401
      this->Textures[i]->Delete();
      this->Textures[i] = NULL;
    }
402
  }
David C. Lonie's avatar
David C. Lonie committed
403
404

  DeleteHelper(this->CopyDepthVAO);
405
  DeleteHelper(this->CopyDepthVBO);
David C. Lonie's avatar
David C. Lonie committed
406
  DeleteHelper(this->BackBlendVAO);
407
  DeleteHelper(this->BackBlendVBO);
David C. Lonie's avatar
David C. Lonie committed
408
  DeleteHelper(this->BlendVAO);
409
  DeleteHelper(this->BlendVBO);
David C. Lonie's avatar
David C. Lonie committed
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428

  // don't delete the shader programs -- let the cache clean them up.
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::RenderTranslucentPass()
{
  this->TranslucentPass->Render(this->RenderState);
  ++this->RenderCount;
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::Initialize(const vtkRenderState *s)
{
  this->RenderState = s;

  // Get current viewport size:
  vtkRenderer *r=s->GetRenderer();
  if(s->GetFrameBuffer()==0)
429
  {
David C. Lonie's avatar
David C. Lonie committed
430
431
432
    // get the viewport dimensions
    r->GetTiledSizeAndOrigin(&this->ViewportWidth, &this->ViewportHeight,
                             &this->ViewportX, &this->ViewportY);
433
  }
David C. Lonie's avatar
David C. Lonie committed
434
  else
435
  {
David C. Lonie's avatar
David C. Lonie committed
436
437
438
439
440
441
    int size[2];
    s->GetWindowSize(size);
    this->ViewportWidth = size[0];
    this->ViewportHeight = size[1];
    this->ViewportX =0 ;
    this->ViewportY = 0;
442
  }
David C. Lonie's avatar
David C. Lonie committed
443
444
445
446
447
448
449

  // See if we can reuse existing textures:
  if (this->Textures[Back] &&
      (static_cast<int>(this->Textures[Back]->GetHeight()) !=
       this->ViewportHeight ||
       static_cast<int>(this->Textures[Back]->GetWidth()) !=
       this->ViewportWidth))
450
  {
David C. Lonie's avatar
David C. Lonie committed
451
    this->FreeGLObjects();
452
  }
David C. Lonie's avatar
David C. Lonie committed
453
454
455

  // Allocate new textures if needed:
  if (!this->Framebuffer)
456
  {
David C. Lonie's avatar
David C. Lonie committed
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
    this->Framebuffer = vtkFrameBufferObject2::New();

    std::generate(this->Textures,
                  this->Textures + static_cast<int>(NumberOfTextures),
                  &vtkTextureObject::New);

    this->InitColorTexture(this->Textures[BackTemp], s);
    this->InitColorTexture(this->Textures[Back], s);
    this->InitColorTexture(this->Textures[FrontA], s);
    this->InitColorTexture(this->Textures[FrontB], s);
    this->InitDepthTexture(this->Textures[DepthA], s);
    this->InitDepthTexture(this->Textures[DepthB], s);
    this->InitOpaqueDepthTexture(this->Textures[OpaqueDepth], s);

    this->InitFramebuffer(s);
472
  }
David C. Lonie's avatar
David C. Lonie committed
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::InitColorTexture(vtkTextureObject *tex,
                                               const vtkRenderState *s)
{
  tex->SetContext(static_cast<vtkOpenGLRenderWindow*>(
                    s->GetRenderer()->GetRenderWindow()));
  tex->SetFormat(GL_RGBA);
  tex->SetInternalFormat(GL_RGBA8);
  tex->Allocate2D(this->ViewportWidth, this->ViewportHeight, 4,
                  vtkTypeTraits<vtkTypeUInt8>::VTK_TYPE_ID);
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::InitDepthTexture(vtkTextureObject *tex,
                                               const vtkRenderState *s)
{
  tex->SetContext(static_cast<vtkOpenGLRenderWindow*>(
                    s->GetRenderer()->GetRenderWindow()));
  tex->SetFormat(GL_RG);
  tex->SetInternalFormat(GL_RG32F);
  tex->Allocate2D(this->ViewportWidth, this->ViewportHeight, 2,
                  vtkTypeTraits<vtkTypeFloat32>::VTK_TYPE_ID);
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::InitOpaqueDepthTexture(vtkTextureObject *tex,
                                                     const vtkRenderState *s)
{
  tex->SetContext(static_cast<vtkOpenGLRenderWindow*>(
                    s->GetRenderer()->GetRenderWindow()));
  tex->AllocateDepth(this->ViewportWidth, this->ViewportHeight,
                     vtkTextureObject::Float32);
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::InitFramebuffer(const vtkRenderState *s)
{
  this->Framebuffer->SetContext(static_cast<vtkOpenGLRenderWindow*>(
                                  s->GetRenderer()->GetRenderWindow()));

  // Save the current FBO bindings to restore them later.
  this->Framebuffer->SaveCurrentBindings();
  this->Framebuffer->Bind(GL_DRAW_FRAMEBUFFER);

  this->Framebuffer->AddColorAttachment(GL_DRAW_FRAMEBUFFER, BackTemp,
                                        this->Textures[BackTemp]);
  this->Framebuffer->AddColorAttachment(GL_DRAW_FRAMEBUFFER, Back,
                                        this->Textures[Back]);

  this->Framebuffer->AddColorAttachment(GL_DRAW_FRAMEBUFFER, FrontA,
                                        this->Textures[FrontA]);
  this->Framebuffer->AddColorAttachment(GL_DRAW_FRAMEBUFFER, FrontB,
                                        this->Textures[FrontB]);

  // The depth has to be treated like a color attachment, since it's a 2
  // component min-max texture.
  this->Framebuffer->AddColorAttachment(GL_DRAW_FRAMEBUFFER, DepthA,
                                        this->Textures[DepthA]);
  this->Framebuffer->AddColorAttachment(GL_DRAW_FRAMEBUFFER, DepthB,
                                        this->Textures[DepthB]);

  this->Framebuffer->UnBind(GL_DRAW_FRAMEBUFFER);
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::Prepare()
{
  // Prevent vtkOpenGLActor from messing with the depth mask:
  size_t numProps = this->RenderState->GetPropArrayCount();
  for (size_t i = 0; i < numProps; ++i)
545
  {
David C. Lonie's avatar
David C. Lonie committed
546
547
548
    vtkProp *prop = this->RenderState->GetPropArray()[i];
    vtkInformation *info = prop->GetPropertyKeys();
    if (!info)
549
    {
David C. Lonie's avatar
David C. Lonie committed
550
551
552
553
      info = vtkInformation::New();
      prop->SetPropertyKeys(info);
      info->FastDelete();
    }
554
555
    info->Set(vtkOpenGLActor::GLDepthMaskOverride(), -1);
  }
David C. Lonie's avatar
David C. Lonie committed
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570

  // Setup GL state:
  glDisable(GL_DEPTH_TEST);
  this->InitializeOcclusionQuery();
  this->CurrentPeel = 0;
  this->RenderCount = 0;

  // Save the current FBO bindings to restore them later.
  this->Framebuffer->SaveCurrentBindings();
  this->Framebuffer->Bind(GL_DRAW_FRAMEBUFFER);

  // The source front buffer must be initialized, since it simply uses additive
  // blending.
  // The back-blending may discard fragments, so the back peel accumulator needs
  // initialization as well.
571
572
  unsigned int targets[2] = { static_cast<unsigned int>(Back),
                              static_cast<unsigned int>(this->FrontSource) };
David C. Lonie's avatar
David C. Lonie committed
573
574
575
576
577
578
  this->Framebuffer->ActivateDrawBuffers(targets, 2);
  glClearColor(0.f, 0.f, 0.f, 0.f);
  glClear(GL_COLOR_BUFFER_BIT);

  // Fill both depth buffers with -1, -1. This lets us discard fragments in
  // CopyOpaqueDepthBuffers, which gives a moderate performance boost.
579
580
  targets[0] = static_cast<unsigned int>(this->DepthSource);
  targets[1] = static_cast<unsigned int>(this->DepthDestination);
David C. Lonie's avatar
David C. Lonie committed
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
  this->Framebuffer->ActivateDrawBuffers(targets, 2);
  glClearColor(-1, -1, 0, 0);
  glClear(GL_COLOR_BUFFER_BIT);

  // Pre-fill the depth buffer with opaque pass data:
  this->CopyOpaqueDepthBuffer();

  // Initialize the transparent depths for the peeling algorithm:
  this->InitializeDepth();
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::InitializeOcclusionQuery()
{
  glGenQueries(1, &this->OcclusionQueryId);

  int numPixels = this->ViewportHeight * this->ViewportWidth;
  this->OcclusionThreshold = numPixels * this->OcclusionRatio;
  this->WrittenPixels = this->OcclusionThreshold + 1;
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::CopyOpaqueDepthBuffer()
{
  // Initialize the peeling depth buffer using the existing opaque depth buffer.
  // Note that the min component is stored as -depth, allowing
  // glBlendEquation = GL_MAX to be used during peeling.

  // Copy from the current (default) framebuffer's depth buffer into a texture:
  this->Framebuffer->UnBind(GL_DRAW_FRAMEBUFFER);
  this->Textures[OpaqueDepth]->CopyFromFrameBuffer(
        this->ViewportX, this->ViewportY, 0, 0,
        this->ViewportWidth, this->ViewportHeight);
  this->Framebuffer->Bind(GL_DRAW_FRAMEBUFFER);

  // Fill both depth buffers with the opaque fragment depths. InitializeDepth
  // will compare translucent fragment depths with values in DepthDestination
  // and write to DepthSource using MAX blending, so we need both to have opaque
  // fragments (src/dst seem reversed because they're named for their usage in
  // PeelRender).
621
622
623
  unsigned int targets[2] = { static_cast<unsigned int>(this->DepthSource),
                              static_cast<unsigned int>(this->DepthDestination)
                            };
David C. Lonie's avatar
David C. Lonie committed
624
625
626
627
628
  this->Framebuffer->ActivateDrawBuffers(targets, 2);
  this->Textures[OpaqueDepth]->Activate();

  glDisable(GL_BLEND);

629
630
  typedef vtkOpenGLRenderUtilities GLUtil;

David C. Lonie's avatar
David C. Lonie committed
631
632
633
  vtkOpenGLRenderWindow *renWin = static_cast<vtkOpenGLRenderWindow*>(
        this->RenderState->GetRenderer()->GetRenderWindow());
  if (!this->CopyDepthProgram)
634
  {
635
636
637
    std::string fragShader = GLUtil::GetFullScreenQuadFragmentShaderTemplate();
    vtkShaderProgram::Substitute(
          fragShader, "//VTK::FSQ::Decl",
David C. Lonie's avatar
David C. Lonie committed
638
          "uniform float clearValue;\n"
639
640
641
          "uniform sampler2D oDepth;\n");
    vtkShaderProgram::Substitute(
          fragShader, "//VTK::FSQ::Impl",
David C. Lonie's avatar
David C. Lonie committed
642
643
644
645
646
647
          "  float d = texture2D(oDepth, texCoord).x;\n"
          "  if (d == clearValue)\n"
          "    { // If no depth value has been written, discard the frag:\n"
          "    discard;\n"
          "    }\n"
          "  gl_FragData[0] = gl_FragData[1] = vec4(-1, d, 0., 0.);\n"
648
649
650
651
652
          );
    this->CopyDepthProgram = renWin->GetShaderCache()->ReadyShaderProgram(
          GLUtil::GetFullScreenQuadVertexShader().c_str(),
          fragShader.c_str(),
          GLUtil::GetFullScreenQuadGeometryShader().c_str());
653
  }
David C. Lonie's avatar
David C. Lonie committed
654
  else
655
  {
David C. Lonie's avatar
David C. Lonie committed
656
    renWin->GetShaderCache()->ReadyShaderProgram(this->CopyDepthProgram);
657
  }
David C. Lonie's avatar
David C. Lonie committed
658
659

  if (!this->CopyDepthVAO)
660
  {
661
    this->CopyDepthVBO = vtkOpenGLBufferObject::New();
David C. Lonie's avatar
David C. Lonie committed
662
    this->CopyDepthVAO = vtkOpenGLVertexArrayObject::New();
663
664
    GLUtil::PrepFullScreenVAO(this->CopyDepthVBO, this->CopyDepthVAO,
                              this->CopyDepthProgram);
665
  }
David C. Lonie's avatar
David C. Lonie committed
666
667
668
669
670
671
672
673
674
675
676
677

  // Get the clear value. We don't set this, so it should still be what the
  // opaque pass uses:
  GLfloat clearValue = 1.f;
  glGetFloatv(GL_DEPTH_CLEAR_VALUE, &clearValue);
  this->CopyDepthProgram->SetUniformf("clearValue", clearValue);
  this->CopyDepthProgram->SetUniformi(
        "oDepth", this->Textures[OpaqueDepth]->GetTextureUnit());

  this->CopyDepthVAO->Bind();

  annotate("Copying opaque depth!");
678
  GLUtil::DrawFullScreenQuad();
David C. Lonie's avatar
David C. Lonie committed
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
  annotate("Opaque depth copied!");

  this->CopyDepthVAO->Release();

  this->Textures[OpaqueDepth]->Deactivate();
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::InitializeDepth()
{
  // Add the translucent geometry to our depth peeling buffer:

  // We bind the front destination buffer as render target 0 -- the data we
  // write to it isn't used, but this makes it easier to work with the existing
  // polydata shaders as they expect gl_FragData[0] to be RGBA. The front
  // destination buffer is cleared prior to peeling, so it's just a dummy
  // buffer at this point.
696
697
698
  unsigned int targets[2] = { static_cast<unsigned int>(this->FrontDestination),
                              static_cast<unsigned int>(this->DepthSource)
                            };
David C. Lonie's avatar
David C. Lonie committed
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
  this->Framebuffer->ActivateDrawBuffers(targets, 2);

  this->SetCurrentStage(InitializingDepth);
  this->Textures[this->DepthDestination]->Activate();

  glEnable(GL_BLEND);
  glBlendEquation(GL_MAX);
  annotate("Initializing depth.");
  this->RenderTranslucentPass();
  annotate("Depth initialized");

  this->Textures[this->DepthDestination]->Deactivate();
}

//------------------------------------------------------------------------------
bool vtkDualDepthPeelingPass::PeelingDone()
{
  return this->CurrentPeel >= this->MaximumNumberOfPeels ||
         this->WrittenPixels <= this->OcclusionThreshold;
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::Peel()
{
  this->InitializeTargets();
  this->PeelRender();
  this->BlendBackBuffer();
  this->SwapTargets();
  ++this->CurrentPeel;

#ifdef DEBUG_PEEL
  std::cout << "Peel " << this->CurrentPeel << ": Pixels written: "
            << this->WrittenPixels << " (threshold: "
            << this->OcclusionThreshold << ")\n";
#endif // DEBUG_PEEL
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::InitializeTargets()
{
  // Initialize destination buffers to their minima, since we're MAX blending,
  // this ensures that valid outputs are captured.
741
742
743
744
745
  unsigned int destColorBuffers[2] =
                        {
                        static_cast<unsigned int>(this->FrontDestination),
                        static_cast<unsigned int>(BackTemp)
                        };
David C. Lonie's avatar
David C. Lonie committed
746
747
748
749
750
751
752
753
754
755
756
757
758
  this->Framebuffer->ActivateDrawBuffers(destColorBuffers, 2);
  glClearColor(0.f, 0.f, 0.f, 0.f);
  glClear(GL_COLOR_BUFFER_BIT);

  this->Framebuffer->ActivateDrawBuffer(this->DepthDestination);
  glClearColor(-1.f, -1.f, 0.f, 0.f);
  glClear(GL_COLOR_BUFFER_BIT);
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::PeelRender()
{
  // Enable the destination targets:
759
760
761
762
  unsigned int targets[3] = { static_cast<unsigned int>(BackTemp),
                              static_cast<unsigned int>(this->FrontDestination),
                              static_cast<unsigned int>(this->DepthDestination)
                            };
David C. Lonie's avatar
David C. Lonie committed
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
  this->Framebuffer->ActivateDrawBuffers(targets, 3);

  // Use MAX blending to capture peels:
  glEnable(GL_BLEND);
  glBlendEquation(GL_MAX);

  this->SetCurrentStage(Peeling);
  this->Textures[this->FrontSource]->Activate();
  this->Textures[this->DepthSource]->Activate();

  annotate("Start peeling!");
  this->RenderTranslucentPass();
  annotate("Peeling done!");

  this->Textures[this->FrontSource]->Deactivate();
  this->Textures[this->DepthSource]->Deactivate();
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::BlendBackBuffer()
{
  this->Framebuffer->ActivateDrawBuffer(Back);
  this->Textures[BackTemp]->Activate();

  /* For this step, we blend the last peel's back fragments into a back-
   * accumulation buffer. The full over-blending equations are:
   *
   * (f = front frag (incoming peel); b = back frag (current accum. buffer))
   *
   * a = f.a + (1. - f.a) * b.a
   *
   * if a == 0, C == (0, 0, 0). Otherwise,
   *
   * C = ( f.a * f.rgb + (1. - f.a) * b.a * b.rgb ) / a
   *
   * We use premultiplied alphas to save on computations, resulting in:
   *
   * [a * C] = [f.a * f.rgb] + (1 - f.a) * [ b.a * b.rgb ]
   * a = f.a + (1. - f.a) * b.a
   */

  glEnable(GL_BLEND);
  glBlendEquation(GL_FUNC_ADD);
  glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

808
809
  typedef vtkOpenGLRenderUtilities GLUtil;

David C. Lonie's avatar
David C. Lonie committed
810
811
812
  vtkOpenGLRenderWindow *renWin = static_cast<vtkOpenGLRenderWindow*>(
        this->RenderState->GetRenderer()->GetRenderWindow());
  if (!this->BackBlendProgram)
813
  {
814
815
816
    std::string fragShader = GLUtil::GetFullScreenQuadFragmentShaderTemplate();
    vtkShaderProgram::Substitute(
          fragShader, "//VTK::FSQ::Decl",
David C. Lonie's avatar
David C. Lonie committed
817
          "uniform sampler2D newPeel;\n"
818
819
820
          );
    vtkShaderProgram::Substitute(
          fragShader, "//VTK::FSQ::Impl",
David C. Lonie's avatar
David C. Lonie committed
821
822
823
824
825
826
827
          "  vec4 f = texture2D(newPeel, texCoord); // new frag\n"
          "  if (f.a == 0.)\n"
          "    {\n"
          "    discard;\n"
          "    }\n"
          "\n"
          "  gl_FragData[0] = f;\n"
828
829
830
831
832
          );
    this->BackBlendProgram = renWin->GetShaderCache()->ReadyShaderProgram(
          GLUtil::GetFullScreenQuadVertexShader().c_str(),
          fragShader.c_str(),
          GLUtil::GetFullScreenQuadGeometryShader().c_str());
833
  }
David C. Lonie's avatar
David C. Lonie committed
834
  else
835
  {
David C. Lonie's avatar
David C. Lonie committed
836
    renWin->GetShaderCache()->ReadyShaderProgram(this->BackBlendProgram);
837
  }
David C. Lonie's avatar
David C. Lonie committed
838
839

  if (!this->BackBlendVAO)
840
  {
841
    this->BackBlendVBO = vtkOpenGLBufferObject::New();
David C. Lonie's avatar
David C. Lonie committed
842
    this->BackBlendVAO = vtkOpenGLVertexArrayObject::New();
843
844
    GLUtil::PrepFullScreenVAO(this->BackBlendVBO, this->BackBlendVAO,
                              this->BackBlendProgram);
845
  }
David C. Lonie's avatar
David C. Lonie committed
846
847
848
849
850
851
852
853

  this->BackBlendProgram->SetUniformi(
        "newPeel", this->Textures[BackTemp]->GetTextureUnit());

  this->BackBlendVAO->Bind();

  this->StartOcclusionQuery();
  annotate("Start blending back!");
854
  GLUtil::DrawFullScreenQuad();
David C. Lonie's avatar
David C. Lonie committed
855
856
857
858
859
860
861
862
863
864
865
  annotate("Back blended!");
  this->EndOcclusionQuery();

  this->BackBlendVAO->Release();

  this->Textures[BackTemp]->Deactivate();
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::StartOcclusionQuery()
{
866
867
868
869
870
871
  // ES 3.0 only supports checking if *any* samples passed. We'll just use
  // that query to stop peeling once all frags are processed, and ignore the
  // requested occlusion ratio.
#if GL_ES_VERSION_3_0 == 1
  glBeginQuery(GL_ANY_SAMPLES_PASSED, this->OcclusionQueryId);
#else // GL ES 3.0
David C. Lonie's avatar
David C. Lonie committed
872
  glBeginQuery(GL_SAMPLES_PASSED, this->OcclusionQueryId);
873
#endif // GL ES 3.0
David C. Lonie's avatar
David C. Lonie committed
874
875
876
877
878
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::EndOcclusionQuery()
{
879
880
881
882
883
884
885
886
#if GL_ES_VERSION_3_0 == 1
  glEndQuery(GL_ANY_SAMPLES_PASSED);
  GLuint anySamplesPassed;
  glGetQueryObjectuiv(this->OcclusionQueryId, GL_QUERY_RESULT,
                      &anySamplesPassed);
  this->WrittenPixels = anySamplesPassed ? this->OcclusionThreshold + 1
                                         : 0;
#else // GL ES 3.0
David C. Lonie's avatar
David C. Lonie committed
887
888
889
  glEndQuery(GL_SAMPLES_PASSED);
  glGetQueryObjectuiv(this->OcclusionQueryId, GL_QUERY_RESULT,
                      &this->WrittenPixels);
890
#endif // GL ES 3.0
David C. Lonie's avatar
David C. Lonie committed
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::SwapTargets()
{
  std::swap(this->FrontSource, this->FrontDestination);
  std::swap(this->DepthSource, this->DepthDestination);
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::Finalize()
{
  // Mop up any unrendered fragments using simple alpha blending into the back
  // buffer.
  if (this->WrittenPixels > 0)
906
  {
David C. Lonie's avatar
David C. Lonie committed
907
    this->AlphaBlendRender();
908
  }
David C. Lonie's avatar
David C. Lonie committed
909
910
911
912
913
914
915
916
917
918
919
920
921
922

  this->NumberOfRenderedProps =
      this->TranslucentPass->GetNumberOfRenderedProps();

  this->Framebuffer->UnBind(GL_DRAW_FRAMEBUFFER);
  this->BlendFinalImage();

  // Restore blending parameters:
  glEnable(GL_BLEND);
  glBlendEquation(GL_FUNC_ADD);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  size_t numProps = this->RenderState->GetPropArrayCount();
  for (size_t i = 0; i < numProps; ++i)
923
  {
David C. Lonie's avatar
David C. Lonie committed
924
925
926
    vtkProp *prop = this->RenderState->GetPropArray()[i];
    vtkInformation *info = prop->GetPropertyKeys();
    if (info)
927
    {
David C. Lonie's avatar
David C. Lonie committed
928
929
      info->Remove(vtkOpenGLActor::GLDepthMaskOverride());
    }
930
  }
David C. Lonie's avatar
David C. Lonie committed
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978

  this->RenderState = NULL;
  this->DeleteOcclusionQueryId();
  this->SetCurrentStage(Inactive);

#ifdef DEBUG_FRAME
  std::cout << "Depth peel done:\n"
            << "  - Number of peels: " << this->CurrentPeel << "\n"
            << "  - Number of geometry passes: " << this->RenderCount << "\n"
            << "  - Occlusion Ratio: "
            << static_cast<float>(this->WrittenPixels) /
               static_cast<float>(this->ViewportWidth * this->ViewportHeight)
            << " (target: " << this->OcclusionRatio << ")\n";
#endif // DEBUG_FRAME
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::AlphaBlendRender()
{
  /* This pass is mopping up the remaining fragments when we exceed the max
   * number of peels or hit the occlusion limit. We'll simply render all of the
   * remaining fragments into the back destination buffer using the
   * premultiplied-alpha over-blending equations:
   *
   * aC = f.a * f.rgb + (1 - f.a) * b.a * b.rgb
   * a = f.a + (1 - f.a) * b.a
   */
  glEnable(GL_BLEND);
  glBlendEquation(GL_FUNC_ADD);
  glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

  this->SetCurrentStage(AlphaBlending);
  this->Framebuffer->ActivateDrawBuffer(Back);
  this->Textures[this->DepthSource]->Activate();

  annotate("Alpha blend render start");
  this->RenderTranslucentPass();
  annotate("Alpha blend render end");

  this->Textures[this->DepthSource]->Deactivate();
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::BlendFinalImage()
{
  this->Textures[this->FrontSource]->Activate();
  this->Textures[Back]->Activate();

979
980
981
  /* Peeling is done, time to blend the front and back peel textures with the
   * opaque geometry in the existing framebuffer. First, we'll underblend the
   * back texture beneath the front texture in the shader:
David C. Lonie's avatar
David C. Lonie committed
982
   *
983
984
985
   * Blend 'b' under 'f' to form 't':
   * t.rgb = f.a * b.a * b.rgb + f.rgb
   * t.a   = (1 - b.a) * f.a
David C. Lonie's avatar
David C. Lonie committed
986
   *
987
   * ( t = translucent layer (back + front), f = front layer, b = back layer )
David C. Lonie's avatar
David C. Lonie committed
988
   *
989
990
   * Also in the shader, we adjust the translucent layer's alpha so that it
   * can be used for back-to-front blending, so
David C. Lonie's avatar
David C. Lonie committed
991
   *
992
993
994
995
996
997
998
999
   * alphaOverBlend = 1. - alphaUnderBlend
   *
   * To blend the translucent layer over the opaque layer, use regular
   * overblending via glBlendEquation/glBlendFunc:
   *
   * Blend 't' over 'o'
   * C = t.rgb + o.rgb * (1 - t.a)
   * a = t.a + o.a * (1 - t.a)
David C. Lonie's avatar
David C. Lonie committed
1000
1001
1002
1003
1004
1005
   *
   * These blending parameters and fragment shader perform this work.
   * Note that the opaque fragments are assumed to have premultiplied alpha
   * in this implementation. */
  glEnable(GL_BLEND);
  glBlendEquation(GL_FUNC_ADD);
1006
  glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
David C. Lonie's avatar
David C. Lonie committed
1007

1008
1009
  typedef vtkOpenGLRenderUtilities GLUtil;

David C. Lonie's avatar
David C. Lonie committed
1010
1011
1012
  vtkOpenGLRenderWindow *renWin = static_cast<vtkOpenGLRenderWindow*>(
        this->RenderState->GetRenderer()->GetRenderWindow());
  if (!this->BlendProgram)
1013
  {
1014
1015
1016
    std::string fragShader = GLUtil::GetFullScreenQuadFragmentShaderTemplate();
    vtkShaderProgram::Substitute(
          fragShader, "//VTK::FSQ::Decl",
David C. Lonie's avatar
David C. Lonie committed
1017
1018
          "uniform sampler2D frontTexture;\n"
          "uniform sampler2D backTexture;\n"
1019
1020
1021
          );
    vtkShaderProgram::Substitute(
          fragShader, "//VTK::FSQ::Impl",
David C. Lonie's avatar
David C. Lonie committed
1022
1023
1024
1025
1026
          "  vec4 front = texture2D(frontTexture, texCoord);\n"
          "  vec4 back = texture2D(backTexture, texCoord);\n"
          "  front.a = 1. - front.a; // stored as (1 - alpha)\n"
          "  // Underblend. Back color is premultiplied:\n"
          "  gl_FragData[0].rgb = (front.rgb + back.rgb * front.a);\n"
1027
1028
1029
1030
          "  // The first '1. - ...' is to convert the 'underblend' alpha to\n"
          "  // an 'overblend' alpha, since we'll be letting GL do the\n"
          "  // transparent-over-opaque blending pass.\n"
          "  gl_FragData[0].a = (1. - front.a * (1. - back.a));\n"
1031
1032
1033
1034
1035
          );
    this->BlendProgram = renWin->GetShaderCache()->ReadyShaderProgram(
          GLUtil::GetFullScreenQuadVertexShader().c_str(),
          fragShader.c_str(),
          GLUtil::GetFullScreenQuadGeometryShader().c_str());
1036
  }
David C. Lonie's avatar
David C. Lonie committed
1037
  else
1038
  {
David C. Lonie's avatar
David C. Lonie committed
1039
    renWin->GetShaderCache()->ReadyShaderProgram(this->BlendProgram);
1040
  }
David C. Lonie's avatar
David C. Lonie committed
1041
1042

  if (!this->BlendVAO)
1043
  {
1044
    this->BlendVBO = vtkOpenGLBufferObject::New();
David C. Lonie's avatar
David C. Lonie committed
1045
    this->BlendVAO = vtkOpenGLVertexArrayObject::New();
1046
1047
    GLUtil::PrepFullScreenVAO(this->BlendVBO, this->BlendVAO,
                              this->BlendProgram);
1048
  }
David C. Lonie's avatar
David C. Lonie committed
1049
1050
1051
1052
1053
1054
1055
1056
1057

  this->BlendProgram->SetUniformi(
        "frontTexture", this->Textures[this->FrontSource]->GetTextureUnit());
  this->BlendProgram->SetUniformi(
        "backTexture", this->Textures[Back]->GetTextureUnit());

  this->BlendVAO->Bind();

  annotate("blending final!");
1058
  GLUtil::DrawFullScreenQuad();
David C. Lonie's avatar
David C. Lonie committed
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
  annotate("final blended!");

  this->BlendVAO->Release();

  this->Textures[this->FrontSource]->Deactivate();
  this->Textures[Back]->Deactivate();
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::DeleteOcclusionQueryId()
{
  glDeleteQueries(1, &this->OcclusionQueryId);
}