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

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

visibility filter updates

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