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

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