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 *
Line 
1#include "Mesh.h"
2#include "glInterface.h"
3#include "OcclusionQuery.h"
4#include "GlRenderer.h"
5#include "ViewCellsManager.h"
6#include "SceneGraph.h"
7#include "ViewCell.h"
8#include "Beam.h"
9#include "KdTree.h"
10#include "Environment.h"
11#include "Triangle3.h"
12#include "IntersectableWrapper.h"
13#include "BvHierarchy.h"
14#include "KdTree.h"
15#include "SamplingStrategy.h"
16#include "Preprocessor.h"
17#include "SceneGraph.h"
18
19
20#ifdef USE_CG
21
22#include <Cg/cg.h>
23#include <Cg/cgGL.h>
24
25#endif
26
27// if 1 = SAFE RENDERING OF PVS primitives without VBOs for Pvs error estimation
28#define EVAL_ERROR 0
29
30namespace GtpVisibilityPreprocessor {
31
32
33static bool arbQuerySupport = false;
34static bool nvQuerySupport = false;
35
36static GLuint frontDepthMap;
37static GLuint backDepthMap;
38
39const int depthMapSize = 512;
40
41
42static void InitExtensions()
43{
44        GLenum err = glewInit();
45
46        if (GLEW_OK != err)
47        {
48                // problem: glewInit failed, something is seriously wrong
49                cerr << "Error: " << glewGetErrorString(err) << endl;
50                exit(1);
51        }
52
53        if (GLEW_ARB_occlusion_query)
54                arbQuerySupport = true;
55       
56        if (GLEW_NV_occlusion_query)
57                nvQuerySupport = true;
58
59        if  (!arbQuerySupport && !nvQuerySupport)
60        {
61                cout << "I require the GL_ARB_occlusion_query or the GL_NV_occlusion_query OpenGL extension to work.\n";
62                exit(1);
63        }
64
65        if (!GLEW_ARB_vertex_buffer_object)
66        {
67                cout << "vbos not supported" << endl;
68        }
69        else
70        {
71                cout << "vbos supported" << endl;
72        }
73}
74
75
76GlRenderer::GlRenderer(SceneGraph *sceneGraph,
77                                           ViewCellsManager *viewCellsManager,
78                                           KdTree *tree):
79Renderer(sceneGraph, viewCellsManager),
80mKdTree(tree),
81mUseFalseColors(false),
82mVboId(-1),
83mData(NULL),
84mIndices(NULL),
85//mUseVbos(true),
86mUseVbos(false),
87mComputeGVS(false),
88mCurrentFrame(100)
89{
90        mSceneGraph->CollectObjects(mObjects);
91
92#if 1
93        viewCellsManager->GetViewPoint(mViewPoint);
94        mViewDirection = Vector3(0,0,1);
95#else
96
97        // for sg snapshot
98        mViewPoint = Vector3(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
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
113#endif
114
115        mFrame = 0;
116        mWireFrame = false;
117        Environment::GetSingleton()->GetBoolValue("Preprocessor.detectEmptyViewSpace",
118                                                      mDetectEmptyViewSpace);
119
120        //mSnapErrorFrames = false;
121        mSnapErrorFrames = true;
122        mSnapPrefix = "snap/";
123        mUseForcedColors = false;
124        mRenderBoxes = false;
125        //mUseGlLists = true;
126        mUseGlLists = false;
127
128        if (mViewCellsManager->GetViewCellPointsList()->size())
129                mPvsStatFrames = (int)mViewCellsManager->GetViewCellPointsList()->size();
130        else
131                Environment::GetSingleton()->GetIntValue("Preprocessor.pvsRenderErrorSamples",
132                                                                                                 mPvsStatFrames);
133       
134        Debug<<"Info: will evaluate pixel error with "<<mPvsStatFrames<<" samples"<<endl;
135       
136        mPvsErrorBuffer.resize(mPvsStatFrames);
137        ClearErrorBuffer();
138}
139
140
141GlRenderer::~GlRenderer()
142{
143        cerr<<"gl renderer destructor..\n";
144
145        CLEAR_CONTAINER(mOcclusionQueries);
146
147        DeleteVbos();
148
149        if (mData) delete [] mData;
150        if (mIndices) delete [] mIndices;
151
152        glDeleteBuffersARB(1, &mVboId);
153        cerr<<"done."<<endl;
154}
155
156
157void GlRenderer::RenderTriangle(TriangleIntersectable *object)
158{
159        Triangle3 *t = &(object->GetItem());
160        glBegin(GL_TRIANGLES);
161        Vector3 normal = t->GetNormal();
162        glNormal3f(normal.x, normal.y, normal.z);
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);
166        glEnd();
167}
168
169
170void GlRenderer::RenderIntersectable(Intersectable *object)
171{
172  if (!object || (object->mRenderedFrame == mCurrentFrame))
173        return;
174
175        object->mRenderedFrame = mCurrentFrame;
176
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();
223}
224
225
226void GlRenderer::RenderRays(const VssRayContainer &rays, int colorType, int showDistribution, int maxAge)
227{
228        float importance;
229
230        glBegin(GL_LINES);
231
232        VssRayContainer::const_iterator it = rays.begin(), it_end = rays.end();
233
234        for (; it != it_end; ++it)
235        {
236                VssRay *ray = *it;
237
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)) ||
242                        ((ray->mDistribution == SamplingStrategy::MUTATION_BASED_DISTRIBUTION) && ((showDistribution & 8) == 0)) ||
243                        ((mViewCellsManager->GetPreprocessor()->mPass - ray->mPass) >= maxAge))
244                {
245                        continue;
246                }
247               
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
285                glVertex3fv(&ray->mOrigin.x);
286                glVertex3fv(&ray->mTermination.x);
287        }
288
289        glEnd();
290}
291
292
293void GlRenderer::RenderViewCell(ViewCell *vc)
294{
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                }
304
305                RenderMesh(vc->GetMesh());
306        }
307        else
308        {
309                // render viewcells in the subtree
310                if (!vc->IsLeaf())
311                {
312                        ViewCellInterior *vci = (ViewCellInterior *) vc;
313
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                }
324        }
325}
326
327
328void GlRenderer::RenderMeshInstance(MeshInstance *mi)
329{
330        RenderMesh(mi->GetMesh());
331}
332
333
334void
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
351GlRenderer::SetupFalseColor(const unsigned int id)
352{
353        // swap bits of the color
354        glColor3ub(id&255, (id>>8)&255, (id>>16)&255);
355}
356
357
358unsigned int GlRenderer::GetId(const unsigned char r,
359                                                           const unsigned char g,
360                                                           const unsigned char b) const
361{
362        return r + (g << 8) + (b << 16);
363}
364
365
366void
367GlRenderer::SetupMaterial(Material *m)
368{
369  if (m)
370        glColor3fv(&(m->mDiffuseColor.r));
371}
372
373
374void GlRenderer::RenderMesh(Mesh *mesh)
375{
376        int i = 0;
377
378        if (!mUseFalseColors && !mUseForcedColors)
379                SetupMaterial(mesh->mMaterial);
380
381        for (i = 0; i < mesh->mFaces.size(); i++)
382        {
383                if (mWireFrame)
384                        glBegin(GL_LINE_LOOP);
385                else
386                        glBegin(GL_POLYGON);
387
388                Face *face = mesh->mFaces[i];
389                Vector3 normal = mesh->GetNormal(i);
390
391                glNormal3f(normal.x, normal.y, normal.z);
392                for (int j = 0; j < face->mVertexIndices.size(); j++) {
393                        glVertex3fv(&mesh->mVertices[face->mVertexIndices[j]].x);
394                }
395                glEnd();
396        }
397}
398       
399void GlRenderer::InitGL()
400{
401        mSphere = (GLUquadric *)gluNewQuadric();
402
403        glMatrixMode(GL_PROJECTION);
404        glLoadIdentity();
405
406        glMatrixMode(GL_MODELVIEW);
407        glLoadIdentity();
408
409        glFrontFace(GL_CCW);
410        glCullFace(GL_BACK);
411
412        glShadeModel(GL_FLAT);
413        glDepthFunc(GL_LESS );
414        glEnable(GL_DEPTH_TEST);
415        glEnable(GL_CULL_FACE);
416
417        InitExtensions();
418
419        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
420
421        glEnable(GL_NORMALIZE);
422
423        glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
424
425        // create some occlusion queries
426        OcclusionQuery::GenQueries(mOcclusionQueries, 100);
427
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        }
436}
437
438
439void
440GlRenderer::SetupProjection(const int w, const int h, const float angle)
441{
442  glViewport(0, 0, w, h);
443  glMatrixMode(GL_PROJECTION);
444  glLoadIdentity();
445  gluPerspective(angle, 1.0, 0.1, 2.0*Magnitude(mSceneGraph->GetBox().Diagonal()));
446  glMatrixMode(GL_MODELVIEW);
447}
448
449
450
451void
452GlRenderer::SetupCamera()
453{
454        Vector3 target = mViewPoint + mViewDirection;
455
456        Vector3 up(0,1,0);
457
458        if (fabs(DotProd(mViewDirection, up)) > 0.99f)
459          up = Vector3(1, 0, 0);
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);
465}
466
467
468void GlRenderer::_RenderScene()
469{
470        ObjectContainer::const_iterator oi = mObjects.begin();
471
472        for (; oi != mObjects.end(); oi++)
473                RenderIntersectable(*oi);
474}
475
476
477void GlRenderer::_RenderSceneTrianglesWithDrawArrays()
478{
479        EnableDrawArrays();
480       
481        if (mUseVbos)
482                glBindBufferARB(GL_ARRAY_BUFFER_ARB, mVboId);
483
484        const int offset = (int)mObjects.size() * 3;
485        char *arrayPtr = mUseVbos ? NULL : (char *)mData;
486       
487        glVertexPointer(3, GL_FLOAT, 0, (char *)arrayPtr);
488        glNormalPointer(GL_FLOAT, 0, (char *)arrayPtr + offset * sizeof(Vector3));
489       
490        glDrawArrays(GL_TRIANGLES, 0, offset);
491}
492
493
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();
521       
522        glPopMatrix();
523
524#if 1
525        // test the box of the object
526        AxisAlignedBox3 box = leaf->GetBox();
527        RenderBox(box);
528#endif
529}
530
531
532
533void GlRenderer::_RenderSceneTriangles()
534{
535        glBegin(GL_TRIANGLES);
536
537        ObjectContainer::const_iterator oi = mObjects.begin();
538        for (; oi != mObjects.end(); oi++) {
539
540          if ((*oi)->Type() == Intersectable::TRIANGLE_INTERSECTABLE) {
541                        TriangleIntersectable *object = (TriangleIntersectable *)*oi;
542                        Triangle3 *t = &(object->GetItem());
543
544                        Vector3 normal = t->GetNormal();
545                        glNormal3f(normal.x, normal.y, normal.z);
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);
549          }
550        }
551
552        glEnd();
553}
554
555
556bool GlRenderer::RenderScene()
557{
558        ++ mCurrentFrame;
559
560        Intersectable::NewMail();
561
562#if DYNAMIC_OBJECTS_HACK
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        {
569#if USE_TRANSFORMED_MESH_INSTANCE_HACK
570                RenderIntersectable(*dit);
571#else
572                _RenderDynamicObject(*dit);
573#endif
574        }
575#endif
576
577#if 1
578        _RenderSceneTrianglesWithDrawArrays();
579
580#else
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
594#endif
595        return true;
596}
597
598
599void
600GlRendererBuffer::EvalQueryWithItemBuffer()
601{
602        // read back the texture
603        glReadPixels(0, 0,
604                GetWidth(), GetHeight(),
605                GL_RGBA,
606                GL_UNSIGNED_BYTE,
607                mPixelBuffer);
608
609
610        unsigned int *p = mPixelBuffer;
611
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)
619                        {
620                                ++ mObjects[id]->mCounter;
621                        }
622                }
623        }
624}
625
626
627
628/****************************************************************/
629/*               GlRendererBuffer implementation                */
630/****************************************************************/
631
632
633
634GlRendererBuffer::GlRendererBuffer(SceneGraph *sceneGraph,
635                                                                   ViewCellsManager *viewcells,
636                                                                   KdTree *tree):
637GlRenderer(sceneGraph, viewcells, tree) 
638{
639        mPixelBuffer = NULL;
640        // implement width and height in subclasses
641}
642
643
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);
653
654
655        // simulate detectemptyviewspace using backface culling
656        if (mDetectEmptyViewSpace)
657        {
658                glEnable(GL_CULL_FACE);
659                //cout << "culling" << endl;
660        }
661        else
662        {
663                //cout << "not culling" << endl;
664                glDisable(GL_CULL_FACE);
665        }
666
667       
668        //const int numQ = 1;
669        const int numQ = (int)mOcclusionQueries.size();
670       
671        //glFinish();
672#if 0
673        //-- now issue queries for all objects
674        for (int j = 0; j < (int)mObjects.size(); ++ j)
675        {
676                mOcclusionQueries[j]->BeginQuery();
677                RenderIntersectable(mObjects[j]);
678                mOcclusionQueries[j]->EndQuery();
679
680                unsigned int pixelCount;
681
682                pixelCount = mOcclusionQueries[j]->GetQueryResult();
683               
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)
692        {       
693                for (q = 0; ((j + q) < (int)mObjects.size()) && (q < numQ); ++ q)
694                {
695                        mOcclusionQueries[q]->BeginQuery();
696                       
697                        RenderIntersectable(mObjects[j + q]);
698               
699                        mOcclusionQueries[q]->EndQuery();
700                }
701                //cout << "q: " << q << endl;
702                // collect results of the queries
703                for (int t = 0; t < q; ++ t)
704                {
705                        unsigned int pixelCount;
706               
707                        //-- reenable other state
708#if 0
709                        bool available;
710
711                        do
712                        {
713                                available = mOcclusionQueries[t]->ResultAvailable();
714                               
715                                if (!available) cout << "W";
716                        }
717                        while (!available);
718#endif
719
720                        pixelCount = mOcclusionQueries[t]->GetQueryResult();
721
722                        //if (pixelCount > 0)
723                        //      cout <<"o="<<j+q<<" q="<<mOcclusionQueries[q]->GetQueryId()<<" pc="<<pixelCount<<" ";
724                        mObjects[j + t]->mCounter += pixelCount;
725               
726                }
727
728                //j += q;
729        }
730#endif
731        //glFinish();
732        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
733        glDepthMask(GL_TRUE);
734       
735        glEnable(GL_CULL_FACE);
736}
737
738
739void
740GlRenderer::RandomViewPoint()
741{
742  // do not use this function since it could return different viewpoints for
743  // different executions of the algorithm
744
745  //  mViewCellsManager->GetViewPoint(mViewPoint);
746
747  while (1) {
748        Vector3 pVector = Vector3(halton.GetNumber(1),
749                                                          halton.GetNumber(2),
750                                                          halton.GetNumber(3));
751       
752        mViewPoint =  mViewCellsManager->GetViewSpaceBox().GetPoint(pVector);
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),
765                                                                         //     cos(dVector.y),
766                                                                         0.0f,
767                                                                         cos(dVector.x)));
768  halton.GenerateNext();
769}
770
771
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
819}
820
821void
822GlRenderer::RenderBvhNode(BvhNode *node)
823{
824  if (node->IsLeaf()) {
825        BvhLeaf *leaf = (BvhLeaf *) node;
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
843        for (int i=0; i < leaf->mObjects.size(); i++)
844          RenderIntersectable(leaf->mObjects[i]);
845#endif
846  } else {
847        BvhInterior *in = (BvhInterior *)node;
848        RenderBvhNode(in->GetBack());
849        RenderBvhNode(in->GetFront());
850  }
851}
852
853void
854GlRenderer::RenderKdNode(KdNode *node)
855{
856  if (node->IsLeaf())
857        {
858#if !EVAL_ERROR
859                RenderKdLeaf(static_cast<KdLeaf *>(node));
860#else
861                KdLeaf *leaf = static_cast<KdLeaf *>(node);
862                for (int i=0; i < leaf->mObjects.size(); i++)
863                  {
864                        RenderIntersectable(leaf->mObjects[i]);
865                       
866                  }
867#endif
868        }
869        else
870        {
871                KdInterior *inter = static_cast<KdInterior *>(node);
872                RenderKdNode(inter->mBack);
873                RenderKdNode(inter->mFront);
874        }
875}
876
877
878
879
880void
881GlRendererBuffer::EvalRenderCostSample(RenderCostSample &sample,
882                                                                           const bool useOcclusionQueries,
883                                                                           const int threshold
884                                                                           )
885{
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)
907        {
908                (*it)->mCounter = 0;
909
910        }
911
912        ++ mFrame;
913
914        //glCullFace(GL_FRONT);
915        glCullFace(GL_BACK);
916        glDisable(GL_CULL_FACE);
917
918
919        // query all 6 directions for a full point sample
920        for (int i = 0; i < 6; ++ i)
921        {
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)
938                {
939                        char filename[256];
940                        sprintf(filename, "snap/frame-%04d-%d.png", mFrame, i);
941                        //                QImage im = toImage();
942                        //                im.save(filename, "PNG");
943                }
944
945                // evaluate the sample
946                if (useOcclusionQueries)
947                {
948                        EvalQueryWithOcclusionQueries();
949                }
950                else
951                {
952                        EvalQueryWithItemBuffer();
953                }
954        } 
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)
961        {
962                Intersectable *obj = *it;
963                if (obj->mCounter >= threshold)
964                {
965                        ++ sample.mVisibleObjects;
966                        sample.mVisiblePixels += obj->mCounter;
967                }
968        }
969
970        //cout << "RS=" << sample.mVisibleObjects << " ";
971}
972
973
974GlRendererBuffer::~GlRendererBuffer()
975{
976#if 0
977#ifdef USE_CG
978        if (sCgFragmentProgram)
979                cgDestroyProgram(sCgFragmentProgram);
980        if (sCgContext)
981                cgDestroyContext(sCgContext);
982#endif
983#endif
984
985}
986
987
988void
989GlRendererBuffer::SampleRenderCost(const int numSamples,
990                                                                   vector<RenderCostSample> &samples,
991                                                                   const bool useOcclusionQueries,
992                                                                   const int threshold
993                                                                   )
994{
995        MakeCurrent();
996
997        if (mPixelBuffer == NULL)
998                mPixelBuffer = new unsigned int[GetWidth()*GetHeight()];
999
1000        // using 90 degree projection to capture 360 view with 6 samples
1001        SetupProjection(GetHeight(), GetHeight(), 90.0f);
1002
1003        //samples.resize(numSamples);
1004        halton.Reset();
1005
1006        // the number of queries queried in batch mode
1007        const int numQ = 500;
1008
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();
1025}
1026
1027
1028
1029
1030
1031void
1032GlRenderer::ClearErrorBuffer()
1033{
1034  for (int i=0; i < mPvsStatFrames; i++) {
1035        mPvsErrorBuffer[i].mError = 1.0f;
1036  }
1037  mPvsStat.maxError = 0.0f;
1038}
1039
1040
1041void
1042GlRendererBuffer::EvalPvsStat()
1043{
1044        MakeCurrent();
1045       
1046        GlRenderer::EvalPvsStat();
1047       
1048        DoneCurrent();
1049  //  mRenderingFinished.wakeAll();
1050}
1051
1052
1053void GlRendererBuffer::EvalPvsStat(const SimpleRayContainer &viewPoints)
1054{
1055        MakeCurrent();
1056
1057        GlRenderer::EvalPvsStat(viewPoints);
1058 
1059        DoneCurrent();
1060}
1061
1062
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       
1214#if 0
1215#ifdef USE_CG
1216        // bind pixel shader implementing the front depth buffer functionality
1217        cgGLBindProgram(sCgFragmentProgram);
1218        cgGLEnableProfile(sCgFragmentProfile);
1219#endif
1220#endif
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       
1274        // 6. Use occlusion queries for all viewcell meshes associated with the beam ->
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
1346        ////////
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);
1354
1355#if 0
1356#ifdef USE_CG
1357        cgGLDisableProfile(sCgFragmentProfile);
1358#endif
1359#endif
1360
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{
1404        //MakeCurrent();
1405        GlRenderer::InitGL();
1406
1407#if 0
1408        // initialise dual depth buffer textures
1409        glGenTextures(1, &frontDepthMap);
1410        glBindTexture(GL_TEXTURE_2D, frontDepthMap);
1411
1412        glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, depthMapSize,
1413                depthMapSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
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);
1422
1423        glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, depthMapSize,
1424                                 depthMapSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
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
1430
1431#ifdef USE_CG
1432
1433        // cg initialization
1434        cgSetErrorCallback(handleCgError);
1435        sCgContext = cgCreateContext();
1436
1437        if (cgGLIsProfileSupported(CG_PROFILE_ARBFP1))
1438                sCgFragmentProfile = CG_PROFILE_ARBFP1;
1439        else
1440        {
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        }
1450
1451        sCgFragmentProgram = cgCreateProgramFromFile(sCgContext,
1452                                                         CG_SOURCE, "../src/dual_depth.cg",
1453                                                                                                 sCgFragmentProfile,
1454                                                                                                 NULL,
1455                                                                                                 NULL);
1456
1457        if (!cgIsProgramCompiled(sCgFragmentProgram))
1458                cgCompileProgram(sCgFragmentProgram);
1459
1460        cgGLLoadProgram(sCgFragmentProgram);
1461        cgGLBindProgram(sCgFragmentProgram);
1462
1463        Debug << "---- PROGRAM BEGIN ----\n" <<
1464                cgGetProgramString(sCgFragmentProgram, CG_COMPILED_PROGRAM) << "---- PROGRAM END ----\n";
1465
1466#endif
1467#endif
1468        //DoneCurrent();
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
1480bool GlRendererBuffer::ValidViewPoint()
1481{       
1482        MakeCurrent();
1483
1484        SetupProjection(GetWidth(), GetHeight());
1485
1486        bool result = GlRenderer::ValidViewPoint();
1487       
1488        DoneCurrent();
1489       
1490        return result;
1491}
1492
1493
1494void
1495GlRenderer::EvalPvsStat()
1496{
1497  mPvsStat.Reset();
1498  halton.Reset();
1499
1500  SetupProjection(GetWidth(), GetHeight());
1501
1502  cout << "Random Pvs STATS, mPvsStatFrames=" << mPvsStatFrames << endl;
1503 
1504  for (int i=0; i < mPvsStatFrames; i++) {
1505        float err;
1506        // set frame id for saving the error buffer
1507        mFrame = i;
1508
1509        //      cerr<<"RV"<<endl;
1510        RandomViewPoint();
1511        //      cerr<<"RV2"<<endl;
1512
1513        if (mPvsErrorBuffer[i].mError == 1.0f) {
1514          // check if the view point is valid
1515          if (!ValidViewPoint()) {
1516                mPvsErrorBuffer[i].mError = -1.0f;
1517          }
1518
1519          // manualy corrected view point
1520          if (mFrame == 5105)
1521                mPvsErrorBuffer[i].mError = -1.0f;
1522        }
1523
1524
1525        if (mPvsErrorBuffer[i].mError > 0.0f) {
1526                int pvsSize;
1527
1528                float error = GetPixelError(pvsSize);
1529
1530
1531          //      emit UpdatePvsErrorItem(i,
1532          //                                                      mPvsErrorBuffer[i]);
1533          //      swapBuffers();
1534                mPvsErrorBuffer[i].mError = error;
1535                mPvsErrorBuffer[i].mPvsSize = pvsSize;
1536
1537                cout<<"("<<i<<" ["<<mViewPoint<<"]["<<mViewDirection<<"] "<<mPvsErrorBuffer[i].mError<<")";
1538        }
1539
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  }
1553 
1554  glFinish();
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
1587  cout<<endl<<flush;
1588}
1589
1590
1591void GlRenderer::EvalPvsStat(const SimpleRayContainer &viewPoints)
1592{
1593        mPvsStat.Reset();
1594
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)
1604        {
1605                //cout << "\n\nvp: " << (*sit) << endl;
1606                SimpleRay sray = *sit;
1607                int pvsSize = 0;
1608
1609                // set frame id for saving the error buffer
1610                mFrame = i;
1611                mViewPoint = sray.mOrigin;
1612                mViewDirection = sray.mDirection;
1613
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
1619                        const float error = GetPixelError(pvsSize);
1620
1621                        mPvsErrorBuffer[i].mError = error;
1622                        mPvsErrorBuffer[i].mPvsSize = pvsSize;
1623
1624                        const int pixelError = (int)mPvsErrorBuffer[i].mError * GetWidth() * GetHeight();
1625                        if (0 && (pixelError > 0) && (pvsSize > 0))
1626                        {
1627                                cout << "err: " << i << "," << mViewPoint << "," << mViewDirection << " "
1628                                         << mPvsErrorBuffer[i].mError * GetWidth() * GetHeight() << endl;
1629                        }
1630                }
1631
1632                const float err = mPvsErrorBuffer[i].mError;
1633
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               
1638                if (//(mFrame > 0) &&
1639                        (err >= 0.0f) && (err < (1.0f - 1e-6f)) && (pvsSize > 0))
1640                {
1641                        if (err > mPvsStat.maxError)
1642                        {
1643                                mPvsStat.maxError = err;
1644
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
1659        }
1660
1661        glFinish();
1662
1663
1664        cout << endl << flush;
1665}
1666
1667
1668
1669bool
1670GlRenderer::ValidViewPoint()
1671{
1672        //cout<<"VV4 ";
1673        if (!mDetectEmptyViewSpace)
1674                return true;
1675        //cout << "vp: " << mViewPoint << " dir: " << mViewDirection << endl;
1676
1677        OcclusionQuery *query = mOcclusionQueries[0];
1678
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);
1684
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
1705        //      int wait = 0;
1706        //      while (!query->ResultAvailable()) {
1707        //        wait++;
1708        //      }
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;
1720}
1721
1722
1723float GlRenderer::GetPixelError(int &pvsSize)
1724{
1725        return -1.0f;
1726}
1727
1728
1729void GlRenderer::RenderViewPoint()
1730{
1731        mWireFrame = true;
1732        glPushMatrix();
1733        glTranslatef(mViewPoint.x, mViewPoint.y, mViewPoint.z);
1734        glScalef(5.0f, 5.0f, 5.0f);
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;
1742}
1743
1744
1745void GlRenderer::EnableDrawArrays()
1746{
1747  glEnableClientState(GL_VERTEX_ARRAY);
1748  glEnableClientState(GL_NORMAL_ARRAY);
1749}
1750
1751
1752void GlRenderer::DisableDrawArrays()
1753{
1754        glDisableClientState(GL_VERTEX_ARRAY);
1755        glDisableClientState(GL_NORMAL_ARRAY);
1756}
1757
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
1771                if (!obj->Mailed2())
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
1786                if (obj->Mailed2())
1787                        continue;
1788
1789                obj->Mail2();
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);
1813}
1814
1815#else
1816
1817void GlRenderer::RenderKdLeaf(KdLeaf *leaf)
1818{
1819        if (!leaf->mIndexBufferSize)
1820                return;
1821
1822        size_t offset = mObjects.size() * 3;
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
1833
1834
1835void GlRenderer::PreparePvs(const ObjectPvs &pvs)
1836{
1837        int indexBufferSize = 0;
1838        mRenderedNodes = 0;
1839
1840        KdNode::NewMail2();
1841               
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{
1864        if (node->Mailed2())
1865                return;
1866
1867        node->Mail2();
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
1900                ++ mRenderedNodes;
1901
1902                leaf->mIndexBufferSize = indexBufferSize - leaf->mIndexBufferStart;
1903        }
1904}
1905
1906
1907void GlRenderer::CreateVertexArrays(SceneGraphLeaf *leaf)
1908{
1909    mData = new Vector3[leaf->mGeometry.size() * 6];
1910        mIndices = new unsigned int[leaf->mGeometry.size() * 3];
1911
1912        size_t offset = leaf->mGeometry.size() * 3;
1913
1914        for (size_t i = 0; i < leaf->mGeometry.size(); ++ i)
1915        {
1916                TriangleIntersectable *obj = static_cast<TriangleIntersectable *>(leaf->mGeometry[i]);
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
1940                glBufferDataARB(GL_ARRAY_BUFFER_ARB, leaf->mGeometry.size() * 6 * sizeof(Vector3), mData, GL_STATIC_DRAW_ARB);
1941                glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
1942
1943                DisableDrawArrays();
1944
1945                delete [] mData;
1946                mData = NULL;
1947        }
1948
1949        cout << "\n******** created vertex buffer objects **********" << endl; 
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.