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

Revision 2685, 46.8 KB checked in by mattausch, 16 years ago (diff)

fixed bugs: pixel measurement for pgv now working, fixed renderpvs crash

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