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

Revision 2633, 45.5 KB checked in by mattausch, 16 years ago (diff)

revived hash pvs

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