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

Revision 2685, 64.2 KB checked in by mattausch, 16 years ago (diff)

fixed bugs: pixel measurement for pgv now working, fixed renderpvs crash

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
571        if (mUseVbos)
572                glBindBufferARB(GL_ARRAY_BUFFER_ARB, mVboId);
573
574        mUseFalseColors = false;
575
576        int offset = (int)mObjects.size() * 3;
577        char *arrayPtr = mUseVbos ? NULL : (char *)mData;
578
579        glVertexPointer(3, GL_FLOAT, 0, (char *)arrayPtr);
580        glNormalPointer(GL_FLOAT, 0, (char *)arrayPtr + offset * sizeof(Vector3));
581        glDrawElements(GL_TRIANGLES, mIndexBufferSize, GL_UNSIGNED_INT, mIndices);
582
583#if DYNAMIC_OBJECTS_HACK
584        // handle dynamic objects
585        DynamicObjectsContainer::const_iterator dit, dit_end = mDynamicObjects.end();
586
587        for (dit = mDynamicObjects.begin(); dit != dit_end; ++ dit)
588        {
589                _RenderDynamicObject(*dit);
590        }
591#endif
592}
593
594
595void QtGlRendererWidget::PreparePvs(const ObjectPvs &pvs)
596{
597        int indexBufferSize = 0;
598       
599        // hack: mail not working with multiple threads
600        KdNode::NewMail2();
601
602        mPvsSize = pvs.GetSize();
603
604#if DYNAMIC_OBJECTS_HACK
605        mDynamicObjects.clear();
606#endif
607
608        ObjectPvsIterator it = pvs.GetIterator();
609
610        while (it.HasMoreEntries())
611        {
612                Intersectable *obj = it.Next();
613                switch (obj->Type())
614                {
615                case Intersectable::KD_INTERSECTABLE:
616                        {
617                                KdNode *node = static_cast<KdIntersectable *>(obj)->GetItem();
618                                _UpdatePvsIndices(node, indexBufferSize);
619                        }
620                        break;
621#if DYNAMIC_OBJECTS_HACK
622#if USE_TRANSFORMED_MESH_INSTANCE_HACK
623
624                case Intersectable::TRANSFORMED_MESH_INSTANCE:
625                        mDynamicObjects.push_back(static_cast<TransformedMeshInstance *>(obj));
626                        break;
627
628#else
629                case Intersectable::SCENEGRAPHLEAF_INTERSECTABLE:
630                        mDynamicObjects.push_back(static_cast<SceneGraphLeafIntersectable *>(obj)->GetItem());
631                        break;
632#endif
633#endif
634                default:
635                        cerr << "PreparePvs: type " << Intersectable::GetTypeName(obj) << " not handled yet" << endl;
636                }
637        }
638
639        mIndexBufferSize = indexBufferSize;
640}
641
642
643void QtGlRendererWidget::VisualizePvs()
644{
645        if (mUseVbos)
646                glBindBufferARB(GL_ARRAY_BUFFER_ARB, mVboId);
647
648        ++ mCurrentFrame;
649
650        EnableDrawArrays();
651               
652        if (mDetectEmptyViewSpace)
653                glEnable(GL_CULL_FACE);
654        else
655                glDisable(GL_CULL_FACE);
656
657        ViewCell *viewcell = NULL;
658        viewcell = mViewCellsManager->GetViewCell(mViewPoint, true);
659
660        if (viewcell)
661        {
662#if 0
663                // copy the pvs so that it can be filtered ...
664                if (PvsChanged(viewcell))
665                {
666                        mPvsCache.Reset();
667                        mPvsCache.mViewCell = viewcell;
668                        mPvsCache.mUnfilteredPvsSize = viewcell->GetPvs().GetSize();
669
670                        if (mUseSpatialFilter)
671                        {
672                                //mMutex.lock();
673                                // mSpatialFilter size is in range 0.001 - 0.1
674                                mViewCellsManager->ApplyFilter2(viewcell,
675                                        mUseFilter,
676                                        100.0f * mSpatialFilterSize,
677                                        mPvsCache.mPvs,         
678                                        &mPvsCache.filteredBoxes);
679                                //mPvsCache.mPvs = pvs;
680                                //mMutex.unlock();
681                                //cout << "pvs size: " << mPvsCache.mPvs.GetSize() << endl;
682                        }
683                        else
684                        {
685                                mPvsCache.mPvs = viewcell->GetPvs();
686                        }
687                       
688                        // update the indices for rendering
689                        PreparePvs(mPvsCache.mPvs);
690                        emit PvsUpdated();
691                        mCurrentPvsCost = mPvsCache.mPvs.EvalPvsCost();
692                }
693#else
694       
695                PreparePvs(viewcell->GetPvs());
696                emit PvsUpdated();
697
698#endif
699
700                // Render PVS
701                if (mUseSpatialFilter && mRenderBoxes)
702                {
703                        for (size_t i=0; i < mPvsCache.filteredBoxes.size(); ++ i)
704                        {
705                                RenderBox(mPvsCache.filteredBoxes[i]);
706                        }
707                }
708                else
709                {
710                        if (!mRenderVisibilityEstimates && !mUseRandomColorPerPvsObject)
711                                _RenderPvs();
712                        else
713                                _RenderColoredPvs();
714                }
715
716                if (mRenderFilter)
717                {
718                        mWireFrame = true;
719                        RenderIntersectable(viewcell);
720                       
721                        mWireFrame = false;
722                }
723                mCurrentPvsCost = viewcell->GetPvs().EvalPvsCost();
724        }
725        else
726        {
727                //OcclusionQuery *query = mOcclusionQueries[0];
728                //query->BeginQuery();
729               
730                RenderScene();
731
732                //query->EndQuery();
733                //int pixels = query->GetQueryResult();
734                //cout << " pixels: " << pixels;
735        }
736
737        //cout << "vp: " << mViewPoint << " vd: " << mViewDirection << endl;
738}
739
740float
741QtGlRendererWidget::RenderErrors()
742{
743        float pErrorPixels = -1.0f;
744
745        SetupCamera();
746        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
747
748        glPushAttrib(GL_ENABLE_BIT);
749
750        glStencilFunc(GL_EQUAL, 0x0, 0x1);
751        glStencilOp(GL_KEEP, GL_KEEP, GL_INCR);
752
753        glColor3f(0.6f, 0.6f, 0.6f);
754
755        // Render PVS
756        VisualizePvs();
757
758        glEnable(GL_STENCIL_TEST);
759
760        glDisable(GL_LIGHTING);
761
762        SetupCamera();
763
764        mUseForcedColors = true;
765
766        glColor3f(1.0f, 0.0f, 0.0f);
767
768        OcclusionQuery *query = mOcclusionQueries[0];
769        query->BeginQuery();
770
771        RenderScene();
772
773        mUseForcedColors = false;
774
775        query->EndQuery();
776
777        glDisable(GL_STENCIL_TEST);
778        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
779
780        glPopAttrib();
781
782        // reenable other state
783        //  int wait=0;
784        //  while (!query.ResultAvailable()) {
785        //      wait++;
786        //  }
787
788        int pixelCount = query->GetQueryResult();
789        pErrorPixels = ((float)pixelCount) / (GetWidth() * GetHeight());
790       
791        if (0) cout << "error pixels=" << pixelCount << endl;
792
793        mRenderError = pErrorPixels;
794
795        return pErrorPixels;
796}
797
798
799void QtGlRendererWidget::timerEvent(QTimerEvent *event)
800{
801        //std::cout << "Timer ID:" << event->timerId();
802        update();
803}
804
805
806void QtGlRendererWidget::mousePressEvent(QMouseEvent *e)
807{
808        int x = e->pos().x();
809        int y = e->pos().y();
810
811        mousePoint.x = x;
812        mousePoint.y = y;
813
814}
815
816void QtGlRendererWidget::mouseReleaseEvent(QMouseEvent *e)
817{
818
819  if (e->modifiers() & Qt::AltModifier)
820        if (mCurrentDynamicObjectIdx >= 0) {
821          // preprocessor->ScheduleUpdateDynamicObjects();
822        }
823}
824
825void
826QtGlRendererWidget::mouseMoveEvent(QMouseEvent *e)
827{
828        float MOVE_SENSITIVITY = Magnitude(mSceneGraph->GetBox().Diagonal())*1e-3;
829        float TURN_SENSITIVITY = 0.1f;
830        float TILT_SENSITIVITY = 32.0 ;
831        float TURN_ANGLE= M_PI / 36.0 ;
832
833        int x = e->pos().x();
834        int y = e->pos().y();
835
836        int diffx = -(mousePoint.x - x);
837        int diffy = -(mousePoint.y - y);
838
839        const float t = 1.0f;
840
841        if (e->modifiers() & Qt::ControlModifier)
842        {
843                mViewPoint.y += (y-mousePoint.y)*MOVE_SENSITIVITY / 2.0;
844                mViewPoint.x += (x-mousePoint.x)*MOVE_SENSITIVITY / 2.0;
845        }
846#if DYNAMIC_OBJECTS_HACK
847        else if (e->modifiers() & Qt::AltModifier)
848        {
849                if (mCurrentDynamicObjectIdx >= 0)
850                {
851                        Matrix4x4 tm;
852
853                        switch (mTrafoType)
854                        {
855                        case 0:
856                                {
857                                  if (e->modifiers() & Qt::ShiftModifier) {
858                                        const Vector3 transl(0, diffy, 0);
859                                        tm = TranslationMatrix(transl);
860                                 
861                                  } else {
862                                        const Vector3 transl(diffx, 0, diffy);
863                                        tm = TranslationMatrix(transl);
864                                  }
865                                }
866                                break;
867                        case 1:
868                                {
869                                        float scalef = 1.0f + 0.01f * (diffx + diffy);
870                                        if (scalef < 0.9) scalef = 0.9f;
871                                        else if (scalef > 1.1f) scalef = 1.1f;
872                                        tm = ScaleMatrix(scalef, scalef, scalef);
873                                }
874                                break;
875                        case 2:
876                                {
877                                  //                                    tm = RotationXMatrix(diffx) * RotationYMatrix(diffy);
878                                  tm = RotationYMatrix(diffx);
879                                }
880                                break;
881                        default:
882                                cerr << "not implemented" << endl;
883                        }
884
885                        SceneGraphLeaf *l =
886                          mViewCellsManager->GetPreprocessor()->mDynamicObjects[mCurrentDynamicObjectIdx];
887                        l->ApplyTransform(tm);
888                       
889                        updateGL();
890                }
891        }
892#endif
893        else
894        {
895                mViewPoint += mViewDirection*((mousePoint.y - y)*MOVE_SENSITIVITY);
896                float adiff = TURN_ANGLE*(x - mousePoint.x)*-TURN_SENSITIVITY;
897                float angle = atan2(mViewDirection.x, mViewDirection.z);
898                mViewDirection.x = sin(angle + adiff);
899                mViewDirection.z = cos(angle + adiff);
900        }
901
902        mousePoint.x = x;
903        mousePoint.y = y;
904
905        updateGL();
906}
907
908
909void
910QtGlRendererWidget::resizeGL(int w, int h)
911{
912        SetupCameraProjection(w, h);
913        updateGL();
914}
915
916
917void QtGlRendererWidget::paintGL()
918{
919        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
920
921        if (1)
922        {
923                SetupCameraProjection(width(), height());
924                SetupCamera();
925
926                if (mRenderErrors)
927                {
928                        RenderErrors();
929                }
930                else
931                {
932                        glColor3f(0.6f, 0.6f, 0.6f);
933                        VisualizePvs();
934                }
935
936                if (mShowRays)
937                {
938                        RenderRays(mViewCellsManager->mVizBuffer.GetRays(), mRayVisualizationMethod, mShowDistribution, 1);
939                }
940        }
941
942        RenderInfo();
943        mFrame ++;
944        //      cout<<"vp="<<mViewPoint<<" vd="<<mViewDirection<<endl;
945}
946
947
948void
949QtGlRendererWidget::SetupCamera()
950{
951        if (!mTopView)
952                GlRenderer::SetupCamera();
953        else
954        {
955                if (0)
956                {
957                        float dist = Magnitude(mSceneGraph->GetBox().Diagonal())*0.05;
958                        Vector3 pos = mViewPoint - dist*Vector3(mViewDirection.x,
959                                -1,
960                                mViewDirection.y);
961
962                        Vector3 target = mViewPoint + dist*mViewDirection;
963                        Vector3 up(0,1,0);
964
965                        glLoadIdentity();
966                        gluLookAt(pos.x, pos.y, pos.z,
967                                target.x, target.y, target.z,
968                                up.x, up.y, up.z);
969                }
970                else
971                {
972                        float dist = Magnitude(mSceneGraph->GetBox().Diagonal()) * mTopDistance;
973                        Vector3 pos = mViewPoint  + dist * Vector3(0,   1, 0);
974
975                        Vector3 target = mViewPoint;
976                        Vector3 up(mViewDirection.x, 0, mViewDirection.z);
977
978                        glLoadIdentity();
979                        gluLookAt(pos.x, pos.y, pos.z,
980                                target.x, target.y, target.z,
981                                up.x, up.y, up.z);
982
983                }
984        }
985
986}
987
988
989void
990QtGlRendererWidget::keyPressEvent ( QKeyEvent * e )
991{
992        switch (e->key())
993        {
994case Qt::Key_E:
995        mRenderErrors = !mRenderErrors;
996        updateGL();
997        break;
998case Qt::Key_R:
999        mUseRandomColorPerPvsObject = !mUseRandomColorPerPvsObject;;
1000        updateGL();
1001        break;
1002case Qt::Key_T:
1003        mTopView = !mTopView;
1004        SetupCameraProjection(width(), height());
1005        updateGL();
1006        break;
1007case Qt::Key_V:
1008        mRenderViewCells = !mRenderViewCells;
1009        updateGL();
1010        break;
1011case Qt::Key_P:
1012        // set random viewpoint
1013        mViewCellsManager->GetViewPoint(mViewPoint);
1014        updateGL();
1015        break;
1016case Qt::Key_S: {
1017        // set view poitn and direction
1018        QString text;
1019        bool ok;
1020        text.sprintf("%f %f %f", mViewPoint.x, mViewPoint.y, mViewPoint.z);
1021        text = QInputDialog::getText(this,
1022                "Enter a view point",
1023                "",
1024                QLineEdit::Normal,
1025                text,
1026                &ok);
1027        if (!ok)
1028                break;
1029
1030        if (sscanf(text.toAscii(), "%f %f %f", &mViewPoint.x, &mViewPoint.y, &mViewPoint.z) == 3) {
1031                text.sprintf("%f %f %f", mViewDirection.x, mViewDirection.y, mViewDirection.z);
1032                text = QInputDialog::getText(this,
1033                        "Enter a direction",
1034                        "",
1035                        QLineEdit::Normal,
1036                        text,
1037                        &ok);
1038                if (!ok)
1039                        break;
1040                if (sscanf(text.toAscii(), "%f %f %f", &mViewDirection.x,
1041                        &mViewDirection.y, &mViewDirection.z) == 3) {
1042                                updateGL();
1043                        }
1044                        break;
1045        }
1046                                }
1047default:
1048        cerr << "unknown key" << endl;
1049        e->ignore();
1050        break;
1051        }
1052}
1053
1054
1055
1056QtGlRendererWidget::QtGlRendererWidget(
1057                                                                           SceneGraph *sceneGraph,
1058                                                                           ViewCellsManager *viewcells,
1059                                                                           KdTree *tree,
1060                                                                           QWidget * parent,
1061                                                                           const QGLWidget * shareWidget,
1062                                                                           Qt::WFlags f
1063                                                                           )
1064                                                                           :
1065GlRendererWidget(sceneGraph, viewcells, tree), QGLWidget(QGLFormat(QGL::SampleBuffers), parent, shareWidget, f)
1066{
1067        mPreprocessorThread = NULL;
1068        mTopView = false;
1069        mRenderViewCells = false;
1070        mTopDistance = 1.0f;
1071        mCutViewCells = false;
1072        mCutScene = false;
1073        mRenderErrors = false;
1074        mRenderBoxes = false;
1075        mRenderFilter = true;
1076        mRenderVisibilityEstimates = false;
1077        //mRenderVisibilityEstimates = true;
1078
1079        mComputeGVS = false;
1080        mUseRandomColorPerPvsObject = false;
1081
1082        mHideByCost = false;
1083        mUseTransparency = false;
1084
1085        mTransferFunction = 1.0f;
1086        mIndexBufferSize = 0;
1087
1088        const int delay = 250; // in milliseconds
1089        timerId = startTimer(delay);
1090
1091        bool tmp;
1092
1093        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilityFilter", tmp );
1094        mUseFilter = tmp;
1095
1096        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilitySpatialFilter", tmp );
1097        mUseSpatialFilter = tmp;
1098
1099        //mLogWriter = new LogWriter("myfile.out");
1100
1101        mShowRenderCost = false;
1102        mShowPvsSizes = false;
1103        mShowComparison = false;
1104        mShowPiercingRays = false;
1105        mShowWeightedRays = false;
1106        mUseStandardColors = false;
1107        mShowWeightedCost = true;
1108
1109        mShowDistanceWeightedPvs = true;
1110        mShowDistanceWeightedTriangles = false;
1111        mShowWeightedTriangles = false;
1112        mShowDistribution = 15;
1113        mCurrentDynamicObjectIdx = -1;
1114
1115        mSpatialFilterSize = 0.01;
1116        mPvsSize = 0;
1117        mRayVisualizationMethod = 0;
1118        mTrafoType = 0;
1119
1120        mRenderError = 0.0f;
1121        mShowRays = false;
1122
1123        SetSceneCut(1000);
1124        mControlWidget = new QtRendererControlWidget(NULL);
1125
1126        connect(mControlWidget, SIGNAL(SetViewCellGranularity(int)), this, SLOT(SetViewCellGranularity(int)));
1127        connect(mControlWidget, SIGNAL(SetTransferFunction(int)), this, SLOT(SetTransferFunction(int)));
1128
1129        connect(mControlWidget, SIGNAL(UpdateAllPvs()), this, SLOT(UpdateAllPvs()));
1130        connect(mControlWidget, SIGNAL(ComputeVisibility()), this, SLOT(ComputeVisibility()));
1131        connect(mControlWidget, SIGNAL(StopComputation()), this, SLOT(StopComputation()));
1132        connect(mControlWidget, SIGNAL(SetRandomViewPoint()), this,     SLOT(SetRandomViewPoint()));
1133        connect(mControlWidget, SIGNAL(StoreStatistics(void)), this, SLOT(StoreStatistics(void)));
1134        connect(mControlWidget, SIGNAL(ComputeGVS(void)), this, SLOT(ComputeGVS(void)));
1135        connect(mControlWidget, SIGNAL(LoadObject(void)), this, SLOT(LoadObject(void)));
1136
1137        connect(mControlWidget, SIGNAL(SetSceneCut(int)), this, SLOT(SetSceneCut(int)));
1138        connect(mControlWidget, SIGNAL(SetTopDistance(int)), this, SLOT(SetTopDistance(int)));
1139        connect(mControlWidget, SIGNAL(SetTransparency(int)), this, SLOT(SetTransparency(int)));
1140
1141        connect(mControlWidget, SIGNAL(SetVisibilityFilterSize(int)), this, SLOT(SetVisibilityFilterSize(int)));
1142        connect(mControlWidget, SIGNAL(SetSpatialFilterSize(int)), this, SLOT(SetSpatialFilterSize(int)));
1143        connect(mControlWidget, SIGNAL(SetHidingCost(int)), this, SLOT(SetHidingCost(int)));
1144
1145        connect(mControlWidget, SIGNAL(SetShowViewCells(bool)), this, SLOT(SetShowViewCells(bool)));
1146        connect(mControlWidget, SIGNAL(SetShowRenderCost(bool)), this, SLOT(SetShowRenderCost(bool)));
1147        connect(mControlWidget, SIGNAL(SetUseTransparency(bool)), this, SLOT(SetUseTransparency(bool)));
1148        connect(mControlWidget, SIGNAL(SetShowPvsSizes(bool)), this, SLOT(SetShowPvsSizes(bool)));
1149        connect(mControlWidget, SIGNAL(SetShowComparison(bool)), this, SLOT(SetShowComparison(bool)));
1150        connect(mControlWidget, SIGNAL(SetTopView(bool)), this, SLOT(SetTopView(bool)));
1151        connect(mControlWidget, SIGNAL(SetCutViewCells(bool)), this, SLOT(SetCutViewCells(bool)));
1152        connect(mControlWidget, SIGNAL(SetHideByCost(bool)), this, SLOT(SetHideByCost(bool)));
1153        connect(mControlWidget, SIGNAL(SetCutScene(bool)), this, SLOT(SetCutScene(bool)));
1154        connect(mControlWidget, SIGNAL(SetRenderErrors(bool)), this, SLOT(SetRenderErrors(bool)));
1155        connect(mControlWidget, SIGNAL(SetRenderBoxes(bool)), this, SLOT(SetRenderBoxes(bool)));
1156        connect(mControlWidget, SIGNAL(SetRenderFilter(bool)), this, SLOT(SetRenderFilter(bool)));
1157        connect(mControlWidget, SIGNAL(SetRenderVisibilityEstimates(bool)), this, SLOT(SetRenderVisibilityEstimates(bool)));
1158        connect(mControlWidget, SIGNAL(SetUseFilter(bool)), this, SLOT(SetUseFilter(bool)));
1159        connect(mControlWidget, SIGNAL(SetUseSpatialFilter(bool)), this, SLOT(SetUseSpatialFilter(bool)));
1160        connect(mControlWidget, SIGNAL(SetShowPiercingRays(bool)), this, SLOT(SetShowPiercingRays(bool)));
1161        connect(mControlWidget, SIGNAL(SetShowWireFrame(bool)), this, SLOT(SetShowWireFrame(bool)));
1162        connect(mControlWidget, SIGNAL(SetShowWeightedRays(bool)), this, SLOT(SetShowWeightedRays(bool)));
1163        connect(mControlWidget, SIGNAL(SetShowWeightedCost(bool)), this, SLOT(SetShowWeightedCost(bool)));
1164
1165        connect(mControlWidget, SIGNAL(SetShowDistanceWeightedTriangles(bool)), this, SLOT(SetShowDistanceWeightedTriangles(bool)));
1166        connect(mControlWidget, SIGNAL(SetShowDistanceWeightedPvs(bool)), this, SLOT(SetShowDistanceWeightedPvs(bool)));
1167        connect(mControlWidget, SIGNAL(SetShowWeightedTriangles(bool)), this, SLOT(SetShowWeightedTriangles(bool)));
1168
1169        connect(mControlWidget, SIGNAL(UseConstColorForRayViz(bool)), this, SLOT(UseConstColorForRayViz(bool)));
1170        connect(mControlWidget, SIGNAL(UseRayLengthForRayViz(bool)), this, SLOT(UseRayLengthForRayViz(bool)));
1171        connect(mControlWidget, SIGNAL(SetShowContribution(bool)), this, SLOT(SetShowContribution(bool)));
1172        connect(mControlWidget, SIGNAL(SetShowDistribution(bool)), this, SLOT(SetShowDistribution(bool)));
1173
1174        connect(mControlWidget, SIGNAL(SetShowDistribution1(bool)), this, SLOT(SetShowDistribution1(bool)));
1175        connect(mControlWidget, SIGNAL(SetShowDistribution2(bool)), this, SLOT(SetShowDistribution2(bool)));
1176        connect(mControlWidget, SIGNAL(SetShowDistribution3(bool)), this, SLOT(SetShowDistribution3(bool)));
1177        connect(mControlWidget, SIGNAL(SetShowDistribution4(bool)), this, SLOT(SetShowDistribution4(bool)));
1178
1179        connect(mControlWidget, SIGNAL(SetShowRays(bool)), this, SLOT(SetShowRays(bool)));
1180
1181        connect(mControlWidget, SIGNAL(SetTranslation(bool)), this, SLOT(SetTranslation(bool)));
1182        connect(mControlWidget, SIGNAL(SetRotation(bool)), this, SLOT(SetRotation(bool)));
1183        connect(mControlWidget, SIGNAL(SetScale(bool)), this, SLOT(SetScale(bool)));
1184
1185        connect(mControlWidget, SIGNAL(UpdateDynamicObjects()), this, SLOT(UpdateDynamicObjects()));
1186
1187        setWindowTitle("PVS Visualization");
1188
1189        // setting the main window size here
1190        resize(800, 600);
1191        //resize(640, 400);
1192       
1193        mControlWidget->show();
1194}
1195
1196void
1197QtGlRendererWidget::UpdateAllPvs()
1198{
1199        // $$ does not work so far:(
1200        mViewCellsManager->UpdatePvsForEvaluation();
1201        //      mViewCellsManager->FinalizeViewCells(false);
1202}
1203
1204void
1205QtGlRendererWidget::ComputeVisibility()
1206{
1207        cerr<<"Compute Visibility called!\n"<<endl;
1208        if (!mPreprocessorThread->isRunning())
1209                mPreprocessorThread->RunThread();
1210}
1211
1212void
1213QtGlRendererWidget::StopComputation()
1214{
1215        cerr<<"stop computation called!\n"<<endl;
1216        mViewCellsManager->GetPreprocessor()->mStopComputation = true;
1217}
1218
1219void
1220QtGlRendererWidget::SetRandomViewPoint()
1221{
1222        cerr<<"setting random view point!\n"<<endl;
1223        mViewCellsManager->GetViewPoint(mViewPoint);
1224        updateGL();
1225}
1226
1227
1228void QtGlRendererWidget::StoreStatistics()
1229{
1230        cerr<<"storing statistics!\n"<<endl;
1231        const int currentSamples = mViewCellsManager->GetPreprocessor()->mCurrentSamples;
1232
1233        cout<<"**********************************************" << endl;
1234        cout << "reached " << currentSamples << " samples " << " => writing file" << endl;
1235               
1236        LogWriter writer;
1237        writer.SetFilename("compare.log");
1238        writer.Write(currentSamples, mViewCellsManager->GetViewCells());
1239        cout << "finished writing file" << endl;
1240        mCompareInfo.clear();
1241        updateGL();
1242}
1243
1244
1245void QtGlRendererWidget::LoadObject()
1246{
1247        string filename("../data/teapot.bn");
1248        //string filename("../data/cube.obj");
1249       
1250        cout << "Loading model << " << filename << endl;
1251
1252        ++ mCurrentDynamicObjectIdx;
1253
1254        if (mViewCellsManager->GetPreprocessor()->LoadDynamicGeometry(filename)) {
1255         
1256          cout << "Loading finished" << endl;
1257        } else
1258          cerr << "Loading failed" << endl;
1259       
1260    updateGL();
1261}
1262
1263void
1264QtGlRendererWidget::RenderRenderCost()
1265{
1266        static vector<float> costFunction;
1267        static float maxCost = -1;
1268        if (costFunction.size()==0) {
1269                ViewCellsTree *tree = mViewCellsManager->GetViewCellsTree();
1270                if (tree) {
1271                        tree->GetCostFunction(costFunction);
1272                        maxCost = -1;
1273                        for (int i=0;  i < costFunction.size(); i++) {
1274                                //                cout<<i<<":"<<costFunction[i]<<" ";
1275                                // update cost function to an absolute value based on the total geometry count
1276                                costFunction[i] *= mSceneGraph->GetSize();
1277                                if (costFunction[i] > maxCost)
1278                                        maxCost = costFunction[i];
1279                        }
1280                }
1281        }
1282
1283
1284        int currentPos = (int)mViewCellsManager->GetViewCells().size();
1285        float currentCost= -1;
1286
1287        if (currentPos < costFunction.size())
1288                currentCost = costFunction[currentPos];
1289#if 1   
1290        cout<<"costFunction.size()="<<(int)costFunction.size()<<endl;
1291        cout<<"CP="<<currentPos<<endl;
1292        cout<<"MC="<<maxCost<<endl;
1293        cout<<"CC="<<currentCost<<endl;
1294#endif
1295        if (costFunction.size()) {
1296                float scaley = 1.0f/log10(maxCost);
1297                float scalex = 1.0f/(float)costFunction.size();
1298
1299                glDisable(GL_DEPTH_TEST);
1300                // init ortographic projection
1301                glMatrixMode(GL_PROJECTION);
1302
1303                glPushMatrix();
1304
1305                glLoadIdentity();
1306                gluOrtho2D(0, 1.0f, 0, 1.0f);
1307
1308                glTranslatef(0.1f, 0.1f, 0.0f);
1309                glScalef(0.8f, 0.8f, 1.0f);
1310                glMatrixMode(GL_MODELVIEW);
1311                glLoadIdentity();
1312
1313                glColor3f(1.0f,0,0);
1314                glBegin(GL_LINE_STRIP);
1315                //        glVertex3f(0,0,0);
1316
1317                for (int i=0;  i < costFunction.size(); i++) {
1318                        float x =  i*scalex;
1319                        float y = log10(costFunction[i])*scaley;
1320                        glVertex3f(x,y,0.0f);
1321                }
1322                glEnd();
1323
1324                glColor3f(1.0f,0,0);
1325                glBegin(GL_LINES);
1326                float x =  currentPos*scalex;
1327                glVertex3f(x,0.0,0.0f);
1328                glVertex3f(x,1.0f,0.0f);
1329                glEnd();
1330
1331                glColor3f(0.0f,0,0);
1332                // show a grid
1333                glBegin(GL_LINE_LOOP);
1334                glVertex3f(0,0,0.0f);
1335                glVertex3f(1,0,0.0f);
1336                glVertex3f(1,1,0.0f);
1337                glVertex3f(0,1,0.0f);
1338                glEnd();
1339
1340                glBegin(GL_LINES);
1341                for (int i=0;  i < costFunction.size(); i += 1000) {
1342                        float x =  i*scalex;
1343                        glVertex3f(x,0.0,0.0f);
1344                        glVertex3f(x,1.0f,0.0f);
1345                }
1346
1347                for (int i=0;  pow(10.0f, i) < maxCost; i+=1) {
1348                        float y = i*scaley;
1349                        //              QString s;
1350                        //              s.sprintf("%d", (int)pow(10,i));
1351                        //              renderText(width()/2+5, y*height(), s);
1352                        glVertex3f(0.0f, y, 0.0f);
1353                        glVertex3f(1.0f, y, 0.0f);
1354                }
1355
1356                glEnd();
1357
1358
1359                // restore the projection matrix
1360                glMatrixMode(GL_PROJECTION);
1361                glPopMatrix();
1362                glMatrixMode(GL_MODELVIEW);
1363                glEnable(GL_DEPTH_TEST);
1364
1365        }
1366
1367
1368
1369}
1370
1371void
1372QtGlRendererWidget::RenderInfo()
1373{
1374
1375        QString s;
1376
1377        int vc = 0;
1378        if (mViewCellsManager)
1379                vc = (int)mViewCellsManager->GetViewCells().size();
1380
1381        int filter = 0;
1382        if (mViewCellsManager)
1383                filter = mViewCellsManager->GetMaxFilterSize();
1384
1385        glColor3f(0.0f, 0.0f, 1.0f);
1386
1387#if REMOVE_TEMPORARY
1388        s.sprintf("frame:%04d viewpoint:(%4.1f,%4.1f,%4.1f) dir:(%4.1f,%4.1f,%4.1f)",
1389                mFrame,
1390                mViewPoint.x,
1391                mViewPoint.y,
1392                mViewPoint.z,
1393                mViewDirection.x,
1394                mViewDirection.y,
1395                mViewDirection.z
1396                );
1397
1398        renderText(20, 20, s);
1399
1400        s.sprintf("viewcells:%04d filter:%04d pvs:%04d error:%5.5f %",
1401                vc,
1402                filter,
1403                mPvsSize,
1404                mRenderError*100.0f);
1405
1406        renderText(20, 40, s);
1407#endif
1408
1409        QFont font40; font40.setPointSize(30);
1410        //s.sprintf("PVS: %04d", mPvsSize);
1411        //renderText(20, 40, s, font40);
1412       
1413        //s.sprintf("RAW TRI: %07d", mViewCellsManager->GetPreprocessor()->mGenericStats);
1414        //renderText(290, 40, s, font40);
1415        //s.sprintf("PVS TRI: %07d", mViewCellsManager->GetPreprocessor()->mGenericStats2);
1416        //renderText(290, 70, s, font40);
1417
1418        s.sprintf("PVS TRI: %07d", (int)mCurrentPvsCost);
1419        renderText(290, 70, s, font40);
1420        //renderText(290, 70, s, font40);
1421
1422}
1423
1424
1425void
1426QtGlRendererWidget::SetViewCellGranularity(int number)
1427{
1428        if (mViewCellsManager)
1429        {
1430                //      mViewCellsManager->SetMaxFilterSize(number);
1431
1432                // $$ tmp off
1433                mViewCellsManager->CollectViewCells(number);
1434
1435                // $$ does not work so far:(
1436                //      mViewCellsManager->UpdatePvsForEvaluation();
1437                //      mViewCellsManager->FinalizeViewCells(false);
1438        }
1439        updateGL();
1440}
1441
1442void
1443QtGlRendererWidget::SetVisibilityFilterSize(int number)
1444{
1445        if (mViewCellsManager)
1446                mViewCellsManager->SetMaxFilterSize(number);
1447
1448        mPvsCache.Reset();
1449        updateGL();
1450}
1451
1452void
1453QtGlRendererWidget::SetSpatialFilterSize(int number)
1454{
1455        mSpatialFilterSize = 1e-3*number;
1456        mPvsCache.Reset();
1457        updateGL();
1458}
1459
1460void
1461QtGlRendererWidget::SetSceneCut(int number)
1462{
1463        // assume the cut plane can only be aligned with xz plane
1464        // shift it along y according to number, which is percentage of the bounding
1465        // box position
1466        if (mViewCellsManager)
1467        {
1468                const float f = number / 1000.0f;
1469                AxisAlignedBox3 box = mViewCellsManager->GetViewSpaceBox();
1470                Vector3 p = (1.0f - f) * box.Min() + f * box.Max();
1471                mSceneCutPlane.mNormal = Vector3(0, -1, 0);
1472                mSceneCutPlane.mD = -DotProd(mSceneCutPlane.mNormal, p);
1473
1474                updateGL();
1475        }
1476}
1477
1478void
1479QtGlRendererWidget::SetHidingCost(int number)
1480{
1481        mHidingCost = (float)number / 1000.0f;
1482}
1483
1484
1485void
1486QtGlRendererWidget::SetTopDistance(int number)
1487{
1488        mTopDistance = number / 1000.0f;
1489        updateGL();
1490}
1491
1492void QtGlRendererWidget::SetTransparency(int number)
1493{
1494        mTransparency = number / 1000.0f;
1495        updateGL();
1496}
1497
1498#if 0
1499float QtGlRendererWidget::ComputeRenderCost(ViewCell *vc)
1500{
1501        ObjectPvs basePvs;
1502       
1503        basePvs = vc->CopyPvs();
1504        ObjectPvsIterator pit = basePvs.GetIterator();
1505
1506        float renderCost = 0;
1507
1508        //cout << "cost vis: " << mShowDistanceWeightedPvs << " " << " " << mShowDistanceWeightedTriangles << " " << mShowWeightedTriangles << endl;
1509       
1510        // first mark all objects from this pvs
1511        while (pit.HasMoreEntries())   
1512        {
1513                KdIntersectable *kdObj = static_cast<KdIntersectable *>(pit.Next());
1514
1515                if (mShowDistanceWeightedPvs)
1516                {
1517                        const AxisAlignedBox3 box = kdObj->GetBox();
1518
1519                        const float dist = SqrDistance(vc->GetBox().Center(), box.Center());
1520                        renderCost += 1.0f / dist;
1521                }
1522                else if (mShowDistanceWeightedTriangles)
1523                {
1524                        const AxisAlignedBox3 box = kdObj->GetBox();
1525
1526                        const float dist = SqrDistance(vc->GetBox().Center(), box.Center());
1527                        renderCost += kdObj->ComputeNumTriangles() / dist;
1528                }
1529                else //if (mShowWeightedTriangles)
1530                {
1531                        renderCost += kdObj->ComputeNumTriangles();
1532                }
1533                //if (pit.Next()->Mail();
1534        }
1535
1536        return renderCost;
1537}
1538#else
1539
1540float QtGlRendererWidget::ComputeRenderCost(ViewCell *vc)
1541{
1542        float renderCost = 0;
1543
1544#ifdef USE_VERBOSE_PVS
1545        if (mShowDistanceWeightedPvs)
1546        {
1547                return vc->GetPvs().mStats.mDistanceWeightedPvs;
1548        }
1549        else if (mShowDistanceWeightedTriangles)
1550        {
1551                return vc->GetPvs().mStats.mDistanceWeightedTriangles;
1552        }
1553        else //if (mShowWeightedTriangles)
1554        {
1555                return vc->GetPvs().mStats.mWeightedTriangles;
1556        }
1557#else
1558        return 0.0f;
1559#endif
1560}
1561#endif
1562
1563
1564
1565void QtGlRendererWidget::ComputeMaxValues(const ViewCellContainer &viewCells,
1566                                                                                  int &maxPvs,
1567                                                                                  int &maxPiercingRays,
1568                                                                                  float &maxRelativeRays,
1569                                                                                  float &maxRcCost)
1570{
1571        maxPvs = -1;
1572        maxPiercingRays = 1; // not zero for savety
1573        maxRelativeRays = Limits::Small; // not zero for savety
1574        maxRcCost = Limits::Small;
1575
1576        for (size_t i = 0; i < viewCells.size(); ++ i)
1577        {
1578                ViewCell *vc = viewCells[i];
1579
1580                if (mShowPvsSizes) // pvs size
1581                {
1582                        //const int p = vc->GetPvs().CountObjectsInPvs();
1583                        const int p = vc->GetPvs().GetSize();
1584                        if (p > maxPvs)
1585                                maxPvs = p;
1586                }
1587                else if (mShowPiercingRays) // relative number of rays
1588                {
1589                        const int piercingRays = vc->GetNumPiercingRays();
1590
1591                        if (piercingRays > maxPiercingRays)
1592                                maxPiercingRays = piercingRays;
1593                }
1594                else if (mShowWeightedRays)
1595                {
1596                        const int piercingRays = vc->GetNumPiercingRays();
1597
1598                        const float relativeArea =
1599                                vc->GetBox().SurfaceArea() / mViewCellsManager->GetViewSpaceBox().SurfaceArea();
1600
1601                        if ((float)piercingRays / relativeArea > maxRelativeRays)
1602                                maxRelativeRays = (float)piercingRays / relativeArea;
1603                }
1604                else if (mShowWeightedCost)
1605                {
1606                        const float rcCost = ComputeRenderCost(vc);
1607                        mViewCellsManager->UpdateScalarPvsCost(vc, rcCost);
1608
1609                        if (rcCost > maxRcCost)
1610                                maxRcCost = rcCost;
1611                }
1612        }
1613}
1614
1615
1616void QtGlRendererWidget::RenderViewCells()
1617{
1618        mUseFalseColors = true;
1619        //glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT | GL_POLYGON_BIT);
1620
1621        glEnable(GL_CULL_FACE);
1622        glCullFace(GL_FRONT);
1623        //glDisable(GL_CULL_FACE);
1624
1625        if (mCutViewCells)
1626        {
1627                double eq[4];
1628                eq[0] = mSceneCutPlane.mNormal.x;
1629                eq[1] = mSceneCutPlane.mNormal.y;
1630                eq[2] = mSceneCutPlane.mNormal.z;
1631                eq[3] = mSceneCutPlane.mD;
1632
1633                glClipPlane(GL_CLIP_PLANE0, eq);
1634                glEnable(GL_CLIP_PLANE0);
1635        }
1636
1637        ViewCellContainer &viewcells = mViewCellsManager->GetViewCells();
1638       
1639        int maxPvs, maxPiercingRays;
1640        float maxRelativeRays, maxRcCost;
1641
1642        ComputeMaxValues(viewcells, maxPvs, maxPiercingRays, maxRelativeRays, maxRcCost);
1643       
1644        // matt: temp hack
1645        //maxRcCost = 5000.0f;
1646        //cout << "maxRcCost: " << maxRcCost << endl;
1647
1648        int i;
1649
1650        // transparency
1651        if (!mUseTransparency)
1652        {
1653                glEnable(GL_DEPTH_TEST);
1654                glDisable(GL_BLEND);
1655        }
1656        else
1657        {
1658                glDisable(GL_DEPTH_TEST);
1659                glEnable(GL_BLEND);
1660
1661                glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1662                //glBlendFunc(GL_SRC_ALPHA, GL_ONE);
1663
1664                for (i = 0; i < viewcells.size(); ++ i)
1665                {
1666                        ViewCell *vc = viewcells[i];
1667
1668                        const float dist = SqrDistance(mDummyViewPoint, vc->GetBox().Center());
1669                        vc->SetDistance(dist);
1670                }
1671
1672                sort(viewcells.begin(), viewcells.end(), nearerThan);
1673        }
1674
1675        //mWireFrame = true;
1676               
1677        // normal rendering
1678        //if (!mShowPvsSizes && !mShowPiercingRays && !mShowWeightedRays && !mShowWeightedCost && !mShowComparison)
1679        if (mUseStandardColors)
1680        {
1681                for (i = 0; i < viewcells.size(); ++ i)
1682                {
1683                        ViewCell *vc = viewcells[i];
1684                        RgbColor c;
1685
1686                        //if (!mShowPvsSizes && !mShowPiercingRays)
1687                        c = vc->GetColor();
1688                       
1689                        glColor3f(c.r, c.g, c.b);
1690
1691                        if (!mHideByCost || (mHidingCost < (vc->GetNumPiercingRays() / (float)maxPiercingRays)))
1692                        {
1693                RenderViewCell(vc);
1694                        }
1695                }
1696        }
1697        else // using specialised colors
1698        {
1699                if (!mShowComparison)
1700                        AssignImportanceByRelativeValue(viewcells, maxPvs, maxPiercingRays, maxRelativeRays, maxRcCost);
1701                else
1702                {
1703                        if (mCompareInfo.empty())
1704                        {
1705                                LogReader reader;
1706                                reader.SetFilename("compare.log");
1707                                int samples;
1708                                reader.Read(samples, mCompareInfo);
1709                        }
1710
1711                        AssignColorByComparison(viewcells, mCompareInfo);
1712                }
1713
1714                glEnable(GL_DEPTH_TEST);       
1715        }
1716       
1717        glEnable(GL_CULL_FACE);
1718        glDisable(GL_CULL_FACE);
1719
1720        glDisable(GL_CLIP_PLANE0);
1721
1722        mUseFalseColors = false;
1723        mWireFrame = false;
1724
1725        glPopAttrib();
1726}
1727
1728
1729void QtGlRendererWidget::AssignImportanceByRelativeValue(const ViewCellContainer &viewCells,
1730                                                                                                                 int &maxPvs,
1731                                                                                                                 int &maxPiercingRays,
1732                                                                                                                 float &maxRelativeRays,
1733                                                                                                                 float &maxRcCost)
1734{
1735        for (size_t i = 0; i < viewCells.size(); ++ i)
1736        {
1737                RgbColor c;
1738                ViewCell *vc = viewCells[i];
1739
1740                float importance;
1741
1742                if (mShowPiercingRays)
1743                {
1744                        importance = mTransferFunction *
1745                                ((float)vc->GetNumPiercingRays() / (float)maxPiercingRays);
1746                }
1747                else if (mShowWeightedRays) // relative number of rays
1748                {
1749                        float relativeArea = vc->GetBox().SurfaceArea() / mViewCellsManager->GetViewSpaceBox().SurfaceArea();
1750
1751                        if (relativeArea < Limits::Small)
1752                                relativeArea = Limits::Small;
1753
1754                        importance = mTransferFunction * ((float)vc->GetNumPiercingRays() / relativeArea) / maxRelativeRays;
1755                }
1756                else if (mShowPvsSizes) // pvs size
1757                {
1758                        importance = mTransferFunction *
1759                                ((float)vc->GetPvs().GetSize() / (float)maxPvs);
1760                } // weighted render cost
1761                else if (mShowWeightedCost)
1762                {
1763                        const float rcCost = mTransferFunction * ComputeRenderCost(vc);
1764                        importance = rcCost / maxRcCost;
1765                }
1766if (importance > 1.0f) importance = 1.0f;
1767                // c = RgbColor(importance, 1.0f - importance, 0.0f);
1768                c = RainbowColorMapping(importance);
1769
1770                glColor4f(c.r, c.g, c.b, 1.0f - mTransparency);
1771
1772                if (!mHideByCost || (mHidingCost < importance))
1773                {
1774                        RenderViewCell(vc);
1775                }
1776        }
1777}
1778
1779
1780void QtGlRendererWidget::AssignColorByComparison(const ViewCellContainer &viewcells,
1781                                                                                                 //const ViewCellInfoContainer &infos1,
1782                                                                                                 const ViewCellInfoContainer &compareInfo)
1783{
1784        if (viewcells.size() > compareInfo.size())
1785        {
1786                cerr << "loaded size (" << (int)compareInfo.size()
1787                         << ") does not fit to view cells size (" << (int)viewcells.size() << ")" << endl;
1788                return;
1789        }
1790
1791        //const float maxRatio = 1.0f;
1792        const float maxRatio = 2.0f;
1793        const float minRatio = 0.0f;
1794
1795        const float scale = 1.0f / (maxRatio - minRatio);
1796
1797        for (size_t i = 0; i < viewcells.size(); ++ i)
1798        {
1799                RgbColor c;
1800                ViewCell *vc = viewcells[i];
1801
1802                //ViewCellInfo vc1Info = infos1[i];
1803                ViewCellInfo vc2Info = compareInfo[i];
1804
1805                //const float vcRatio = vc->GetNumPiercingRays() / vc2Info.mPiercingRays + Limits::Small;
1806                float vcRatio = 1.0f;//maxRatio;
1807               
1808                if (vc2Info.mPvsSize > Limits::Small)
1809                        vcRatio = (float)vc->GetPvs().GetSize() / vc2Info.mPvsSize;
1810
1811                // truncate here
1812                if (vcRatio > maxRatio) vcRatio = 1.0f;
1813
1814                const float importance = (vcRatio - minRatio) * scale;
1815       
1816                if (0 && (i < 20))
1817                {
1818                        cout << "pvs1: " << vc->GetPvs().GetSize() << " pvs2: " << compareInfo[i].mPvsSize << " importance: " << importance << endl;
1819                }
1820
1821                // c = RgbColor(importance, 1.0f - importance, 0.0f);
1822                c = RainbowColorMapping(importance);
1823
1824                glColor4f(c.r, c.g, c.b, 1.0f);
1825
1826                if (1)//!mHideByCost || (mHidingCost < importance))
1827                {
1828                        RenderViewCell(vc);
1829                }
1830        }
1831}
1832
1833
1834
1835/**********************************************************************/
1836/*              QtRendererControlWidget implementation                */
1837/**********************************************************************/
1838
1839
1840QGroupBox *QtRendererControlWidget::CreateVisualizationPanel(QWidget *parent)
1841{
1842        QRadioButton *rb1, *rb2, *rb3, *rb4, *rb5;
1843       
1844        rb1 = new QRadioButton("random colors", parent);
1845        rb1->setText("random");
1846        connect(rb1, SIGNAL(toggled(bool)), SIGNAL(SetShowWireFrame(bool)));
1847
1848        // Create a check box to be in the group box
1849        rb2 = new QRadioButton("piercing rays", parent);
1850        rb2->setText("piercing rays");
1851        //vl->addWidget(rb1);
1852        connect(rb2, SIGNAL(toggled(bool)), SIGNAL(SetShowPiercingRays(bool)));
1853
1854        rb3 = new QRadioButton("pvs size", parent);
1855        rb3->setText("pvs size");
1856        connect(rb3, SIGNAL(toggled(bool)), SIGNAL(SetShowPvsSizes(bool)));
1857       
1858        rb4 = new QRadioButton("weighted rays", parent);
1859        rb4->setText("weighted rays");
1860        connect(rb4, SIGNAL(toggled(bool)), SIGNAL(SetShowWeightedRays(bool)));
1861       
1862        rb5 = new QRadioButton("pvs cost", parent);
1863        rb5->setText("pvs cost");
1864        connect(rb5, SIGNAL(toggled(bool)), SIGNAL(SetShowWeightedCost(bool)));
1865
1866        QGroupBox *groupBox = new QGroupBox("PVS Visualization");
1867
1868        QVBoxLayout *vbox2 = new QVBoxLayout;
1869   
1870        vbox2->addWidget(rb1);
1871        vbox2->addWidget(rb2);
1872        vbox2->addWidget(rb3);
1873        vbox2->addWidget(rb4);
1874        vbox2->addWidget(rb5);
1875       
1876        rb5->setChecked(true);
1877
1878        vbox2->addStretch(1);
1879        groupBox->setLayout(vbox2);
1880
1881        return groupBox;
1882}
1883
1884
1885QGroupBox *QtRendererControlWidget::CreateTrafoPanel(QWidget *parent)
1886{
1887        QRadioButton *rb1, *rb2, *rb3;
1888       
1889        rb1 = new QRadioButton("translation", parent);
1890        rb1->setText("translation");
1891        connect(rb1, SIGNAL(toggled(bool)), SIGNAL(SetTranslation(bool)));
1892
1893        // Create a check box to be in the group box
1894        rb2 = new QRadioButton("scale", parent);
1895        rb2->setText("scale");
1896        //vl->addWidget(rb1);
1897        connect(rb2, SIGNAL(toggled(bool)), SIGNAL(SetScale(bool)));
1898
1899        rb3 = new QRadioButton("rotation", parent);
1900        rb3->setText("rotation");
1901        connect(rb3, SIGNAL(toggled(bool)), SIGNAL(SetRotation(bool)));
1902   
1903        QVBoxLayout *vbox2 = new QVBoxLayout;
1904        QGroupBox *groupBox = new QGroupBox("Trafo types");
1905
1906        vbox2->addWidget(rb1);
1907        vbox2->addWidget(rb2);
1908        vbox2->addWidget(rb3);
1909       
1910        rb1->setChecked(true);
1911
1912        vbox2->addStretch(1);
1913
1914
1915        QPushButton *button = new QPushButton("Update", groupBox);
1916        vbox2->addWidget(button);
1917        connect(button, SIGNAL(clicked()), SIGNAL(UpdateDynamicObjects()));
1918       
1919       
1920        groupBox->setLayout(vbox2);
1921       
1922        return groupBox;
1923}
1924
1925
1926QGroupBox *QtRendererControlWidget::CreateRenderCostPanel(QWidget *parent)
1927{
1928        QRadioButton *rb1, *rb2, *rb3;
1929       
1930        // Create a check box to be in the group box
1931        rb1 = new QRadioButton("triangles", parent);
1932        rb1->setText("triangles");
1933        connect(rb1, SIGNAL(toggled(bool)), SIGNAL(SetShowWeightedTriangles(bool)));
1934
1935        rb2 = new QRadioButton("distance weighted pvs", parent);
1936        rb2->setText("distance weighted");
1937        connect(rb2, SIGNAL(toggled(bool)), SIGNAL(SetShowDistanceWeightedPvs(bool)));
1938
1939        rb3 = new QRadioButton("distance weighted triangles", parent);
1940        rb3->setText("distance weighted triangles");
1941        connect(rb3, SIGNAL(toggled(bool)), SIGNAL(SetShowDistanceWeightedTriangles(bool)));
1942
1943        QGroupBox *groupBox = new QGroupBox("Render cost options");
1944        QVBoxLayout *vbox2 = new QVBoxLayout;
1945   
1946        vbox2->addWidget(rb1);
1947        vbox2->addWidget(rb2);
1948        vbox2->addWidget(rb3);
1949       
1950        rb1->setChecked(true);
1951
1952        vbox2->addStretch(1);
1953        groupBox->setLayout(vbox2);
1954
1955        return groupBox;
1956}
1957
1958
1959QGroupBox *QtRendererControlWidget::CreateRayVisualizationPanel(QWidget *parent)
1960{
1961        QRadioButton *rb1, *rb2, *rb3, *rb4;
1962       
1963        // Create a check box to be in the group box
1964        rb1 = new QRadioButton("const color", parent);
1965        rb1->setText("const color");
1966        //vl->addWidget(rb1);
1967        connect(rb1, SIGNAL(toggled(bool)), SIGNAL(UseConstColorForRayViz(bool)));
1968
1969        rb2 = new QRadioButton("ray length", parent);
1970        rb2->setText("ray length");
1971        connect(rb2, SIGNAL(toggled(bool)), SIGNAL(UseRayLengthForRayViz(bool)));
1972       
1973        rb3 = new QRadioButton("contribution", parent);
1974        rb3->setText("contribution");
1975        connect(rb3, SIGNAL(toggled(bool)), SIGNAL(SetShowContribution(bool)));
1976       
1977        rb4 = new QRadioButton("distribution", parent);
1978        rb4->setText("distribution");
1979        connect(rb4, SIGNAL(toggled(bool)), SIGNAL(SetShowDistribution(bool)));
1980
1981
1982        ///////////////////////////
1983
1984       
1985        QGroupBox *groupBox = new QGroupBox("Ray visualization");
1986        QVBoxLayout *vbox2 = new QVBoxLayout;
1987   
1988        vbox2->addWidget(rb1);
1989        vbox2->addWidget(rb2);
1990        vbox2->addWidget(rb3);
1991        vbox2->addWidget(rb4);
1992       
1993        rb1->setChecked(true);
1994
1995
1996        QCheckBox *cb = new QCheckBox("Distribution 1", parent);
1997        vbox2->addWidget(cb);
1998        cb->setChecked(true);
1999        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowDistribution1(bool)));
2000
2001        cb = new QCheckBox("Distribution 2", parent);
2002        vbox2->addWidget(cb);
2003        cb->setChecked(true);
2004        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowDistribution2(bool)));
2005
2006        cb = new QCheckBox("Distribution 3", parent);
2007        vbox2->addWidget(cb);
2008        cb->setChecked(true);
2009        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowDistribution3(bool)));
2010       
2011        cb = new QCheckBox("Distribution 4", parent);
2012        vbox2->addWidget(cb);
2013        cb->setChecked(true);
2014        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowDistribution4(bool)));
2015
2016
2017        vbox2->addStretch(1);
2018        groupBox->setLayout(vbox2);
2019
2020        return groupBox;
2021}
2022
2023
2024QtRendererControlWidget::QtRendererControlWidget(QWidget * parent, Qt::WFlags f):
2025QWidget(parent, f)
2026{
2027
2028        QVBoxLayout *vl = new QVBoxLayout;
2029        setLayout(vl);
2030       
2031        //QWidget *vbox;
2032
2033        //vbox = new QGroupBox("Render Controls", this);
2034        //layout()->addWidget(vbox);
2035        //vl = new QVBoxLayout;
2036        //vbox->setLayout(vl);
2037
2038        QLabel *label;
2039        QSlider *slider;
2040        QPushButton *button;
2041
2042#if 0//REMOVE_TEMPORARY
2043
2044        label = new QLabel("Granularity");
2045        //vbox->layout()->addWidget(label);
2046        vl->addWidget(label);
2047
2048        slider = new QSlider(Qt::Horizontal);
2049        vl->addWidget(slider);
2050        slider->show();
2051        slider->setRange(1, 10000);
2052        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2053        slider->setValue(200);
2054
2055        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetViewCellGranularity(int)));
2056
2057        ///////////////////////////
2058
2059        label = new QLabel("Transfer function");
2060        vl->addWidget(label);
2061
2062        slider = new QSlider(Qt::Horizontal);
2063        vl->addWidget(slider);
2064        slider->show();
2065        slider->setRange(1, 10000);
2066        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2067        slider->setValue(100);
2068
2069
2070        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetTransferFunction(int)));
2071
2072        ////////////////////////////////////////7
2073
2074        button = new QPushButton("Update all PVSs");
2075        vl->addWidget(button);
2076        connect(button, SIGNAL(clicked()), SLOT(UpdateAllPvs()));
2077
2078        ////////////////////////////////////////77777
2079
2080        label = new QLabel("Filter size");
2081        vl->addWidget(label);
2082
2083        slider = new QSlider(Qt::Horizontal);
2084        vl->addWidget(slider);
2085        slider->show();
2086        slider->setRange(1, 100);
2087        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2088        slider->setValue(3);
2089
2090        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetVisibilityFilterSize(int)));
2091
2092#endif
2093
2094
2095       
2096        ///////////////////////////////////
2097
2098
2099        QWidget *hbox = new QWidget();
2100        vl->addWidget(hbox);
2101        QHBoxLayout *hlayout = new QHBoxLayout;
2102        hbox->setLayout(hlayout);
2103
2104        QCheckBox *cb = new QCheckBox("Show viewcells", hbox);
2105        hlayout->addWidget(cb);
2106        cb->setChecked(false);
2107        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowViewCells(bool)));
2108       
2109        cb = new QCheckBox("Render errors", hbox);
2110        hlayout->layout()->addWidget(cb);
2111        cb->setChecked(false);
2112        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetRenderErrors(bool)));
2113
2114#if REMOVE_TEMPORARY
2115        cb = new QCheckBox("Render cost curve", hbox);
2116        hlayout->addWidget(cb);
2117        cb->setChecked(false);
2118        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowRenderCost(bool)));
2119#endif
2120        cb = new QCheckBox("Show rays", hbox);
2121        hlayout->addWidget(cb);
2122        cb->setChecked(false);
2123        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowRays(bool)));
2124#if REMOVE_TEMPORARY   
2125        cb = new QCheckBox("Show Comparison", hbox);
2126        hlayout->addWidget(cb);
2127        cb->setChecked(false);
2128        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetShowComparison(bool)));
2129#endif
2130
2131        //////////////////
2132
2133        QHBoxLayout *vh = new QHBoxLayout;
2134
2135        QGroupBox *myBox = new QGroupBox("Visualization");
2136
2137        myBox->setLayout(vh);
2138        vl->addWidget(myBox, 0, 0);
2139
2140        QGroupBox *groupBox = CreateVisualizationPanel(hbox);
2141        vh->addWidget(groupBox, 0, 0);
2142
2143#if REMOVE_TEMPORARY
2144        QGroupBox *groupBox2 = CreateRenderCostPanel(hbox);
2145        vh->addWidget(groupBox2, 0, 0);
2146       
2147        QGroupBox *groupBox3 = CreateRayVisualizationPanel(hbox);
2148        vh->addWidget(groupBox3, 0, 0);
2149
2150        QGroupBox *groupBox4 = CreateTrafoPanel(hbox);
2151        vh->addWidget(groupBox4, 0, 0);
2152#endif
2153
2154        //////////////////////////////////
2155
2156        bool tmp = false;
2157        const int range = 1000;
2158
2159        //vbox->resize(800,150);
2160        QWidget *vbox;
2161
2162        vbox = new QGroupBox("Rendering", this);
2163        layout()->addWidget(vbox);
2164
2165        vl = new QVBoxLayout;
2166        vbox->setLayout(vl);
2167
2168
2169        cb = new QCheckBox("Cut view cells", vbox);
2170        vbox->layout()->addWidget(cb);
2171        cb->setChecked(false);
2172        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetCutViewCells(bool)));
2173
2174
2175        slider = new QSlider(Qt::Horizontal, vbox);
2176        vbox->layout()->addWidget(slider);
2177        slider->show();
2178        slider->setRange(0, 1000);
2179        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2180        slider->setValue(1000);
2181
2182        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetSceneCut(int)));
2183
2184
2185        cb = new QCheckBox("Use spatial filter", vbox);
2186        vbox->layout()->addWidget(cb);
2187        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilitySpatialFilter", tmp);
2188        cb->setChecked(tmp);
2189        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetUseSpatialFilter(bool)));
2190
2191
2192        label = new QLabel("Spatial Filter size");
2193        vbox->layout()->addWidget(label);
2194       
2195        slider = new QSlider(Qt::Horizontal, vbox);
2196        vbox->layout()->addWidget(slider);
2197        slider->show();
2198        slider->setRange(1, 100);
2199        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2200        slider->setValue(10);
2201
2202        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetSpatialFilterSize(int)));
2203
2204        ////////////////////////////
2205
2206       
2207        cb = new QCheckBox("Hide view cells by render cost ", vbox);
2208        vbox->layout()->addWidget(cb);
2209        cb->setChecked(false);
2210        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetHideByCost(bool)));
2211
2212        label = new QLabel("Hide by cost");
2213        vbox->layout()->addWidget(label);
2214
2215        // the render cost visualization
2216        slider = new QSlider(Qt::Horizontal, vbox);
2217        vbox->layout()->addWidget(slider);
2218        slider->show();
2219        slider->setRange(0, range);
2220        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2221        slider->setValue(0);
2222        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetHidingCost(int)));
2223
2224        ///////////////////////////////////////////
2225
2226        cb = new QCheckBox("Top View", vbox);
2227        vbox->layout()->addWidget(cb);
2228        cb->setChecked(false);
2229        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetTopView(bool)));
2230
2231
2232        label = new QLabel("Top distance");
2233        vbox->layout()->addWidget(label);
2234       
2235        slider = new QSlider(Qt::Horizontal, vbox);
2236        vbox->layout()->addWidget(slider);
2237        slider->show();
2238        slider->setRange(1, 1000);
2239        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2240        slider->setValue(500);
2241
2242        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetTopDistance(int)));
2243       
2244
2245        ///////////////////////////////////////////
2246#if REMOVE_TEMPORARY
2247        cb = new QCheckBox("Transparency", vbox);
2248        vbox->layout()->addWidget(cb);
2249        cb->setChecked(false);
2250        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetUseTransparency(bool)));
2251
2252        label = new QLabel("Use transparency");
2253        vbox->layout()->addWidget(label);
2254
2255        // the render cost visualization
2256        slider = new QSlider(Qt::Horizontal, vbox);
2257        vbox->layout()->addWidget(slider);
2258        slider->show();
2259        slider->setRange(0, range);
2260        slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
2261        slider->setValue(0);
2262        connect(slider, SIGNAL(valueChanged(int)), SIGNAL(SetTransparency(int)));
2263#endif
2264       
2265
2266        //////////////////////////////
2267
2268#if REMOVE_TEMPORARY
2269
2270        cb = new QCheckBox("Cut scene", vbox);
2271        vbox->layout()->addWidget(cb);
2272        cb->setChecked(false);
2273        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetCutScene(bool)));
2274
2275        cb = new QCheckBox("Render boxes", vbox);
2276        vbox->layout()->addWidget(cb);
2277        cb->setChecked(false);
2278        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetRenderBoxes(bool)));
2279
2280        cb = new QCheckBox("Render visibility estimates", vbox);
2281        vbox->layout()->addWidget(cb);
2282        cb->setChecked(false);
2283        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetRenderVisibilityEstimates(bool)));
2284#endif
2285
2286#if REMOVE_TEMPORARY
2287
2288        cb = new QCheckBox("Use filter", vbox);
2289        vbox->layout()->addWidget(cb);
2290        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilityFilter", tmp);
2291        cb->setChecked(tmp);
2292        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetUseFilter(bool)));
2293#endif
2294
2295
2296       
2297
2298#if REMOVE_TEMPORARY
2299       
2300        cb = new QCheckBox("Render filter", vbox);
2301        vbox->layout()->addWidget(cb);
2302        cb->setChecked(true);
2303        connect(cb, SIGNAL(toggled(bool)), SIGNAL(SetRenderFilter(bool)));
2304
2305
2306        /*vbox = new QGroupBox("PVS Errors", this);
2307        layout()->addWidget(vbox);
2308
2309        vl = new QVBoxLayout;
2310        vbox->setLayout(vl);
2311
2312        button = new QPushButton("Compute Visibility", vbox);
2313        vbox->layout()->addWidget(button);
2314        connect(button, SIGNAL(clicked()), SLOT(ComputeVisibility()));
2315
2316        button = new QPushButton("Stop Computation", vbox);
2317        vbox->layout()->addWidget(button);
2318        connect(button, SIGNAL(clicked()), SLOT(StopComputation()));
2319
2320        button = new QPushButton("Set Random View Point", vbox);
2321        vbox->layout()->addWidget(button);
2322        connect(button, SIGNAL(clicked()), SLOT(SetRandomViewPoint()));*/
2323
2324        button = new QPushButton("Store statistics", vbox);
2325        vbox->layout()->addWidget(button);
2326        connect(button, SIGNAL(clicked()), SIGNAL(StoreStatistics()));
2327
2328#endif
2329
2330        button = new QPushButton("Compute GVS", vbox);
2331        vbox->layout()->addWidget(button);
2332        connect(button, SIGNAL(clicked()), SIGNAL(ComputeGVS()));
2333
2334#if DYNAMIC_OBJECTS_HACK
2335
2336        button = new QPushButton("Load object", vbox);
2337        vbox->layout()->addWidget(button);
2338        connect(button, SIGNAL(clicked()), SIGNAL(LoadObject()));
2339#endif
2340
2341        /*cb = new QCheckBox("Stats", vbox);
2342        vbox->layout()->addWidget(cb);
2343        cb->setChecked(false);
2344        connect(cb, SIGNAL(toggled(bool)), SIGNAL(StoreStatistics()));*/
2345
2346        if (0)
2347        {
2348                vbox = new QGroupBox("PVS Errors", this);
2349                layout()->addWidget(vbox);
2350
2351                vl = new QVBoxLayout;
2352                vbox->setLayout(vl);
2353
2354                mPvsErrorWidget = new QListWidget(vbox);
2355                vbox->layout()->addWidget(mPvsErrorWidget);
2356
2357                connect(mPvsErrorWidget,
2358                        SIGNAL(doubleClicked(const QModelIndex &)),
2359                        this,
2360                        SLOT(PvsErrorClicked(const QModelIndex &)));
2361
2362                button = new QPushButton("Next Error Frame", vbox);
2363                vbox->layout()->addWidget(button);
2364                connect(button, SIGNAL(clicked(void)), SLOT(FocusNextPvsErrorFrame(void)));
2365        }
2366       
2367        //connect(button, SIGNAL(clicked(void)), SLOT(StoreStatistics(void)));
2368       
2369        //////////////////////////////////////////
2370
2371
2372        setWindowTitle("Preprocessor Control Widget");
2373        adjustSize();
2374}
2375
2376
2377
2378
2379void
2380QtRendererControlWidget::FocusNextPvsErrorFrame(void)
2381{}
2382
2383void
2384QtRendererControlWidget::UpdatePvsErrorItem(int row,
2385                                                                                        GlRendererBuffer::PvsErrorEntry &pvsErrorEntry)
2386{
2387
2388        QListWidgetItem *i = mPvsErrorWidget->item(row);
2389        QString s;
2390        s.sprintf("%5.5f", pvsErrorEntry.mError);
2391        if (i) {
2392                i->setText(s);
2393        } else {
2394                new QListWidgetItem(s, mPvsErrorWidget);
2395        }
2396        mPvsErrorWidget->update();
2397}
2398
2399
2400
2401
2402/*********************************************************************/
2403/*                   QtGlDebuggerWidget implementation               */
2404/*********************************************************************/
2405
2406
2407QtGlDebuggerWidget::QtGlDebuggerWidget(QtGlRendererBuffer *buf, QWidget *parent)
2408: QGLWidget(QGLFormat(QGL::SampleBuffers), parent), mRenderBuffer(buf)
2409{
2410        // create the pbuffer
2411        //pbuffer = new QGLPixelBuffer(QSize(512, 512), format(), this);
2412        timerId = startTimer(20);
2413        setWindowTitle(("OpenGL pbuffers"));
2414}
2415
2416
2417QtGlDebuggerWidget::~QtGlDebuggerWidget()
2418{
2419        mRenderBuffer->releaseFromDynamicTexture();
2420        glDeleteTextures(1, &dynamicTexture);
2421
2422        DEL_PTR(mRenderBuffer);
2423}
2424
2425
2426void QtGlDebuggerWidget::initializeGL()
2427{
2428        glMatrixMode(GL_PROJECTION);
2429        glLoadIdentity();
2430
2431        glFrustum(-1, 1, -1, 1, 10, 100);
2432        glTranslatef(-0.5f, -0.5f, -0.5f);
2433        glTranslatef(0.0f, 0.0f, -15.0f);
2434        glMatrixMode(GL_MODELVIEW);
2435
2436        glEnable(GL_CULL_FACE);
2437        initCommon();
2438        initPbuffer();
2439
2440}
2441
2442
2443void QtGlDebuggerWidget::resizeGL(int w, int h)
2444{
2445        glViewport(0, 0, w, h);
2446}
2447
2448
2449void QtGlDebuggerWidget::paintGL()
2450{
2451        // draw a spinning cube into the pbuffer..
2452        mRenderBuffer->makeCurrent();
2453
2454        BeamSampleStatistics stats;
2455        mRenderBuffer->SampleBeamContributions(mSourceObject, mBeam, mSamples, stats);
2456
2457        glFlush();
2458
2459        // rendering directly to a texture is not supported on X11, unfortunately
2460        mRenderBuffer->updateDynamicTexture(dynamicTexture);
2461
2462        // and use the pbuffer contents as a texture when rendering the
2463        // background and the bouncing cubes
2464        makeCurrent();
2465        glBindTexture(GL_TEXTURE_2D, dynamicTexture);
2466        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2467
2468        // draw the background
2469        glMatrixMode(GL_MODELVIEW);
2470        glPushMatrix();
2471        glLoadIdentity();
2472        glMatrixMode(GL_PROJECTION);
2473        glPushMatrix();
2474        glLoadIdentity();
2475
2476        glPopMatrix();
2477        glMatrixMode(GL_MODELVIEW);
2478        glPopMatrix();
2479}
2480
2481
2482void QtGlDebuggerWidget::initPbuffer()
2483{
2484        // set up the pbuffer context
2485        mRenderBuffer->makeCurrent();
2486       
2487        // generate a texture that has the same size/format as the pbuffer
2488        dynamicTexture = mRenderBuffer->generateDynamicTexture();
2489
2490        // bind the dynamic texture to the pbuffer - this is a no-op under X11
2491        mRenderBuffer->bindToDynamicTexture(dynamicTexture);
2492        //makeCurrent();
2493}
2494
2495
2496void QtGlDebuggerWidget::initCommon()
2497{
2498        glEnable(GL_TEXTURE_2D);
2499        glEnable(GL_DEPTH_TEST);
2500
2501        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
2502}
2503
2504
2505void QtGlRendererWidget::_RenderColoredPvs()
2506{
2507        // note: could be done more efficiently using color buffers
2508        mPvsSize = mPvsCache.mPvs.GetSize();
2509
2510        ObjectPvsIterator it = mPvsCache.mPvs.GetIterator();
2511
2512        PvsData pvsData;
2513
2514        while (it.HasMoreEntries())
2515        {
2516                Intersectable *object = it.Next(pvsData);
2517
2518                RgbColor color;
2519
2520                //float visibility = mTransferFunction*log10(entry.mData.mSumPdf + 1); // /5.0f
2521                // glColor3f(visibility, 0.0f, 0.0f);
2522                //cerr << "sumpdf: " << pvsData.mSumPdf << endl;
2523                if (mUseRandomColorPerPvsObject)
2524                {
2525                        KdIntersectable *kdint = static_cast<KdIntersectable *>(object);
2526
2527                        if (kdint->mGenericIdx == -1)
2528                        {
2529                                kdint->mGenericIdx = (int)mColors.size();
2530                                mColors.push_back(RandomColor());
2531                        }
2532                        color = mColors[kdint->mGenericIdx];
2533                }
2534                else
2535                {
2536                        color = RainbowColorMapping(mTransferFunction * log10(pvsData.mSumPdf + 1));
2537                }
2538
2539                glColor3f(color.r, color.g, color.b);
2540
2541                mUseForcedColors = true;
2542                RenderIntersectable(object);
2543                mUseForcedColors = false;
2544        }
2545}
2546
2547void
2548QtGlRendererWidget::UpdateDynamicObjects()
2549{
2550  preprocessor->ScheduleUpdateDynamicObjects();
2551 
2552}
2553
2554}
Note: See TracBrowser for help on using the repository browser.