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

Revision 2571, 40.5 KB checked in by mattausch, 17 years ago (diff)
  • Property svn:executable set to *
Line 
1#include "Mesh.h"
2#include "glInterface.h"
3#include "OcclusionQuery.h"
4#include "GlRenderer.h"
5#include "ViewCellsManager.h"
6#include "SceneGraph.h"
7#include "Viewcell.h"
8#include "Beam.h"
9#include "KdTree.h"
10#include "Environment.h"
11#include "Triangle3.h"
12#include "IntersectableWrapper.h"
13#include "BvHierarchy.h"
14#include "KdTree.h"
15
16#ifdef USE_CG
17
18#include <Cg/cg.h>
19#include <Cg/cgGL.h>
20
21#endif
22
23namespace GtpVisibilityPreprocessor {
24
25
26static bool arbQuerySupport = false;
27static bool nvQuerySupport = false;
28
29static GLuint frontDepthMap;
30static GLuint backDepthMap;
31
32const int depthMapSize = 512;
33
34
35static void InitExtensions()
36{
37        GLenum err = glewInit();
38
39        if (GLEW_OK != err)
40        {
41                // problem: glewInit failed, something is seriously wrong
42                cerr << "Error: " << glewGetErrorString(err) << endl;
43                exit(1);
44        }
45
46        if (GLEW_ARB_occlusion_query)
47                arbQuerySupport = true;
48       
49        if (GLEW_NV_occlusion_query)
50                nvQuerySupport = true;
51
52        if  (!arbQuerySupport && !nvQuerySupport)
53        {
54                cout << "I require the GL_ARB_occlusion_query or the GL_NV_occlusion_query OpenGL extension to work.\n";
55                exit(1);
56        }
57
58        if (!GLEW_ARB_vertex_buffer_object)
59        {
60                cout << "vbos not supported" << endl;
61        }
62        else
63        {
64                cout << "vbos supported" << endl;
65        }
66}
67
68
69GlRenderer::GlRenderer(SceneGraph *sceneGraph,
70                                           ViewCellsManager *viewCellsManager,
71                                           KdTree *tree):
72Renderer(sceneGraph, viewCellsManager),
73mKdTree(tree),
74mUseFalseColors(false),
75mVboId(-1),
76mData(NULL),
77mIndices(NULL),
78//mUseVbos(true),
79mUseVbos(false),
80mCurrentFrame(-1)
81{
82        mSceneGraph->CollectObjects(&mObjects);
83
84        viewCellsManager->GetViewPoint(mViewPoint);
85
86        mViewDirection = Vector3(0,0,1);
87
88        mFrame = 0;
89        mWireFrame = false;
90        Environment::GetSingleton()->GetBoolValue("Preprocessor.detectEmptyViewSpace",
91                                                      mDetectEmptyViewSpace);
92        mSnapErrorFrames = true;
93        mSnapPrefix = "snap/";
94        mUseForcedColors = false;
95        mRenderBoxes = false;
96        //mUseGlLists = true;
97        mUseGlLists = false;
98
99        if (mViewCellsManager->GetViewCellPoints()->size())
100                mPvsStatFrames = (int)mViewCellsManager->GetViewCellPoints()->size();
101        else
102                Environment::GetSingleton()->GetIntValue("Preprocessor.pvsRenderErrorSamples", mPvsStatFrames);
103
104
105        mPvsErrorBuffer.resize(mPvsStatFrames);
106        ClearErrorBuffer();
107}
108
109
110GlRenderer::~GlRenderer()
111{
112        cerr<<"gl renderer destructor..\n";
113
114        CLEAR_CONTAINER(mOcclusionQueries);
115
116        DeleteVbos();
117
118        if (mData) delete [] mData;
119        if (mIndices) delete [] mIndices;
120
121        glDeleteBuffersARB(1, &mVboId);
122        cerr<<"done."<<endl;
123}
124
125
126void GlRenderer::RenderTriangle(TriangleIntersectable *object)
127{
128        Triangle3 &t = object->GetItem();
129
130        glBegin(GL_TRIANGLES);
131        Vector3 normal = t.GetNormal();
132        glNormal3f(normal.x, normal.y, normal.z);
133        glVertex3f(t.mVertices[0].x, t.mVertices[0].y, t.mVertices[0].z);
134        glVertex3f(t.mVertices[1].x, t.mVertices[1].y, t.mVertices[1].z);
135        glVertex3f(t.mVertices[2].x, t.mVertices[2].y, t.mVertices[2].z);
136        glEnd();
137}
138
139
140void GlRenderer::RenderIntersectable(Intersectable *object)
141{
142        if (!object)
143                return;
144
145        if (object->mRenderedFrame == mCurrentFrame)
146                return;
147
148        object->mRenderedFrame = mCurrentFrame;
149
150        //if (object->Mailed()) return;
151        //object->Mail();
152
153        glPushAttrib(GL_CURRENT_BIT);
154
155        if (mUseFalseColors)
156                SetupFalseColor(object->mId);
157
158        switch (object->Type())
159        {
160        case Intersectable::MESH_INSTANCE:
161                RenderMeshInstance((MeshInstance *)object);
162                break;
163        case Intersectable::VIEW_CELL:
164                RenderViewCell(static_cast<ViewCell *>(object));
165                break;
166        case Intersectable::TRANSFORMED_MESH_INSTANCE:
167                RenderTransformedMeshInstance(static_cast<TransformedMeshInstance *>(object));
168                break;
169        case Intersectable::TRIANGLE_INTERSECTABLE:
170                RenderTriangle(static_cast<TriangleIntersectable *>(object));
171                break;
172        case Intersectable::BVH_INTERSECTABLE:
173                {
174                        BvhNode *node = static_cast<BvhNode *>(object);
175
176                        if (mRenderBoxes)
177                                RenderBox(node->GetBoundingBox());
178                        else
179                                RenderBvhNode(node);
180                        break;
181                }
182        case Intersectable::KD_INTERSECTABLE:
183                {
184                        KdNode *node = (static_cast<KdIntersectable *>(object))->GetItem();
185
186                        if (mRenderBoxes)
187                                RenderBox(mKdTree->GetBox(node));
188                        else
189                                RenderKdNode(node);
190                        break;
191                }
192
193        default:
194                cerr<<"Rendering this object not yet implemented\n";
195                break;
196        }
197
198        glPopAttrib();
199}
200
201
202void GlRenderer::RenderRays(const VssRayContainer &rays)
203{
204        VssRayContainer::const_iterator it = rays.begin(), it_end = rays.end();
205
206        glBegin(GL_LINES);
207       
208        for (; it != it_end; ++it)
209        {
210                VssRay *ray = *it;
211                const float importance = log10(1e3*ray->mWeightedPvsContribution)/3.0f;
212               
213                glColor3f(1.0f, 0.0f, 0.0f);
214                //glColor3f(importance, importance, importance);
215                glVertex3fv(&ray->mOrigin.x);
216                glVertex3fv(&ray->mTermination.x);
217        }
218
219        glEnd();
220}
221
222
223void GlRenderer::RenderViewCell(ViewCell *vc)
224{
225        if (vc->GetMesh())
226        {
227                if (!mUseFalseColors)
228                {
229                        if (vc->GetValid())
230                                glColor3f(0,1,0);
231                        else
232                                glColor3f(0,0,1);
233                }
234
235                RenderMesh(vc->GetMesh());
236        }
237        else
238        {
239                // render viewcells in the subtree
240                if (!vc->IsLeaf())
241                {
242                        ViewCellInterior *vci = (ViewCellInterior *) vc;
243
244                        ViewCellContainer::iterator it = vci->mChildren.begin();
245                        for (; it != vci->mChildren.end(); ++it)
246                        {
247                                RenderViewCell(*it);
248                        }
249                }
250                else
251                {
252                        // cerr<<"Empty viewcell mesh\n";
253                }
254        }
255}
256
257
258void GlRenderer::RenderMeshInstance(MeshInstance *mi)
259{
260        RenderMesh(mi->GetMesh());
261}
262
263
264void
265GlRenderer::RenderTransformedMeshInstance(TransformedMeshInstance *mi)
266{
267        // apply world transform before rendering
268        Matrix4x4 m;
269        mi->GetWorldTransform(m);
270
271        glPushMatrix();
272
273        glMultMatrixf((float *)m.x);
274
275        RenderMesh(mi->GetMesh());
276       
277        glPopMatrix();
278}
279
280
281void
282GlRenderer::SetupFalseColor(const unsigned int id)
283{
284        // swap bits of the color
285        glColor3ub(id&255, (id>>8)&255, (id>>16)&255);
286}
287
288
289unsigned int GlRenderer::GetId(const unsigned char r,
290                                                           const unsigned char g,
291                                                           const unsigned char b) const
292{
293        return r + (g << 8) + (b << 16);
294}
295
296
297void
298GlRenderer::SetupMaterial(Material *m)
299{
300  if (m)
301        glColor3fv(&(m->mDiffuseColor.r));
302}
303
304
305void GlRenderer::RenderMesh(Mesh *mesh)
306{
307        int i = 0;
308
309        if (!mUseFalseColors && !mUseForcedColors)
310                SetupMaterial(mesh->mMaterial);
311
312        for (i = 0; i < mesh->mFaces.size(); i++)
313        {
314                if (mWireFrame)
315                        glBegin(GL_LINE_LOOP);
316                else
317                        glBegin(GL_POLYGON);
318
319                Face *face = mesh->mFaces[i];
320                for (int j = 0; j < face->mVertexIndices.size(); j++) {
321                        glVertex3fv(&mesh->mVertices[face->mVertexIndices[j]].x);
322                }
323                glEnd();
324        }
325}
326       
327void
328GlRenderer::InitGL()
329{
330  mSphere = (GLUquadric *)gluNewQuadric();
331 
332  glMatrixMode(GL_PROJECTION);
333  glLoadIdentity();
334 
335  glMatrixMode(GL_MODELVIEW);
336  glLoadIdentity();
337
338  glFrontFace(GL_CCW);
339  glCullFace(GL_BACK);
340
341  glShadeModel(GL_FLAT);
342  glDepthFunc(GL_LESS );
343  glEnable(GL_DEPTH_TEST);
344  glEnable(GL_CULL_FACE);
345 
346  InitExtensions();
347
348  glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
349
350  glEnable(GL_NORMALIZE);
351 
352  glClearColor(0.0f, 0.0f, 1.0f, 1.0f);
353 
354  OcclusionQuery::GenQueries(mOcclusionQueries, 10);
355
356  CreateVertexArrays();
357}
358
359
360void
361GlRenderer::SetupProjection(const int w, const int h, const float angle)
362{
363  glViewport(0, 0, w, h);
364  glMatrixMode(GL_PROJECTION);
365  glLoadIdentity();
366  gluPerspective(angle, 1.0, 0.1, 2.0*Magnitude(mSceneGraph->GetBox().Diagonal()));
367  glMatrixMode(GL_MODELVIEW);
368}
369
370
371
372void
373GlRenderer::SetupCamera()
374{
375        Vector3 target = mViewPoint + mViewDirection;
376
377        Vector3 up(0,1,0);
378
379        if (abs(DotProd(mViewDirection, up)) > 0.99f)
380                up = Vector3(1, 0, 0);
381
382        glLoadIdentity();
383        gluLookAt(mViewPoint.x, mViewPoint.y, mViewPoint.z,
384                target.x, target.y, target.z,
385                up.x, up.y, up.z);
386}
387
388void
389GlRenderer::_RenderScene()
390{
391        ObjectContainer::const_iterator oi = mObjects.begin();
392        for (; oi != mObjects.end(); oi++)
393                RenderIntersectable(*oi);
394}
395
396void GlRenderer::_RenderSceneTrianglesWithDrawArrays()
397{
398        EnableDrawArrays();
399       
400        if (mUseVbos)
401                glBindBufferARB(GL_ARRAY_BUFFER_ARB, mVboId);
402
403        int offset = (int)mObjects.size() * 3;
404        char *arrayPtr = mUseVbos ? NULL : (char *)mData;
405       
406        glVertexPointer(3, GL_FLOAT, 0, (char *)arrayPtr);
407        glNormalPointer(GL_FLOAT, 0, (char *)arrayPtr + offset * sizeof(Vector3));
408       
409        glDrawArrays(GL_TRIANGLES, 0, (int)mObjects.size() * 3);
410        //DisableDrawArrays();
411}
412
413
414void GlRenderer::_RenderSceneTriangles()
415{
416        glBegin(GL_TRIANGLES);
417
418        ObjectContainer::const_iterator oi = mObjects.begin();
419        for (; oi != mObjects.end(); oi++) {
420
421                if ((*oi)->Type() == Intersectable::TRIANGLE_INTERSECTABLE) {
422                        TriangleIntersectable *object = (TriangleIntersectable *)*oi;
423                        Triangle3 &t = object->GetItem();
424
425                        Vector3 normal = t.GetNormal();
426                        glNormal3f(normal.x, normal.y, normal.z);
427                        glVertex3f(t.mVertices[0].x, t.mVertices[0].y, t.mVertices[0].z);
428                        glVertex3f(t.mVertices[1].x, t.mVertices[1].y, t.mVertices[1].z);
429                        glVertex3f(t.mVertices[2].x, t.mVertices[2].y, t.mVertices[2].z);
430
431                }
432        }
433
434        glEnd();
435}
436
437
438bool
439GlRenderer::RenderScene()
440{
441  Intersectable::NewMail();
442
443#if 1
444 
445  _RenderSceneTrianglesWithDrawArrays();
446
447#else
448  static int glList = -1;
449  if (mUseGlLists) {
450        if (glList == -1) {
451          glList = glGenLists(1);
452          glNewList(glList, GL_COMPILE);
453          _RenderSceneTriangles();
454          glEndList();
455        }
456       
457        glCallList(glList);
458  } else
459        _RenderSceneTriangles();
460       
461#endif
462  return true;
463}
464
465
466void
467GlRendererBuffer::EvalQueryWithItemBuffer()
468{
469        // read back the texture
470        glReadPixels(0, 0,
471                                GetWidth(), GetHeight(),
472                                GL_RGBA,
473                                GL_UNSIGNED_BYTE,
474                                mPixelBuffer);
475               
476                       
477        unsigned int *p = mPixelBuffer;
478                       
479        for (int y = 0; y < GetHeight(); y++)
480        {
481                for (int x = 0; x < GetWidth(); x++, p++)
482                {
483                        unsigned int id = (*p) & 0xFFFFFF;
484
485                        if (id != 0xFFFFFF)
486                        {
487                                ++ mObjects[id]->mCounter;
488                        }
489                }
490        }
491}
492
493
494
495/****************************************************************/
496/*               GlRendererBuffer implementation                */
497/****************************************************************/
498
499
500
501GlRendererBuffer::GlRendererBuffer(SceneGraph *sceneGraph,
502                                                                   ViewCellsManager *viewcells,
503                                                                   KdTree *tree):
504GlRenderer(sceneGraph, viewcells, tree) 
505{
506  mPixelBuffer = NULL;
507  // implement width and height in subclasses
508}
509
510
511void
512GlRendererBuffer::EvalQueryWithOcclusionQueries(
513                                                                           //RenderCostSample &sample
514                                                                           )
515{
516        glDepthFunc(GL_LEQUAL);
517               
518        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
519        glDepthMask(GL_FALSE);
520
521
522        // simulate detectemptyviewspace using backface culling
523        if (mDetectEmptyViewSpace)
524        {
525                glEnable(GL_CULL_FACE);
526                //cout << "culling" << endl;
527        }
528        else
529        {
530                //cout << "not culling" << endl;
531                glDisable(GL_CULL_FACE);
532        }
533
534       
535        //const int numQ = 1;
536        const int numQ = (int)mOcclusionQueries.size();
537       
538        //glFinish();
539#if 0
540        //-- now issue queries for all objects
541        for (int j = 0; j < (int)mObjects.size(); ++ j)
542        {
543                mOcclusionQueries[j]->BeginQuery();
544                RenderIntersectable(mObjects[j]);
545                mOcclusionQueries[j]->EndQuery();
546
547                unsigned int pixelCount;
548
549                pixelCount = mOcclusionQueries[j]->GetQueryResult();
550               
551                mObjects[j]->mCounter += pixelCount;
552        }
553#else
554
555        int q = 0;
556
557        //-- now issue queries for all objects
558        for (int j = 0; j < (int)mObjects.size(); j += q)
559        {       
560                for (q = 0; ((j + q) < (int)mObjects.size()) && (q < numQ); ++ q)
561                {
562                        //glFinish();
563                        mOcclusionQueries[q]->BeginQuery();
564                       
565                        RenderIntersectable(mObjects[j + q]);
566               
567                        mOcclusionQueries[q]->EndQuery();
568                        //glFinish();
569                }
570                //cout << "q: " << q << endl;
571                // collect results of the queries
572                for (int t = 0; t < q; ++ t)
573                {
574                        unsigned int pixelCount;
575               
576                        //-- reenable other state
577#if 0
578                        bool available;
579
580                        do
581                        {
582                                available = mOcclusionQueries[t]->ResultAvailable();
583                               
584                                if (!available) cout << "W";
585                        }
586                        while (!available);
587#endif
588
589                        pixelCount = mOcclusionQueries[t]->GetQueryResult();
590
591                        //if (pixelCount > 0)
592                        //      cout <<"o="<<j+q<<" q="<<mOcclusionQueries[q]->GetQueryId()<<" pc="<<pixelCount<<" ";
593                        mObjects[j + t]->mCounter += pixelCount;
594               
595                }
596
597                //j += q;
598        }
599#endif
600        //glFinish();
601        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
602        glDepthMask(GL_TRUE);
603       
604        glEnable(GL_CULL_FACE);
605}
606
607
608void
609GlRenderer::RandomViewPoint()
610{
611  // do not use this function since it could return different viewpoints for
612  // different executions of the algorithm
613
614  //  mViewCellsManager->GetViewPoint(mViewPoint);
615
616  while (1) {
617        Vector3 pVector = Vector3(halton.GetNumber(1),
618                                                          halton.GetNumber(2),
619                                                          halton.GetNumber(3));
620       
621        mViewPoint =  mViewCellsManager->GetViewSpaceBox().GetPoint(pVector);
622        ViewCell *v = mViewCellsManager->GetViewCell(mViewPoint);
623        if (v && v->GetValid())
624          break;
625        // generate a new vector
626        halton.GenerateNext();
627  }
628 
629  Vector3 dVector = Vector3(2*M_PI*halton.GetNumber(4),
630                                                        M_PI*halton.GetNumber(5),
631                                                        0.0f);
632 
633  mViewDirection = Normalize(Vector3(sin(dVector.x),
634                                                                         //                                                                      cos(dVector.y),
635                                                                         0.0f,
636                                                                         cos(dVector.x)));
637  halton.GenerateNext();
638}
639
640
641void
642GlRenderer::RenderBox(const AxisAlignedBox3 &box)
643{
644
645  glBegin(GL_LINE_LOOP);
646  glVertex3d(box.Min().x, box.Max().y, box.Min().z );
647  glVertex3d(box.Max().x, box.Max().y, box.Min().z );
648  glVertex3d(box.Max().x, box.Min().y, box.Min().z );
649  glVertex3d(box.Min().x, box.Min().y, box.Min().z );
650  glEnd();
651
652  glBegin(GL_LINE_LOOP);
653  glVertex3d(box.Min().x, box.Min().y, box.Max().z );
654  glVertex3d(box.Max().x, box.Min().y, box.Max().z );
655  glVertex3d(box.Max().x, box.Max().y, box.Max().z );
656  glVertex3d(box.Min().x, box.Max().y, box.Max().z );
657  glEnd();
658
659  glBegin(GL_LINE_LOOP);
660  glVertex3d(box.Max().x, box.Min().y, box.Min().z );
661  glVertex3d(box.Max().x, box.Min().y, box.Max().z );
662  glVertex3d(box.Max().x, box.Max().y, box.Max().z );
663  glVertex3d(box.Max().x, box.Max().y, box.Min().z );
664  glEnd();
665
666  glBegin(GL_LINE_LOOP);
667  glVertex3d(box.Min().x, box.Min().y, box.Min().z );
668  glVertex3d(box.Min().x, box.Min().y, box.Max().z );
669  glVertex3d(box.Min().x, box.Max().y, box.Max().z );
670  glVertex3d(box.Min().x, box.Max().y, box.Min().z );
671  glEnd();
672
673  glBegin(GL_LINE_LOOP);
674  glVertex3d(box.Min().x, box.Min().y, box.Min().z );
675  glVertex3d(box.Max().x, box.Min().y, box.Min().z );
676  glVertex3d(box.Max().x, box.Min().y, box.Max().z );
677  glVertex3d(box.Min().x, box.Min().y, box.Max().z );
678  glEnd();
679
680  glBegin(GL_LINE_LOOP);
681  glVertex3d(box.Min().x, box.Max().y, box.Min().z );
682  glVertex3d(box.Max().x, box.Max().y, box.Min().z );
683  glVertex3d(box.Max().x, box.Max().y, box.Max().z );
684  glVertex3d(box.Min().x, box.Max().y, box.Max().z );
685
686  glEnd();
687
688}
689
690void
691GlRenderer::RenderBvhNode(BvhNode *node)
692{
693  if (node->IsLeaf()) {
694        BvhLeaf *leaf = (BvhLeaf *) node;
695
696#if 0
697        if (leaf->mGlList == 0) {
698          leaf->mGlList = glGenLists(1);
699          if (leaf->mGlList != 0)
700                glNewList(leaf->mGlList, GL_COMPILE);
701         
702          for (int i=0; i < leaf->mObjects.size(); i++)
703                RenderIntersectable(leaf->mObjects[i]);
704         
705          if (leaf->mGlList != 0)
706                glEndList();
707        }
708       
709        if (leaf->mGlList != 0)
710          glCallList(leaf->mGlList);
711#else
712        for (int i=0; i < leaf->mObjects.size(); i++)
713          RenderIntersectable(leaf->mObjects[i]);
714#endif
715  } else {
716        BvhInterior *in = (BvhInterior *)node;
717        RenderBvhNode(in->GetBack());
718        RenderBvhNode(in->GetFront());
719  }
720}
721
722void
723GlRenderer::RenderKdNode(KdNode *node)
724{
725        if (node->IsLeaf())
726        {
727#if 1
728                RenderKdLeaf(static_cast<KdLeaf *>(node));
729#else
730                KdLeaf *leaf = (KdLeaf *)node;
731                for (int i=0; i < leaf->mObjects.size(); i++)
732                {
733                        RenderIntersectable(leaf->mObjects[i]);
734                }
735#endif
736        }
737        else
738        {
739                KdInterior *in = (KdInterior *)node;
740                RenderKdNode(in->mBack);
741                RenderKdNode(in->mFront);
742        }
743}
744
745
746
747
748void
749GlRendererBuffer::EvalRenderCostSample(RenderCostSample &sample,
750                                                                           const bool useOcclusionQueries,
751                                                                           const int threshold
752                                                                           )
753{
754        // choose a random view point
755        mViewCellsManager->GetViewPoint(mViewPoint);
756        sample.mPosition = mViewPoint;
757        //cout << "viewpoint: " << mViewPoint << endl;
758
759        // take a render cost sample by rendering a cube
760        Vector3 directions[6];
761
762        directions[0] = Vector3(1,0,0);
763        directions[1] = Vector3(0,1,0);
764        directions[2] = Vector3(0,0,1);
765        directions[3] = Vector3(-1,0,0);
766        directions[4] = Vector3(0,-1,0);
767        directions[5] = Vector3(0,0,-1);
768
769        sample.mVisibleObjects = 0;
770
771        // reset object counters
772        ObjectContainer::const_iterator it, it_end = mObjects.end();
773
774        for (it = mObjects.begin(); it != it_end; ++ it)
775        {
776                (*it)->mCounter = 0;
777
778        }
779
780        ++ mFrame;
781
782        //glCullFace(GL_FRONT);
783        glCullFace(GL_BACK);
784        glDisable(GL_CULL_FACE);
785
786
787        // query all 6 directions for a full point sample
788        for (int i = 0; i < 6; ++ i)
789        {
790                mViewDirection = directions[i];
791                SetupCamera();
792
793                glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
794                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
795                //glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);      glDepthMask(GL_TRUE);
796                glDepthFunc(GL_LESS);
797
798                mUseFalseColors = true;
799
800                // the actual scene rendering fills the depth (for occlusion queries)
801                // and the frame buffer (for item buffer)
802                RenderScene();
803
804
805                if (0)
806                {
807                        char filename[256];
808                        sprintf(filename, "snap/frame-%04d-%d.png", mFrame, i);
809                        //                QImage im = toImage();
810                        //                im.save(filename, "PNG");
811                }
812
813                // evaluate the sample
814                if (useOcclusionQueries)
815                {
816                        EvalQueryWithOcclusionQueries();
817                }
818                else
819                {
820                        EvalQueryWithItemBuffer();
821                }
822        } 
823
824        // now evaluate the statistics over that sample
825        // currently only the number of visible objects is taken into account
826        sample.Reset();
827
828        for (it = mObjects.begin(); it != it_end; ++ it)
829        {
830                Intersectable *obj = *it;
831                if (obj->mCounter >= threshold)
832                {
833                        ++ sample.mVisibleObjects;
834                        sample.mVisiblePixels += obj->mCounter;
835                }
836        }
837
838        //cout << "RS=" << sample.mVisibleObjects << " ";
839}
840
841
842GlRendererBuffer::~GlRendererBuffer()
843{
844#if 0
845#ifdef USE_CG
846        if (sCgFragmentProgram)
847                cgDestroyProgram(sCgFragmentProgram);
848        if (sCgContext)
849                cgDestroyContext(sCgContext);
850#endif
851#endif
852
853}
854
855
856void
857GlRendererBuffer::SampleRenderCost(const int numSamples,
858                                                                   vector<RenderCostSample> &samples,
859                                                                   const bool useOcclusionQueries,
860                                                                   const int threshold
861                                                                   )
862{
863        MakeCurrent();
864
865        if (mPixelBuffer == NULL)
866                mPixelBuffer = new unsigned int[GetWidth()*GetHeight()];
867
868        // using 90 degree projection to capture 360 view with 6 samples
869        SetupProjection(GetHeight(), GetHeight(), 90.0f);
870
871        //samples.resize(numSamples);
872        halton.Reset();
873
874        // the number of queries queried in batch mode
875        const int numQ = 500;
876
877        //const int numQ = (int)mObjects.size();
878        if (useOcclusionQueries)
879        {
880                cout << "\ngenerating " << numQ << " queries ... ";
881                OcclusionQuery::GenQueries(mOcclusionQueries, numQ);
882                cout << "finished" << endl;
883        }
884
885        // sampling queries
886        for (int i = 0; i < numSamples; ++ i)
887        {
888                cout << ".";
889                EvalRenderCostSample(samples[i], useOcclusionQueries, threshold);
890        }
891
892        DoneCurrent();
893}
894
895
896
897
898
899void
900GlRenderer::ClearErrorBuffer()
901{
902  for (int i=0; i < mPvsStatFrames; i++) {
903        mPvsErrorBuffer[i].mError = 1.0f;
904  }
905  mPvsStat.maxError = 0.0f;
906}
907
908
909void
910GlRendererBuffer::EvalPvsStat()
911{
912        MakeCurrent();
913       
914        GlRenderer::EvalPvsStat();
915       
916        DoneCurrent();
917  //  mRenderingFinished.wakeAll();
918}
919
920
921void GlRendererBuffer::EvalPvsStat(const SimpleRayContainer &viewPoints)
922{
923        MakeCurrent();
924
925        GlRenderer::EvalPvsStat(viewPoints);
926 
927        DoneCurrent();
928}
929
930
931void GlRendererBuffer::SampleBeamContributions(Intersectable *sourceObject,
932                                                                                           Beam &beam,
933                                                                                           const int desiredSamples,
934                                                                                           BeamSampleStatistics &stat)
935{
936        // TODO: should be moved out of here (not to be done every time)
937        // only back faces are interesting for the depth pass
938        glShadeModel(GL_FLAT);
939        glDisable(GL_LIGHTING);
940
941        // needed to kill the fragments for the front buffer
942        glEnable(GL_ALPHA_TEST);
943        glAlphaFunc(GL_GREATER, 0);
944
945        // assumes that the beam is constructed and contains kd-tree nodes
946        // and viewcells which it intersects
947 
948 
949        // Get the number of viewpoints to be sampled
950        // Now it is a sqrt but in general a wiser decision could be made.
951        // The less viewpoints the better for rendering performance, since less passes
952        // over the beam is needed.
953        // The viewpoints could actually be generated outside of the bounding box which
954        // would distribute the 'efective viewpoints' of the object surface and thus
955        // with a few viewpoints better sample the viewpoint space....
956
957        //TODO: comment in
958        //int viewPointSamples = sqrt((float)desiredSamples);
959        int viewPointSamples = max(desiredSamples / (GetWidth() * GetHeight()), 1);
960       
961        // the number of direction samples per pass is given by the number of viewpoints
962        int directionalSamples = desiredSamples / viewPointSamples;
963       
964        Debug << "directional samples: " << directionalSamples << endl;
965        for (int i = 0; i < viewPointSamples; ++ i)
966        {
967                Vector3 viewPoint = beam.mBox.GetRandomPoint();
968               
969                // perhaps the viewpoint should be shifted back a little bit so that it always lies
970                // inside the source object
971                // 'ideally' the viewpoints would be distributed on the soureObject surface, but this
972        // would require more complicated sampling (perhaps hierarchical rejection sampling of
973                // the object surface is an option here - only the mesh faces which are inside the box
974                // are considered as candidates)
975               
976                SampleViewpointContributions(sourceObject,
977                                                                         viewPoint,
978                                                                         beam,
979                                                                         directionalSamples,
980                                                                         stat);
981        }
982
983
984        // note:
985        // this routine would be called only if the number of desired samples is sufficiently
986        // large - for other rss tree cells the cpu based sampling is perhaps more efficient
987        // distributing the work between cpu and gpu would also allow us to place more sophisticated
988        // sample distributions (silhouette ones) using the cpu and the jittered once on the GPU
989        // in order that thios scheme is working well the gpu render buffer should run in a separate
990        // thread than the cpu sampler, which would not be such a big problem....
991
992        // disable alpha test again
993        glDisable(GL_ALPHA_TEST);
994}
995
996
997
998void GlRendererBuffer::SampleViewpointContributions(Intersectable *sourceObject,
999                                                                                                        const Vector3 viewPoint,
1000                                                                                                        Beam &beam,
1001                                                                                                        const int samples,
1002                                                    BeamSampleStatistics &stat)
1003{
1004    // 1. setup the view port to match the desired samples
1005        glViewport(0, 0, samples, samples);
1006
1007        // 2. setup the projection matrix and view matrix to match the viewpoint + beam.mDirBox
1008        SetupProjectionForViewPoint(viewPoint, beam, sourceObject);
1009
1010
1011        // 3. reset z-buffer to 0 and render the source object for the beam
1012        //    with glCullFace(Enabled) and glFrontFace(GL_CW)
1013        //    save result to the front depth map
1014        //    the front depth map holds ray origins
1015
1016
1017        // front depth buffer must be initialised to 0
1018        float clearDepth;
1019       
1020        glGetFloatv(GL_DEPTH_CLEAR_VALUE, &clearDepth);
1021        glClearDepth(0.0f);
1022        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
1023
1024
1025        // glFrontFace(GL_CCW);
1026        glEnable(GL_CULL_FACE);
1027        glCullFace(GL_FRONT);
1028        glColorMask(0, 0, 0, 0);
1029       
1030
1031        // stencil is increased where the source object is located
1032        glEnable(GL_STENCIL_TEST);     
1033        glStencilFunc(GL_ALWAYS, 0x1, 0x1);
1034        glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
1035
1036
1037#if 0
1038        static int glSourceObjList = -1;         
1039        if (glSourceObjList != -1)
1040        {
1041                glSourceObjList = glGenLists(1);
1042                glNewList(glSourceObjList, GL_COMPILE);
1043
1044                RenderIntersectable(sourceObject);
1045       
1046                glEndList();
1047        }
1048        glCallList(glSourceObjList);
1049
1050#else
1051        RenderIntersectable(sourceObject);
1052
1053#endif 
1054
1055         // copy contents of the front depth buffer into depth texture
1056        glBindTexture(GL_TEXTURE_2D, frontDepthMap);   
1057        glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, depthMapSize, depthMapSize);
1058
1059        // reset clear function
1060        glClearDepth(clearDepth);
1061       
1062       
1063        // 4. set up the termination depth buffer (= standard depth buffer)
1064        //    only rays which have non-zero entry in the origin buffer are valid since
1065        //    they realy start on the object surface (this is tagged by setting a
1066        //    stencil buffer bit at step 3).
1067       
1068        glStencilFunc(GL_EQUAL, 0x1, 0x1);
1069        glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
1070
1071        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1072        glDepthMask(1);
1073
1074        glEnable(GL_DEPTH_TEST);
1075               
1076        glEnable(GL_CULL_FACE);
1077        glCullFace(GL_BACK);
1078
1079        // setup front depth buffer
1080        glEnable(GL_TEXTURE_2D);
1081       
1082#if 0
1083#ifdef USE_CG
1084        // bind pixel shader implementing the front depth buffer functionality
1085        cgGLBindProgram(sCgFragmentProgram);
1086        cgGLEnableProfile(sCgFragmentProfile);
1087#endif
1088#endif
1089        // 5. render all objects inside the beam
1090        //    we can use id based false color to read them back for gaining the pvs
1091
1092        glColorMask(1, 1, 1, 1);
1093
1094       
1095        // if objects not stored in beam => extract objects
1096        if (beam.mFlags & !Beam::STORE_OBJECTS)
1097        {
1098                vector<KdNode *>::const_iterator it, it_end = beam.mKdNodes.end();
1099
1100                Intersectable::NewMail();
1101                for (it = beam.mKdNodes.begin(); it != it_end; ++ it)
1102                {
1103                        mKdTree->CollectObjects(*it, beam.mObjects);
1104                }
1105        }
1106
1107
1108        //    (objects can be compiled to a gl list now so that subsequent rendering for
1109        //    this beam is fast - the same hold for step 3)
1110        //    Afterwards we have two depth buffers defining the ray origin and termination
1111       
1112
1113#if 0
1114        static int glObjList = -1;
1115        if (glObjList != -1)
1116        {
1117                glObjList = glGenLists(1);
1118                glNewList(glObjList, GL_COMPILE);
1119       
1120                ObjectContainer::const_iterator it, it_end = beam.mObjects.end();
1121                for (it = beam.mObjects.begin(); it != it_end; ++ it)
1122                {
1123                        // render all objects except the source object
1124                        if (*it != sourceObject)
1125                                RenderIntersectable(*it);
1126                }
1127               
1128                glEndList();
1129        }
1130
1131        glCallList(glObjList);
1132#else
1133        ObjectContainer::const_iterator it, it_end = beam.mObjects.end();
1134        for (it = beam.mObjects.begin(); it != it_end; ++ it)
1135        {       
1136                // render all objects except the source object
1137                if (*it != sourceObject)
1138                        RenderIntersectable(*it);
1139        }
1140#endif
1141       
1142        // 6. Use occlusion queries for all viewcell meshes associated with the beam ->
1143        //     a fragment passes if the corresponding stencil fragment is set and its depth is
1144        //     between origin and termination buffer
1145
1146        // create new queries if necessary
1147        OcclusionQuery::GenQueries(mOcclusionQueries, (int)beam.mViewCells.size());
1148
1149        // check whether any backfacing polygon would pass the depth test?
1150        // matt: should check both back /front facing because of dual depth buffer
1151        // and danger of cutting the near plane with front facing polys.
1152       
1153        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1154        glDepthMask(GL_FALSE);
1155        glDisable(GL_CULL_FACE);
1156
1157 
1158        ViewCellContainer::const_iterator vit, vit_end = beam.mViewCells.end();
1159
1160        int queryIdx = 0;
1161
1162        for (vit = beam.mViewCells.begin(); vit != vit_end; ++ vit)
1163        {
1164                mOcclusionQueries[queryIdx ++]->BeginQuery();
1165                RenderIntersectable(*vit);
1166                mOcclusionQueries[queryIdx]->EndQuery();
1167
1168                ++ queryIdx;
1169        }
1170
1171        // at this point, if possible, go and do some other computation
1172
1173        // 7. The number of visible pixels is the number of sample rays which see the source
1174        //    object from the corresponding viewcell -> remember these values for later update
1175        //   of the viewcell pvs - or update immediately?
1176
1177        queryIdx = 0;
1178
1179        for (vit = beam.mViewCells.begin(); vit != vit_end; ++ vit)
1180        {
1181                // fetch queries
1182                unsigned int pixelCount = mOcclusionQueries[queryIdx ++]->GetQueryResult();
1183
1184                if (pixelCount)
1185                        Debug << "view cell " << (*vit)->GetId() << " visible pixels: " << pixelCount << endl;
1186        }
1187       
1188
1189        // 8. Copmpute rendering statistics
1190        // In general it is not neccessary to remember to extract all the rays cast. I hope it
1191        // would be sufficient to gain only the intergral statistics about the new contributions
1192        // and so the rss tree would actually store no new rays (only the initial ones)
1193        // the subdivision of the tree would only be driven by the statistics (the glrender could
1194        // evaluate the contribution entropy for example)
1195        // However might be an option to extract/store only those the rays which made a contribution
1196        // (new viewcell has been discovered) or relative contribution greater than a threshold ...
1197
1198        ObjectContainer pvsObj;
1199        stat.pvsSize = ComputePvs(beam.mObjects, pvsObj);
1200       
1201        // to gain ray source and termination
1202        // copy contents of ray termination buffer into depth texture
1203        // and compare with ray source buffer
1204#if 0
1205        VssRayContainer rays;
1206
1207        glBindTexture(GL_TEXTURE_2D, backDepthMap);     
1208        glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, depthMapSize, depthMapSize);
1209
1210        ComputeRays(Intersectable *sourceObj, rays);
1211
1212#endif
1213
1214        ////////
1215        //-- cleanup
1216
1217        // reset gl state
1218        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1219        glDepthMask(GL_TRUE);
1220        glEnable(GL_CULL_FACE);
1221        glDisable(GL_STENCIL_TEST);
1222
1223#if 0
1224#ifdef USE_CG
1225        cgGLDisableProfile(sCgFragmentProfile);
1226#endif
1227#endif
1228
1229        glDisable(GL_TEXTURE_2D);
1230
1231        // remove objects from beam
1232        if (beam.mFlags & !Beam::STORE_OBJECTS)
1233                beam.mObjects.clear();
1234}
1235
1236
1237void GlRendererBuffer::SetupProjectionForViewPoint(const Vector3 &viewPoint,
1238                                                                                                   const Beam &beam,
1239                                                                                                   Intersectable *sourceObject)
1240{
1241        float left, right, bottom, top, znear, zfar;
1242
1243        beam.ComputePerspectiveFrustum(left, right, bottom, top, znear, zfar,
1244                                                                   mSceneGraph->GetBox());
1245
1246        //Debug << left << " " << right << " " << bottom << " " << top << " " << znear << " " << zfar << endl;
1247        glMatrixMode(GL_PROJECTION);
1248        glLoadIdentity();
1249        glFrustum(left, right, bottom, top, znear, zfar);
1250        //glFrustum(-1, 1, -1, 1, 1, 20000);
1251
1252    const Vector3 center = viewPoint + beam.GetMainDirection() * (zfar - znear) * 0.3f;
1253        const Vector3 up =
1254                Normalize(CrossProd(beam.mPlanes[0].mNormal, beam.mPlanes[4].mNormal));
1255
1256#ifdef GTP_DEBUG
1257        Debug << "view point: " << viewPoint << endl;
1258        Debug << "eye: " << center << endl;
1259        Debug << "up: " << up << endl;
1260#endif
1261
1262        glMatrixMode(GL_MODELVIEW);
1263        glLoadIdentity();
1264        gluLookAt(viewPoint.x, viewPoint.y, viewPoint.z,
1265                          center.x, center.y, center.z,                   
1266                          up.x, up.y, up.z);
1267}               
1268
1269 
1270void GlRendererBuffer::InitGL()
1271{
1272        MakeCurrent();
1273        GlRenderer::InitGL();
1274
1275        // initialise dual depth buffer textures
1276        glGenTextures(1, &frontDepthMap);
1277        glBindTexture(GL_TEXTURE_2D, frontDepthMap);
1278
1279        glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, depthMapSize,
1280                depthMapSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
1281
1282        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1283        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1284        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
1285        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
1286
1287        glGenTextures(1, &backDepthMap);
1288        glBindTexture(GL_TEXTURE_2D, backDepthMap);
1289
1290        glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, depthMapSize,
1291                depthMapSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
1292        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1293        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1294        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
1295        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
1296
1297#if 0
1298#ifdef USE_CG
1299
1300        // cg initialization
1301        cgSetErrorCallback(handleCgError);
1302        sCgContext = cgCreateContext();
1303
1304        if (cgGLIsProfileSupported(CG_PROFILE_ARBFP1))
1305                sCgFragmentProfile = CG_PROFILE_ARBFP1;
1306        else
1307        {
1308                // try FP30
1309                if (cgGLIsProfileSupported(CG_PROFILE_FP30))
1310                        sCgFragmentProfile = CG_PROFILE_FP30;
1311                else
1312                {
1313                        Debug << "Neither arbfp1 or fp30 fragment profiles supported on this system" << endl;
1314                        exit(1);
1315                }
1316        }
1317
1318        sCgFragmentProgram = cgCreateProgramFromFile(sCgContext,
1319                                                         CG_SOURCE, "../src/dual_depth.cg",
1320                                                                                                 sCgFragmentProfile,
1321                                                                                                 NULL,
1322                                                                                                 NULL);
1323
1324        if (!cgIsProgramCompiled(sCgFragmentProgram))
1325                cgCompileProgram(sCgFragmentProgram);
1326
1327        cgGLLoadProgram(sCgFragmentProgram);
1328        cgGLBindProgram(sCgFragmentProgram);
1329
1330        Debug << "---- PROGRAM BEGIN ----\n" <<
1331                cgGetProgramString(sCgFragmentProgram, CG_COMPILED_PROGRAM) << "---- PROGRAM END ----\n";
1332
1333#endif
1334
1335#endif
1336        DoneCurrent();
1337}
1338
1339
1340void GlRendererBuffer::ComputeRays(Intersectable *sourceObj, VssRayContainer &rays)
1341{
1342        for (int i = 0; i < depthMapSize * depthMapSize; ++ i)
1343        {
1344                //todo glGetTexImage()
1345        }
1346}
1347
1348bool GlRendererBuffer::ValidViewPoint()
1349{       
1350        MakeCurrent();
1351
1352        SetupProjection(GetWidth(), GetHeight());
1353
1354        bool result = GlRenderer::ValidViewPoint();
1355
1356        DoneCurrent();
1357       
1358        return result;
1359}
1360
1361
1362void
1363GlRenderer::EvalPvsStat()
1364{
1365  mPvsStat.Reset();
1366  halton.Reset();
1367
1368  SetupProjection(GetWidth(), GetHeight());
1369
1370  cout<<"mPvsStatFrames="<<mPvsStatFrames<<endl;
1371 
1372  for (int i=0; i < mPvsStatFrames; i++) {
1373        float err;
1374        // set frame id for saving the error buffer
1375        mFrame = i;
1376        RandomViewPoint();
1377
1378        if (mPvsErrorBuffer[i].mError == 1.0f) {
1379          // check if the view point is valid
1380          if (!ValidViewPoint())
1381                mPvsErrorBuffer[i].mError = -1.0f;
1382
1383          // manualy corrected view point
1384          if (mFrame == 5105)
1385                mPvsErrorBuffer[i].mError = -1.0f;
1386        }
1387       
1388       
1389        // atlanta problematic frames: 325 525 691 1543
1390#if 0
1391        if (mFrame != 325 &&
1392                mFrame != 525 &&
1393                mFrame != 691 &&
1394                mFrame != 1543)
1395          mPvsErrorBuffer[i] = -1;
1396        else {
1397          Debug<<"frame ="<<mFrame<<" vp="<<mViewPoint<<" vd="<<mViewDirection<<endl;
1398        }
1399#endif
1400       
1401        if (mPvsErrorBuffer[i].mError > 0.0f) {
1402          int pvsSize;
1403         
1404          float error = GetPixelError(pvsSize);
1405          mPvsErrorBuffer[i].mError = error;
1406          mPvsErrorBuffer[i].mPvsSize = pvsSize;
1407
1408          //      emit UpdatePvsErrorItem(i,
1409          //                                                      mPvsErrorBuffer[i]);
1410          cout<<"("<<i<<","<<mPvsErrorBuffer[i].mError<<")";
1411          //      swapBuffers();
1412        }
1413       
1414        err = mPvsErrorBuffer[i].mError;
1415       
1416        if (err >= 0.0f) {
1417          if (err > mPvsStat.maxError)
1418                mPvsStat.maxError = err;
1419          mPvsStat.sumError += err;
1420          mPvsStat.sumPvsSize += mPvsErrorBuffer[i].mPvsSize;
1421         
1422          if (err == 0.0f)
1423                mPvsStat.errorFreeFrames++;
1424          mPvsStat.frames++;
1425        }
1426  }
1427 
1428  glFinish();
1429  cout<<endl<<flush;
1430}
1431
1432
1433void GlRenderer::EvalPvsStat(const SimpleRayContainer &viewPoints)
1434{
1435  mPvsStat.Reset();
1436
1437  SetupProjection(GetWidth(), GetHeight());
1438 
1439  cout << "mPvsStatFrames=" << mPvsStatFrames << endl;
1440 
1441  SimpleRayContainer::const_iterator sit, sit_end = viewPoints.end();
1442  int i = 0;
1443 
1444  for (sit = viewPoints.begin(); sit != sit_end; ++ sit, ++ i)
1445        {
1446         
1447          //cout << "view point: " << (*sit) << endl;;
1448          SimpleRay sray = *sit;
1449         
1450          float err;
1451         
1452          // set frame id for saving the error buffer
1453          mFrame = i;
1454          mViewPoint = sray.mOrigin;
1455          mViewDirection = sray.mDirection;
1456         
1457          if (mPvsErrorBuffer[i].mError > 0.0f)
1458          {
1459                  int pvsSize;
1460
1461                  // compute the pixel error
1462                  float error = GetPixelError(pvsSize);
1463
1464                  mPvsErrorBuffer[i].mError = error;
1465                  mPvsErrorBuffer[i].mPvsSize = pvsSize;
1466
1467                  cout << "(" << i << "," << mPvsErrorBuffer[i].mError <<")";
1468          }
1469
1470          err = mPvsErrorBuffer[i].mError;
1471
1472          if (err >= 0.0f)
1473          {
1474                  if (err > mPvsStat.maxError)
1475                          mPvsStat.maxError = err;
1476
1477                  mPvsStat.sumError += err;
1478                  mPvsStat.sumPvsSize += mPvsErrorBuffer[i].mPvsSize;
1479
1480                  if (err == 0.0f)
1481                          ++ mPvsStat.errorFreeFrames;
1482
1483                  ++ mPvsStat.frames;
1484          }
1485        }
1486 
1487  glFinish();
1488  cout << endl << flush;
1489}
1490
1491
1492
1493bool
1494GlRenderer::ValidViewPoint()
1495{
1496        //cout<<"VV4 ";
1497        if (!mDetectEmptyViewSpace)
1498                return true;
1499        //cout << "vp: " << mViewPoint << " dir: " << mViewDirection << endl;
1500
1501        OcclusionQuery *query = mOcclusionQueries[0];
1502
1503        // now check whether any backfacing polygon would pass the depth test
1504        SetupCamera();
1505        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1506        glEnable( GL_CULL_FACE );
1507        glCullFace(GL_BACK);
1508
1509        //cout<<"VV1 ";
1510        RenderScene();
1511
1512        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1513        glDepthMask(GL_FALSE);
1514        glDisable( GL_CULL_FACE );
1515
1516        query->BeginQuery();
1517
1518        //  cout<<"VV2 ";
1519        RenderScene();
1520        //  cout<<"VV3 ";
1521
1522        query->EndQuery();
1523
1524        // at this point, if possible, go and do some other computation
1525        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1526        glDepthMask(GL_TRUE);
1527        glEnable( GL_CULL_FACE );
1528
1529        //  int wait = 0;
1530        //  while (!query.ResultAvailable()) {
1531        //      wait++;
1532        //  }
1533
1534        // reenable other state
1535        unsigned int pixelCount = query->GetQueryResult();
1536        //  cout<<"VV4 ";
1537
1538        //cout<<"count: " << pixelCount<<endl;
1539
1540        if (pixelCount > 0)
1541        {
1542                return false; // backfacing polygon found -> not a valid viewspace sample
1543        }
1544        return true;
1545}
1546
1547
1548float GlRenderer::GetPixelError(int &pvsSize)
1549{
1550  return -1.0f;
1551}
1552
1553
1554void GlRenderer::RenderViewPoint()
1555{
1556        mWireFrame = true;
1557        glPushMatrix();
1558        glTranslatef(mViewPoint.x, mViewPoint.y, mViewPoint.z);
1559        glScalef(5.0f, 5.0f, 5.0f);
1560        glPushAttrib(GL_CURRENT_BIT);
1561        glColor3f(1.0f, 0.0f, 0.0f);
1562        gluSphere((::GLUquadric *)mSphere,
1563                1e-3*Magnitude(mViewCellsManager->GetViewSpaceBox().Size()), 6, 6);
1564        glPopAttrib();
1565        glPopMatrix();
1566        mWireFrame = false;
1567}
1568
1569
1570void GlRenderer::EnableDrawArrays()
1571{
1572        glEnableClientState(GL_VERTEX_ARRAY);
1573        glEnableClientState(GL_NORMAL_ARRAY);
1574}
1575
1576
1577void GlRenderer::DisableDrawArrays()
1578{
1579        glDisableClientState(GL_VERTEX_ARRAY);
1580        glDisableClientState(GL_NORMAL_ARRAY);
1581}
1582
1583
1584#if 0
1585
1586void GlRenderer::RenderKdLeaf(KdLeaf *leaf)
1587{
1588        int bufferSize = 0;
1589
1590        // count #new triangles
1591        for (size_t i = 0; i < leaf->mObjects.size(); ++ i)
1592        {
1593                TriangleIntersectable *obj = static_cast<TriangleIntersectable *>(leaf->mObjects[i]);
1594
1595                // check if already rendered
1596                if (!obj->Mailed())
1597                        bufferSize += 3;
1598                //else cout << obj->mMailbox << " " << obj->sMailId << " ";
1599        }
1600
1601        Vector3 *vertices = new Vector3[bufferSize];
1602        Vector3 *normals = new Vector3[bufferSize];
1603
1604        int j = 0;
1605
1606        for (size_t i = 0; i < leaf->mObjects.size(); ++ i)
1607        {
1608                TriangleIntersectable *obj = static_cast<TriangleIntersectable *>(leaf->mObjects[i]);
1609
1610                // check if already rendered
1611                if (obj->Mailed())
1612                        continue;
1613
1614                obj->Mail();
1615
1616                Triangle3 tri = obj->GetItem();
1617
1618                vertices[j * 3 + 0] = tri.mVertices[0];
1619                vertices[j * 3 + 1] = tri.mVertices[1];
1620                vertices[j * 3 + 2] = tri.mVertices[2];
1621
1622                Vector3 n = tri.GetNormal();
1623
1624                normals[j * 3 + 0] = n;
1625                normals[j * 3 + 1] = n;
1626                normals[j * 3 + 2] = n;
1627
1628                ++ j;
1629        }
1630
1631        glVertexPointer(3, GL_FLOAT, 0, vertices);
1632        glNormalPointer(GL_FLOAT, 0, normals);
1633
1634        glDrawArrays(GL_TRIANGLES, 0, bufferSize);
1635
1636        DEL_PTR(vertices);
1637        DEL_PTR(normals);
1638}
1639
1640#else
1641
1642void GlRenderer::RenderKdLeaf(KdLeaf *leaf)
1643{
1644        if (!leaf->mIndexBufferSize)
1645                return;
1646
1647        size_t offset = mObjects.size() * 3;
1648        char *arrayPtr = mUseVbos ? NULL : (char *)mData;
1649       
1650        glVertexPointer(3, GL_FLOAT, 0, (char *)arrayPtr);
1651        glNormalPointer(GL_FLOAT, 0, (char *)arrayPtr + offset * sizeof(Vector3));
1652       
1653        glDrawElements(GL_TRIANGLES, leaf->mIndexBufferSize, GL_UNSIGNED_INT, mIndices + leaf->mIndexBufferStart);
1654}
1655
1656#endif
1657
1658void GlRenderer::CreateVertexArrays()
1659{
1660        mData = new Vector3[mObjects.size() * 6];
1661        mIndices = new unsigned int[mObjects.size() * 3];
1662
1663        size_t offset = mObjects.size() * 3;
1664
1665        for (size_t i = 0; i < mObjects.size(); ++ i)
1666        {
1667                TriangleIntersectable *obj = static_cast<TriangleIntersectable *>(mObjects[i]);
1668
1669                Triangle3 tri = obj->GetItem();
1670                const Vector3 n = tri.GetNormal();
1671
1672                mData[i * 3 + 0] = tri.mVertices[0];
1673                mData[i * 3 + 1] = tri.mVertices[1];
1674                mData[i * 3 + 2] = tri.mVertices[2];
1675
1676                mData[offset + i * 3 + 0] = n;
1677                mData[offset + i * 3 + 1] = n;
1678                mData[offset + i * 3 + 2] = n;
1679        }
1680
1681        if (mUseVbos)
1682        {
1683                EnableDrawArrays();
1684
1685                glGenBuffersARB(1, &mVboId);
1686                glBindBufferARB(GL_ARRAY_BUFFER_ARB, mVboId);
1687
1688                glVertexPointer(3, GL_FLOAT, 0, (char *)NULL);
1689                glNormalPointer(GL_FLOAT, 0, (char *)NULL + offset * sizeof(Vector3));
1690
1691                glBufferDataARB(GL_ARRAY_BUFFER_ARB, mObjects.size() * 6 * sizeof(Vector3), mData, GL_STATIC_DRAW_ARB);
1692                glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
1693
1694                DisableDrawArrays();
1695
1696                delete [] mData;
1697        }
1698
1699        cout << "\n******** created vertex buffer objects **********" << endl; 
1700}
1701
1702
1703void GlRenderer::DeleteVbos()
1704{
1705        glDeleteBuffersARB(1, &mVboId);
1706
1707/*
1708        KdLeafContainer leaves;
1709        mKdTree->CollectLeaves(leaves);
1710
1711        KdLeafContainer::const_iterator kit, kit_end = leaves.end();
1712
1713        for (kit = leaves.begin(); kit != kit_end; ++ kit)
1714        {
1715                KdLeaf *leaf = *kit;
1716
1717                if (leaf->mVboId == -1)
1718                {
1719                        // delete old vbo
1720                        glDeleteBuffersARB(1, &leaf->mVboId);
1721                        leaf->mVboId = -1;
1722                }
1723        }
1724*/
1725}
1726
1727
1728
1729}
Note: See TracBrowser for help on using the repository browser.