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

Revision 2653, 47.9 KB checked in by bittner, 16 years ago (diff)

merge - pvs error code
glrenderer.cpp

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