source: GTP/trunk/Lib/Vis/Preprocessing/src/QtInterface/QtGlRenderer.cpp @ 2720

Revision 2720, 71.2 KB checked in by mattausch, 16 years ago (diff)

dynamic objects problem!!

Line 
1#include "glInterface.h"
2#include "QtGlRenderer.h"
3#include "Mesh.h"
4#include "OcclusionQuery.h"
5#include "ViewCellsManager.h"
6#include "SceneGraph.h"
7#include "Pvs.h"
8#include "Viewcell.h"
9#include "Beam.h"
10#include "KdTree.h"
11#include "Environment.h"
12#include "RssPreprocessor.h"
13#include "RssTree.h"
14#include "Trackball.h"
15#include "QtPreprocessorThread.h"
16#include "Material.h"
17#include "IntersectableWrapper.h"
18#include "LogWriter.h"
19#include "RayCaster.h"
20#include "ObjectPlacer.h"
21
22#define TEASER 1
23
24#define USE_CG 1
25
26#define TEST_PVS_RENDERING 0
27
28#if USE_CG
29#include <Cg/cg.h>
30#include <Cg/cgGL.h>
31#endif
32
33#include <QVBoxLayout>
34
35
36using namespace std;
37
38
39namespace GtpVisibilityPreprocessor
40{
41
42 
43class ViewCellsManager;
44
45static CGcontext sCgContext = NULL;
46static CGprogram sCgFragmentProgram = NULL;
47static CGprofile sCgFragmentProfile;
48
49
50QtGlRendererWidget *rendererWidget = NULL;
51QtGlDebuggerWidget *debuggerWidget = NULL;
52
53
54
55static SimpleRayContainer sViewPointsList;
56static SimpleRayContainer::const_iterator sViewPointsListIt;
57static int sCurrentSamples = 0;
58static int sNextSamplesThreshold[] = {10000000, 50000000, 100000000, 250000000};
59//static int sNextSamplesThreshold[] = {100000000, 200000000};
60static int sNumReplays = 4;
61static int sCurrentSamplesThreshold = 0;
62
63
64void processHits (GLint hits, GLuint buffer[])
65{
66   unsigned int i, j;
67   GLuint names, *ptr;
68
69   cout << "hits: " << hits << endl;;
70   ptr = (GLuint *) buffer;
71
72   for (i = 0; i < hits; i++)
73   {
74           /*  for each hit  */
75           names = *ptr;
76
77           printf ("number of names for hit: %d\n", names); ptr ++;
78           printf("z1: %g;", (float) *ptr / 0x7fffffff); ptr ++;
79           printf("z2: %g\n", (float) *ptr / 0x7fffffff); ptr ++;
80           printf ("the name is ");
81
82           // for each name
83           for (j = 0; j < names; j++)
84                   printf ("%d ", *ptr); ptr++;
85
86           printf ("\n");
87   }
88}
89
90
91static inline bool ilt(Intersectable *obj1, Intersectable *obj2)
92{
93        return obj1->mId < obj2->mId;
94}
95
96
97inline static bool nearerThan(ViewCell *vc1, ViewCell *vc2)
98{
99        return vc1->GetDistance() > vc2->GetDistance();
100}
101
102
103#if USE_CG
104static void handleCgError()
105{
106    Debug << "Cg error: " << cgGetErrorString(cgGetError()) << endl;
107    exit(1);
108}
109#endif
110
111
112void QtGlRendererBuffer::MakeLive()
113{
114        QGLPixelBuffer::makeCurrent();
115        //makeCurrent();
116}
117
118
119void QtGlRendererBuffer::DoneLive()
120{
121        QGLPixelBuffer::doneCurrent();
122        //doneCurrent();
123}
124 
125
126QtGlRendererBuffer::QtGlRendererBuffer(int w, int h,
127                                                                           SceneGraph *sceneGraph,
128                                                                           ViewCellsManager *viewcells,
129                                                                           KdTree *tree):
130QGLPixelBuffer(QSize(w, h),
131                           QGLFormat(QGL::SampleBuffers)
132                           /*,|
133                                                 QGL::StencilBuffer |
134                                                 QGL::DepthBuffer |
135                                                 QGL::DoubleBuffer |
136                                                 QGL::Rgba)
137                                                 */),
138GlRendererBuffer(sceneGraph, viewcells, tree)
139{
140        //makeCurrent();
141        MakeLive();
142        glViewport(0, 0, w, h);
143    glMatrixMode(GL_PROJECTION);
144    glLoadIdentity();
145    glOrtho(-1, 1, -1, 1, -99, 99);
146    glMatrixMode(GL_MODELVIEW);
147    glLoadIdentity();
148
149        InitGL();
150
151        //doneCurrent();
152        //DoneLive();
153}
154
155
156void QtGlRendererBuffer::RenderPvs(const ObjectPvs &pvs)
157{
158        EnableDrawArrays();
159       
160        // prepare pvs for rendering
161        PreparePvs(pvs);
162
163        if (mUseVbos)
164                glBindBufferARB(GL_ARRAY_BUFFER_ARB, mVboId);
165
166        int offset = (int)mObjects.size() * 3;
167        char *arrayPtr = mUseVbos ? NULL : (char *)mData;
168
169        glVertexPointer(3, GL_FLOAT, 0, (char *)arrayPtr);
170        glNormalPointer(GL_FLOAT, 0, (char *)arrayPtr + offset * sizeof(Vector3));
171        glDrawElements(GL_TRIANGLES, mIndexBufferSize, GL_UNSIGNED_INT, mIndices);
172}
173
174
175void QtGlRendererBuffer::RenderTrianglePvs()
176{
177        ObjectContainer::const_iterator oit, oit_end =
178                mViewCellsManager->GetPreprocessor()->mTrianglePvs.end();
179
180        //int sz = mViewCellsManager->GetPreprocessor()->mDummyBuffer.size();
181
182        int i = 0;
183        for (oit = mViewCellsManager->GetPreprocessor()->mTrianglePvs.begin();
184                 oit != oit_end; ++ oit, ++ i)
185        {
186                //int dum = mViewCellsManager->GetPreprocessor()->mDummyBuffer[i];
187                //glColor3f(0, (float)dum / 20.0f, 1);
188                if (mUseFalseColors) SetupFalseColor((*oit)->mId);
189
190                RenderIntersectable(*oit);
191        }
192}
193
194
195
196// reimplemented here so that we can snap the error windows
197float QtGlRendererBuffer::GetPixelError(int &pvsSize, int pass)
198{
199        MakeLive();
200
201        if (0)
202        {
203                cout << "stencil: " << format().stencil() << endl;
204                cout << "depth: " << format().depth() << endl;
205                cout << "rgba: " << format().rgba() << endl;
206                cout << "double: " << format().doubleBuffer() << endl;
207                cout << "depth: " << format().depth() << endl;
208                cout << "gl:" << format().hasOpenGL() << endl;
209                cout << "dir:" << format().directRendering() << endl;
210        }
211
212        ++ mCurrentFrame;
213
214        float pErrorPixels = -1.0f;
215
216        mUseFalseColors = false;
217        unsigned int pixelCount = 0;
218
219       
220        ViewCell *viewcell = mViewCellsManager->GetViewCell(mViewPoint);
221
222        if (viewcell == NULL)
223                return -1.0f;
224
225        bool evaluateFilter;
226        Environment::GetSingleton()->GetBoolValue("Preprocessor.evaluateFilter", evaluateFilter);
227
228        ObjectPvs pvs;
229
230        if (!evaluateFilter)
231                pvs = viewcell->GetPvs();
232        else
233                mViewCellsManager->ApplyFilter2(viewcell, false, mViewCellsManager->GetFilterWidth(), pvs);
234
235        pvsSize = pvs.GetSize();
236       
237        // hack: assume that view cell empty
238        if (pvsSize == 0)
239                return 0.0f;
240
241        SetupCamera();
242
243        // use shading
244        if (mSnapErrorFrames)
245        {
246                glEnable(GL_NORMALIZE);
247
248                // mat_specular and mat_shininess are NOT default values
249                GLfloat mat_ambient[] = {0.2f, 0.2f, 0.2f, 1.0f};
250                GLfloat mat_diffuse[] = {1.0f, 1.0f, 1.0f, 1.0f};
251                GLfloat mat_specular[] = {0.3f, 0.3f, 0.3f, 1.0f};
252                GLfloat mat_shininess[] = {1.0f};
253
254                glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
255                glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
256                glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
257                glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
258
259                GLfloat light_ambient[] = {0.1, 0.1, 0.1, 1.0};
260                //GLfloat light_diffuse[] = {0.6, 0.6, 0.6, 1.0};
261                GLfloat light_diffuse[] = {0.5, 0.5, 0.5, 1.0};
262                GLfloat light_specular[] = {1.0, 1.0, 1.0, 1.0};
263
264                glEnable(GL_LIGHTING);
265                GLfloat light_position[] =  {0.f, 0.f, 0.f, 1.0f};
266
267                // lights in arena
268               
269                glEnable(GL_LIGHT0);
270
271                // a light
272                glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
273                glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
274                glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
275
276               
277               
278               
279                glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
280                glEnable(GL_COLOR_MATERIAL);
281
282                GLfloat lmodel_ambient[] = {0.1f, 0.1f, 0.1f, 1.0f};
283                glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
284
285                glShadeModel(GL_SMOOTH);
286        }
287
288        //glDisable(GL_ALPHA_TEST);
289               
290        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
291        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
292
293        //glColor3f(0.6f, 0.6f, 0.6f);
294        glColor3f(0, 1, 0);
295
296        glDepthFunc(GL_LESS);
297        glDepthMask(GL_TRUE);
298        glEnable(GL_DEPTH_TEST);
299
300        glFrontFace(GL_CCW);
301        glCullFace(GL_BACK);
302
303        glStencilFunc(GL_EQUAL, 0x0, 0x1);
304        glStencilOp(GL_KEEP, GL_KEEP, GL_INCR);
305
306        KdNode::NewMail2();
307        Intersectable::NewMail();
308
309        // render pvs once
310        RenderPvs(pvs);
311
312        //cout << "rendered nodes: " << mRenderedNodes << endl;
313
314        //glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_FALSE);
315        //glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE);
316        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
317
318        glEnable(GL_STENCIL_TEST);
319        glColor3f(1, 0, 0);
320
321
322        // render scene, record differences
323        OcclusionQuery *query = mOcclusionQueries[0];
324
325        KdNode::NewMail2();
326        Intersectable::NewMail();
327
328        query->BeginQuery();
329
330        // current frame has to be increased at each rendering pass
331        ++ mCurrentFrame;
332
333        RenderScene();
334
335        glFlush();
336
337        query->EndQuery();
338        glDisable(GL_STENCIL_TEST);
339       
340        pixelCount = query->GetQueryResult();
341
342        pErrorPixels = (float)pixelCount / (GetWidth() * GetHeight());
343
344        const int pixelThres = 0;
345
346        // some error happened
347        if (pixelCount > pixelThres)
348        {
349                cout << "f " << mFrame << " id " << viewcell->GetId() << " pvs " << pvsSize
350                         << " e " << pixelCount << " vp " << mViewPoint << " vd " << mViewDirection << endl;
351       
352                if (mSnapErrorFrames)
353                {
354                        glReadBuffer(GL_BACK);
355                        //glReadBuffer(GL_FRONT);
356
357                        //////////////
358                        //-- output error visualization
359
360                        char filename[256];
361                        //sprintf(filename, "error-frame-%04d-%05d.bmp", pass, mFrame);
362                        //sprintf(filename, "error-frame-%05d-%0.5f.png", mFrame, pErrorPixels);
363                        sprintf_s(filename, "error-frame-%05d-%04d-%08d.png", mFrame, viewcell->GetId(), pixelCount);
364
365                        QImage im = toImage();
366                        string str = mSnapPrefix + filename;
367                        QString qstr(str.c_str());
368
369                        im.save(qstr, "PNG");
370
371                        if (0)
372                        {
373                                ///////////
374                                //-- output computed pvs
375
376                                //mUseFalseColors = false;
377                                mUseFalseColors = true;
378                                glPushAttrib(GL_CURRENT_BIT);
379                                glColor3f(0, 1, 0);
380
381                                glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
382                                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
383
384                                KdNode::NewMail2();
385                                Intersectable::NewMail();
386
387                                ++ mCurrentFrame;
388
389                                // render pvs once
390                                //RenderPvs(pvs);
391                                RenderTrianglePvs();
392
393                                glFlush();
394
395                                mUseFalseColors = false;
396
397                                im = toImage();
398                                sprintf_s(filename, "error-frame-%04d-%04d-%08d-pvs.png", mFrame, viewcell->GetId(), pixelCount);
399                                str = mSnapPrefix + filename;
400                                qstr = str.c_str();
401                                im.save(qstr, "PNG");
402
403                                glPopAttrib();
404                        }
405                }
406        }
407
408        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
409
410        //DoneLive();
411
412        return pErrorPixels;
413}
414
415int
416QtGlRendererBuffer::ComputePvs(ObjectContainer &objects,
417                                                           ObjectContainer &pvs) const
418{
419        int pvsSize = 0;
420        QImage image = toImage();
421
422        Intersectable::NewMail();
423
424        std::stable_sort(objects.begin(), objects.end(), ilt);
425
426        MeshInstance dummy(NULL);
427
428        Intersectable *obj = NULL;
429
430        for (int x = 0; x < image.width(); ++ x)
431        {
432                for (int y = 0; y < image.height(); ++ y)
433                {
434                        QRgb pix = image.pixel(x, y);
435                        const int id = GetId(qRed(pix), qGreen(pix), qBlue(pix));
436
437                        dummy.SetId(id);
438
439                        ObjectContainer::iterator oit =
440                                lower_bound(objects.begin(), objects.end(), &dummy, ilt);
441
442                        if (//(oit != oit.end()) &&
443                                ((*oit)->GetId() == id) &&
444                                !obj->Mailed())
445                        {
446                                obj = *oit;
447                                obj->Mail();
448                                ++ pvsSize;
449                                pvs.push_back(obj);
450                        }
451                }
452        }
453
454        return pvsSize;
455}
456
457
458void QtGlRendererWidget::InitGL()
459{
460        GlRenderer::InitGL();
461
462        //glEnable(GL_FOG);
463        //glFogi(GL_FOG_MODE, GL_EXP);
464        //glFogf(GL_FOG_DENSITY, .2f);
465        glFogi(GL_FOG_MODE, GL_LINEAR);
466        glFogf(GL_FOG_START, 50.f);
467        glFogf(GL_FOG_END, 500.f);
468
469       
470        // mat_specular and mat_shininess are NOT default values
471        GLfloat mat_ambient[] = {0.1f, 0.1f, 0.1f, 1.0f};
472        GLfloat mat_diffuse[] = {1.0f, 1.0f, 1.0f, 1.0f};
473        GLfloat mat_specular[] = {0.3f, 0.3f, 0.3f, 1.0f};
474        GLfloat mat_shininess[] = {1.0f};
475
476        glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
477        glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
478        glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
479        glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
480
481
482        glEnable(GL_LIGHTING);
483
484        // a light     
485        GLfloat light_ambient[] = {0.05, 0.05, 0.05, 1.0};
486    GLfloat light_diffuse[] = {0.7, 0.7, 0.7, 1.0};
487    GLfloat light_specular[] = {0.3, 0.3, 0.3, 1.0};
488    //GLfloat light_position[] =  {0.f, .0f, 0.f, 1.0f};
489    //GLfloat light_position[] =  {600.0f, 250.0f, -500.f, 1.0f};
490    //GLfloat light_position[] = {278.0f, 548.8f,279.0f, 1.0f};
491
492
493
494        glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
495        glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
496        glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
497
498        glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 1);
499        glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0);
500        glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, 0);
501       
502        //      GLfloat light1_position[] =  {-22.076887, 21.070816, 50.272095};
503       
504        // GLfloat light1_position[] =  {0, 0, -100};
505
506        glLightfv(GL_LIGHT1, GL_AMBIENT, light_ambient);
507        glLightfv(GL_LIGHT1, GL_DIFFUSE, light_diffuse);
508        glLightfv(GL_LIGHT1, GL_SPECULAR, light_specular);
509
510        glLightf(GL_LIGHT1, GL_CONSTANT_ATTENUATION, 1.0f);
511        glLightf(GL_LIGHT1, GL_LINEAR_ATTENUATION, 0);
512        glLightf(GL_LIGHT1, GL_QUADRATIC_ATTENUATION, 0);
513
514
515        glLightfv(GL_LIGHT2, GL_AMBIENT, light_ambient);
516        glLightfv(GL_LIGHT2, GL_DIFFUSE, light_diffuse);
517        glLightfv(GL_LIGHT2, GL_SPECULAR, light_specular);
518       
519       
520        glEnable(GL_LIGHT0);
521        glEnable(GL_LIGHT1);
522        glEnable(GL_LIGHT2);
523
524       
525        GLfloat lmodel_ambient[] = {0.05f, 0.05f, 0.05f, 1.0f};
526        glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
527       
528        glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
529        //glColorMaterial(GL_FRONT_AND_BACK, GL_SPECULAR);
530        glEnable(GL_COLOR_MATERIAL);
531
532        glShadeModel(GL_SMOOTH);
533}
534
535
536void
537QtGlRendererWidget::SetupCameraProjection(const int w, const int h, const float angle)
538{
539        if (!mTopView) {
540                int ww = w;
541                int hh = h;
542                glViewport(0, 0, ww, hh);
543                glMatrixMode(GL_PROJECTION);
544                glLoadIdentity();
545                gluPerspective(angle, ww/(float)hh, 0.1, 2.0 * Magnitude(mSceneGraph->GetBox().Diagonal()));
546                glMatrixMode(GL_MODELVIEW);
547        } else {
548                int ww = w;
549                int hh = h;
550                glViewport(0, 0, ww, hh);
551                glMatrixMode(GL_PROJECTION);
552                glLoadIdentity();
553                gluPerspective(50.0, ww / (float)hh, 0.1, 20.0 * Magnitude(mSceneGraph->GetBox().Diagonal()));
554                glMatrixMode(GL_MODELVIEW);
555        }
556}
557
558
559bool QtGlRendererWidget::PvsChanged(ViewCell *viewCell) const
560{
561        if (viewCell != mPvsCache.mViewCell)
562                return true;
563
564        if (viewCell->GetPvs().GetSize() != mPvsCache.mUnfilteredPvsSize)
565                return true;
566
567        return false;
568}
569
570
571void QtGlRendererWidget::_RenderPvs()
572{
573        EnableDrawArrays();
574
575        if (mUseVbos)
576                glBindBufferARB(GL_ARRAY_BUFFER_ARB, mVboId);
577
578        mUseFalseColors = false;
579
580        int offset = (int)mObjects.size() * 3;
581        char *arrayPtr = mUseVbos ? NULL : (char *)mData;
582
583        glVertexPointer(3, GL_FLOAT, 0, (char *)arrayPtr);
584        glNormalPointer(GL_FLOAT, 0, (char *)arrayPtr + offset * sizeof(Vector3));
585        glDrawElements(GL_TRIANGLES, mIndexBufferSize, GL_UNSIGNED_INT, mIndices);
586
587        // handle dynamic objects in pvss
588        DynamicObjectsContainer::const_iterator dit, dit_end = mDynamicPvsObjects.end();
589
590        //cout << "dynamic objects in pvs " << mDynamicPvsObjects.size() << endl;;
591#if 0
592        for (dit = mDynamicPvsObjects.begin(); dit != dit_end; ++ dit)
593        {
594                _RenderDynamicObject(*dit);
595        }
596#endif
597        //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
598
599        // show placed dynamic objects as wireframe
600        Preprocessor *p = mViewCellsManager->GetPreprocessor();
601        dit_end = p->mDynamicObjects.end();
602
603        int i = 0;
604        for (dit = p->mDynamicObjects.begin(); dit != dit_end; ++ dit, ++ i)
605        {
606                if (i == mCurrentDynamicObjectIdx)
607                        glColor3f(1, 0, 1);
608                else
609                        glColor3f(0, 1, 0);
610
611                _RenderDynamicObject(*dit);
612        }
613       
614        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
615}
616
617
618void QtGlRendererWidget::PreparePvs(const ObjectPvs &pvs)
619{
620        int indexBufferSize = 0;
621       
622        // hack: mail not working with multiple threads
623        KdNode::NewMail2();
624
625        mPvsSize = pvs.GetSize();
626
627        mDynamicPvsObjects.clear();
628
629        ObjectPvsIterator it = pvs.GetIterator();
630
631        while (it.HasMoreEntries())
632        {
633                Intersectable *obj = it.Next();
634
635                switch (obj->Type())
636                {
637                case Intersectable::KD_INTERSECTABLE:
638                        {
639                                KdNode *node = static_cast<KdIntersectable *>(obj)->GetItem();
640                                _UpdatePvsIndices(node, indexBufferSize);
641                        }
642                        break;
643
644                case Intersectable::SCENEGRAPHLEAF_INTERSECTABLE:
645                        mDynamicPvsObjects.push_back(static_cast<SceneGraphLeafIntersectable *>(obj)->GetItem());
646                        break;
647                default:
648                        cerr << "PreparePvs: type " << Intersectable::GetTypeName(obj) << " not handled yet" << endl;
649                }
650        }
651
652        mIndexBufferSize = indexBufferSize;
653}
654
655
656void QtGlRendererWidget::VisualizePvs()
657{
658        if (mUseVbos)
659                glBindBufferARB(GL_ARRAY_BUFFER_ARB, mVboId);
660
661        ++ mCurrentFrame;
662
663        EnableDrawArrays();
664               
665        if (mDetectEmptyViewSpace)
666                glEnable(GL_CULL_FACE);
667        else
668                glDisable(GL_CULL_FACE);
669
670        ViewCell *viewcell = NULL;
671        viewcell = mViewCellsManager->GetViewCell(mViewPoint, true);
672
673        if (viewcell)
674        {
675                // copy the pvs so that it can be filtered ...
676                if (PvsChanged(viewcell))
677                {
678                        mPvsCache.Reset();
679                        mPvsCache.mViewCell = viewcell;
680                        mPvsCache.mUnfilteredPvsSize = viewcell->GetPvs().GetSize();
681
682                        if (mUseSpatialFilter)
683                        {
684                                //mMutex.lock();
685                                // mSpatialFilter size is in range 0.001 - 0.1
686                                mViewCellsManager->ApplyFilter2(viewcell,
687                                        mUseFilter,
688                                        100.0f * mSpatialFilterSize,
689                                        mPvsCache.mPvs,         
690                                        &mPvsCache.filteredBoxes);
691                                //mPvsCache.mPvs = pvs;
692                                //mMutex.unlock();
693                                //cout << "pvs size: " << mPvsCache.mPvs.GetSize() << endl;
694                        }
695                        else
696                        {
697                                mPvsCache.mPvs = viewcell->GetPvs();
698                        }
699                       
700                        // update the indices for rendering
701                        PreparePvs(mPvsCache.mPvs);
702                        emit PvsUpdated();
703
704                        mCurrentPvsCost = mPvsCache.mPvs.EvalPvsCost();
705                }
706
707                // Render PVS
708                if (mUseSpatialFilter && mRenderBoxes)
709                {
710                        for (size_t i=0; i < mPvsCache.filteredBoxes.size(); ++ i)
711                        {
712                                RenderBox(mPvsCache.filteredBoxes[i]);
713                        }
714                }
715                else
716                {
717                        if (!mRenderVisibilityEstimates && !mUseRandomColorPerPvsObject)
718                                _RenderPvs();
719                        else
720                                _RenderColoredPvs();
721                }
722
723                if (mRenderFilter)
724                {
725                        mWireFrame = true;
726                        RenderIntersectable(viewcell);
727                       
728                        mWireFrame = false;
729                }
730        }
731        else
732        {
733                RenderScene();
734        }
735
736        //cout << "vp: " << mViewPoint << " vd: " << mViewDirection << endl;
737}
738
739float
740QtGlRendererWidget::RenderErrors()
741{
742        float pErrorPixels = -1.0f;
743
744        SetupCamera();
745        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
746
747        glPushAttrib(GL_ENABLE_BIT);
748
749        glStencilFunc(GL_EQUAL, 0x0, 0x1);
750        glStencilOp(GL_KEEP, GL_KEEP, GL_INCR);
751
752#if TEASER
753        glColor3f(0.0f, 0.8f, 0.0f);
754#else
755        glColor3f(0.6f, 0.6f, 0.6f);
756#endif
757       
758        // Render PVS
759        VisualizePvs();
760
761        glEnable(GL_STENCIL_TEST);
762        glDisable(GL_LIGHTING);
763
764        SetupCamera();
765
766        mUseForcedColors = true;
767
768        glColor3f(1.0f, 0.0f, 0.0f);
769
770        OcclusionQuery *query = mOcclusionQueries[0];
771        query->BeginQuery();
772
773        RenderScene();
774
775        mUseForcedColors = false;
776
777        query->EndQuery();
778
779        glDisable(GL_STENCIL_TEST);
780        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
781
782        glPopAttrib();
783
784        // reenable other state
785        //  int wait=0;
786        //  while (!query.ResultAvailable()) {
787        //      wait++;
788        //  }
789
790        int pixelCount = query->GetQueryResult();
791        pErrorPixels = (float)pixelCount / (GetWidth() * GetHeight());
792       
793        if (0) cout << "error pixels=" << pixelCount << endl;
794
795        mRenderError = pErrorPixels;
796
797        return pErrorPixels;
798}
799
800
801void QtGlRendererWidget::timerEvent(QTimerEvent *timerEvent)
802{
803        if (mReplayMode && (timerEvent->timerId() == mReplayTimerId))
804        {
805                if (sViewPointsListIt == sViewPointsList.end())
806                {
807                        cout << "stopping replay" << endl;
808                        mReplayMode = false;
809                        GetPreprocessor()->mSynchronize = false;
810                }
811                else
812                {
813                        SimpleRay sray = *sViewPointsListIt;
814
815                        mViewPoint = sray.mOrigin;
816                        mViewDirection = sray.mDirection;
817
818                        ++ sViewPointsListIt;
819                }
820
821                updateGL();
822
823                // output the current frame buffer
824                if (mExportFrameBuffer)
825                {
826                        const int dist = sViewPointsListIt - sViewPointsList.begin();
827
828                        char filename[200];
829                        sprintf(filename, "error-frame-%04d-%05d.bmp", sCurrentSamples, dist);
830                        //QPixmap img = renderPixmap(0, 0, true);
831                        QImage im = grabFrameBuffer();
832
833                        string str = mSnapPrefix + filename;
834                        QString qstr(str.c_str());
835
836                        //im.save(qstr, "PNG");
837                        // use bmp for lossless storage (for video)
838                        im.save(qstr, "BMP");
839                }
840        }
841        else if (timerEvent->timerId() == mUpdateTimerId)
842                // update pvss from time to time
843                update();
844
845        // grab frame buffer after a certain number of samples
846        if (!mReplayMode &&
847                (sCurrentSamplesThreshold < sNumReplays) &&
848                ((GetPreprocessor()->mCurrentSamples > sNextSamplesThreshold[sCurrentSamplesThreshold])))
849        {
850                ++ sCurrentSamplesThreshold;
851                cout << "replaying at total samples: " << GetPreprocessor()->mCurrentSamples << endl;
852                ReplayViewPoints();
853        }
854
855}
856
857
858void QtGlRendererWidget::mousePressEvent(QMouseEvent *e)
859{
860        int x = e->pos().x();
861        int y = e->pos().y();
862
863        mousePoint.x = x;
864        mousePoint.y = y;
865
866        if (e->button() == Qt::RightButton)
867        {
868                if (mPlacer->GetCurrentObject())
869                {
870                        Vector3 pt = Unproject(x, y);
871
872                        mPlacer->PlaceObject(pt);
873                        SceneGraphLeaf *leaf = mPlacer->GetCurrentObject();
874
875                        // hack: should just pass a IntersectableGroup as a whole
876                        // instead we duplicate the object container and create a new
877                        // leaf
878                        SceneGraphLeaf *newObj = new SceneGraphLeaf(*leaf);
879
880                        // make current object
881                        // the object is added at the end of the vector
882                        mCurrentDynamicObjectIdx = (int)GetPreprocessor()->mDynamicObjects.size();
883
884                        GetPreprocessor()->RegisterDynamicObject(newObj);
885                }
886        }
887}
888
889
890void QtGlRendererWidget::mouseReleaseEvent(QMouseEvent *e)
891{
892        int x = e->pos().x();
893        int y = e->pos().y();
894
895        mousePoint.x = x;
896        mousePoint.y = y;
897
898        if (e->modifiers() & Qt::ShiftModifier)
899        {
900                const Vector3 pt = Unproject(x, y);
901
902                int idx = FindDynamicObject(x, y);
903               
904                if (idx >= 0)
905                {
906                        mCurrentDynamicObjectIdx = idx;
907                }
908        }
909}
910
911void
912QtGlRendererWidget::mouseMoveEvent(QMouseEvent *e)
913{
914        if (mReplayMode)
915                return;
916
917        float MOVE_SENSITIVITY = Magnitude(mSceneGraph->GetBox().Diagonal())*1e-3;
918        float TURN_SENSITIVITY = 0.1f;
919        float TILT_SENSITIVITY = 32.0 ;
920        float TURN_ANGLE= M_PI / 36.0 ;
921
922        int x = e->pos().x();
923        int y = e->pos().y();
924
925        int diffx = -(mousePoint.x - x);
926        int diffy = -(mousePoint.y - y);
927
928        const float t = 1.0f;
929        if (e->modifiers() & Qt::ControlModifier)
930        {
931                mViewPoint.y += (y-mousePoint.y)*MOVE_SENSITIVITY / 2.0;
932                mViewPoint.x += (x-mousePoint.x)*MOVE_SENSITIVITY / 2.0;
933        }
934        else if (e->modifiers() & Qt::AltModifier)
935        {
936                if (mCurrentDynamicObjectIdx >= 0)
937                {
938                        Matrix4x4 tm;
939
940                        SceneGraphLeaf *l =
941                          mViewCellsManager->GetPreprocessor()->mDynamicObjects[mCurrentDynamicObjectIdx];
942
943                        switch (mTrafoType)
944                        {
945                        case 0:
946                                {
947                                  if (e->modifiers() & Qt::ShiftModifier) {
948                                        const Vector3 transl(0, diffy, 0);
949                                        tm = TranslationMatrix(transl);
950                                 
951                                  } else {
952                                        const Vector3 transl(diffx, 0, diffy);
953                                        tm = TranslationMatrix(transl);
954                                  }
955                                }
956                                break;
957                        case 1:
958                                {
959                                        float scalef = 1.0f + 0.01f * (diffx + diffy);
960                                        if (scalef < 0.9) scalef = 0.9f;
961                                        else if (scalef > 1.1f) scalef = 1.1f;
962                                        tm = ScaleMatrix(scalef, scalef, scalef);
963                                }
964                                break;
965                        case 2:
966                                {
967                                        // tm = RotationXMatrix(diffx) * RotationYMatrix(diffy);
968                                        tm = RotationYMatrix(diffx);
969                                }
970                                break;
971                        default:
972                                cerr << "not implemented" << endl;
973                        }
974                       
975                        l->ApplyTransform(tm);
976
977                        updateGL();
978                }
979        }
980        else
981        {
982                mViewPoint += mViewDirection*((mousePoint.y - y)*MOVE_SENSITIVITY);
983                float adiff = TURN_ANGLE*(x - mousePoint.x)*-TURN_SENSITIVITY;
984                float angle = atan2(mViewDirection.x, mViewDirection.z);
985                mViewDirection.x = sin(angle + adiff);
986                mViewDirection.z = cos(angle + adiff);
987        }
988
989        mousePoint.x = x;
990        mousePoint.y = y;
991
992        updateGL();
993}
994
995
996void
997QtGlRendererWidget::resizeGL(int w, int h)
998{
999        SetupCameraProjection(w, h);
1000        updateGL();
1001}
1002
1003
1004void QtGlRendererWidget::paintGL()
1005{
1006        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1007
1008        SetupCameraProjection(width(), height());
1009        SetupCamera();
1010
1011        GLfloat light0_position[] =  {22.495655, 21.070816, -1001.375000};
1012        GLfloat light1_position[] =  {-22.076887, 21.070816, -997.272095};
1013        GLfloat light2_position[] =  { 0.3, 1.5, -0.3, 0.0  };
1014
1015        glLightfv (GL_LIGHT0, GL_POSITION, light0_position);
1016        glLightfv (GL_LIGHT1, GL_POSITION, light1_position);
1017        glLightfv (GL_LIGHT2, GL_POSITION, light2_position);
1018
1019        if (mRenderErrors)
1020                RenderErrors();
1021        else
1022        {
1023                glColor3f(0.6f, 0.6f, 0.6f);
1024                VisualizePvs();
1025        }
1026
1027        if (mShowRays)
1028                RenderRays(mViewCellsManager->mVizBuffer.GetRays(), mRayVisualizationMethod, mShowDistribution, 1);
1029       
1030        RenderInfo();
1031
1032        ++ mFrame;
1033        //      cout<<"vp="<<mViewPoint<<" vd="<<mViewDirection<<endl;
1034}
1035
1036
1037void
1038QtGlRendererWidget::SetupCamera()
1039{
1040        if (!mTopView)
1041                GlRenderer::SetupCamera();
1042        else
1043        {
1044                if (0)
1045                {
1046                        float dist = Magnitude(mSceneGraph->GetBox().Diagonal())*0.05;
1047                        Vector3 pos = mViewPoint - dist*Vector3(mViewDirection.x,
1048                                -1,
1049                                mViewDirection.y);
1050
1051                        Vector3 target = mViewPoint + dist*mViewDirection;
1052                        Vector3 up(0,1,0);
1053
1054                        glLoadIdentity();
1055                        gluLookAt(pos.x, pos.y, pos.z,
1056                                target.x, target.y, target.z,
1057                                up.x, up.y, up.z);
1058                }
1059                else
1060                {
1061                        float dist = Magnitude(mSceneGraph->GetBox().Diagonal()) * mTopDistance;
1062                        Vector3 pos = mViewPoint  + dist * Vector3(0,   1, 0);
1063
1064                        Vector3 target = mViewPoint;
1065                        Vector3 up(mViewDirection.x, 0, mViewDirection.z);
1066
1067                        glLoadIdentity();
1068                        gluLookAt(pos.x, pos.y, pos.z,
1069                                target.x, target.y, target.z,
1070                                up.x, up.y, up.z);
1071
1072                }
1073        }
1074
1075}
1076
1077
1078void
1079QtGlRendererWidget::keyPressEvent ( QKeyEvent * e )
1080{
1081        switch (e->key())
1082        {
1083        case Qt::Key_E:
1084                mRenderErrors = !mRenderErrors;
1085                updateGL();
1086                break;
1087        case Qt::Key_R:
1088                mUseRandomColorPerPvsObject = !mUseRandomColorPerPvsObject;;
1089                updateGL();
1090                break;
1091        case Qt::Key_T:
1092                mTopView = !mTopView;
1093                SetupCameraProjection(width(), height());
1094                updateGL();
1095                break;
1096        case Qt::Key_V:
1097                mRenderViewCells = !mRenderViewCells;
1098                updateGL();
1099                break;
1100        case Qt::Key_P:
1101                // set random viewpoint
1102                mViewCellsManager->GetViewPoint(mViewPoint);
1103                updateGL();
1104                break;
1105        case Qt::Key_S: {
1106                // set view poitn and direction
1107                QString text;
1108                bool ok;
1109                text.sprintf("%f %f %f", mViewPoint.x, mViewPoint.y, mViewPoint.z);
1110                text = QInputDialog::getText(this,
1111                        "Enter a view point",
1112                        "",
1113                        QLineEdit::Normal,
1114                        text,
1115                        &ok);
1116                if (!ok)
1117                        break;
1118
1119                if (sscanf_s(text.toAscii(), "%f %f %f", &mViewPoint.x, &mViewPoint.y, &mViewPoint.z) == 3) {
1120                        text.sprintf("%f %f %f", mViewDirection.x, mViewDirection.y, mViewDirection.z);
1121                        text = QInputDialog::getText(this,
1122                                "Enter a direction",
1123                                "",
1124                                QLineEdit::Normal,
1125                                text,
1126                                &ok);
1127                        if (!ok)
1128                                break;
1129                        if (sscanf_s(text.toAscii(), "%f %f %f", &mViewDirection.x,
1130                                &mViewDirection.y, &mViewDirection.z) == 3) {
1131                                        updateGL();
1132                        }
1133                        break;
1134                }
1135                                        }
1136        default:
1137                cerr << "unknown key" << endl;
1138                e->ignore();
1139                break;
1140        }
1141}
1142
1143
1144
1145QtGlRendererWidget::QtGlRendererWidget(
1146                                                                           SceneGraph *sceneGraph,
1147                                                                           ViewCellsManager *viewcells,
1148                                                                           KdTree *tree,
1149                                                                           QWidget * parent,
1150                                                                           const QGLWidget * shareWidget,
1151                                                                           Qt::WFlags f):
1152GlRendererWidget(sceneGraph, viewcells, tree),
1153QGLWidget(QGLFormat(QGL::SampleBuffers), parent, shareWidget, f)
1154{
1155        mPreprocessorThread = NULL;
1156        mTopView = false;
1157        mRenderViewCells = false;
1158        mTopDistance = 1.0f;
1159        mCutViewCells = false;
1160        mCutScene = false;
1161        mRenderErrors = false;
1162        mRenderBoxes = false;
1163        mRenderFilter = true;
1164        mRenderVisibilityEstimates = false;
1165        //mRenderVisibilityEstimates = true;
1166
1167        mComputeGVS = false;
1168        mUseRandomColorPerPvsObject = false;
1169        //mUseRandomColorPerPvsObject = true;
1170
1171        mHideByCost = false;
1172        mUseTransparency = false;
1173
1174        mTransferFunction = 1.0f;
1175        mIndexBufferSize = 0;
1176
1177        const int delay = 250; // in milliseconds
1178        mUpdateTimerId = startTimer(delay);
1179        mReplayTimerId = startTimer(1); // use fastest replay rate
1180
1181        bool tmp;
1182
1183        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilityFilter", tmp );
1184        mUseFilter = tmp;
1185
1186        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilitySpatialFilter", tmp );
1187        mUseSpatialFilter = tmp;
1188
1189        mShowRenderCost = false;
1190        mShowPvsSizes = false;
1191        mShowComparison = false;
1192        mShowPiercingRays = false;
1193        mShowWeightedRays = false;
1194        mUseStandardColors = false;
1195        mShowWeightedCost = true;
1196
1197        mShowDistanceWeightedPvs = true;
1198        mShowDistanceWeightedTriangles = false;
1199        mShowWeightedTriangles = false;
1200        mShowDistribution = 15;
1201
1202        mSpatialFilterSize = 0.01;
1203        mPvsSize = 0;
1204        mRayVisualizationMethod = 0;
1205        mTrafoType = 0;
1206
1207        mRenderError = 0.0f;
1208
1209        mShowRays = false;
1210        mReplayMode = false;
1211
1212        mPlacer = new ObjectPlacer();
1213
1214        mCurrentDynamicObjectIdx = -1;
1215
1216        // export frame buffer during walkthrough
1217        mExportFrameBuffer = true;
1218        //mExportFrameBuffer = false;
1219
1220        SetSceneCut(1000);
1221        mControlWidget = new QtRendererControlWidget(NULL);
1222
1223        connect(mControlWidget, SIGNAL(SetViewCellGranularity(int)), this, SLOT(SetViewCellGranularity(int)));
1224        connect(mControlWidget, SIGNAL(SetTransferFunction(int)), this, SLOT(SetTransferFunction(int)));
1225
1226        connect(mControlWidget, SIGNAL(UpdateAllPvs()), this, SLOT(UpdateAllPvs()));
1227        connect(mControlWidget, SIGNAL(ComputeVisibility()), this, SLOT(ComputeVisibility()));
1228        connect(mControlWidget, SIGNAL(StopComputation()), this, SLOT(StopComputation()));
1229        connect(mControlWidget, SIGNAL(SetRandomViewPoint()), this,     SLOT(SetRandomViewPoint()));
1230        connect(mControlWidget, SIGNAL(StoreStatistics(void)), this, SLOT(StoreStatistics(void)));
1231        connect(mControlWidget, SIGNAL(ComputeGVS(void)), this, SLOT(ComputeGVS(void)));
1232        connect(mControlWidget, SIGNAL(ReplayViewPoints(void)), this, SLOT(ReplayViewPoints(void)));
1233        connect(mControlWidget, SIGNAL(NextObject(void)), this, SLOT(NextObject(void)));
1234
1235        connect(mControlWidget, SIGNAL(SetSceneCut(int)), this, SLOT(SetSceneCut(int)));
1236        connect(mControlWidget, SIGNAL(SetTopDistance(int)), this, SLOT(SetTopDistance(int)));
1237        connect(mControlWidget, SIGNAL(SetTransparency(int)), this, SLOT(SetTransparency(int)));
1238
1239        connect(mControlWidget, SIGNAL(SetVisibilityFilterSize(int)), this, SLOT(SetVisibilityFilterSize(int)));
1240        connect(mControlWidget, SIGNAL(SetSpatialFilterSize(int)), this, SLOT(SetSpatialFilterSize(int)));
1241        connect(mControlWidget, SIGNAL(SetHidingCost(int)), this, SLOT(SetHidingCost(int)));
1242
1243        connect(mControlWidget, SIGNAL(SetShowViewCells(bool)), this, SLOT(SetShowViewCells(bool)));
1244        connect(mControlWidget, SIGNAL(SetShowRenderCost(bool)), this, SLOT(SetShowRenderCost(bool)));
1245        connect(mControlWidget, SIGNAL(SetUseTransparency(bool)), this, SLOT(SetUseTransparency(bool)));
1246        connect(mControlWidget, SIGNAL(SetShowPvsSizes(bool)), this, SLOT(SetShowPvsSizes(bool)));
1247        connect(mControlWidget, SIGNAL(SetShowComparison(bool)), this, SLOT(SetShowComparison(bool)));
1248        connect(mControlWidget, SIGNAL(SetTopView(bool)), this, SLOT(SetTopView(bool)));
1249        connect(mControlWidget, SIGNAL(SetCutViewCells(bool)), this, SLOT(SetCutViewCells(bool)));
1250        connect(mControlWidget, SIGNAL(SetHideByCost(bool)), this, SLOT(SetHideByCost(bool)));
1251        connect(mControlWidget, SIGNAL(SetCutScene(bool)), this, SLOT(SetCutScene(bool)));
1252        connect(mControlWidget, SIGNAL(SetRenderErrors(bool)), this, SLOT(SetRenderErrors(bool)));
1253        connect(mControlWidget, SIGNAL(SetRenderBoxes(bool)), this, SLOT(SetRenderBoxes(bool)));
1254        connect(mControlWidget, SIGNAL(SetRenderFilter(bool)), this, SLOT(SetRenderFilter(bool)));
1255        connect(mControlWidget, SIGNAL(SetRenderVisibilityEstimates(bool)), this, SLOT(SetRenderVisibilityEstimates(bool)));
1256        connect(mControlWidget, SIGNAL(SetUseFilter(bool)), this, SLOT(SetUseFilter(bool)));
1257        connect(mControlWidget, SIGNAL(SetUseSpatialFilter(bool)), this, SLOT(SetUseSpatialFilter(bool)));
1258        connect(mControlWidget, SIGNAL(SetShowPiercingRays(bool)), this, SLOT(SetShowPiercingRays(bool)));
1259        connect(mControlWidget, SIGNAL(SetShowWireFrame(bool)), this, SLOT(SetShowWireFrame(bool)));
1260        connect(mControlWidget, SIGNAL(SetShowWeightedRays(bool)), this, SLOT(SetShowWeightedRays(bool)));
1261        connect(mControlWidget, SIGNAL(SetShowWeightedCost(bool)), this, SLOT(SetShowWeightedCost(bool)));
1262
1263        connect(mControlWidget, SIGNAL(SetShowDistanceWeightedTriangles(bool)), this, SLOT(SetShowDistanceWeightedTriangles(bool)));
1264        connect(mControlWidget, SIGNAL(SetShowDistanceWeightedPvs(bool)), this, SLOT(SetShowDistanceWeightedPvs(bool)));
1265        connect(mControlWidget, SIGNAL(SetShowWeightedTriangles(bool)), this, SLOT(SetShowWeightedTriangles(bool)));
1266
1267        connect(mControlWidget, SIGNAL(UseConstColorForRayViz(bool)), this, SLOT(UseConstColorForRayViz(bool)));
1268        connect(mControlWidget, SIGNAL(UseRayLengthForRayViz(bool)), this, SLOT(UseRayLengthForRayViz(bool)));
1269        connect(mControlWidget, SIGNAL(SetShowContribution(bool)), this, SLOT(SetShowContribution(bool)));
1270        connect(mControlWidget, SIGNAL(SetShowDistribution(bool)), this, SLOT(SetShowDistribution(bool)));
1271
1272        connect(mControlWidget, SIGNAL(SetShowDistribution1(bool)), this, SLOT(SetShowDistribution1(bool)));
1273        connect(mControlWidget, SIGNAL(SetShowDistribution2(bool)), this, SLOT(SetShowDistribution2(bool)));
1274        connect(mControlWidget, SIGNAL(SetShowDistribution3(bool)), this, SLOT(SetShowDistribution3(bool)));
1275        connect(mControlWidget, SIGNAL(SetShowDistribution4(bool)), this, SLOT(SetShowDistribution4(bool)));
1276
1277        connect(mControlWidget, SIGNAL(SetShowRays(bool)), this, SLOT(SetShowRays(bool)));
1278
1279#if 1
1280        connect(mControlWidget, SIGNAL(SetTranslation(bool)), this, SLOT(SetTranslation(bool)));
1281        connect(mControlWidget, SIGNAL(SetRotation(bool)), this, SLOT(SetRotation(bool)));
1282        connect(mControlWidget, SIGNAL(SetScale(bool)), this, SLOT(SetScale(bool)));
1283#endif
1284        connect(mControlWidget, SIGNAL(UpdateDynamicObjects()), this, SLOT(UpdateDynamicObjects()));
1285        connect(mControlWidget, SIGNAL(DeleteDynamicObject()), this, SLOT(DeleteDynamicObject()));
1286
1287        setWindowTitle("PVS Visualization");
1288
1289        // setting the main window size here
1290        //resize(800, 600);
1291        resize(640, 480);
1292       
1293        mControlWidget->show();
1294
1295        LoadObjects();
1296}
1297
1298void
1299QtGlRendererWidget::UpdateAllPvs()
1300{
1301        // $$ does not work so far:(
1302        mViewCellsManager->UpdatePvsForEvaluation();
1303        //      mViewCellsManager->FinalizeViewCells(false);
1304}
1305
1306void
1307QtGlRendererWidget::ComputeVisibility()
1308{
1309        cerr<<"Compute Visibility called!\n"<<endl;
1310        if (!mPreprocessorThread->isRunning())
1311                mPreprocessorThread->RunThread();
1312}
1313
1314void
1315QtGlRendererWidget::StopComputation()
1316{
1317        cerr<<"stop computation called!\n"<<endl;
1318        mViewCellsManager->GetPreprocessor()->mStopComputation = true;
1319}
1320
1321void
1322QtGlRendererWidget::SetRandomViewPoint()
1323{
1324        cerr<<"setting random view point!\n"<<endl;
1325        mViewCellsManager->GetViewPoint(mViewPoint);
1326        updateGL();
1327}
1328
1329
1330void QtGlRendererWidget::StoreStatistics()
1331{
1332        cerr<<"storing statistics!\n"<<endl;
1333        const int currentSamples = mViewCellsManager->GetPreprocessor()->mCurrentSamples;
1334
1335        cout<<"**********************************************" << endl;
1336        cout << "reached " << currentSamples << " samples " << " => writing file" << endl;
1337               
1338        LogWriter writer;
1339        writer.SetFilename("compare.log");
1340        writer.Write(currentSamples, mViewCellsManager->GetViewCells());
1341        cout << "finished writing file" << endl;
1342        mCompareInfo.clear();
1343        updateGL();
1344}
1345
1346
1347void QtGlRendererWidget::LoadObjects()
1348{
1349        AxisAlignedBox3 sceneBox = mViewCellsManager->GetViewSpaceBox();
1350       
1351        float x = 1.0f;
1352        float y = 20.0f;
1353        float z = 80.0f;
1354
1355        AxisAlignedBox3 box(Vector3(0.5f * x, 0, -0.5f * z), Vector3(-0.5f * x, y, 0.5f * z));
1356
1357//      box.Scale(Vector3(0.02f, 0.1f, 0.1f));
1358
1359        box.Translate(-box.Min());
1360
1361        SceneGraphLeaf *leaf = GetPreprocessor()->GenerateBoxGeometry(box);
1362        mPlacer->AddObject(leaf);
1363       
1364        LoadObject("../data/teapot.bn");
1365        LoadObject("../data/bunny.bn");
1366        LoadObject("../data/horse.bn");
1367}
1368
1369
1370void QtGlRendererWidget::NextObject()
1371{
1372        mPlacer->NextObject();
1373}
1374
1375
1376void QtGlRendererWidget::LoadObject(const string &filename)
1377{
1378        cout << "Loading model " << filename << endl;
1379
1380        SceneGraphLeaf *leaf =
1381                mViewCellsManager->GetPreprocessor()->LoadDynamicGeometry(filename);
1382
1383        if (leaf)
1384        {
1385                mPlacer->AddObject(leaf);
1386                cout << "Loading finished" << endl;
1387        }
1388        else
1389                cerr << "Loading failed" << endl;
1390       
1391    //updateGL();
1392}
1393
1394
1395QtGlRendererWidget::~QtGlRendererWidget()
1396{
1397        delete mPlacer;
1398}
1399
1400
1401void
1402QtGlRendererWidget::RenderRenderCost()
1403{
1404        static vector<float> costFunction;
1405        static float maxCost = -1;
1406        if (costFunction.size()==0) {
1407                ViewCellsTree *tree = mViewCellsManager->GetViewCellsTree();
1408                if (tree) {
1409                        tree->GetCostFunction(costFunction);
1410                        maxCost = -1;
1411                        for (int i=0;  i < costFunction.size(); i++) {
1412                                //                cout<<i<<":"<<costFunction[i]<<" ";
1413                                // update cost function to an absolute value based on the total geometry count
1414                                costFunction[i] *= mSceneGraph->GetSize();
1415                                if (costFunction[i] > maxCost)
1416                                        maxCost = costFunction[i];
1417                        }
1418                }
1419        }
1420
1421
1422        int currentPos = (int)mViewCellsManager->GetViewCells().size();
1423        float currentCost= -1;
1424
1425        if (currentPos < costFunction.size())
1426                currentCost = costFunction[currentPos];
1427#if 1   
1428        cout<<"costFunction.size()="<<(int)costFunction.size()<<endl;
1429        cout<<"CP="<<currentPos<<endl;
1430        cout<<"MC="<<maxCost<<endl;
1431        cout<<"CC="<<currentCost<<endl;
1432#endif
1433        if (costFunction.size()) {
1434                float scaley = 1.0f/log10(maxCost);
1435                float scalex = 1.0f/(float)costFunction.size();
1436
1437                glDisable(GL_DEPTH_TEST);
1438                // init ortographic projection
1439                glMatrixMode(GL_PROJECTION);
1440
1441                glPushMatrix();
1442
1443                glLoadIdentity();
1444                gluOrtho2D(0, 1.0f, 0, 1.0f);
1445
1446                glTranslatef(0.1f, 0.1f, 0.0f);
1447                glScalef(0.8f, 0.8f, 1.0f);
1448                glMatrixMode(GL_MODELVIEW);
1449                glLoadIdentity();
1450
1451                glColor3f(1.0f,0,0);
1452                glBegin(GL_LINE_STRIP);
1453                //        glVertex3f(0,0,0);
1454
1455                for (int i=0;  i < costFunction.size(); i++) {
1456                        float x =  i*scalex;
1457                        float y = log10(costFunction[i])*scaley;
1458                        glVertex3f(x,y,0.0f);
1459                }
1460                glEnd();
1461
1462                glColor3f(1.0f,0,0);
1463                glBegin(GL_LINES);
1464                float x =  currentPos*scalex;
1465                glVertex3f(x,0.0,0.0f);
1466                glVertex3f(x,1.0f,0.0f);
1467                glEnd();
1468
1469                glColor3f(0.0f,0,0);
1470                // show a grid
1471                glBegin(GL_LINE_LOOP);
1472                glVertex3f(0,0,0.0f);
1473                glVertex3f(1,0,0.0f);
1474                glVertex3f(1,1,0.0f);
1475                glVertex3f(0,1,0.0f);
1476                glEnd();
1477
1478                glBegin(GL_LINES);
1479                for (int i=0;  i < costFunction.size(); i += 1000) {
1480                        float x =  i*scalex;
1481                        glVertex3f(x,0.0,0.0f);
1482                        glVertex3f(x,1.0f,0.0f);
1483                }
1484
1485                for (int i=0;  pow(10.0f, i) < maxCost; i+=1) {
1486                        float y = i*scaley;
1487                        //              QString s;
1488                        //              s.sprintf("%d", (int)pow(10,i));
1489                        //              renderText(width()/2+5, y*height(), s);
1490                        glVertex3f(0.0f, y, 0.0f);
1491                        glVertex3f(1.0f, y, 0.0f);
1492                }
1493
1494                glEnd();
1495
1496
1497                // restore the projection matrix
1498                glMatrixMode(GL_PROJECTION);
1499                glPopMatrix();
1500                glMatrixMode(GL_MODELVIEW);
1501                glEnable(GL_DEPTH_TEST);
1502
1503        }
1504
1505
1506
1507}
1508
1509void
1510QtGlRendererWidget::RenderInfo()
1511{
1512
1513        QString s;
1514
1515        int vc = 0;
1516        if (mViewCellsManager)
1517                vc = (int)mViewCellsManager->GetViewCells().size();
1518
1519        int filter = 0;
1520        if (mViewCellsManager)
1521                filter = mViewCellsManager->GetMaxFilterSize();
1522
1523#if 0 //REMOVE_TEMPORARY
1524        s.sprintf("frame:%04d viewpoint:(%4.1f,%4.1f,%4.1f) dir:(%4.1f,%4.1f,%4.1f)",
1525                mFrame,
1526                mViewPoint.x,
1527                mViewPoint.y,
1528                mViewPoint.z,
1529                mViewDirection.x,
1530                mViewDirection.y,
1531                mViewDirection.z
1532                );
1533
1534        renderText(20, 20, s);
1535
1536        s.sprintf("viewcells:%04d filter:%04d pvs:%04d error:%5.5f %",
1537                vc,
1538                filter,
1539                mPvsSize,
1540                mRenderError * 100.0f);
1541
1542        renderText(20, 40, s);
1543#endif
1544
1545        glDisable(GL_LIGHTING);
1546        //qglColor(QColor(0, 255, 0));
1547        glColor3f(0, 1, 0);
1548        QFont font40; font40.setPointSize(25);
1549        //s.sprintf("PVS: %04d", mPvsSize);
1550        //renderText(20, 40, s, font40);
1551       
1552        //s.sprintf("RAW TRI: %07d", mViewCellsManager->GetPreprocessor()->mGenericStats);
1553        //renderText(290, 40, s, font40);
1554        //s.sprintf("PVS TRI: %07d", mViewCellsManager->GetPreprocessor()->mGenericStats2);
1555        //renderText(290, 70, s, font40);
1556
1557        s.sprintf("PVS TRI: %08d", (int)mCurrentPvsCost);
1558        //renderText(290, 70, s, font40);
1559        renderText(325, 40, s, font40);
1560        s.sprintf("error: %3.3f %", mRenderError * 100.0f);
1561        renderText(20, 40, s, font40);
1562
1563        //renderText(290, 70, s, font40);
1564        glEnable(GL_LIGHTING);
1565
1566}
1567
1568
1569void
1570QtGlRendererWidget::SetViewCellGranularity(int number)
1571{
1572        if (mViewCellsManager)
1573        {
1574                //      mViewCellsManager->SetMaxFilterSize(number);
1575
1576                // $$ tmp off
1577                mViewCellsManager->CollectViewCells(number);
1578
1579                // $$ does not work so far:(
1580                //      mViewCellsManager->UpdatePvsForEvaluation();
1581                //      mViewCellsManager->FinalizeViewCells(false);
1582        }
1583        updateGL();
1584}
1585
1586void
1587QtGlRendererWidget::SetVisibilityFilterSize(int number)
1588{
1589        if (mViewCellsManager)
1590                mViewCellsManager->SetMaxFilterSize(number);
1591
1592        mPvsCache.Reset();
1593        updateGL();
1594}
1595
1596void
1597QtGlRendererWidget::SetSpatialFilterSize(int number)
1598{
1599        mSpatialFilterSize = 1e-3*number;
1600        mPvsCache.Reset();
1601        updateGL();
1602}
1603
1604void
1605QtGlRendererWidget::SetSceneCut(int number)
1606{
1607        // assume the cut plane can only be aligned with xz plane
1608        // shift it along y according to number, which is percentage of the bounding
1609        // box position
1610        if (mViewCellsManager)
1611        {
1612                const float f = number / 1000.0f;
1613                AxisAlignedBox3 box = mViewCellsManager->GetViewSpaceBox();
1614                Vector3 p = (1.0f - f) * box.Min() + f * box.Max();
1615                mSceneCutPlane.mNormal = Vector3(0, -1, 0);
1616                mSceneCutPlane.mD = -DotProd(mSceneCutPlane.mNormal, p);
1617
1618                updateGL();
1619        }
1620}
1621
1622void
1623QtGlRendererWidget::SetHidingCost(int number)
1624{
1625        mHidingCost = (float)number / 1000.0f;
1626}
1627
1628
1629void
1630QtGlRendererWidget::SetTopDistance(int number)
1631{
1632        mTopDistance = number / 1000.0f;
1633        updateGL();
1634}
1635
1636void QtGlRendererWidget::SetTransparency(int number)
1637{
1638        mTransparency = number / 1000.0f;
1639        updateGL();
1640}
1641
1642
1643float QtGlRendererWidget::ComputeRenderCost(ViewCell *vc)
1644{
1645        float renderCost = 0;
1646
1647#ifdef USE_VERBOSE_PVS
1648        if (mShowDistanceWeightedPvs)
1649        {
1650                return vc->GetPvs().mStats.mDistanceWeightedPvs;
1651        }
1652        else if (mShowDistanceWeightedTriangles)
1653        {
1654                return vc->GetPvs().mStats.mDistanceWeightedTriangles;
1655        }
1656        else //if (mShowWeightedTriangles)
1657        {
1658                return vc->GetPvs().mStats.mWeightedTriangles;
1659        }
1660#else
1661        return 0.0f;
1662#endif
1663}
1664
1665
1666void QtGlRendererWidget::ComputeMaxValues(const ViewCellContainer &viewCells,
1667                                                                                  int &maxPvs,
1668                                                                                  int &maxPiercingRays,
1669                                                                                  float &maxRelativeRays,
1670                                                                                  float &maxRcCost)
1671{
1672        maxPvs = -1;
1673        maxPiercingRays = 1; // not zero for savety
1674        maxRelativeRays = Limits::Small; // not zero for savety
1675        maxRcCost = Limits::Small;
1676
1677        for (size_t i = 0; i < viewCells.size(); ++ i)
1678        {
1679                ViewCell *vc = viewCells[i];
1680
1681                if (mShowPvsSizes) // pvs size
1682                {
1683                        //const int p = vc->GetPvs().CountObjectsInPvs();
1684                        const int p = vc->GetPvs().GetSize();
1685                        if (p > maxPvs)
1686                                maxPvs = p;
1687                }
1688                else if (mShowPiercingRays) // relative number of rays
1689                {
1690                        const int piercingRays = vc->GetNumPiercingRays();
1691
1692                        if (piercingRays > maxPiercingRays)
1693                                maxPiercingRays = piercingRays;
1694                }
1695                else if (mShowWeightedRays)
1696                {
1697                        const int piercingRays = vc->GetNumPiercingRays();
1698
1699                        const float relativeArea =
1700                                vc->GetBox().SurfaceArea() / mViewCellsManager->GetViewSpaceBox().SurfaceArea();
1701
1702                        if ((float)piercingRays / relativeArea > maxRelativeRays)
1703                                maxRelativeRays = (float)piercingRays / relativeArea;
1704                }
1705                else if (mShowWeightedCost)
1706                {
1707                        const float rcCost = ComputeRenderCost(vc);
1708                        mViewCellsManager->UpdateScalarPvsCost(vc, rcCost);
1709
1710                        if (rcCost > maxRcCost)
1711                                maxRcCost = rcCost;
1712                }
1713        }
1714}
1715
1716
1717void QtGlRendererWidget::RenderViewCells()
1718{
1719        mUseFalseColors = true;
1720        //glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT | GL_POLYGON_BIT);
1721
1722        glEnable(GL_CULL_FACE);
1723        glCullFace(GL_FRONT);
1724        //glDisable(GL_CULL_FACE);
1725
1726        if (mCutViewCells)
1727        {
1728                double eq[4];
1729                eq[0] = mSceneCutPlane.mNormal.x;
1730                eq[1] = mSceneCutPlane.mNormal.y;
1731                eq[2] = mSceneCutPlane.mNormal.z;
1732                eq[3] = mSceneCutPlane.mD;
1733
1734                glClipPlane(GL_CLIP_PLANE0, eq);
1735                glEnable(GL_CLIP_PLANE0);
1736        }
1737
1738        ViewCellContainer &viewcells = mViewCellsManager->GetViewCells();
1739       
1740        int maxPvs, maxPiercingRays;
1741        float maxRelativeRays, maxRcCost;
1742
1743        ComputeMaxValues(viewcells, maxPvs, maxPiercingRays, maxRelativeRays, maxRcCost);
1744       
1745        // matt: temp hack
1746        //maxRcCost = 5000.0f;
1747        //cout << "maxRcCost: " << maxRcCost << endl;
1748
1749        int i;
1750
1751        // transparency
1752        if (!mUseTransparency)
1753        {
1754                glEnable(GL_DEPTH_TEST);
1755                glDisable(GL_BLEND);
1756        }
1757        else
1758        {
1759                glDisable(GL_DEPTH_TEST);
1760                glEnable(GL_BLEND);
1761
1762                glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1763                //glBlendFunc(GL_SRC_ALPHA, GL_ONE);
1764
1765                for (i = 0; i < viewcells.size(); ++ i)
1766                {
1767                        ViewCell *vc = viewcells[i];
1768
1769                        const float dist = SqrDistance(mDummyViewPoint, vc->GetBox().Center());
1770                        vc->SetDistance(dist);
1771                }
1772
1773                sort(viewcells.begin(), viewcells.end(), nearerThan);
1774        }
1775
1776        //mWireFrame = true;
1777               
1778        // normal rendering
1779        //if (!mShowPvsSizes && !mShowPiercingRays && !mShowWeightedRays && !mShowWeightedCost && !mShowComparison)
1780        if (mUseStandardColors)
1781        {
1782                for (i = 0; i < viewcells.size(); ++ i)
1783                {
1784                        ViewCell *vc = viewcells[i];
1785                        RgbColor c;
1786
1787                        //if (!mShowPvsSizes && !mShowPiercingRays)
1788                        c = vc->GetColor();
1789                       
1790                        glColor3f(c.r, c.g, c.b);
1791
1792                        if (!mHideByCost || (mHidingCost < (vc->GetNumPiercingRays() / (float)maxPiercingRays)))
1793                        {
1794                RenderViewCell(vc);
1795                        }
1796                }
1797        }
1798        else // using specialised colors
1799        {
1800                if (!mShowComparison)
1801                        AssignImportanceByRelativeValue(viewcells, maxPvs, maxPiercingRays, maxRelativeRays, maxRcCost);
1802                else
1803                {
1804                        if (mCompareInfo.empty())
1805                        {
1806                                LogReader reader;
1807                                reader.SetFilename("compare.log");
1808                                int samples;
1809                                reader.Read(samples, mCompareInfo);
1810                        }
1811
1812                        AssignColorByComparison(viewcells, mCompareInfo);
1813                }
1814
1815                glEnable(GL_DEPTH_TEST);       
1816        }
1817       
1818        glEnable(GL_CULL_FACE);
1819        glDisable(GL_CULL_FACE);
1820
1821        glDisable(GL_CLIP_PLANE0);
1822
1823        mUseFalseColors = false;
1824        mWireFrame = false;
1825
1826        glPopAttrib();
1827}
1828
1829
1830void QtGlRendererWidget::AssignImportanceByRelativeValue(const ViewCellContainer &viewCells,
1831                                                                                                                 int &maxPvs,
1832                                                                                                                 int &maxPiercingRays,
1833                                                                                                                 float &maxRelativeRays,
1834                                                                                                                 float &maxRcCost)
1835{
1836        for (size_t i = 0; i < viewCells.size(); ++ i)
1837        {
1838                RgbColor c;
1839                ViewCell *vc = viewCells[i];
1840
1841                float importance;
1842
1843                if (mShowPiercingRays)
1844                {
1845                        importance = mTransferFunction *
1846                                ((float)vc->GetNumPiercingRays() / (float)maxPiercingRays);
1847                }
1848                else if (mShowWeightedRays) // relative number of rays
1849                {
1850                        float relativeArea = vc->GetBox().SurfaceArea() / mViewCellsManager->GetViewSpaceBox().SurfaceArea();
1851
1852                        if (relativeArea < Limits::Small)
1853                                relativeArea = Limits::Small;
1854
1855                        importance = mTransferFunction * ((float)vc->GetNumPiercingRays() / relativeArea) / maxRelativeRays;
1856                }
1857                else if (mShowPvsSizes) // pvs size
1858                {
1859                        importance = mTransferFunction *
1860                                ((float)vc->GetPvs().GetSize() / (float)maxPvs);
1861                } // weighted render cost
1862                else if (mShowWeightedCost)
1863                {
1864                        const float rcCost = mTransferFunction * ComputeRenderCost(vc);
1865                        importance = rcCost / maxRcCost;
1866                }
1867               
1868                if (importance > 1.0f) importance = 1.0f;
1869                // c = RgbColor(importance, 1.0f - importance, 0.0f);
1870                c = RainbowColorMapping(importance);
1871
1872                glColor4f(c.r, c.g, c.b, 1.0f - mTransparency);
1873
1874                if (!mHideByCost || (mHidingCost < importance))
1875                {
1876                        RenderViewCell(vc);
1877                }
1878        }
1879}
1880
1881
1882void QtGlRendererWidget::AssignColorByComparison(const ViewCellContainer &viewcells,
1883                                                                                                 //const ViewCellInfoContainer &infos1,
1884                                                                                                 const ViewCellInfoContainer &compareInfo)
1885{
1886        if (viewcells.size() > compareInfo.size())
1887        {
1888                cerr << "loaded size (" << (int)compareInfo.size()
1889                         << ") does not fit to view cells size (" << (int)viewcells.size() << ")" << endl;
1890                return;
1891        }
1892
1893        //const float maxRatio = 1.0f;
1894        const float maxRatio = 2.0f;
1895        const float minRatio = 0.0f;
1896
1897        const float scale = 1.0f / (maxRatio - minRatio);
1898
1899        for (size_t i = 0; i < viewcells.size(); ++ i)
1900        {
1901                RgbColor c;
1902                ViewCell *vc = viewcells[i];
1903
1904                //ViewCellInfo vc1Info = infos1[i];
1905                ViewCellInfo vc2Info = compareInfo[i];
1906
1907                //const float vcRatio = vc->GetNumPiercingRays() / vc2Info.mPiercingRays + Limits::Small;
1908                float vcRatio = 1.0f;//maxRatio;
1909               
1910                if (vc2Info.mPvsSize > Limits::Small)
1911                        vcRatio = (float)vc->GetPvs().GetSize() / vc2Info.mPvsSize;
1912
1913                // truncate here
1914                if (vcRatio > maxRatio) vcRatio = 1.0f;
1915
1916                const float importance = (vcRatio - minRatio) * scale;
1917       
1918                if (0 && (i < 20))
1919                {
1920                        cout << "pvs1: " << vc->GetPvs().GetSize() << " pvs2: "
1921                                 << compareInfo[i].mPvsSize << " importance: " << importance << endl;
1922                }
1923
1924                // c = RgbColor(importance, 1.0f - importance, 0.0f);
1925                c = RainbowColorMapping(importance);
1926
1927                glColor4f(c.r, c.g, c.b, 1.0f);
1928
1929                if (1)//!mHideByCost || (mHidingCost < importance))
1930                {
1931                        RenderViewCell(vc);
1932                }
1933        }
1934}
1935
1936
1937
1938/**********************************************************************/
1939/*              QtRendererControlWidget implementation                */
1940/**********************************************************************/
1941
1942
1943QGroupBox *QtRendererControlWidget::CreateVisualizationPanel(QWidget *parent)
1944{
1945        QRadioButton *rb1, *rb2, *rb3, *rb4, *rb5;
1946       
1947        rb1 = new QRadioButton("random colors", parent);
1948        rb1->setText("random");
1949        connect(rb1, SIGNAL(toggled(bool)), SIGNAL(SetShowWireFrame(bool)));
1950
1951        // Create a check box to be in the group box
1952        rb2 = new QRadioButton("piercing rays", parent);
1953        rb2->setText("piercing rays");
1954        //vl->addWidget(rb1);
1955        connect(rb2, SIGNAL(toggled(bool)), SIGNAL(SetShowPiercingRays(bool)));
1956
1957        rb3 = new QRadioButton("pvs size", parent);
1958        rb3->setText("pvs size");
1959        connect(rb3, SIGNAL(toggled(bool)), SIGNAL(SetShowPvsSizes(bool)));
1960       
1961        rb4 = new QRadioButton("weighted rays", parent);
1962        rb4->setText("weighted rays");
1963        connect(rb4, SIGNAL(toggled(bool)), SIGNAL(SetShowWeightedRays(bool)));
1964       
1965        rb5 = new QRadioButton("pvs cost", parent);
1966        rb5->setText("pvs cost");
1967        connect(rb5, SIGNAL(toggled(bool)), SIGNAL(SetShowWeightedCost(bool)));
1968
1969        QGroupBox *groupBox = new QGroupBox("PVS Visualization");
1970
1971        QVBoxLayout *vbox2 = new QVBoxLayout;
1972   
1973        vbox2->addWidget(rb1);
1974        vbox2->addWidget(rb2);
1975        vbox2->addWidget(rb3);
1976        vbox2->addWidget(rb4);
1977        vbox2->addWidget(rb5);
1978       
1979        rb5->setChecked(true);
1980
1981        vbox2->addStretch(1);
1982        groupBox->setLayout(vbox2);
1983
1984        return groupBox;
1985}
1986
1987
1988QGroupBox *QtRendererControlWidget::CreateTrafoPanel(QWidget *parent)
1989{
1990        QRadioButton *rb1, *rb2, *rb3;
1991       
1992        rb1 = new QRadioButton("translation", parent);
1993        rb1->setText("translation");
1994        connect(rb1, SIGNAL(toggled(bool)), SIGNAL(SetTranslation(bool)));
1995
1996        // Create a check box to be in the group box
1997        rb2 = new QRadioButton("scale", parent);
1998        rb2->setText("scale");
1999        //vl->addWidget(rb1);
2000        connect(rb2, SIGNAL(toggled(bool)), SIGNAL(SetScale(bool)));
2001
2002        rb3 = new QRadioButton("rotation", parent);
2003        rb3->setText("rotation");
2004        connect(rb3, SIGNAL(toggled(bool)), SIGNAL(SetRotation(bool)));
2005   
2006        QVBoxLayout *vbox2 = new QVBoxLayout;
2007        QGroupBox *groupBox = new QGroupBox("Dynamic Obojects");
2008
2009        vbox2->addWidget(rb1);
2010        vbox2->addWidget(rb2);
2011        vbox2->addWidget(rb3);
2012       
2013        rb1->setChecked(true);
2014
2015        vbox2->addStretch(1);
2016
2017
2018        QPushButton *button = new QPushButton("Update", groupBox);
2019        vbox2->addWidget(button);
2020        connect(button, SIGNAL(clicked()), SIGNAL(UpdateDynamicObjects()));
2021       
2022        button = new QPushButton("Delete", groupBox);
2023        vbox2->addWidget(button);
2024        connect(button, SIGNAL(clicked()), SIGNAL(DeleteDynamicObject()));
2025       
2026        button = new QPushButton("Next object", groupBox);
2027        vbox2->layout()->addWidget(button);
2028        connect(button, SIGNAL(clicked()), SIGNAL(NextObject()));
2029
2030        groupBox->setLayout(vbox2);
2031       
2032        return groupBox;
2033}
2034
2035
2036QGroupBox *QtRendererControlWidget::CreateRenderCostPanel(QWidget *parent)
2037{
2038        QRadioButton *rb1, *rb2, *rb3;
2039       
2040        // Create a check box to be in the group box
2041        rb1 = new QRadioButton("triangles", parent);
2042        rb1->setText("triangles");
2043        connect(rb1, SIGNAL(toggled(bool)), SIGNAL(SetShowWeightedTriangles(bool)));
2044
2045        rb2 = new QRadioButton("distance weighted pvs", parent);
2046        rb2->setText("distance weighted");
2047        connect(rb2, SIGNAL(toggled(bool)), SIGNAL(SetShowDistanceWeightedPvs(bool)));
2048
2049        rb3 = new QRadioButton("distance weighted triangles", parent);
2050        rb3->setText("distance weighted triangles");
2051        connect(rb3, SIGNAL(toggled(bool)), SIGNAL(SetShowDistanceWeightedTriangles(bool)));
2052
2053        QGroupBox *groupBox = new QGroupBox("Render cost options");
2054        QVBoxLayout *vbox2 = new QVBoxLayout;
2055   
2056        vbox2->addWidget(rb1);
2057        vbox2->addWidget(rb2);
2058        vbox2->addWidget(rb3);
2059       
2060        rb1->setChecked(true);
2061
2062        vbox2->addStretch(1);
2063        groupBox->setLayout(vbox2);
2064
2065        return groupBox;
2066}
2067
2068
2069QGroupBox *QtRendererControlWidget::CreateRayVisualizationPanel(QWidget *parent)
2070{
2071        QRadioButton *rb1, *rb2, *rb3, *rb4;
2072       
2073        // Create a check box to be in the group box
2074        rb1 = new QRadioButton("const color", parent);
2075        rb1->setText("const color");
2076        //vl->addWidget(rb1);
2077        connect(rb1, SIGNAL(toggled(bool)), SIGNAL(UseConstColorForRayViz(bool)));
2078
2079        rb2 = new QRadioButton("ray length", parent);
2080        rb2->setText("ray length");
2081        connect(rb2, SIGNAL(toggled(bool)), SIGNAL(UseRayLengthForRayViz(bool)));
2082       
2083        rb3 = new QRadioButton("contribution", parent);
2084        rb3->setText("contribution");
2085        connect(rb3, SIGNAL(toggled(bool)), SIGNAL(SetShowContribution(bool)));
2086       
2087        rb4 = new QRadioButton("distribution", parent);
2088        rb4->setText("distribution");
2089        connect(rb4, SIGNAL(toggled(bool)), SIGNAL(SetShowDistribution(bool)));
2090
2091
2092        ///////////////////////////
2093
2094       
2095        QGroupBox *groupBox = new QGroupBox("Ray visualization");
2096        QVBoxLayout *vbox2 = new QVBoxLayout;
2097   
2098        vbox2->addWidget(rb1);
2099        vbox2->addWidget(rb2);
2100        vbox2->addWidget(rb3);
2101        vbox2->addWidget(rb4);
2102       
2103        rb1->setChecked(true);
2104
2105
2106        QCheckBox *cb = new QCheckBox("Distribution 1", parent);
2107        vbox2->addWidget(cb);
2108        cb->setChecked(true);
2109        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowDistribution1(bool)));
2110
2111        cb = new QCheckBox("Distribution 2", parent);
2112        vbox2->addWidget(cb);
2113        cb->setChecked(true);
2114        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowDistribution2(bool)));
2115
2116        cb = new QCheckBox("Distribution 3", parent);
2117        vbox2->addWidget(cb);
2118        cb->setChecked(true);
2119        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowDistribution3(bool)));
2120       
2121        cb = new QCheckBox("Distribution 4", parent);
2122        vbox2->addWidget(cb);
2123        cb->setChecked(true);
2124        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowDistribution4(bool)));
2125
2126
2127        vbox2->addStretch(1);
2128        groupBox->setLayout(vbox2);
2129
2130        return groupBox;
2131}
2132
2133
2134QtRendererControlWidget::QtRendererControlWidget(QWidget * parent, Qt::WFlags f):
2135QWidget(parent, f)
2136{
2137
2138        QVBoxLayout *vl = new QVBoxLayout;
2139        setLayout(vl);
2140       
2141        //QWidget *vbox;
2142
2143        //vbox = new QGroupBox("Render Controls", this);
2144        //layout()->addWidget(vbox);
2145        //vl = new QVBoxLayout;
2146        //vbox->setLayout(vl);
2147
2148        QLabel *label;
2149        QSlider *slider;
2150        QPushButton *button;
2151
2152#if 0//REMOVE_TEMPORARY
2153
2154        label = new QLabel("Granularity");
2155        //vbox->layout()->addWidget(label);
2156        vl->addWidget(label);
2157
2158        slider = new QSlider(Qt::Horizontal);
2159        vl->addWidget(slider);
2160        slider->show();
2161        slider->setRange(1, 10000);
2162        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2163        slider->setValue(200);
2164
2165        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetViewCellGranularity(int)));
2166
2167        ///////////////////////////
2168
2169        label = new QLabel("Transfer function");
2170        vl->addWidget(label);
2171
2172        slider = new QSlider(Qt::Horizontal);
2173        vl->addWidget(slider);
2174        slider->show();
2175        slider->setRange(1, 10000);
2176        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2177        slider->setValue(100);
2178
2179
2180        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetTransferFunction(int)));
2181
2182        ////////////////////////////////////////7
2183
2184        button = new QPushButton("Update all PVSs");
2185        vl->addWidget(button);
2186        connect(button, SIGNAL(clicked()), SLOT(UpdateAllPvs()));
2187
2188        ////////////////////////////////////////77777
2189
2190        label = new QLabel("Filter size");
2191        vl->addWidget(label);
2192
2193        slider = new QSlider(Qt::Horizontal);
2194        vl->addWidget(slider);
2195        slider->show();
2196        slider->setRange(1, 100);
2197        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2198        slider->setValue(3);
2199
2200        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetVisibilityFilterSize(int)));
2201
2202#endif
2203
2204
2205       
2206        ///////////////////////////////////
2207
2208
2209        QWidget *hbox = new QWidget();
2210        vl->addWidget(hbox);
2211        QHBoxLayout *hlayout = new QHBoxLayout;
2212        hbox->setLayout(hlayout);
2213
2214        QCheckBox *cb = new QCheckBox("Show viewcells", hbox);
2215        hlayout->addWidget(cb);
2216        cb->setChecked(false);
2217        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowViewCells(bool)));
2218       
2219        cb = new QCheckBox("Render errors", hbox);
2220        hlayout->layout()->addWidget(cb);
2221        cb->setChecked(false);
2222        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetRenderErrors(bool)));
2223
2224#if REMOVE_TEMPORARY
2225        cb = new QCheckBox("Render cost curve", hbox);
2226        hlayout->addWidget(cb);
2227        cb->setChecked(false);
2228        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowRenderCost(bool)));
2229#endif
2230        cb = new QCheckBox("Show rays", hbox);
2231        hlayout->addWidget(cb);
2232        cb->setChecked(false);
2233        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowRays(bool)));
2234#if REMOVE_TEMPORARY   
2235        cb = new QCheckBox("Show Comparison", hbox);
2236        hlayout->addWidget(cb);
2237        cb->setChecked(false);
2238        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowComparison(bool)));
2239#endif
2240
2241        //////////////////
2242
2243        QHBoxLayout *vh = new QHBoxLayout;
2244
2245        QGroupBox *myBox = new QGroupBox("Visualization");
2246
2247        myBox->setLayout(vh);
2248        vl->addWidget(myBox, 0, 0);
2249
2250        QGroupBox *groupBox = CreateVisualizationPanel(hbox);
2251        vh->addWidget(groupBox, 0, 0);
2252
2253#if REMOVE_TEMPORARY
2254        QGroupBox *groupBox2 = CreateRenderCostPanel(hbox);
2255        vh->addWidget(groupBox2, 0, 0);
2256       
2257        QGroupBox *groupBox3 = CreateRayVisualizationPanel(hbox);
2258        vh->addWidget(groupBox3, 0, 0);
2259#endif
2260
2261#if 1
2262        QGroupBox *groupBox4 = CreateTrafoPanel(hbox);
2263        vh->addWidget(groupBox4, 0, 0);
2264#endif
2265
2266        //////////////////////////////////
2267
2268        bool tmp = false;
2269        const int range = 1000;
2270
2271        //vbox->resize(800,150);
2272        QWidget *vbox;
2273
2274        vbox = new QGroupBox("Rendering", this);
2275        layout()->addWidget(vbox);
2276
2277        vl = new QVBoxLayout;
2278        vbox->setLayout(vl);
2279
2280
2281        cb = new QCheckBox("Cut view cells", vbox);
2282        vbox->layout()->addWidget(cb);
2283        cb->setChecked(false);
2284        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetCutViewCells(bool)));
2285
2286
2287        slider = new QSlider(Qt::Horizontal, vbox);
2288        vbox->layout()->addWidget(slider);
2289        slider->show();
2290        slider->setRange(0, 1000);
2291        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2292        slider->setValue(1000);
2293
2294        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetSceneCut(int)));
2295
2296
2297        cb = new QCheckBox("Use spatial filter", vbox);
2298        vbox->layout()->addWidget(cb);
2299        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilitySpatialFilter", tmp);
2300        cb->setChecked(tmp);
2301        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetUseSpatialFilter(bool)));
2302
2303
2304        label = new QLabel("Spatial Filter size");
2305        vbox->layout()->addWidget(label);
2306       
2307        slider = new QSlider(Qt::Horizontal, vbox);
2308        vbox->layout()->addWidget(slider);
2309        slider->show();
2310        slider->setRange(1, 100);
2311        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2312        slider->setValue(10);
2313
2314        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetSpatialFilterSize(int)));
2315
2316        ////////////////////////////
2317
2318       
2319        cb = new QCheckBox("Hide view cells by render cost ", vbox);
2320        vbox->layout()->addWidget(cb);
2321        cb->setChecked(false);
2322        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetHideByCost(bool)));
2323
2324        label = new QLabel("Hide by cost");
2325        vbox->layout()->addWidget(label);
2326
2327        // the render cost visualization
2328        slider = new QSlider(Qt::Horizontal, vbox);
2329        vbox->layout()->addWidget(slider);
2330        slider->show();
2331        slider->setRange(0, range);
2332        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2333        slider->setValue(0);
2334        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetHidingCost(int)));
2335
2336        ///////////////////////////////////////////
2337
2338        cb = new QCheckBox("Top View", vbox);
2339        vbox->layout()->addWidget(cb);
2340        cb->setChecked(false);
2341        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetTopView(bool)));
2342
2343
2344        label = new QLabel("Top distance");
2345        vbox->layout()->addWidget(label);
2346       
2347        slider = new QSlider(Qt::Horizontal, vbox);
2348        vbox->layout()->addWidget(slider);
2349        slider->show();
2350        slider->setRange(1, 1000);
2351        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2352        slider->setValue(500);
2353
2354        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetTopDistance(int)));
2355       
2356
2357        ///////////////////////////////////////////
2358#if REMOVE_TEMPORARY
2359        cb = new QCheckBox("Transparency", vbox);
2360        vbox->layout()->addWidget(cb);
2361        cb->setChecked(false);
2362        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetUseTransparency(bool)));
2363
2364        label = new QLabel("Use transparency");
2365        vbox->layout()->addWidget(label);
2366
2367        // the render cost visualization
2368        slider = new QSlider(Qt::Horizontal, vbox);
2369        vbox->layout()->addWidget(slider);
2370        slider->show();
2371        slider->setRange(0, range);
2372        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2373        slider->setValue(0);
2374        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetTransparency(int)));
2375#endif
2376       
2377
2378        //////////////////////////////
2379
2380#if REMOVE_TEMPORARY
2381
2382        cb = new QCheckBox("Cut scene", vbox);
2383        vbox->layout()->addWidget(cb);
2384        cb->setChecked(false);
2385        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetCutScene(bool)));
2386
2387        cb = new QCheckBox("Render boxes", vbox);
2388        vbox->layout()->addWidget(cb);
2389        cb->setChecked(false);
2390        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetRenderBoxes(bool)));
2391
2392        cb = new QCheckBox("Render visibility estimates", vbox);
2393        vbox->layout()->addWidget(cb);
2394        cb->setChecked(false);
2395        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetRenderVisibilityEstimates(bool)));
2396#endif
2397
2398#if REMOVE_TEMPORARY
2399
2400        cb = new QCheckBox("Use filter", vbox);
2401        vbox->layout()->addWidget(cb);
2402        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilityFilter", tmp);
2403        cb->setChecked(tmp);
2404        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetUseFilter(bool)));
2405#endif
2406
2407#if REMOVE_TEMPORARY
2408       
2409        cb = new QCheckBox("Render filter", vbox);
2410        vbox->layout()->addWidget(cb);
2411        cb->setChecked(true);
2412        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetRenderFilter(bool)));
2413
2414        /*vbox = new QGroupBox("PVS Errors", this);
2415        layout()->addWidget(vbox);
2416
2417        vl = new QVBoxLayout;
2418        vbox->setLayout(vl);
2419
2420        button = new QPushButton("Compute Visibility", vbox);
2421        vbox->layout()->addWidget(button);
2422        connect(button, SIGNAL(clicked()), SLOT(ComputeVisibility()));
2423
2424        button = new QPushButton("Stop Computation", vbox);
2425        vbox->layout()->addWidget(button);
2426        connect(button, SIGNAL(clicked()), SLOT(StopComputation()));
2427
2428        button = new QPushButton("Set Random View Point", vbox);
2429        vbox->layout()->addWidget(button);
2430        connect(button, SIGNAL(clicked()), SLOT(SetRandomViewPoint()));*/
2431
2432        button = new QPushButton("Store statistics", vbox);
2433        vbox->layout()->addWidget(button);
2434        connect(button, SIGNAL(clicked()), SIGNAL(StoreStatistics()));
2435
2436#endif
2437
2438#if 0
2439       
2440        button = new QPushButton("Compute GVS", vbox);
2441        vbox->layout()->addWidget(button);
2442        connect(button, SIGNAL(clicked()), SIGNAL(ComputeGVS()));
2443#endif
2444       
2445        button = new QPushButton("Replay view points", vbox);
2446        vbox->layout()->addWidget(button);
2447        connect(button, SIGNAL(clicked()), SIGNAL(ReplayViewPoints()));
2448
2449
2450        /*cb = new QCheckBox("Stats", vbox);
2451        vbox->layout()->addWidget(cb);
2452        cb->setChecked(false);
2453        connect(cb, SIGNAL(toggled(bool)), SIGNAL(StoreStatistics()));*/
2454
2455        if (0)
2456        {
2457                vbox = new QGroupBox("PVS Errors", this);
2458                layout()->addWidget(vbox);
2459
2460                vl = new QVBoxLayout;
2461                vbox->setLayout(vl);
2462
2463                mPvsErrorWidget = new QListWidget(vbox);
2464                vbox->layout()->addWidget(mPvsErrorWidget);
2465
2466                connect(mPvsErrorWidget,
2467                        SIGNAL(doubleClicked(const QModelIndex &)),
2468                        this,
2469                        SLOT(PvsErrorClicked(const QModelIndex &)));
2470
2471                button = new QPushButton("Next Error Frame", vbox);
2472                vbox->layout()->addWidget(button);
2473                connect(button, SIGNAL(clicked(void)), SLOT(FocusNextPvsErrorFrame(void)));
2474        }
2475       
2476        //connect(button, SIGNAL(clicked(void)), SLOT(StoreStatistics(void)));
2477       
2478        //////////////////////////////////////////
2479
2480
2481        setWindowTitle("Preprocessor Control Widget");
2482        adjustSize();
2483}
2484
2485
2486
2487
2488void
2489QtRendererControlWidget::FocusNextPvsErrorFrame(void)
2490{}
2491
2492void
2493QtRendererControlWidget::UpdatePvsErrorItem(int row,
2494                                                                                        GlRendererBuffer::PvsErrorEntry &pvsErrorEntry)
2495{
2496
2497        QListWidgetItem *i = mPvsErrorWidget->item(row);
2498        QString s;
2499        s.sprintf("%5.5f", pvsErrorEntry.mError);
2500        if (i) {
2501                i->setText(s);
2502        } else {
2503                new QListWidgetItem(s, mPvsErrorWidget);
2504        }
2505        mPvsErrorWidget->update();
2506}
2507
2508
2509
2510
2511/*********************************************************************/
2512/*                   QtGlDebuggerWidget implementation               */
2513/*********************************************************************/
2514
2515
2516QtGlDebuggerWidget::QtGlDebuggerWidget(QtGlRendererBuffer *buf, QWidget *parent)
2517: QGLWidget(QGLFormat(QGL::SampleBuffers), parent), mRenderBuffer(buf)
2518{
2519        // create the pbuffer
2520        //pbuffer = new QGLPixelBuffer(QSize(512, 512), format(), this);
2521        //mUpdateTimerId = startTimer(20);
2522        setWindowTitle(("OpenGL pbuffers"));
2523}
2524
2525
2526QtGlDebuggerWidget::~QtGlDebuggerWidget()
2527{
2528        mRenderBuffer->releaseFromDynamicTexture();
2529        glDeleteTextures(1, &dynamicTexture);
2530
2531        DEL_PTR(mRenderBuffer);
2532}
2533
2534
2535void QtGlDebuggerWidget::initializeGL()
2536{
2537        glMatrixMode(GL_PROJECTION);
2538        glLoadIdentity();
2539
2540        glFrustum(-1, 1, -1, 1, 10, 100);
2541        glTranslatef(-0.5f, -0.5f, -0.5f);
2542        glTranslatef(0.0f, 0.0f, -15.0f);
2543        glMatrixMode(GL_MODELVIEW);
2544
2545        glEnable(GL_CULL_FACE);
2546        initCommon();
2547        initPbuffer();
2548
2549}
2550
2551
2552void QtGlDebuggerWidget::resizeGL(int w, int h)
2553{
2554        glViewport(0, 0, w, h);
2555}
2556
2557
2558void QtGlDebuggerWidget::paintGL()
2559{
2560        // draw a spinning cube into the pbuffer..
2561        mRenderBuffer->makeCurrent();
2562
2563        BeamSampleStatistics stats;
2564        mRenderBuffer->SampleBeamContributions(mSourceObject, mBeam, mSamples, stats);
2565
2566        glFlush();
2567
2568        // rendering directly to a texture is not supported on X11, unfortunately
2569        mRenderBuffer->updateDynamicTexture(dynamicTexture);
2570
2571        // and use the pbuffer contents as a texture when rendering the
2572        // background and the bouncing cubes
2573        makeCurrent();
2574        glBindTexture(GL_TEXTURE_2D, dynamicTexture);
2575        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2576
2577        // draw the background
2578        glMatrixMode(GL_MODELVIEW);
2579        glPushMatrix();
2580        glLoadIdentity();
2581        glMatrixMode(GL_PROJECTION);
2582        glPushMatrix();
2583        glLoadIdentity();
2584
2585        glPopMatrix();
2586        glMatrixMode(GL_MODELVIEW);
2587        glPopMatrix();
2588}
2589
2590
2591void QtGlDebuggerWidget::initPbuffer()
2592{
2593        // set up the pbuffer context
2594        mRenderBuffer->makeCurrent();
2595        // generate a texture that has the same size/format as the pbuffer
2596        dynamicTexture = mRenderBuffer->generateDynamicTexture();
2597        // bind the dynamic texture to the pbuffer - this is a no-op under X11
2598        mRenderBuffer->bindToDynamicTexture(dynamicTexture);
2599        //makeCurrent();
2600}
2601
2602
2603void QtGlDebuggerWidget::initCommon()
2604{
2605        glEnable(GL_TEXTURE_2D);
2606        glEnable(GL_DEPTH_TEST);
2607
2608        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
2609}
2610
2611
2612void QtGlRendererWidget::_RenderColoredPvs()
2613{
2614        // note: could be done more efficiently using color buffers
2615        mPvsSize = mPvsCache.mPvs.GetSize();
2616
2617        ObjectPvsIterator it = mPvsCache.mPvs.GetIterator();
2618
2619        PvsData pvsData;
2620
2621        while (it.HasMoreEntries())
2622        {
2623                Intersectable *obj = it.Next(pvsData);
2624
2625                RgbColor color;
2626
2627                //cerr << "sumpdf: " << pvsData.mSumPdf << endl;
2628                if (mUseRandomColorPerPvsObject)
2629                {
2630                        if (obj->Type() == Intersectable::KD_INTERSECTABLE)
2631                        {
2632                                KdIntersectable *kdint = static_cast<KdIntersectable *>(obj);
2633
2634                                if (kdint->mGenericIdx == -1)
2635                                {
2636                                        kdint->mGenericIdx = (int)mColors.size();
2637                                        mColors.push_back(RandomColor(0, 1));
2638                                }
2639                                color = mColors[kdint->mGenericIdx];
2640                        }
2641                }
2642                else
2643                {
2644                        color = RainbowColorMapping(mTransferFunction * log10(pvsData.mSumPdf + 1));
2645                }
2646
2647                glColor3f(color.r, color.g, color.b);
2648
2649                mUseForcedColors = true;
2650                RenderIntersectable(obj);
2651                mUseForcedColors = false;
2652        }
2653}
2654
2655
2656void QtGlRendererWidget::UpdateDynamicObjects()
2657{
2658        preprocessor->ScheduleUpdateDynamicObjects(); 
2659}
2660
2661
2662void QtGlRendererWidget::ReplayViewPoints()
2663{
2664        ViewCellPointsList *vcPoints = mViewCellsManager->GetViewCellPointsList();
2665
2666        ViewCellPointsList::const_iterator vit, vit_end = vcPoints->end();
2667
2668        sViewPointsList.clear();
2669
2670        for (vit = vcPoints->begin(); vit != vit_end; ++ vit)
2671        {
2672                ViewCellPoints *vp = *vit;
2673
2674                SimpleRayContainer::const_iterator rit, rit_end = vp->second.end();
2675       
2676                for (rit = vp->second.begin(); rit != rit_end; ++ rit)
2677                {
2678                        sViewPointsList.push_back(*rit);
2679                }
2680        }
2681
2682        if (!sViewPointsList.empty())
2683        {
2684                cout << "replaying " << (int)sViewPointsList.size() << " view points " << endl;
2685               
2686                mReplayMode = true;
2687               
2688                if (mExportFrameBuffer)
2689                        GetPreprocessor()->mSynchronize = true;
2690
2691                sCurrentSamples = GetPreprocessor()->mCurrentSamples;
2692                sViewPointsListIt = sViewPointsList.begin();
2693        }
2694}
2695
2696
2697
2698Vector3 QtGlRendererWidget::Unproject(int x, int y)
2699{
2700        // swap y coordinate
2701        y = GetHeight() - y;
2702
2703        // HACK: should come from camera!
2704        double projection[16];
2705        glGetDoublev(GL_PROJECTION_MATRIX, projection);
2706        double modelview[16];
2707        glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
2708
2709        const int viewport[4] = {0,0, GetWidth(), GetHeight()};
2710
2711        RenderScene();
2712
2713        float z;
2714        glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &z);
2715       
2716        GLdouble rx, ry, rz;
2717        gluUnProject(x, y, z, modelview, projection, viewport, &rx, &ry, &rz);
2718
2719        return Vector3(rx, ry, rz);
2720}
2721
2722
2723int QtGlRendererWidget::FindDynamicObject(float x, float y)
2724{
2725
2726        if (GetPreprocessor()->mDynamicObjects.empty())
2727                return -1;
2728
2729        makeCurrent();
2730       
2731        // this is the same as in every OpenGL picking example
2732        const int maxSize = 512;
2733       
2734        // see below for an explanation on the buffer content
2735        GLuint buffer[maxSize];
2736        glSelectBuffer(maxSize, buffer);
2737       
2738        // enter select mode
2739        glRenderMode(GL_SELECT);
2740        glInitNames();
2741        glPushName(0);
2742       
2743        glMatrixMode(GL_PROJECTION);
2744        glPushMatrix();
2745        glLoadIdentity();
2746
2747        glViewport(0, 0, width(), height());
2748
2749        GLint viewport[4];
2750        glGetIntegerv(GL_VIEWPORT, viewport);
2751
2752        const float w = 1.0f;
2753
2754        //gluPickMatrix(x, y, 1000.0, 1000.0, viewport);
2755        gluPickMatrix((GLdouble)x, (GLdouble)(viewport[3] - y), w, w, viewport);
2756
2757        GLfloat aspect = (GLfloat) width() / height();
2758        gluPerspective(70.0f, aspect, 0.1f, 2.0f * Magnitude(mSceneGraph->GetBox().Diagonal()));
2759       
2760        glMatrixMode(GL_MODELVIEW);
2761        glPushMatrix();
2762        glLoadIdentity();
2763        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2764       
2765       
2766        SetupCamera();
2767
2768        for (GLuint i = 0; i < GetPreprocessor()->mDynamicObjects.size(); ++ i)
2769        {
2770                glLoadName(i);
2771                _RenderDynamicObject(GetPreprocessor()->mDynamicObjects[i]);
2772        }
2773
2774        glFlush();
2775        glPopMatrix();
2776
2777        glMatrixMode(GL_PROJECTION);
2778        glPopMatrix();
2779
2780        int hits = glRenderMode(GL_RENDER);
2781
2782        // finally release the rendering context again
2783        if (!hits)
2784        {
2785                cout << "no object picked" << endl;
2786                return -1;
2787        }
2788
2789        //processHits(hits, buffer);
2790       
2791        // Each hit takes 4 items in the buffer.
2792        // The first item is the number of names on the name stack when the hit occured.
2793        // The second item is the minimum z value of all the verticies that intersected
2794        // the viewing area at the time of the hit. The third item is the maximum z value
2795        // of all the vertices that intersected the viewing area at the time of the hit
2796        // and the last item is the content of the name stack at the time of the hit
2797        // (name of the object). We are only interested in the object name
2798        // (number of the surface).
2799        // return the name of the clicked surface
2800        return buffer[3];
2801}
2802
2803
2804void QtGlRendererWidget::DeleteDynamicObject()
2805{
2806        Preprocessor *p = GetPreprocessor();
2807
2808        if ((mCurrentDynamicObjectIdx < 0) ||
2809                (mCurrentDynamicObjectIdx >= p->mDynamicObjects.size()))
2810                return;
2811
2812        cout << "deleting object" << endl;
2813
2814        SceneGraphLeaf *l = p->mDynamicObjects[mCurrentDynamicObjectIdx];
2815
2816        // tell the preprocessor that an object was deleted
2817        p->ObjectRemoved(l);
2818
2819        swap(p->mDynamicObjects[mCurrentDynamicObjectIdx], p->mDynamicObjects.back());
2820        p->mDynamicObjects.pop_back();
2821
2822        delete l;
2823
2824        mCurrentDynamicObjectIdx = -1;
2825}       
2826
2827}
Note: See TracBrowser for help on using the repository browser.