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

Revision 2662, 61.1 KB checked in by mattausch, 16 years ago (diff)

working on gvs pixel error evaluation bugfixing

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