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

Revision 2643, 46.2 KB checked in by mattausch, 16 years ago (diff)

compiling under release internal

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