source: trunk/VUT/GtpVisibilityPreprocessor/src/GlRenderer.cpp @ 599

Revision 599, 33.9 KB checked in by bittner, 18 years ago (diff)

slider visualization

  • 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#include <GL/glext.h>
12#include <Cg/cg.h>
13#include <Cg/cgGL.h>
14
15static CGcontext sCgContext = NULL;
16static CGprogram sCgFragmentProgram = NULL;
17static CGprofile sCgFragmentProfile;
18
19GLuint frontDepthMap;
20GLuint backDepthMap;
21
22const int depthMapSize = 512;
23static vector<int> sQueries;
24
25GlRendererWidget *rendererWidget = NULL;
26GlDebuggerWidget *debuggerWidget = NULL;
27
28
29#ifdef _WIN32
30PFNGLGENOCCLUSIONQUERIESNVPROC glGenOcclusionQueriesNV;
31PFNGLBEGINOCCLUSIONQUERYNVPROC glBeginOcclusionQueryNV;
32PFNGLENDOCCLUSIONQUERYNVPROC glEndOcclusionQueryNV;
33PFNGLGETOCCLUSIONQUERYUIVNVPROC glGetOcclusionQueryuivNV;
34#endif
35
36GlRenderer::GlRenderer(SceneGraph *sceneGraph,
37                                           ViewCellsManager *viewCellsManager,
38                                           KdTree *tree):
39  Renderer(sceneGraph, viewCellsManager),
40  mKdTree(tree)
41{
42  mSceneGraph->CollectObjects(&mObjects);
43  mViewPoint = mSceneGraph->GetBox().Center();
44  mViewDirection = Vector3(0,0,1);
45  //  timerId = startTimer(10);
46  // debug coords for atlanta
47  mViewPoint = Vector3(3473, 6.778, -1699);
48  mViewDirection = Vector3(-0.2432, 0, 0.97);
49 
50  mFrame = 0;
51  mWireFrame = false;
52  environment->GetBoolValue("Preprocessor.detectEmptyViewSpace", mDetectEmptyViewSpace);
53  mSnapErrorFrames = false;
54  mSnapPrefix = "";
55
56}
57
58GlRenderer::~GlRenderer()
59{
60  cerr<<"gl renderer destructor..\n";
61  if (sCgFragmentProgram)
62        cgDestroyProgram(sCgFragmentProgram);
63  if (sCgContext)
64        cgDestroyContext(sCgContext);
65  cerr<<"done."<<endl;
66}
67
68
69static void handleCgError()
70{
71    Debug << "Cg error: " << cgGetErrorString(cgGetError()) << endl;
72    exit(1);
73}
74
75void
76GlRenderer::RenderIntersectable(Intersectable *object)
77{
78
79  glPushAttrib(GL_CURRENT_BIT);
80  if (mUseFalseColors)
81        SetupFalseColor(object->mId);
82 
83
84  switch (object->Type()) {
85  case Intersectable::MESH_INSTANCE:
86        RenderMeshInstance((MeshInstance *)object);
87        break;
88  case Intersectable::VIEW_CELL:
89          RenderViewCell(dynamic_cast<ViewCell *>(object));
90          break;
91  default:
92        cerr<<"Rendering this object not yet implemented\n";
93        break;
94  }
95
96  glPopAttrib();
97}
98
99
100void
101GlRenderer::RenderViewCell(ViewCell *vc)
102{
103  if (vc->GetMesh()) {
104
105        if (!mUseFalseColors) {
106          if (vc->GetValid())
107                glColor3f(0,1,0);
108          else
109                glColor3f(0,0,1);
110        }
111       
112        RenderMesh(vc->GetMesh());
113  } else {
114        // render viewcells in the subtree
115        if (!vc->IsLeaf()) {
116          ViewCellInterior *vci = (ViewCellInterior *) vc;
117
118          ViewCellContainer::iterator it = vci->mChildren.begin();
119          for (; it != vci->mChildren.end(); ++it) {
120                RenderViewCell(*it);
121          }
122        }
123  }
124}
125
126
127void
128GlRenderer::RenderMeshInstance(MeshInstance *mi)
129{
130  RenderMesh(mi->GetMesh());
131}
132
133void
134GlRenderer::SetupFalseColor(const int id)
135{
136  // swap bits of the color
137 
138  glColor3ub(id&255, (id>>8)&255, (id>>16)&255);
139}
140
141
142int GlRenderer::GetId(int r, int g, int b) const
143{
144        return r + (g << 8) + (b << 16);
145}
146
147void
148GlRenderer::SetupMaterial(Material *m)
149{
150  if (m)
151        glColor3fv(&(m->mDiffuseColor.r));
152}
153
154void
155GlRenderer::RenderMesh(Mesh *mesh)
156{
157  int i = 0;
158
159  if (!mUseFalseColors)
160        SetupMaterial(mesh->mMaterial);
161 
162  for (i=0; i < mesh->mFaces.size(); i++) {
163        if (mWireFrame)
164          glBegin(GL_LINE_LOOP);
165        else
166          glBegin(GL_POLYGON);
167
168        Face *face = mesh->mFaces[i];
169        for (int j = 0; j < face->mVertexIndices.size(); j++) {
170          glVertex3fv(&mesh->mVertices[face->mVertexIndices[j]].x);
171        }
172        glEnd();
173  }
174}
175       
176void
177GlRenderer::InitGL()
178{
179  glMatrixMode(GL_PROJECTION);
180  glLoadIdentity();
181 
182  glMatrixMode(GL_MODELVIEW);
183  glLoadIdentity();
184
185  glEnable(GL_CULL_FACE);
186  glShadeModel(GL_FLAT);
187  glEnable(GL_DEPTH_TEST);
188  glEnable(GL_CULL_FACE);
189 
190  glGenOcclusionQueriesNV = (PFNGLGENOCCLUSIONQUERIESNVPROC)
191        wglGetProcAddress("glGenOcclusionQueriesNV");
192  glBeginOcclusionQueryNV = (PFNGLBEGINOCCLUSIONQUERYNVPROC)
193        wglGetProcAddress("glBeginOcclusionQueryNV");
194  glEndOcclusionQueryNV = (PFNGLENDOCCLUSIONQUERYNVPROC)
195        wglGetProcAddress("glEndOcclusionQueryNV");
196  glGetOcclusionQueryuivNV = (PFNGLGETOCCLUSIONQUERYUIVNVPROC)
197        wglGetProcAddress("glGetOcclusionQueryuivNV");
198
199        glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
200
201}
202
203void
204GlRendererWidget::RenderInfo()
205{
206  QString s;
207  s.sprintf("frame:%04d viewpoint:(%4.1f,%4.1f,%4.1f) dir:(%4.1f,%4.1f,%4.1f)",
208                        mFrame,
209                        mViewPoint.x,
210                        mViewPoint.y,
211                        mViewPoint.z,
212                        mViewDirection.x,
213                        mViewDirection.y,
214                        mViewDirection.z
215
216                        );
217  renderText(0,20,s);
218}
219
220
221void
222GlRenderer::SetupProjection(const int w, const int h)
223{
224  glViewport(0, 0, w, h);
225  glMatrixMode(GL_PROJECTION);
226  glLoadIdentity();
227  gluPerspective(70.0, 1.0, 0.1, 2.0*Magnitude(mSceneGraph->GetBox().Diagonal()));
228  glMatrixMode(GL_MODELVIEW);
229}
230
231void
232GlRenderer::SetupCamera()
233{
234  Vector3 target = mViewPoint + mViewDirection;
235  Vector3 up(0,1,0);
236 
237  glLoadIdentity();
238  gluLookAt(mViewPoint.x, mViewPoint.y, mViewPoint.z,
239                        target.x, target.y, target.z,
240                        up.x, up.y, up.z);
241}
242
243void
244GlRendererBuffer::RandomViewPoint()
245{
246 
247 
248  // do not use this function since it could return different viewpoints for
249  // different executions of the algorithm
250
251  //mViewCellsManager->GetViewPoint(mViewPoint);
252
253  while (1) {
254        Vector3 pVector = Vector3(halton.GetNumber(1),
255                                                          halton.GetNumber(2),
256                                                          halton.GetNumber(3));
257       
258        mViewPoint =  mSceneGraph->GetBox().GetPoint(pVector);
259        ViewCell *v = mViewCellsManager->GetViewCell(mViewPoint);
260        if (v && v->GetValid())
261          break;
262        // generate a new vector
263        halton.GenerateNext();
264  }
265 
266 
267  Vector3 dVector = Vector3(2*M_PI*halton.GetNumber(4),
268                                                        M_PI*halton.GetNumber(5),
269                                                        0.0f);
270 
271  mViewDirection = Normalize(Vector3(sin(dVector.x),
272                                                                         //                                                                      cos(dVector.y),
273                                                                         0.0f,
274                                                                         cos(dVector.x)));
275  halton.GenerateNext();
276}
277
278
279GlRendererBuffer::GlRendererBuffer(const int w,
280                                                                   const int h,
281                                                                   SceneGraph *sceneGraph,
282                                                                   ViewCellsManager *viewcells,
283                                                                   KdTree *tree):
284QGLPixelBuffer(QSize(w, h)), GlRenderer(sceneGraph, viewcells, tree) {
285 
286 environment->GetIntValue("Preprocessor.pvsRenderErrorSamples", mPvsStatFrames);
287   mPvsErrorBuffer.resize(mPvsStatFrames);
288         ClearErrorBuffer();
289           
290           InitGL();
291                 
292                 }
293
294float
295GlRendererBuffer::GetPixelError()
296{
297  float pErrorPixels = -1.0f;
298
299  glReadBuffer(GL_BACK);
300 
301  //  mUseFalseColors = true;
302 
303  mUseFalseColors = false;
304
305  static int query = -1;
306  unsigned int pixelCount;
307
308  if (query == -1)
309        glGenOcclusionQueriesNV(1, (unsigned int *)&query);
310
311  if (mDetectEmptyViewSpace) {
312        // now check whether any backfacing polygon would pass the depth test
313        SetupCamera();
314        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
315        glEnable( GL_CULL_FACE );
316       
317        RenderScene();
318       
319        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
320        glDepthMask(GL_FALSE);
321        glDisable( GL_CULL_FACE );
322       
323        glBeginOcclusionQueryNV(query);
324       
325        RenderScene();
326       
327        glEndOcclusionQueryNV();
328       
329        // at this point, if possible, go and do some other computation
330        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
331        glDepthMask(GL_TRUE);
332        glEnable( GL_CULL_FACE );
333       
334        // reenable other state
335        glGetOcclusionQueryuivNV(query,
336                                                         GL_PIXEL_COUNT_NV,
337                                                         &pixelCount);
338       
339        if (pixelCount > 0)
340          return -1.0f; // backfacing polygon found -> not a valid viewspace sample
341  } else
342        glDisable( GL_CULL_FACE );
343       
344
345  ViewCell *viewcell = mViewCellsManager->GetViewCell(mViewPoint);
346       
347  if (viewcell) {
348        SetupCamera();
349        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
350
351        glColorMask(GL_FALSE, GL_TRUE, GL_FALSE, GL_FALSE);
352
353        // Render PVS
354        std::map<Intersectable *,
355          PvsData<Intersectable *>,
356          LtSample<Intersectable *> >::const_iterator it = viewcell->GetPvs().mEntries.begin();
357       
358        for (; it != viewcell->GetPvs().mEntries.end(); ++ it) {
359          Intersectable *object = (*it).first;
360          RenderIntersectable(object);
361        }
362
363        //      glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_FALSE);
364        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
365        mUseFalseColors = true;
366
367        glBeginOcclusionQueryNV(query);
368
369        SetupCamera();
370
371        RenderScene();
372       
373        glEndOcclusionQueryNV();
374       
375
376        unsigned int pixelCount;
377        // reenable other state
378        glGetOcclusionQueryuivNV(query,
379                                                         GL_PIXEL_COUNT_NV,
380                                                         &pixelCount);
381       
382        pErrorPixels = ((float)pixelCount)/(GetWidth()*GetHeight());
383        if (mSnapErrorFrames && pErrorPixels > 0.01) {
384         
385          char filename[256];
386          sprintf(filename, "error-frame-%04d-%0.5f.png", mFrame, pErrorPixels);
387          QImage im = toImage();
388          im.save(mSnapPrefix + filename, "PNG");
389          if (1) { //0 && mFrame == 1543) {
390                int x,y;
391                int lastIndex = -1;
392                for (y=0; y < im.height(); y++)
393                  for (x=0; x < im.width(); x++) {
394                        QRgb p = im.pixel(x,y);
395                        int index = qRed(p) + (qGreen(p)<<8) + (qBlue(p)<<16);
396                        if (qGreen(p) != 255 && index!=0) {
397                          if (index != lastIndex) {
398                                Debug<<"ei="<<index<<" ";
399                                lastIndex = index;
400                          }
401                        }
402                  }
403          }
404
405
406          mUseFalseColors = false;
407          glPushAttrib(GL_CURRENT_BIT);
408          glColor3f(0,1,0);
409          glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
410          SetupCamera();
411          glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
412         
413          // Render PVS
414          std::map<Intersectable *,
415                PvsData<Intersectable *>,
416                LtSample<Intersectable *> >::const_iterator it = viewcell->GetPvs().mEntries.begin();
417         
418          for (; it != viewcell->GetPvs().mEntries.end(); ++ it) {
419                Intersectable *object = (*it).first;
420                RenderIntersectable(object);
421          }
422
423          im = toImage();
424          sprintf(filename, "error-frame-%04d-%0.5f-pvs.png", mFrame, pErrorPixels);
425          im.save(mSnapPrefix + filename, "PNG");
426          glPopAttrib();
427        }
428        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
429  }
430 
431  return pErrorPixels;
432}
433
434
435float
436GlRendererWidget::RenderErrors()
437{
438  float pErrorPixels = -1.0f;
439
440  glReadBuffer(GL_BACK);
441 
442  mUseFalseColors = true;
443
444  SetupCamera();
445  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
446
447
448  if (mDetectEmptyViewSpace)
449        glEnable( GL_CULL_FACE );
450  else
451        glDisable( GL_CULL_FACE );
452
453  ObjectContainer::const_iterator oi = mObjects.begin();
454  for (; oi != mObjects.end(); oi++)
455        RenderIntersectable(*oi);
456
457  ViewCell *viewcell = mViewCellsManager->GetViewCell(mViewPoint);
458 
459  QImage im1, im2;
460  QImage diff;
461 
462  if (viewcell) {
463        // read back the texture
464        im1 = grabFrameBuffer(true);
465       
466        SetupCamera();
467        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
468       
469        std::map<Intersectable *,
470          PvsData<Intersectable *>,
471          LtSample<Intersectable *> >::const_iterator it = viewcell->GetPvs().mEntries.begin();
472       
473        for (; it != viewcell->GetPvs().mEntries.end(); ++ it) {
474          Intersectable *object = (*it).first;
475          RenderIntersectable(object);
476        }
477
478        // read back the texture
479        im2 = grabFrameBuffer(true);
480       
481        diff = im1;
482        int x, y;
483        int errorPixels = 0;
484       
485        for (y = 0; y < im1.height(); y++)
486          for (x = 0; x < im1.width(); x++)
487                if (im1.pixel(x, y) == im2.pixel(x, y))
488                  diff.setPixel(x, y, qRgba(0,0,0,0));
489                else {
490                  diff.setPixel(x, y, qRgba(255,128,128,255));
491                  errorPixels++;
492                 
493                }
494        pErrorPixels = ((float)errorPixels)/(im1.height()*im1.width());
495  }
496
497  // now render the pvs again
498  SetupCamera();
499  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
500  mUseFalseColors = false;
501       
502  oi = mObjects.begin();
503  for (; oi != mObjects.end(); oi++)
504        RenderIntersectable(*oi);
505
506  // now render im1
507  if (viewcell) {
508        if (1 || mTopView) {
509          mWireFrame = true;
510          RenderIntersectable(viewcell);
511          mWireFrame = false;
512        }
513       
514        // init ortographic projection
515        glMatrixMode(GL_PROJECTION);
516        glPushMatrix();
517       
518        glLoadIdentity();
519        gluOrtho2D(0, 1.0f, 0, 1.0f);
520       
521        glMatrixMode(GL_MODELVIEW);
522        glLoadIdentity();
523       
524        bindTexture(diff);
525       
526        glPushAttrib(GL_ENABLE_BIT);
527        glEnable( GL_ALPHA_TEST );
528        glDisable( GL_CULL_FACE );
529        glAlphaFunc( GL_GREATER, 0.5 );
530       
531        glEnable( GL_TEXTURE_2D );
532        glBegin(GL_QUADS);
533       
534        glTexCoord2f(0,0);
535        glVertex3f(0,0,0);
536       
537        glTexCoord2f(1,0);
538        glVertex3f( 1, 0, 0);
539       
540        glTexCoord2f(1,1);
541        glVertex3f( 1, 1, 0);
542       
543        glTexCoord2f(0,1);
544        glVertex3f(0, 1, 0);
545        glEnd();
546       
547        glPopAttrib();
548       
549        // restore the projection matrix
550        glMatrixMode(GL_PROJECTION);
551        glPopMatrix();
552        glMatrixMode(GL_MODELVIEW);
553  }
554
555  return pErrorPixels;
556}
557
558
559bool
560GlRenderer::RenderScene()
561{
562  static int glList = -1;
563  if (glList == -1)
564  {
565        glList = glGenLists(1);
566        glNewList(glList, GL_COMPILE);
567        ObjectContainer::const_iterator oi = mObjects.begin();
568        for (; oi != mObjects.end(); oi++)
569          RenderIntersectable(*oi);
570        glEndList();
571  }
572 
573  glCallList(glList);
574 
575  return true;
576}
577
578
579void
580GlRendererBuffer::ClearErrorBuffer()
581{
582  for (int i=0; i < mPvsStatFrames; i++) {
583        mPvsErrorBuffer[i] = 1.0f;
584  }
585}
586
587
588void
589GlRendererBuffer::EvalPvsStat()
590{
591  mPvsStat.Reset();
592  halton.Reset();
593
594  makeCurrent();
595  SetupProjection(GetWidth(), GetHeight());
596 
597  for (int i=0; i < mPvsStatFrames; i++) {
598        float err;
599        // set frame id for saving the error buffer
600        mFrame = i;
601        RandomViewPoint();
602
603        // atlanta problematic frames: 325 525 691 1543
604#if 0
605        if (mFrame != 325 &&
606                mFrame != 525 &&
607                mFrame != 691 &&
608                mFrame != 1543)
609          mPvsErrorBuffer[i] = -1;
610        else {
611          Debug<<"frame ="<<mFrame<<" vp="<<mViewPoint<<" vd="<<mViewDirection<<endl;
612        }
613#endif
614        if (mPvsErrorBuffer[i] > 0.0f) {
615          mPvsErrorBuffer[i] = GetPixelError();
616          cout<<"("<<i<<","<<mPvsErrorBuffer[i]<<")";
617          //      swapBuffers();
618        }
619       
620        err = mPvsErrorBuffer[i];
621       
622        if (err >= 0.0f) {
623          if (err > mPvsStat.maxError)
624                mPvsStat.maxError = err;
625          mPvsStat.sumError += err;
626          if (err == 0.0f)
627                mPvsStat.errorFreeFrames++;
628          mPvsStat.frames++;
629        }
630  }
631
632  glFinish();
633  doneCurrent();
634
635  cout<<endl<<flush;
636  //  mRenderingFinished.wakeAll();
637}
638
639
640
641
642
643void
644GlRendererWidget::mousePressEvent(QMouseEvent *e)
645{
646  int x = e->pos().x();
647  int y = e->pos().y();
648
649  mousePoint.x = x;
650  mousePoint.y = y;
651 
652}
653
654void
655GlRendererWidget::mouseMoveEvent(QMouseEvent *e)
656{
657  float MOVE_SENSITIVITY = Magnitude(mSceneGraph->GetBox().Diagonal())*1e-3;
658  float TURN_SENSITIVITY=0.1f;
659  float TILT_SENSITIVITY=32.0 ;
660  float TURN_ANGLE= M_PI/36.0 ;
661
662  int x = e->pos().x();
663  int y = e->pos().y();
664 
665  if (e->modifiers() & Qt::ControlModifier) {
666        mViewPoint.y += (y-mousePoint.y)*MOVE_SENSITIVITY/2.0;
667        mViewPoint.x += (x-mousePoint.x)*MOVE_SENSITIVITY/2.0;
668  } else {
669        mViewPoint += mViewDirection*((mousePoint.y - y)*MOVE_SENSITIVITY);
670        float adiff = TURN_ANGLE*(x - mousePoint.x)*-TURN_SENSITIVITY;
671        float angle = atan2(mViewDirection.x, mViewDirection.z);
672        mViewDirection.x = sin(angle+adiff);
673        mViewDirection.z = cos(angle+adiff);
674  }
675 
676  mousePoint.x = x;
677  mousePoint.y = y;
678 
679  updateGL();
680}
681
682void
683GlRendererWidget::mouseReleaseEvent(QMouseEvent *)
684{
685
686
687}
688
689void
690GlRendererWidget::resizeGL(int w, int h)
691{
692  SetupProjection(w, h);
693  updateGL();
694}
695
696void
697GlRendererWidget::paintGL()
698{
699  if (mRenderViewCells)
700        RenderViewCells();
701  else {
702        RenderErrors();
703        RenderInfo();
704  }
705 
706  mFrame++;
707}
708
709
710void
711GlRendererWidget::SetupCamera()
712{
713  if (!mTopView)
714        GlRenderer::SetupCamera();
715  else {
716        float dist = Magnitude(mSceneGraph->GetBox().Diagonal())*0.05;
717        Vector3 pos = mViewPoint - dist*Vector3(mViewDirection.x,
718                                                                                        -1,
719                                                                                        mViewDirection.y);
720       
721        Vector3 target = mViewPoint + dist*mViewDirection;
722        Vector3 up(0,1,0);
723       
724        glLoadIdentity();
725        gluLookAt(pos.x, pos.y, pos.z,
726                          target.x, target.y, target.z,
727                          up.x, up.y, up.z);
728  }
729
730}
731
732void
733GlRendererWidget::keyPressEvent ( QKeyEvent * e )
734{
735  switch (e->key()) {
736  case Qt::Key_T:
737        mTopView = !mTopView;
738        updateGL();
739        break;
740  case Qt::Key_V:
741        mRenderViewCells = !mRenderViewCells;
742        updateGL();
743        break;
744  default:
745        e->ignore();
746        break;
747  }
748 
749}
750
751GlRendererWidget::GlRendererWidget(SceneGraph *sceneGraph,
752                                                                   ViewCellsManager *viewcells,
753                                                                   KdTree *tree,
754                                                                   QWidget * parent,
755                                                                   const QGLWidget * shareWidget,
756                                                                   Qt::WFlags f
757                                                                   )
758  :
759  GlRenderer(sceneGraph, viewcells, tree), QGLWidget(parent, shareWidget, f)
760{
761  mTopView = false;
762  mRenderViewCells = false;
763
764  QSlider *slider = new QSlider(this);
765  slider->show();
766  slider->setRange(1, 10000);
767
768  connect(slider, SIGNAL(valueChanged(int)), this, SLOT(SetViewcellGranularity(int)));
769}
770
771void
772GlRendererWidget::SetViewcellGranularity(int number)
773{
774  mViewCellsManager->CollectViewCells(number);
775  updateGL();
776}
777
778void
779GlRendererWidget::RenderViewCells()
780{
781  mUseFalseColors = true;
782
783  SetupCamera();
784  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
785
786  int i;
787  ViewCellContainer &viewcells = mViewCellsManager->GetViewCells();
788  for (i=0; i < viewcells.size(); i++) {
789        ViewCell *vc = viewcells[i];
790        Mesh *m = vc->GetMesh();
791        float r = RandomValue(0.5, 1.0);
792        float g = RandomValue(0.5, 1.0);
793        float b = RandomValue(0.5, 1.0);
794
795        glColor3f(r, g, b);
796        //SetupMaterial(m->mMaterial);
797
798        RenderViewCell(vc);
799  }
800
801}
802
803void GlRendererBuffer::SampleBeamContributions(Intersectable *sourceObject,
804                                                                                           Beam &beam,
805                                                                                           const int desiredSamples,
806                                                                                           BeamSampleStatistics &stat)
807{
808        // TODO: should be moved out of here (not to be done every time)
809        // only back faces are interesting for the depth pass
810        glShadeModel(GL_FLAT);
811        glDisable(GL_LIGHTING);
812
813        // needed to kill the fragments for the front buffer
814        glEnable(GL_ALPHA_TEST);
815        glAlphaFunc(GL_GREATER, 0);
816
817        // assumes that the beam is constructed and contains kd-tree nodes
818        // and viewcells which it intersects
819 
820 
821        // Get the number of viewpoints to be sampled
822        // Now it is a sqrt but in general a wiser decision could be made.
823        // The less viewpoints the better for rendering performance, since less passes
824        // over the beam is needed.
825        // The viewpoints could actually be generated outside of the bounding box which
826        // would distribute the 'efective viewpoints' of the object surface and thus
827        // with a few viewpoints better sample the viewpoint space....
828
829        //TODO: comment in
830        //int viewPointSamples = sqrt((float)desiredSamples);
831        int viewPointSamples = max(desiredSamples / (GetWidth() * GetHeight()), 1);
832       
833        // the number of direction samples per pass is given by the number of viewpoints
834        int directionalSamples = desiredSamples / viewPointSamples;
835       
836        Debug << "directional samples: " << directionalSamples << endl;
837        for (int i = 0; i < viewPointSamples; ++ i)
838        {
839                Vector3 viewPoint = beam.mBox.GetRandomPoint();
840               
841                // perhaps the viewpoint should be shifted back a little bit so that it always lies
842                // inside the source object
843                // 'ideally' the viewpoints would be distributed on the soureObject surface, but this
844        // would require more complicated sampling (perhaps hierarchical rejection sampling of
845                // the object surface is an option here - only the mesh faces which are inside the box
846                // are considered as candidates)
847               
848                SampleViewpointContributions(sourceObject,
849                                                                         viewPoint,
850                                                                         beam,
851                                                                         directionalSamples,
852                                                                         stat);
853        }
854
855
856        // note:
857        // this routine would be called only if the number of desired samples is sufficiently
858        // large - for other rss tree cells the cpu based sampling is perhaps more efficient
859        // distributing the work between cpu and gpu would also allow us to place more sophisticated
860        // sample distributions (silhouette ones) using the cpu and the jittered once on the GPU
861        // in order that thios scheme is working well the gpu render buffer should run in a separate
862        // thread than the cpu sampler, which would not be such a big problem....
863
864        // disable alpha test again
865        glDisable(GL_ALPHA_TEST);
866}
867
868
869void GlRendererBuffer::SampleViewpointContributions(Intersectable *sourceObject,
870                                                                                                        const Vector3 viewPoint,
871                                                                                                        Beam &beam,
872                                                                                                        const int samples,
873                                                    BeamSampleStatistics &stat)
874{
875    // 1. setup the view port to match the desired samples
876        glViewport(0, 0, samples, samples);
877
878        // 2. setup the projection matrix and view matrix to match the viewpoint + beam.mDirBox
879        SetupProjectionForViewPoint(viewPoint, beam, sourceObject);
880
881
882        // 3. reset z-buffer to 0 and render the source object for the beam
883        //    with glCullFace(Enabled) and glFrontFace(GL_CW)
884        //    save result to the front depth map
885        //    the front depth map holds ray origins
886
887
888        // front depth buffer must be initialised to 0
889        float clearDepth;
890       
891        glGetFloatv(GL_DEPTH_CLEAR_VALUE, &clearDepth);
892        glClearDepth(0.0f);
893        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
894
895
896        //glFrontFace(GL_CW);
897        glEnable(GL_CULL_FACE);
898        glCullFace(GL_FRONT);
899        glColorMask(0, 0, 0, 0);
900       
901
902        // stencil is increased where the source object is located
903        glEnable(GL_STENCIL_TEST);     
904        glStencilFunc(GL_ALWAYS, 0x1, 0x1);
905        glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
906
907
908#if 0
909        static int glSourceObjList = -1;         
910        if (glSourceObjList != -1)
911        {
912                glSourceObjList = glGenLists(1);
913                glNewList(glSourceObjList, GL_COMPILE);
914
915                RenderIntersectable(sourceObject);
916       
917                glEndList();
918        }
919        glCallList(glSourceObjList);
920
921#else
922        RenderIntersectable(sourceObject);
923
924#endif 
925
926         // copy contents of the front depth buffer into depth texture
927        glBindTexture(GL_TEXTURE_2D, frontDepthMap);   
928        glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, depthMapSize, depthMapSize);
929
930
931        // reset clear function
932        glClearDepth(clearDepth);
933
934       
935       
936        // 4. set up the termination depth buffer (= standard depth buffer)
937        //    only rays which have non-zero entry in the origin buffer are valid since
938        //    they realy start on the object surface (this is tagged by setting a
939        //    stencil buffer bit at step 3).
940       
941        glStencilFunc(GL_EQUAL, 0x1, 0x1);
942        glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
943
944        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
945        glDepthMask(1);
946
947        glEnable(GL_DEPTH_TEST);
948               
949        glEnable(GL_CULL_FACE);
950        glCullFace(GL_BACK);
951
952        // setup front depth buffer
953        glEnable(GL_TEXTURE_2D);
954       
955        // bind pixel shader implementing the front depth buffer functionality
956        cgGLBindProgram(sCgFragmentProgram);
957        cgGLEnableProfile(sCgFragmentProfile);
958
959
960        // 5. render all objects inside the beam
961        //    we can use id based false color to read them back for gaining the pvs
962
963        glColorMask(1, 1, 1, 1);
964
965       
966        // if objects not stored in beam => extract objects
967        if (beam.mFlags & !Beam::STORE_OBJECTS)
968        {
969                vector<KdNode *>::const_iterator it, it_end = beam.mKdNodes.end();
970
971                Intersectable::NewMail();
972                for (it = beam.mKdNodes.begin(); it != it_end; ++ it)
973                {
974                        mKdTree->CollectObjects(*it, beam.mObjects);
975                }
976        }
977
978
979        //    (objects can be compiled to a gl list now so that subsequent rendering for
980        //    this beam is fast - the same hold for step 3)
981        //    Afterwards we have two depth buffers defining the ray origin and termination
982       
983
984#if 0
985        static int glObjList = -1;
986        if (glObjList != -1)
987        {
988                glObjList = glGenLists(1);
989                glNewList(glObjList, GL_COMPILE);
990       
991                ObjectContainer::const_iterator it, it_end = beam.mObjects.end();
992                for (it = beam.mObjects.begin(); it != it_end; ++ it)
993                {
994                        // render all objects except the source object
995                        if (*it != sourceObject)
996                                RenderIntersectable(*it);
997                }
998               
999                glEndList();
1000        }
1001
1002        glCallList(glObjList);
1003#else
1004        ObjectContainer::const_iterator it, it_end = beam.mObjects.end();
1005        for (it = beam.mObjects.begin(); it != it_end; ++ it)
1006        {       
1007                // render all objects except the source object
1008                if (*it != sourceObject)
1009                        RenderIntersectable(*it);
1010        }
1011#endif
1012       
1013   
1014
1015        // 6. Use occlusion queries for all viewcell meshes associated with the beam ->
1016        //     a fragment passes if the corresponding stencil fragment is set and its depth is
1017        //     between origin and termination buffer
1018
1019        // create new queries if necessary
1020        GenQueries((int)beam.mViewCells.size());
1021
1022        // check whether any backfacing polygon would pass the depth test?
1023        // matt: should check both back /front facing because of dual depth buffer
1024        // and danger of cutting the near plane with front facing polys.
1025       
1026        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1027        glDepthMask(GL_FALSE);
1028        glDisable(GL_CULL_FACE);
1029
1030 
1031        ViewCellContainer::const_iterator vit, vit_end = beam.mViewCells.end();
1032
1033        int queryIdx = 0;
1034
1035        for (vit = beam.mViewCells.begin(); vit != vit_end; ++ vit)
1036        {
1037                glBeginOcclusionQueryNV(sQueries[queryIdx ++]);
1038
1039                RenderIntersectable(*vit);
1040               
1041                glEndOcclusionQueryNV();
1042        }
1043
1044
1045
1046        // at this point, if possible, go and do some other computation
1047
1048
1049       
1050        // 7. The number of visible pixels is the number of sample rays which see the source
1051        //    object from the corresponding viewcell -> remember these values for later update
1052        //   of the viewcell pvs - or update immediately?
1053
1054        queryIdx = 0;
1055        unsigned int pixelCount;
1056
1057        for (vit = beam.mViewCells.begin(); vit != vit_end; ++ vit)
1058        {
1059                // fetch queries
1060                glGetOcclusionQueryuivNV(sQueries[queryIdx ++],
1061                                                                 GL_PIXEL_COUNT_NV,
1062                                                                 &pixelCount);
1063                if (pixelCount)
1064                        Debug << "view cell " << (*vit)->GetId() << " visible pixels: " << pixelCount << endl;
1065        }
1066       
1067
1068        // 8. Copmpute rendering statistics
1069        // In general it is not neccessary to remember to extract all the rays cast. I hope it
1070        // would be sufficient to gain only the intergral statistics about the new contributions
1071        // and so the rss tree would actually store no new rays (only the initial ones)
1072        // the subdivision of the tree would only be driven by the statistics (the glrender could
1073        // evaluate the contribution entropy for example)
1074        // However might be an option to extract/store only those the rays which made a contribution
1075        // (new viewcell has been discovered) or relative contribution greater than a threshold ...
1076
1077        ObjectContainer pvsObj;
1078        stat.pvsSize = ComputePvs(beam.mObjects, pvsObj);
1079       
1080        // to gain ray source and termination
1081        // copy contents of ray termination buffer into depth texture
1082        // and compare with ray source buffer
1083#if 0
1084        VssRayContainer rays;
1085
1086        glBindTexture(GL_TEXTURE_2D, backDepthMap);     
1087        glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, depthMapSize, depthMapSize);
1088
1089        ComputeRays(Intersectable *sourceObj, rays);
1090
1091#endif
1092
1093
1094
1095        //-- cleanup
1096
1097
1098        // reset gl state
1099        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1100        glDepthMask(GL_TRUE);
1101        glEnable(GL_CULL_FACE);
1102        glDisable(GL_STENCIL_TEST);
1103        cgGLDisableProfile(sCgFragmentProfile);
1104        glDisable(GL_TEXTURE_2D);
1105
1106        // remove objects from beam
1107        if (beam.mFlags & !Beam::STORE_OBJECTS)
1108                beam.mObjects.clear();
1109}
1110
1111
1112void GlRendererBuffer::GenQueries(const int numQueries)
1113{
1114        if ((int)sQueries.size() < numQueries)
1115        {
1116                const int n = numQueries - (int)sQueries.size();
1117                unsigned int *newQueries = new unsigned int[n];
1118
1119                glGenOcclusionQueriesNV(n, (unsigned int *)newQueries);
1120
1121                for (int i = 0; i < n; ++ i)
1122                {
1123                        sQueries.push_back(newQueries[i]);
1124                }
1125
1126                delete [] newQueries;
1127        }
1128}
1129
1130
1131void GlRendererBuffer::SetupProjectionForViewPoint(const Vector3 &viewPoint,
1132                                                                                                   const Beam &beam,
1133                                                                                                   Intersectable *sourceObject)
1134{
1135        float left, right, bottom, top, znear, zfar;
1136
1137        beam.ComputePerspectiveFrustum(left, right, bottom, top, znear, zfar,
1138                                                                   mSceneGraph->GetBox());
1139
1140        //Debug << left << " " << right << " " << bottom << " " << top << " " << znear << " " << zfar << endl;
1141        glMatrixMode(GL_PROJECTION);
1142        glLoadIdentity();
1143        glFrustum(left, right, bottom, top, znear, zfar);
1144        //glFrustum(-1, 1, -1, 1, 1, 20000);
1145
1146    const Vector3 center = viewPoint + beam.GetMainDirection() * (zfar - znear) * 0.3f;
1147        const Vector3 up =
1148                Normalize(CrossProd(beam.mPlanes[0].mNormal, beam.mPlanes[4].mNormal));
1149
1150#ifdef _DEBUG
1151        Debug << "view point: " << viewPoint << endl;
1152        Debug << "eye: " << center << endl;
1153        Debug << "up: " << up << endl;
1154#endif
1155
1156        glMatrixMode(GL_MODELVIEW);
1157        glLoadIdentity();
1158        gluLookAt(viewPoint.x, viewPoint.y, viewPoint.z,
1159                          center.x, center.y, center.z,                   
1160                          up.x, up.y, up.z);
1161}               
1162
1163 
1164void GlRendererBuffer::InitGL()
1165{
1166 makeCurrent();
1167 GlRenderer::InitGL();
1168#if 1
1169        // initialise dual depth buffer textures
1170        glGenTextures(1, &frontDepthMap);
1171        glBindTexture(GL_TEXTURE_2D, frontDepthMap);
1172       
1173        glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, depthMapSize,
1174                depthMapSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
1175        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1176        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1177        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
1178        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
1179
1180        glGenTextures(1, &backDepthMap);
1181        glBindTexture(GL_TEXTURE_2D, backDepthMap);
1182       
1183        glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, depthMapSize,
1184                depthMapSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
1185        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1186        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1187        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
1188        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
1189
1190        // cg initialization
1191        cgSetErrorCallback(handleCgError);
1192        sCgContext = cgCreateContext();
1193       
1194        if (cgGLIsProfileSupported(CG_PROFILE_ARBFP1))
1195                sCgFragmentProfile = CG_PROFILE_ARBFP1;
1196        else
1197        {
1198          // try FP30
1199          if (cgGLIsProfileSupported(CG_PROFILE_FP30))
1200            sCgFragmentProfile = CG_PROFILE_FP30;
1201          else
1202          {
1203                  Debug << "Neither arbfp1 or fp30 fragment profiles supported on this system" << endl;
1204                  exit(1);
1205          }
1206  }
1207
1208
1209 sCgFragmentProgram = cgCreateProgramFromFile(sCgContext,
1210                                                                                           CG_SOURCE, "../src/dual_depth.cg",
1211                                                                                           sCgFragmentProfile,
1212                                                                                           NULL,
1213                                                                                           NULL);
1214
1215  if (!cgIsProgramCompiled(sCgFragmentProgram))
1216          cgCompileProgram(sCgFragmentProgram);
1217
1218  cgGLLoadProgram(sCgFragmentProgram);
1219  cgGLBindProgram(sCgFragmentProgram);
1220
1221  Debug << "---- PROGRAM BEGIN ----\n" <<
1222          cgGetProgramString(sCgFragmentProgram, CG_COMPILED_PROGRAM) << "---- PROGRAM END ----\n";
1223
1224#endif
1225  doneCurrent();
1226}
1227
1228
1229void GlRendererBuffer::ComputeRays(Intersectable *sourceObj, VssRayContainer &rays)
1230{
1231        for (int i = 0; i < depthMapSize * depthMapSize; ++ i)
1232        {
1233                //todo glGetTexImage()
1234        }
1235}
1236
1237
1238
1239inline bool ilt(Intersectable *obj1, Intersectable *obj2)
1240{
1241        return obj1->mId < obj2->mId;
1242}
1243
1244
1245int GlRendererBuffer::ComputePvs(ObjectContainer &objects,
1246                                                                 ObjectContainer &pvs) const
1247{
1248        int pvsSize = 0;
1249        QImage image = toImage();
1250        Intersectable::NewMail();
1251
1252        std::stable_sort(objects.begin(), objects.end(), ilt);
1253
1254        MeshInstance dummy(NULL);
1255
1256        Intersectable *obj = NULL;
1257                       
1258        for (int x = 0; x < image.width(); ++ x)
1259        {
1260                for (int y = 0; y < image.height(); ++ y)
1261                {
1262                        QRgb pix = image.pixel(x, y);
1263                        const int id = GetId(qRed(pix), qGreen(pix), qBlue(pix));
1264
1265                        dummy.SetId(id);
1266
1267                        ObjectContainer::iterator oit =
1268                                lower_bound(objects.begin(), objects.end(), &dummy, ilt);
1269                       
1270                       
1271                        if (//(oit != oit.end()) &&
1272                                ((*oit)->GetId() == id) &&
1273                                !obj->Mailed())
1274                        {
1275                                obj = *oit;
1276                                obj->Mail();
1277                                ++ pvsSize;
1278                                pvs.push_back(obj);
1279                        }
1280                }
1281        }
1282
1283        return pvsSize;
1284}
1285
1286/***********************************************************************/
1287/*                     GlDebuggerWidget implementation                             */
1288/***********************************************************************/
1289
1290
1291GlDebuggerWidget::GlDebuggerWidget(GlRendererBuffer *buf, QWidget *parent)
1292      : QGLWidget(QGLFormat(QGL::SampleBuffers), parent), mRenderBuffer(buf)
1293{
1294        // create the pbuffer
1295    //pbuffer = new QGLPixelBuffer(QSize(512, 512), format(), this);
1296    timerId = startTimer(20);
1297    setWindowTitle(("OpenGL pbuffers"));
1298}
1299
1300
1301GlDebuggerWidget::~GlDebuggerWidget()
1302{
1303 mRenderBuffer->releaseFromDynamicTexture();
1304   glDeleteTextures(1, &dynamicTexture);
1305         
1306         DEL_PTR(mRenderBuffer);
1307}
1308
1309
1310void GlDebuggerWidget::initializeGL()
1311{
1312        glMatrixMode(GL_PROJECTION);
1313        glLoadIdentity();
1314
1315        glFrustum(-1, 1, -1, 1, 10, 100);
1316        glTranslatef(-0.5f, -0.5f, -0.5f);
1317        glTranslatef(0.0f, 0.0f, -15.0f);
1318        glMatrixMode(GL_MODELVIEW);
1319
1320        glEnable(GL_CULL_FACE);
1321        initCommon();
1322        initPbuffer();
1323
1324}
1325
1326
1327void GlDebuggerWidget::resizeGL(int w, int h)
1328{
1329        glViewport(0, 0, w, h);
1330}
1331
1332
1333void GlDebuggerWidget::paintGL()
1334{
1335        // draw a spinning cube into the pbuffer..
1336        mRenderBuffer->makeCurrent();
1337       
1338        BeamSampleStatistics stats;
1339        mRenderBuffer->SampleBeamContributions(mSourceObject, mBeam, mSamples, stats);
1340
1341        glFlush();
1342
1343        // rendering directly to a texture is not supported on X11, unfortunately
1344    mRenderBuffer->updateDynamicTexture(dynamicTexture);
1345   
1346    // and use the pbuffer contents as a texture when rendering the
1347    // background and the bouncing cubes
1348    makeCurrent();
1349    glBindTexture(GL_TEXTURE_2D, dynamicTexture);
1350    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1351
1352    // draw the background
1353    glMatrixMode(GL_MODELVIEW);
1354    glPushMatrix();
1355    glLoadIdentity();
1356    glMatrixMode(GL_PROJECTION);
1357    glPushMatrix();
1358    glLoadIdentity();
1359
1360        glPopMatrix();
1361        glMatrixMode(GL_MODELVIEW);
1362        glPopMatrix();
1363}
1364
1365
1366void GlDebuggerWidget::initPbuffer()
1367{
1368        // set up the pbuffer context
1369    mRenderBuffer->makeCurrent();
1370        /*mRenderBuffer->InitGL();
1371
1372        glViewport(0, 0, mRenderBuffer->size().width(), mRenderBuffer->size().height());
1373        glMatrixMode(GL_PROJECTION);
1374        glLoadIdentity();
1375        glOrtho(-1, 1, -1, 1, -99, 99);
1376        glTranslatef(-0.5f, -0.5f, 0.0f);
1377        glMatrixMode(GL_MODELVIEW);
1378        glLoadIdentity();
1379
1380        glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);*/
1381       
1382        // generate a texture that has the same size/format as the pbuffer
1383    dynamicTexture = mRenderBuffer->generateDynamicTexture();
1384
1385        // bind the dynamic texture to the pbuffer - this is a no-op under X11
1386        mRenderBuffer->bindToDynamicTexture(dynamicTexture);
1387        makeCurrent();
1388}
1389
1390void GlDebuggerWidget::initCommon()
1391{
1392        glEnable(GL_TEXTURE_2D);
1393        glEnable(GL_DEPTH_TEST);
1394
1395        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
1396}
Note: See TracBrowser for help on using the repository browser.