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

Revision 2619, 43.9 KB checked in by bittner, 16 years ago (diff)

TEST PVS RENDERING ON

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