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

Revision 997, 55.5 KB checked in by mattausch, 18 years ago (diff)

fixed bug for histogram
improved samplerenderer
todo: difference detectempty true / false

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