vtkOpenGLPolyDataMapper.cxx 113 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
/*=========================================================================

  Program:   Visualization Toolkit

  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.

=========================================================================*/
Ken Martin's avatar
Ken Martin committed
14
#include "vtkOpenGLPolyDataMapper.h"
15

16
#include "vtkCamera.h"
17
#include "vtkCellArray.h"
Ken Martin's avatar
Ken Martin committed
18
#include "vtkCellData.h"
19
20
21
22
#include "vtkCommand.h"
#include "vtkFloatArray.h"
#include "vtkHardwareSelector.h"
#include "vtkImageData.h"
23
#include "vtkInformation.h"
24
25
#include "vtkLight.h"
#include "vtkLightCollection.h"
26
#include "vtkLightingMapPass.h"
27
#include "vtkMath.h"
28
#include "vtkMatrix3x3.h"
29
#include "vtkMatrix4x4.h"
30
#include "vtkObjectFactory.h"
31
#include "vtkOpenGLActor.h"
Ken Martin's avatar
Ken Martin committed
32
#include "vtkOpenGLBufferObject.h"
33
#include "vtkOpenGLCamera.h"
Ken Martin's avatar
Ken Martin committed
34
35
36
#include "vtkOpenGLError.h"
#include "vtkOpenGLHelper.h"
#include "vtkOpenGLIndexBufferObject.h"
David C. Lonie's avatar
David C. Lonie committed
37
#include "vtkOpenGLRenderPass.h"
38
#include "vtkOpenGLRenderWindow.h"
Ken Martin's avatar
Ken Martin committed
39
#include "vtkOpenGLRenderer.h"
40
41
#include "vtkOpenGLShaderCache.h"
#include "vtkOpenGLTexture.h"
Ken Martin's avatar
Ken Martin committed
42
#include "vtkOpenGLVertexArrayObject.h"
Ken Martin's avatar
Ken Martin committed
43
#include "vtkOpenGLVertexBufferObject.h"
44
45
46
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkProperty.h"
47
#include "vtkScalarsToColors.h"
48
#include "vtkShaderProgram.h"
49
#include "vtkTextureObject.h"
Ken Martin's avatar
Ken Martin committed
50
#include "vtkTransform.h"
51
#include "vtkUnsignedIntArray.h"
Tim Thirion's avatar
Tim Thirion committed
52
#include "vtkValuePass.h"
53

Ken Martin's avatar
Ken Martin committed
54
55
#include "vtkShadowMapPass.h"

Ken Martin's avatar
Ken Martin committed
56
// Bring in our fragment lit shader symbols.
Ken Martin's avatar
Ken Martin committed
57
58
#include "vtkPolyDataVS.h"
#include "vtkPolyDataFS.h"
59
#include "vtkPolyDataWideLineGS.h"
60

Ken Martin's avatar
Ken Martin committed
61
#include <algorithm>
Ken Martin's avatar
Ken Martin committed
62
#include <sstream>
Ken Martin's avatar
Ken Martin committed
63

64

65
//-----------------------------------------------------------------------------
Ken Martin's avatar
Ken Martin committed
66
vtkStandardNewMacro(vtkOpenGLPolyDataMapper)
67
68

//-----------------------------------------------------------------------------
Ken Martin's avatar
Ken Martin committed
69
vtkOpenGLPolyDataMapper::vtkOpenGLPolyDataMapper()
Ken Martin's avatar
Ken Martin committed
70
  : UsingScalarColoring(false)
71
{
72
  this->InternalColorTexture = 0;
73
  this->PopulateSelectionSettings = 1;
74
  this->LastSelectionState = vtkHardwareSelector::MIN_KNOWN_PASS - 1;
75
  this->CurrentInput = 0;
76
77
  this->TempMatrix4 = vtkMatrix4x4::New();
  this->TempMatrix3 = vtkMatrix3x3::New();
78
  this->DrawingEdges = false;
Ken Martin's avatar
Ken Martin committed
79
  this->ForceTextureCoordinates = false;
80

Ken Martin's avatar
Ken Martin committed
81
82
  this->PrimitiveIDOffset = 0;

83
84
85
86
  this->CellScalarTexture = NULL;
  this->CellScalarBuffer = NULL;
  this->CellNormalTexture = NULL;
  this->CellNormalBuffer = NULL;
87

88
  this->HavePickScalars = false;
89
90
  this->HaveCellScalars = false;
  this->HaveCellNormals = false;
91
92
93
94
95

  this->PointIdArrayName = NULL;
  this->CellIdArrayName = NULL;
  this->ProcessIdArrayName = NULL;
  this->CompositeIdArrayName = NULL;
Ken Martin's avatar
Ken Martin committed
96
  this->VBO = vtkOpenGLVertexBufferObject::New();
97
98

  this->AppleBugPrimIDBuffer = 0;
99
  this->HaveAppleBug = false;
100
  this->HaveAppleBugForce = 0;
Dan Lipsa's avatar
Dan Lipsa committed
101
  this->LastBoundBO = NULL;
102
103
104
105

  this->VertexShaderCode = 0;
  this->FragmentShaderCode = 0;
  this->GeometryShaderCode = 0;
106
107
108
109
110
111
112

  this->LastLightComplexity[&this->Points] = -1;
  this->LastLightComplexity[&this->Lines] = -1;
  this->LastLightComplexity[&this->Tris] = -1;
  this->LastLightComplexity[&this->TriStrips] = -1;
  this->LastLightComplexity[&this->TrisEdges] = -1;
  this->LastLightComplexity[&this->TriStripsEdges] = -1;
113

114
115
  this->TimerQuery = 0;
}
116

117
//-----------------------------------------------------------------------------
Ken Martin's avatar
Ken Martin committed
118
vtkOpenGLPolyDataMapper::~vtkOpenGLPolyDataMapper()
119
{
120
121
122
123
124
  if (this->InternalColorTexture)
    { // Resources released previously.
    this->InternalColorTexture->Delete();
    this->InternalColorTexture = 0;
    }
125
126
  this->TempMatrix3->Delete();
  this->TempMatrix4->Delete();
127
128
129
130
131
132
133
134

  if (this->CellScalarTexture)
    { // Resources released previously.
    this->CellScalarTexture->Delete();
    this->CellScalarTexture = 0;
    }
  if (this->CellScalarBuffer)
    { // Resources released previously.
Ken Martin's avatar
Ken Martin committed
135
    this->CellScalarBuffer->Delete();
136
137
138
139
140
141
142
143
144
145
    this->CellScalarBuffer = 0;
    }

  if (this->CellNormalTexture)
    { // Resources released previously.
    this->CellNormalTexture->Delete();
    this->CellNormalTexture = 0;
    }
  if (this->CellNormalBuffer)
    { // Resources released previously.
Ken Martin's avatar
Ken Martin committed
146
    this->CellNormalBuffer->Delete();
147
148
    this->CellNormalBuffer = 0;
    }
149
150
151
152
153

  this->SetPointIdArrayName(NULL);
  this->SetCellIdArrayName(NULL);
  this->SetProcessIdArrayName(NULL);
  this->SetCompositeIdArrayName(NULL);
Ken Martin's avatar
Ken Martin committed
154
155
  this->VBO->Delete();
  this->VBO = 0;
156
157
158
159
160

  if (this->AppleBugPrimIDBuffer)
    {
    this->AppleBugPrimIDBuffer->Delete();
    }
161
162
163
164

  this->SetVertexShaderCode(0);
  this->SetFragmentShaderCode(0);
  this->SetGeometryShaderCode(0);
165
166
167
}

