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

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