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

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