//-----------------------------------------------------------------------------
Ken Martin's avatar
Ken Martin committed
168
void vtkOpenGLPolyDataMapper::ReleaseGraphicsResources(vtkWindow* win)
169
{
170
171
172
173
174
175
176
177
178
  vtkOpenGLRenderWindow *rwin =
   vtkOpenGLRenderWindow::SafeDownCast(win);
  if (rwin)
    {
    // Ensure that the context is current before releasing any
    // graphics resources tied to it.
    rwin->MakeCurrent();
    }

Ken Martin's avatar
Ken Martin committed
179
  this->VBO->ReleaseGraphicsResources();
180
181
182
183
  this->Points.ReleaseGraphicsResources(win);
  this->Lines.ReleaseGraphicsResources(win);
  this->Tris.ReleaseGraphicsResources(win);
  this->TriStrips.ReleaseGraphicsResources(win);
184
185
  this->TrisEdges.ReleaseGraphicsResources(win);
  this->TriStripsEdges.ReleaseGraphicsResources(win);
186

187
188
189
190
  if (this->InternalColorTexture)
    {
    this->InternalColorTexture->ReleaseGraphicsResources(win);
    }
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
  if (this->CellScalarTexture)
    {
    this->CellScalarTexture->ReleaseGraphicsResources(win);
    }
  if (this->CellScalarBuffer)
    {
    this->CellScalarBuffer->ReleaseGraphicsResources();
    }
  if (this->CellNormalTexture)
    {
    this->CellNormalTexture->ReleaseGraphicsResources(win);
    }
  if (this->CellNormalBuffer)
    {
    this->CellNormalBuffer->ReleaseGraphicsResources();
    }
207
208
209
210
  if (this->AppleBugPrimIDBuffer)
    {
    this->AppleBugPrimIDBuffer->ReleaseGraphicsResources();
    }
211
212
  if (this->TimerQuery)
    {
213
#if GL_ES_VERSION_2_0 != 1 && GL_ES_VERSION_3_0 != 1
214
    glDeleteQueries(1, &this->TimerQuery);
215
#endif
216
217
    this->TimerQuery = 0;
    }
218
219
  this->VBOBuildString = "";
  this->IBOBuildString = "";
220
  this->Modified();
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
void vtkOpenGLPolyDataMapper::AddShaderReplacement(
    vtkShader::Type shaderType, // vertex, fragment, etc
    std::string originalValue,
    bool replaceFirst,  // do this replacement before the default
    std::string replacementValue,
    bool replaceAll)
{
  vtkOpenGLPolyDataMapper::ReplacementSpec spec;
  spec.ShaderType = shaderType;
  spec.OriginalValue = originalValue;
  spec.ReplaceFirst = replaceFirst;

  vtkOpenGLPolyDataMapper::ReplacementValue values;
  values.Replacement = replacementValue;
  values.ReplaceAll = replaceAll;

  this->UserShaderReplacements[spec] = values;
}

void vtkOpenGLPolyDataMapper::ClearShaderReplacement(
    vtkShader::Type shaderType, // vertex, fragment, etc
    std::string originalValue,
    bool replaceFirst)
{
  vtkOpenGLPolyDataMapper::ReplacementSpec spec;
  spec.ShaderType = shaderType;
  spec.OriginalValue = originalValue;
  spec.ReplaceFirst = replaceFirst;

  typedef std::map<const vtkOpenGLPolyDataMapper::ReplacementSpec,
Ken Martin's avatar
Ken Martin committed
253
    vtkOpenGLPolyDataMapper::ReplacementValue>::iterator RIter;
254
255
256
257
258
259
260
  RIter found = this->UserShaderReplacements.find(spec);
  if (found == this->UserShaderReplacements.end())
    {
    this->UserShaderReplacements.erase(found);
    }
}

261
//-----------------------------------------------------------------------------
262
263
264
void vtkOpenGLPolyDataMapper::BuildShaders(
    std::map<vtkShader::Type, vtkShader *> shaders,
    vtkRenderer *ren, vtkActor *actor)
265
{
266
  this->GetShaderTemplate(shaders, ren, actor);
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285

  typedef std::map<const vtkOpenGLPolyDataMapper::ReplacementSpec,
    vtkOpenGLPolyDataMapper::ReplacementValue>::const_iterator RIter;

  // user specified pre replacements
  for (RIter i = this->UserShaderReplacements.begin();
    i != this->UserShaderReplacements.end(); i++)
    {
    if (i->first.ReplaceFirst)
      {
      std::string ssrc = shaders[i->first.ShaderType]->GetSource();
      vtkShaderProgram::Substitute(ssrc,
        i->first.OriginalValue,
        i->second.Replacement,
        i->second.ReplaceAll);
      shaders[i->first.ShaderType]->SetSource(ssrc);
      }
    }

286
  this->ReplaceShaderValues(shaders, ren, actor);
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301

  // user specified post replacements
  for (RIter i = this->UserShaderReplacements.begin();
    i != this->UserShaderReplacements.end(); i++)
    {
    if (!i->first.ReplaceFirst)
      {
      std::string ssrc = shaders[i->first.ShaderType]->GetSource();
      vtkShaderProgram::Substitute(ssrc,
        i->first.OriginalValue,
        i->second.Replacement,
        i->second.ReplaceAll);
      shaders[i->first.ShaderType]->SetSource(ssrc);
      }
    }
302
303
}

304
305
306
bool vtkOpenGLPolyDataMapper::HaveWideLines(
  vtkRenderer *ren,
  vtkActor *actor)
307
308
309
310
311
312
313
314
315
316
{
  if ((this->LastBoundBO == &this->Lines ||
       this->LastBoundBO == &this->TrisEdges ||
       this->LastBoundBO == &TriStripsEdges ||
       (actor->GetProperty()->GetRepresentation() == VTK_WIREFRAME &&
          (this->LastBoundBO == &this->Tris ||
            this->LastBoundBO == &this->TriStrips)))
      && actor->GetProperty()->GetLineWidth() > 1.0
      && vtkOpenGLRenderWindow::GetContextSupportsOpenGL32())
    {
317
318
319
320
321
322
    // we have wide lines, but the OpenGL implementation may
    // actually support them, check the range to see if we
      // really need have to implement our own wide lines
    vtkOpenGLRenderWindow *renWin = vtkOpenGLRenderWindow::SafeDownCast(ren->GetRenderWindow());
    return !(renWin &&
      renWin->GetMaximumHardwareLineWidth() >= actor->GetProperty()->GetLineWidth());
323
324
325
326
    }
  return false;
}

327
//-----------------------------------------------------------------------------
Bill Lorensen's avatar
Bill Lorensen committed
328
vtkMTimeType vtkOpenGLPolyDataMapper::GetRenderPassStageMTime(vtkActor *actor)
329
330
{
  vtkInformation *info = actor->GetPropertyKeys();
Bill Lorensen's avatar
Bill Lorensen committed
331
  vtkMTimeType renderPassMTime = 0;
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

  int curRenderPasses = 0;
  if (info && info->Has(vtkOpenGLRenderPass::RenderPasses()))
    {
    curRenderPasses = info->Length(vtkOpenGLRenderPass::RenderPasses());
    }

  int lastRenderPasses = 0;
  if (this->LastRenderPassInfo->Has(vtkOpenGLRenderPass::RenderPasses()))
    {
    lastRenderPasses =
        this->LastRenderPassInfo->Length(vtkOpenGLRenderPass::RenderPasses());
    }

  // Determine the last time a render pass changed stages:
  if (curRenderPasses != lastRenderPasses)
    {
    // Number of passes changed, definitely need to update.
    // Fake the time to force an update:
    renderPassMTime = VTK_UNSIGNED_LONG_MAX;
    }
  else
    {
    // Compare the current to the previous render passes:
    for (int i = 0; i < curRenderPasses; ++i)
      {
      vtkObjectBase *curRP = info->Get(vtkOpenGLRenderPass::RenderPasses(), i);
      vtkObjectBase *lastRP =
          this->LastRenderPassInfo->Get(vtkOpenGLRenderPass::RenderPasses(), i);

      if (curRP != lastRP)
        {
        // Render passes have changed. Force update:
        renderPassMTime = VTK_UNSIGNED_LONG_MAX;
        break;
        }
      else
        {
        // Render passes have not changed -- check MTime.
        vtkOpenGLRenderPass *rp = static_cast<vtkOpenGLRenderPass*>(curRP);
        renderPassMTime = std::max(renderPassMTime, rp->GetShaderStageMTime());
        }
      }
    }

  // Cache the current set of render passes for next time:
  if (info)
    {
    this->LastRenderPassInfo->CopyEntry(info,
                                        vtkOpenGLRenderPass::RenderPasses());
    }
  else
    {
    this->LastRenderPassInfo->Clear();
    }

  return renderPassMTime;
}

391
//-----------------------------------------------------------------------------
392
void vtkOpenGLPolyDataMapper::GetShaderTemplate(
393
    std::map<vtkShader::Type, vtkShader *> shaders,
394
    vtkRenderer *ren, vtkActor *actor)
395
{
396
  if (this->VertexShaderCode && strcmp(this->VertexShaderCode,"") != 0)
397
    {
398
    shaders[vtkShader::Vertex]->SetSource(this->VertexShaderCode);
399
400
401
    }
  else
    {
402
403
404
405
406
407
408
409
410
411
412
413
414
    shaders[vtkShader::Vertex]->SetSource(vtkPolyDataVS);
    }

  if (this->FragmentShaderCode && strcmp(this->FragmentShaderCode,"") != 0)
    {
    shaders[vtkShader::Fragment]->SetSource(this->FragmentShaderCode);
    }
  else
    {
    shaders[vtkShader::Fragment]->SetSource(vtkPolyDataFS);
    }

  if (this->GeometryShaderCode && strcmp(this->GeometryShaderCode,"") != 0)
415
    {
416
    shaders[vtkShader::Geometry]->SetSource(this->GeometryShaderCode);
417
418
419
    }
  else
    {
420
421
422
423
424
425
426
427
    if (this->HaveWideLines(ren, actor))
      {
      shaders[vtkShader::Geometry]->SetSource(vtkPolyDataWideLineGS);
      }
    else
      {
      shaders[vtkShader::Geometry]->SetSource("");
      }
428
    }
429
}
430

David C. Lonie's avatar
David C. Lonie committed
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//------------------------------------------------------------------------------
void vtkOpenGLPolyDataMapper::ReplaceShaderRenderPass(
    std::map<vtkShader::Type, vtkShader *> shaders, vtkRenderer *,
    vtkActor *act)
{
  std::string VSSource = shaders[vtkShader::Vertex]->GetSource();
  std::string GSSource = shaders[vtkShader::Geometry]->GetSource();
  std::string FSSource = shaders[vtkShader::Fragment]->GetSource();

  vtkInformation *info = act->GetPropertyKeys();
  if (info && info->Has(vtkOpenGLRenderPass::RenderPasses()))
    {
    int numRenderPasses = info->Length(vtkOpenGLRenderPass::RenderPasses());
    for (int i = 0; i < numRenderPasses; ++i)
      {
      vtkObjectBase *rpBase = info->Get(vtkOpenGLRenderPass::RenderPasses(), i);
      vtkOpenGLRenderPass *rp = static_cast<vtkOpenGLRenderPass*>(rpBase);
      if (!rp->ReplaceShaderValues(VSSource, GSSource, FSSource, this, act))
        {
        vtkErrorMacro("vtkOpenGLRenderPass::ReplaceShaderValues failed for "
                      << rp->GetClassName());
        }
      }
    }

  shaders[vtkShader::Vertex]->SetSource(VSSource);
  shaders[vtkShader::Geometry]->SetSource(GSSource);
  shaders[vtkShader::Fragment]->SetSource(FSSource);
}

//------------------------------------------------------------------------------
462
463
464
void vtkOpenGLPolyDataMapper::ReplaceShaderColor(
  std::map<vtkShader::Type, vtkShader *> shaders,
  vtkRenderer *, vtkActor *actor)
465
{
466
  std::string VSSource = shaders[vtkShader::Vertex]->GetSource();
467
  std::string GSSource = shaders[vtkShader::Geometry]->GetSource();
468
469
  std::string FSSource = shaders[vtkShader::Fragment]->GetSource();

470
471
472
473
474
475
476
  // crate the material/color property declarations, and VS implementation
  // these are always defined
  std::string colorDec =
    "uniform float opacityUniform; // the fragment opacity\n"
    "uniform vec3 ambientColorUniform; // intensity weighted color\n"
    "uniform vec3 diffuseColorUniform; // intensity weighted color\n";
  // add some if we have a backface property
477
  if (actor->GetBackfaceProperty() && !this->DrawingEdges)
478
479
480
481
482
483
484
    {
    colorDec +=
      "uniform float opacityUniformBF; // the fragment opacity\n"
      "uniform vec3 ambientColorUniformBF; // intensity weighted color\n"
      "uniform vec3 diffuseColorUniformBF; // intensity weighted color\n";
    }
  // add more for specular
485
  if (this->LastLightComplexity[this->LastBoundBO])
486
487
488
489
490
491
492
493
494
495
496
497
    {
    colorDec +=
      "uniform vec3 specularColorUniform; // intensity weighted color\n"
      "uniform float specularPowerUniform;\n";
    if (actor->GetBackfaceProperty())
      {
      colorDec +=
        "uniform vec3 specularColorUniformBF; // intensity weighted color\n"
        "uniform float specularPowerUniformBF;\n";
      }
    }
  // add scalar vertex coloring
498
  if (this->VBO->ColorComponents != 0 && !this->DrawingEdges)
Ken Martin's avatar
Ken Martin committed
499
    {
500
    colorDec += "varying vec4 vertexColorVSOutput;\n";
Ken Martin's avatar
Ken Martin committed
501
    vtkShaderProgram::Substitute(VSSource,"//VTK::Color::Dec",
Ken Martin's avatar
Ken Martin committed
502
                        "attribute vec4 scalarColor;\n"
503
                        "varying vec4 vertexColorVSOutput;");
Ken Martin's avatar
Ken Martin committed
504
    vtkShaderProgram::Substitute(VSSource,"//VTK::Color::Impl",
505
506
507
508
509
510
511
512
                        "vertexColorVSOutput =  scalarColor;");
    vtkShaderProgram::Substitute(GSSource,
      "//VTK::Color::Dec",
      "in vec4 vertexColorVSOutput[];\n"
      "out vec4 vertexColorGSOutput;");
    vtkShaderProgram::Substitute(GSSource,
      "//VTK::Color::Impl",
      "vertexColorGSOutput = vertexColorVSOutput[i];");
513
    }
Ken Martin's avatar
Ken Martin committed
514
  if (this->HaveCellScalars && !this->HavePickScalars && !this->DrawingEdges)
515
516
517
    {
    colorDec += "uniform samplerBuffer textureC;\n";
    }
518

Ken Martin's avatar
Ken Martin committed
519
  vtkShaderProgram::Substitute(FSSource,"//VTK::Color::Dec", colorDec);
520
521
522
523
524
525
526
527

  // now handle the more complex fragment shader implementation
  // the following are always defined variables.  We start
  // by assiging a default value from the uniform
  std::string colorImpl =
    "vec3 ambientColor;\n"
    "  vec3 diffuseColor;\n"
    "  float opacity;\n";
528
  if (this->LastLightComplexity[this->LastBoundBO])
529
530
531
532
533
    {
    colorImpl +=
      "  vec3 specularColor;\n"
      "  float specularPower;\n";
    }
534
  if (actor->GetBackfaceProperty() && !this->DrawingEdges)
535
    {
536
    if (this->LastLightComplexity[this->LastBoundBO])
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
      {
      colorImpl +=
        "  if (int(gl_FrontFacing) == 0) {\n"
        "    ambientColor = ambientColorUniformBF;\n"
        "    diffuseColor = diffuseColorUniformBF;\n"
        "    specularColor = specularColorUniformBF;\n"
        "    specularPower = specularPowerUniformBF;\n"
        "    opacity = opacityUniformBF; }\n"
        "  else {\n"
        "    ambientColor = ambientColorUniform;\n"
        "    diffuseColor = diffuseColorUniform;\n"
        "    specularColor = specularColorUniform;\n"
        "    specularPower = specularPowerUniform;\n"
        "    opacity = opacityUniform; }\n";
      }
    else
      {
      colorImpl +=
        "  if (int(gl_FrontFacing) == 0) {\n"
        "    ambientColor = ambientColorUniformBF;\n"
        "    diffuseColor = diffuseColorUniformBF;\n"
        "    opacity = opacityUniformBF; }\n"
        "  else {\n"
        "    ambientColor = ambientColorUniform;\n"
        "    diffuseColor = diffuseColorUniform;\n"
        "    opacity = opacityUniform; }\n";
      }
    }
  else
    {
    colorImpl +=
Ken Martin's avatar
Ken Martin committed
568
569
570
      "  ambientColor = ambientColorUniform;\n"
      "  diffuseColor = diffuseColorUniform;\n"
      "  opacity = opacityUniform;\n";
571
    if (this->LastLightComplexity[this->LastBoundBO])
572
573
      {
      colorImpl +=
Ken Martin's avatar
Ken Martin committed
574
575
        "  specularColor = specularColorUniform;\n"
        "  specularPower = specularPowerUniform;\n";
576
577
578
579
      }
    }

  // now handle scalar coloring
580
  if (this->VBO->ColorComponents != 0 && !this->DrawingEdges)
581
    {
Ken Martin's avatar
Ken Martin committed
582
    if (this->ScalarMaterialMode == VTK_MATERIALMODE_AMBIENT ||
Ken Martin's avatar
Ken Martin committed
583
584
        (this->ScalarMaterialMode == VTK_MATERIALMODE_DEFAULT &&
          actor->GetProperty()->GetAmbient() > actor->GetProperty()->GetDiffuse()))
Ken Martin's avatar
Ken Martin committed
585
      {
586
587
588
589
      vtkShaderProgram::Substitute(FSSource,"//VTK::Color::Impl",
        colorImpl +
        "  ambientColor = vertexColorVSOutput.rgb;\n"
        "  opacity = opacity*vertexColorVSOutput.a;");
Ken Martin's avatar
Ken Martin committed
590
591
      }
    else if (this->ScalarMaterialMode == VTK_MATERIALMODE_DIFFUSE ||
Ken Martin's avatar
Ken Martin committed
592
593
        (this->ScalarMaterialMode == VTK_MATERIALMODE_DEFAULT &&
          actor->GetProperty()->GetAmbient() <= actor->GetProperty()->GetDiffuse()))
Ken Martin's avatar
Ken Martin committed
594
      {
Ken Martin's avatar
Ken Martin committed
595
      vtkShaderProgram::Substitute(FSSource,"//VTK::Color::Impl", colorImpl +
596
597
        "  diffuseColor = vertexColorVSOutput.rgb;\n"
        "  opacity = opacity*vertexColorVSOutput.a;");
Ken Martin's avatar
Ken Martin committed
598
599
600
      }
    else
      {
Ken Martin's avatar
Ken Martin committed
601
      vtkShaderProgram::Substitute(FSSource,"//VTK::Color::Impl", colorImpl +
602
603
604
        "  diffuseColor = vertexColorVSOutput.rgb;\n"
        "  ambientColor = vertexColorVSOutput.rgb;\n"
        "  opacity = opacity*vertexColorVSOutput.a;");
Ken Martin's avatar
Ken Martin committed
605
      }
Ken Martin's avatar
Ken Martin committed
606
607
608
    }
  else
    {
Ken Martin's avatar
Ken Martin committed
609
    // are we doing scalar coloring by texture?
610
611
612
    if (this->InterpolateScalarsBeforeMapping &&
        this->ColorCoordinates &&
        !this->DrawingEdges)
Ken Martin's avatar
Ken Martin committed
613
614
615
616
617
      {
      if (this->ScalarMaterialMode == VTK_MATERIALMODE_AMBIENT ||
          (this->ScalarMaterialMode == VTK_MATERIALMODE_DEFAULT &&
            actor->GetProperty()->GetAmbient() > actor->GetProperty()->GetDiffuse()))
        {
Ken Martin's avatar
Ken Martin committed
618
        vtkShaderProgram::Substitute(FSSource,
619
620
621
622
          "//VTK::Color::Impl", colorImpl +
          "  vec4 texColor = texture2D(texture1, tcoordVCVSOutput.st);\n"
          "  ambientColor = texColor.rgb;\n"
          "  opacity = opacity*texColor.a;");
Ken Martin's avatar
Ken Martin committed
623
624
625
626
627
        }
      else if (this->ScalarMaterialMode == VTK_MATERIALMODE_DIFFUSE ||
          (this->ScalarMaterialMode == VTK_MATERIALMODE_DEFAULT &&
           actor->GetProperty()->GetAmbient() <= actor->GetProperty()->GetDiffuse()))
        {
Ken Martin's avatar
Ken Martin committed
628
        vtkShaderProgram::Substitute(FSSource,
629
630
631
632
          "//VTK::Color::Impl", colorImpl +
          "  vec4 texColor = texture2D(texture1, tcoordVCVSOutput.st);\n"
          "  diffuseColor = texColor.rgb;\n"
          "  opacity = opacity*texColor.a;");
Ken Martin's avatar
Ken Martin committed
633
634
635
        }
      else
        {
Ken Martin's avatar
Ken Martin committed
636
        vtkShaderProgram::Substitute(FSSource,
637
638
639
640
641
          "//VTK::Color::Impl", colorImpl +
          "vec4 texColor = texture2D(texture1, tcoordVCVSOutput.st);\n"
          "  ambientColor = texColor.rgb;\n"
          "  diffuseColor = texColor.rgb;\n"
          "  opacity = opacity*texColor.a;");
Ken Martin's avatar
Ken Martin committed
642
643
644
645
        }
      }
    else
      {
Ken Martin's avatar
Ken Martin committed
646
      if (this->HaveCellScalars && !this->DrawingEdges)
647
648
649
650
651
        {
        if (this->ScalarMaterialMode == VTK_MATERIALMODE_AMBIENT ||
            (this->ScalarMaterialMode == VTK_MATERIALMODE_DEFAULT &&
              actor->GetProperty()->GetAmbient() > actor->GetProperty()->GetDiffuse()))
          {
Ken Martin's avatar
Ken Martin committed
652
          vtkShaderProgram::Substitute(FSSource,
653
654
655
            "//VTK::Color::Impl", colorImpl +
            "  vec4 texColor = texelFetchBuffer(textureC, gl_PrimitiveID + PrimitiveIDOffset);\n"
            "  ambientColor = texColor.rgb;\n"
656
657
            "  opacity = opacity*texColor.a;"
            );
658
659
660
661
662
          }
        else if (this->ScalarMaterialMode == VTK_MATERIALMODE_DIFFUSE ||
            (this->ScalarMaterialMode == VTK_MATERIALMODE_DEFAULT &&
             actor->GetProperty()->GetAmbient() <= actor->GetProperty()->GetDiffuse()))
          {
Ken Martin's avatar
Ken Martin committed
663
          vtkShaderProgram::Substitute(FSSource,
664
665
666
            "//VTK::Color::Impl", colorImpl +
           "  vec4 texColor = texelFetchBuffer(textureC, gl_PrimitiveID + PrimitiveIDOffset);\n"
            "  diffuseColor = texColor.rgb;\n"
667
            "  opacity = opacity*texColor.a;"
668
            //  "  diffuseColor = vec3((gl_PrimitiveID%256)/255.0,((gl_PrimitiveID/256)%256)/255.0,1.0);\n"
669
            );
670
671
672
          }
        else
          {
Ken Martin's avatar
Ken Martin committed
673
          vtkShaderProgram::Substitute(FSSource,
674
675
676
677
            "//VTK::Color::Impl", colorImpl +
            "vec4 texColor = texelFetchBuffer(textureC, gl_PrimitiveID + PrimitiveIDOffset);\n"
            "  ambientColor = texColor.rgb;\n"
            "  diffuseColor = texColor.rgb;\n"
678
679
            "  opacity = opacity*texColor.a;"
            );
680
681
          }
        }
Ken Martin's avatar
Ken Martin committed
682
      vtkShaderProgram::Substitute(FSSource,"//VTK::Color::Impl", colorImpl);
Ken Martin's avatar
Ken Martin committed
683
      }
Ken Martin's avatar
Ken Martin committed
684
    }
685
686

  shaders[vtkShader::Vertex]->SetSource(VSSource);
687
  shaders[vtkShader::Geometry]->SetSource(GSSource);
688
  shaders[vtkShader::Fragment]->SetSource(FSSource);
689
690
}

691
692
void vtkOpenGLPolyDataMapper::ReplaceShaderLight(
  std::map<vtkShader::Type, vtkShader *> shaders,
Ken Martin's avatar
Ken Martin committed
693
  vtkRenderer *, vtkActor *actor)
694
{
695
696
  std::string FSSource = shaders[vtkShader::Fragment]->GetSource();

697
  // check for normal rendering
Ken Martin's avatar
Ken Martin committed
698
  vtkInformation *info = actor->GetPropertyKeys();
699
700
701
702
703
704
705
706
707
708
709
  if (info && info->Has(vtkLightingMapPass::RENDER_NORMALS()))
      {
      vtkShaderProgram::Substitute(FSSource,"//VTK::Light::Impl",
        "  vec3 n = (normalVCVSOutput + 1.0) * 0.5;\n"
        "  gl_FragData[0] = vec4(n.x, n.y, n.z, 1.0);"
      );
      shaders[vtkShader::Fragment]->SetSource(FSSource);
      return;
      }

  // check for shadow maps
Ken Martin's avatar
Ken Martin committed
710
  std::string shadowFactor = "";
Ken Martin's avatar
Ken Martin committed
711
  if (info && info->Has(vtkShadowMapPass::ShadowMapPass()))
Ken Martin's avatar
Ken Martin committed
712
    {
Ken Martin's avatar
Ken Martin committed
713
714
715
    vtkShadowMapPass *smp = vtkShadowMapPass::SafeDownCast(
      info->Get(vtkShadowMapPass::ShadowMapPass()));
    if (smp)
Ken Martin's avatar
Ken Martin committed
716
      {
Ken Martin's avatar
Ken Martin committed
717
718
719
720
721
      vtkShaderProgram::Substitute(FSSource,"//VTK::Light::Dec",
        smp->GetFragmentDeclaration(), false);
      vtkShaderProgram::Substitute(FSSource,"//VTK::Light::Impl",
        smp->GetFragmentImplementation(), false);
      shadowFactor = "*factors[lightNum]";
Ken Martin's avatar
Ken Martin committed
722
723
724
      }
    }

725
726
727
728
729
730
731
732
733
734
735
  // If rendering, set diffuse and specular colors to pure white
  if (info && info->Has(vtkLightingMapPass::RENDER_LUMINANCE()))
    {
      vtkShaderProgram::Substitute(FSSource, "//VTK::Light::Impl",
        "  diffuseColor = vec3(1, 1, 1);\n"
        "  specularColor = vec3(1, 1, 1);\n"
        "  //VTK::Light::Impl\n",
        false
      );
    }

Tim Thirion's avatar
Tim Thirion committed
736
737
  int lastLightComplexity = this->LastLightComplexity[this->LastBoundBO];
  if (info && info->Has(vtkValuePass::RENDER_VALUES()))
738
    {
Tim Thirion's avatar
Tim Thirion committed
739
740
741
742
743
744
    lastLightComplexity = 0;
    }

  switch (lastLightComplexity)
    {
    case 0: // no lighting or RENDER_VALUES
745
746
747
748
      vtkShaderProgram::Substitute(FSSource, "//VTK::Light::Impl",
        "  gl_FragData[0] = vec4(ambientColor + diffuseColor, opacity);\n"
        "  //VTK::Light::Impl\n",
        false
749
750
751
752
        );
      break;

    case 1:  // headlight
753
754
      vtkShaderProgram::Substitute(FSSource, "//VTK::Light::Impl",
        "  float df = max(0.0, normalVCVSOutput.z);\n"
755
756
757
        "  float sf = pow(df, specularPower);\n"
        "  vec3 diffuse = df * diffuseColor;\n"
        "  vec3 specular = sf * specularColor;\n"
758
759
760
761
        "  gl_FragData[0] = vec4(ambientColor + diffuse + specular, opacity);\n"
        "  //VTK::Light::Impl\n",
        false
      );
762
      break;
763

764
    case 2: // light kit
Ken Martin's avatar
Ken Martin committed
765
      vtkShaderProgram::Substitute(FSSource,"//VTK::Light::Dec",
766
767
768
769
770
771
        // only allow for up to 6 active lights
        "uniform int numberOfLights;\n"
        // intensity weighted color
        "uniform vec3 lightColor[6];\n"
        "uniform vec3 lightDirectionVC[6]; // normalized\n"
        "uniform vec3 lightHalfAngleVC[6]; // normalized"
772
      );
Ken Martin's avatar
Ken Martin committed
773
      vtkShaderProgram::Substitute(FSSource,"//VTK::Light::Impl",
774
775
776
777
        "vec3 diffuse = vec3(0,0,0);\n"
        "  vec3 specular = vec3(0,0,0);\n"
        "  for (int lightNum = 0; lightNum < numberOfLights; lightNum++)\n"
        "    {\n"
778
        "    float df = max(0.0, dot(normalVCVSOutput, -lightDirectionVC[lightNum]));\n"
Ken Martin's avatar
Ken Martin committed
779
        "    diffuse += ((df" + shadowFactor + ") * lightColor[lightNum]);\n"
780
        "    if (dot(normalVCVSOutput, lightDirectionVC[lightNum]) < 0.0)\n"
781
        "      {\n"
782
        "      float sf = pow( max(0.0, dot(lightHalfAngleVC[lightNum],normalVCVSOutput)), specularPower);\n"
Ken Martin's avatar
Ken Martin committed
783
        "      specular += ((sf" + shadowFactor + ") * lightColor[lightNum]);\n"
784
785
786
787
        "      }\n"
        "    }\n"
        "  diffuse = diffuse * diffuseColor;\n"
        "  specular = specular * specularColor;\n"
788
789
790
791
        "  gl_FragData[0] = vec4(ambientColor + diffuse + specular, opacity);"
        "  //VTK::Light::Impl",
        false
      );
792
793
794
      break;

    case 3: // positional
Ken Martin's avatar
Ken Martin committed
795
      vtkShaderProgram::Substitute(FSSource,"//VTK::Light::Dec",
796
797
798
799
800
801
802
803
804
805
806
        // only allow for up to 6 active lights
        "uniform int numberOfLights;\n"
        // intensity weighted color
        "uniform vec3 lightColor[6];\n"
        "uniform vec3 lightDirectionVC[6]; // normalized\n"
        "uniform vec3 lightHalfAngleVC[6]; // normalized\n"
        "uniform vec3 lightPositionVC[6];\n"
        "uniform vec3 lightAttenuation[6];\n"
        "uniform float lightConeAngle[6];\n"
        "uniform float lightExponent[6];\n"
        "uniform int lightPositional[6];"
807
      );
Ken Martin's avatar
Ken Martin committed
808
      vtkShaderProgram::Substitute(FSSource,"//VTK::Light::Impl",
809
810
811
812
813
814
815
816
817
818
819
820
        "  vec3 diffuse = vec3(0,0,0);\n"
        "  vec3 specular = vec3(0,0,0);\n"
        "  vec3 vertLightDirectionVC;\n"
        "  for (int lightNum = 0; lightNum < numberOfLights; lightNum++)\n"
        "    {\n"
        "    float attenuation = 1.0;\n"
        "    if (lightPositional[lightNum] == 0)\n"
        "      {\n"
        "      vertLightDirectionVC = lightDirectionVC[lightNum];\n"
        "      }\n"
        "    else\n"
        "      {\n"
Ken Martin's avatar
Ken Martin committed
821
        "      vertLightDirectionVC = vertexVC.xyz - lightPositionVC[lightNum];\n"
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
        "      float distanceVC = length(vertLightDirectionVC);\n"
        "      vertLightDirectionVC = normalize(vertLightDirectionVC);\n"
        "      attenuation = 1.0 /\n"
        "        (lightAttenuation[lightNum].x\n"
        "         + lightAttenuation[lightNum].y * distanceVC\n"
        "         + lightAttenuation[lightNum].z * distanceVC * distanceVC);\n"
        "      // per OpenGL standard cone angle is 90 or less for a spot light\n"
        "      if (lightConeAngle[lightNum] <= 90.0)\n"
        "        {\n"
        "        float coneDot = dot(vertLightDirectionVC, lightDirectionVC[lightNum]);\n"
        "        // if inside the cone\n"
        "        if (coneDot >= cos(radians(lightConeAngle[lightNum])))\n"
        "          {\n"
        "          attenuation = attenuation * pow(coneDot, lightExponent[lightNum]);\n"
        "          }\n"
        "        else\n"
        "          {\n"
        "          attenuation = 0.0;\n"
        "          }\n"
        "        }\n"
        "      }\n"
843
        "    float df = max(0.0, attenuation*dot(normalVCVSOutput, -vertLightDirectionVC));\n"
Ken Martin's avatar
Ken Martin committed
844
        "    diffuse += ((df" + shadowFactor + ") * lightColor[lightNum]);\n"
845
        "    if (dot(normalVCVSOutput, vertLightDirectionVC) < 0.0)\n"
846
        "      {\n"
847
        "      float sf = attenuation*pow( max(0.0, dot(lightHalfAngleVC[lightNum],normalVCVSOutput)), specularPower);\n"
Ken Martin's avatar
Ken Martin committed
848
        "      specular += ((sf" + shadowFactor + ") * lightColor[lightNum]);\n"
849
850
851
852
        "      }\n"
        "    }\n"
        "  diffuse = diffuse * diffuseColor;\n"
        "  specular = specular * specularColor;\n"
853
854
855
        "  gl_FragData[0] = vec4(ambientColor + diffuse + specular, opacity);\n"
        "  //VTK::Light::Impl",
        false
856
857
858
        );
      break;
    }
859

860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
  // If rendering luminance values, write those values to the fragment
  if (info && info->Has(vtkLightingMapPass::RENDER_LUMINANCE()))
  {
    switch (this->LastLightComplexity[this->LastBoundBO])
    {
      case 0: // no lighting
        vtkShaderProgram::Substitute(FSSource, "//VTK::Light::Impl",
          "  gl_FragData[0] = vec4(0.0, 0.0, 0.0, 1.0);"
        );
        break;
      case 1: // headlight
      case 2: // light kit
      case 3: // positional
        vtkShaderProgram::Substitute(FSSource, "//VTK::Light::Impl",
          "  float ambientY = dot(vec3(0.2126, 0.7152, 0.0722), ambientColor);\n"
          "  gl_FragData[0] = vec4(ambientY, diffuse.x, specular.x, 1.0);"
        );
        break;
    }
  }

881
  shaders[vtkShader::Fragment]->SetSource(FSSource);
882
883
}

884
885
886
void vtkOpenGLPolyDataMapper::ReplaceShaderTCoord(
  std::map<vtkShader::Type, vtkShader *> shaders,
  vtkRenderer *, vtkActor *actor)
887
{
888
889
890
891
892
  if (this->DrawingEdges)
    {
    return;
    }

893
  std::string VSSource = shaders[vtkShader::Vertex]->GetSource();
894
  std::string GSSource = shaders[vtkShader::Geometry]->GetSource();
895
  std::string FSSource = shaders[vtkShader::Fragment]->GetSource();
896

Ken Martin's avatar
Ken Martin committed
897
  if (this->VBO->TCoordComponents)
Ken Martin's avatar
Ken Martin committed
898
    {
899
900
    vtkInformation *info = actor->GetPropertyKeys();
    if (info && info->Has(vtkProp::GeneralTextureTransform()))
Ken Martin's avatar
Ken Martin committed
901
      {
Ken Martin's avatar
Ken Martin committed
902
      vtkShaderProgram::Substitute(VSSource, "//VTK::TCoord::Dec",
903
904
905
        "//VTK::TCoord::Dec\n"
        "uniform mat4 tcMatrix;",
        false);
Ken Martin's avatar
Ken Martin committed
906
      if (this->VBO->TCoordComponents == 1)
907
        {
Ken Martin's avatar
Ken Martin committed
908
        vtkShaderProgram::Substitute(VSSource, "//VTK::TCoord::Impl",
909
          "vec4 tcoordTmp = tcMatrix*vec4(tcoordMC,0.0,0.0,1.0);\n"
910
          "tcoordVCVSOutput = tcoordTmp.x/tcoordTmp.w;");
911
912
913
        }
      else
        {
Ken Martin's avatar
Ken Martin committed
914
        vtkShaderProgram::Substitute(VSSource, "//VTK::TCoord::Impl",
915
          "vec4 tcoordTmp = tcMatrix*vec4(tcoordMC,0.0,1.0);\n"
916
          "tcoordVCVSOutput = tcoordTmp.xy/tcoordTmp.w;");
917
918
919
920
        }
      }
    else
      {
Ken Martin's avatar
Ken Martin committed
921
      vtkShaderProgram::Substitute(VSSource, "//VTK::TCoord::Impl",
922
        "tcoordVCVSOutput = tcoordMC;");
923
924
      }

925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
    int tNumComp = 4;
    vtkTexture *texture = actor->GetTexture();
    if (this->ColorTextureMap)
      {
      texture = this->InternalColorTexture;
      }
    if (!texture && actor->GetProperty()->GetNumberOfTextures())
      {
      texture = actor->GetProperty()->GetTexture(0);
      }
    if (texture)
      {
      tNumComp =
        vtkOpenGLTexture::SafeDownCast(texture)->
          GetTextureObject()->GetComponents();
      }

Ken Martin's avatar
Ken Martin committed
942
    if (this->VBO->TCoordComponents == 1)
943
      {
Ken Martin's avatar
Ken Martin committed
944
      vtkShaderProgram::Substitute(VSSource, "//VTK::TCoord::Dec",
945
946
947
948
949
950
951
952
        "attribute float tcoordMC; varying float tcoordVCVSOutput;");
      vtkShaderProgram::Substitute(GSSource,
        "//VTK::TCoord::Dec",
        "in float tcoordVCVSOutput[];\n"
        "out float tcoordVCGSOutput;");
      vtkShaderProgram::Substitute(GSSource,
        "//VTK::TCoord::Impl",
        "tcoordVCGSOutput = tcoordVCVSOutput[i];");
Ken Martin's avatar
Ken Martin committed
953
      vtkShaderProgram::Substitute(FSSource, "//VTK::TCoord::Dec",
954
955
        "varying float tcoordVCVSOutput;\n"
        "uniform sampler2D texture1;");
956
957
958
      switch (tNumComp)
        {
        case 1:
Ken Martin's avatar
Ken Martin committed
959
          vtkShaderProgram::Substitute(FSSource, "//VTK::TCoord::Impl",
960
            "vec4 tcolor = texture2D(texture1, vec2(tcoordVCVSOutput,0.0));\n"
961
962
963
964
            "gl_FragData[0] = clamp(gl_FragData[0],0.0,1.0)*\n"
            "  vec4(tcolor.r,tcolor.r,tcolor.r,1.0);");
          break;
        case 2:
Ken Martin's avatar
Ken Martin committed
965
          vtkShaderProgram::Substitute(FSSource, "//VTK::TCoord::Impl",
966
            "vec4 tcolor = texture2D(texture1, vec2(tcoordVCVSOutput,0.0));\n"
967
968
969
970
            "gl_FragData[0] = clamp(gl_FragData[0],0.0,1.0)*\n"
            "  vec4(tcolor.r,tcolor.r,tcolor.r,tcolor.g);");
          break;
        default:
Ken Martin's avatar
Ken Martin committed
971
          vtkShaderProgram::Substitute(FSSource, "//VTK::TCoord::Impl",
972
            "gl_FragData[0] = clamp(gl_FragData[0],0.0,1.0)*texture2D(texture1, vec2(tcoordVCVSOutput,0.0));");
973
        }
Ken Martin's avatar
Ken Martin committed
974
      }
Ken Martin's avatar
Ken Martin committed
975
976
    else
      {
Ken Martin's avatar
Ken Martin committed
977
      vtkShaderProgram::Substitute(VSSource, "//VTK::TCoord::Dec",
978
979
980
981
982
983
984
985
        "attribute vec2 tcoordMC; varying vec2 tcoordVCVSOutput;");
      vtkShaderProgram::Substitute(GSSource,
        "//VTK::TCoord::Dec",
        "in vec2 tcoordVCVSOutput[];\n"
        "out vec2 tcoordVCGSOutput;");
      vtkShaderProgram::Substitute(GSSource,
        "//VTK::TCoord::Impl",
        "tcoordVCGSOutput = tcoordVCVSOutput[i];");
Ken Martin's avatar
Ken Martin committed
986
      vtkShaderProgram::Substitute(FSSource, "//VTK::TCoord::Dec",
987
        "varying vec2 tcoordVCVSOutput; uniform sampler2D texture1;");
988
989
      // do texture mapping except for scalar coloring case which is
      // handled above
Ken Martin's avatar
Ken Martin committed
990
991
      if (!this->InterpolateScalarsBeforeMapping || !this->ColorCoordinates)
        {
992
993
994
        switch (tNumComp)
          {
          case 1:
Ken Martin's avatar
Ken Martin committed
995
            vtkShaderProgram::Substitute(FSSource, "//VTK::TCoord::Impl",
996
              "vec4 tcolor = texture2D(texture1, tcoordVCVSOutput);\n"
997
998
999
1000
              "gl_FragData[0] = clamp(gl_FragData[0],0.0,1.0)*\n"
              "  vec4(tcolor.r,tcolor.r,tcolor.r,1.0);");
            break;
          case 2:
Ken Martin's avatar
Ken Martin committed
1001
            vtkShaderProgram::Substitute(FSSource, "//VTK::TCoord::Impl",
1002
              "vec4 tcolor = texture2D(texture1, tcoordVCVSOutput);\n"
1003
1004
1005
1006
              "gl_FragData[0] = clamp(gl_FragData[0],0.0,1.0)*\n"
              "  vec4(tcolor.r,tcolor.r,tcolor.r,tcolor.g);");
            break;
          default:
Ken Martin's avatar
Ken Martin committed
1007
            vtkShaderProgram::Substitute(FSSource, "//VTK::TCoord::Impl",
1008
              "gl_FragData[0] = clamp(gl_FragData[0],0.0,1.0)*texture2D(texture1, tcoordVCVSOutput.st);");
1009
          }
Ken Martin's avatar
Ken Martin committed
1010
        }
Ken Martin's avatar
Ken Martin committed
1011
1012
1013
      }
    }

1014
  shaders[vtkShader::Vertex]->SetSource(VSSource);
1015
  shaders[vtkShader::Geometry]->SetSource(GSSource);
1016
1017
1018
1019
1020
1021
1022
1023
1024
  shaders[vtkShader::Fragment]->SetSource(FSSource);
}

void vtkOpenGLPolyDataMapper::ReplaceShaderPicking(
  std::map<vtkShader::Type, vtkShader *> shaders,
  vtkRenderer *, vtkActor *)
{
  std::string FSSource = shaders[vtkShader::Fragment]->GetSource();

1025
  if (this->LastSelectionState >= vtkHardwareSelector::MIN_KNOWN_PASS)
1026
    {
1027
1028
    if (this->HavePickScalars)
      {
Ken Martin's avatar
Ken Martin committed
1029
      vtkShaderProgram::Substitute(FSSource,
1030
1031
        "//VTK::Picking::Dec",
        "uniform samplerBuffer textureC;");
Ken Martin's avatar
Ken Martin committed
1032
      vtkShaderProgram::Substitute(FSSource, "//VTK::Picking::Impl",
1033
1034
1035
1036
1037
        "  gl_FragData[0] = texelFetchBuffer(textureC, gl_PrimitiveID + PrimitiveIDOffset);\n"
        );
      }
    else
      {
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
      switch (this->LastSelectionState)
        {
        case vtkHardwareSelector::ID_LOW24:
          vtkShaderProgram::Substitute(FSSource,
          "//VTK::Picking::Impl",
          "  int idx = gl_PrimitiveID + 1 + PrimitiveIDOffset;\n"
          "  gl_FragData[0] = vec4(float(idx%256)/255.0, float((idx/256)%256)/255.0, float((idx/65536)%256)/255.0, 1.0);\n");
        break;
        case vtkHardwareSelector::ID_MID24:
          // this may yerk on openGL ES 2.0 so no really huge meshes in ES 2.0 OK
          vtkShaderProgram::Substitute(FSSource,
          "//VTK::Picking::Impl",
          "  int idx = (gl_PrimitiveID + 1 + PrimitiveIDOffset);\n idx = ((idx & 0xff000000) >> 24);\n"
          "  gl_FragData[0] = vec4(float(idx%256)/255.0, float((idx/256)%256)/255.0, float(idx/65536)/255.0, 1.0);\n");
        break;
        default:
          vtkShaderProgram::Substitute(FSSource, "//VTK::Picking::Dec",
            "uniform vec3 mapperIndex;");
          vtkShaderProgram::Substitute(FSSource,
            "//VTK::Picking::Impl",
            "  gl_FragData[0] = vec4(mapperIndex,1.0);\n");
        }
1060
      }
1061
    }
1062
1063
1064
1065
1066
1067
1068
1069
1070
  shaders[vtkShader::Fragment]->SetSource(FSSource);
}

void vtkOpenGLPolyDataMapper::ReplaceShaderClip(
  std::map<vtkShader::Type, vtkShader *> shaders,
  vtkRenderer *, vtkActor *)
{
  std::string VSSource = shaders[vtkShader::Vertex]->GetSource();
  std::string FSSource = shaders[vtkShader::Fragment]->GetSource();
Ken Martin's avatar
Ken Martin committed
1071

1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
  if (this->GetNumberOfClippingPlanes())
    {
    // add all the clipping planes
    int numClipPlanes = this->GetNumberOfClippingPlanes();
    if (numClipPlanes > 6)
      {
      vtkErrorMacro(<< "OpenGL has a limit of 6 clipping planes");
      numClipPlanes = 6;
      }

Ken Martin's avatar
Ken Martin committed
1082
    vtkShaderProgram::Substitute(VSSource, "//VTK::Clip::Dec",
1083
1084
      "uniform int numClipPlanes;\n"
      "uniform vec4 clipPlanes[6];\n"
1085
      "varying float clipDistancesVSOutput[6];");
Ken Martin's avatar
Ken Martin committed
1086
    vtkShaderProgram::Substitute(VSSource, "//VTK::Clip::Impl",
1087
1088
      "for (int planeNum = 0; planeNum < numClipPlanes; planeNum++)\n"
      "    {\n"
1089
      "    clipDistancesVSOutput[planeNum] = dot(clipPlanes[planeNum], vertexMC);\n"
1090
      "    }\n");
Ken Martin's avatar
Ken Martin committed
1091
    vtkShaderProgram::Substitute(FSSource, "//VTK::Clip::Dec",
1092
      "uniform int numClipPlanes;\n"
1093
      "varying float clipDistancesVSOutput[6];");
Ken Martin's avatar
Ken Martin committed
1094
    vtkShaderProgram::Substitute(FSSource, "//VTK::Clip::Impl",
1095
1096
      "for (int planeNum = 0; planeNum < numClipPlanes; planeNum++)\n"
      "    {\n"
1097
      "    if (clipDistancesVSOutput[planeNum] < 0.0) discard;\n"
1098
      "    }\n");
1099
    }
1100
1101
1102
1103
1104
1105
1106
1107
  shaders[vtkShader::Vertex]->SetSource(VSSource);
  shaders[vtkShader::Fragment]->SetSource(FSSource);
}

void vtkOpenGLPolyDataMapper::ReplaceShaderNormal(
  std::map<vtkShader::Type, vtkShader *> shaders,
  vtkRenderer *, vtkActor *actor)
{
1108
  if (this->LastLightComplexity[this->LastBoundBO] > 0)
1109
1110
    {
    std::string VSSource = shaders[vtkShader::Vertex]->GetSource();
1111
    std::string GSSource = shaders[vtkShader::Geometry]->GetSource();
1112
1113
1114
1115
    std::string FSSource = shaders[vtkShader::Fragment]->GetSource();

    if (this->VBO->NormalOffset)
      {
1116
      vtkShaderProgram::Substitute(VSSource,
1117
1118
1119
        "//VTK::Normal::Dec",
        "attribute vec3 normalMC;\n"
        "uniform mat3 normalMatrix;\n"
1120
        "varying vec3 normalVCVSOutput;");
1121
1122
      vtkShaderProgram::Substitute(VSSource,
        "//VTK::Normal::Impl",
1123
1124
1125
1126
1127
1128
1129
1130
        "normalVCVSOutput = normalMatrix * normalMC;");
      vtkShaderProgram::Substitute(GSSource,
        "//VTK::Normal::Dec",
        "in vec3 normalVCVSOutput[];\n"
        "out vec3 normalVCGSOutput;");
      vtkShaderProgram::Substitute(GSSource,
        "//VTK::Normal::Impl",
        "normalVCGSOutput = normalVCVSOutput[i];");
1131
1132
      vtkShaderProgram::Substitute(FSSource,
        "//VTK::Normal::Dec",
1133
        "varying vec3 normalVCVSOutput;");
1134
1135
      vtkShaderProgram::Substitute(FSSource,
        "//VTK::Normal::Impl",
1136
        "vec3 normalVCVSOutput = normalize(normalVCVSOutput);\n"
1137
1138
        //  if (!gl_FrontFacing) does not work in intel hd4000 mac
        //  if (int(gl_FrontFacing) == 0) does not work on mesa
1139
        "  if (gl_FrontFacing == false) { normalVCVSOutput = -normalVCVSOutput; }\n"
1140
1141
1142
1143
1144
1145
1146
        //"normalVC = normalVCVarying;"
        );
      }
    else
      {
      if (this->HaveCellNormals)
        {
1147
1148
1149
1150
        vtkShaderProgram::Substitute(FSSource,
          "//VTK::Normal::Dec",
          "uniform mat3 normalMatrix;\n"
          "uniform samplerBuffer textureN;\n");
1151
1152
        vtkShaderProgram::Substitute(FSSource,
          "//VTK::Normal::Impl",
1153
          "vec3 normalVCVSOutput = normalize(normalMatrix *\n"
1154
          "    texelFetchBuffer(textureN, gl_PrimitiveID + PrimitiveIDOffset).xyz);\n"
1155
          "  if (gl_FrontFacing == false) { normalVCVSOutput = -normalVCVSOutput; }\n"
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
          );
        }
      else
        {
        if (actor->GetProperty()->GetRepresentation() == VTK_WIREFRAME)
          {
          // generate a normal for lines, it will be perpendicular to the line
          // and maximally aligned with the camera view direction
          // no clue if this is the best way to do this.
          // the code below has been optimized a bit so what follows is
          // an explanation of the basic approach. Compute the gradient of the line
          // with respect to x and y, the the larger of the two
          // cross that with the camera view direction. That gives a vector
          // orthogonal to the camera view and the line. Note that the line and the camera
          // view are probably not orthogonal. Which is why when we cross result that with
          // the line gradient again we get a reasonable normal. It will be othogonal to
          // the line (which is a plane but maximally aligned with the camera view.
David C. Lonie's avatar
David C. Lonie committed
1173
1174
1175
1176
1177
1178
          vtkShaderProgram::Substitute(
                FSSource,"//VTK::UniformFlow::Impl",
                "  vec3 fdx = vec3(dFdx(vertexVC.x),dFdx(vertexVC.y),dFdx(vertexVC.z));\n"
                "  vec3 fdy = vec3(dFdy(vertexVC.x),dFdy(vertexVC.y),dFdy(vertexVC.z));\n"
                "  //VTK::UniformFlow::Impl\n" // For further replacements
                );
1179
          vtkShaderProgram::Substitute(FSSource,"//VTK::Normal::Impl",
1180
            "vec3 normalVCVSOutput;\n"
David C. Lonie's avatar
David C. Lonie committed
1181
1182
            "  fdx = normalize(fdx);\n"
            "  fdy = normalize(fdy);\n"
1183
            "  if (abs(fdx.x) > 0.0)\n"
1184
1185
            "    { normalVCVSOutput = normalize(cross(vec3(fdx.y, -fdx.x, 0.0), fdx)); }\n"
            "  else { normalVCVSOutput = normalize(cross(vec3(fdy.y, -fdy.x, 0.0), fdy));}"
Ken Martin's avatar