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

Revision 884, 54.5 KB checked in by bittner, 18 years ago (diff)

Spatial visibility filter

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