source: GTP/trunk/Lib/Vis/Preprocessing/src/GlRenderer.cpp @ 991

Revision 991, 54.7 KB checked in by mattausch, 18 years ago (diff)
  • Property svn:executable set to *
Line 
1#include "Mesh.h"
2#include "GlRenderer.h"
3#include "ViewCellsManager.h"
4#include "SceneGraph.h"
5#include "Pvs.h"
6#include "Viewcell.h"
7#include "Beam.h"
8#include "KdTree.h"
9#include "Environment.h"
10
11//#define GL_GLEXT_PROTOTYPES
12#include <GL/glext.h>
13#include <Cg/cg.h>
14#include <Cg/cgGL.h>
15
16#include <QVBoxLayout>
17
18namespace GtpVisibilityPreprocessor {
19
20static CGcontext sCgContext = NULL;
21static CGprogram sCgFragmentProgram = NULL;
22static CGprofile sCgFragmentProfile;
23
24GLuint frontDepthMap;
25GLuint backDepthMap;
26
27const int depthMapSize = 512;
28static vector<int> sQueries;
29
30GlRendererWidget *rendererWidget = NULL;
31GlDebuggerWidget *debuggerWidget = NULL;
32
33
34#ifdef _WIN32
35PFNGLGENOCCLUSIONQUERIESNVPROC glGenOcclusionQueriesNV;
36PFNGLBEGINOCCLUSIONQUERYNVPROC glBeginOcclusionQueryNV;
37PFNGLENDOCCLUSIONQUERYNVPROC glEndOcclusionQueryNV;
38PFNGLGETOCCLUSIONQUERYUIVNVPROC glGetOcclusionQueryuivNV;
39
40//PFNGLGENQUERIESARBPROC glGenQueriesARB;
41//PFNGLBEGINQUERYARBPROC glBeginQueryARB;
42//PFNGLENDQUERYARBPROC glEndQueryARB;
43//PFNGLGETQUERYUIVARBPROC glGetQueryuivARB;
44#endif
45
46
47GlRenderer::GlRenderer(SceneGraph *sceneGraph,
48                                           ViewCellsManager *viewCellsManager,
49                                           KdTree *tree):
50  Renderer(sceneGraph, viewCellsManager),
51  mKdTree(tree)
52{
53  mSceneGraph->CollectObjects(&mObjects);
54  mViewPoint = mSceneGraph->GetBox().Center();
55  mViewDirection = Vector3(0,0,1);
56
57  mViewPoint = Vector3(991.7, 187.8, -271);
58  mViewDirection = Vector3(0.9, 0, -0.4);
59
60  //  timerId = startTimer(10);
61  // debug coords for atlanta
62  //  mViewPoint = Vector3(3473, 6.778, -1699);
63  //  mViewDirection = Vector3(-0.2432, 0, 0.97);
64 
65  mFrame = 0;
66  mWireFrame = false;
67  environment->GetBoolValue("Preprocessor.detectEmptyViewSpace", mDetectEmptyViewSpace);
68  mSnapErrorFrames = true;
69  mSnapPrefix = "snap/";
70  mUseForcedColors = false;
71
72  mUseGlLists = true;
73 
74}
75
76GlRenderer::~GlRenderer()
77{
78  cerr<<"gl renderer destructor..\n";
79  if (sCgFragmentProgram)
80        cgDestroyProgram(sCgFragmentProgram);
81  if (sCgContext)
82        cgDestroyContext(sCgContext);
83  cerr<<"done."<<endl;
84}
85
86
87static void handleCgError()
88{
89    Debug << "Cg error: " << cgGetErrorString(cgGetError()) << endl;
90    exit(1);
91}
92
93void
94GlRenderer::RenderIntersectable(Intersectable *object)
95{
96
97  glPushAttrib(GL_CURRENT_BIT);
98  if (mUseFalseColors)
99        SetupFalseColor(object->mId);
100 
101
102  switch (object->Type()) {
103  case Intersectable::MESH_INSTANCE:
104        RenderMeshInstance((MeshInstance *)object);
105        break;
106  case Intersectable::VIEW_CELL:
107          RenderViewCell(dynamic_cast<ViewCell *>(object));
108          break;
109  default:
110        cerr<<"Rendering this object not yet implemented\n";
111        break;
112  }
113
114  glPopAttrib();
115}
116
117
118void
119GlRenderer::RenderViewCell(ViewCell *vc)
120{
121  if (vc->GetMesh()) {
122
123        if (!mUseFalseColors) {
124          if (vc->GetValid())
125                glColor3f(0,1,0);
126          else
127                glColor3f(0,0,1);
128        }
129       
130        RenderMesh(vc->GetMesh());
131  } else {
132        // render viewcells in the subtree
133        if (!vc->IsLeaf()) {
134          ViewCellInterior *vci = (ViewCellInterior *) vc;
135
136          ViewCellContainer::iterator it = vci->mChildren.begin();
137          for (; it != vci->mChildren.end(); ++it) {
138                RenderViewCell(*it);
139          }
140        } else {
141          //      cerr<<"Empty viewcell mesh\n";
142        }
143  }
144}
145
146
147void
148GlRenderer::RenderMeshInstance(MeshInstance *mi)
149{
150  RenderMesh(mi->GetMesh());
151}
152
153void
154GlRenderer::SetupFalseColor(const int id)
155{
156  // swap bits of the color
157  glColor3ub(id&255, (id>>8)&255, (id>>16)&255);
158}
159
160
161int GlRenderer::GetId(int r, int g, int b) const
162{
163        return r + (g << 8) + (b << 16);
164}
165
166void
167GlRenderer::SetupMaterial(Material *m)
168{
169  if (m)
170        glColor3fv(&(m->mDiffuseColor.r));
171}
172
173void
174GlRenderer::RenderMesh(Mesh *mesh)
175{
176  int i = 0;
177
178  if (!mUseFalseColors && !mUseForcedColors)
179        SetupMaterial(mesh->mMaterial);
180 
181  for (i=0; i < mesh->mFaces.size(); i++) {
182        if (mWireFrame)
183          glBegin(GL_LINE_LOOP);
184        else
185          glBegin(GL_POLYGON);
186
187        Face *face = mesh->mFaces[i];
188        for (int j = 0; j < face->mVertexIndices.size(); j++) {
189          glVertex3fv(&mesh->mVertices[face->mVertexIndices[j]].x);
190        }
191        glEnd();
192  }
193}
194       
195void
196GlRenderer::InitGL()
197{
198  glMatrixMode(GL_PROJECTION);
199  glLoadIdentity();
200 
201  glMatrixMode(GL_MODELVIEW);
202  glLoadIdentity();
203
204  glEnable(GL_CULL_FACE);
205  glShadeModel(GL_FLAT);
206  glEnable(GL_DEPTH_TEST);
207  glEnable(GL_CULL_FACE);
208 
209  glGenOcclusionQueriesNV = (PFNGLGENOCCLUSIONQUERIESNVPROC)
210        wglGetProcAddress("glGenOcclusionQueriesNV");
211  glBeginOcclusionQueryNV = (PFNGLBEGINOCCLUSIONQUERYNVPROC)
212        wglGetProcAddress("glBeginOcclusionQueryNV");
213  glEndOcclusionQueryNV = (PFNGLENDOCCLUSIONQUERYNVPROC)
214        wglGetProcAddress("glEndOcclusionQueryNV");
215  glGetOcclusionQueryuivNV = (PFNGLGETOCCLUSIONQUERYUIVNVPROC)
216        wglGetProcAddress("glGetOcclusionQueryuivNV");
217
218
219#if 0
220  glGenQueriesARB = (PFNGLGENDQUERIESARBPROC)
221        wglGetProcAddress("glGenQueriesARB");
222  glBeginQueryARB = (PFNGLBEGINQUERYARBPROC)
223        wglGetProcAddress("glBeginQueryARB");
224  glEndQueryARB = (PFNGLENDQUERYARBPROC)
225        wglGetProcAddress("glEndQueryARB");
226  glGetQueryuivARB = (PFNGLGETQUERYUIVARBPROC)
227        wglGetProcAddress("glGetQueryuivARB");
228
229#endif
230 
231
232#if 0
233  GLfloat mat_ambient[]   = {  0.5, 0.5, 0.5, 1.0  };
234  /*  mat_specular and mat_shininess are NOT default values     */
235  GLfloat mat_diffuse[]   = {  1.0, 1.0, 1.0, 1.0  };
236  GLfloat mat_specular[]  = {  0.3, 0.3, 0.3, 1.0  };
237  GLfloat mat_shininess[] = {  1.0  };
238 
239  GLfloat light_ambient[]  = {  0.2, 0.2, 0.2, 1.0  };
240  GLfloat light_diffuse[]  = {  0.4, 0.4, 0.4, 1.0  };
241  GLfloat light_specular[] = {  0.3, 0.3, 0.3, 1.0  };
242 
243  GLfloat lmodel_ambient[] = {  0.3, 0.3, 0.3, 1.0  };
244 
245 
246  // default Material
247  glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
248  glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
249  glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
250  glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
251
252  // a light
253  glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
254  glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
255  glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
256 
257  glLightfv(GL_LIGHT1, GL_AMBIENT, light_ambient);
258  glLightfv(GL_LIGHT1, GL_DIFFUSE, light_diffuse);
259  glLightfv(GL_LIGHT1, GL_SPECULAR, light_specular);
260 
261  glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
262 
263  glEnable(GL_LIGHTING);
264  glEnable(GL_LIGHT0);
265  glEnable(GL_LIGHT1);
266 
267 
268  // set position of the light
269  GLfloat infinite_light[] = {  1.0, 0.8, 1.0, 0.0  };
270  glLightfv (GL_LIGHT0, GL_POSITION, infinite_light);
271 
272  // set position of the light2
273  GLfloat infinite_light2[] = {  -0.3, 1.5, 1.0, 0.0  };
274  glLightfv (GL_LIGHT1, GL_POSITION, infinite_light2);
275 
276  glColorMaterial( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
277  //   glColorMaterial( GL_FRONT_AND_BACK, GL_SPECULAR);
278  glEnable(GL_COLOR_MATERIAL);
279 
280  glShadeModel( GL_FLAT );
281 
282  glDepthFunc( GL_LESS );
283  glEnable( GL_DEPTH_TEST );
284#endif
285
286  glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE );
287
288  glEnable( GL_NORMALIZE );
289 
290  glClearColor(0.0f, 0.0f, 1.0f, 1.0f);
291}
292
293void
294GlRendererWidget::RenderInfo()
295{
296  QString s;
297  int vc = 0;
298  if (mViewCellsManager)
299        vc = mViewCellsManager->GetViewCells().size();
300  int filter = 0;
301  if (mViewCellsManager)
302        filter = mViewCellsManager->GetMaxFilterSize();
303
304  s.sprintf("frame:%04d viewpoint:(%4.1f,%4.1f,%4.1f) dir:(%4.1f,%4.1f,%4.1f) viewcells:%04d filter:%04d pvs:%04d error:%5.5f\%",
305                        mFrame,
306                        mViewPoint.x,
307                        mViewPoint.y,
308                        mViewPoint.z,
309                        mViewDirection.x,
310                        mViewDirection.y,
311                        mViewDirection.z,
312                        vc,
313
314                        filter,
315                        mPvsSize,
316                        mRenderError*100.0f
317                        );
318 
319  glColor3f(0.0f,0.0f,0.0f);
320  renderText(0,20,s);
321 
322  if (mShowRenderCost) {
323        static vector<float> costFunction;
324        static float maxCost = -1;
325        if (costFunction.size()==0) {
326          ViewCellsTree *tree = mViewCellsManager->GetViewCellsTree();
327          if (tree) {
328                tree->GetCostFunction(costFunction);
329                maxCost = -1;
330                for (int i=0;  i < costFunction.size(); i++) {
331                  //              cout<<i<<":"<<costFunction[i]<<" ";
332                  if (costFunction[i] > maxCost)
333                        maxCost = costFunction[i];
334                }
335          }
336        }
337
338       
339        int currentPos = mViewCellsManager->GetViewCells().size();
340        float currentCost=-1;
341
342        if (currentPos < costFunction.size())
343          currentCost = costFunction[currentPos];
344#if 0   
345        cout<<"costFunction.size()="<<costFunction.size()<<endl;
346        cout<<"CP="<<currentPos<<endl;
347        cout<<"MC="<<maxCost<<endl;
348        cout<<"CC="<<currentCost<<endl;
349#endif
350        if (costFunction.size()) {
351          glDisable(GL_DEPTH_TEST);
352          // init ortographic projection
353          glMatrixMode(GL_PROJECTION);
354          glPushMatrix();
355         
356          glLoadIdentity();
357          gluOrtho2D(0, 1.0f, 0, 1.0f);
358         
359          glTranslatef(0.1f, 0.1f, 0.0f);
360          glScalef(0.8f, 0.8f, 1.0f);
361          glMatrixMode(GL_MODELVIEW);
362          glLoadIdentity();
363         
364          glColor3f(1.0f,0,0);
365          glBegin(GL_LINE_STRIP);
366          //      glVertex3f(0,0,0);
367         
368          for (int i=0;  i < costFunction.size(); i++) {
369                float x =  i/(float)costFunction.size();
370                float y = costFunction[i]/(maxCost*0.5f);
371                glVertex3f(x,y,0.0f);
372          }
373          glEnd();
374         
375          glColor3f(1.0f,0,0);
376          glBegin(GL_LINES);
377          float x =  currentPos/(float)costFunction.size();
378          glVertex3f(x,0.0,0.0f);
379          glVertex3f(x,1.0f,0.0f);
380          glEnd();
381         
382          glColor3f(0.0f,0,0);
383          // show a grid
384          glBegin(GL_LINE_LOOP);
385          glVertex3f(0,0,0.0f);
386          glVertex3f(1,0,0.0f);
387          glVertex3f(1,1,0.0f);
388          glVertex3f(0,1,0.0f);
389          glEnd();
390
391          glBegin(GL_LINES);
392          for (int i=0;  i < 50000 && i < costFunction.size(); i+=10000) {
393                float x =  i/(float)costFunction.size();
394                glVertex3f(x,0.0,0.0f);
395                glVertex3f(x,1.0f,0.0f);
396          }
397
398          for (int i=0;  i < maxCost; i+=100) {
399                float y = i/(maxCost*0.5f);
400                glVertex3f(0,y,0.0f);
401                glVertex3f(1,y,0.0f);
402          }
403
404          glEnd();
405
406         
407          // restore the projection matrix
408          glMatrixMode(GL_PROJECTION);
409          glPopMatrix();
410          glMatrixMode(GL_MODELVIEW);
411          glEnable(GL_DEPTH_TEST);
412
413        }
414  }
415}
416
417
418void
419GlRenderer::SetupProjection(const int w, const int h, const float angle)
420{
421  glViewport(0, 0, w, h);
422  glMatrixMode(GL_PROJECTION);
423  glLoadIdentity();
424  gluPerspective(angle, 1.0, 0.1, 2.0*Magnitude(mSceneGraph->GetBox().Diagonal()));
425  glMatrixMode(GL_MODELVIEW);
426}
427
428void
429GlRenderer::SetupCamera()
430{
431  Vector3 target = mViewPoint + mViewDirection;
432
433  Vector3 up(0,1,0);
434 
435  if (abs(DotProd(mViewDirection, up)) > 0.99f)
436        up = Vector3(1, 0, 0);
437 
438  glLoadIdentity();
439  gluLookAt(mViewPoint.x, mViewPoint.y, mViewPoint.z,
440                        target.x, target.y, target.z,
441                        up.x, up.y, up.z);
442}
443
444
445void
446GlRendererBuffer::EvalRenderCostSample(
447                                                                           RenderCostSample &sample
448                                                                           )
449{
450  mViewCellsManager->GetViewPoint(mViewPoint);
451  sample.mPosition = mViewPoint;
452
453  cout << mViewPoint << endl;
454 
455  // take a render cost sample by rendering a cube
456  Vector3 directions[6];
457  directions[0] = Vector3(1,0,0);
458  directions[1] = Vector3(0,1,0);
459  directions[2] = Vector3(0,0,1);
460  directions[3] = Vector3(-1,0,0);
461  directions[4] = Vector3(0,-1,0);
462  directions[5] = Vector3(0,0,-1);
463
464  sample.mVisibleObjects = 0;
465
466  int i, j;
467 
468  // reset object visibility
469  for (i=0; i < mObjects.size(); i++) {
470        mObjects[i]->mCounter = 0;
471  }
472  mFrame++;
473  for (i=0; i < 6; i++) {
474        mViewDirection = directions[i];
475        SetupCamera();
476        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
477        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
478       
479        glDepthFunc( GL_LESS );
480
481        mUseFalseColors = true;
482
483        RenderScene();
484
485        if (1) {
486          char filename[256];
487          sprintf(filename, "snap/frame-%04d-%d.png", mFrame, i);
488          QImage im = toImage();
489          im.save(filename, "PNG");
490        }
491       
492        bool useItemBuffer = false;
493       
494        if (useItemBuffer) {
495          // read back the texture
496          glReadPixels(0, 0,
497                                   GetWidth(), GetHeight(),
498                                   GL_RGBA,
499                                   GL_UNSIGNED_BYTE,
500                                   mPixelBuffer);
501         
502          int x, y;
503          unsigned int *p = mPixelBuffer;
504          for (y = 0; y < GetHeight(); y++)
505                for (x = 0; x < GetWidth(); x++, p++) {
506                  unsigned int id = (*p) & 0xFFFFFF;
507                  if (id != 0xFFFFFF)
508                        mObjects[id]->mCounter++;
509                }
510         
511        } else {
512       
513          //      glDepthFunc( GL_LEQUAL );
514          glDepthFunc( GL_LEQUAL );
515         
516          glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
517          glDepthMask(GL_FALSE);
518         
519          // now issue queries for all objects
520          for (j = 0; j < mObjects.size(); j++) {
521                int q;
522                for (q = 0; j + q < mObjects.size() && q < mOcclusionQueries.size(); q++) {
523                  glBeginOcclusionQueryNV(mOcclusionQueries[q]);
524                  RenderIntersectable(mObjects[j+q]);
525                  glEndOcclusionQueryNV();
526                }
527               
528               
529                // collect results of the queries
530                for (q = 0; j + q < mObjects.size() && q < mOcclusionQueries.size(); q++) {
531                  unsigned int pixelCount;
532                  // reenable other state
533
534#if 1
535                  do {
536                        glGetOcclusionQueryuivNV(mOcclusionQueries[q],
537                                                                         GL_PIXEL_COUNT_AVAILABLE_NV,
538                                                                         &pixelCount);
539                        if (!pixelCount)
540                          cout<<"W";
541                  } while(!pixelCount);
542#endif
543
544                  glGetOcclusionQueryuivNV(mOcclusionQueries[q],
545                                                                   GL_PIXEL_COUNT_NV,
546                                                                   &pixelCount);
547                  //            if (pixelCount)
548                  //              cout<<"q="<<mOcclusionQueries[q]<<" pc="<<pixelCount<<" ";
549                  mObjects[j+q]->mCounter += pixelCount;
550                }
551                j += q;
552          }
553         
554          glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
555          glDepthMask(GL_TRUE);
556        }
557         
558       
559  } 
560  // now evaluate the statistics over that sample
561  // currently only the number of visible objects is taken into account
562  sample.Reset();
563  for (j = 0; j < mObjects.size(); j++) {
564        if (mObjects[j]->mCounter) {
565          sample.mVisibleObjects++;
566          sample.mVisiblePixels += mObjects[j]->mCounter;
567        }
568  }
569  cout<<"RS="<<sample.mVisibleObjects<<" ";
570}
571
572void
573GlRendererBuffer::SampleRenderCost(
574                                                                   const int n,
575                                                                   vector<RenderCostSample> &samples
576                                                                   )
577{cout << "here1" << endl;
578  makeCurrent();
579
580  if (mPixelBuffer == NULL)
581        mPixelBuffer = new unsigned int[GetWidth()*GetHeight()];
582 
583  SetupProjection(GetHeight(), GetHeight(), 90.0f);
584
585  samples.resize(n);
586  halton.Reset();
587 
588  int i;
589  int numQ = 500;
590
591  cout << "here2988" << endl;
592
593  if (mOcclusionQueries.size() < numQ)
594  {
595          cout << "allocating occ queries..." << endl;
596       
597          unsigned int *queries = new unsigned int[numQ];
598         
599          // matt: ?
600          for (i = 0; i < numQ; ++ i)
601          queries[i] = 111;
602       
603          glGenOcclusionQueriesNV(numQ, queries);
604
605          mOcclusionQueries.resize(numQ);
606       
607          for (i=0; i < numQ; ++ i)
608          {
609                  mOcclusionQueries[i] = queries[i];
610          }
611   
612          DEL_PTR(queries);
613  }
614 
615  for (i=0; i < n; ++ i)
616  {
617          cout << i << " ";
618          EvalRenderCostSample(samples[i]);
619  }
620
621  doneCurrent();
622
623}
624 
625
626void
627GlRendererBuffer::RandomViewPoint()
628{
629 
630 
631  // do not use this function since it could return different viewpoints for
632  // different executions of the algorithm
633
634  //mViewCellsManager->GetViewPoint(mViewPoint);
635
636  while (1) {
637        Vector3 pVector = Vector3(halton.GetNumber(1),
638                                                          halton.GetNumber(2),
639                                                          halton.GetNumber(3));
640       
641        mViewPoint =  mSceneGraph->GetBox().GetPoint(pVector);
642        ViewCell *v = mViewCellsManager->GetViewCell(mViewPoint);
643        if (v && v->GetValid())
644          break;
645        // generate a new vector
646        halton.GenerateNext();
647  }
648 
649 
650  Vector3 dVector = Vector3(2*M_PI*halton.GetNumber(4),
651                                                        M_PI*halton.GetNumber(5),
652                                                        0.0f);
653 
654  mViewDirection = Normalize(Vector3(sin(dVector.x),
655                                                                         //                                                                      cos(dVector.y),
656                                                                         0.0f,
657                                                                         cos(dVector.x)));
658  halton.GenerateNext();
659}
660
661
662GlRendererBuffer::GlRendererBuffer(const int w,
663                                                                   const int h,
664                                                                   SceneGraph *sceneGraph,
665                                                                   ViewCellsManager *viewcells,
666                                                                   KdTree *tree):
667QGLPixelBuffer(QSize(w, h)), GlRenderer(sceneGraph, viewcells, tree) {
668 
669  environment->GetIntValue("Preprocessor.pvsRenderErrorSamples", mPvsStatFrames);
670  mPvsErrorBuffer.resize(mPvsStatFrames);
671  ClearErrorBuffer();
672
673  mPixelBuffer = NULL;
674 
675  makeCurrent();
676  InitGL();
677  doneCurrent();
678 
679}
680
681float
682GlRendererBuffer::GetPixelError(int &pvsSize)
683{
684  float pErrorPixels = -1.0f;
685 
686  glReadBuffer(GL_BACK);
687 
688  //  mUseFalseColors = true;
689 
690  mUseFalseColors = false;
691
692  static int query = -1;
693  unsigned int pixelCount;
694
695  if (query == -1)
696        glGenOcclusionQueriesNV(1, (unsigned int *)&query);
697
698  if (mDetectEmptyViewSpace) {
699        // now check whether any backfacing polygon would pass the depth test
700        SetupCamera();
701        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
702        glEnable( GL_CULL_FACE );
703       
704        RenderScene();
705       
706        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
707        glDepthMask(GL_FALSE);
708        glDisable( GL_CULL_FACE );
709       
710        glBeginOcclusionQueryNV(query);
711       
712        RenderScene();
713       
714        glEndOcclusionQueryNV();
715       
716        // at this point, if possible, go and do some other computation
717        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
718        glDepthMask(GL_TRUE);
719        glEnable( GL_CULL_FACE );
720       
721        // reenable other state
722        glGetOcclusionQueryuivNV(query,
723                                                         GL_PIXEL_COUNT_NV,
724                                                         &pixelCount);
725       
726        if (pixelCount > 0)
727          return -1.0f; // backfacing polygon found -> not a valid viewspace sample
728  } else
729        glDisable( GL_CULL_FACE );
730       
731
732  ViewCell *viewcell = NULL;
733 
734  PrVs prvs;
735  //  mViewCellsManager->SetMaxFilterSize(1);
736  mViewCellsManager->GetPrVS(mViewPoint, prvs, mViewCellsManager->GetFilterWidth());
737  viewcell = prvs.mViewCell;
738 
739  //  ViewCell *viewcell = mViewCellsManager->GetViewCell(mViewPoint);
740  pvsSize = 0;
741  if (viewcell) {
742        SetupCamera();
743        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
744
745        glColorMask(GL_FALSE, GL_TRUE, GL_FALSE, GL_FALSE);
746       
747        // Render PVS
748        std::map<Intersectable *,
749          PvsData<Intersectable *>,
750          LtSample<Intersectable *> >::const_iterator it = viewcell->GetPvs().mEntries.begin();
751
752        pvsSize = viewcell->GetPvs().mEntries.size();
753       
754        for (; it != viewcell->GetPvs().mEntries.end(); ++ it) {
755          Intersectable *object = (*it).first;
756          RenderIntersectable(object);
757        }
758
759        //      glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_FALSE);
760        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
761        mUseFalseColors = true;
762
763        glBeginOcclusionQueryNV(query);
764
765        SetupCamera();
766
767        RenderScene();
768       
769        glEndOcclusionQueryNV();
770       
771
772        unsigned int pixelCount;
773        // reenable other state
774        glGetOcclusionQueryuivNV(query,
775                                                         GL_PIXEL_COUNT_NV,
776                                                         &pixelCount);
777       
778        pErrorPixels = ((float)pixelCount)/(GetWidth()*GetHeight());
779        if (mSnapErrorFrames && pErrorPixels > 0.01) {
780         
781          char filename[256];
782          sprintf(filename, "error-frame-%04d-%0.5f.png", mFrame, pErrorPixels);
783          QImage im = toImage();
784          im.save(mSnapPrefix + filename, "PNG");
785          if (1) { //0 && mFrame == 1543) {
786                int x,y;
787                int lastIndex = -1;
788                for (y=0; y < im.height(); y++)
789                  for (x=0; x < im.width(); x++) {
790                        QRgb p = im.pixel(x,y);
791                        int index = qRed(p) + (qGreen(p)<<8) + (qBlue(p)<<16);
792                        if (qGreen(p) != 255 && index!=0) {
793                          if (index != lastIndex) {
794                                Debug<<"ei="<<index<<" ";
795                                lastIndex = index;
796                          }
797                        }
798                  }
799          }
800
801
802          mUseFalseColors = false;
803          glPushAttrib(GL_CURRENT_BIT);
804          glColor3f(0,1,0);
805          glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
806          SetupCamera();
807          glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
808         
809          // Render PVS
810          std::map<Intersectable *,
811                PvsData<Intersectable *>,
812                LtSample<Intersectable *> >::const_iterator it = viewcell->GetPvs().mEntries.begin();
813         
814          for (; it != viewcell->GetPvs().mEntries.end(); ++ it) {
815                Intersectable *object = (*it).first;
816                RenderIntersectable(object);
817          }
818
819          im = toImage();
820          sprintf(filename, "error-frame-%04d-%0.5f-pvs.png", mFrame, pErrorPixels);
821          im.save(mSnapPrefix + filename, "PNG");
822          glPopAttrib();
823        }
824        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
825  }
826
827  if (viewcell)
828        mViewCellsManager->DeleteLocalMergeTree(viewcell);
829 
830  return pErrorPixels;
831}
832
833
834void
835GlRendererWidget::SetupProjection(const int w, const int h)
836{
837  if (!mTopView)
838        GlRenderer::SetupProjection(w, h);
839  else {
840        glViewport(0, 0, w, h);
841        glMatrixMode(GL_PROJECTION);
842        glLoadIdentity();
843        gluPerspective(50.0, 1.0, 0.1, 20.0*Magnitude(mSceneGraph->GetBox().Diagonal()));
844        glMatrixMode(GL_MODELVIEW);
845  }
846}
847
848void
849GlRendererWidget::RenderPvs()
850{
851  SetupCamera();
852  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
853 
854  ViewCell *viewcell = NULL;
855
856  PrVs prvs;
857 
858  if (!mUseFilter) {
859        viewcell = mViewCellsManager->GetViewCell(mViewPoint, true);
860  } else {
861        //  mViewCellsManager->SetMaxFilterSize(1);
862        mViewCellsManager->GetPrVS(mViewPoint, prvs, mViewCellsManager->GetFilterWidth());
863        viewcell = prvs.mViewCell;
864  }
865 
866  if (viewcell) {
867        // copy the pvs so that it can be filtered...
868        ObjectPvs pvs = viewcell->GetPvs();
869
870        if (mUseSpatialFilter) {
871          mViewCellsManager->ApplySpatialFilter(mKdTree,
872                                                                                        mSpatialFilterSize*
873                                                                                        Magnitude(mViewCellsManager->GetViewSpaceBox().Size()),
874                                                                                        pvs);
875        }
876       
877       
878        // read back the texture
879        std::map<Intersectable *,
880          PvsData<Intersectable *>,
881          LtSample<Intersectable *> >::const_iterator it = pvs.mEntries.begin();
882
883        mPvsSize = pvs.mEntries.size();
884         
885        for (; it != pvs.mEntries.end(); ++ it) {
886          Intersectable *object = (*it).first;
887          float visibility = log10((*it).second.mSumPdf + 1)/5.0f;
888          glColor3f(visibility, 0.0f, 0.0f);
889          mUseForcedColors = true;
890          RenderIntersectable(object);
891          mUseForcedColors = false;
892        }
893
894        if (mRenderFilter) {
895          mWireFrame = true;
896          RenderIntersectable(viewcell);
897          mWireFrame = false;
898        }
899       
900        if (mUseFilter)
901          mViewCellsManager->DeleteLocalMergeTree(viewcell);
902  } else {
903        ObjectContainer::const_iterator oi = mObjects.begin();
904        for (; oi != mObjects.end(); oi++)
905          RenderIntersectable(*oi);
906  }
907}
908
909float
910GlRendererWidget::RenderErrors()
911{
912  float pErrorPixels = -1.0f;
913
914  glReadBuffer(GL_BACK);
915 
916  mUseFalseColors = true;
917
918  SetupCamera();
919  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
920 
921  double eq[4];
922  eq[0] = mSceneCutPlane.mNormal.x;
923  eq[1] = mSceneCutPlane.mNormal.y;
924  eq[2] = mSceneCutPlane.mNormal.z;
925  eq[3] = mSceneCutPlane.mD;
926 
927  if (mCutScene) {
928        glClipPlane(GL_CLIP_PLANE0, eq);
929    glEnable(GL_CLIP_PLANE0);
930  }
931 
932  if (mDetectEmptyViewSpace)
933        glEnable( GL_CULL_FACE );
934  else
935        glDisable( GL_CULL_FACE );
936
937  ObjectContainer::const_iterator oi = mObjects.begin();
938  for (; oi != mObjects.end(); oi++)
939        RenderIntersectable(*oi);
940
941  ViewCell *viewcell = NULL;
942
943  QImage im1, im2;
944  QImage diff;
945 
946  if (viewcell) {
947        // read back the texture
948        im1 = grabFrameBuffer(true);
949       
950        RenderPvs();
951
952        // read back the texture
953        im2 = grabFrameBuffer(true);
954       
955        diff = im1;
956        int x, y;
957        int errorPixels = 0;
958       
959        for (y = 0; y < im1.height(); y++)
960          for (x = 0; x < im1.width(); x++)
961                if (im1.pixel(x, y) == im2.pixel(x, y))
962                  diff.setPixel(x, y, qRgba(0,0,0,0));
963                else {
964                  diff.setPixel(x, y, qRgba(255,128,128,255));
965                  errorPixels++;
966                }
967        pErrorPixels = ((float)errorPixels)/(im1.height()*im1.width());
968  }
969
970  // now render the pvs again
971  SetupCamera();
972  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
973  mUseFalseColors = false;
974 
975  oi = mObjects.begin();
976  for (; oi != mObjects.end(); oi++)
977        RenderIntersectable(*oi);
978
979  // now render im1
980  if (viewcell) {
981        if (0 && mTopView) {
982          mWireFrame = true;
983          RenderIntersectable(viewcell);
984          mWireFrame = false;
985        }
986       
987        // init ortographic projection
988        glMatrixMode(GL_PROJECTION);
989        glPushMatrix();
990       
991        glLoadIdentity();
992        gluOrtho2D(0, 1.0f, 0, 1.0f);
993       
994        glMatrixMode(GL_MODELVIEW);
995        glLoadIdentity();
996       
997        bindTexture(diff);
998       
999        glPushAttrib(GL_ENABLE_BIT);
1000        glEnable( GL_ALPHA_TEST );
1001        glDisable( GL_CULL_FACE );
1002        glAlphaFunc( GL_GREATER, 0.5 );
1003       
1004        glEnable( GL_TEXTURE_2D );
1005        glBegin(GL_QUADS);
1006       
1007        glTexCoord2f(0,0);
1008        glVertex3f(0,0,0);
1009       
1010        glTexCoord2f(1,0);
1011        glVertex3f( 1, 0, 0);
1012       
1013        glTexCoord2f(1,1);
1014        glVertex3f( 1, 1, 0);
1015       
1016        glTexCoord2f(0,1);
1017        glVertex3f(0, 1, 0);
1018        glEnd();
1019       
1020        glPopAttrib();
1021       
1022        // restore the projection matrix
1023        glMatrixMode(GL_PROJECTION);
1024        glPopMatrix();
1025        glMatrixMode(GL_MODELVIEW);
1026  }
1027
1028  glDisable(GL_CLIP_PLANE0);
1029 
1030  mRenderError = pErrorPixels;
1031  return pErrorPixels;
1032}
1033
1034void
1035GlRenderer::_RenderScene()
1036{
1037  ObjectContainer::const_iterator oi = mObjects.begin();
1038  for (; oi != mObjects.end(); oi++)
1039        RenderIntersectable(*oi);
1040}
1041
1042bool
1043GlRenderer::RenderScene()
1044{
1045  static int glList = -1;
1046  if (mUseGlLists) {
1047        if (glList == -1) {
1048          glList = glGenLists(1);
1049          glNewList(glList, GL_COMPILE);
1050          _RenderScene();
1051          glEndList();
1052        }
1053        glCallList(glList);
1054  } else
1055        _RenderScene();
1056       
1057 
1058  return true;
1059}
1060
1061
1062void
1063GlRendererBuffer::ClearErrorBuffer()
1064{
1065  for (int i=0; i < mPvsStatFrames; i++) {
1066        mPvsErrorBuffer[i].mError = 1.0f;
1067  }
1068}
1069
1070
1071void
1072GlRendererBuffer::EvalPvsStat()
1073{
1074  mPvsStat.Reset();
1075  halton.Reset();
1076
1077  makeCurrent();
1078  SetupProjection(GetWidth(), GetHeight());
1079 
1080  for (int i=0; i < mPvsStatFrames; i++) {
1081        float err;
1082        // set frame id for saving the error buffer
1083        mFrame = i;
1084        RandomViewPoint();
1085
1086        // atlanta problematic frames: 325 525 691 1543
1087#if 0
1088        if (mFrame != 325 &&
1089                mFrame != 525 &&
1090                mFrame != 691 &&
1091                mFrame != 1543)
1092          mPvsErrorBuffer[i] = -1;
1093        else {
1094          Debug<<"frame ="<<mFrame<<" vp="<<mViewPoint<<" vd="<<mViewDirection<<endl;
1095        }
1096#endif
1097        if (mPvsErrorBuffer[i].mError > 0.0f) {
1098          int pvsSize;
1099          float error = GetPixelError(pvsSize);
1100          mPvsErrorBuffer[i].mError = error;
1101          mPvsErrorBuffer[i].mPvsSize = pvsSize;
1102
1103          emit UpdatePvsErrorItem(i,
1104                                                          mPvsErrorBuffer[i]);
1105         
1106          cout<<"("<<i<<","<<mPvsErrorBuffer[i].mError<<")";
1107          //      swapBuffers();
1108        }
1109       
1110        err = mPvsErrorBuffer[i].mError;
1111       
1112        if (err >= 0.0f) {
1113          if (err > mPvsStat.maxError)
1114                mPvsStat.maxError = err;
1115          mPvsStat.sumError += err;
1116          mPvsStat.sumPvsSize += mPvsErrorBuffer[i].mPvsSize;
1117         
1118          if (err == 0.0f)
1119                mPvsStat.errorFreeFrames++;
1120          mPvsStat.frames++;
1121        }
1122  }
1123
1124  glFinish();
1125  doneCurrent();
1126
1127  cout<<endl<<flush;
1128  //  mRenderingFinished.wakeAll();
1129}
1130
1131
1132
1133
1134
1135void
1136GlRendererWidget::mousePressEvent(QMouseEvent *e)
1137{
1138  int x = e->pos().x();
1139  int y = e->pos().y();
1140
1141  mousePoint.x = x;
1142  mousePoint.y = y;
1143 
1144}
1145
1146void
1147GlRendererWidget::mouseMoveEvent(QMouseEvent *e)
1148{
1149  float MOVE_SENSITIVITY = Magnitude(mSceneGraph->GetBox().Diagonal())*1e-3;
1150  float TURN_SENSITIVITY=0.1f;
1151  float TILT_SENSITIVITY=32.0 ;
1152  float TURN_ANGLE= M_PI/36.0 ;
1153
1154  int x = e->pos().x();
1155  int y = e->pos().y();
1156 
1157  if (e->modifiers() & Qt::ControlModifier) {
1158        mViewPoint.y += (y-mousePoint.y)*MOVE_SENSITIVITY/2.0;
1159        mViewPoint.x += (x-mousePoint.x)*MOVE_SENSITIVITY/2.0;
1160  } else {
1161        mViewPoint += mViewDirection*((mousePoint.y - y)*MOVE_SENSITIVITY);
1162        float adiff = TURN_ANGLE*(x - mousePoint.x)*-TURN_SENSITIVITY;
1163        float angle = atan2(mViewDirection.x, mViewDirection.z);
1164        mViewDirection.x = sin(angle+adiff);
1165        mViewDirection.z = cos(angle+adiff);
1166  }
1167 
1168  mousePoint.x = x;
1169  mousePoint.y = y;
1170 
1171  updateGL();
1172}
1173
1174void
1175GlRendererWidget::mouseReleaseEvent(QMouseEvent *)
1176{
1177
1178
1179}
1180
1181void
1182GlRendererWidget::resizeGL(int w, int h)
1183{
1184  SetupProjection(w, h);
1185  updateGL();
1186}
1187
1188void
1189GlRendererWidget::paintGL()
1190{
1191  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1192
1193 
1194  if (!mRenderViewCells) {
1195        if (mRenderErrors)
1196          RenderErrors();
1197        else
1198          RenderPvs();
1199        RenderInfo();
1200  } else {
1201        RenderViewCells();
1202       
1203        mWireFrame = true;
1204        RenderScene();
1205        mWireFrame = false;
1206       
1207        RenderInfo();
1208  }
1209
1210  mFrame++;
1211}
1212
1213
1214void
1215GlRendererWidget::SetupCamera()
1216{
1217  if (!mTopView)
1218        GlRenderer::SetupCamera();
1219  else {
1220        if (0) {
1221          float dist = Magnitude(mSceneGraph->GetBox().Diagonal())*0.05;
1222          Vector3 pos = mViewPoint - dist*Vector3(mViewDirection.x,
1223                                                                                          -1,
1224                                                                                          mViewDirection.y);
1225         
1226          Vector3 target = mViewPoint + dist*mViewDirection;
1227          Vector3 up(0,1,0);
1228         
1229          glLoadIdentity();
1230          gluLookAt(pos.x, pos.y, pos.z,
1231                                target.x, target.y, target.z,
1232                                up.x, up.y, up.z);
1233        } else {
1234          float dist = Magnitude(mSceneGraph->GetBox().Diagonal())*mTopDistance;
1235          Vector3 pos = mViewPoint  + dist*Vector3(0,
1236                                                                                           1,
1237                                                                                           0);
1238         
1239          Vector3 target = mViewPoint;
1240          Vector3 up(mViewDirection.x, 0, mViewDirection.z);
1241         
1242          glLoadIdentity();
1243          gluLookAt(pos.x, pos.y, pos.z,
1244                                target.x, target.y, target.z,
1245                                up.x, up.y, up.z);
1246         
1247        }
1248  }
1249
1250}
1251
1252void
1253GlRendererWidget::keyPressEvent ( QKeyEvent * e )
1254{
1255  switch (e->key()) {
1256  case Qt::Key_T:
1257        mTopView = !mTopView;
1258        SetupProjection(width(), height());
1259        updateGL();
1260        break;
1261  case Qt::Key_V:
1262        mRenderViewCells = !mRenderViewCells;
1263        updateGL();
1264        break;
1265  default:
1266        e->ignore();
1267        break;
1268  }
1269}
1270
1271 
1272RendererControlWidget::RendererControlWidget(QWidget * parent, Qt::WFlags f):
1273  QWidget(parent, f)
1274{
1275
1276  QVBoxLayout *vl = new QVBoxLayout;
1277  setLayout(vl);
1278 
1279  QWidget *vbox = new QGroupBox("ViewCells", this);
1280  layout()->addWidget(vbox);
1281 
1282  vl = new QVBoxLayout;
1283  vbox->setLayout(vl);
1284
1285  QLabel *label = new QLabel("Granularity");
1286  vbox->layout()->addWidget(label);
1287
1288  QSlider *slider = new QSlider(Qt::Horizontal, vbox);
1289  vl->addWidget(slider);
1290  slider->show();
1291  slider->setRange(1, 10000);
1292  slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
1293  slider->setValue(200);
1294
1295  connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetViewCellGranularity(int)));
1296
1297  label = new QLabel("Filter size");
1298  vbox->layout()->addWidget(label);
1299 
1300  slider = new QSlider(Qt::Horizontal, vbox);
1301  vbox->layout()->addWidget(slider);
1302  slider->show();
1303  slider->setRange(1, 100);
1304  slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
1305  slider->setValue(3);
1306 
1307  connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetVisibilityFilterSize(int)));
1308
1309
1310  label = new QLabel("Spatial Filter size");
1311  vbox->layout()->addWidget(label);
1312 
1313  slider = new QSlider(Qt::Horizontal, vbox);
1314  vbox->layout()->addWidget(slider);
1315  slider->show();
1316  slider->setRange(1, 100);
1317  slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
1318  slider->setValue(10);
1319 
1320  connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetSpatialFilterSize(int)));
1321
1322
1323
1324  QWidget *hbox = new QWidget(vbox);
1325  vl->addWidget(hbox);
1326  QHBoxLayout *hlayout = new QHBoxLayout;
1327  hbox->setLayout(hlayout);
1328 
1329  QCheckBox *cb = new QCheckBox("Show viewcells", hbox);
1330  hlayout->addWidget(cb);
1331  cb->setChecked(false);
1332  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowViewCells(bool)));
1333
1334  cb = new QCheckBox("Show render cost", hbox);
1335  hlayout->addWidget(cb);
1336  cb->setChecked(false);
1337  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowRenderCost(bool)));
1338
1339  cb = new QCheckBox("Show pvs sizes", hbox);
1340  hlayout->addWidget(cb);
1341  cb->setChecked(false);
1342  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowPvsSizes(bool)));
1343
1344  vbox->resize(800,100);
1345
1346 
1347  vbox = new QGroupBox("Rendering", this);
1348  layout()->addWidget(vbox);
1349 
1350  vl = new QVBoxLayout;
1351  vbox->setLayout(vl);
1352
1353
1354
1355  slider = new QSlider(Qt::Horizontal, vbox);
1356  vbox->layout()->addWidget(slider);
1357  slider->show();
1358  slider->setRange(0, 1000);
1359  slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
1360  slider->setValue(1000);
1361
1362  connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetSceneCut(int)));
1363
1364  cb = new QCheckBox("Render errors", vbox);
1365  vbox->layout()->addWidget(cb);
1366  cb->setChecked(false);
1367  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetRenderErrors(bool)));
1368
1369  cb = new QCheckBox("Use filter", vbox);
1370  vbox->layout()->addWidget(cb);
1371  cb->setChecked(true);
1372  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetUseFilter(bool)));
1373
1374  cb = new QCheckBox("Use spatial filter", vbox);
1375  vbox->layout()->addWidget(cb);
1376  cb->setChecked(true);
1377  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetUseSpatialFilter(bool)));
1378
1379  cb = new QCheckBox("Render filter", vbox);
1380  vbox->layout()->addWidget(cb);
1381  cb->setChecked(true);
1382  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetRenderFilter(bool)));
1383
1384
1385  cb = new QCheckBox("Cut view cells", vbox);
1386  vbox->layout()->addWidget(cb);
1387  cb->setChecked(false);
1388  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetCutViewCells(bool)));
1389
1390  cb = new QCheckBox("Cut scene", vbox);
1391  vbox->layout()->addWidget(cb);
1392  cb->setChecked(false);
1393  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetCutScene(bool)));
1394
1395 
1396  slider = new QSlider(Qt::Horizontal, vbox);
1397  vbox->layout()->addWidget(slider);
1398  slider->show();
1399  slider->setRange(1, 1000);
1400  slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
1401  slider->setValue(500);
1402 
1403  connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetTopDistance(int)));
1404 
1405  cb = new QCheckBox("Top View", vbox);
1406  vbox->layout()->addWidget(cb);
1407  cb->setChecked(false);
1408  connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetTopView(bool)));
1409
1410  vbox = new QGroupBox("PVS Errors", this);
1411  layout()->addWidget(vbox);
1412
1413  vl = new QVBoxLayout;
1414  vbox->setLayout(vl);
1415
1416  mPvsErrorWidget = new QListWidget(vbox);
1417  vbox->layout()->addWidget(mPvsErrorWidget);
1418 
1419  connect(mPvsErrorWidget,
1420                  SIGNAL(doubleClicked(const QModelIndex &)),
1421                  this,
1422                  SLOT(PvsErrorClicked(const QModelIndex &)));
1423 
1424  QPushButton *button = new QPushButton("Next Error Frame", vbox);
1425  vbox->layout()->addWidget(button);
1426  connect(button, SIGNAL(clicked(void)), SLOT(FocusNextPvsErrorFrame(void)));
1427
1428  setWindowTitle("Preprocessor Control Widget");
1429  adjustSize();
1430}
1431
1432
1433
1434void
1435RendererControlWidget::FocusNextPvsErrorFrame(void)
1436{
1437 
1438 
1439}
1440
1441void
1442RendererControlWidget::UpdatePvsErrorItem(int row,
1443                                                                                  GlRendererBuffer::PvsErrorEntry &pvsErrorEntry)
1444{
1445
1446  QListWidgetItem *i = mPvsErrorWidget->item(row);
1447  QString s;
1448  s.sprintf("%5.5f", pvsErrorEntry.mError);
1449  if (i) {
1450        i->setText(s);
1451  } else {
1452        new QListWidgetItem(s, mPvsErrorWidget);
1453  }
1454  mPvsErrorWidget->update();
1455}
1456
1457GlRendererWidget::GlRendererWidget(SceneGraph *sceneGraph,
1458                                                                   ViewCellsManager *viewcells,
1459                                                                   KdTree *tree,
1460                                                                   QWidget * parent,
1461                                                                   const QGLWidget * shareWidget,
1462                                                                   Qt::WFlags f
1463                                                                   )
1464  :
1465  GlRenderer(sceneGraph, viewcells, tree), QGLWidget(parent, shareWidget, f)
1466{
1467  mTopView = false;
1468  mRenderViewCells = false;
1469  mTopDistance = 1.0f;
1470  mCutViewCells = false;
1471  mCutScene = false;
1472  mRenderErrors = false;
1473  mRenderFilter = true;
1474  mUseFilter = true;
1475  mUseSpatialFilter = true;
1476  mShowRenderCost = false;
1477  mShowPvsSizes = false;
1478  mSpatialFilterSize = 0.01;
1479  mPvsSize = 0;
1480  mRenderError = 0.0f;
1481  mControlWidget = new RendererControlWidget(NULL);
1482 
1483  connect(mControlWidget, SIGNAL(SetViewCellGranularity(int)), this, SLOT(SetViewCellGranularity(int)));
1484  connect(mControlWidget, SIGNAL(SetSceneCut(int)), this, SLOT(SetSceneCut(int)));
1485  connect(mControlWidget, SIGNAL(SetTopDistance(int)), this, SLOT(SetTopDistance(int)));
1486
1487  connect(mControlWidget, SIGNAL(SetVisibilityFilterSize(int)), this, SLOT(SetVisibilityFilterSize(int)));
1488  connect(mControlWidget, SIGNAL(SetSpatialFilterSize(int)), this, SLOT(SetSpatialFilterSize(int)));
1489
1490  connect(mControlWidget, SIGNAL(SetShowViewCells(bool)), this, SLOT(SetShowViewCells(bool)));
1491  connect(mControlWidget, SIGNAL(SetShowRenderCost(bool)), this, SLOT(SetShowRenderCost(bool)));
1492  connect(mControlWidget, SIGNAL(SetShowPvsSizes(bool)), this, SLOT(SetShowPvsSizes(bool)));
1493  connect(mControlWidget, SIGNAL(SetTopView(bool)), this, SLOT(SetTopView(bool)));
1494  connect(mControlWidget, SIGNAL(SetCutViewCells(bool)), this, SLOT(SetCutViewCells(bool)));
1495  connect(mControlWidget, SIGNAL(SetCutScene(bool)), this, SLOT(SetCutScene(bool)));
1496  connect(mControlWidget, SIGNAL(SetRenderErrors(bool)), this, SLOT(SetRenderErrors(bool)));
1497  connect(mControlWidget, SIGNAL(SetRenderFilter(bool)), this, SLOT(SetRenderFilter(bool)));
1498  connect(mControlWidget, SIGNAL(SetUseFilter(bool)), this, SLOT(SetUseFilter(bool)));
1499  connect(mControlWidget, SIGNAL(SetUseSpatialFilter(bool)),
1500                  this, SLOT(SetUseSpatialFilter(bool)));
1501
1502 
1503  mControlWidget->show();
1504}
1505
1506void
1507GlRendererWidget::SetViewCellGranularity(int number)
1508{
1509  if (mViewCellsManager)
1510        //      mViewCellsManager->SetMaxFilterSize(number);
1511    mViewCellsManager->CollectViewCells(number);
1512
1513  updateGL();
1514}
1515
1516void
1517GlRendererWidget::SetVisibilityFilterSize(int number)
1518{
1519  if (mViewCellsManager)
1520        mViewCellsManager->SetMaxFilterSize(number);
1521  updateGL();
1522}
1523
1524void
1525GlRendererWidget::SetSpatialFilterSize(int number)
1526{
1527  mSpatialFilterSize = 1e-3*number;
1528  updateGL();
1529}
1530
1531void
1532GlRendererWidget::SetSceneCut(int number)
1533{
1534  // assume the cut plane can only be aligned with xz plane
1535  // shift it along y according to number, which is percentage of the bounding
1536  // box position
1537  if (mViewCellsManager) {
1538        AxisAlignedBox3 box = mViewCellsManager->GetViewSpaceBox();
1539        Vector3 p = box.Min() + (number/1000.0f)*box.Max();
1540        mSceneCutPlane.mNormal = Vector3(0,-1,0);
1541        mSceneCutPlane.mD = -DotProd(mSceneCutPlane.mNormal, p);
1542        updateGL();
1543  }
1544}
1545
1546void
1547GlRendererWidget::SetTopDistance(int number)
1548{
1549  mTopDistance = number/1000.0f;
1550  updateGL();
1551}
1552
1553void
1554GlRendererWidget::RenderViewCells()
1555{
1556  mUseFalseColors = true;
1557
1558  SetupCamera();
1559  glEnable(GL_CULL_FACE);
1560  //glDisable(GL_CULL_FACE);
1561  glCullFace(GL_FRONT);
1562  double eq[4];
1563  eq[0] = mSceneCutPlane.mNormal.x;
1564  eq[1] = mSceneCutPlane.mNormal.y;
1565  eq[2] = mSceneCutPlane.mNormal.z;
1566  eq[3] = mSceneCutPlane.mD;
1567
1568  if (mCutViewCells) {
1569        glClipPlane(GL_CLIP_PLANE0, eq);
1570        glEnable(GL_CLIP_PLANE0);
1571  }
1572 
1573  int i;
1574  ViewCellContainer &viewcells = mViewCellsManager->GetViewCells();
1575  int maxPvs = -1;
1576  for (i=0; i < viewcells.size(); i++) {
1577        ViewCell *vc = viewcells[i];
1578        int p = vc->GetPvs().GetSize();
1579        if (p > maxPvs)
1580          maxPvs = p;
1581  }
1582
1583
1584  for (i=0; i < viewcells.size(); i++) {
1585        ViewCell *vc = viewcells[i];
1586        //      Mesh *m = vc->GetMesh();
1587
1588
1589        RgbColor c;
1590
1591        if (!mShowPvsSizes)
1592          c = vc->GetColor();
1593        else {
1594          float importance = (float)vc->GetPvs().GetSize() / (float)maxPvs;
1595          c = RgbColor(importance, 1.0f - importance, 0.0f);
1596        }
1597        glColor3f(c.r, c.g, c.b);
1598       
1599        RenderViewCell(vc);
1600  }
1601
1602  glDisable(GL_CLIP_PLANE0);
1603
1604}
1605
1606void GlRendererBuffer::SampleBeamContributions(Intersectable *sourceObject,
1607                                                                                           Beam &beam,
1608                                                                                           const int desiredSamples,
1609                                                                                           BeamSampleStatistics &stat)
1610{
1611        // TODO: should be moved out of here (not to be done every time)
1612        // only back faces are interesting for the depth pass
1613        glShadeModel(GL_FLAT);
1614        glDisable(GL_LIGHTING);
1615
1616        // needed to kill the fragments for the front buffer
1617        glEnable(GL_ALPHA_TEST);
1618        glAlphaFunc(GL_GREATER, 0);
1619
1620        // assumes that the beam is constructed and contains kd-tree nodes
1621        // and viewcells which it intersects
1622 
1623 
1624        // Get the number of viewpoints to be sampled
1625        // Now it is a sqrt but in general a wiser decision could be made.
1626        // The less viewpoints the better for rendering performance, since less passes
1627        // over the beam is needed.
1628        // The viewpoints could actually be generated outside of the bounding box which
1629        // would distribute the 'efective viewpoints' of the object surface and thus
1630        // with a few viewpoints better sample the viewpoint space....
1631
1632        //TODO: comment in
1633        //int viewPointSamples = sqrt((float)desiredSamples);
1634        int viewPointSamples = max(desiredSamples / (GetWidth() * GetHeight()), 1);
1635       
1636        // the number of direction samples per pass is given by the number of viewpoints
1637        int directionalSamples = desiredSamples / viewPointSamples;
1638       
1639        Debug << "directional samples: " << directionalSamples << endl;
1640        for (int i = 0; i < viewPointSamples; ++ i)
1641        {
1642                Vector3 viewPoint = beam.mBox.GetRandomPoint();
1643               
1644                // perhaps the viewpoint should be shifted back a little bit so that it always lies
1645                // inside the source object
1646                // 'ideally' the viewpoints would be distributed on the soureObject surface, but this
1647        // would require more complicated sampling (perhaps hierarchical rejection sampling of
1648                // the object surface is an option here - only the mesh faces which are inside the box
1649                // are considered as candidates)
1650               
1651                SampleViewpointContributions(sourceObject,
1652                                                                         viewPoint,
1653                                                                         beam,
1654                                                                         directionalSamples,
1655                                                                         stat);
1656        }
1657
1658
1659        // note:
1660        // this routine would be called only if the number of desired samples is sufficiently
1661        // large - for other rss tree cells the cpu based sampling is perhaps more efficient
1662        // distributing the work between cpu and gpu would also allow us to place more sophisticated
1663        // sample distributions (silhouette ones) using the cpu and the jittered once on the GPU
1664        // in order that thios scheme is working well the gpu render buffer should run in a separate
1665        // thread than the cpu sampler, which would not be such a big problem....
1666
1667        // disable alpha test again
1668        glDisable(GL_ALPHA_TEST);
1669}
1670
1671
1672void GlRendererBuffer::SampleViewpointContributions(Intersectable *sourceObject,
1673                                                                                                        const Vector3 viewPoint,
1674                                                                                                        Beam &beam,
1675                                                                                                        const int samples,
1676                                                    BeamSampleStatistics &stat)
1677{
1678    // 1. setup the view port to match the desired samples
1679        glViewport(0, 0, samples, samples);
1680
1681        // 2. setup the projection matrix and view matrix to match the viewpoint + beam.mDirBox
1682        SetupProjectionForViewPoint(viewPoint, beam, sourceObject);
1683
1684
1685        // 3. reset z-buffer to 0 and render the source object for the beam
1686        //    with glCullFace(Enabled) and glFrontFace(GL_CW)
1687        //    save result to the front depth map
1688        //    the front depth map holds ray origins
1689
1690
1691        // front depth buffer must be initialised to 0
1692        float clearDepth;
1693       
1694        glGetFloatv(GL_DEPTH_CLEAR_VALUE, &clearDepth);
1695        glClearDepth(0.0f);
1696        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
1697
1698
1699        //glFrontFace(GL_CW);
1700        glEnable(GL_CULL_FACE);
1701        glCullFace(GL_FRONT);
1702        glColorMask(0, 0, 0, 0);
1703       
1704
1705        // stencil is increased where the source object is located
1706        glEnable(GL_STENCIL_TEST);     
1707        glStencilFunc(GL_ALWAYS, 0x1, 0x1);
1708        glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
1709
1710
1711#if 0
1712        static int glSourceObjList = -1;         
1713        if (glSourceObjList != -1)
1714        {
1715                glSourceObjList = glGenLists(1);
1716                glNewList(glSourceObjList, GL_COMPILE);
1717
1718                RenderIntersectable(sourceObject);
1719       
1720                glEndList();
1721        }
1722        glCallList(glSourceObjList);
1723
1724#else
1725        RenderIntersectable(sourceObject);
1726
1727#endif 
1728
1729         // copy contents of the front depth buffer into depth texture
1730        glBindTexture(GL_TEXTURE_2D, frontDepthMap);   
1731        glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, depthMapSize, depthMapSize);
1732
1733
1734        // reset clear function
1735        glClearDepth(clearDepth);
1736
1737       
1738       
1739        // 4. set up the termination depth buffer (= standard depth buffer)
1740        //    only rays which have non-zero entry in the origin buffer are valid since
1741        //    they realy start on the object surface (this is tagged by setting a
1742        //    stencil buffer bit at step 3).
1743       
1744        glStencilFunc(GL_EQUAL, 0x1, 0x1);
1745        glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
1746
1747        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1748        glDepthMask(1);
1749
1750        glEnable(GL_DEPTH_TEST);
1751               
1752        glEnable(GL_CULL_FACE);
1753        glCullFace(GL_BACK);
1754
1755        // setup front depth buffer
1756        glEnable(GL_TEXTURE_2D);
1757       
1758        // bind pixel shader implementing the front depth buffer functionality
1759        cgGLBindProgram(sCgFragmentProgram);
1760        cgGLEnableProfile(sCgFragmentProfile);
1761
1762
1763        // 5. render all objects inside the beam
1764        //    we can use id based false color to read them back for gaining the pvs
1765
1766        glColorMask(1, 1, 1, 1);
1767
1768       
1769        // if objects not stored in beam => extract objects
1770        if (beam.mFlags & !Beam::STORE_OBJECTS)
1771        {
1772                vector<KdNode *>::const_iterator it, it_end = beam.mKdNodes.end();
1773
1774                Intersectable::NewMail();
1775                for (it = beam.mKdNodes.begin(); it != it_end; ++ it)
1776                {
1777                        mKdTree->CollectObjects(*it, beam.mObjects);
1778                }
1779        }
1780
1781
1782        //    (objects can be compiled to a gl list now so that subsequent rendering for
1783        //    this beam is fast - the same hold for step 3)
1784        //    Afterwards we have two depth buffers defining the ray origin and termination
1785       
1786
1787#if 0
1788        static int glObjList = -1;
1789        if (glObjList != -1)
1790        {
1791                glObjList = glGenLists(1);
1792                glNewList(glObjList, GL_COMPILE);
1793       
1794                ObjectContainer::const_iterator it, it_end = beam.mObjects.end();
1795                for (it = beam.mObjects.begin(); it != it_end; ++ it)
1796                {
1797                        // render all objects except the source object
1798                        if (*it != sourceObject)
1799                                RenderIntersectable(*it);
1800                }
1801               
1802                glEndList();
1803        }
1804
1805        glCallList(glObjList);
1806#else
1807        ObjectContainer::const_iterator it, it_end = beam.mObjects.end();
1808        for (it = beam.mObjects.begin(); it != it_end; ++ it)
1809        {       
1810                // render all objects except the source object
1811                if (*it != sourceObject)
1812                        RenderIntersectable(*it);
1813        }
1814#endif
1815       
1816   
1817
1818        // 6. Use occlusion queries for all viewcell meshes associated with the beam ->
1819        //     a fragment passes if the corresponding stencil fragment is set and its depth is
1820        //     between origin and termination buffer
1821
1822        // create new queries if necessary
1823        GenQueries((int)beam.mViewCells.size());
1824
1825        // check whether any backfacing polygon would pass the depth test?
1826        // matt: should check both back /front facing because of dual depth buffer
1827        // and danger of cutting the near plane with front facing polys.
1828       
1829        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1830        glDepthMask(GL_FALSE);
1831        glDisable(GL_CULL_FACE);
1832
1833 
1834        ViewCellContainer::const_iterator vit, vit_end = beam.mViewCells.end();
1835
1836        int queryIdx = 0;
1837
1838        for (vit = beam.mViewCells.begin(); vit != vit_end; ++ vit)
1839        {
1840                glBeginOcclusionQueryNV(sQueries[queryIdx ++]);
1841
1842                RenderIntersectable(*vit);
1843               
1844                glEndOcclusionQueryNV();
1845        }
1846
1847
1848
1849        // at this point, if possible, go and do some other computation
1850
1851
1852       
1853        // 7. The number of visible pixels is the number of sample rays which see the source
1854        //    object from the corresponding viewcell -> remember these values for later update
1855        //   of the viewcell pvs - or update immediately?
1856
1857        queryIdx = 0;
1858        unsigned int pixelCount;
1859
1860        for (vit = beam.mViewCells.begin(); vit != vit_end; ++ vit)
1861        {
1862                // fetch queries
1863                glGetOcclusionQueryuivNV(sQueries[queryIdx ++],
1864                                                                 GL_PIXEL_COUNT_NV,
1865                                                                 &pixelCount);
1866                if (pixelCount)
1867                        Debug << "view cell " << (*vit)->GetId() << " visible pixels: " << pixelCount << endl;
1868        }
1869       
1870
1871        // 8. Copmpute rendering statistics
1872        // In general it is not neccessary to remember to extract all the rays cast. I hope it
1873        // would be sufficient to gain only the intergral statistics about the new contributions
1874        // and so the rss tree would actually store no new rays (only the initial ones)
1875        // the subdivision of the tree would only be driven by the statistics (the glrender could
1876        // evaluate the contribution entropy for example)
1877        // However might be an option to extract/store only those the rays which made a contribution
1878        // (new viewcell has been discovered) or relative contribution greater than a threshold ...
1879
1880        ObjectContainer pvsObj;
1881        stat.pvsSize = ComputePvs(beam.mObjects, pvsObj);
1882       
1883        // to gain ray source and termination
1884        // copy contents of ray termination buffer into depth texture
1885        // and compare with ray source buffer
1886#if 0
1887        VssRayContainer rays;
1888
1889        glBindTexture(GL_TEXTURE_2D, backDepthMap);     
1890        glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, depthMapSize, depthMapSize);
1891
1892        ComputeRays(Intersectable *sourceObj, rays);
1893
1894#endif
1895
1896
1897
1898        //-- cleanup
1899
1900
1901        // reset gl state
1902        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1903        glDepthMask(GL_TRUE);
1904        glEnable(GL_CULL_FACE);
1905        glDisable(GL_STENCIL_TEST);
1906        cgGLDisableProfile(sCgFragmentProfile);
1907        glDisable(GL_TEXTURE_2D);
1908
1909        // remove objects from beam
1910        if (beam.mFlags & !Beam::STORE_OBJECTS)
1911                beam.mObjects.clear();
1912}
1913
1914
1915void GlRendererBuffer::GenQueries(const int numQueries)
1916{
1917        if ((int)sQueries.size() < numQueries)
1918        {
1919                const int n = numQueries - (int)sQueries.size();
1920                unsigned int *newQueries = new unsigned int[n];
1921
1922                glGenOcclusionQueriesNV(n, (unsigned int *)newQueries);
1923
1924                for (int i = 0; i < n; ++ i)
1925                {
1926                        sQueries.push_back(newQueries[i]);
1927                }
1928
1929                delete [] newQueries;
1930        }
1931}
1932
1933
1934void GlRendererBuffer::SetupProjectionForViewPoint(const Vector3 &viewPoint,
1935                                                                                                   const Beam &beam,
1936                                                                                                   Intersectable *sourceObject)
1937{
1938        float left, right, bottom, top, znear, zfar;
1939
1940        beam.ComputePerspectiveFrustum(left, right, bottom, top, znear, zfar,
1941                                                                   mSceneGraph->GetBox());
1942
1943        //Debug << left << " " << right << " " << bottom << " " << top << " " << znear << " " << zfar << endl;
1944        glMatrixMode(GL_PROJECTION);
1945        glLoadIdentity();
1946        glFrustum(left, right, bottom, top, znear, zfar);
1947        //glFrustum(-1, 1, -1, 1, 1, 20000);
1948
1949    const Vector3 center = viewPoint + beam.GetMainDirection() * (zfar - znear) * 0.3f;
1950        const Vector3 up =
1951                Normalize(CrossProd(beam.mPlanes[0].mNormal, beam.mPlanes[4].mNormal));
1952
1953#ifdef _DEBUG
1954        Debug << "view point: " << viewPoint << endl;
1955        Debug << "eye: " << center << endl;
1956        Debug << "up: " << up << endl;
1957#endif
1958
1959        glMatrixMode(GL_MODELVIEW);
1960        glLoadIdentity();
1961        gluLookAt(viewPoint.x, viewPoint.y, viewPoint.z,
1962                          center.x, center.y, center.z,                   
1963                          up.x, up.y, up.z);
1964}               
1965
1966 
1967void GlRendererBuffer::InitGL()
1968{
1969 makeCurrent();
1970 GlRenderer::InitGL();
1971
1972#if 1
1973        // initialise dual depth buffer textures
1974        glGenTextures(1, &frontDepthMap);
1975        glBindTexture(GL_TEXTURE_2D, frontDepthMap);
1976       
1977        glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, depthMapSize,
1978                depthMapSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
1979        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1980        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1981        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
1982        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
1983
1984        glGenTextures(1, &backDepthMap);
1985        glBindTexture(GL_TEXTURE_2D, backDepthMap);
1986       
1987        glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, depthMapSize,
1988                depthMapSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
1989        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1990        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1991        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
1992        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
1993
1994        // cg initialization
1995        cgSetErrorCallback(handleCgError);
1996        sCgContext = cgCreateContext();
1997       
1998        if (cgGLIsProfileSupported(CG_PROFILE_ARBFP1))
1999                sCgFragmentProfile = CG_PROFILE_ARBFP1;
2000        else
2001        {
2002          // try FP30
2003          if (cgGLIsProfileSupported(CG_PROFILE_FP30))
2004            sCgFragmentProfile = CG_PROFILE_FP30;
2005          else
2006          {
2007                  Debug << "Neither arbfp1 or fp30 fragment profiles supported on this system" << endl;
2008                  exit(1);
2009          }
2010  }
2011
2012
2013 sCgFragmentProgram = cgCreateProgramFromFile(sCgContext,
2014                                                                                           CG_SOURCE, "../src/dual_depth.cg",
2015                                                                                           sCgFragmentProfile,
2016                                                                                           NULL,
2017                                                                                           NULL);
2018
2019  if (!cgIsProgramCompiled(sCgFragmentProgram))
2020          cgCompileProgram(sCgFragmentProgram);
2021
2022  cgGLLoadProgram(sCgFragmentProgram);
2023  cgGLBindProgram(sCgFragmentProgram);
2024
2025  Debug << "---- PROGRAM BEGIN ----\n" <<
2026          cgGetProgramString(sCgFragmentProgram, CG_COMPILED_PROGRAM) << "---- PROGRAM END ----\n";
2027
2028#endif
2029  doneCurrent();
2030}
2031
2032
2033void GlRendererBuffer::ComputeRays(Intersectable *sourceObj, VssRayContainer &rays)
2034{
2035        for (int i = 0; i < depthMapSize * depthMapSize; ++ i)
2036        {
2037                //todo glGetTexImage()
2038        }
2039}
2040
2041
2042
2043inline bool ilt(Intersectable *obj1, Intersectable *obj2)
2044{
2045        return obj1->mId < obj2->mId;
2046}
2047
2048
2049int GlRendererBuffer::ComputePvs(ObjectContainer &objects,
2050                                                                 ObjectContainer &pvs) const
2051{
2052        int pvsSize = 0;
2053        QImage image = toImage();
2054        Intersectable::NewMail();
2055
2056        std::stable_sort(objects.begin(), objects.end(), ilt);
2057
2058        MeshInstance dummy(NULL);
2059
2060        Intersectable *obj = NULL;
2061                       
2062        for (int x = 0; x < image.width(); ++ x)
2063        {
2064                for (int y = 0; y < image.height(); ++ y)
2065                {
2066                        QRgb pix = image.pixel(x, y);
2067                        const int id = GetId(qRed(pix), qGreen(pix), qBlue(pix));
2068
2069                        dummy.SetId(id);
2070
2071                        ObjectContainer::iterator oit =
2072                                lower_bound(objects.begin(), objects.end(), &dummy, ilt);
2073                       
2074                       
2075                        if (//(oit != oit.end()) &&
2076                                ((*oit)->GetId() == id) &&
2077                                !obj->Mailed())
2078                        {
2079                                obj = *oit;
2080                                obj->Mail();
2081                                ++ pvsSize;
2082                                pvs.push_back(obj);
2083                        }
2084                }
2085        }
2086
2087        return pvsSize;
2088}
2089
2090/***********************************************************************/
2091/*                     GlDebuggerWidget implementation                             */
2092/***********************************************************************/
2093
2094
2095GlDebuggerWidget::GlDebuggerWidget(GlRendererBuffer *buf, QWidget *parent)
2096      : QGLWidget(QGLFormat(QGL::SampleBuffers), parent), mRenderBuffer(buf)
2097{
2098        // create the pbuffer
2099    //pbuffer = new QGLPixelBuffer(QSize(512, 512), format(), this);
2100    timerId = startTimer(20);
2101    setWindowTitle(("OpenGL pbuffers"));
2102}
2103
2104
2105GlDebuggerWidget::~GlDebuggerWidget()
2106{
2107 mRenderBuffer->releaseFromDynamicTexture();
2108   glDeleteTextures(1, &dynamicTexture);
2109         
2110         DEL_PTR(mRenderBuffer);
2111}
2112
2113
2114void GlDebuggerWidget::initializeGL()
2115{
2116        glMatrixMode(GL_PROJECTION);
2117        glLoadIdentity();
2118
2119        glFrustum(-1, 1, -1, 1, 10, 100);
2120        glTranslatef(-0.5f, -0.5f, -0.5f);
2121        glTranslatef(0.0f, 0.0f, -15.0f);
2122        glMatrixMode(GL_MODELVIEW);
2123
2124        glEnable(GL_CULL_FACE);
2125        initCommon();
2126        initPbuffer();
2127
2128}
2129
2130
2131void GlDebuggerWidget::resizeGL(int w, int h)
2132{
2133        glViewport(0, 0, w, h);
2134}
2135
2136
2137void GlDebuggerWidget::paintGL()
2138{
2139        // draw a spinning cube into the pbuffer..
2140        mRenderBuffer->makeCurrent();
2141       
2142        BeamSampleStatistics stats;
2143        mRenderBuffer->SampleBeamContributions(mSourceObject, mBeam, mSamples, stats);
2144
2145        glFlush();
2146
2147        // rendering directly to a texture is not supported on X11, unfortunately
2148    mRenderBuffer->updateDynamicTexture(dynamicTexture);
2149   
2150    // and use the pbuffer contents as a texture when rendering the
2151    // background and the bouncing cubes
2152    makeCurrent();
2153    glBindTexture(GL_TEXTURE_2D, dynamicTexture);
2154    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2155
2156    // draw the background
2157    glMatrixMode(GL_MODELVIEW);
2158    glPushMatrix();
2159    glLoadIdentity();
2160    glMatrixMode(GL_PROJECTION);
2161    glPushMatrix();
2162    glLoadIdentity();
2163
2164        glPopMatrix();
2165        glMatrixMode(GL_MODELVIEW);
2166        glPopMatrix();
2167}
2168
2169
2170void GlDebuggerWidget::initPbuffer()
2171{
2172        // set up the pbuffer context
2173    mRenderBuffer->makeCurrent();
2174        /*mRenderBuffer->InitGL();
2175
2176        glViewport(0, 0, mRenderBuffer->size().width(), mRenderBuffer->size().height());
2177        glMatrixMode(GL_PROJECTION);
2178        glLoadIdentity();
2179        glOrtho(-1, 1, -1, 1, -99, 99);
2180        glTranslatef(-0.5f, -0.5f, 0.0f);
2181        glMatrixMode(GL_MODELVIEW);
2182        glLoadIdentity();
2183
2184        glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);*/
2185       
2186        // generate a texture that has the same size/format as the pbuffer
2187    dynamicTexture = mRenderBuffer->generateDynamicTexture();
2188
2189        // bind the dynamic texture to the pbuffer - this is a no-op under X11
2190        mRenderBuffer->bindToDynamicTexture(dynamicTexture);
2191        makeCurrent();
2192}
2193
2194void GlDebuggerWidget::initCommon()
2195{
2196        glEnable(GL_TEXTURE_2D);
2197        glEnable(GL_DEPTH_TEST);
2198
2199        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
2200}
2201
2202}
Note: See TracBrowser for help on using the repository browser.