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

Revision 2616, 43.7 KB checked in by bittner, 16 years ago (diff)

merge

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