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

Revision 2679, 64.4 KB checked in by mattausch, 16 years ago (diff)

found error with qglpixelbuffer

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