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

Revision 2695, 47.1 KB checked in by mattausch, 16 years ago (diff)

debug version: problematic view points for vienna detected

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