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

Revision 2667, 60.7 KB checked in by bittner, 16 years ago (diff)

merge on nemo

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