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

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