Salome HOME
Merge remote-tracking branch 'origin/vsr/fix_single_study_pb' into pre/fix_single_study
[modules/gui.git] / src / VTKViewer / VTKViewer_PolyDataMapper.cxx
1 // Copyright (C) 2007-2014  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include "VTKViewer_PolyDataMapper.h"
21 #include "VTKViewer_MarkerUtils.h"
22
23 #include <utilities.h>
24
25 #include <QString>
26
27 #include <vtkCellArray.h>
28 #include <vtkXMLImageDataReader.h>
29 #include <vtkImageData.h>
30 #include <vtkObjectFactory.h>
31 #include <vtkPointData.h>
32 #include <vtkPolyData.h>
33 #include <vtkProperty.h>
34 #include <vtkRenderer.h>
35 #include <vtkSmartPointer.h>
36 #include <vtkTimerLog.h>
37 #include <vtkWindow.h>
38 #include <vtkRenderWindow.h>
39 #include <vtkCommand.h>
40 #include <vtkCellData.h>
41
42 #ifndef WIN32
43 # ifndef GLX_GLXEXT_LEGACY
44 #  define GLX_GLXEXT_LEGACY
45 # endif
46 # include <GL/glx.h>
47 # include <dlfcn.h>
48 #else
49 # include <wingdi.h>
50 #endif
51
52 #ifndef VTK_IMPLEMENT_MESA_CXX
53 vtkStandardNewMacro(VTKViewer_PolyDataMapper);
54 #endif
55
56 // some definitions for what the polydata has in it
57 #define VTK_PDPSM_COLORS             0x0001
58 #define VTK_PDPSM_CELL_COLORS        0x0002
59 #define VTK_PDPSM_POINT_TYPE_FLOAT   0x0004
60 #define VTK_PDPSM_POINT_TYPE_DOUBLE  0x0008
61 #define VTK_PDPSM_NORMAL_TYPE_FLOAT  0x0010
62 #define VTK_PDPSM_NORMAL_TYPE_DOUBLE 0x0020
63 #define VTK_PDPSM_OPAQUE_COLORS      0x0040
64
65 #ifndef APIENTRY
66 #define APIENTRY
67 #endif
68 #ifndef APIENTRYP
69 #define APIENTRYP APIENTRY *
70 #endif
71
72 #ifndef GL_ARB_shader_objects
73 typedef char GLcharARB;
74 #endif
75
76 #ifndef GL_VERTEX_PROGRAM_POINT_SIZE_ARB
77 #define GL_VERTEX_PROGRAM_POINT_SIZE_ARB  0x8642
78 #endif
79
80 #ifndef GL_VERTEX_SHADER_ARB
81 #define GL_VERTEX_SHADER_ARB              0x8B31
82 #endif
83
84 #ifndef GL_ARB_point_sprite
85 #define GL_POINT_SPRITE_ARB               0x8861
86 #define GL_COORD_REPLACE_ARB              0x8862
87 #endif
88
89 #ifndef GL_ARB_vertex_buffer_object
90 typedef ptrdiff_t GLsizeiptrARB;
91
92 #define GL_ARRAY_BUFFER_ARB               0x8892
93 #define GL_STATIC_DRAW_ARB                0x88E4
94 #endif
95 typedef void (APIENTRYP PFNGLSHADERSOURCEARBPROC) (GLhandleARB shaderObj, GLsizei count, const GLcharARB* *string, const GLint *length);
96 typedef GLhandleARB (APIENTRYP PFNGLCREATESHADEROBJECTARBPROC) (GLenum shaderType);
97 typedef void (APIENTRYP PFNGLBINDBUFFERARBPROC) (GLenum target, GLuint buffer);
98 typedef void (APIENTRYP PFNGLDELETEBUFFERSARBPROC) (GLsizei n, const GLuint *buffers);
99 typedef void (APIENTRYP PFNGLGENBUFFERSARBPROC) (GLsizei n, GLuint *buffers);
100 typedef void (APIENTRYP PFNGLBUFFERDATAARBPROC) (GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage);
101 typedef void (APIENTRYP PFNGLCOMPILESHADERARBPROC) (GLhandleARB shaderObj);
102 typedef GLhandleARB (APIENTRYP PFNGLCREATEPROGRAMOBJECTARBPROC) (void);
103 typedef void (APIENTRYP PFNGLATTACHOBJECTARBPROC) (GLhandleARB containerObj, GLhandleARB obj);
104 typedef void (APIENTRYP PFNGLLINKPROGRAMARBPROC) (GLhandleARB programObj);
105 typedef void (APIENTRYP PFNGLUSEPROGRAMOBJECTARBPROC) (GLhandleARB programObj);
106 typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONARBPROC) (GLhandleARB programObj, const GLcharARB *name);
107 typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERARBPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer);
108 typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYARBPROC) (GLuint index);
109 typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYARBPROC) (GLuint index);
110
111 typedef GLfloat TBall; 
112
113
114 static PFNGLSHADERSOURCEARBPROC             vglShaderSourceARB             = NULL;
115 static PFNGLCREATESHADEROBJECTARBPROC       vglCreateShaderObjectARB       = NULL;
116 static PFNGLCOMPILESHADERARBPROC            vglCompileShaderARB            = NULL;
117 static PFNGLCREATEPROGRAMOBJECTARBPROC      vglCreateProgramObjectARB      = NULL;
118 static PFNGLATTACHOBJECTARBPROC             vglAttachObjectARB             = NULL;
119 static PFNGLLINKPROGRAMARBPROC              vglLinkProgramARB              = NULL;
120 static PFNGLUSEPROGRAMOBJECTARBPROC         vglUseProgramObjectARB         = NULL;
121
122 static PFNGLGENBUFFERSARBPROC               vglGenBuffersARB               = NULL;
123 static PFNGLBINDBUFFERARBPROC               vglBindBufferARB               = NULL;
124 static PFNGLBUFFERDATAARBPROC               vglBufferDataARB               = NULL;
125 static PFNGLDELETEBUFFERSARBPROC            vglDeleteBuffersARB            = NULL;
126 static PFNGLGETATTRIBLOCATIONARBPROC        vglGetAttribLocationARB        = NULL;
127 static PFNGLVERTEXATTRIBPOINTERARBPROC      vglVertexAttribPointerARB      = NULL;
128 static PFNGLENABLEVERTEXATTRIBARRAYARBPROC  vglEnableVertexAttribArrayARB  = NULL;
129 static PFNGLDISABLEVERTEXATTRIBARRAYARBPROC vglDisableVertexAttribArrayARB = NULL;
130
131
132 #ifndef WIN32
133 #define GL_GetProcAddress( x )   glXGetProcAddressARB( (const GLubyte*)x )
134 #else
135 #define GL_GetProcAddress( x )   wglGetProcAddress( (const LPCSTR)x )
136 #endif
137
138 #ifdef WIN32
139   #ifdef max
140     #undef max
141   #endif
142 #endif
143
144 // ----------------------------------------------- Special Textures -----------------------------------
145 // texture id for balls drawing
146 #define BallTextureId 0 
147
148 bool InitializeBufferExtensions()
149 {
150   vglShaderSourceARB = (PFNGLSHADERSOURCEARBPROC)GL_GetProcAddress( "glShaderSourceARB" );
151   if( !vglShaderSourceARB )
152     return false;
153
154   vglCreateShaderObjectARB = (PFNGLCREATESHADEROBJECTARBPROC)GL_GetProcAddress( "glCreateShaderObjectARB" );
155   if( !vglCreateShaderObjectARB )
156     return false;
157
158   vglCompileShaderARB = (PFNGLCOMPILESHADERARBPROC)GL_GetProcAddress( "glCompileShaderARB" );
159   if( !vglCompileShaderARB )
160     return false;
161
162   vglCreateProgramObjectARB = (PFNGLCREATEPROGRAMOBJECTARBPROC)GL_GetProcAddress( "glCreateProgramObjectARB" );
163   if( !vglCreateProgramObjectARB )
164     return false;
165
166   vglAttachObjectARB = (PFNGLATTACHOBJECTARBPROC)GL_GetProcAddress( "glAttachObjectARB" );
167   if( !vglAttachObjectARB )
168     return false;
169
170   vglLinkProgramARB = (PFNGLLINKPROGRAMARBPROC)GL_GetProcAddress( "glLinkProgramARB" );
171   if( !vglLinkProgramARB )
172     return false;
173
174   vglUseProgramObjectARB = (PFNGLUSEPROGRAMOBJECTARBPROC)GL_GetProcAddress( "glUseProgramObjectARB" );
175   if( !vglUseProgramObjectARB )
176     return false;
177
178   vglGenBuffersARB = (PFNGLGENBUFFERSARBPROC)GL_GetProcAddress( "glGenBuffersARB" );
179   if( !vglGenBuffersARB )
180     return false;
181
182   vglBindBufferARB = (PFNGLBINDBUFFERARBPROC)GL_GetProcAddress( "glBindBufferARB" );
183   if( !vglBindBufferARB )
184     return false;
185
186   vglBufferDataARB = (PFNGLBUFFERDATAARBPROC)GL_GetProcAddress( "glBufferDataARB" );
187   if( !vglBufferDataARB )
188     return false;
189
190   vglDeleteBuffersARB = (PFNGLDELETEBUFFERSARBPROC)GL_GetProcAddress( "glDeleteBuffersARB" );
191   if( !vglDeleteBuffersARB )
192     return false;
193
194   vglGetAttribLocationARB = (PFNGLGETATTRIBLOCATIONARBPROC)GL_GetProcAddress( "glGetAttribLocation" );
195   if( !vglGetAttribLocationARB )
196     return false;
197
198   vglVertexAttribPointerARB = (PFNGLVERTEXATTRIBPOINTERARBPROC)GL_GetProcAddress( "glVertexAttribPointer" );
199   if( !vglVertexAttribPointerARB )
200     return false;
201
202   vglEnableVertexAttribArrayARB = (PFNGLENABLEVERTEXATTRIBARRAYARBPROC)GL_GetProcAddress( "glEnableVertexAttribArray" );
203   if(!vglEnableVertexAttribArrayARB)
204     return false;
205
206   vglDisableVertexAttribArrayARB = (PFNGLDISABLEVERTEXATTRIBARRAYARBPROC)GL_GetProcAddress( "glDisableVertexAttribArray" );
207
208   if(!vglDisableVertexAttribArrayARB)
209     return false;
210
211   
212   return true;
213 };
214
215 //-----------------------------------------------------------------------------
216 char* readFromFile( std::string fileName )
217 {
218   FILE* file = fopen( fileName.c_str(), "r" );
219
220   char* content = NULL;
221   int count = 0;
222
223   if( file != NULL )
224   {
225     fseek( file, 0, SEEK_END );
226     count = ftell( file );
227     rewind( file );
228
229     if( count > 0 )
230     {
231       content = ( char* )malloc( sizeof( char ) * ( count + 1 ) );
232       count = fread( content, sizeof( char ), count, file );
233       content[ count ] = '\0';
234     }
235     fclose( file );
236   }
237
238   return content;
239 }
240
241 static bool IsBufferExtensionsInitialized = InitializeBufferExtensions();
242
243 //-----------------------------------------------------------------------------
244 VTKViewer_PolyDataMapper::VTKViewer_PolyDataMapper()
245 {
246   Q_INIT_RESOURCE( VTKViewer );
247
248   this->ExtensionsInitialized     = ES_None;
249
250   this->PointSpriteTexture        = 0;
251
252   this->MarkerEnabled             = false;
253   this->MarkerType                = VTK::MT_NONE;
254   this->MarkerScale               = VTK::MS_NONE;
255   this->MarkerId                  = 0;
256   this->BallEnabled               = false;
257   this->BallScale                 = 1.0;
258   this->VertexProgram             = 0;
259 }
260
261 //-----------------------------------------------------------------------------
262 VTKViewer_PolyDataMapper::~VTKViewer_PolyDataMapper()
263 {
264   if( PointSpriteTexture > 0 )
265     glDeleteTextures( 1, &PointSpriteTexture );
266 }
267
268 //-----------------------------------------------------------------------------
269 void VTKViewer_PolyDataMapper::InitShader()
270 {
271   std::string fileName = std::string( getenv( "GUI_ROOT_DIR") ) +
272                          "/share/salome/resources/gui/Vertex_Program_ARB.txt";
273
274   char* shader = readFromFile( fileName );
275
276   GLhandleARB VertexShader = vglCreateShaderObjectARB( GL_VERTEX_SHADER_ARB );
277   vglShaderSourceARB( VertexShader, 1, (const GLcharARB**)&shader, NULL );
278   vglCompileShaderARB( VertexShader );
279
280   this->VertexProgram = vglCreateProgramObjectARB();
281   vglAttachObjectARB( this->VertexProgram, VertexShader );
282
283   vglLinkProgramARB( this->VertexProgram );
284   free( shader );
285 }
286
287
288 //-----------------------------------------------------------------------------
289 void VTKViewer_PolyDataMapper::SetMarkerEnabled( bool theMarkerEnabled )
290 {
291   if( this->MarkerEnabled == theMarkerEnabled )
292     return;
293
294   this->MarkerEnabled = theMarkerEnabled;
295   this->Modified();
296 }
297
298 //-----------------------------------------------------------------------------
299 // Definition of structures and fuctions used in SetBallEnabled() method
300 namespace VTK
301 {
302   //----------------------------------------------------------------------------
303   vtkSmartPointer<vtkImageData> MakeTexture( const char* theMainTexture, const char* theAlphaTexture ) {
304     if( !theMainTexture || !theAlphaTexture )
305       return 0;
306     
307     vtkXMLImageDataReader* aMainReader = vtkXMLImageDataReader::New();
308     vtkXMLImageDataReader* anAlphaReader = vtkXMLImageDataReader::New();
309     
310     aMainReader->SetFileName( theMainTexture );
311     anAlphaReader->SetFileName( theAlphaTexture );
312
313     aMainReader->Update();
314     anAlphaReader->Update();
315     
316     vtkImageData* aMainImageData = aMainReader->GetOutput();
317     vtkImageData* anAlphaImageData = anAlphaReader->GetOutput();
318     
319     int* aMainImageSize = aMainImageData->GetDimensions();
320     int* anAlphaImageSize = anAlphaImageData->GetDimensions();
321     if(aMainImageSize[0] != anAlphaImageSize[0] || aMainImageSize[1] != anAlphaImageSize[1])
322       return NULL;
323
324     vtkSmartPointer<vtkImageData> aCompositeImageData = vtkImageData::New();
325     aCompositeImageData->Delete();
326     
327     int aNbCompositeComponents = 4;
328     aCompositeImageData->SetDimensions(aMainImageSize);
329     aCompositeImageData->AllocateScalars( VTK_UNSIGNED_CHAR, aNbCompositeComponents );
330     
331     unsigned char* aMainDataPtr = (unsigned char*)aMainImageData->GetScalarPointer();
332     unsigned char* anAlphaDataPtr = (unsigned char*)anAlphaImageData->GetScalarPointer();
333     unsigned char *aCompositeDataPtr = (unsigned char * )aCompositeImageData->GetScalarPointer();
334
335     int aNbMainComponents = aMainImageData->GetNumberOfScalarComponents();
336     int aNbAlphaComponents = anAlphaImageData->GetNumberOfScalarComponents();
337     int aCompositeSize = aMainImageSize[0] * aMainImageSize[1] * aNbCompositeComponents;
338
339     int aMainId = 0, anAlphaId = 0, aCompositeId = 0;
340     for(; aCompositeId < aCompositeSize;) {
341       aCompositeDataPtr[aCompositeId] = aMainDataPtr[aMainId];
342       aCompositeDataPtr[aCompositeId + 1] = aMainDataPtr[aMainId + 1];
343       aCompositeDataPtr[aCompositeId + 2] = aMainDataPtr[aMainId + 2];
344       aCompositeDataPtr[aCompositeId + 3] = anAlphaDataPtr[anAlphaId];
345
346       aMainId += aNbMainComponents;
347       anAlphaId += aNbAlphaComponents;
348       aCompositeId += aNbCompositeComponents;
349     }
350     aMainReader->Delete();
351     anAlphaReader->Delete();
352     return aCompositeImageData;
353   }  
354 }
355
356 //-----------------------------------------------------------------------------
357 bool VTKViewer_PolyDataMapper::GetBallEnabled()
358 {
359   return this->BallEnabled;
360 }
361 //-----------------------------------------------------------------------------
362 void VTKViewer_PolyDataMapper::SetBallEnabled( bool theBallEnabled )
363
364   if( this->BallEnabled == theBallEnabled )
365     return;
366   else 
367     this->BallEnabled = theBallEnabled;
368
369   if(!this->BallEnabled) {
370     this->ImageData = NULL;
371   }
372
373   if(this->BallEnabled) {
374     if(this->SpecialTextures.find(BallTextureId) == SpecialTextures.end()){
375       QString aMainTexture  = getenv( "GUI_ROOT_DIR" );
376       aMainTexture.append("/share/salome/resources/gui/sprite_texture.vti");
377       
378       QString anAlphaTexture = getenv( "GUI_ROOT_DIR" );
379       anAlphaTexture.append( "/share/salome/resources/gui/sprite_alpha.vti" );
380       vtkSmartPointer<vtkImageData> aTextureValue = VTK::MakeTexture( aMainTexture.toLatin1().constData(), anAlphaTexture.toLatin1().constData() );
381       this->SpecialTextures[BallTextureId] = aTextureValue;
382     }
383     this->ImageData = this->SpecialTextures[BallTextureId];
384   }
385   this->Modified();
386 }
387
388 //-----------------------------------------------------------------------------
389 double VTKViewer_PolyDataMapper::GetBallScale()
390 {
391   return this->BallScale;
392 }
393 //-----------------------------------------------------------------------------
394 void VTKViewer_PolyDataMapper::SetBallScale( double theBallScale )
395 {
396   if( this->BallScale == theBallScale )
397     return;
398   this->BallScale = theBallScale;
399 }
400
401 //-----------------------------------------------------------------------------
402 void VTKViewer_PolyDataMapper::SetMarkerStd( VTK::MarkerType theMarkerType, VTK::MarkerScale theMarkerScale )
403 {
404   if( this->MarkerType == theMarkerType && this->MarkerScale == theMarkerScale )
405     return;
406
407   this->MarkerType = theMarkerType;
408   this->MarkerScale = theMarkerScale;
409
410   if( this->MarkerType == VTK::MT_NONE || this->MarkerType == VTK::MT_USER ) {
411     this->ImageData = NULL;
412     this->Modified();
413     return;
414   }
415
416   int aMarkerType = (int)this->MarkerType;
417   int aMarkerScale = (int)this->MarkerScale;
418
419   int anId = (int)VTK::MS_70 * aMarkerType + aMarkerScale;
420
421   if( this->StandardTextures.find( anId ) == this->StandardTextures.end() )
422   {
423     QString aFileName = QString( ":/textures/texture%1.dat" ).arg( aMarkerType );
424     VTK::MarkerTexture aMarkerTexture;
425     if( VTK::LoadTextureData( aFileName, theMarkerScale, aMarkerTexture ) )
426       this->StandardTextures[ anId ] = VTK::MakeVTKImage( aMarkerTexture );
427   }
428
429   this->ImageData = this->StandardTextures[ anId ];
430   this->Modified();
431 }
432
433 //-----------------------------------------------------------------------------
434 void VTKViewer_PolyDataMapper::SetMarkerTexture( int theMarkerId, VTK::MarkerTexture theMarkerTexture )
435 {
436   if( this->MarkerType == VTK::MT_USER && this->MarkerId == theMarkerId )
437     return;
438
439   this->MarkerType = VTK::MT_USER;
440   this->MarkerId = theMarkerId;
441
442   if( this->CustomTextures.find( theMarkerId ) == this->CustomTextures.end() )
443     this->CustomTextures[ theMarkerId ] = VTK::MakeVTKImage( theMarkerTexture );
444
445   this->ImageData = this->CustomTextures[ theMarkerId ];
446   this->Modified();
447 }
448
449 //-----------------------------------------------------------------------------
450 VTK::MarkerType VTKViewer_PolyDataMapper::GetMarkerType()
451 {
452   return this->MarkerType;
453 }
454
455 //-----------------------------------------------------------------------------
456 VTK::MarkerScale VTKViewer_PolyDataMapper::GetMarkerScale()
457 {
458   return this->MarkerScale;
459 }
460
461 //-----------------------------------------------------------------------------
462 int VTKViewer_PolyDataMapper::GetMarkerTexture()
463 {
464   return this->MarkerId;
465 }
466
467 //-----------------------------------------------------------------------------
468 int VTKViewer_PolyDataMapper::InitExtensions()
469 {
470   char* ext = (char*)glGetString( GL_EXTENSIONS );
471   if( !IsBufferExtensionsInitialized ||
472       strstr( ext, "GL_ARB_point_sprite" ) == NULL ||
473       strstr( ext, "GL_ARB_vertex_buffer_object" ) == NULL ||
474       strstr( ext, "GL_ARB_shader_objects") == NULL )
475   {
476     MESSAGE("Initializing ARB extensions failed");
477     return ES_Error;
478   }
479
480   if( this->BallEnabled )
481     this->InitShader();
482
483   return ES_Ok;
484 }
485
486 //-----------------------------------------------------------------------------
487 void VTKViewer_PolyDataMapper::InitPointSprites()
488 {
489   glEnable( GL_POINT_SPRITE_ARB );
490   glEnable( GL_VERTEX_PROGRAM_POINT_SIZE_ARB );
491
492   glPushAttrib( GL_COLOR_BUFFER_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT | GL_ENABLE_BIT | GL_LIGHTING_BIT );
493
494   glDepthFunc( GL_LEQUAL );
495   glEnable( GL_DEPTH_TEST );
496
497   glEnable( GL_ALPHA_TEST );
498   if(!this->BallEnabled) {
499     glAlphaFunc( GL_GREATER, 0.0 );
500   }
501   else { 
502     glAlphaFunc( GL_GREATER, 0.5 );
503   }
504
505   glDisable( GL_LIGHTING );
506
507   glDisable( GL_COLOR_MATERIAL );
508 }
509
510 //-----------------------------------------------------------------------------
511 void VTKViewer_PolyDataMapper::CleanupPointSprites()
512 {
513   glPopAttrib();
514
515   glDisable( GL_VERTEX_PROGRAM_POINT_SIZE_ARB );
516   glDisable( GL_POINT_SPRITE_ARB );
517 }
518
519 //-----------------------------------------------------------------------------
520 void VTKViewer_PolyDataMapper::InitTextures()
521 {
522   if( !this->ImageData.GetPointer() )
523     return;
524
525   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
526   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
527
528   if(this->BallEnabled) {
529     glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
530     glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
531   } else {
532     glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
533     glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
534   }
535
536   int* aSize = this->ImageData->GetDimensions();
537   unsigned char* dataPtr = (unsigned char*)this->ImageData->GetScalarPointer();
538   glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, aSize[0], aSize[1], 0,
539                 GL_RGBA, GL_UNSIGNED_BYTE, dataPtr );
540
541   //glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
542   glEnable( GL_TEXTURE_2D );
543   glTexEnvf( GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE );
544   glBindTexture( GL_TEXTURE_2D, this->PointSpriteTexture );
545 }
546
547 //-----------------------------------------------------------------------------
548 void VTKViewer_PolyDataMapper::RenderPiece( vtkRenderer* ren, vtkActor* act )
549 {
550   bool isUsePointSprites = (this->MarkerEnabled && this->MarkerType != VTK::MT_NONE) || 
551     this->BallEnabled;
552   if( isUsePointSprites )
553   {
554     if( this->ExtensionsInitialized == ES_None )
555       this->ExtensionsInitialized = this->InitExtensions();
556     this->InitPointSprites();
557     this->InitTextures();
558   }
559
560   if(!this->BallEnabled || this->ExtensionsInitialized != ES_Ok) {
561     MAPPER_SUPERCLASS::RenderPiece( ren, act );
562     if( isUsePointSprites )
563       this->CleanupPointSprites();
564   } else {
565     vtkIdType numPts;
566     vtkPolyData *input= this->GetInput();
567
568     //
569     // make sure that we've been properly initialized
570     //
571     if (ren->GetRenderWindow()->CheckAbortStatus())
572       return;
573
574     if ( input == NULL )
575     {
576       vtkErrorMacro(<< "No input!");
577       return;
578     }
579     else
580     {
581       this->InvokeEvent(vtkCommand::StartEvent,NULL);
582       this->Update();
583       this->InvokeEvent(vtkCommand::EndEvent,NULL);
584       numPts = input->GetNumberOfPoints();
585     }
586
587     if (numPts == 0)
588     {
589       vtkDebugMacro(<< "No points!");
590       return;
591     }
592
593     // make sure our window is current
594     ren->GetRenderWindow()->MakeCurrent();
595
596
597     vglUseProgramObjectARB( this->VertexProgram );
598
599     //
600     // if something has changed regenerate colors and display lists
601     // if required
602     //
603     int noAbort=1;
604     if ( this->GetMTime() > this->BuildTime ||
605          input->GetMTime() > this->BuildTime ||
606          act->GetProperty()->GetMTime() > this->BuildTime ||
607          ren->GetRenderWindow() != this->LastWindow)
608     {
609       // sets this->Colors as side effect
610       this->MapScalars( act->GetProperty()->GetOpacity() );
611
612       if (!this->ImmediateModeRendering &&
613           !this->GetGlobalImmediateModeRendering())
614       {
615         this->ReleaseGraphicsResources(ren->GetRenderWindow());
616         this->LastWindow = ren->GetRenderWindow();
617
618         // get a unique display list id
619         this->ListId = glGenLists(1);
620         glNewList(this->ListId,GL_COMPILE);
621
622         noAbort = this->Draw(ren,act);
623         glEndList();
624
625         // Time the actual drawing
626         this->Timer->StartTimer();
627         glCallList(this->ListId);
628         this->Timer->StopTimer();
629       }
630       else
631       {
632         this->ReleaseGraphicsResources(ren->GetRenderWindow());
633         this->LastWindow = ren->GetRenderWindow();
634       }
635       if (noAbort)
636         this->BuildTime.Modified();
637     }
638     // if nothing changed but we are using display lists, draw it
639     else
640     {
641       if (!this->ImmediateModeRendering &&
642           !this->GetGlobalImmediateModeRendering())
643       {
644         // Time the actual drawing
645         this->Timer->StartTimer();
646         glCallList(this->ListId);
647         this->Timer->StopTimer();
648       }
649     }
650
651     // if we are in immediate mode rendering we always
652     // want to draw the primitives here
653     if (this->ImmediateModeRendering ||
654         this->GetGlobalImmediateModeRendering())
655     {
656       // sets this->Colors as side effect
657       this->MapScalars( act->GetProperty()->GetOpacity() );
658
659       // Time the actual drawing
660       this->Timer->StartTimer();
661       this->Draw(ren,act);
662       this->Timer->StopTimer();
663     }
664
665     this->TimeToDraw = (float)this->Timer->GetElapsedTime();
666
667     // If the timer is not accurate enough, set it to a small
668     // time so that it is not zero
669     if ( this->TimeToDraw == 0.0 )
670       this->TimeToDraw = 0.0001;
671
672     vglUseProgramObjectARB( 0 );
673
674     this->CleanupPointSprites();
675   }  
676 }
677
678 //-----------------------------------------------------------------------------
679 // Definition of structures and fuctions used in Draw() method
680 namespace VTK
681 {
682   //-----------------------------------------------------------------------------
683   struct TVertex
684   {
685     GLfloat r, g, b, a;
686     GLfloat vx, vy, vz;
687   };
688
689   //-----------------------------------------------------------------------------
690   struct TColorFunctorBase
691   {
692     double myAlpha;
693
694     TColorFunctorBase( vtkProperty* theProperty )
695     {
696       myAlpha = theProperty->GetOpacity();
697     }
698
699     virtual
700     void
701     get( TVertex& theVertex, vtkIdType thePointId, vtkIdType theCellId ) = 0;
702   };
703
704   //-----------------------------------------------------------------------------
705   struct TPropertyColor : TColorFunctorBase
706   {
707     double myColor[3];
708
709     TPropertyColor( vtkProperty* theProperty ):
710       TColorFunctorBase( theProperty )
711     {
712       theProperty->GetColor( myColor );
713     }
714
715     virtual
716     void
717     get( TVertex& theVertex, vtkIdType thePointId, vtkIdType theCellId )
718     {
719       theVertex.r = myColor[0];
720       theVertex.g = myColor[1];
721       theVertex.b = myColor[2];
722       theVertex.a = myAlpha;
723     }
724   };
725
726   //-----------------------------------------------------------------------------
727   struct TColors2Color : TColorFunctorBase
728   {
729     vtkUnsignedCharArray* myColors;
730
731     TColors2Color( vtkProperty* theProperty,
732                    vtkUnsignedCharArray* theColors ):
733       TColorFunctorBase( theProperty ),
734       myColors( theColors )
735     {}
736
737     virtual
738     void
739     get( TVertex& theVertex, vtkIdType thePointId, vtkIdType theCellId )
740     {
741       vtkIdType aTupleId = GetTupleId( thePointId, theCellId );
742       unsigned char* aColor = myColors->GetPointer( aTupleId << 2 );
743
744       theVertex.r = int( aColor[0] ) / 255.0;
745       theVertex.g = int( aColor[1] ) / 255.0;
746       theVertex.b = int( aColor[2] ) / 255.0;
747       theVertex.a = myAlpha;
748     }
749
750     virtual
751     vtkIdType
752     GetTupleId( vtkIdType thePointId, vtkIdType theCellId ) = 0;
753   };
754
755   //-----------------------------------------------------------------------------
756   struct TPointColors2Color : TColors2Color
757   {
758     TPointColors2Color( vtkProperty* theProperty,
759                         vtkUnsignedCharArray* theColors ):
760       TColors2Color( theProperty, theColors )
761     {}
762
763     virtual
764     vtkIdType
765     GetTupleId( vtkIdType thePointId, vtkIdType theCellId )
766     {
767       return thePointId;
768     }
769   };
770
771   //-----------------------------------------------------------------------------
772   struct TCellColors2Color : TColors2Color
773   {
774     TCellColors2Color( vtkProperty* theProperty,
775                        vtkUnsignedCharArray* theColors ):
776       TColors2Color( theProperty, theColors )
777     {}
778
779     virtual
780     vtkIdType
781     GetTupleId( vtkIdType thePointId, vtkIdType theCellId )
782     {
783       return theCellId;
784     }
785   };
786
787   //-----------------------------------------------------------------------------
788   template < class TCoordinates >
789   void DrawPoints( TCoordinates* theStartPoints,
790                    vtkCellArray* theCells,
791                    TColorFunctorBase* theColorFunctor,
792                    TVertex* theVertexArr,
793                    vtkIdType &theCellId,
794                    vtkIdType &theVertexId,
795                    TBall* theBallArr,
796                    vtkDataArray* theDiamArray,
797                    double theBallScale )
798   {
799     vtkIdType* ptIds = theCells->GetPointer();
800     vtkIdType* endPtIds = ptIds + theCells->GetNumberOfConnectivityEntries();
801
802     bool mapBalls = false; 
803     if(theBallArr && theDiamArray) {
804       mapBalls = true;
805     }
806
807     while ( ptIds < endPtIds ) {
808       vtkIdType nPts = *ptIds;
809       ++ptIds;
810
811       while ( nPts > 0 ) {
812         TVertex& aVertex = theVertexArr[ theVertexId ];
813         vtkIdType aPointId = *ptIds;
814
815         TCoordinates* anOffsetPoints = theStartPoints + 3 * aPointId;
816         aVertex.vx = anOffsetPoints[0];
817         aVertex.vy = anOffsetPoints[1];
818         aVertex.vz = anOffsetPoints[2];
819
820         theColorFunctor->get( aVertex, aPointId, theCellId );
821
822         ++theVertexId;
823         ++ptIds; 
824         --nPts; 
825       }
826       
827       if(mapBalls){
828         theBallArr[theCellId] = (TBall)theDiamArray->GetTuple(theCellId)[0]*theBallScale;
829       }
830
831       ++theCellId;
832     }
833   }
834
835   //-----------------------------------------------------------------------------
836   template < class TCoordinates >
837   void DrawCellsPoints( vtkPolyData* theInput,
838                         vtkPoints* thePoints,
839                         TColorFunctorBase* theColorFunctor,
840                         TVertex* theVertexArr,
841                         TBall* theBallArr,
842                         double theBallScale )
843   {
844     vtkIdType aCellId = 0, aVertexId = 0;
845
846     TCoordinates* aStartPoints = (TCoordinates*)thePoints->GetVoidPointer(0);
847     vtkDataArray* aDiams = theInput->GetCellData() ? theInput->GetCellData()->GetScalars() : 0;    
848
849     if ( vtkCellArray* aCellArray = theInput->GetVerts() ) {
850       DrawPoints( aStartPoints, aCellArray, theColorFunctor, theVertexArr, aCellId, aVertexId, theBallArr, aDiams, theBallScale );
851     }
852   
853     if ( vtkCellArray* aCellArray = theInput->GetLines() )
854       DrawPoints( aStartPoints, aCellArray, theColorFunctor, theVertexArr, aCellId, aVertexId, theBallArr, aDiams, theBallScale );
855   
856     if ( vtkCellArray* aCellArray = theInput->GetPolys() )
857       DrawPoints( aStartPoints, aCellArray, theColorFunctor, theVertexArr, aCellId, aVertexId, theBallArr, aDiams, theBallScale );
858   
859     if ( vtkCellArray* aCellArray = theInput->GetStrips() )
860       DrawPoints( aStartPoints, aCellArray, theColorFunctor, theVertexArr, aCellId, aVertexId, theBallArr, aDiams, theBallScale ); 
861   }
862 } // namespace VTK
863
864 //-----------------------------------------------------------------------------
865 int VTKViewer_PolyDataMapper::Draw( vtkRenderer* ren, vtkActor* act )
866 {  
867   if( (!this->MarkerEnabled || this->MarkerType == VTK::MT_NONE || !this->ImageData.GetPointer()) && !this->BallEnabled)
868     return MAPPER_SUPERCLASS::Draw( ren, act );
869
870   vtkUnsignedCharArray* colors = NULL;
871   vtkPolyData* input  = this->GetInput();
872   vtkPoints* points;
873   int noAbort = 1;
874   int cellScalars = 0;
875   vtkProperty* prop = act->GetProperty();
876
877   points = input->GetPoints();
878
879   if ( this->Colors )
880   {
881     if(!this->BallEnabled) {
882       colors = this->Colors;
883       if ( (this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA ||
884             this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA ||
885             !input->GetPointData()->GetScalars() )
886            && this->ScalarMode != VTK_SCALAR_MODE_USE_POINT_FIELD_DATA )
887         cellScalars = 1;
888     }
889   }
890
891   {
892     vtkIdType aTotalConnectivitySize = 0;
893     vtkIdType aNbCells = 0;
894
895     if ( vtkCellArray* aCellArray = input->GetVerts() ) {
896       aTotalConnectivitySize += aCellArray->GetNumberOfConnectivityEntries() - aCellArray->GetNumberOfCells();
897       aNbCells += aCellArray->GetNumberOfCells();
898     }
899
900     if ( vtkCellArray* aCellArray = input->GetLines() ) {
901       aTotalConnectivitySize += aCellArray->GetNumberOfConnectivityEntries() - aCellArray->GetNumberOfCells();
902       aNbCells += aCellArray->GetNumberOfCells();
903     }
904
905     if ( vtkCellArray* aCellArray = input->GetPolys() ) {
906       aTotalConnectivitySize += aCellArray->GetNumberOfConnectivityEntries() - aCellArray->GetNumberOfCells();
907       aNbCells += aCellArray->GetNumberOfCells();
908     }
909
910     if ( vtkCellArray* aCellArray = input->GetStrips() ) {
911       aTotalConnectivitySize += aCellArray->GetNumberOfConnectivityEntries() - aCellArray->GetNumberOfCells();
912       aNbCells += aCellArray->GetNumberOfCells();
913     }
914
915     if ( aTotalConnectivitySize > 0 ) {
916       VTK::TVertex* aVertexArr = new VTK::TVertex[ aTotalConnectivitySize ];
917       
918       TBall* aBallArray = 0;
919
920       if(this->BallEnabled) {
921         aBallArray = new TBall[aNbCells];
922       }
923
924       int* aSize = this->ImageData->GetDimensions();
925       glPointSize( std::max( aSize[0], aSize[1] ) );
926
927       int aMode = 0; // to remove
928       {
929         VTK::TColorFunctorBase* aColorFunctor = NULL;
930         if( colors && aMode != 1 ) {
931           if ( cellScalars )
932             aColorFunctor = new VTK::TCellColors2Color( prop, colors );
933           else
934             aColorFunctor = new VTK::TPointColors2Color( prop, colors );
935         } else {
936           aColorFunctor = new VTK::TPropertyColor( prop );
937         }
938         if ( points->GetDataType() == VTK_FLOAT )
939           VTK::DrawCellsPoints< float >( input, points, aColorFunctor, aVertexArr, aBallArray, GetBallScale() );
940         else
941           VTK::DrawCellsPoints< double >( input, points, aColorFunctor, aVertexArr, aBallArray, GetBallScale() );
942
943         delete aColorFunctor;
944       }
945
946       if( this->ExtensionsInitialized == ES_Ok ) {
947         GLuint aBufferObjectID, aDiamsID = 0;
948         GLint attribute_diams = -1;
949         vglGenBuffersARB( 1, &aBufferObjectID );
950         vglBindBufferARB( GL_ARRAY_BUFFER_ARB, aBufferObjectID );
951         
952         int anArrayObjectSize = sizeof( VTK::TVertex ) * aTotalConnectivitySize;
953         vglBufferDataARB( GL_ARRAY_BUFFER_ARB, anArrayObjectSize, aVertexArr, GL_STATIC_DRAW_ARB );
954         
955         delete [] aVertexArr;
956         
957         vglBindBufferARB( GL_ARRAY_BUFFER_ARB, 0 );
958         vglBindBufferARB( GL_ARRAY_BUFFER_ARB, aBufferObjectID );        
959         
960         glColorPointer( 4, GL_FLOAT, sizeof(VTK::TVertex), (void*)0 );
961         glVertexPointer( 3, GL_FLOAT, sizeof(VTK::TVertex), (void*)(4*sizeof(GLfloat)) );
962         
963         glEnableClientState( GL_VERTEX_ARRAY );
964         glEnableClientState( GL_COLOR_ARRAY );
965
966         if(this->BallEnabled) {
967           vglGenBuffersARB( 2, &aDiamsID);
968           vglBindBufferARB( GL_ARRAY_BUFFER_ARB, aDiamsID);
969
970           int aDiamsSize = sizeof(TBall)*aNbCells;
971           vglBufferDataARB( GL_ARRAY_BUFFER_ARB, aDiamsSize, aBallArray, GL_STATIC_DRAW_ARB);
972
973           delete [] aBallArray;
974           vglBindBufferARB( GL_ARRAY_BUFFER_ARB, 0 );
975           vglBindBufferARB( GL_ARRAY_BUFFER_ARB, aDiamsID );
976
977           attribute_diams = vglGetAttribLocationARB(this->VertexProgram, "diameter");
978           vglEnableVertexAttribArrayARB(attribute_diams);
979           vglBindBufferARB(GL_ARRAY_BUFFER_ARB, aDiamsID);
980           vglVertexAttribPointerARB(
981                                     attribute_diams,   // attribute
982                                     1,                 // number of elements per vertex, here (diameter)
983                                     GL_FLOAT,          // the type of each element
984                                     GL_FALSE,          // take our values as-is
985                                     0,                 // no extra data between each position
986                                     0                  // offset of first element
987                                     );
988         }
989
990         glDrawArrays( GL_POINTS, 0, aTotalConnectivitySize );
991         
992         glDisableClientState( GL_COLOR_ARRAY );
993         glDisableClientState( GL_VERTEX_ARRAY );       
994         vglDeleteBuffersARB( 1, &aBufferObjectID );
995
996         if(this->BallEnabled) {
997           vglDisableVertexAttribArrayARB(attribute_diams);
998           vglDeleteBuffersARB( 2, &aDiamsID );
999         }
1000
1001           } else { // there are no extensions
1002         glColorPointer( 4, GL_FLOAT, sizeof(VTK::TVertex), aVertexArr );
1003         glVertexPointer( 3, GL_FLOAT, sizeof(VTK::TVertex), 
1004                          (void*)((GLfloat*)((void*)(aVertexArr)) + 4));
1005
1006         glEnableClientState( GL_VERTEX_ARRAY );
1007         glEnableClientState( GL_COLOR_ARRAY );
1008         
1009         glDrawArrays( GL_POINTS, 0, aTotalConnectivitySize );
1010         
1011         glDisableClientState( GL_COLOR_ARRAY );
1012         glDisableClientState( GL_VERTEX_ARRAY );
1013
1014         delete [] aVertexArr;
1015       }
1016     }
1017   }
1018
1019   this->UpdateProgress(1.0);
1020   return noAbort;
1021 }