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

Revision 2721, 47.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 (0) {
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        //mSnapErrorFrames = false;
151        mSnapErrorFrames = true;
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#if !EVAL_ERROR
845                RenderKdLeaf(static_cast<KdLeaf *>(node));
846#else
847                KdLeaf *leaf = static_cast<KdLeaf *>(node);
848                for (int i=0; i < leaf->mObjects.size(); i++)
849                  {
850                        RenderIntersectable(leaf->mObjects[i]);
851                       
852                  }
853#endif
854        }
855        else
856        {
857                KdInterior *inter = static_cast<KdInterior *>(node);
858                RenderKdNode(inter->mBack);
859                RenderKdNode(inter->mFront);
860        }
861}
862
863
864void GlRendererBuffer::EvalRenderCostSample(RenderCostSample &sample,
865                                                                                        const bool useOcclusionQueries,
866                                                                                        const int threshold)
867{
868        // choose a random view point
869        mViewCellsManager->GetViewPoint(mViewPoint);
870        sample.mPosition = mViewPoint;
871        //cout << "viewpoint: " << mViewPoint << endl;
872
873        // take a render cost sample by rendering a cube
874        Vector3 directions[6];
875
876        directions[0] = Vector3(1,0,0);
877        directions[1] = Vector3(0,1,0);
878        directions[2] = Vector3(0,0,1);
879        directions[3] = Vector3(-1,0,0);
880        directions[4] = Vector3(0,-1,0);
881        directions[5] = Vector3(0,0,-1);
882
883        sample.mVisibleObjects = 0;
884
885        // reset object counters
886        ObjectContainer::const_iterator it, it_end = mObjects.end();
887
888        for (it = mObjects.begin(); it != it_end; ++ it)
889                (*it)->mCounter = 0;
890
891        ++ mFrame;
892
893        //glCullFace(GL_FRONT);
894        glCullFace(GL_BACK);
895        glDisable(GL_CULL_FACE);
896
897
898        // query all 6 directions for a full point sample
899        for (int i = 0; i < 6; ++ i)
900        {
901                mViewDirection = directions[i];
902                SetupCamera();
903
904                glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
905                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
906                //glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);      glDepthMask(GL_TRUE);
907                glDepthFunc(GL_LESS);
908
909                mUseFalseColors = true;
910
911                // the actual scene rendering fills the depth (for occlusion queries)
912                // and the frame buffer (for item buffer)
913                RenderScene();
914
915
916                if (0)
917                {
918                        char filename[256];
919                        sprintf_s(filename, "snap/frame-%04d-%d.png", mFrame, i);
920                        //                QImage im = toImage();
921                        //                im.save(filename, "PNG");
922                }
923
924                // evaluate the sample
925                if (useOcclusionQueries)
926                        EvalQueryWithOcclusionQueries();
927                else
928                        EvalQueryWithItemBuffer();
929        } 
930
931        // now evaluate the statistics over that sample
932        // currently only the number of visible objects is taken into account
933        sample.Reset();
934
935        for (it = mObjects.begin(); it != it_end; ++ it)
936        {
937                Intersectable *obj = *it;
938                if (obj->mCounter >= threshold)
939                {
940                        ++ sample.mVisibleObjects;
941                        sample.mVisiblePixels += obj->mCounter;
942                }
943        }
944
945        //cout << "RS=" << sample.mVisibleObjects << " ";
946}
947
948
949GlRendererBuffer::~GlRendererBuffer()
950{
951#if 0
952#ifdef USE_CG
953        if (sCgFragmentProgram)
954                cgDestroyProgram(sCgFragmentProgram);
955        if (sCgContext)
956                cgDestroyContext(sCgContext);
957#endif
958#endif
959
960}
961
962
963void
964GlRendererBuffer::SampleRenderCost(const int numSamples,
965                                                                   vector<RenderCostSample> &samples,
966                                                                   const bool useOcclusionQueries,
967                                                                   const int threshold
968                                                                   )
969{
970        MakeLive();
971
972        if (mPixelBuffer == NULL)
973                mPixelBuffer = new unsigned int[GetWidth()*GetHeight()];
974
975        // using 90 degree projection to capture 360 view with 6 samples
976        SetupProjection(GetHeight(), GetHeight(), 90.0f);
977
978        //samples.resize(numSamples);
979        halton.Reset();
980
981        // the number of queries queried in batch mode
982        const int numQ = 500;
983
984        //const int numQ = (int)mObjects.size();
985        if (useOcclusionQueries)
986        {
987                cout << "\ngenerating " << numQ << " queries ... ";
988                OcclusionQuery::GenQueries(mOcclusionQueries, numQ);
989                cout << "finished" << endl;
990        }
991
992        // sampling queries
993        for (int i = 0; i < numSamples; ++ i)
994        {
995                cout << ".";
996                EvalRenderCostSample(samples[i], useOcclusionQueries, threshold);
997        }
998
999        DoneLive();
1000}
1001
1002
1003
1004
1005
1006void
1007GlRenderer::ClearErrorBuffer()
1008{
1009  for (int i=0; i < mPvsStatFrames; i++) {
1010        mPvsErrorBuffer[i].mError = 1.0f;
1011  }
1012  mPvsStat.maxError = 0.0f;
1013}
1014
1015
1016void
1017GlRendererBuffer::EvalPvsStat()
1018{
1019        //MakeLive();
1020       
1021        GlRenderer::EvalPvsStat();
1022       
1023        //DoneLive();
1024        // mRenderingFinished.wakeAll();
1025}
1026
1027
1028void GlRendererBuffer::EvalPvsStat(const SimpleRayContainer &viewPoints)
1029{
1030        //MakeLive();
1031
1032        GlRenderer::EvalPvsStat(viewPoints);
1033 
1034        //DoneLive();
1035}
1036
1037
1038void GlRendererBuffer::SampleBeamContributions(Intersectable *sourceObject,
1039                                                                                           Beam &beam,
1040                                                                                           const int desiredSamples,
1041                                                                                           BeamSampleStatistics &stat)
1042{
1043        // TODO: should be moved out of here (not to be done every time)
1044        // only back faces are interesting for the depth pass
1045        glShadeModel(GL_FLAT);
1046        glDisable(GL_LIGHTING);
1047
1048        // needed to kill the fragments for the front buffer
1049        glEnable(GL_ALPHA_TEST);
1050        glAlphaFunc(GL_GREATER, 0);
1051
1052        // assumes that the beam is constructed and contains kd-tree nodes
1053        // and viewcells which it intersects
1054 
1055 
1056        // Get the number of viewpoints to be sampled
1057        // Now it is a sqrt but in general a wiser decision could be made.
1058        // The less viewpoints the better for rendering performance, since less passes
1059        // over the beam is needed.
1060        // The viewpoints could actually be generated outside of the bounding box which
1061        // would distribute the 'efective viewpoints' of the object surface and thus
1062        // with a few viewpoints better sample the viewpoint space....
1063
1064        //TODO: comment in
1065        //int viewPointSamples = sqrt((float)desiredSamples);
1066        int viewPointSamples = max(desiredSamples / (GetWidth() * GetHeight()), 1);
1067       
1068        // the number of direction samples per pass is given by the number of viewpoints
1069        int directionalSamples = desiredSamples / viewPointSamples;
1070       
1071        Debug << "directional samples: " << directionalSamples << endl;
1072        for (int i = 0; i < viewPointSamples; ++ i)
1073        {
1074                Vector3 viewPoint = beam.mBox.GetRandomPoint();
1075               
1076                // perhaps the viewpoint should be shifted back a little bit so that it always lies
1077                // inside the source object
1078                // 'ideally' the viewpoints would be distributed on the soureObject surface, but this
1079        // would require more complicated sampling (perhaps hierarchical rejection sampling of
1080                // the object surface is an option here - only the mesh faces which are inside the box
1081                // are considered as candidates)
1082               
1083                SampleViewpointContributions(sourceObject,
1084                                                                         viewPoint,
1085                                                                         beam,
1086                                                                         directionalSamples,
1087                                                                         stat);
1088        }
1089
1090
1091        // note:
1092        // this routine would be called only if the number of desired samples is sufficiently
1093        // large - for other rss tree cells the cpu based sampling is perhaps more efficient
1094        // distributing the work between cpu and gpu would also allow us to place more sophisticated
1095        // sample distributions (silhouette ones) using the cpu and the jittered once on the GPU
1096        // in order that thios scheme is working well the gpu render buffer should run in a separate
1097        // thread than the cpu sampler, which would not be such a big problem....
1098
1099        // disable alpha test again
1100        glDisable(GL_ALPHA_TEST);
1101}
1102
1103
1104
1105void GlRendererBuffer::SampleViewpointContributions(Intersectable *sourceObject,
1106                                                                                                        const Vector3 viewPoint,
1107                                                                                                        Beam &beam,
1108                                                                                                        const int samples,
1109                                                    BeamSampleStatistics &stat)
1110{
1111    // 1. setup the view port to match the desired samples
1112        glViewport(0, 0, samples, samples);
1113
1114        // 2. setup the projection matrix and view matrix to match the viewpoint + beam.mDirBox
1115        SetupProjectionForViewPoint(viewPoint, beam, sourceObject);
1116
1117
1118        // 3. reset z-buffer to 0 and render the source object for the beam
1119        //    with glCullFace(Enabled) and glFrontFace(GL_CW)
1120        //    save result to the front depth map
1121        //    the front depth map holds ray origins
1122
1123
1124        // front depth buffer must be initialised to 0
1125        float clearDepth;
1126       
1127        glGetFloatv(GL_DEPTH_CLEAR_VALUE, &clearDepth);
1128        glClearDepth(0.0f);
1129        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
1130
1131
1132        // glFrontFace(GL_CCW);
1133        glEnable(GL_CULL_FACE);
1134        glCullFace(GL_FRONT);
1135        glColorMask(0, 0, 0, 0);
1136       
1137
1138        // stencil is increased where the source object is located
1139        glEnable(GL_STENCIL_TEST);     
1140        glStencilFunc(GL_ALWAYS, 0x1, 0x1);
1141        glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
1142
1143
1144#if 0
1145        static int glSourceObjList = -1;         
1146        if (glSourceObjList != -1)
1147        {
1148                glSourceObjList = glGenLists(1);
1149                glNewList(glSourceObjList, GL_COMPILE);
1150
1151                RenderIntersectable(sourceObject);
1152       
1153                glEndList();
1154        }
1155        glCallList(glSourceObjList);
1156
1157#else
1158        RenderIntersectable(sourceObject);
1159
1160#endif 
1161
1162         // copy contents of the front depth buffer into depth texture
1163        glBindTexture(GL_TEXTURE_2D, frontDepthMap);   
1164        glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, depthMapSize, depthMapSize);
1165
1166        // reset clear function
1167        glClearDepth(clearDepth);
1168       
1169       
1170        // 4. set up the termination depth buffer (= standard depth buffer)
1171        //    only rays which have non-zero entry in the origin buffer are valid since
1172        //    they realy start on the object surface (this is tagged by setting a
1173        //    stencil buffer bit at step 3).
1174       
1175        glStencilFunc(GL_EQUAL, 0x1, 0x1);
1176        glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
1177
1178        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1179        glDepthMask(1);
1180
1181        glEnable(GL_DEPTH_TEST);
1182               
1183        glEnable(GL_CULL_FACE);
1184        glCullFace(GL_BACK);
1185
1186        // setup front depth buffer
1187        glEnable(GL_TEXTURE_2D);
1188       
1189#if 0
1190#ifdef USE_CG
1191        // bind pixel shader implementing the front depth buffer functionality
1192        cgGLBindProgram(sCgFragmentProgram);
1193        cgGLEnableProfile(sCgFragmentProfile);
1194#endif
1195#endif
1196        // 5. render all objects inside the beam
1197        //    we can use id based false color to read them back for gaining the pvs
1198
1199        glColorMask(1, 1, 1, 1);
1200
1201       
1202        // if objects not stored in beam => extract objects
1203        if (beam.mFlags & !Beam::STORE_OBJECTS)
1204        {
1205                vector<KdNode *>::const_iterator it, it_end = beam.mKdNodes.end();
1206
1207                Intersectable::NewMail();
1208                for (it = beam.mKdNodes.begin(); it != it_end; ++ it)
1209                {
1210                        mKdTree->CollectObjects(*it, beam.mObjects);
1211                }
1212        }
1213
1214
1215        //    (objects can be compiled to a gl list now so that subsequent rendering for
1216        //    this beam is fast - the same hold for step 3)
1217        //    Afterwards we have two depth buffers defining the ray origin and termination
1218       
1219
1220#if 0
1221        static int glObjList = -1;
1222        if (glObjList != -1)
1223        {
1224                glObjList = glGenLists(1);
1225                glNewList(glObjList, GL_COMPILE);
1226       
1227                ObjectContainer::const_iterator it, it_end = beam.mObjects.end();
1228                for (it = beam.mObjects.begin(); it != it_end; ++ it)
1229                {
1230                        // render all objects except the source object
1231                        if (*it != sourceObject)
1232                                RenderIntersectable(*it);
1233                }
1234               
1235                glEndList();
1236        }
1237
1238        glCallList(glObjList);
1239#else
1240        ObjectContainer::const_iterator it, it_end = beam.mObjects.end();
1241        for (it = beam.mObjects.begin(); it != it_end; ++ it)
1242        {       
1243                // render all objects except the source object
1244                if (*it != sourceObject)
1245                        RenderIntersectable(*it);
1246        }
1247#endif
1248       
1249        // 6. Use occlusion queries for all viewcell meshes associated with the beam ->
1250        //     a fragment passes if the corresponding stencil fragment is set and its depth is
1251        //     between origin and termination buffer
1252
1253        // create new queries if necessary
1254        OcclusionQuery::GenQueries(mOcclusionQueries, (int)beam.mViewCells.size());
1255
1256        // check whether any backfacing polygon would pass the depth test?
1257        // matt: should check both back /front facing because of dual depth buffer
1258        // and danger of cutting the near plane with front facing polys.
1259       
1260        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1261        glDepthMask(GL_FALSE);
1262        glDisable(GL_CULL_FACE);
1263
1264 
1265        ViewCellContainer::const_iterator vit, vit_end = beam.mViewCells.end();
1266
1267        int queryIdx = 0;
1268
1269        for (vit = beam.mViewCells.begin(); vit != vit_end; ++ vit)
1270        {
1271                mOcclusionQueries[queryIdx ++]->BeginQuery();
1272                RenderIntersectable(*vit);
1273                mOcclusionQueries[queryIdx]->EndQuery();
1274
1275                ++ queryIdx;
1276        }
1277
1278        // at this point, if possible, go and do some other computation
1279
1280        // 7. The number of visible pixels is the number of sample rays which see the source
1281        //    object from the corresponding viewcell -> remember these values for later update
1282        //   of the viewcell pvs - or update immediately?
1283
1284        queryIdx = 0;
1285
1286        for (vit = beam.mViewCells.begin(); vit != vit_end; ++ vit)
1287        {
1288                // fetch queries
1289                unsigned int pixelCount = mOcclusionQueries[queryIdx ++]->GetQueryResult();
1290
1291                if (pixelCount)
1292                        Debug << "view cell " << (*vit)->GetId() << " visible pixels: " << pixelCount << endl;
1293        }
1294       
1295
1296        // 8. Copmpute rendering statistics
1297        // In general it is not neccessary to remember to extract all the rays cast. I hope it
1298        // would be sufficient to gain only the intergral statistics about the new contributions
1299        // and so the rss tree would actually store no new rays (only the initial ones)
1300        // the subdivision of the tree would only be driven by the statistics (the glrender could
1301        // evaluate the contribution entropy for example)
1302        // However might be an option to extract/store only those the rays which made a contribution
1303        // (new viewcell has been discovered) or relative contribution greater than a threshold ...
1304
1305        ObjectContainer pvsObj;
1306        stat.pvsSize = ComputePvs(beam.mObjects, pvsObj);
1307       
1308        // to gain ray source and termination
1309        // copy contents of ray termination buffer into depth texture
1310        // and compare with ray source buffer
1311#if 0
1312        VssRayContainer rays;
1313
1314        glBindTexture(GL_TEXTURE_2D, backDepthMap);     
1315        glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, depthMapSize, depthMapSize);
1316
1317        ComputeRays(Intersectable *sourceObj, rays);
1318
1319#endif
1320
1321        ////////
1322        //-- cleanup
1323
1324        // reset gl state
1325        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1326        glDepthMask(GL_TRUE);
1327        glEnable(GL_CULL_FACE);
1328        glDisable(GL_STENCIL_TEST);
1329
1330#if 0
1331#ifdef USE_CG
1332        cgGLDisableProfile(sCgFragmentProfile);
1333#endif
1334#endif
1335
1336        glDisable(GL_TEXTURE_2D);
1337
1338        // remove objects from beam
1339        if (beam.mFlags & !Beam::STORE_OBJECTS)
1340                beam.mObjects.clear();
1341}
1342
1343
1344void GlRendererBuffer::SetupProjectionForViewPoint(const Vector3 &viewPoint,
1345                                                                                                   const Beam &beam,
1346                                                                                                   Intersectable *sourceObject)
1347{
1348        float left, right, bottom, top, znear, zfar;
1349
1350        beam.ComputePerspectiveFrustum(left, right, bottom, top, znear, zfar,
1351                                                                   mSceneGraph->GetBox());
1352
1353        //Debug << left << " " << right << " " << bottom << " " << top << " " << znear << " " << zfar << endl;
1354        glMatrixMode(GL_PROJECTION);
1355        glLoadIdentity();
1356        glFrustum(left, right, bottom, top, znear, zfar);
1357        //glFrustum(-1, 1, -1, 1, 1, 20000);
1358
1359    const Vector3 center = viewPoint + beam.GetMainDirection() * (zfar - znear) * 0.3f;
1360        const Vector3 up =
1361                Normalize(CrossProd(beam.mPlanes[0].mNormal, beam.mPlanes[4].mNormal));
1362
1363#ifdef GTP_DEBUG
1364        Debug << "view point: " << viewPoint << endl;
1365        Debug << "eye: " << center << endl;
1366        Debug << "up: " << up << endl;
1367#endif
1368
1369        glMatrixMode(GL_MODELVIEW);
1370        glLoadIdentity();
1371        gluLookAt(viewPoint.x, viewPoint.y, viewPoint.z,
1372                          center.x, center.y, center.z,                   
1373                          up.x, up.y, up.z);
1374}               
1375
1376 
1377void GlRendererBuffer::InitGL()
1378{
1379        //MakeCurrent();
1380        GlRenderer::InitGL();
1381
1382#if 0
1383        // initialise dual depth buffer textures
1384        glGenTextures(1, &frontDepthMap);
1385        glBindTexture(GL_TEXTURE_2D, frontDepthMap);
1386
1387        glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, depthMapSize,
1388                depthMapSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
1389
1390        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1391        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1392        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
1393        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
1394
1395        glGenTextures(1, &backDepthMap);
1396        glBindTexture(GL_TEXTURE_2D, backDepthMap);
1397
1398        glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, depthMapSize,
1399                                 depthMapSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
1400        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1401        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1402        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
1403        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
1404
1405
1406#ifdef USE_CG
1407
1408        // cg initialization
1409        cgSetErrorCallback(handleCgError);
1410        sCgContext = cgCreateContext();
1411
1412        if (cgGLIsProfileSupported(CG_PROFILE_ARBFP1))
1413                sCgFragmentProfile = CG_PROFILE_ARBFP1;
1414        else
1415        {
1416                // try FP30
1417                if (cgGLIsProfileSupported(CG_PROFILE_FP30))
1418                        sCgFragmentProfile = CG_PROFILE_FP30;
1419                else
1420                {
1421                        Debug << "Neither arbfp1 or fp30 fragment profiles supported on this system" << endl;
1422                        exit(1);
1423                }
1424        }
1425
1426        sCgFragmentProgram = cgCreateProgramFromFile(sCgContext,
1427                                                         CG_SOURCE, "../src/dual_depth.cg",
1428                                                                                                 sCgFragmentProfile,
1429                                                                                                 NULL,
1430                                                                                                 NULL);
1431
1432        if (!cgIsProgramCompiled(sCgFragmentProgram))
1433                cgCompileProgram(sCgFragmentProgram);
1434
1435        cgGLLoadProgram(sCgFragmentProgram);
1436        cgGLBindProgram(sCgFragmentProgram);
1437
1438        Debug << "---- PROGRAM BEGIN ----\n" <<
1439                cgGetProgramString(sCgFragmentProgram, CG_COMPILED_PROGRAM) << "---- PROGRAM END ----\n";
1440
1441#endif
1442#endif
1443        //DoneCurrent();
1444}
1445
1446
1447void GlRendererBuffer::ComputeRays(Intersectable *sourceObj, VssRayContainer &rays)
1448{
1449        for (int i = 0; i < depthMapSize * depthMapSize; ++ i)
1450        {
1451                // TODO (use glGetTexImage())
1452        }
1453}
1454
1455
1456bool GlRendererBuffer::ValidViewPoint()
1457{       
1458        MakeLive();
1459
1460        SetupProjection(GetWidth(), GetHeight());
1461
1462        bool result = GlRenderer::ValidViewPoint();
1463       
1464        DoneLive();
1465       
1466        return result;
1467}
1468
1469
1470void
1471GlRenderer::EvalPvsStat()
1472{
1473        mPvsStat.Reset();
1474        halton.Reset();
1475
1476        SetupProjection(GetWidth(), GetHeight());
1477
1478        cout << "Random Pvs STATS, mPvsStatFrames=" << mPvsStatFrames << endl;
1479
1480        for (int i=0; i < mPvsStatFrames; i++) {
1481                float err;
1482                // set frame id for saving the error buffer
1483                mFrame = i;
1484
1485                //      cerr<<"RV"<<endl;
1486                RandomViewPoint();
1487                //      cerr<<"RV2"<<endl;
1488
1489                if (mPvsErrorBuffer[i].mError == 1.0f) {
1490                        // check if the view point is valid
1491                        if (!ValidViewPoint()) {
1492                                mPvsErrorBuffer[i].mError = -1.0f;
1493                        }
1494
1495                        // manualy corrected view point
1496                        if (mFrame == 5105)
1497                                mPvsErrorBuffer[i].mError = -1.0f;
1498                }
1499
1500
1501                if (mPvsErrorBuffer[i].mError > 0.0f)
1502                {
1503                        int pvsSize;
1504
1505                        mPvsErrorBuffer[i].mError = GetPixelError(pvsSize, 0);
1506                        mPvsErrorBuffer[i].mPvsSize = pvsSize;
1507
1508                        //cout<<"("<<i<<" ["<<mViewPoint<<"]["<<mViewDirection<<"] "<<mPvsErrorBuffer[i].mError<<")";
1509                }
1510
1511                err = mPvsErrorBuffer[i].mError;
1512
1513                if (err >= 0.0f) {
1514                        if (err > mPvsStat.maxError)
1515                                mPvsStat.maxError = err;
1516                        mPvsStat.sumError += err;
1517                        mPvsStat.sumPvsSize += mPvsErrorBuffer[i].mPvsSize;
1518
1519                        if (err == 0.0f)
1520                                mPvsStat.errorFreeFrames++;
1521                        mPvsStat.frames++;
1522                }
1523        }
1524
1525        glFinish();
1526
1527        static bool first = true;
1528
1529        if (first) {
1530
1531                bool exportRandomViewCells;
1532                Environment::GetSingleton()->GetBoolValue("ViewCells.exportRandomViewCells",
1533                        exportRandomViewCells);
1534
1535                if (0 && exportRandomViewCells)
1536                {
1537                        char buff[512];
1538                        Environment::GetSingleton()->GetStringValue("Scene.filename", buff);
1539                        string filename(buff);
1540
1541                        string viewCellPointsFile;
1542
1543                        if (strstr(filename.c_str(), ".obj"))
1544                                viewCellPointsFile = ReplaceSuffix(filename, ".obj", ".vc");
1545                        else if (strstr(filename.c_str(), ".dat"))
1546                                viewCellPointsFile = ReplaceSuffix(filename, ".dat", ".vc");
1547                        else if (strstr(filename.c_str(), ".x3d"))
1548                                viewCellPointsFile = ReplaceSuffix(filename, ".x3d", ".vc");
1549
1550
1551                        cout << "exporting random view cells" << endl;
1552                        preprocessor->mViewCellsManager->ExportRandomViewCells(viewCellPointsFile);
1553                        cout << "finished" << endl;
1554                }
1555                first = false;
1556        }
1557
1558        cout<<endl<<flush;
1559}
1560
1561
1562void GlRenderer::EvalPvsStat(const SimpleRayContainer &viewPoints)
1563{
1564        mPvsStat.Reset();
1565        ++ mPvsStat.pass;
1566
1567        SetupProjection(GetWidth(), GetHeight());
1568
1569        cout << "mPvsStatFrames=" << viewPoints.size() << endl;
1570
1571        SimpleRayContainer::const_iterator sit, sit_end = viewPoints.end();
1572
1573        int i = 0;
1574
1575        for (sit = viewPoints.begin(); sit != sit_end; ++ sit, ++ i)
1576        {
1577                SimpleRay sray = *sit;
1578               
1579                int pvsSize = -1;
1580
1581                // set frame id for saving the error buffer
1582                mFrame = i;
1583                mViewPoint = sray.mOrigin;
1584                mViewDirection = sray.mDirection;
1585
1586                // skip all frames which have already 0 pixel error
1587                // $$ Reverted back by JB for efficiency
1588                if (mPvsErrorBuffer[i].mError > 0.0f)
1589                {
1590                        // compute the pixel error
1591                        mPvsErrorBuffer[i].mError = GetPixelError(pvsSize, mPvsStat.pass);
1592                        mPvsErrorBuffer[i].mPvsSize = pvsSize;
1593
1594                        if (0 && (mPvsErrorBuffer[i].mError * GetWidth() * GetHeight() > 0) && (pvsSize > 0))
1595                        {
1596                                cout << "error in frame " << i << "," << mViewPoint << "," << mViewDirection << " "
1597                                         << mPvsErrorBuffer[i].mError * GetWidth() * GetHeight() << endl;
1598                        }
1599                }
1600
1601                const float err = mPvsErrorBuffer[i].mError;
1602
1603                // hack:
1604                // do not account for the case that no PVS is rendered - hack for 08 rebuttal GVS evaluation
1605                // drop the first frame (for some reason, the first frame yields wrong pixel error)
1606               
1607                if (pvsSize != 0)
1608                {
1609                        // hack: test if error is suspiciously large
1610                        if ((err >=  -1e-6f) && (err < (1.0f - 1e-6f)))
1611                        {
1612                                if (err > mPvsStat.maxError)
1613                                {
1614                                        mPvsStat.maxError = err;
1615                                        cout << "new max error: " << mPvsStat.maxError * GetWidth() * GetHeight()  << endl;
1616                                }
1617
1618                                mPvsStat.sumError += err;
1619                                mPvsStat.sumPvsSize += mPvsErrorBuffer[i].mPvsSize;
1620
1621                                if (err == 0.0f)
1622                                        ++ mPvsStat.errorFreeFrames;
1623
1624                                // $$ JB
1625                                // moved it back here not to count frames with negative err (backfacing triangle)
1626                                ++ mPvsStat.frames;
1627
1628                                if ((mPvsStat.frames % 100) == 0)
1629                                        cout << "processed " << mPvsStat.frames << " valid view points " << endl;
1630                        }
1631                        else
1632                        {
1633                                cerr << "warning: strange error (" << err << "), pvs size " << pvsSize << endl;
1634                        }
1635                }
1636        }
1637
1638        glFinish();
1639
1640
1641        cout << endl << flush;
1642}
1643
1644
1645
1646bool
1647GlRenderer::ValidViewPoint()
1648{
1649        //cout<<"VV4 ";
1650        if (!mDetectEmptyViewSpace)
1651                return true;
1652        //cout << "vp: " << mViewPoint << " dir: " << mViewDirection << endl;
1653
1654        OcclusionQuery *query = mOcclusionQueries[0];
1655
1656        // now check whether any backfacing polygon would pass the depth test
1657        SetupCamera();
1658        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1659        glEnable( GL_CULL_FACE );
1660        glCullFace(GL_BACK);
1661
1662        //cout<<"VV1 ";
1663        RenderScene();
1664
1665        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1666        glDepthMask(GL_FALSE);
1667        glDisable( GL_CULL_FACE );
1668
1669        query->BeginQuery();
1670
1671        //  cout<<"VV2 ";
1672        RenderScene();
1673        //  cout<<"VV3 ";
1674
1675        query->EndQuery();
1676
1677        // at this point, if possible, go and do some other computation
1678        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1679        glDepthMask(GL_TRUE);
1680        glEnable( GL_CULL_FACE );
1681
1682        //      int wait = 0;
1683        //      while (!query->ResultAvailable()) {
1684        //        wait++;
1685        //      }
1686
1687        // reenable other state
1688        unsigned int pixelCount = query->GetQueryResult();
1689        //  cout<<"VV4 ";
1690
1691
1692        // backfacing polygon found -> not a valid viewspace sample
1693        if (pixelCount > 0)
1694                return false;
1695       
1696        return true;
1697}
1698
1699
1700float GlRenderer::GetPixelError(int &pvsSize, int pass)
1701{
1702        return -1.0f;
1703}
1704
1705
1706void GlRenderer::RenderViewPoint()
1707{
1708        mWireFrame = true;
1709        glPushMatrix();
1710        glTranslatef(mViewPoint.x, mViewPoint.y, mViewPoint.z);
1711        glScalef(5.0f, 5.0f, 5.0f);
1712        glPushAttrib(GL_CURRENT_BIT);
1713        glColor3f(1.0f, 0.0f, 0.0f);
1714        gluSphere((::GLUquadric *)mSphere,
1715                1e-3*Magnitude(mViewCellsManager->GetViewSpaceBox().Size()), 6, 6);
1716        glPopAttrib();
1717        glPopMatrix();
1718        mWireFrame = false;
1719}
1720
1721
1722void GlRenderer::EnableDrawArrays()
1723{
1724  glEnableClientState(GL_VERTEX_ARRAY);
1725  glEnableClientState(GL_NORMAL_ARRAY);
1726}
1727
1728
1729void GlRenderer::DisableDrawArrays()
1730{
1731        glDisableClientState(GL_VERTEX_ARRAY);
1732        glDisableClientState(GL_NORMAL_ARRAY);
1733}
1734
1735
1736#if 0
1737
1738void GlRenderer::RenderKdLeaf(KdLeaf *leaf)
1739{
1740        int bufferSize = 0;
1741
1742        // count #new triangles
1743        for (size_t i = 0; i < leaf->mObjects.size(); ++ i)
1744        {
1745                TriangleIntersectable *obj = static_cast<TriangleIntersectable *>(leaf->mObjects[i]);
1746
1747                // check if already rendered
1748                if (!obj->Mailed2())
1749                        bufferSize += 3;
1750                //else cout << obj->mMailbox << " " << obj->sMailId << " ";
1751        }
1752
1753        Vector3 *vertices = new Vector3[bufferSize];
1754        Vector3 *normals = new Vector3[bufferSize];
1755
1756        int j = 0;
1757
1758        for (size_t i = 0; i < leaf->mObjects.size(); ++ i)
1759        {
1760                TriangleIntersectable *obj = static_cast<TriangleIntersectable *>(leaf->mObjects[i]);
1761
1762                // check if already rendered
1763                if (obj->Mailed2())
1764                        continue;
1765
1766                obj->Mail2();
1767
1768                Triangle3 tri = obj->GetItem();
1769
1770                vertices[j * 3 + 0] = tri.mVertices[0];
1771                vertices[j * 3 + 1] = tri.mVertices[1];
1772                vertices[j * 3 + 2] = tri.mVertices[2];
1773
1774                Vector3 n = tri.GetNormal();
1775
1776                normals[j * 3 + 0] = n;
1777                normals[j * 3 + 1] = n;
1778                normals[j * 3 + 2] = n;
1779
1780                ++ j;
1781        }
1782
1783        glVertexPointer(3, GL_FLOAT, 0, vertices);
1784        glNormalPointer(GL_FLOAT, 0, normals);
1785
1786        glDrawArrays(GL_TRIANGLES, 0, bufferSize);
1787
1788        DEL_PTR(vertices);
1789        DEL_PTR(normals);
1790}
1791
1792#else
1793
1794void GlRenderer::RenderKdLeaf(KdLeaf *leaf)
1795{
1796        if (!leaf->mIndexBufferSize)
1797                return;
1798
1799        size_t offset = mObjects.size() * 3;
1800        char *arrayPtr = mUseVbos ? NULL : (char *)mData;
1801       
1802        glVertexPointer(3, GL_FLOAT, 0, (char *)arrayPtr);
1803        glNormalPointer(GL_FLOAT, 0, (char *)arrayPtr + offset * sizeof(Vector3));
1804       
1805        glDrawElements(GL_TRIANGLES, leaf->mIndexBufferSize, GL_UNSIGNED_INT, mIndices + leaf->mIndexBufferStart);
1806}
1807
1808#endif
1809
1810
1811
1812void GlRenderer::PreparePvs(const ObjectPvs &pvs)
1813{
1814        int indexBufferSize = 0;
1815        mRenderedNodes = 0;
1816
1817        KdNode::NewMail2();
1818               
1819        ObjectPvsIterator it = pvs.GetIterator();
1820
1821        while (it.HasMoreEntries())
1822        {
1823                Intersectable *obj = it.Next();
1824                switch (obj->Type())
1825                {
1826                case Intersectable::KD_INTERSECTABLE:
1827                        {
1828                                KdNode *node = static_cast<KdIntersectable *>(obj)->GetItem();
1829                                _UpdatePvsIndices(node, indexBufferSize);
1830                        }
1831                        break;
1832                       
1833                }
1834        }
1835
1836        mIndexBufferSize = indexBufferSize;
1837}
1838
1839
1840void GlRenderer::_UpdatePvsIndices(KdNode *node, int &indexBufferSize)
1841{
1842        if (node->Mailed2())
1843                return;
1844
1845        node->Mail2();
1846
1847        // if (mObjects.size() * 3 < indexBufferSize) cerr << "problem: " << mObjects.size() * 3 << " < " << indexBufferSize << endl;
1848        if (!node->IsLeaf())
1849        {
1850                KdInterior *kdInterior = static_cast<KdInterior *>(node);
1851
1852                _UpdatePvsIndices(kdInterior->mBack, indexBufferSize);
1853                _UpdatePvsIndices(kdInterior->mFront, indexBufferSize);
1854        }
1855        else
1856        {
1857                KdLeaf *leaf = static_cast<KdLeaf *>(node);
1858
1859                leaf->mIndexBufferStart = indexBufferSize;
1860
1861                for (size_t i = 0; i < leaf->mObjects.size(); ++ i)
1862                {
1863                        TriangleIntersectable *obj =
1864                                static_cast<TriangleIntersectable *>(leaf->mObjects[i]);
1865
1866                        if (obj->mRenderedFrame != mCurrentFrame)
1867                        {
1868                                obj->mRenderedFrame = mCurrentFrame;
1869                               
1870                                const int id = obj->GetId() * 3;
1871
1872                                mIndices[indexBufferSize + 0] = id + 0;
1873                                mIndices[indexBufferSize + 1] = id + 1;
1874                                mIndices[indexBufferSize + 2] = id + 2;
1875
1876                                indexBufferSize += 3;
1877                        }
1878                }
1879
1880                ++ mRenderedNodes;
1881
1882                leaf->mIndexBufferSize = indexBufferSize - leaf->mIndexBufferStart;
1883        }
1884}
1885
1886
1887void GlRenderer::CreateVertexArrays(SceneGraphLeaf *leaf)
1888{
1889        size_t offset = leaf->mGeometry.size() * 3;
1890
1891    mData = new Vector3[offset * 2];
1892        mIndices = new unsigned int[offset];
1893
1894
1895        for (size_t i = 0; i < leaf->mGeometry.size(); ++ i)
1896        {
1897                TriangleIntersectable *obj = static_cast<TriangleIntersectable *>(leaf->mGeometry[i]);
1898
1899                Triangle3 tri = obj->GetItem();
1900                const Vector3 n = tri.GetNormal();
1901
1902                mData[i * 3 + 0] = tri.mVertices[0];
1903                mData[i * 3 + 1] = tri.mVertices[1];
1904                mData[i * 3 + 2] = tri.mVertices[2];
1905
1906                mData[offset + i * 3 + 0] = n;
1907                mData[offset + i * 3 + 1] = n;
1908                mData[offset + i * 3 + 2] = n;
1909
1910                mIndices[i * 3 + 0] = 0;
1911                mIndices[i * 3 + 1] = 0;
1912                mIndices[i * 3 + 2] = 0;
1913        }
1914
1915        cout << "\n******** created vertex arrays **********" << endl; 
1916
1917        if (mUseVbos)
1918        {
1919                EnableDrawArrays();
1920
1921                glGenBuffersARB(1, &mVboId);
1922                glBindBufferARB(GL_ARRAY_BUFFER_ARB, mVboId);
1923
1924                glVertexPointer(3, GL_FLOAT, 0, (char *)NULL);
1925                glNormalPointer(GL_FLOAT, 0, (char *)NULL + offset * sizeof(Vector3));
1926
1927                glBufferDataARB(GL_ARRAY_BUFFER_ARB, offset * 2 * sizeof(Vector3), mData, GL_STATIC_DRAW_ARB);
1928                glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
1929
1930                DisableDrawArrays();
1931
1932                delete [] mData;
1933                mData = NULL;
1934
1935                cout << "\n******** created vertex buffer objects **********" << endl; 
1936        }
1937}
1938
1939
1940void GlRenderer::DeleteVbos()
1941{
1942        glDeleteBuffersARB(1, &mVboId);
1943}
1944
1945
1946
1947}
Note: See TracBrowser for help on using the repository browser.