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

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