source: GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellsManager.cpp @ 2224

Revision 2224, 176.6 KB checked in by mattausch, 17 years ago (diff)
Line 
1#include "ViewCellsManager.h"
2#include "RenderSimulator.h"
3#include "Mesh.h"
4#include "Triangle3.h"
5#include "ViewCell.h"
6#include "Environment.h"
7#include "X3dParser.h"
8#include "ViewCellBsp.h"
9#include "KdTree.h"
10#include "HierarchyManager.h"
11#include "Exporter.h"
12#include "VspBspTree.h"
13#include "ViewCellsParser.h"
14#include "Beam.h"
15#include "VssPreprocessor.h"
16#include "RssPreprocessor.h"
17#include "BoundingBoxConverter.h"
18#include "GlRenderer.h"
19#include "ResourceManager.h"
20#include "IntersectableWrapper.h"
21#include "VspTree.h"
22#include "OspTree.h"
23#include "BvHierarchy.h"
24#include "SamplingStrategy.h"
25#include "SceneGraph.h"
26#include "PerfTimer.h"
27
28
29#define USE_RAY_LENGTH_AS_CONTRIBUTION 0
30#define DIST_WEIGHTED_CONTRIBUTION 0
31#define SUM_RAY_CONTRIBUTIONS 1
32#define AVG_RAY_CONTRIBUTIONS 0
33#define CONTRIBUTION_RELATIVE_TO_PVS_SIZE 0
34#define PVS_ADD_DIRTY 1
35
36namespace GtpVisibilityPreprocessor {
37
38
39PerfTimer viewCellCastTimer;
40PerfTimer pvsTimer;
41PerfTimer objTimer;
42
43// HACK
44const static bool SAMPLE_AFTER_SUBDIVISION = true;
45//const static bool CLAMP_TO_BOX = false;
46const static bool CLAMP_TO_BOX = true;
47
48
49int ViewCellsManager::sRenderCostEvaluationType = 0;
50
51
52template <typename T> class myless
53{
54public:
55        //bool operator() (HierarchyNode *v1, HierarchyNode *v2) const
56        bool operator() (T v1, T v2) const
57        {
58                return (v1->GetMergeCost() < v2->GetMergeCost());
59        }
60};
61
62
63ViewCellsManager::ViewCellsManager(ViewCellsTree *viewCellsTree):
64mRenderer(NULL),
65mInitialSamples(0),
66mConstructionSamples(0),
67mPostProcessSamples(0),
68mVisualizationSamples(0),
69mTotalAreaValid(false),
70mTotalArea(0.0f),
71mViewCellsFinished(false),
72mMaxPvsSize(9999999),
73mMinPvsSize(0),
74mMaxPvsRatio(1.0),
75mViewCellPvsIsUpdated(false),
76mPreprocessor(NULL),
77mViewCellsTree(viewCellsTree),
78mUsePredefinedViewCells(false),
79mMixtureDistribution(NULL)
80{
81        mViewSpaceBox.Initialize();
82        ParseEnvironment();
83
84        mViewCellsTree->SetViewCellsManager(this);
85        mSamplesStat.Reset();
86        mStats.open("mystats.log");
87}
88
89
90int ViewCellsManager::CastEvaluationSamples(const int samplesPerPass,
91                                                                                        VssRayContainer &passSamples)
92{
93        static int pass = 0;
94        static int totalRays = 0;
95
96        SimpleRayContainer rays;
97        rays.reserve(samplesPerPass);
98        passSamples.reserve(samplesPerPass * 2);
99 
100        long startTime = GetTime();
101
102        //cout<<"Progress :"<<i/1e6f<<"M rays, "<<(100.0f*i)/mTotalSamples<<"%"<<endl;
103       
104        //rays.clear();
105        //passSamples.clear();
106       
107        mMixtureDistribution->GenerateSamples(samplesPerPass, rays);
108       
109        const bool doubleRays = true;
110        const bool pruneInvalidRays = true;
111        mPreprocessor->CastRays(rays, passSamples, doubleRays, pruneInvalidRays);
112
113        mMixtureDistribution->ComputeContributions(passSamples);
114        mMixtureDistribution->UpdateDistributions(passSamples);
115       
116        Real time = TimeDiff(startTime, GetTime());
117        PrintPvsStatistics(mStats);
118       
119        mStats <<
120                "#Pass\n" << pass ++ <<endl<<
121                "#Time\n" << time <<endl<<
122                "#TotalSamples\n" <<totalRays<<endl;
123       
124
125        totalRays += samplesPerPass;
126
127        return (int)passSamples.size();
128}
129
130
131void ViewCellsManager::ParseEnvironment()
132{
133        // visualization stuff
134        Environment::GetSingleton()->GetBoolValue("ViewCells.Visualization.exportRays", mExportRays);
135        Environment::GetSingleton()->GetBoolValue("ViewCells.Visualization.exportGeometry", mExportGeometry);
136        Environment::GetSingleton()->GetFloatValue("ViewCells.maxPvsRatio", mMaxPvsRatio);
137       
138        Environment::GetSingleton()->GetBoolValue("ViewCells.processOnlyValidViewCells", mOnlyValidViewCells);
139
140        Environment::GetSingleton()->GetIntValue("ViewCells.Construction.samples", mConstructionSamples);
141        Environment::GetSingleton()->GetIntValue("ViewCells.PostProcess.samples", mPostProcessSamples);
142        Environment::GetSingleton()->GetBoolValue("ViewCells.PostProcess.useRaysForMerge", mUseRaysForMerge);
143
144        Environment::GetSingleton()->GetIntValue("ViewCells.Visualization.samples", mVisualizationSamples);
145
146        Environment::GetSingleton()->GetIntValue("ViewCells.Construction.samplesPerPass", mSamplesPerPass);
147        Environment::GetSingleton()->GetBoolValue("ViewCells.exportToFile", mExportViewCells);
148       
149        Environment::GetSingleton()->GetIntValue("ViewCells.active", mNumActiveViewCells);
150        Environment::GetSingleton()->GetBoolValue("ViewCells.PostProcess.compress", mCompressViewCells);
151        Environment::GetSingleton()->GetBoolValue("ViewCells.Visualization.useClipPlane", mUseClipPlaneForViz);
152        Environment::GetSingleton()->GetBoolValue("ViewCells.PostProcess.merge", mMergeViewCells);
153        Environment::GetSingleton()->GetBoolValue("ViewCells.evaluateViewCells", mEvaluateViewCells);
154        Environment::GetSingleton()->GetBoolValue("ViewCells.showVisualization", mShowVisualization);
155        Environment::GetSingleton()->GetIntValue("ViewCells.Filter.maxSize", mMaxFilterSize);
156        Environment::GetSingleton()->GetFloatValue("ViewCells.Filter.width", mFilterWidth);
157        Environment::GetSingleton()->GetIntValue("ViewCells.renderCostEvaluationType", sRenderCostEvaluationType);
158
159        Environment::GetSingleton()->GetBoolValue("ViewCells.exportBboxesForPvs", mExportBboxesForPvs);
160        Environment::GetSingleton()->GetBoolValue("ViewCells.exportPvs", mExportPvs);
161
162        Environment::GetSingleton()->GetBoolValue("ViewCells.useKdPvs", mUseKdPvs);
163
164        char buf[100];
165        Environment::GetSingleton()->GetStringValue("ViewCells.samplingType", buf);
166
167        // mix of sampling strategies
168        if (0)
169        {
170                mStrategies.push_back(SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION);
171        }
172        else
173        {
174                mStrategies.push_back(SamplingStrategy::OBJECT_BASED_DISTRIBUTION);
175                //mStrategies.push_back(SamplingStrategy::REVERSE_VIEWSPACE_BORDER_BASED_DISTRIBUTION);
176                mStrategies.push_back(SamplingStrategy::REVERSE_OBJECT_BASED_DISTRIBUTION);
177                       
178                mStrategies.push_back(SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION);
179        }
180               
181    Debug << "casting strategies: ";
182        for (int i = 0; i < (int)mStrategies.size(); ++ i)
183                Debug << mStrategies[i] << " ";
184        Debug << endl;
185
186        // sampling type for view cells construction samples
187        if (strcmp(buf, "object") == 0)
188        {
189                mSamplingType = SamplingStrategy::OBJECT_BASED_DISTRIBUTION;
190        }
191        else if (strcmp(buf, "box") == 0)
192        {
193                mSamplingType = SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION;
194        }
195        else if (strcmp(buf, "directional") == 0)
196        {
197                mSamplingType = SamplingStrategy::DIRECTION_BASED_DISTRIBUTION;
198        }
199        else if (strcmp(buf, "object_directional") == 0)
200        {
201                mSamplingType = SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION;
202        }
203        else if (strcmp(buf, "reverse_object") == 0)
204        {
205                mSamplingType = SamplingStrategy::REVERSE_OBJECT_BASED_DISTRIBUTION;
206        }
207        /*else if (strcmp(buf, "interior") == 0)
208        {
209                mSamplingType = Preprocessor::OBJECTS_INTERIOR_DISTRIBUTION;
210        }*/
211        else
212        {
213                Debug << "error! wrong sampling type" << endl;
214                exit(0);
215        }
216
217        // sampling type for evaluation samples
218        Environment::GetSingleton()->GetStringValue("ViewCells.Evaluation.samplingType", buf);
219       
220        if (strcmp(buf, "object") == 0)
221        {
222                mEvaluationSamplingType = SamplingStrategy::OBJECT_BASED_DISTRIBUTION;
223        }
224        else if (strcmp(buf, "box") == 0)
225        {
226                mEvaluationSamplingType = SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION;
227        }
228        else if (strcmp(buf, "directional") == 0)
229        {
230                mEvaluationSamplingType = SamplingStrategy::DIRECTION_BASED_DISTRIBUTION;
231        }
232        else if (strcmp(buf, "object_directional") == 0)
233        {
234                mEvaluationSamplingType = SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION;
235        }
236        else if (strcmp(buf, "reverse_object") == 0)
237        {
238                mEvaluationSamplingType = SamplingStrategy::REVERSE_OBJECT_BASED_DISTRIBUTION;
239        }
240        else
241        {
242                mEvaluationSamplingType = -1;
243                Debug << "error! wrong sampling type" << endl;
244                exit(0);
245        }
246
247        Environment::GetSingleton()->GetStringValue("ViewCells.renderCostEvaluationType", buf);
248       
249        if (strcmp(buf, "perobject") == 0)
250        {
251                sRenderCostEvaluationType = ViewCellsManager::PER_OBJECT;
252        }
253        else if (strcmp(buf, "pertriangle") == 0)
254        {
255                sRenderCostEvaluationType = ViewCellsManager::PER_TRIANGLE;
256        }
257        else
258        {
259                Debug << "error! wrong sampling type" << endl;
260                exit(0);
261        }
262
263    Environment::GetSingleton()->GetStringValue("ViewCells.Visualization.colorCode", buf);
264
265        if (strcmp(buf, "PVS") == 0)
266                mColorCode = 1;
267        else if (strcmp(buf, "MergedLeaves") == 0)
268                mColorCode = 2;
269        else if (strcmp(buf, "MergedTreeDiff") == 0)
270                mColorCode = 3;
271        else
272                mColorCode = 0;
273
274
275        Debug << "************ View Cells Manager options ***************" << endl;
276        Debug << "color code: " << mColorCode << endl;
277
278        Debug << "export rays: " << mExportRays << endl;
279        Debug << "export geometry: " << mExportGeometry << endl;
280        Debug << "max pvs ratio: " << mMaxPvsRatio << endl;
281       
282        Debug << "process only valid view cells: " << mOnlyValidViewCells << endl;
283        Debug << "construction samples: " << mConstructionSamples << endl;
284        Debug << "post process samples: " << mPostProcessSamples << endl;
285        Debug << "post process use rays for merge: " << mUseRaysForMerge << endl;
286        Debug << "visualization samples: " << mVisualizationSamples << endl;
287        Debug << "construction samples per pass: " << mSamplesPerPass << endl;
288        Debug << "export to file: " << mExportViewCells << endl;
289       
290        Debug << "active view cells: " << mNumActiveViewCells << endl;
291        Debug << "post process compress: " << mCompressViewCells << endl;
292        Debug << "visualization use clipPlane: " << mUseClipPlaneForViz << endl;
293        Debug << "post process merge: " << mMergeViewCells << endl;
294        Debug << "evaluate view cells: " << mEvaluateViewCells << endl;
295        Debug << "sampling type: " << mSamplingType << endl;
296        Debug << "render cost evaluation type: " << sRenderCostEvaluationType << endl;
297        Debug << "evaluation sampling type: " << mEvaluationSamplingType << endl;
298        Debug << "show visualization: " << mShowVisualization << endl;
299        Debug << "filter width: " << mFilterWidth << endl;
300        Debug << "sample after subdivision: " << SAMPLE_AFTER_SUBDIVISION << endl;
301
302        Debug << "export bounding boxes: " << mExportBboxesForPvs << endl;
303        Debug << "export pvs for view cells: " << mExportPvs << endl;
304        Debug << "use kd pvs " << mUseKdPvs << endl;
305
306        Debug << endl;
307}
308
309
310ViewCell *ViewCellsManager::GetViewCellById(const int id)
311{
312        ViewCellContainer::const_iterator vit, vit_end = mViewCells.end();
313
314        for (vit = mViewCells.begin(); vit != vit_end; ++ vit)
315        {
316                if ((*vit)->GetId() == id)
317                        return (*vit);
318        }
319        return NULL;
320}
321
322
323bool ViewCellsManager::ExportRandomViewCells(const string &filename,
324                                                                                         const vector<ViewCellPoints *> &viewCells)
325{
326        std::ofstream outStream;
327        outStream.open(filename.c_str());
328
329        vector<ViewCellPoints *>::const_iterator vit, vit_end = viewCells.end();
330   
331        for (vit = viewCells.begin(); vit != vit_end; ++ vit)
332        {
333                ViewCell *vc = (*vit)->first;
334
335                outStream << "v " << vc->GetId() << endl;
336
337                SimpleRayContainer viewPoints;
338       
339                SimpleRayContainer::const_iterator pit, pit_end = (*vit)->second.end();
340
341                for (pit = (*vit)->second.begin(); pit != pit_end; ++ pit)
342                {
343                        const Vector3 pt = (*pit).mOrigin;
344                        const Vector3 dir = (*pit).mDirection;
345
346                        outStream << "p " << pt.x  << " " << pt.y  << " " << pt.z
347                                      << " "  << dir.x << " " << dir.y << " " << dir.z << endl;
348                }
349        }
350
351        return true;
352}
353
354
355bool ViewCellsManager::GenerateRandomViewCells(vector<ViewCellPoints *> &viewCells,
356                                                                                           const int nViewCells,
357                                                                                           const int nViewPoints)
358{
359        ViewCellContainer rViewCells;
360
361        cout << "generating " << nViewCells << " random view cells" << endl;
362        ///GenerateRandomViewCells(rViewCells, nViewCells);
363
364        //cout << "finished" << endl;
365
366        //for (int i = 0; i < viewCells.size(); ++ i)
367        //      cout << "vc " << i << ": " << viewCells[i]->GetId() << endl;
368
369        cout << "generating " << nViewPoints << " view points per view cell" << endl;
370           
371        int generatedViewCells = 0;
372        int i = 0;
373    while (generatedViewCells < nViewCells)
374        {
375                ++ i;
376               
377                const int idx = (int)RandomValue(0.0f, (float)mViewCells.size() - 0.5f);
378                       
379                ViewCell *viewCell = GetViewCell(idx);
380               
381                cout << "testing view cell: " << viewCell->GetId() << endl;
382
383                if (!viewCell->Mailed())
384                {
385                        viewCell->Mail();
386
387                        SimpleRayContainer viewPoints;
388                       
389                        // generate random view points
390                        if (IsValidViewSpace(viewCell) &&
391                                GenerateViewPoints(viewCell, nViewPoints, viewPoints))
392                        {
393                                Debug << "vc: " << viewCell->GetId() << endl;
394
395                                ViewCellPoints *vcPts = new ViewCellPoints();
396                                viewCells.push_back(vcPts);
397
398                                // valid view cell found
399                                vcPts->first = viewCell;
400
401                                // generate view points
402                                ++ generatedViewCells;
403
404                                SimpleRayContainer::const_iterator pit, pit_end = viewPoints.end();
405
406                                for (pit = viewPoints.begin(); pit != pit_end; ++ pit)
407                                {
408                                        Debug << "vp: " << (*pit) << endl;
409                                        vcPts->second.push_back(*pit); 
410                                }
411                                cout << "view cell " << generatedViewCells << " generated: " << viewCell->GetId() << endl;     
412                        }
413                        else
414                        {
415                                cout << "error: invalid view cell " << generatedViewCells << " with id " << viewCell->GetId() << endl; 
416                        }
417                }
418
419                if (i > nViewCells * 1000000) // safety
420                {
421                        cout << "big error" << endl;
422                        break;
423                }
424                cout << "processd view cells " << generatedViewCells << " of " << nViewCells << endl << endl;
425        }
426
427        return true;
428}
429
430
431bool ViewCellsManager::ImportRandomViewCells(const string &filename,
432                                                                                         vector<ViewCellPoints *> &viewCells)
433{
434        ifstream inStream(filename.c_str());
435        if (!inStream.is_open())
436                return false;
437
438        ViewCellPoints *currentViewCell = NULL;
439
440        string buf;
441        while (!(getline(inStream, buf)).eof())
442        {
443                switch (buf[0])
444                {
445                case 'v':
446                        {
447                                int id;
448                                sscanf(buf.c_str(), "v %d", &id);
449                       
450                                currentViewCell = new ViewCellPoints();
451                                currentViewCell->first = GetViewCellById(id);
452                                               
453                                viewCells.push_back(currentViewCell);
454                                break;
455                        }
456                case 'p':
457                        {
458                                Vector3 pt, dir;
459                                sscanf(buf.c_str(), "p %f %f %f %f %f %f", &pt.x, &pt.y, &pt.z, &dir.x, &dir.y, &dir.z);
460                               
461                                SimpleRay ray(pt, dir, 0, 1);
462                                currentViewCell->second.push_back(ray);
463                                break;
464                        }
465                default:
466                        break;
467                }
468        }
469
470        return true;
471}
472
473
474bool ViewCellsManager::ImportRandomViewCells(const string &filename)
475{
476        return ImportRandomViewCells(filename, mViewCellPoints);
477}
478
479
480bool ViewCellsManager::GenerateViewPoints(ViewCell *viewCell,
481                                                                                  const int numViewPoints,
482                                                                                  SimpleRayContainer &viewPoints)
483{
484        bool success = true;
485        int generatedPts = 0;
486        int i = 0;
487
488        cout << "generating view points for view cell " << viewCell->GetId() << endl;
489
490        while (generatedPts < numViewPoints)
491        {
492                SimpleRay pt;
493
494                if (GenerateViewPoint(viewCell, pt))
495                {
496                        ++ generatedPts;
497                        cout << "generated view point " << generatedPts << endl;
498                        viewPoints.push_back(pt);
499                }
500
501                // savety criterium
502                if (++ i > numViewPoints * 3)
503                {
504                        return false;
505                }
506        }
507       
508        cout << "view point generation finished" << endl;
509
510        return true;
511}
512
513
514bool ViewCellsManager::ExportRandomViewCells(const string &filename)
515{
516        const int numViewCells = 100;
517        const int numViewPoints = 10;
518
519        preprocessor->mViewCellsManager->
520                GenerateRandomViewCells(mViewCellPoints, numViewCells, numViewPoints);
521
522        //cout << "exporting random view cells" << endl;
523        return preprocessor->mViewCellsManager->ExportRandomViewCells(filename,  mViewCellPoints);
524}
525
526
527bool ViewCellsManager::GenerateViewPoint(ViewCell *viewCell,
528                                                                                 SimpleRay &ray)
529{
530        // do not use this function since it could return different viewpoints for
531        // different executions of the algorithm
532        int tries = 0;
533        Vector3 viewPoint, direction;
534        const int maxTries = 10;
535
536        while (1)
537        {
538                // hack
539                if (!viewCell->GetMesh())
540                        CreateMesh(viewCell);
541
542        Mesh *mesh = viewCell->GetMesh();
543                AxisAlignedBox3 box = mesh->mBox;
544                //cout <<"box: " << box << endl;
545                /*Vector3 pVector = Vector3(halton.GetNumber(1),
546                                                                  halton.GetNumber(2),
547                                                                  halton.GetNumber(3));*/
548
549                Vector3 pVector = Vector3(Random(1.0f),
550                                                                  Random(1.0f),
551                                                                  Random(1.0f));
552
553                viewPoint =  box.GetPoint(pVector);
554       
555                //const Vector3 dVector = Vector3(2 * M_PI * halton.GetNumber(4), M_PI*halton.GetNumber(5),0.0f);
556                const Vector3 dVector = Vector3(2 * M_PI * Random(1.0f), M_PI * Random(1.0f), 0.0f);
557                direction = Normalize(Vector3(sin(dVector.x), 0.0f, cos(dVector.x)));
558                //halton.GenerateNext();
559
560                ViewCell *v = GetViewCell(viewPoint);
561
562                if (v && v->GetValid())
563                {
564                        mPreprocessor->GetRenderer()->mViewPoint = viewPoint;
565                        mPreprocessor->GetRenderer()->mViewDirection = direction;
566                        //mPreprocessor->GetRenderer()->EvalPvsStat();
567
568                        if (mPreprocessor->GetRenderer()->ValidViewPoint())
569                        {
570                                cout << "view point valid " << viewPoint << " " << direction << endl;
571                                break;
572                        }
573                       
574                }
575
576                // generate a new vector
577                //halton.GenerateNext();
578
579                //if (!box.IsInside(viewPoint))
580                //      cout << "error!" << endl;
581                if (++ tries > maxTries)
582                {
583                        cerr << "error: no view point computed" << endl;
584                        return false;
585                }
586        }
587
588        ray = SimpleRay(viewPoint, direction, 0, 1);
589        //cout << "view point generated: " << viewPoint << " " << direction << endl;
590
591        return true;
592}
593
594
595bool ViewCellsManager::IsValidViewSpace(ViewCell *vc)
596{
597        SimpleRay simpleRay;
598        //check if view point can be generated
599        return GenerateViewPoint(vc, simpleRay);
600}
601
602
603bool ViewCellsManager::GenerateRandomViewCells(ViewCellContainer &viewCells,
604                                                                                           const int numViewCells)
605{
606        int generatedViewCells = 0;
607        //HaltonSequence halton;
608        //float r[1];
609
610        ViewCell::NewMail();
611
612        while (generatedViewCells < numViewCells)
613        {
614                // savety criterium
615                const int tries = 100000 + generatedViewCells;
616                int i = 0;
617
618                // generate next view cell
619                while (1)
620                {
621                        //halton.GetNext(1, r);
622                        //const int idx = (int)(r[0] * mViewCells.size() - 1.0f);
623                        const int idx = (int)RandomValue(0.0f, (float)mViewCells.size() - 0.5f);
624                       
625                        ViewCell *viewCell = GetViewCell(idx);
626
627                        if (!viewCell->Mailed())
628                        {
629                                viewCell->Mail();
630
631                                // check for valid view space
632                                if (IsValidViewSpace(viewCell))
633                                {
634                                        // valid view cell found
635                                        viewCells.push_back(viewCell);
636
637                        ++ generatedViewCells;
638                                        //cout << "view cell " << generatedViewCells << " generated: " << viewCell->GetId() << endl;   
639                                        break;
640                                }
641                                else
642                                {
643                                        cout << "error: invalid view cell " << generatedViewCells << " with id " << viewCell->GetId() << endl; 
644                                }
645                        }
646
647                        if (++ i == tries) // no new view cell fond
648                        {
649                                cerr << "big error! no view cell found" << endl;
650                                return false;
651                        }               
652                }                       
653        }
654
655        return true;
656}
657
658
659ViewCellsManager::~ViewCellsManager()
660{
661        // HACK: if view cells tree does not
662        // handle view cells, we have to do it here
663        // question: rather create view cells resource manager?
664        if (!ViewCellsTreeConstructed())
665        {
666                CLEAR_CONTAINER(mViewCells);
667        }
668        else
669        {
670                DEL_PTR(mViewCellsTree);
671        }
672
673        DEL_PTR(mMixtureDistribution);
674       
675        CLEAR_CONTAINER(mViewCellPoints);
676}
677
678
679Intersectable *
680ViewCellsManager::GetIntersectable(const VssRay &ray, const bool isTermination) const
681{
682        if (mUseKdPvs)
683        {
684                KdNode *node = GetPreprocessor()->
685                        mKdTree->GetPvsNode(isTermination ?     ray.mTermination : ray.mOrigin);
686          return GetPreprocessor()->mKdTree->GetOrCreateKdIntersectable(node);
687        }
688        else
689          {
690                return isTermination ? ray.mTerminationObject : ray.mOriginObject;
691          }
692}
693
694
695void
696ViewCellsManager::CollectObjects(const AxisAlignedBox3 &box, ObjectContainer &objects)
697{
698        GetPreprocessor()->mKdTree->CollectObjects(box, objects);
699}
700
701AxisAlignedBox3 ViewCellsManager::GetViewCellBox(ViewCell *vc)
702{
703  Mesh *m = vc->GetMesh();
704 
705  if (m)
706  {
707          m->ComputeBoundingBox();
708          return m->mBox;
709  }
710
711  AxisAlignedBox3 box;
712  box.Initialize();
713 
714  if (!vc->IsLeaf()) {
715        ViewCellInterior *vci = (ViewCellInterior *) vc;
716       
717        ViewCellContainer::iterator it = vci->mChildren.begin();
718        for (; it != vci->mChildren.end(); ++it) {
719          box.Include(GetViewCellBox(*it));
720        }
721  }
722 
723  return box;
724}
725
726
727int ViewCellsManager::CastPassSamples(const int samplesPerPass,
728                                                                          const vector<int> &strategies,
729                                                                          VssRayContainer &passSamples
730                                                                          ) const
731{
732        long startTime = GetTime();
733       
734        SimpleRayContainer simpleRays;
735       
736        simpleRays.reserve(samplesPerPass);
737        passSamples.reserve(samplesPerPass * 2); // always creates double rays
738
739        // create one third of each type
740        int castRays = 0;
741       
742        const int numRaysPerPass = samplesPerPass / (int)strategies.size();
743        vector<int>::const_iterator iit, iit_end = strategies.end();
744
745        for (iit = strategies.begin(); iit != iit_end; ++ iit)
746        {
747                const int stype = *iit;
748                const int newRays =
749                        mPreprocessor->GenerateRays(numRaysPerPass, stype, simpleRays);
750
751                cout << "cast " << newRays << " rays of strategy " << stype << endl;
752                castRays += newRays;
753        }
754
755        cout << "generated " << samplesPerPass << " samples in "
756                 << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
757
758        startTime = GetTime();
759
760        // shoot simple ray and add it to importance samples
761        mPreprocessor->CastRays(simpleRays, passSamples, true);
762       
763        cout << "cast " <<  samplesPerPass << " samples in "
764                 << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
765
766        return (int)passSamples.size();
767}
768
769
770/// helper function which destroys rays or copies them into the output ray container
771inline void disposeRays(VssRayContainer &rays, VssRayContainer *outRays)
772{
773        cout << "disposing samples ... ";
774        long startTime = GetTime();
775        int n = (int)rays.size();
776
777        if (outRays)
778        {
779                VssRayContainer::const_iterator it, it_end = rays.end();
780                for (it = rays.begin(); it != it_end; ++ it)
781                {
782                        outRays->push_back(*it);
783                }
784        }
785        else
786        {
787                VssRayContainer::const_iterator it, it_end = rays.end();
788                for (it = rays.begin(); it != it_end; ++ it)
789                {
790                        if (!(*it)->IsActive())
791                                delete (*it);
792                }
793        }
794
795        cout << "finished" << endl;
796        Debug << "disposed " << n << " samples in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
797}
798
799
800int ViewCellsManager::Construct(Preprocessor *preprocessor, VssRayContainer *outRays)
801{
802        int numSamples = 0;
803
804        SimpleRayContainer simpleRays;
805        VssRayContainer initialSamples;
806
807        // store pointer to preprocessor for further use during construction
808        mPreprocessor = preprocessor;
809       
810        // now decode distribution string
811        char mix[1024];
812        Environment::GetSingleton()->GetStringValue("RssPreprocessor.distributions", mix);
813        Debug << "using mixture distributions: " << mix << endl;
814
815        mMixtureDistribution = new MixtureDistribution(*mPreprocessor);
816        mMixtureDistribution->Construct(mix);
817
818        ///////////////////////////////////////////////////////
819        //-- Initial sampling for the construction of the view cell hierarchy.
820        //-- We use uniform sampling / box based sampling.
821       
822        long startTime = GetTime();
823        cout << "view cell construction: casting " << mInitialSamples << " initial samples ... " << endl;
824
825        // cast initial samples
826       
827        // mix of sampling strategies
828        vector<int>dummy;
829        //dummy.push_back(SamplingStrategy::OBJECT_BASED_DISTRIBUTION);
830        //dummy.push_back(SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION);
831        //dummy.push_back(SamplingStrategy::REVERSE_OBJECT_BASED_DISTRIBUTION);
832
833        CastPassSamples(mInitialSamples, mStrategies, initialSamples);
834
835        cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
836
837        // construct view cells
838        ConstructSubdivision(preprocessor->mObjects, initialSamples);
839
840        // initial samples count for overall samples ...
841        numSamples += mInitialSamples;
842
843        // rays can be passed or deleted
844        disposeRays(initialSamples, outRays);
845
846        cout << "time needed for initial construction: "
847                 << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
848
849        Debug << "time needed for initial construction: "
850                  << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
851
852        // collect view cells and compute statistics
853        ResetViewCells();
854
855
856        ///////////////////
857        //-- Initial hierarchy construction finished.
858        //-- We can do some stats and visualization
859       
860        if (0)
861        {
862                //-- export initial view cell partition
863                Debug << "\nView cells after initial sampling:\n" << mCurrentViewCellsStats << endl;
864
865                const string filename("viewcells.wrl");
866                Exporter *exporter = Exporter::GetExporter(filename.c_str());
867       
868                if (exporter)
869                {
870                        cout << "exporting initial view cells (=leaves) to " << filename.c_str() << " ... ";
871
872                        if (mExportGeometry)
873                        {
874                                exporter->ExportGeometry(preprocessor->mObjects);
875                        }
876
877                        exporter->SetWireframe();
878                        ExportViewCellsForViz(exporter, NULL, mColorCode, GetClipPlane());
879
880                        delete exporter;
881                        cout << "finished" << endl;
882                }
883        }
884
885
886        //////////////////////
887        //-- Cast some more sampling after initial construction.
888        //-- The additional rays can be used to gain
889        //-- some more information before the bottom-up merge
890        //-- note: guided rays could be used for this task
891
892        // time spent after construction of the initial partition
893        startTime = GetTime();
894        const int n = mConstructionSamples; //+initialSamples;
895
896        while (numSamples < n)
897        {
898                cout << "casting " << mSamplesPerPass << " samples of " << n << " ... ";
899                Debug << "casting " << mSamplesPerPass << " samples of " << n << " ... ";
900
901                VssRayContainer constructionSamples;
902
903                // cast new samples
904                numSamples += CastPassSamples(mSamplesPerPass,
905                                                                          mStrategies,
906                                                                          constructionSamples);
907
908                cout << "finished" << endl;
909                cout << "computing sample contribution for " << (int)constructionSamples.size() << " samples ... ";
910
911                // computes sample contribution of cast rays
912                if (SAMPLE_AFTER_SUBDIVISION)
913                        ComputeSampleContributions(constructionSamples, true, false);
914
915                cout << "finished" << endl;
916
917                disposeRays(constructionSamples, outRays);
918                cout << "total samples: " << numSamples << endl;
919        }
920
921        if (0)
922        {
923                ///////////////
924                //-- Get stats after the additional sampling step
925                //-- and before the bottom-up merge step
926
927                EvaluateViewCellsStats();
928                Debug << "\noriginal view cell partition before post process:\n"
929                          << mCurrentViewCellsStats << endl;
930       
931                mRenderer->RenderScene();
932                SimulationStatistics ss;
933                static_cast<RenderSimulator *>(mRenderer)->GetStatistics(ss);
934
935                Debug << ss << endl;
936        }
937
938        ////////////////////
939        //-- post processing of the initial construction
940        //-- We can bottom-up merge the view cells in this step
941        //-- We can additionally cast some post processing sample rays.
942        //-- These rays can be used to store the view cells with the rays
943
944        VssRayContainer postProcessSamples;
945        cout << "casting " << mPostProcessSamples << " post processing samples ... ";
946       
947        CastPassSamples(mPostProcessSamples, mStrategies, postProcessSamples);
948
949        cout << "finished" << endl;
950        cout << "starting post processing and visualization" << endl;
951
952        // store view cells with rays for post processing?
953        const bool storeViewCells = true;
954
955        if (SAMPLE_AFTER_SUBDIVISION)
956                ComputeSampleContributions(postProcessSamples, true, storeViewCells);
957
958        PostProcess(preprocessor->mObjects, postProcessSamples);
959
960        const float secs = TimeDiff(startTime, GetTime()) * 1e-3f;
961        cout << "post processing (=merge) finished in " << secs << " secs" << endl;
962
963        Debug << "post processing time: " << secs << endl;
964        disposeRays(postProcessSamples, outRays);
965
966
967        ////////////////
968        //-- Evaluation of the resulting view cell partition.
969        //-- We cast a number of new samples and measure the render cost
970
971        if (mEvaluateViewCells)
972        {
973                EvalViewCellPartition();
974        }
975       
976        /////////////////
977        //-- Show some visualizations
978
979        if (mShowVisualization)
980        {
981                ///////////////
982                //-- visualization rays, e.g., to show some samples in the scene
983               
984                VssRayContainer visSamples;
985                int numSamples = CastPassSamples(mVisualizationSamples,
986                                                                                 mStrategies,
987                                                                                 visSamples);
988
989                if (SAMPLE_AFTER_SUBDIVISION)
990                        ComputeSampleContributions(visSamples, true, storeViewCells);
991
992                // various visualizations
993                Visualize(preprocessor->mObjects, visSamples);
994
995                disposeRays(visSamples, outRays);
996        }
997
998        // recalculate view cells
999        EvaluateViewCellsStats();
1000
1001        if (1) CompressViewCells();
1002
1003        // write view cells to disc
1004        if (mExportViewCells)
1005        {
1006                char filename[100];
1007
1008                Environment::GetSingleton()->GetStringValue("ViewCells.filename", filename);
1009                ExportViewCells(filename, mExportPvs, mPreprocessor->mObjects);
1010        }
1011
1012        return numSamples;
1013}
1014
1015
1016AxisAlignedPlane *ViewCellsManager::GetClipPlane()
1017{
1018        return mUseClipPlaneForViz ? &mClipPlaneForViz : NULL;
1019}
1020
1021
1022ViewCellsManager *ViewCellsManager::LoadViewCells(const string &filename,
1023                                                                                                  ObjectContainer &pvsObjects,
1024                                                                                                  bool finalizeViewCells,
1025                                                                                                  BoundingBoxConverter *bconverter)
1026                                                                                                 
1027{
1028        ObjectContainer preprocessorObjects;
1029
1030        return LoadViewCells(filename,
1031                                                 pvsObjects,
1032                                                 preprocessorObjects,
1033                                                 finalizeViewCells,
1034                                                 bconverter);
1035}
1036
1037
1038ViewCellsManager *ViewCellsManager::LoadViewCells(const string &filename,
1039                                                                                                  ObjectContainer &pvsObjects,
1040                                                                                                  ObjectContainer &preprocessorObjects,
1041                                                                                                  bool finalizeViewCells,
1042                                                                                                  BoundingBoxConverter *bconverter)
1043                                                                                                 
1044{
1045        ViewCellsParser parser;
1046        ViewCellsManager *vm = NULL;
1047
1048        const long startTime = GetTime();
1049        const bool success = parser.ParseViewCellsFile(filename,
1050                                                                                                   &vm,
1051                                                                                                   pvsObjects,
1052                                                                                                   preprocessorObjects,
1053                                                                                                   bconverter);
1054
1055        if (!success)
1056        {
1057                Debug << "Error: loading view cells failed!" << endl;
1058                DEL_PTR(vm);
1059
1060                return NULL;
1061        }
1062       
1063        if (0)
1064        {
1065                vm->ResetViewCells();
1066        }
1067        else
1068        {
1069                //hack: should work with reset function
1070                ViewCellContainer leaves;
1071
1072                vm->mViewCells.clear();
1073                vm->mViewCellsTree->CollectLeaves(vm->mViewCellsTree->GetRoot(), leaves);
1074               
1075                ViewCellContainer::const_iterator it, it_end = leaves.end();
1076
1077                for (it = leaves.begin(); it != it_end; ++ it)
1078                {
1079                        vm->mViewCells.push_back(*it);
1080                }
1081        }
1082
1083        vm->mViewCellsFinished = true;
1084        vm->mMaxPvsSize = (int)pvsObjects.size();
1085
1086        if (finalizeViewCells)
1087        {
1088                // create the meshes and compute view cell volumes
1089                const bool createMeshes = true;
1090                vm->FinalizeViewCells(createMeshes);
1091        }
1092
1093        cout << (int)vm->mViewCells.size() << " view cells loaded in "
1094                 << TimeDiff(startTime, GetTime()) * 1e-3f << " secs" << endl;
1095
1096        Debug << (int)vm->mViewCells.size() << " view cells loaded in "
1097                  << TimeDiff(startTime, GetTime()) * 1e-3f << " secs" << endl;
1098       
1099        return vm;
1100}
1101
1102
1103bool VspBspViewCellsManager::ExportViewCells(const string filename,
1104                                                                                         const bool exportPvs,
1105                                                                                         const ObjectContainer &objects)
1106{
1107        if (!ViewCellsConstructed() || !ViewCellsTreeConstructed())
1108        {
1109                return false;
1110        }
1111
1112        cout << "exporting view cells to xml ... ";
1113
1114        OUT_STREAM stream(filename.c_str());
1115
1116        // for output we need unique ids for each view cell
1117        CreateUniqueViewCellIds();
1118
1119        stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"<<endl;
1120        stream << "<VisibilitySolution>" << endl;
1121
1122        if (exportPvs)
1123        {
1124                //-- export bounding boxes
1125                stream << "<BoundingBoxes>" << endl;
1126
1127                if (mUseKdPvs)
1128                {
1129                        vector<KdIntersectable *>::iterator kit, kit_end = GetPreprocessor()->mKdTree->mKdIntersectables.end();
1130
1131                        int id = 0;
1132                        for (kit = GetPreprocessor()->mKdTree->mKdIntersectables.begin(); kit != kit_end; ++ kit, ++ id)
1133                        {
1134                                Intersectable *obj = *kit;
1135                                const AxisAlignedBox3 box = obj->GetBox();
1136                 
1137                                obj->SetId(id);
1138       
1139                                stream << "<BoundingBox" << " id=\"" << id << "\""
1140                                           << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
1141                                           << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z << "\" />" << endl;
1142                        }
1143                }
1144                else
1145                {
1146                        ObjectContainer::const_iterator oit, oit_end = objects.end();
1147               
1148                        for (oit = objects.begin(); oit != oit_end; ++ oit)
1149                        {
1150                                const AxisAlignedBox3 box = (*oit)->GetBox();
1151
1152                                ////////////
1153                                //-- the bounding boxes
1154
1155                                stream << "<BoundingBox" << " id=\"" << (*oit)->GetId() << "\""
1156                                           << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
1157                                           << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z << "\" />" << endl;
1158                        }
1159                }
1160
1161                stream << "</BoundingBoxes>" << endl;
1162        }
1163
1164       
1165        /////////////
1166        //-- export the view cells and the pvs
1167
1168        const int numViewCells = mCurrentViewCellsStats.viewCells;
1169        stream << "<ViewCells number=\"" << numViewCells << "\" >" << endl;
1170
1171        mViewCellsTree->Export(stream, exportPvs);
1172
1173        stream << "</ViewCells>" << endl;
1174
1175
1176        //////////
1177        //-- export the view space hierarchy
1178       
1179        stream << "<ViewSpaceHierarchy type=\"bsp\""
1180                   << " min=\"" << mViewSpaceBox.Min().x << " " << mViewSpaceBox.Min().y << " " << mViewSpaceBox.Min().z << "\""
1181                   << " max=\"" << mViewSpaceBox.Max().x << " " << mViewSpaceBox.Max().y << " " << mViewSpaceBox.Max().z << "\">" << endl;
1182
1183        mVspBspTree->Export(stream);
1184        stream << "</ViewSpaceHierarchy>" << endl;
1185
1186        stream << "</VisibilitySolution>" << endl;
1187
1188        stream.close();
1189        cout << "finished" << endl;
1190
1191        return true;
1192}
1193
1194void ViewCellsManager::EvalViewCellHistogram(const string filename,
1195                                                                                         const int nViewCells)
1196{
1197        std::ofstream outstream;
1198        outstream.open(filename.c_str());
1199
1200        ViewCellContainer viewCells;
1201        // $$ JB hack - the collect best viewcells does not work?
1202#if 1
1203        mViewCellsTree->CollectBestViewCellSet(viewCells, nViewCells);
1204#else
1205        viewCells = mViewCells;
1206#endif
1207
1208        float maxRenderCost, minRenderCost;
1209
1210        // sort by render cost
1211        sort(viewCells.begin(), viewCells.end(), ViewCell::SmallerRenderCost);
1212
1213        minRenderCost = viewCells.front()->GetRenderCost();
1214        maxRenderCost = viewCells.back()->GetRenderCost();
1215
1216        Debug << "histogram min rc: " << minRenderCost << " max rc: " << maxRenderCost << endl;
1217
1218    int histoIntervals;
1219        Environment::GetSingleton()->GetIntValue("Preprocessor.histogram.intervals", histoIntervals);
1220        const int intervals = min(histoIntervals, (int)viewCells.size());
1221
1222        int histoMaxVal;
1223        Environment::GetSingleton()->GetIntValue("Preprocessor.histogram.maxValue", histoMaxVal);
1224        maxRenderCost = min((float)histoMaxVal, maxRenderCost);
1225
1226       
1227        const float range = maxRenderCost - minRenderCost;
1228        const float stepSize = range / (float)intervals;
1229
1230        float currentRenderCost = minRenderCost;//(int)ceil(minRenderCost);
1231
1232        const float totalRenderCost = mViewCellsTree->GetRoot()->GetRenderCost();
1233        const float totalVol = GetViewSpaceBox().GetVolume();
1234        //const float totalVol = mViewCellsTree->GetRoot()->GetVolume();
1235
1236        int j = 0;
1237        int i = 0;
1238       
1239        ViewCellContainer::const_iterator it = viewCells.begin(), it_end = viewCells.end();             
1240
1241        // count for integral
1242        float volSum = 0;
1243        int smallerCostSum = 0;
1244       
1245        // note can skip computations for view cells already
1246        // evaluated and delete them from vector ...
1247    while (1)
1248        {
1249                // count for histogram value
1250                float volDif = 0;
1251                int smallerCostDif = 0;
1252
1253                while ((i < (int)viewCells.size()) && (viewCells[i]->GetRenderCost() < currentRenderCost))
1254                {
1255                        volSum += viewCells[i]->GetVolume();
1256                        volDif += viewCells[i]->GetVolume();
1257
1258                        ++ i;
1259                        ++ smallerCostSum;
1260                        ++ smallerCostDif;
1261                }
1262               
1263                if ((i >= (int)viewCells.size()) || (currentRenderCost >= maxRenderCost))
1264                        break;
1265               
1266                const float rcRatio = currentRenderCost / maxRenderCost;
1267                const float volRatioSum = volSum / totalVol;
1268                const float volRatioDif = volDif / totalVol;
1269
1270                outstream << "#Pass\n" << j ++ << endl;
1271                outstream << "#RenderCostRatio\n" << rcRatio << endl;
1272                outstream << "#WeightedCost\n" << currentRenderCost / totalVol << endl;
1273                outstream << "#ViewCellsDif\n" << smallerCostDif << endl;
1274                outstream << "#ViewCellsSum\n" << smallerCostSum << endl;       
1275                outstream << "#VolumeDif\n" << volRatioDif << endl << endl;
1276                outstream << "#VolumeSum\n" << volRatioSum << endl << endl;
1277
1278                // increase current render cost
1279                currentRenderCost += stepSize;
1280        }
1281
1282        outstream.close();
1283}
1284
1285void ViewCellsManager::EvalViewCellHistogramForPvsSize(const string filename,
1286                                                                                                           const int nViewCells)
1287{
1288        std::ofstream outstream;
1289        outstream.open(filename.c_str());
1290
1291        ViewCellContainer viewCells;
1292#ifdef USE_BIT_PVS
1293        cout << "objects size: " << (int)ObjectPvsIterator::sObjects.size() << endl;
1294        cout << "pvs size: " <<  ObjectPvs::sPvsSize << endl;
1295#endif
1296        // $$ JB hack - the collect best viewcells does not work?
1297#if 0
1298        mViewCellsTree->CollectBestViewCellSet(viewCells, nViewCells);
1299#else
1300        viewCells = mViewCells;
1301#endif
1302        ViewCellContainer::iterator it = viewCells.begin(), it_end = viewCells.end();           
1303        for (; it != it_end; ++it)
1304        {
1305                if (1)
1306                        (*it)->UpdatePvsCost();
1307                else
1308                        (*it)->SetPvsCost((float)(*it)->GetFilteredPvsSize());
1309        }
1310
1311        float maxPvs, maxVal, minVal;
1312       
1313        // sort by pvs size
1314        sort(viewCells.begin(), viewCells.end(), ViewCell::SmallerPvs);
1315
1316        maxPvs = viewCells.back()->GetPvsCost();
1317        minVal = 0;
1318
1319        // hack: normalize pvs size
1320        int histoMaxVal;
1321        Environment::GetSingleton()->GetIntValue("Preprocessor.histogram.maxValue", histoMaxVal);
1322        maxVal = max((float)histoMaxVal, maxPvs);
1323               
1324        Debug << "histogram minpvssize: " << minVal << " maxpvssize: " << maxVal
1325                << " real maxpvs " << maxPvs << endl;
1326
1327        int histoIntervals;
1328        Environment::GetSingleton()->GetIntValue("Preprocessor.histogram.intervals", histoIntervals);
1329        const int intervals = min(histoIntervals, (int)viewCells.size());
1330
1331        const float range = maxVal - minVal;
1332        int stepSize = (int)(range / intervals);
1333
1334        // set step size to avoid endless loop
1335        if (!stepSize) stepSize = 1;
1336       
1337        Debug << "intervals " << histoIntervals << endl;
1338        Debug << "stepsize: " << stepSize << endl;
1339        cout << "intervals " << histoIntervals << endl;
1340        cout << "stepsize: " << stepSize << endl;
1341
1342        const float totalRenderCost = mViewCellsTree->GetRoot()->GetRenderCost();
1343        const float totalVol = GetViewSpaceBox().GetVolume();
1344
1345        float currentPvs = minVal;
1346       
1347        int i = 0;
1348        int j = 0;
1349        float volSum = 0;
1350        int smallerSum = 0;
1351
1352        it = viewCells.begin();
1353       
1354        for (int j = 0; j < intervals; ++ j)
1355        {
1356                float volDif = 0;
1357                int smallerDif = 0;
1358
1359                while ((i < (int)viewCells.size()) &&
1360                           (viewCells[i]->GetPvsCost() < currentPvs))
1361                {
1362                        volDif += viewCells[i]->GetVolume();
1363                        volSum += viewCells[i]->GetVolume();
1364
1365                        ++ i;
1366                        ++ smallerDif;
1367                        ++ smallerSum;
1368                }
1369               
1370                //              if (0 && (i < (int)viewCells.size()))
1371                //                Debug << "new pvs cost increase: " << mViewCellsTree->GetPvsCost(viewCells[i])
1372                //                              << " " << currentPvs << endl;
1373               
1374                const float volRatioDif = volDif / totalVol;
1375                const float volRatioSum = volSum / totalVol;
1376
1377                outstream << "#Pass\n" << j << endl;
1378                outstream << "#Pvs\n" << currentPvs << endl;
1379                outstream << "#ViewCellsDif\n" << smallerDif << endl;
1380                outstream << "#ViewCellsSum\n" << smallerSum << endl;   
1381                outstream << "#VolumeDif\n" << volRatioDif << endl << endl;
1382                outstream << "#VolumeSum\n" << volRatioSum << endl << endl;
1383       
1384                //-- increase current pvs size to define next interval
1385                currentPvs += stepSize;
1386        }
1387
1388        outstream.close();
1389}
1390
1391
1392void ViewCellsManager::EvalViewCellHistogramForPvsSize(const string filename,
1393                                                                                                           ViewCellContainer &viewCells)
1394{
1395        std::ofstream outstream;
1396        outstream.open(filename.c_str());
1397
1398        float maxPvs, maxVal, minVal;
1399       
1400        // sort by pvs size
1401        sort(viewCells.begin(), viewCells.end(), ViewCell::SmallerPvs);
1402
1403        maxPvs = viewCells.back()->GetPvsCost();
1404        minVal = 0;
1405
1406        // hack: normalize pvs size
1407        int histoMaxVal;
1408        Environment::GetSingleton()->GetIntValue("Preprocessor.histogram.maxValue", histoMaxVal);
1409        maxVal = max((float)histoMaxVal, maxPvs);
1410               
1411        Debug << "histogram minpvssize: " << minVal << " maxpvssize: " << maxVal
1412                << " real maxpvs " << maxPvs << endl;
1413
1414        int histoIntervals;
1415        Environment::GetSingleton()->GetIntValue("Preprocessor.histogram.intervals", histoIntervals);
1416        const int intervals = min(histoIntervals, (int)viewCells.size());
1417
1418        const float range = maxVal - minVal;
1419        int stepSize = (int)(range / intervals);
1420
1421        // set step size to avoid endless loop
1422        if (!stepSize) stepSize = 1;
1423       
1424        Debug << "intervals " << histoIntervals << endl;
1425        Debug << "stepsize: " << stepSize << endl;
1426        cout << "intervals " << histoIntervals << endl;
1427        cout << "stepsize: " << stepSize << endl;
1428
1429        const float totalRenderCost = mViewCellsTree->GetRoot()->GetRenderCost();
1430        const float totalVol = GetViewSpaceBox().GetVolume();
1431
1432        float currentPvs = minVal;
1433       
1434        int i = 0;
1435        int j = 0;
1436        float volSum = 0;
1437        int smallerSum = 0;
1438
1439        //ViewCellContainer::const_iterator it = viewCells.begin(), it_end = viewCells.end();   
1440       
1441        for (int j = 0; j < intervals; ++ j)
1442        {
1443                float volDif = 0;
1444                int smallerDif = 0;
1445
1446                while ((i < (int)viewCells.size()) &&
1447                           (viewCells[i]->GetPvsCost() < currentPvs))
1448                {
1449                        volDif += viewCells[i]->GetVolume();
1450                        volSum += viewCells[i]->GetVolume();
1451
1452                        ++ i;
1453                        ++ smallerDif;
1454                        ++ smallerSum;
1455                }
1456               
1457                //              if (0 && (i < (int)viewCells.size()))
1458                //                Debug << "new pvs cost increase: " << mViewCellsTree->GetPvsCost(viewCells[i])
1459                //                              << " " << currentPvs << endl;
1460               
1461                const float volRatioDif = volDif / totalVol;
1462                const float volRatioSum = volSum / totalVol;
1463
1464                outstream << "#Pass\n" << j << endl;
1465                outstream << "#Pvs\n" << currentPvs << endl;
1466                outstream << "#ViewCellsDif\n" << smallerDif << endl;
1467                outstream << "#ViewCellsSum\n" << smallerSum << endl;   
1468                outstream << "#VolumeDif\n" << volRatioDif << endl << endl;
1469                outstream << "#VolumeSum\n" << volRatioSum << endl << endl;
1470       
1471                //-- increase current pvs size to define next interval
1472                currentPvs += stepSize;
1473        }
1474
1475        outstream.close();
1476}
1477
1478
1479bool ViewCellsManager::GetExportPvs() const
1480{
1481        return mExportPvs;
1482}
1483
1484
1485void ViewCellsManager::ResetPvs()
1486{
1487        if (ViewCellsTreeConstructed())
1488        {
1489                mViewCellsTree->ResetPvs();
1490        }
1491        else
1492        {
1493                cout << "view cells tree not constructed" << endl;
1494        }
1495}
1496
1497
1498void ViewCellsManager::ExportStats(const string &fileName)
1499{
1500        mViewCellsTree->ExportStats(fileName);
1501}
1502
1503
1504void ViewCellsManager::EvalViewCellPartition()
1505{
1506        int samplesPerPass;
1507        int numSamples;
1508        int castSamples = 0;
1509        char str[64];
1510        int oldSamples = 0;
1511
1512        int samplesForStats;
1513
1514        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.samplesPerPass", samplesPerPass);
1515        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.samplesForStats", samplesForStats);
1516        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.samples", numSamples);
1517
1518        char statsPrefix[100];
1519        Environment::GetSingleton()->GetStringValue("ViewCells.Evaluation.statsPrefix", statsPrefix);
1520
1521        Debug << "view cell evaluation samples per pass: " << samplesPerPass << endl;
1522        Debug << "view cell evaluation samples: " << numSamples << endl;
1523        Debug << "view cell stats prefix: " << statsPrefix << endl;
1524
1525        cout << "reseting pvs ... ";
1526               
1527        const bool startFromZero = true;
1528
1529        // reset pvs and start over from zero
1530        if (startFromZero)
1531        {
1532                mViewCellsTree->ResetPvs();
1533        }
1534        else // start from current sampless
1535        {
1536                // statistics before casting more samples
1537                cout << "compute new statistics ... ";
1538                sprintf(str, "-%09d-eval.log", castSamples);
1539                string fName = string(statsPrefix) + string(str);
1540
1541                mViewCellsTree->ExportStats(fName);
1542                cout << "finished" << endl;
1543        }
1544
1545        cout << "finished" << endl;
1546    cout << "Evaluating view cell partition ... " << endl;
1547
1548        while (castSamples < numSamples)
1549        {               
1550                ///////////////
1551                //-- we have to use uniform sampling strategy for construction rays
1552
1553                VssRayContainer evaluationSamples;
1554                const int samplingType = mEvaluationSamplingType;
1555
1556                long startTime = GetTime();
1557
1558                cout << "casting " << samplesPerPass << " samples ... ";
1559                Debug << "casting " << samplesPerPass << " samples ... ";
1560
1561                CastPassSamples(samplesPerPass, mStrategies, evaluationSamples);
1562               
1563                castSamples += samplesPerPass;
1564
1565                Real timeDiff = TimeDiff(startTime, GetTime());
1566               
1567                cout << "finished in " << timeDiff * 1e-3f << " secs" << endl;
1568                cout << "computing sample contributions of " << (int)evaluationSamples.size()  << " samples ... ";
1569               
1570                Debug << "finished in " << timeDiff * 1e-3f << " secs" << endl;
1571                Debug << "computing sample contributions of " << (int)evaluationSamples.size()  << " samples ... ";
1572
1573                startTime = GetTime();
1574
1575                ComputeSampleContributions(evaluationSamples, true, false);
1576
1577                timeDiff = TimeDiff(startTime, GetTime());
1578                cout << "finished in " << timeDiff * 1e-3 << " secs" << endl;
1579                Debug << "finished in " << timeDiff * 1e-3 << " secs" << endl;
1580
1581                if ((castSamples >= samplesForStats + oldSamples) || (castSamples >= numSamples))
1582                {
1583                        oldSamples += samplesForStats;
1584
1585                        ///////////
1586                        //-- output stats
1587
1588                        sprintf(str, "-%09d-eval.log", castSamples);
1589                        string fileName = string(statsPrefix) + string(str);
1590
1591                        ///////////////
1592                        //-- propagate pvs or pvs size information
1593
1594                        startTime = GetTime();
1595                        ObjectPvs pvs;
1596
1597                        cout << "updating pvs for evaluation ... " << endl;
1598
1599                        UpdatePvsForEvaluation(mViewCellsTree->GetRoot(), pvs);
1600
1601                        timeDiff = TimeDiff(startTime, GetTime());
1602                        cout << "finished updating the pvs in " << timeDiff * 1e-3 << " secs" << endl;
1603                        Debug << "pvs evaluated in " << timeDiff * 1e-3 << " secs" << endl;
1604               
1605                        startTime = GetTime();
1606                        cout << "compute new statistics ... " << endl;
1607
1608                        ExportStats(fileName);
1609
1610                        timeDiff = TimeDiff(startTime, GetTime());
1611                        cout << "finished in " << timeDiff * 1e-3 << " secs" << endl;
1612                        Debug << "statistis computed in " << timeDiff * 1e-3 << " secs" << endl;
1613                }
1614
1615                disposeRays(evaluationSamples, NULL);
1616        }
1617       
1618
1619        ////////////
1620        //-- histogram
1621
1622        const int numLeaves = mViewCellsTree->GetNumInitialViewCells(mViewCellsTree->GetRoot());
1623        bool useHisto;
1624        int histoStepSize;
1625
1626        Environment::GetSingleton()->GetBoolValue("ViewCells.Evaluation.histogram", useHisto);
1627        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.histoStepSize", histoStepSize);
1628
1629        if (useHisto)
1630        {
1631                // evaluate view cells in a histogram           
1632                char s[64];
1633
1634                for (int pass = histoStepSize; pass <= numLeaves; pass += histoStepSize)
1635                {
1636                        string filename;
1637
1638                        cout << "computing histogram for " << pass << " view cells" << endl;
1639#if 0
1640                        //-- evaluate histogram for render cost
1641                        sprintf(s, "-%09d-histo.log", pass);
1642                        filename = string(statsPrefix) + string(s);
1643
1644                        EvalViewCellHistogram(filename, pass);
1645
1646#endif
1647                        //////////////////////////////////////////
1648            //-- evaluate histogram for pvs size
1649
1650                        cout << "computing pvs histogram for " << pass << " view cells" << endl;
1651
1652                        sprintf(s, "-%09d-histo-pvs.log", pass);
1653                        filename = string(statsPrefix) + string(s);
1654
1655                        EvalViewCellHistogram(filename, pass);
1656                        //                      EvalViewCellHistogramForPvsSize(filename, pass);
1657                }
1658        }
1659}
1660
1661
1662inline float EvalMergeCost(ViewCell *root, ViewCell *candidate)
1663{
1664        return root->GetPvs().GetPvsHomogenity(candidate->GetPvs());
1665}
1666
1667
1668/// Returns index of the best view cells of the neighborhood
1669static int GetBestViewCellIdx(ViewCell *root, const ViewCellContainer &neighborhood)
1670{
1671        int bestViewCellIdx = 0;
1672
1673        float mergeCost = Limits::Infinity;
1674        int i = 0;
1675
1676        ViewCellContainer::const_iterator vit, vit_end = neighborhood.end();
1677
1678        for (vit = neighborhood.begin(); vit != vit_end; ++ vit, ++ i)
1679        {
1680                const float mc = EvalMergeCost(root, *vit);
1681               
1682                if (mc < mergeCost)
1683                {
1684                        mergeCost = mc;
1685                        bestViewCellIdx = i;
1686                }
1687        }
1688
1689        return bestViewCellIdx;
1690}
1691
1692
1693void ViewCellsManager::SetMaxFilterSize(const int size)
1694{
1695        mMaxFilterSize = size;
1696}
1697
1698
1699float ViewCellsManager::EvalRenderCost(Intersectable *obj) //const
1700{
1701        switch (sRenderCostEvaluationType)
1702        {
1703        case PER_OBJECT:
1704                return 1.0f;
1705       
1706        case PER_TRIANGLE:
1707                {
1708                        return (float)obj->NumberOfFaces();
1709                }
1710        default:
1711                cout << "default" << endl;
1712                return 1.0f;
1713        }
1714
1715        // should not come here
1716        return 0.0f;
1717}
1718
1719
1720ViewCell *ViewCellsManager::ConstructLocalMergeTree(ViewCell *currentViewCell,
1721                                                                                                        const ViewCellContainer &viewCells)
1722{
1723        ViewCell *root = currentViewCell;
1724        ViewCellContainer neighborhood = viewCells;
1725
1726        ViewCellContainer::const_iterator it, it_end = neighborhood.end();
1727
1728        const int n = min(mMaxFilterSize, (int)neighborhood.size());
1729       
1730        /////////////////
1731        //-- use priority queue to merge leaf pairs
1732       
1733        for (int nMergedViewCells = 0; nMergedViewCells < n; ++ nMergedViewCells)
1734        {
1735                const int bestViewCellIdx = GetBestViewCellIdx(root, neighborhood);
1736               
1737                ViewCell *bestViewCell = neighborhood[bestViewCellIdx];
1738       
1739                // remove from vector
1740                swap(neighborhood[bestViewCellIdx], neighborhood.back());
1741                neighborhood.pop_back();
1742       
1743                if (!bestViewCell || !root)
1744            cout << "warning!!" << endl;
1745               
1746                // create new root of the hierarchy
1747                root = MergeViewCells(root, bestViewCell);
1748        }
1749
1750        return root;   
1751}
1752
1753
1754struct SortableViewCellEntry {
1755
1756        SortableViewCellEntry() {}
1757        SortableViewCellEntry(const float v, ViewCell *cell):mValue(v), mViewCell(cell) {}
1758
1759        float mValue;
1760        ViewCell *mViewCell;
1761
1762        friend bool operator<(const SortableViewCellEntry &a, const SortableViewCellEntry &b) {
1763                return a.mValue < b.mValue;
1764        }
1765};
1766
1767
1768ViewCell * ViewCellsManager::ConstructLocalMergeTree2(ViewCell *currentViewCell,
1769                                                                                                          const ViewCellContainer &viewCells)
1770{
1771 
1772  vector<SortableViewCellEntry> neighborhood(viewCells.size());
1773  int i, j;
1774  for (i = 0, j = 0; i < viewCells.size(); i++) {
1775        if (viewCells[i] != currentViewCell)
1776          neighborhood[j++] = SortableViewCellEntry(
1777                                                                                                EvalMergeCost(currentViewCell, viewCells[i]),
1778                                                                                                viewCells[i]);
1779  }
1780  neighborhood.resize(j);
1781 
1782  sort(neighborhood.begin(), neighborhood.end());
1783 
1784  ViewCell *root = currentViewCell;
1785 
1786  vector<SortableViewCellEntry>::const_iterator it, it_end = neighborhood.end();
1787 
1788  const int n = min(mMaxFilterSize, (int)neighborhood.size());
1789  //-- use priority queue to merge leaf pairs
1790 
1791  //cout << "neighborhood: " << neighborhood.size() << endl;
1792  for (int nMergedViewCells = 0; nMergedViewCells < n; ++ nMergedViewCells)
1793  {
1794          ViewCell *bestViewCell = neighborhood[nMergedViewCells].mViewCell;
1795          //cout <<nMergedViewCells<<":"<<"homogenity=" <<neighborhood[nMergedViewCells].mValue<<endl;
1796          // create new root of the hierarchy
1797          root = MergeViewCells(root, bestViewCell);
1798          // set negative cost so that this view cell gets deleted
1799          root->SetMergeCost(-1.0f);
1800  }
1801 
1802  return root; 
1803}
1804
1805void
1806ViewCellsManager::DeleteLocalMergeTree(ViewCell *vc
1807                                                                           ) const
1808{
1809        if (!vc->IsLeaf() && vc->GetMergeCost() < 0.0f)
1810        {       
1811                ViewCellInterior *vci = (ViewCellInterior *) vc;
1812                ViewCellContainer::const_iterator it, it_end = vci->mChildren.end();
1813
1814        for (it = vci->mChildren.begin(); it != it_end; ++ it)
1815                        DeleteLocalMergeTree(*it);
1816               
1817                vci->mChildren.clear();
1818               
1819                delete vci;
1820  }
1821}
1822
1823
1824bool ViewCellsManager::CheckValidity(ViewCell *vc,
1825                                                                         int minPvsSize,
1826                                                                         int maxPvsSize) const
1827{
1828
1829        const float pvsCost = vc->GetPvs().EvalPvsCost();
1830
1831        if ((pvsCost > maxPvsSize) || (pvsCost < minPvsSize))
1832        {
1833                cout << "err: " << pvsCost << " " << minPvsSize << " " << maxPvsSize << endl;
1834                return false;
1835        }
1836
1837        return true;
1838}
1839
1840
1841int ViewCellsManager::ComputeBoxIntersections(const AxisAlignedBox3 &box,
1842                                                                                          ViewCellContainer &viewCells) const
1843{
1844        return 0;
1845};
1846
1847
1848AxisAlignedBox3 ViewCellsManager::GetFilterBBox(const Vector3 &viewPoint,
1849                                                                                                const float width) const
1850{
1851  float w = Magnitude(mViewSpaceBox.Size())*width;
1852  Vector3 min = viewPoint - w * 0.5f;
1853  Vector3 max = viewPoint + w * 0.5f;
1854 
1855  return AxisAlignedBox3(min, max);
1856}
1857
1858
1859void ViewCellsManager::GetPrVS(const Vector3 &viewPoint,
1860                                                           PrVs &prvs,
1861                                                           const float filterWidth)
1862{
1863  ViewCell *currentViewCell = GetViewCell(viewPoint);
1864
1865  if (mMaxFilterSize < 1) {
1866        prvs.mViewCell = currentViewCell;
1867        return;
1868  }
1869 
1870  const AxisAlignedBox3 box = GetFilterBBox(viewPoint, filterWidth);
1871 
1872  if (currentViewCell)
1873        {
1874          ViewCellContainer viewCells;
1875          ComputeBoxIntersections(box, viewCells);
1876         
1877          ViewCell *root = ConstructLocalMergeTree2(currentViewCell, viewCells);
1878          prvs.mViewCell = root;
1879         
1880        }
1881  else
1882        {
1883          prvs.mViewCell = NULL;
1884          //prvs.mPvs = root->GetPvs();
1885        }
1886}
1887
1888
1889bool ViewCellsManager::ViewCellsTreeConstructed() const
1890{
1891    return (mViewCellsTree && mViewCellsTree->GetRoot());
1892}
1893
1894
1895void ViewCellsManager::SetValidity(ViewCell *vc,
1896                                                                   int minPvs,
1897                                                                   int maxPvs) const
1898{
1899        vc->SetValid(CheckValidity(vc, minPvs, maxPvs));
1900}
1901
1902
1903void
1904ViewCellsManager::SetValidity(
1905                                                          int minPvsSize,
1906                                                          int maxPvsSize) const
1907{
1908        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
1909
1910
1911        for (it = mViewCells.begin(); it != it_end; ++ it)
1912        {
1913                SetValidity(*it, minPvsSize, maxPvsSize);
1914        }
1915}
1916
1917void
1918ViewCellsManager::SetValidityPercentage(
1919                                                                                const float minValid,
1920                                                                                const float maxValid
1921                                                                                )
1922{
1923  ObjectPvs dummyPvs;
1924  // update pvs sizes
1925  for (int i = 0; i < (int)mViewCells.size(); ++ i) {
1926        UpdatePvsForEvaluation(mViewCells[i], dummyPvs);
1927  }
1928 
1929  sort(mViewCells.begin(), mViewCells.end(), ViewCell::SmallerPvs);
1930 
1931  int start = (int)(mViewCells.size() * minValid);
1932  int end = (int)(mViewCells.size() * maxValid);
1933 
1934  for (int i = 0; i < (int)mViewCells.size(); ++ i)
1935        {
1936          //      cout<<"pvs:"<<mViewCells[i]->GetCachedPvsCost()<<endl;
1937          mViewCells[i]->SetValid(i >= start && i <= end);
1938        }
1939}
1940
1941
1942int ViewCellsManager::CountValidViewcells() const
1943{
1944        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
1945        int valid = 0;
1946
1947        for (it = mViewCells.begin(); it != it_end; ++ it)
1948        {       
1949                if ((*it)->GetValid())
1950                        ++ valid;
1951        }
1952
1953        return valid;
1954}
1955
1956
1957bool ViewCellsManager::LoadViewCellsGeometry(const string filename,
1958                                                                                         const bool extrudeBaseTriangles)
1959{
1960        /// we use predefined view cells from now on
1961        mUsePredefinedViewCells = true;
1962        X3dParser parser;
1963       
1964        if (extrudeBaseTriangles)
1965        {
1966                Environment::GetSingleton()->GetFloatValue("ViewCells.height", parser.mViewCellHeight);
1967                const bool success = parser.ParseFile(filename, *this);
1968
1969                if (!success)
1970                        return false;
1971        }
1972        else
1973        {
1974                // hack: use standard mesh loading
1975                // create temporary scene graph for loading the view cells geometry
1976                // note: delete the meshes as they are created two times for transformed mesh instances.
1977                SceneGraphNode *root = new SceneGraphNode();
1978                const bool success = parser.ParseFile(filename, root, true);
1979               
1980                if (!success)
1981                {
1982                        DEL_PTR(root);
1983                        return false;
1984                }
1985
1986                ObjectContainer::const_iterator oit, oit_end = root->mGeometry.end();
1987               
1988                for (oit = root->mGeometry.begin(); oit != oit_end; ++ oit)
1989                {
1990                        Mesh *mesh;
1991                        if ((*oit)->Type() == Intersectable::TRANSFORMED_MESH_INSTANCE)
1992                        {
1993                                TransformedMeshInstance *mit = static_cast<TransformedMeshInstance *>(*oit);
1994                                mesh = MeshManager::GetSingleton()->CreateResource();
1995                                mit->GetTransformedMesh(*mesh);
1996                        }
1997                        else if ((*oit)->Type() == Intersectable::MESH_INSTANCE)
1998                        {
1999                                MeshInstance *mit = static_cast<MeshInstance *>(*oit);
2000                                mesh = mit->GetMesh();
2001                        }
2002                        mesh->ComputeBoundingBox();
2003                        mViewCells.push_back(GenerateViewCell(mesh));
2004                }
2005
2006                DEL_PTR(root);
2007        }
2008
2009        // set view space box to bounding box of the view cells
2010        AxisAlignedBox3 bbox;
2011        bbox.Initialize();
2012        ViewCellContainer::iterator it = mViewCells.begin(), it_end = mViewCells.end();
2013
2014        for (; it != it_end; ++ it)
2015        {
2016                bbox.Include((*it)->GetMesh()->mBox);
2017        }
2018
2019        SetViewSpaceBox(bbox);
2020        cout << "view space box: " << bbox << endl;
2021        cout << "generated " << (int)mViewCells.size() << " view cells using the geometry " << filename << endl;
2022
2023        return true;
2024}
2025
2026
2027bool ViewCellsManager::GetViewPoint(Vector3 &viewPoint) const
2028{
2029  viewPoint = mViewSpaceBox.GetRandomPoint();
2030  return true;
2031}
2032
2033bool ViewCellsManager::GetViewPoint(Vector3 &viewPoint, const Vector3 &params) const
2034{
2035  viewPoint = mViewSpaceBox.GetRandomPoint(params);
2036  return true;
2037}
2038
2039
2040float ViewCellsManager::GetViewSpaceVolume()
2041{
2042        return mViewSpaceBox.GetVolume() * (2.0f * sqr((float)M_PI));
2043}
2044
2045
2046bool ViewCellsManager::ViewPointValid(const Vector3 &viewPoint) const
2047{
2048        if (!ViewCellsConstructed())
2049        {
2050                return mViewSpaceBox.IsInside(viewPoint);
2051        }
2052        else
2053        {
2054                if (!mViewSpaceBox.IsInside(viewPoint))
2055                        return false;
2056
2057                ViewCell *viewcell = GetViewCell(viewPoint);
2058
2059                if (!viewcell || !viewcell->GetValid())
2060                        return false;
2061        }
2062
2063        return true;
2064}
2065
2066
2067float
2068ViewCellsManager::ComputeSampleContributions(const VssRayContainer &rays,
2069                                                                                         const bool addContributions,
2070                                                                                         const bool storeViewCells,
2071                                                                                         const bool useHitObjects)
2072{
2073        float sum = 0.0f;
2074
2075        VssRayContainer::const_iterator it, it_end = rays.end();
2076
2077        for (it = rays.begin(); it != it_end; ++ it)
2078        {
2079                if (!ViewCellsConstructed())
2080                {
2081                        // view cells not yet constructed
2082                        // just take the lenghts of the rays as contributions
2083                        if ((*it)->mTerminationObject)
2084                        {
2085                                sum += (*it)->Length();
2086                        }
2087                }
2088                else
2089                {
2090                        sum += ComputeSampleContribution(*(*it), addContributions, storeViewCells, useHitObjects);
2091                }
2092        }
2093
2094        cout << "view cell cast time: " << viewCellCastTimer.TotalTime() << " s" << endl;
2095        Debug << "view cell cast time: " << viewCellCastTimer.TotalTime() << " s" << endl;
2096
2097        cout << "pvs time: " << pvsTimer.TotalTime() << " s" << endl;
2098        Debug << "pvs time: " << pvsTimer.TotalTime() << " s" << endl;
2099       
2100        return sum;
2101}
2102
2103
2104void ViewCellsManager::EvaluateViewCellsStats()
2105{
2106        mCurrentViewCellsStats.Reset();
2107        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
2108
2109        for (it = mViewCells.begin(); it != it_end; ++ it)
2110        {
2111                mViewCellsTree->UpdateViewCellsStats(*it, mCurrentViewCellsStats);
2112        }
2113}
2114
2115
2116void ViewCellsManager::EvaluateRenderStatistics(float &totalRenderCost,
2117                                                                                                float &expectedRenderCost,
2118                                                                                                float &deviation,
2119                                                                                                float &variance,
2120                                                                                                float &totalCost,
2121                                                                                                float &avgRenderCost)
2122{
2123        ////////////
2124        //-- compute expected value
2125
2126        totalRenderCost = 0;
2127        totalCost = 0;
2128
2129        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
2130
2131        for (it = mViewCells.begin(); it != it_end; ++ it)
2132        {
2133                ViewCell *vc = *it;
2134                totalRenderCost += vc->GetPvs().EvalPvsCost() * vc->GetVolume();
2135                totalCost += (int)vc->GetPvs().EvalPvsCost();
2136        }
2137
2138        // normalize with view space box
2139        totalRenderCost /= mViewSpaceBox.GetVolume();
2140        expectedRenderCost = totalRenderCost / (float)mViewCells.size();
2141        avgRenderCost = totalCost / (float)mViewCells.size();
2142
2143
2144        ///////////
2145        //-- compute standard defiation
2146
2147        variance = 0;
2148        deviation = 0;
2149
2150        for (it = mViewCells.begin(); it != it_end; ++ it)
2151        {
2152                ViewCell *vc = *it;
2153
2154                float renderCost = vc->GetPvs().EvalPvsCost() * vc->GetVolume();
2155                float dev;
2156
2157                if (1)
2158                        dev = fabs(avgRenderCost - (float)vc->GetPvs().EvalPvsCost());
2159                else
2160                        dev = fabs(expectedRenderCost - renderCost);
2161
2162                deviation += dev;
2163                variance += dev * dev;
2164        }
2165
2166        variance /= (float)mViewCells.size();
2167        deviation /= (float)mViewCells.size();
2168}
2169
2170
2171float ViewCellsManager::GetArea(ViewCell *viewCell) const
2172{
2173        return viewCell->GetArea();
2174}
2175
2176
2177float ViewCellsManager::GetVolume(ViewCell *viewCell) const
2178{
2179        return viewCell->GetVolume();
2180}
2181
2182
2183void ViewCellsManager::CompressViewCells()
2184{
2185        if (!(ViewCellsTreeConstructed() && mCompressViewCells))
2186                return;
2187
2188        ////////////
2189        //-- compression
2190       
2191        int pvsEntries = mViewCellsTree->CountStoredPvsEntries(mViewCellsTree->GetRoot());
2192
2193        cout << "number of entries before compress: " << pvsEntries << endl;
2194        Debug << "number of entries before compress: " << pvsEntries << endl;
2195
2196        mViewCellsTree->SetViewCellsStorage(ViewCellsTree::COMPRESSED);
2197
2198        pvsEntries = mViewCellsTree->CountStoredPvsEntries(mViewCellsTree->GetRoot());
2199
2200        Debug << "number of entries after compress: " << pvsEntries << endl;
2201        cout << "number of entries after compress: " << pvsEntries << endl;
2202}
2203
2204
2205ViewCell *ViewCellsManager::ExtrudeViewCell(const Triangle3 &baseTri,
2206                                                                                        const float height) const
2207{
2208        // one mesh per view cell
2209        Mesh *mesh = MeshManager::GetSingleton()->CreateResource();
2210//ootl::hash_map<int, Intersectable *> hmap(-2, NULL);
2211        ////////////
2212        //-- construct prism
2213
2214        // bottom
2215        mesh->mFaces.push_back(new Face(2,1,0));
2216        // top
2217    mesh->mFaces.push_back(new Face(3,4,5));
2218        // sides
2219        mesh->mFaces.push_back(new Face(1, 4, 3, 0));
2220        mesh->mFaces.push_back(new Face(2, 5, 4, 1));
2221        mesh->mFaces.push_back(new Face(3, 5, 2, 0));
2222
2223
2224        /////////////
2225        //-- extrude new vertices for top of prism
2226
2227        const Vector3 triNorm = baseTri.GetNormal();
2228        Triangle3 topTri;
2229
2230        // add base vertices and calculate top vertices
2231        for (int i = 0; i < 3; ++ i)
2232        {
2233                mesh->mVertices.push_back(baseTri.mVertices[i]);
2234        }
2235
2236        // add top vertices
2237        for (int i = 0; i < 3; ++ i)
2238        {
2239                mesh->mVertices.push_back(baseTri.mVertices[i] + height * triNorm);
2240        }
2241
2242        // do we have to preprocess this mesh (we don't want to trace view cells!)?
2243        mesh->ComputeBoundingBox();
2244       
2245        return GenerateViewCell(mesh);
2246}
2247
2248
2249void ViewCellsManager::FinalizeViewCells(const bool createMesh)
2250{
2251        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
2252
2253        // volume and area of the view cells are recomputed
2254        // a view cell mesh is created
2255        for (it = mViewCells.begin(); it != it_end; ++ it)
2256        {
2257                Finalize(*it, createMesh);
2258        }
2259
2260        mViewCellsTree->AssignRandomColors();
2261
2262        mTotalAreaValid = false;
2263}
2264
2265
2266void ViewCellsManager::Finalize(ViewCell *viewCell, const bool createMesh)
2267{
2268        // implemented in subclasses
2269}
2270
2271
2272/** fast way of merging 2 view cells.
2273*/
2274ViewCellInterior *ViewCellsManager::MergeViewCells(ViewCell *left, ViewCell *right) const
2275{
2276        // generate parent view cell
2277        ViewCellInterior *vc = new ViewCellInterior();
2278
2279        vc->GetPvs().Clear();
2280        ObjectPvs::Merge(vc->GetPvs(), left->GetPvs(), right->GetPvs());
2281
2282        // set only links to child (not from child to parent, maybe not wished!!)
2283        vc->mChildren.push_back(left);
2284        vc->mChildren.push_back(right);
2285
2286        // update pvs size
2287        UpdateScalarPvsSize(vc, vc->GetPvs().EvalPvsCost(), vc->GetPvs().GetSize());
2288
2289        return vc;
2290}
2291
2292
2293ViewCellInterior *ViewCellsManager::MergeViewCells(ViewCellContainer &children) const
2294{
2295        ViewCellInterior *vc = new ViewCellInterior();
2296        ViewCellContainer::const_iterator it, it_end = children.end();
2297
2298        for (it = children.begin(); it != it_end; ++ it)
2299        {
2300                vc->GetPvs().MergeInPlace((*it)->GetPvs());
2301       
2302                vc->mChildren.push_back(*it);
2303        }
2304
2305        return vc;
2306}
2307
2308
2309void ViewCellsManager::SetRenderer(Renderer *renderer)
2310{
2311        mRenderer = renderer;
2312}
2313
2314
2315ViewCellsTree *ViewCellsManager::GetViewCellsTree()
2316{
2317        return mViewCellsTree;
2318}
2319
2320
2321void ViewCellsManager::SetVisualizationSamples(const int visSamples)
2322{
2323        mVisualizationSamples = visSamples;
2324}
2325
2326
2327void ViewCellsManager::SetConstructionSamples(const int constructionSamples)
2328{
2329        mConstructionSamples = constructionSamples;
2330}
2331
2332
2333void ViewCellsManager::SetInitialSamples(const int initialSamples)
2334{
2335        mInitialSamples = initialSamples;
2336}
2337
2338
2339void ViewCellsManager::SetPostProcessSamples(const int postProcessSamples)
2340{
2341        mPostProcessSamples = postProcessSamples;
2342}
2343
2344
2345int ViewCellsManager::GetVisualizationSamples() const
2346{
2347        return mVisualizationSamples;
2348}
2349
2350
2351int ViewCellsManager::GetConstructionSamples() const
2352{
2353        return mConstructionSamples;
2354}
2355
2356
2357int ViewCellsManager::GetPostProcessSamples() const
2358{
2359        return mPostProcessSamples;
2360}
2361
2362
2363void ViewCellsManager::UpdatePvs()
2364{
2365        if (mViewCellPvsIsUpdated || !ViewCellsTreeConstructed())
2366                return;
2367
2368        mViewCellPvsIsUpdated = true;
2369
2370        ViewCellContainer leaves;
2371        mViewCellsTree->CollectLeaves(mViewCellsTree->GetRoot(), leaves);
2372
2373        ViewCellContainer::const_iterator it, it_end = leaves.end();
2374
2375        for (it = leaves.begin(); it != it_end; ++ it)
2376        {
2377                mViewCellsTree->PropagatePvs(*it);
2378        }
2379}
2380
2381
2382void ViewCellsManager::GetPvsStatistics(PvsStatistics &stat)
2383{
2384  // update pvs of view cells tree if necessary
2385  if (0) UpdatePvs();
2386 
2387  ViewCellContainer::const_iterator it = mViewCells.begin();
2388 
2389  stat.viewcells = 0;
2390  stat.minPvs = 100000000;
2391  stat.maxPvs = 0;
2392  stat.avgPvs = 0.0f;
2393  stat.avgPvsEntries = 0.0f;
2394  stat.avgFilteredPvs = 0.0f;
2395  stat.avgFilteredPvsEntries = 0.0f;
2396  stat.avgFilterContribution = 0.0f;
2397  stat.avgFilterRadius = 0;
2398  stat.avgFilterRatio = 0;
2399  stat.avgRelPvsIncrease = 0.0f;
2400  stat.devRelPvsIncrease = 0.0f;
2401  stat.renderCost = 0.0f;
2402  stat.mem = 0.0f;
2403
2404  if (mPerViewCellStat.size() != mViewCells.size()) {
2405        // reset the pvs size array after the first call to this routine
2406        mPerViewCellStat.resize(mViewCells.size());
2407        for (int i=0; i < mPerViewCellStat.size(); i++) {
2408          mPerViewCellStat[i].pvsSize = 0.0f;
2409          mPerViewCellStat[i].relPvsIncrease = 0.0f;
2410        }
2411  }
2412  int i;
2413  bool evaluateFilter;
2414  Environment::GetSingleton()->GetBoolValue("Preprocessor.evaluateFilter", evaluateFilter);
2415
2416  const float vol = mViewSpaceBox.GetVolume();
2417
2418  for (i = 0; it != mViewCells.end(); ++ it, ++ i)
2419  {
2420          ViewCell *viewcell = *it;
2421          if (viewcell->GetValid()) {
2422                  const float pvsCost = mViewCellsTree->GetPvsCost(viewcell);
2423                  const float renderCost = pvsCost * viewcell->GetVolume() / vol;
2424
2425                  if (pvsCost < stat.minPvs)
2426                          stat.minPvs = pvsCost;
2427                  if (pvsCost > stat.maxPvs)
2428                          stat.maxPvs = pvsCost;
2429
2430                  stat.avgPvs += pvsCost;
2431                  stat.renderCost += renderCost;
2432
2433                  const float pvsEntries = (float)mViewCellsTree->GetPvsEntries(viewcell);
2434                  stat.avgPvsEntries += pvsEntries;
2435
2436                  if (mPerViewCellStat[i].pvsSize > 0.0f)
2437                          mPerViewCellStat[i].relPvsIncrease = (pvsCost - mPerViewCellStat[i].pvsSize) / mPerViewCellStat[i].pvsSize;
2438
2439                  stat.avgRelPvsIncrease += mPerViewCellStat[i].relPvsIncrease;
2440
2441                  // update the pvs size
2442                  mPerViewCellStat[i].pvsSize = pvsCost;
2443
2444
2445
2446                  if (evaluateFilter) {
2447                          ObjectPvs filteredPvs;
2448
2449                          PvsFilterStatistics fstat = ApplyFilter2(viewcell,
2450                                  false,
2451                                  mFilterWidth,
2452                                  filteredPvs);
2453
2454                          float filteredCost = filteredPvs.EvalPvsCost();
2455
2456                          stat.avgFilteredPvs += filteredCost;
2457                          stat.avgFilteredPvsEntries += filteredPvs.GetSize();
2458
2459                          stat.avgFilterContribution += filteredCost - pvsCost;
2460
2461                          stat.avgFilterRadius += fstat.mAvgFilterRadius;
2462                          int sum = fstat.mGlobalFilterCount + fstat.mLocalFilterCount;
2463                          if (sum) {
2464                                  stat.avgFilterRatio += fstat.mLocalFilterCount /
2465                                          (float) sum;
2466                          }
2467
2468                  } else {
2469                          stat.avgFilteredPvs += pvsCost;
2470                          stat.avgFilterContribution += 0;
2471                  }
2472
2473                  ++ stat.viewcells;
2474          }
2475  }
2476
2477
2478
2479  if (stat.viewcells) {
2480          stat.mem = (float)(ObjectPvs::GetEntrySizeByte() * stat.avgPvsEntries + stat.viewcells * 16) / float(1024 * 1024);
2481
2482          stat.avgPvs/=stat.viewcells;
2483          stat.avgPvsEntries/=stat.viewcells;
2484          stat.avgFilteredPvsEntries/=stat.viewcells;
2485          stat.avgFilteredPvs/=stat.viewcells;
2486          stat.avgFilterContribution/=stat.viewcells;
2487          stat.avgFilterRadius/=stat.viewcells;
2488          stat.avgFilterRatio/=stat.viewcells;
2489          stat.avgRelPvsIncrease/=stat.viewcells;
2490         
2491          // evaluate std deviation of relPvsIncrease
2492          float sum=0.0f;
2493          for (i=0; i < stat.viewcells; i++) {
2494                  sum += sqr(mPerViewCellStat[i].relPvsIncrease - stat.avgRelPvsIncrease);
2495          }
2496          stat.devRelPvsIncrease = sqrt(sum/stat.viewcells);
2497  }
2498
2499}
2500
2501
2502void ViewCellsManager::PrintPvsStatistics(ostream &s)
2503{
2504  s<<"############# Viewcell PVS STAT ##################\n";
2505  PvsStatistics pvsStat;
2506  GetPvsStatistics(pvsStat);
2507  s<<"#AVG_PVS\n"<<pvsStat.avgPvs<<endl;
2508  s<<"#AVG_ENTRIES_PVS\n"<<pvsStat.avgPvsEntries<<endl;
2509  s<<"#RENDERCOST\n"<<pvsStat.renderCost<<endl;
2510  s<<"#AVG_FILTERED_PVS\n"<<pvsStat.avgFilteredPvs<<endl;
2511  s<<"#AVG_FILTERED_ENTRIES_PVS\n"<<pvsStat.avgFilteredPvsEntries<<endl;
2512  s<<"#AVG_FILTER_CONTRIBUTION\n"<<pvsStat.avgFilterContribution<<endl;
2513  s<<"#AVG_FILTER_RADIUS\n"<<pvsStat.avgFilterRadius<<endl;
2514  s<<"#AVG_FILTER_RATIO\n"<<pvsStat.avgFilterRatio<<endl;
2515  s<<"#MAX_PVS\n"<<pvsStat.maxPvs<<endl;
2516  s<<"#MIN_PVS\n"<<pvsStat.minPvs<<endl;
2517  s<<"#AVG_REL_PVS_INCREASE\n"<<pvsStat.avgRelPvsIncrease<<endl;
2518  s<<"#DEV_REL_PVS_INCREASE\n"<<pvsStat.devRelPvsIncrease<<endl;
2519  s<<"#MEMROY\n"<<pvsStat.mem<<endl;
2520
2521  s<<"#CONTRIBUTING_RAYS\n"<<mSamplesStat.mContributingRays<<endl;
2522
2523  if (mSamplesStat.mRays) {
2524        s<<"#AVG_VIEWCELLS_PER_RAY\n"<<mSamplesStat.mViewCells/(float)mSamplesStat.mRays<<endl;
2525  } else {
2526        s<<"#AVG_VIEWCELLS_PER_RAY\n 1 \n";
2527  }
2528  mSamplesStat.Reset();
2529}
2530
2531
2532int ViewCellsManager::CastBeam(Beam &beam)
2533{
2534        return 0;
2535}
2536
2537
2538ViewCellContainer &ViewCellsManager::GetViewCells()
2539{
2540        return mViewCells;
2541}
2542
2543
2544void ViewCellsManager::SetViewSpaceBox(const AxisAlignedBox3 &box)
2545{
2546        mViewSpaceBox = box;
2547       
2548        // hack: create clip plane relative to new view space box
2549        CreateClipPlane();
2550        // the total area of the view space has changed
2551        mTotalAreaValid = false;
2552}
2553
2554
2555void ViewCellsManager::CreateClipPlane()
2556{
2557        int axis = 0;
2558        float pos;
2559        bool orientation;
2560        Vector3 absPos;
2561
2562        Environment::GetSingleton()->GetFloatValue("ViewCells.Visualization.clipPlanePos", pos);
2563        Environment::GetSingleton()->GetIntValue("ViewCells.Visualization.clipPlaneAxis", axis);
2564
2565        if (axis < 0)
2566        {
2567                axis = -axis;
2568                orientation = false;
2569                absPos = mViewSpaceBox.Max() -  mViewSpaceBox.Size() * pos;
2570        }
2571        else
2572        {
2573                orientation = true;
2574                absPos = mViewSpaceBox.Min() +  mViewSpaceBox.Size() * pos;
2575        }
2576
2577        mClipPlaneForViz = AxisAlignedPlane(axis, absPos[axis]);
2578        mClipPlaneForViz.mOrientation = orientation;
2579}
2580
2581
2582AxisAlignedBox3 ViewCellsManager::GetViewSpaceBox() const
2583{
2584        return mViewSpaceBox;
2585}
2586
2587
2588void ViewCellsManager::ResetViewCells()
2589{
2590        // recollect view cells
2591        mViewCells.clear();
2592        CollectViewCells();
2593       
2594        // stats are computed once more
2595        EvaluateViewCellsStats();
2596
2597        // has to be recomputed
2598        mTotalAreaValid = false;
2599}
2600
2601
2602int ViewCellsManager::GetMaxPvsSize() const
2603{
2604        return mMaxPvsSize;
2605}
2606
2607
2608int ViewCellsManager::GetMinPvsSize() const
2609{
2610        return mMinPvsSize;
2611}
2612
2613
2614
2615float ViewCellsManager::GetMaxPvsRatio() const
2616{
2617        return mMaxPvsRatio;
2618}
2619
2620
2621inline static void AddSampleToPvs(ObjectPvs &pvs,
2622                                                                  Intersectable *obj,
2623                                                                  const float pdf)
2624{
2625#if PVS_ADD_DIRTY
2626        pvs.AddSampleDirtyCheck(obj, pdf);
2627
2628        if (pvs.RequiresResort())
2629        {
2630                pvs.SimpleSort();
2631        }
2632#else
2633        pvs.AddSample(obj, pdf);
2634#endif
2635}
2636
2637
2638void ViewCellsManager::SortViewCellPvs()
2639{
2640        ViewCellContainer::iterator it, it_end = mViewCells.end();
2641       
2642        for (it = mViewCells.begin(); it != it_end; ++ it)
2643        {
2644                ObjectPvs &pvs = (*it)->GetPvs();
2645                if (pvs.RequiresResortLog())
2646                        pvs.SimpleSort();
2647        }
2648}
2649
2650
2651void ViewCellsManager::ComputeViewCellContribution(ViewCell *viewCell,
2652                                                                                                   VssRay &ray,
2653                                                                                                   Intersectable *obj,
2654                                                                                                   const Vector3 &pt,
2655                                                                                                   const bool addSamplesToPvs)
2656{
2657        // check if we are outside of view space
2658        // $$JB tmp commented to speedup up computations
2659#if 0
2660        if (!obj || !viewCell->GetValid())
2661                return;
2662#endif
2663
2664        // if ray not outside of view space
2665        float relContribution = 0.0f;
2666        float absContribution = 0.0f;
2667        bool hasAbsContribution;
2668
2669        // todo: maybe not correct for kd node pvs
2670        if (addSamplesToPvs)
2671        {
2672                hasAbsContribution = viewCell->GetPvs().AddSampleDirtyCheck(obj, ray.mPdf);
2673                //hasAbsContribution = viewCell->GetPvs().AddSample(obj,ray.mPdf);
2674        }
2675        else
2676        {
2677                hasAbsContribution =
2678                        viewCell->GetPvs().GetSampleContribution(obj, ray.mPdf, relContribution);
2679        }
2680
2681        // $$ clear the relative contribution as it is currently not correct anyway
2682        //  relContribution = 0.0f;
2683
2684        if (hasAbsContribution) 
2685        {
2686                ++ ray.mPvsContribution;
2687                absContribution = relContribution = 1.0f;
2688
2689                if (viewCell->GetPvs().RequiresResort())
2690                        viewCell->GetPvs().SimpleSort();
2691
2692#if CONTRIBUTION_RELATIVE_TO_PVS_SIZE
2693                relContribution /= viewcell->GetPvs().GetSize();
2694#endif
2695
2696#if DIST_WEIGHTED_CONTRIBUTION
2697                // recalculate the contribution - weight the 1.0f contribution by the sqr distance to the
2698                // object-> a new contribution in the proximity of the viewcell has a larger weight!
2699                relContribution /=
2700                        SqrDistance(GetViewCellBox(viewcell).Center(), ray.mTermination);
2701
2702#endif
2703        }
2704
2705#if SUM_RAY_CONTRIBUTIONS || AVG_RAY_CONTRIBUTIONS
2706        ray.mRelativePvsContribution += relContribution;
2707#else
2708        // recalculate relative contribution - use max of Rel Contribution
2709        if (ray.mRelativePvsContribution < relContribution)
2710                ray.mRelativePvsContribution = relContribution;
2711#endif
2712}
2713
2714
2715int ViewCellsManager::GetNumViewCells() const
2716{
2717        return (int)mViewCells.size();
2718}
2719
2720
2721void
2722ViewCellsManager::DeterminePvsObjects(
2723                                                                          VssRayContainer &rays,
2724                                                                          const bool useHitObjects)
2725{
2726        if (!useHitObjects)
2727        {
2728                // store higher order object (e.g., bvh node) instead of object itself
2729                VssRayContainer::const_iterator it, it_end = rays.end();
2730       
2731                for (it = rays.begin(); it != it_end; ++ it)
2732                {
2733                        VssRay *vssRay = *it;
2734
2735                        // set only the termination object
2736                        vssRay->mTerminationObject = GetIntersectable(*vssRay, true);
2737                }
2738        }
2739}
2740
2741
2742float ViewCellsManager::ComputeSampleContribution(VssRay &ray,
2743                                                                                                  const bool addRays,
2744                                                                                                  ViewCell *currentViewCell,
2745                                                                                                  const bool useHitObjects)
2746{
2747        ray.mPvsContribution = 0;
2748        ray.mRelativePvsContribution = 0.0f;
2749
2750        if (!ray.mTerminationObject)
2751                return 0.0f;
2752
2753        // optain pvs entry (can be different from hit object)
2754        Intersectable *terminationObj;
2755
2756        terminationObj = ray.mTerminationObject;
2757
2758        ComputeViewCellContribution(currentViewCell,
2759                                                                ray,
2760                                                                terminationObj,
2761                                                                ray.mTermination,
2762                                                                addRays);
2763       
2764#if USE_RAY_LENGTH_AS_CONTRIBUTION
2765        float c = 0.0f;
2766        if (terminationObj)
2767                c = ray.Length();
2768
2769        ray.mRelativePvsContribution = ray.mPvsContribution = c;
2770        return c;
2771#else
2772        return ABS_CONTRIBUTION_WEIGHT*ray.mPvsContribution +
2773          (1.0f - ABS_CONTRIBUTION_WEIGHT)*ray.mRelativePvsContribution;
2774#endif
2775}
2776
2777
2778float
2779ViewCellsManager::ComputeSampleContribution(VssRay &ray,
2780                                                                                        const bool addRays,
2781                                                                                        const bool storeViewCells,
2782                                                                                        const bool useHitObjects)
2783{
2784        ray.mPvsContribution = 0;
2785        ray.mRelativePvsContribution = 0.0f;
2786
2787        ++ mSamplesStat.mRays;
2788       
2789        if (!ray.mTerminationObject)
2790          return 0.0f;
2791       
2792        static Ray hray;
2793        hray.Init(ray);
2794
2795        float tmin = 0, tmax = 1.0;
2796
2797        if (!GetViewSpaceBox().GetRaySegment(hray, tmin, tmax) || (tmin > tmax)) {
2798          // cerr<<"ray outside view space box\n";
2799          return 0;
2800        }
2801
2802        Vector3 origin = hray.Extrap(tmin);
2803        Vector3 termination = hray.Extrap(tmax);
2804       
2805        ViewCell::NewMail();
2806       
2807        viewCellCastTimer.Entry();
2808
2809        static ViewCellContainer viewCells;
2810        static VssRay *lastVssRay = NULL;
2811       
2812        // check if last ray was not same ray with reverse direction
2813        if (!lastVssRay ||
2814                !(ray.mOrigin == lastVssRay->mTermination) ||
2815                !(ray.mTermination == lastVssRay->mOrigin))
2816        {
2817                viewCells.clear();
2818               
2819                // traverse the view space subdivision
2820                CastLineSegment(origin, termination, viewCells);
2821                lastVssRay = &ray;
2822        }
2823       
2824        viewCellCastTimer.Exit();
2825
2826        mSamplesStat.mViewCells += (int)viewCells.size();
2827
2828        if (storeViewCells)
2829        {       
2830          // cerr << "Store viewcells should not be used in the test!" << endl;
2831          // copy viewcells memory efficiently
2832#if VSS_STORE_VIEWCELLS
2833          ray.mViewCells.reserve(viewCells.size());
2834          ray.mViewCells = viewCells;
2835#else
2836          cerr << "Vss store viewcells not supported." << endl;
2837          exit(1);
2838#endif
2839        }
2840       
2841        Intersectable *terminationObj;
2842       
2843        objTimer.Entry();
2844
2845        // obtain pvs entry (can be different from hit object)
2846        terminationObj = ray.mTerminationObject;
2847       
2848        objTimer.Exit();
2849       
2850        pvsTimer.Entry();
2851
2852        ViewCellContainer::const_iterator it = viewCells.begin();
2853
2854        for (; it != viewCells.end(); ++ it)
2855        {
2856                ComputeViewCellContribution(*it,
2857                                                                        ray,
2858                                                                        terminationObj,
2859                                                                        ray.mTermination,
2860                                                                        addRays);
2861        }
2862
2863        pvsTimer.Exit();
2864
2865        mSamplesStat.mPvsContributions += ray.mPvsContribution;
2866        if (ray.mPvsContribution)
2867                ++ mSamplesStat.mContributingRays;
2868       
2869#if AVG_RAY_CONTRIBUTIONS
2870        ray.mRelativePvsContribution /= (float)viewCells.size();
2871#endif
2872 
2873#if USE_RAY_LENGTH_AS_CONTRIBUTION
2874        float c = 0.0f;
2875        if (terminationObj)
2876          c = ray.Length();
2877        ray.mRelativePvsContribution = ray.mPvsContribution = c;
2878        return c;
2879#else
2880        return ABS_CONTRIBUTION_WEIGHT*ray.mPvsContribution +
2881          (1.0f - ABS_CONTRIBUTION_WEIGHT)*ray.mRelativePvsContribution;
2882#endif
2883}
2884
2885
2886void ViewCellsManager::GetRaySets(const VssRayContainer &sourceRays,
2887                                                                  const int maxSize,
2888                                                                  VssRayContainer &usedRays,
2889                                                                  VssRayContainer *savedRays) const
2890{
2891        const int limit = min(maxSize, (int)sourceRays.size());
2892        const float prop = (float)limit / ((float)sourceRays.size() + Limits::Small);
2893
2894        VssRayContainer::const_iterator it, it_end = sourceRays.end();
2895        for (it = sourceRays.begin(); it != it_end; ++ it)
2896        {
2897                if (Random(1.0f) < prop)
2898                        usedRays.push_back(*it);
2899                else if (savedRays)
2900                        savedRays->push_back(*it);
2901        }
2902}
2903
2904
2905float ViewCellsManager::GetRendercost(ViewCell *viewCell) const
2906{
2907        return (float)mViewCellsTree->GetPvsCost(viewCell);
2908}
2909
2910
2911float ViewCellsManager::GetAccVcArea()
2912{
2913        // if already computed
2914        if (mTotalAreaValid)
2915        {
2916                return mTotalArea;
2917        }
2918
2919        mTotalArea = 0;
2920        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
2921
2922        for (it = mViewCells.begin(); it != it_end; ++ it)
2923        {
2924                //Debug << "area: " << GetArea(*it);
2925        mTotalArea += GetArea(*it);
2926        }
2927
2928        mTotalAreaValid = true;
2929
2930        return mTotalArea;
2931}
2932
2933
2934void ViewCellsManager::PrintStatistics(ostream &s) const
2935{
2936        s << mCurrentViewCellsStats << endl;
2937}
2938
2939
2940void ViewCellsManager::CreateUniqueViewCellIds()
2941{
2942        if (ViewCellsTreeConstructed())
2943        {
2944                mViewCellsTree->CreateUniqueViewCellsIds();
2945        }
2946        else // no view cells tree, handle view cells "myself"
2947        {
2948                int i = 0;
2949                ViewCellContainer::const_iterator vit, vit_end = mViewCells.end();
2950                for (vit = mViewCells.begin(); vit != vit_end; ++ vit)
2951                {
2952                        if ((*vit)->GetId() != OUT_OF_BOUNDS_ID)
2953                        {
2954                                mViewCells[i]->SetId(i ++);
2955                        }
2956                }
2957        }
2958}
2959
2960
2961void ViewCellsManager::ExportViewCellsForViz(Exporter *exporter,
2962                                                                                         const AxisAlignedBox3 *sceneBox,
2963                                                                                         const bool colorCode,
2964                                                                                         const AxisAlignedPlane *clipPlane
2965                                                                                         ) const
2966{
2967        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
2968
2969        for (it = mViewCells.begin(); it != it_end; ++ it)
2970        {
2971                if (!mOnlyValidViewCells || (*it)->GetValid())
2972                {
2973                        ExportColor(exporter, *it, colorCode); 
2974                        ExportViewCellGeometry(exporter, *it, sceneBox, clipPlane);
2975                }
2976        }
2977}
2978
2979
2980void ViewCellsManager::CreateViewCellMeshes()
2981{
2982        // convert to meshes
2983        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
2984
2985        for (it = mViewCells.begin(); it != it_end; ++ it)
2986        {
2987                if (!(*it)->GetMesh())
2988                {
2989                        CreateMesh(*it);
2990                }
2991        }
2992}
2993
2994
2995bool ViewCellsManager::ExportViewCells(const string filename,
2996                                                                           const bool exportPvs,
2997                                                                           const ObjectContainer &objects)
2998{
2999        return false;
3000}
3001
3002
3003void ViewCellsManager::CollectViewCells(const int n)
3004{
3005        mNumActiveViewCells = n;
3006        mViewCells.clear();
3007        // implemented in subclasses
3008        CollectViewCells();
3009}
3010
3011
3012void ViewCellsManager::SetViewCellActive(ViewCell *vc) const
3013{
3014        ViewCellContainer leaves;
3015        // sets the pointers to the currently active view cells
3016        mViewCellsTree->CollectLeaves(vc, leaves);
3017
3018        ViewCellContainer::const_iterator lit, lit_end = leaves.end();
3019        for (lit = leaves.begin(); lit != lit_end; ++ lit)
3020        {
3021                static_cast<ViewCellLeaf *>(*lit)->SetActiveViewCell(vc);
3022        }
3023}
3024
3025
3026void ViewCellsManager::SetViewCellsActive()
3027{
3028        // collect leaf view cells and set the pointers to
3029        // the currently active view cells
3030        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
3031
3032        for (it = mViewCells.begin(); it != it_end; ++ it)
3033        {
3034                SetViewCellActive(*it);
3035        }
3036}
3037
3038
3039int ViewCellsManager::GetMaxFilterSize() const
3040{
3041        return mMaxFilterSize; 
3042}
3043
3044
3045static const bool USE_ASCII = true;
3046
3047
3048bool ViewCellsManager::ExportBoundingBoxes(const string filename,
3049                                                                                   const ObjectContainer &objects) const
3050{
3051        ObjectContainer::const_iterator it, it_end = objects.end();
3052       
3053        if (USE_ASCII)
3054        {
3055                ofstream boxesOut(filename.c_str());
3056                if (!boxesOut.is_open())
3057                        return false;
3058
3059                for (it = objects.begin(); it != it_end; ++ it)
3060                {
3061                        MeshInstance *mi = static_cast<MeshInstance *>(*it);
3062                        const AxisAlignedBox3 box = mi->GetBox();
3063
3064                        boxesOut << mi->GetId() << " "
3065                                         << box.Min().x << " "
3066                                         << box.Min().y << " "
3067                                         << box.Min().z << " "
3068                                         << box.Max().x << " "
3069                                         << box.Max().y << " "
3070                     << box.Max().z << endl;   
3071                }
3072
3073                boxesOut.close();
3074        }
3075        else
3076        {
3077                ofstream boxesOut(filename.c_str(), ios::binary);
3078
3079                if (!boxesOut.is_open())
3080                        return false;
3081
3082                for (it = objects.begin(); it != it_end; ++ it)
3083                {       
3084                        MeshInstance *mi = static_cast<MeshInstance *>(*it);
3085                        const AxisAlignedBox3 box = mi->GetBox();
3086                        Vector3 bmin = box.Min();
3087                        Vector3 bmax = box.Max();
3088                        int id = mi->GetId();
3089
3090                        boxesOut.write(reinterpret_cast<char *>(&id), sizeof(int));
3091                        boxesOut.write(reinterpret_cast<char *>(&bmin), sizeof(Vector3));
3092                        boxesOut.write(reinterpret_cast<char *>(&bmax), sizeof(Vector3));
3093                }
3094               
3095                boxesOut.close();
3096        }
3097
3098        return true;
3099}
3100
3101
3102bool ViewCellsManager::LoadBoundingBoxes(const string filename,
3103                                                                                 IndexedBoundingBoxContainer &boxes) const
3104{
3105        Vector3 bmin, bmax;
3106        int id;
3107
3108        if (USE_ASCII)
3109        {
3110                ifstream boxesIn(filename.c_str());
3111               
3112                if (!boxesIn.is_open())
3113                {
3114                        cout << "failed to open file " << filename << endl;
3115                        return false;
3116                }
3117
3118                string buf;
3119                while (!(getline(boxesIn, buf)).eof())
3120                {
3121                        sscanf(buf.c_str(), "%d %f %f %f %f %f %f",
3122                                   &id, &bmin.x, &bmin.y, &bmin.z,
3123                                   &bmax.x, &bmax.y, &bmax.z);
3124               
3125                        AxisAlignedBox3 box(bmin, bmax);
3126                        //      MeshInstance *mi = new MeshInstance();
3127                        // HACK: set bounding box to new box
3128                        //mi->mBox = box;
3129
3130                        boxes.push_back(IndexedBoundingBox(id, box));
3131                }
3132
3133                boxesIn.close();
3134        }
3135        else
3136        {
3137                ifstream boxesIn(filename.c_str(), ios::binary);
3138
3139                if (!boxesIn.is_open())
3140                        return false;
3141
3142                while (1)
3143                {
3144                        boxesIn.read(reinterpret_cast<char *>(&id), sizeof(Vector3));
3145                        boxesIn.read(reinterpret_cast<char *>(&bmin), sizeof(Vector3));
3146                        boxesIn.read(reinterpret_cast<char *>(&bmax), sizeof(Vector3));
3147                       
3148                        if (boxesIn.eof())
3149                                break;
3150
3151                       
3152                        AxisAlignedBox3 box(bmin, bmax);
3153                        MeshInstance *mi = new MeshInstance(NULL);
3154
3155                        // HACK: set bounding box to new box
3156                        //mi->mBox = box;
3157                        //boxes.push_back(mi);
3158                        boxes.push_back(IndexedBoundingBox(id, box));
3159                }
3160
3161                boxesIn.close();
3162        }
3163
3164        return true;
3165}
3166
3167
3168float ViewCellsManager::GetFilterWidth()
3169{
3170        return mFilterWidth;
3171}
3172
3173
3174float ViewCellsManager::GetAbsFilterWidth()
3175{
3176        return Magnitude(mViewSpaceBox.Size()) * mFilterWidth;
3177}
3178
3179
3180void ViewCellsManager::UpdateScalarPvsSize(ViewCell *vc,
3181                                                                                   const float pvsCost,
3182                                                                                   const int entriesInPvs) const
3183{
3184        vc->mPvsCost = pvsCost;
3185        vc->mEntriesInPvs = entriesInPvs;
3186
3187        vc->mPvsSizeValid = true;
3188}
3189
3190
3191void
3192ViewCellsManager::ApplyFilter(ViewCell *viewCell,
3193                                                          KdTree *kdTree,
3194                                                          const float viewSpaceFilterSize,
3195                                                          const float spatialFilterSize,
3196                                                          ObjectPvs &pvs
3197                                                          )
3198{
3199  // extend the pvs of the viewcell by pvs of its neighbors
3200  // and apply spatial filter by including all neighbors of the objects
3201  // in the pvs
3202
3203  // get all viewcells intersecting the viewSpaceFilterBox
3204  // and compute the pvs union
3205 
3206  //Vector3 center = viewCell->GetBox().Center();
3207  //  Vector3 center = m->mBox.Center();
3208
3209        //  AxisAlignedBox3 box(center - Vector3(viewSpaceFilterSize/2),
3210        //                                        center + Vector3(viewSpaceFilterSize/2));
3211        if (!ViewCellsConstructed())
3212                return;
3213
3214        if (viewSpaceFilterSize >= 0.0f) {
3215
3216                const bool usePrVS = false;
3217
3218                if (!usePrVS) {
3219                        AxisAlignedBox3 box = GetViewCellBox(viewCell);
3220                        box.Enlarge(Vector3(viewSpaceFilterSize/2));
3221
3222                        ViewCellContainer viewCells;
3223                        ComputeBoxIntersections(box, viewCells);
3224
3225                        //  cout<<"box="<<box<<endl;
3226                        ViewCellContainer::const_iterator it = viewCells.begin(), it_end = viewCells.end();
3227
3228                        for (; it != it_end; ++ it)
3229                        {
3230                                ObjectPvs interPvs;
3231                                //cout<<"v"<<i<<" pvs="<<(*it)->GetPvs().mEntries.size()<<endl;
3232                                ObjectPvs::Merge(interPvs, pvs, (*it)->GetPvs());
3233
3234                                pvs = interPvs;
3235                        }
3236                } else
3237                {
3238                        PrVs prvs;
3239                        AxisAlignedBox3 box = GetViewCellBox(viewCell);
3240
3241                        //  mViewCellsManager->SetMaxFilterSize(1);
3242                        GetPrVS(box.Center(), prvs, viewSpaceFilterSize);
3243                        pvs = prvs.mViewCell->GetPvs();
3244                        DeleteLocalMergeTree(prvs.mViewCell);
3245                }
3246        }
3247        else
3248        {
3249                pvs = viewCell->GetPvs();
3250        }
3251
3252        if (spatialFilterSize >=0.0f)
3253                ApplySpatialFilter(kdTree, spatialFilterSize, pvs);
3254
3255}
3256
3257
3258
3259void
3260ViewCellsManager::ApplyFilter(KdTree *kdTree,
3261                                                          const float relViewSpaceFilterSize,
3262                                                          const float relSpatialFilterSize
3263                                                          )
3264{
3265
3266        if (!ViewCellsConstructed())
3267                return;
3268
3269        ViewCellContainer::const_iterator it, it_end = mViewCells.end();
3270
3271        ObjectPvs *newPvs;
3272        newPvs = new ObjectPvs[mViewCells.size()];
3273
3274        float viewSpaceFilterSize = Magnitude(mViewSpaceBox.Size())*relViewSpaceFilterSize;
3275        float spatialFilterSize = Magnitude(kdTree->GetBox().Size())*relSpatialFilterSize;
3276       
3277        int i;
3278        for (i=0, it = mViewCells.begin(); it != it_end; ++ it, ++ i) {
3279          ApplyFilter(*it,
3280                                  kdTree,
3281                                  viewSpaceFilterSize,
3282                                  spatialFilterSize,
3283                                  newPvs[i]
3284                                  );
3285        }
3286       
3287        // now replace all pvss
3288        for (i = 0, it = mViewCells.begin(); it != it_end; ++ it, ++ i) {
3289         
3290          ObjectPvs &pvs = (*it)->GetPvs();
3291          pvs.Clear();
3292          pvs = newPvs[i];
3293          newPvs[i].Clear();
3294        }
3295
3296        delete [] newPvs;
3297}
3298
3299
3300void
3301ViewCellsManager::ApplySpatialFilter(
3302                                                                         KdTree *kdTree,
3303                                                                         const float spatialFilterSize,
3304                                                                         ObjectPvs &pvs
3305                                                                         )
3306{
3307  // now compute a new Pvs by including also objects intersecting the
3308  // extended boxes of visible objects
3309  Intersectable::NewMail();
3310
3311  ObjectPvsIterator pit = pvs.GetIterator();
3312
3313  while (pit.HasMoreEntries())
3314  {             
3315      pit.Next()->Mail();
3316  }
3317
3318  ObjectPvs nPvs;
3319  int nPvsSize = 0;
3320 
3321  ObjectPvsIterator pit2 = pvs.GetIterator();
3322
3323  while (pit2.HasMoreEntries())
3324  {             
3325          // now go through the pvs again
3326          Intersectable *object = pit2.Next();
3327
3328          //    Vector3 center = object->GetBox().Center();
3329          //    AxisAlignedBox3 box(center - Vector3(spatialFilterSize/2),
3330          //                                            center + Vector3(spatialFilterSize/2));
3331
3332          AxisAlignedBox3 box = object->GetBox();
3333          box.Enlarge(Vector3(spatialFilterSize/2));
3334
3335          ObjectContainer objects;
3336
3337          // $$ warning collect objects takes only unmailed ones!
3338          kdTree->CollectObjects(box, objects);
3339          //    cout<<"collected objects="<<objects.size()<<endl;
3340          ObjectContainer::const_iterator noi = objects.begin();
3341          for (; noi != objects.end(); ++ noi)
3342          {
3343                  Intersectable *o = *noi;
3344                  cout<<"w";
3345                  // $$ JB warning: pdfs are not correct at this point!   
3346                  nPvs.AddSample(o, Limits::Small);
3347                  nPvsSize ++;
3348          }
3349  }
3350
3351  // cout<<"nPvs size = "<<nPvsSize<<endl;
3352  pvs.MergeInPlace(nPvs);
3353}
3354
3355
3356void ViewCellsManager::MergeViewCellsRecursivly(ObjectPvs &pvs,
3357                                                                                                const ViewCellContainer &viewCells) const
3358{
3359        MergeViewCellsRecursivly(pvs, viewCells, 0, (int)viewCells.size() - 1);
3360}
3361
3362
3363void ViewCellsManager::MergeViewCellsRecursivly(ObjectPvs &pvs,
3364                                                                                                const ViewCellContainer &viewCells,
3365                                                                                                const int leftIdx,
3366                                                                                                const int rightIdx) const
3367{
3368        if (leftIdx == rightIdx)
3369        {
3370                pvs = viewCells[leftIdx]->GetPvs();
3371        }
3372        else
3373        {
3374                const int midSplit = (leftIdx + rightIdx) / 2;
3375       
3376                ObjectPvs leftPvs, rightPvs;
3377                MergeViewCellsRecursivly(leftPvs, viewCells, leftIdx, midSplit);
3378                MergeViewCellsRecursivly(rightPvs, viewCells, midSplit, rightIdx);
3379
3380        ObjectPvs::Merge(pvs, leftPvs, rightPvs);
3381        }
3382}
3383
3384
3385PvsFilterStatistics
3386ViewCellsManager::ApplyFilter2(ViewCell *viewCell,
3387                                                           const bool useViewSpaceFilter,
3388                                                           const float filterSize,
3389                                                           ObjectPvs &pvs,
3390                                                           vector<AxisAlignedBox3> *filteredBoxes
3391                                                           )
3392{
3393  PvsFilterStatistics stats;
3394
3395  AxisAlignedBox3 vbox = GetViewCellBox(viewCell);
3396  Vector3 center = vbox.Center();
3397  // copy the PVS
3398  Intersectable::NewMail();
3399  ObjectPvs basePvs = viewCell->GetPvs();
3400  ObjectPvsIterator pit = basePvs.GetIterator();
3401
3402  pvs.Reserve(viewCell->GetFilteredPvsSize());
3403
3404  if (!mUseKdPvs)
3405  {
3406          // first mark all objects from this pvs
3407          while (pit.HasMoreEntries()) 
3408          {
3409                  pit.Next()->Mail();
3410          }
3411  }
3412 
3413  int pvsSize = 0;
3414  int nPvsSize = 0;
3415  float samples = (float)basePvs.GetSamples();
3416 
3417  Debug<<"f #s="<<samples<<"  pvs size = "<<basePvs.GetSize();
3418  //  cout<<"Filter size = "<<filterSize<<endl;
3419  //  cout<<"vbox = "<<vbox<<endl;
3420  //  cout<<"center = "<<center<<endl;
3421
3422
3423   // Minimal number of local samples to take into account
3424   // the local sampling density.
3425   // The size of the filter is a minimum of the conservative
3426   // local sampling density estimate (#rays intersecting teh viewcell and
3427   // the object)
3428   // and gobal estimate for the view cell
3429   // (total #rays intersecting the viewcell)
3430  int minLocalSamples = 2;
3431 
3432  float viewCellRadius = 0.5f*Magnitude(vbox.Diagonal());
3433 
3434  // now compute the filter box around the current viewCell
3435 
3436  if (useViewSpaceFilter) {
3437        //      float radius = Max(viewCellRadius/100.0f, avgRadius - viewCellRadius);
3438        float radius = viewCellRadius/100.0f;
3439        vbox.Enlarge(radius);
3440        cout<<"vbox = "<<vbox<<endl;
3441        ViewCellContainer viewCells;
3442        ComputeBoxIntersections(vbox, viewCells);
3443       
3444        ViewCellContainer::const_iterator it = viewCells.begin(),
3445          it_end = viewCells.end();
3446        int i = 0;
3447        for (i=0; it != it_end; ++ it, ++ i)
3448          if ((*it) != viewCell) {
3449                //cout<<"v"<<i<<" pvs="<<(*it)->GetPvs().mEntries.size()<<endl;
3450                basePvs.MergeInPlace((*it)->GetPvs());
3451          }
3452       
3453        // update samples and globalC
3454        samples = (float)pvs.GetSamples();
3455        //      cout<<"neighboring viewcells = "<<i-1<<endl;
3456        //      cout<<"Samples' = "<<samples<<endl;
3457  }
3458 
3459  // Minimal number of samples so that filtering takes place
3460#define MIN_SAMPLES  50
3461 
3462  if (samples > MIN_SAMPLES) {
3463        float globalC = 2.0f*filterSize/sqrt(samples);
3464       
3465        pit = basePvs.GetIterator();
3466       
3467        ObjectContainer objects;
3468       
3469        PvsData pvsData;
3470
3471        while (pit.HasMoreEntries()) {         
3472          Intersectable *object = pit.Next(pvsData);
3473         
3474          // compute filter size based on the distance and the numebr of samples
3475          AxisAlignedBox3 box = object->GetBox();
3476         
3477          float distance = Distance(center, box.Center());
3478          float globalRadius = distance*globalC;
3479         
3480          int objectSamples = (int)pvsData.mSumPdf;
3481          float localRadius = MAX_FLOAT;
3482         
3483          localRadius = filterSize*0.5f*Magnitude(box.Diagonal())/
3484                sqrt((float)objectSamples);
3485         
3486          //      cout<<"os="<<objectSamples<<" lr="<<localRadius<<" gr="<<globalRadius<<endl;
3487         
3488          // now compute the filter size
3489          float radius;
3490         
3491#if 0
3492          if (objectSamples <= 1) {
3493                if (localRadius > globalRadius) {
3494                  radius = 0.5flRadius;
3495                  stats.mLocalFilterCount++;
3496                } else {
3497                  radius = globalRadius;
3498                  stats.mGlobalFilterCount++;
3499                }
3500          } else {
3501                radius = localRadius;
3502                stats.mLocalFilterCount++;
3503          }
3504#else
3505
3506          //      radius = 0.5f*globalRadius + 0.5f*localRadius;
3507          radius = Min(globalRadius, localRadius);
3508         
3509          if (localRadius > globalRadius)
3510                stats.mLocalFilterCount++;
3511          else
3512                stats.mGlobalFilterCount++;
3513#endif
3514         
3515          stats.mAvgFilterRadius += radius;
3516         
3517          // cout<<"box = "<<box<<endl;
3518          //    cout<<"distance = "<<distance<<endl;
3519          //    cout<<"radiues = "<<radius<<endl;
3520         
3521          box.Enlarge(Vector3(radius));
3522
3523          if (filteredBoxes)
3524                filteredBoxes->push_back(box);
3525
3526          objects.clear();
3527          // $$ warning collect objects takes only unmailed ones!
3528          if (mUseKdPvsAfterFiltering) {
3529                GetPreprocessor()->mKdTree->CollectKdObjects(box, objects);
3530          } else
3531                CollectObjects(box, objects);
3532         
3533          //    cout<<"collected objects="<<objects.size()<<endl;
3534          ObjectContainer::const_iterator noi = objects.begin();
3535          for (; noi != objects.end(); ++ noi) {
3536                Intersectable *o = *noi;
3537                // $$ JB warning: pdfs are not correct at this point!     
3538                pvs.AddSampleDirty(o, Limits::Small);
3539          }
3540        }
3541        stats.mAvgFilterRadius /= (stats.mLocalFilterCount + stats.mGlobalFilterCount);
3542  }
3543 
3544  Debug<<" nPvs size = "<<pvs.GetSize()<<endl;
3545 
3546  if (!mUseKdPvs)
3547  {
3548          PvsData pvsData;
3549
3550          // copy the base pvs to the new pvs
3551          pit = basePvs.GetIterator();
3552          while (pit.HasMoreEntries())
3553          {             
3554                  Intersectable *obj = pit.Next(pvsData);
3555                  pvs.AddSampleDirty(obj, pvsData.mSumPdf);
3556          }
3557  }
3558 
3559  pvs.SimpleSort();
3560  viewCell->SetFilteredPvsSize(pvs.GetSize());
3561 
3562  Intersectable::NewMail();
3563  return stats;
3564}
3565
3566
3567
3568void ViewCellsManager::ExportColor(Exporter *exporter,
3569                                                                   ViewCell *vc,
3570                                                                   bool colorCode) const
3571{
3572        const bool vcValid = CheckValidity(vc, mMinPvsSize, mMaxPvsSize);
3573
3574        float importance = 0;
3575        static Material m;
3576        //cout << "color code: " << colorCode << endl;
3577        switch (mColorCode)
3578        {
3579        case 0: // Random
3580                {
3581                        if (vcValid)
3582                        {
3583                                m.mDiffuseColor.r = 0.2f + RandomValue(0.0f, 0.8f);
3584                                m.mDiffuseColor.g = 0.2f + RandomValue(0.0f, 0.8f);
3585                                m.mDiffuseColor.b = 0.2f + RandomValue(0.0f, 0.8f);
3586                        }
3587                        else
3588                        {
3589                                m.mDiffuseColor.r = 0.0f;
3590                                m.mDiffuseColor.g = 1.0f;
3591                                m.mDiffuseColor.b = 0.0f;
3592                        }
3593
3594                        exporter->SetForcedMaterial(m);
3595                        return;
3596                }
3597               
3598        case 1: // pvs
3599                {
3600                        if (mCurrentViewCellsStats.maxPvs)
3601                        {
3602                                importance = (float)mViewCellsTree->GetPvsCost(vc) /
3603                                                         (float)mCurrentViewCellsStats.maxPvs;
3604                        }
3605                }
3606                break;
3607        case 2: // merges
3608                {
3609            const int lSize = mViewCellsTree->GetNumInitialViewCells(vc);
3610                        importance = (float)lSize / (float)mCurrentViewCellsStats.maxLeaves;
3611                }
3612                break;
3613#if 0
3614        case 3: // merge tree differene
3615                {
3616                        importance = (float)GetMaxTreeDiff(vc) /
3617                                (float)(mVspBspTree->GetStatistics().maxDepth * 2);
3618
3619                }
3620                break;
3621#endif
3622        default:
3623                break;
3624        }
3625
3626        // special color code for invalid view cells
3627        m.mDiffuseColor.r = importance;
3628        m.mDiffuseColor.b = 1.0f;//vcValid ? 0.0f : 1.0f;
3629        m.mDiffuseColor.g = 1.0f - importance;
3630
3631        //Debug << "importance: " << importance << endl;
3632        exporter->SetForcedMaterial(m);
3633}
3634
3635
3636void ViewCellsManager::CollectMergeCandidates(const VssRayContainer &rays,
3637                                                                                          vector<MergeCandidate> &candidates)
3638{
3639        // implemented in subclasses
3640}
3641
3642
3643void ViewCellsManager::UpdatePvsForEvaluation()
3644{
3645        ObjectPvs objPvs;
3646        UpdatePvsForEvaluation(mViewCellsTree->GetRoot(), objPvs);
3647}
3648
3649
3650void ViewCellsManager::UpdatePvsForEvaluation(ViewCell *root, ObjectPvs &pvs)
3651{
3652        // terminate traversal
3653        if (root->IsLeaf())
3654        {
3655                // we assume that pvs is explicitly stored in leaves
3656                pvs = root->GetPvs();
3657                UpdateScalarPvsSize(root, pvs.EvalPvsCost(), pvs.GetSize());
3658                return;
3659        }
3660
3661        ////////////////
3662        //-- interior node => propagate pvs up the tree
3663
3664        ViewCellInterior *interior = static_cast<ViewCellInterior *>(root);
3665
3666        // reset interior pvs
3667        interior->GetPvs().Clear();
3668
3669        // reset recursive pvs
3670        pvs.Clear();
3671
3672        // pvss of child nodes
3673        vector<ObjectPvs> pvsList;
3674        pvsList.resize((int)interior->mChildren.size());
3675
3676        ViewCellContainer::const_iterator vit, vit_end = interior->mChildren.end();
3677       
3678        int i = 0;
3679
3680        for (vit = interior->mChildren.begin(); vit != vit_end; ++ vit, ++ i)
3681        {
3682                //////////////////
3683                //-- recursivly compute child pvss
3684                UpdatePvsForEvaluation(*vit, pvsList[i]/*objPvs*/);
3685        }
3686
3687#if 1
3688        Intersectable::NewMail();
3689
3690        ///////////
3691        //-- merge pvss
3692
3693        vector<ObjectPvs>::iterator oit = pvsList.begin();
3694
3695        PvsData pvsData;
3696
3697        for (vit = interior->mChildren.begin(); vit != vit_end; ++ vit, ++ oit)
3698        {
3699                ObjectPvsIterator pit = (*oit).GetIterator();
3700               
3701                // add pvss to new pvs: use mailing to avoid adding entries two times.
3702                while (pit.HasMoreEntries())
3703                {               
3704                        Intersectable *intersect = pit.Next(pvsData);
3705
3706                        if (!intersect->Mailed())
3707                        {
3708                                intersect->Mail();
3709
3710                                pvs.AddSampleDirty(intersect, pvsData.mSumPdf);
3711                        }
3712                }
3713        }
3714
3715        if (0) pvs.Sort();
3716
3717        // store pvs in this node
3718        if (mViewCellsTree->ViewCellsStorage() == ViewCellsTree::PVS_IN_INTERIORS)
3719        {
3720                interior->SetPvs(pvs);
3721        }
3722       
3723        // set new pvs size
3724        UpdateScalarPvsSize(interior, pvs.EvalPvsCost(), pvs.GetSize());
3725       
3726#else
3727        // really merge cells: slow but sumPdf is correct
3728        viewCellInterior->GetPvs().Merge(backVc->GetPvs());
3729        viewCellInterior->GetPvs().Merge(frontVc->GetPvs());
3730#endif
3731}
3732
3733
3734
3735/*******************************************************************/
3736/*               BspViewCellsManager implementation                */
3737/*******************************************************************/
3738
3739
3740BspViewCellsManager::BspViewCellsManager(ViewCellsTree *vcTree, BspTree *bspTree):
3741ViewCellsManager(vcTree), mBspTree(bspTree)
3742{
3743        Environment::GetSingleton()->GetIntValue("BspTree.Construction.samples", mInitialSamples);
3744
3745        mBspTree->SetViewCellsManager(this);
3746        mBspTree->SetViewCellsTree(mViewCellsTree);
3747}
3748
3749
3750bool BspViewCellsManager::ViewCellsConstructed() const
3751{
3752        return mBspTree->GetRoot() != NULL;
3753}
3754
3755
3756ViewCell *BspViewCellsManager::GenerateViewCell(Mesh *mesh) const
3757{
3758        return new BspViewCell(mesh);
3759}
3760
3761
3762int BspViewCellsManager::ConstructSubdivision(const ObjectContainer &objects,
3763                                                                                          const VssRayContainer &rays)
3764{
3765        // if view cells were already constructed, we can finish
3766        if (ViewCellsConstructed())
3767                return 0;
3768
3769        int sampleContributions = 0;
3770
3771        // construct view cells using the collected samples
3772        RayContainer constructionRays;
3773        VssRayContainer savedRays;
3774
3775        // choose a a number of rays based on the ratio of cast rays / requested rays
3776        const int limit = min(mInitialSamples, (int)rays.size());
3777        VssRayContainer::const_iterator it, it_end = rays.end();
3778
3779        const float prop = (float)limit / ((float)rays.size() + Limits::Small);
3780
3781        for (it = rays.begin(); it != it_end; ++ it)
3782        {
3783                if (Random(1.0f) < prop)
3784                        constructionRays.push_back(new Ray(*(*it)));
3785                else
3786                        savedRays.push_back(*it);
3787        }
3788
3789    if (!mUsePredefinedViewCells)
3790        {
3791                // no view cells loaded
3792                mBspTree->Construct(objects, constructionRays, &mViewSpaceBox);
3793                // collect final view cells
3794                mBspTree->CollectViewCells(mViewCells);
3795        }
3796        else
3797        {       
3798                // use predefined view cells geometry =>
3799                // contruct bsp hierarchy over them
3800                mBspTree->Construct(mViewCells);
3801        }
3802
3803        // destroy rays created only for construction
3804        CLEAR_CONTAINER(constructionRays);
3805
3806        Debug << mBspTree->GetStatistics() << endl;
3807        Debug << "\nView cells after construction:\n" << mCurrentViewCellsStats << endl;
3808
3809        // recast rest of the rays
3810        if (SAMPLE_AFTER_SUBDIVISION)
3811                ComputeSampleContributions(savedRays, true, false);
3812
3813        // real meshes are contructed at this stage
3814        if (0)
3815        {
3816                cout << "finalizing view cells ... ";
3817                FinalizeViewCells(true);
3818                cout << "finished" << endl;     
3819        }
3820
3821        return sampleContributions;
3822}
3823
3824
3825void BspViewCellsManager::CollectViewCells()
3826{       
3827        if (!ViewCellsTreeConstructed())
3828        {       // view cells tree constructed 
3829                mBspTree->CollectViewCells(mViewCells);
3830        }
3831        else
3832        {       // we can use the view cells tree hierarchy to get the right set
3833                mViewCellsTree->CollectBestViewCellSet(mViewCells, mNumActiveViewCells);
3834        }
3835}
3836
3837
3838float BspViewCellsManager::GetProbability(ViewCell *viewCell)
3839{
3840        if (1)
3841                return GetVolume(viewCell) / GetViewSpaceBox().GetVolume();
3842        else
3843                // compute view cell area as subsititute for probability
3844                return GetArea(viewCell) / GetAccVcArea();
3845}
3846
3847
3848
3849int BspViewCellsManager::CastLineSegment(const Vector3 &origin,
3850                                                                                 const Vector3 &termination,
3851                                                                                 ViewCellContainer &viewcells)
3852{
3853        return mBspTree->CastLineSegment(origin, termination, viewcells);
3854}
3855
3856
3857bool BspViewCellsManager::LineSegmentIntersects(const Vector3 &origin,
3858                                                                                                const Vector3 &termination,
3859                                                                                                ViewCell *viewCell)
3860{
3861        return false;
3862}
3863
3864
3865void ViewCellsManager::ExportMergedViewCells(const ObjectContainer &objects)
3866{
3867        // save color code
3868        const int savedColorCode = mColorCode;
3869
3870        Exporter *exporter;
3871
3872        // export merged view cells using pvs color coding
3873        exporter = Exporter::GetExporter("merged_view_cells_pvs.wrl");
3874        cout << "exporting view cells after merge (pvs size) ... ";     
3875
3876        if (exporter)
3877        {
3878                if (mExportGeometry)
3879                {
3880                        exporter->ExportGeometry(objects);
3881                }
3882
3883                exporter->SetFilled();
3884                mColorCode = 1;
3885
3886                ExportViewCellsForViz(exporter, NULL,  mColorCode, GetClipPlane());
3887
3888                delete exporter;
3889        }
3890        cout << "finished" << endl;
3891       
3892        mColorCode = savedColorCode;
3893}
3894
3895
3896int BspViewCellsManager::PostProcess(const ObjectContainer &objects,
3897                                                                         const VssRayContainer &rays)
3898{
3899        if (!ViewCellsConstructed())
3900        {
3901                Debug << "view cells not constructed" << endl;
3902                return 0;
3903        }
3904       
3905        // view cells already finished before post processing step,
3906        // i.e., because they were loaded from disc
3907        if (mViewCellsFinished)
3908        {
3909                FinalizeViewCells(true);
3910                EvaluateViewCellsStats();
3911
3912                return 0;
3913        }
3914
3915        //////////////////
3916        //-- merge leaves of the view cell hierarchy   
3917       
3918        cout << "starting post processing using " << mPostProcessSamples << " samples ... ";
3919        long startTime = GetTime();
3920       
3921        VssRayContainer postProcessRays;
3922        GetRaySets(rays, mPostProcessSamples, postProcessRays);
3923
3924        if (mMergeViewCells)
3925        {
3926                cout << "constructing visibility based merge tree" << endl;
3927                mViewCellsTree->ConstructMergeTree(rays, objects);
3928        }
3929        else
3930        {
3931                cout << "constructing spatial merge tree" << endl;
3932                ViewCell *root;
3933                // the spatial merge tree is difficult to build for
3934                // this type of construction, as view cells cover several
3935                // leaves => create dummy tree which is only 2 levels deep
3936                if (mUsePredefinedViewCells)
3937                {
3938                        root = ConstructDummyMergeTree(mBspTree->GetRoot());
3939                }
3940                else
3941                {
3942                        // create spatial merge hierarchy
3943                        root = ConstructSpatialMergeTree(mBspTree->GetRoot());
3944                }
3945               
3946                mViewCellsTree->SetRoot(root);
3947
3948                // recompute pvs in the whole hierarchy
3949                ObjectPvs pvs;
3950                UpdatePvsForEvaluation(root, pvs);
3951        }
3952
3953        cout << "finished" << endl;
3954        cout << "merged view cells in "
3955                 << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
3956
3957        Debug << "Postprocessing: Merged view cells in "
3958                << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl << endl;
3959
3960       
3961        ////////////////////////
3962        //-- visualization and statistics after merge
3963
3964        if (1)
3965        {
3966                char mstats[100];
3967                Environment::GetSingleton()->GetStringValue("ViewCells.mergeStats", mstats);
3968                mViewCellsTree->ExportStats(mstats);
3969        }
3970
3971        // recompute view cells and stats
3972        ResetViewCells();
3973        Debug << "\nView cells after merge:\n" << mCurrentViewCellsStats << endl;
3974
3975        //  visualization of the view cells
3976        if (1) ExportMergedViewCells(objects);
3977
3978        // compute final meshes and volume / area
3979        if (1) FinalizeViewCells(true);
3980       
3981        return 0;
3982}
3983
3984
3985BspViewCellsManager::~BspViewCellsManager()
3986{
3987}
3988
3989
3990int BspViewCellsManager::GetType() const
3991{
3992        return BSP;
3993}
3994
3995
3996void BspViewCellsManager::Visualize(const ObjectContainer &objects,
3997                                                                        const VssRayContainer &sampleRays)
3998{
3999        if (!ViewCellsConstructed())
4000                return;
4001       
4002        const int savedColorCode = mColorCode;
4003       
4004        if (1) // export final view cells
4005        {
4006                mColorCode = 1; // hack color code
4007                Exporter *exporter = Exporter::GetExporter("final_view_cells.wrl");
4008       
4009                cout << "exporting view cells after merge (pvs size) ... ";     
4010
4011                if (exporter)
4012                {
4013                        if (mExportGeometry)
4014                        {
4015                                exporter->ExportGeometry(objects);
4016                        }
4017
4018                        ExportViewCellsForViz(exporter, NULL, mColorCode, GetClipPlane());
4019                        delete exporter;
4020                }
4021                cout << "finished" << endl;
4022        }
4023
4024        // reset color code
4025        mColorCode = savedColorCode;
4026
4027
4028        //////////////////
4029        //-- visualization of the BSP splits
4030
4031        bool exportSplits = false;
4032        Environment::GetSingleton()->GetBoolValue("BspTree.Visualization.exportSplits", exportSplits);
4033
4034        if (exportSplits)
4035        {
4036                cout << "exporting splits ... ";
4037                ExportSplits(objects);
4038                cout << "finished" << endl;
4039        }
4040
4041        int leafOut;
4042        Environment::GetSingleton()->GetIntValue("ViewCells.Visualization.maxOutput", leafOut);
4043        const int raysOut = 100;
4044        ExportSingleViewCells(objects, leafOut, false, true, false, raysOut, "");
4045}
4046
4047
4048void BspViewCellsManager::ExportSplits(const ObjectContainer &objects)
4049{
4050        Exporter *exporter = Exporter::GetExporter("bsp_splits.x3d");
4051
4052        if (exporter)
4053        {
4054                //exporter->SetFilled();
4055                if (mExportGeometry)
4056                {
4057                        exporter->ExportGeometry(objects);
4058                }
4059
4060                Material m;
4061                m.mDiffuseColor = RgbColor(1, 0, 0);
4062                exporter->SetForcedMaterial(m);
4063                exporter->SetWireframe();
4064
4065                exporter->ExportBspSplits(*mBspTree, true);
4066
4067                // NOTE: take forced material, else big scenes cannot be viewed
4068                m.mDiffuseColor = RgbColor(0, 1, 0);
4069                exporter->SetForcedMaterial(m);
4070                //exporter->ResetForcedMaterial();
4071
4072                delete exporter;
4073        }
4074}
4075
4076
4077void BspViewCellsManager::ExportSingleViewCells(const ObjectContainer &objects,
4078                                                                                                const int maxViewCells,
4079                                                                                                const bool sortViewCells,
4080                                                                                                const bool exportPvs,
4081                                                                                                const bool exportRays,
4082                                                                                                const int maxRays,
4083                                                                                                const string prefix,
4084                                                                                                VssRayContainer *visRays)
4085{
4086        if (sortViewCells)
4087        {       // sort view cells to visualize the largest view cells
4088                sort(mViewCells.begin(), mViewCells.end(), ViewCell::LargerRenderCost);
4089        }
4090
4091        //////////
4092        //-- some view cells for output
4093
4094        ViewCell::NewMail();
4095        const int limit = min(maxViewCells, (int)mViewCells.size());
4096       
4097        for (int i = 0; i < limit; ++ i)
4098        {
4099                const int idx = sortViewCells ? (int)RandomValue(0, (float)mViewCells.size() - 0.5f) : i;
4100                ViewCell *vc = mViewCells[idx];
4101
4102                if (vc->Mailed() || vc->GetId() == OUT_OF_BOUNDS_ID)
4103                        continue;
4104
4105                vc->Mail();
4106
4107                ObjectPvs pvs;
4108                mViewCellsTree->GetPvs(vc, pvs);
4109
4110                char s[64]; sprintf(s, "%sviewcell-%04d.wrl", prefix.c_str(), i);
4111                Exporter *exporter = Exporter::GetExporter(s);
4112               
4113                cout << "view cell " << idx << ": pvs cost=" << (int)mViewCellsTree->GetPvsCost(vc) << endl;
4114
4115                if (exportRays)
4116                {
4117                        ////////////
4118                        //-- export rays piercing this view cell
4119
4120                        // use rays stored with the view cells
4121                        VssRayContainer vcRays, vcRays2, vcRays3;
4122            VssRayContainer collectRays;
4123
4124                        // collect initial view cells
4125                        ViewCellContainer leaves;
4126                        mViewCellsTree->CollectLeaves(vc, leaves);
4127
4128                        ViewCellContainer::const_iterator vit, vit_end = leaves.end();
4129                for (vit = leaves.begin(); vit != vit_end; ++ vit)
4130                        {       
4131                                // prepare some rays for output
4132                                VssRayContainer::const_iterator rit, rit_end = (*vit)->GetOrCreateRays()->end();
4133                                for (rit = (*vit)->GetOrCreateRays()->begin(); rit != rit_end; ++ rit)
4134                                {
4135                                        collectRays.push_back(*rit);
4136                                }
4137                        }
4138
4139                        const int raysOut = min((int)collectRays.size(), maxRays);
4140
4141                        // prepare some rays for output
4142                        VssRayContainer::const_iterator rit, rit_end = collectRays.end();
4143                        for (rit = collectRays.begin(); rit != rit_end; ++ rit)
4144                        {
4145                                const float p = RandomValue(0.0f, (float)collectRays.size());
4146                                if (p < raysOut)
4147                                {
4148                                        if ((*rit)->mFlags & VssRay::BorderSample)
4149                                        {
4150                                                vcRays.push_back(*rit);
4151                                        }
4152                                        else if ((*rit)->mFlags & VssRay::ReverseSample)
4153                                        {
4154                                                vcRays2.push_back(*rit);
4155                                        }
4156                                        else
4157                                        {
4158                                                vcRays3.push_back(*rit);
4159                                        }       
4160                                }
4161                        }
4162
4163                        exporter->ExportRays(vcRays, RgbColor(1, 0, 0));
4164                        exporter->ExportRays(vcRays2, RgbColor(0, 1, 0));
4165                        exporter->ExportRays(vcRays3, RgbColor(1, 1, 1));
4166                }
4167               
4168                ////////////////
4169                //-- export view cell geometry
4170
4171                exporter->SetWireframe();
4172
4173                Material m;//= RandomMaterial();
4174                m.mDiffuseColor = RgbColor(0, 1, 0);
4175                exporter->SetForcedMaterial(m);
4176
4177                ExportViewCellGeometry(exporter, vc, NULL, NULL);
4178                exporter->SetFilled();
4179
4180                if (exportPvs)
4181                {
4182                        Intersectable::NewMail();
4183                        ObjectPvsIterator pit = pvs.GetIterator();
4184
4185                        while (pit.HasMoreEntries())
4186                        {               
4187                                Intersectable *intersect = pit.Next();
4188
4189                // output PVS of view cell
4190                                if (!intersect->Mailed())
4191                                {
4192                                        intersect->Mail();
4193
4194                                        m = RandomMaterial();
4195                                        exporter->SetForcedMaterial(m);
4196                                        exporter->ExportIntersectable(intersect);
4197                                }
4198                        }
4199                        cout << endl;
4200                }
4201               
4202                DEL_PTR(exporter);
4203                cout << "finished" << endl;
4204        }
4205}
4206
4207
4208void BspViewCellsManager::TestSubdivision()
4209{
4210        ViewCellContainer leaves;
4211        mViewCellsTree->CollectLeaves(mViewCellsTree->GetRoot(), leaves);
4212
4213        ViewCellContainer::const_iterator it, it_end = leaves.end();
4214
4215        const float vol = mViewSpaceBox.GetVolume();
4216        float subdivVol = 0;
4217        float newVol = 0;
4218
4219        for (it = leaves.begin(); it != it_end; ++ it)
4220        {
4221                BspNodeGeometry geom;
4222                mBspTree->ConstructGeometry(*it, geom);
4223
4224                const float lVol = geom.GetVolume();
4225                newVol += lVol;
4226                subdivVol += (*it)->GetVolume();
4227
4228                const float thres = 0.9f;
4229                if ((lVol < ((*it)->GetVolume() * thres)) ||
4230                        (lVol * thres > ((*it)->GetVolume())))
4231                        Debug << "warning: " << lVol << " " << (*it)->GetVolume() << endl;
4232        }
4233       
4234        Debug << "exact volume: " << vol << endl;
4235        Debug << "subdivision volume: " << subdivVol << endl;
4236        Debug << "new volume: " << newVol << endl;
4237}
4238
4239
4240void BspViewCellsManager::ExportViewCellGeometry(Exporter *exporter,
4241                                                                                                 ViewCell *vc,
4242                                                                                                 const AxisAlignedBox3 *sceneBox,
4243                                                                                                 const AxisAlignedPlane *clipPlane
4244                                                                                                 ) const
4245{
4246        if (clipPlane)
4247        {
4248                const Plane3 plane = clipPlane->GetPlane();
4249
4250                ViewCellContainer leaves;
4251                mViewCellsTree->CollectLeaves(vc, leaves);
4252                ViewCellContainer::const_iterator it, it_end = leaves.end();
4253
4254                for (it = leaves.begin(); it != it_end; ++ it)
4255                {
4256                        BspNodeGeometry geom;
4257                        BspNodeGeometry front;
4258                        BspNodeGeometry back;
4259
4260                        mBspTree->ConstructGeometry(*it, geom);
4261
4262                        const float eps = 0.0001f;
4263                        const int cf = geom.Side(plane, eps);
4264
4265                        if (cf == -1)
4266                        {
4267                                exporter->ExportPolygons(geom.GetPolys());
4268                        }
4269                        else if (cf == 0)
4270                        {
4271                                geom.SplitGeometry(front,
4272                                                                   back,
4273                                                                   plane,
4274                                                                   mViewSpaceBox,
4275                                                                   eps);
4276
4277                                if (back.Valid())
4278                                {
4279                                        exporter->ExportPolygons(back.GetPolys());
4280                                }                       
4281                        }
4282                }
4283        }
4284        else
4285        {
4286                // export mesh if available
4287                // TODO: some bug here?
4288                if (1 && vc->GetMesh())
4289                {
4290                        exporter->ExportMesh(vc->GetMesh());
4291                }
4292                else
4293                {
4294                        BspNodeGeometry geom;
4295                        mBspTree->ConstructGeometry(vc, geom);
4296                        exporter->ExportPolygons(geom.GetPolys());
4297                }
4298        }
4299}
4300
4301
4302void BspViewCellsManager::CreateMesh(ViewCell *vc)
4303{
4304        // note: should previous mesh be deleted (via mesh manager?)
4305        BspNodeGeometry geom;
4306        mBspTree->ConstructGeometry(vc, geom);
4307
4308        Mesh *mesh = MeshManager::GetSingleton()->CreateResource();
4309       
4310        IncludeNodeGeomInMesh(geom, *mesh);
4311        mesh->ComputeBoundingBox();
4312
4313        vc->SetMesh(mesh);
4314}
4315
4316
4317void BspViewCellsManager::Finalize(ViewCell *viewCell,
4318                                                                   const bool createMesh)
4319{
4320        float area = 0;
4321        float volume = 0;
4322
4323        ViewCellContainer leaves;
4324        mViewCellsTree->CollectLeaves(viewCell, leaves);
4325
4326        ViewCellContainer::const_iterator it, it_end = leaves.end();
4327
4328    for (it = leaves.begin(); it != it_end; ++ it)
4329        {
4330                BspNodeGeometry geom;
4331
4332                mBspTree->ConstructGeometry(*it, geom);
4333
4334                const float lVol = geom.GetVolume();
4335                const float lArea = geom.GetArea();
4336
4337                area += lArea;
4338                volume += lVol;
4339       
4340                CreateMesh(*it);
4341        }
4342
4343        viewCell->SetVolume(volume);
4344        viewCell->SetArea(area);
4345}
4346
4347
4348ViewCell *BspViewCellsManager::GetViewCell(const Vector3 &point, const bool active) const
4349{
4350        if (!ViewCellsConstructed())
4351        {
4352                return NULL;
4353        }
4354        if (!mViewSpaceBox.IsInside(point))
4355        {
4356                return NULL;
4357        }
4358        return mBspTree->GetViewCell(point);
4359}
4360
4361
4362void BspViewCellsManager::CollectMergeCandidates(const VssRayContainer &rays,
4363                                                                                                 vector<MergeCandidate> &candidates)
4364{
4365        cout << "collecting merge candidates ... " << endl;
4366
4367        if (mUseRaysForMerge)
4368        {
4369                mBspTree->CollectMergeCandidates(rays, candidates);
4370        }
4371        else
4372        {
4373                vector<BspLeaf *> leaves;
4374                mBspTree->CollectLeaves(leaves);
4375                mBspTree->CollectMergeCandidates(leaves, candidates);
4376        }
4377
4378        cout << "fininshed collecting candidates" << endl;
4379}
4380
4381
4382
4383bool BspViewCellsManager::ExportViewCells(const string filename,
4384                                                                                  const bool exportPvs,
4385                                                                                  const ObjectContainer &objects)
4386{
4387        if (!ViewCellsConstructed() || !ViewCellsTreeConstructed())
4388        {
4389                return false;
4390        }
4391
4392        cout << "exporting view cells to xml ... ";
4393
4394        OUT_STREAM stream(filename.c_str());
4395
4396        // for output we need unique ids for each view cell
4397        CreateUniqueViewCellIds();
4398
4399        stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"<<endl;
4400        stream << "<VisibilitySolution>" << endl;
4401
4402        if (exportPvs)
4403        {
4404                //////////
4405                //-- export bounding boxes: they are used to identify the objects from the pvs and
4406                //-- assign them to the entities in the rendering engine
4407
4408                stream << "<BoundingBoxes>" << endl;
4409                ObjectContainer::const_iterator oit, oit_end = objects.end();
4410
4411                for (oit = objects.begin(); oit != oit_end; ++ oit)
4412                {
4413                        const AxisAlignedBox3 box = (*oit)->GetBox();
4414                       
4415                        stream << "<BoundingBox" << " id=\"" << (*oit)->GetId() << "\""
4416                                   << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
4417                                   << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z << "\" />" << endl;
4418                }
4419
4420                stream << "</BoundingBoxes>" << endl;
4421        }
4422
4423        ///////////
4424        //-- export the view cells and the pvs
4425
4426        const int numViewCells = mCurrentViewCellsStats.viewCells;
4427        stream << "<ViewCells number=\"" << numViewCells << "\" >" << endl;
4428
4429        mViewCellsTree->Export(stream, exportPvs);
4430       
4431        stream << "</ViewCells>" << endl;
4432
4433        /////////////
4434        //-- export the view space hierarchy
4435        stream << "<ViewSpaceHierarchy type=\"bsp\""
4436                   << " min=\"" << mViewSpaceBox.Min().x << " " << mViewSpaceBox.Min().y << " " << mViewSpaceBox.Min().z << "\""
4437                   << " max=\"" << mViewSpaceBox.Max().x << " " << mViewSpaceBox.Max().y << " " << mViewSpaceBox.Max().z << "\">" << endl;
4438
4439        mBspTree->Export(stream);
4440
4441        // end tags
4442        stream << "</ViewSpaceHierarchy>" << endl;
4443        stream << "</VisibilitySolution>" << endl;
4444
4445        stream.close();
4446        cout << "finished" << endl;
4447
4448        return true;
4449}
4450
4451
4452ViewCell *BspViewCellsManager::ConstructDummyMergeTree(BspNode *root)
4453{
4454        ViewCellInterior *vcRoot = new ViewCellInterior();
4455               
4456        // evaluate merge cost for priority traversal
4457        const float mergeCost =  -(float)root->mTimeStamp;
4458        vcRoot->SetMergeCost(mergeCost);
4459
4460        float volume = 0;
4461        vector<BspLeaf *> leaves;
4462        mBspTree->CollectLeaves(leaves);
4463        vector<BspLeaf *>::const_iterator lit, lit_end = leaves.end();
4464        ViewCell::NewMail();
4465
4466        for (lit = leaves.begin(); lit != lit_end; ++ lit)
4467        {
4468                BspLeaf *leaf = *lit;
4469                ViewCell *vc = leaf->GetViewCell();
4470
4471                if (!vc->Mailed())
4472                {
4473                        vc->Mail();
4474                        vc->SetMergeCost(0.0f);
4475                        vcRoot->SetupChildLink(vc);
4476
4477                        volume += vc->GetVolume();
4478                        volume += vc->GetVolume();     
4479                        vcRoot->SetVolume(volume);
4480                }
4481        }
4482       
4483        return vcRoot;
4484}
4485
4486
4487ViewCell *BspViewCellsManager::ConstructSpatialMergeTree(BspNode *root)
4488{
4489        // terminate recursion
4490        if (root->IsLeaf())
4491        {
4492                BspLeaf *leaf = static_cast<BspLeaf *>(root);
4493                leaf->GetViewCell()->SetMergeCost(0.0f);
4494                return leaf->GetViewCell();
4495        }
4496       
4497        BspInterior *interior = static_cast<BspInterior *>(root);
4498        ViewCellInterior *viewCellInterior = new ViewCellInterior();
4499               
4500        // evaluate merge cost for priority traversal
4501        const float mergeCost = -(float)root->mTimeStamp;
4502        viewCellInterior->SetMergeCost(mergeCost);
4503
4504        float volume = 0;
4505       
4506        BspNode *front = interior->GetFront();
4507        BspNode *back = interior->GetBack();
4508
4509
4510        ////////////
4511        //-- recursivly compute child hierarchies
4512
4513        ViewCell *backVc = ConstructSpatialMergeTree(back);
4514        ViewCell *frontVc = ConstructSpatialMergeTree(front);
4515
4516        viewCellInterior->SetupChildLink(backVc);
4517        viewCellInterior->SetupChildLink(frontVc);
4518
4519        volume += backVc->GetVolume();
4520        volume += frontVc->GetVolume();
4521
4522        viewCellInterior->SetVolume(volume);
4523
4524        return viewCellInterior;
4525}
4526
4527
4528/************************************************************************/
4529/*                   KdViewCellsManager implementation                  */
4530/************************************************************************/
4531
4532
4533
4534KdViewCellsManager::KdViewCellsManager(ViewCellsTree *vcTree, KdTree *kdTree):
4535ViewCellsManager(vcTree), mKdTree(kdTree), mKdPvsDepth(100)
4536{
4537}
4538
4539
4540float KdViewCellsManager::GetProbability(ViewCell *viewCell)
4541{
4542        // compute view cell area / volume as subsititute for probability
4543        if (0)
4544                return GetArea(viewCell) / GetViewSpaceBox().SurfaceArea();
4545        else
4546                return GetVolume(viewCell) / GetViewSpaceBox().GetVolume();
4547}
4548
4549
4550
4551
4552void KdViewCellsManager::CollectViewCells()
4553{
4554        //mKdTree->CollectViewCells(mViewCells); TODO
4555}
4556
4557
4558int KdViewCellsManager::ConstructSubdivision(const ObjectContainer &objects,
4559                                                                  const VssRayContainer &rays)
4560{
4561        // if view cells already constructed
4562        if (ViewCellsConstructed())
4563                return 0;
4564
4565        mKdTree->Construct();
4566
4567        mTotalAreaValid = false;
4568        // create the view cells
4569        mKdTree->CreateAndCollectViewCells(mViewCells);
4570        // cast rays
4571        ComputeSampleContributions(rays, true, false);
4572
4573        EvaluateViewCellsStats();
4574        Debug << "\nView cells after construction:\n" << mCurrentViewCellsStats << endl;
4575
4576        return 0;
4577}
4578
4579
4580bool KdViewCellsManager::ViewCellsConstructed() const
4581{
4582        return mKdTree->GetRoot() != NULL;
4583}
4584
4585
4586int KdViewCellsManager::PostProcess(const ObjectContainer &objects,
4587                                                                        const VssRayContainer &rays)
4588{
4589        return 0;
4590}
4591
4592
4593void KdViewCellsManager::ExportSingleViewCells(const ObjectContainer &objects,
4594                                                                                           const int maxViewCells,
4595                                                                                           const bool sortViewCells,
4596                                                                                           const bool exportPvs,
4597                                                                                           const bool exportRays,
4598                                                                                           const int maxRays,
4599                                                                                           const string prefix,
4600                                                                                           VssRayContainer *visRays)
4601{
4602        // TODO
4603}
4604
4605
4606void KdViewCellsManager::Visualize(const ObjectContainer &objects,
4607                                                                   const VssRayContainer &sampleRays)
4608{
4609        if (!ViewCellsConstructed())
4610                return;
4611
4612        // using view cells instead of the kd PVS of objects
4613        const bool useViewCells = true;
4614        bool exportRays = false;
4615
4616        int limit = min(mVisualizationSamples, (int)sampleRays.size());
4617        const int pvsOut = min((int)objects.size(), 10);
4618        VssRayContainer *rays = new VssRayContainer[pvsOut];
4619
4620        if (useViewCells)
4621        {
4622                const int leafOut = 10;
4623
4624                ViewCell::NewMail();
4625
4626                //-- some rays for output
4627                const int raysOut = min((int)sampleRays.size(), mVisualizationSamples);
4628                Debug << "visualization using " << raysOut << " samples" << endl;
4629
4630                //-- some random view cells and rays for output
4631                vector<KdLeaf *> kdLeaves;
4632
4633                for (int i = 0; i < leafOut; ++ i)
4634                        kdLeaves.push_back(static_cast<KdLeaf *>(mKdTree->GetRandomLeaf()));
4635
4636                for (int i = 0; i < kdLeaves.size(); ++ i)
4637                {
4638                        KdLeaf *leaf = kdLeaves[i];
4639                        RayContainer vcRays;
4640
4641                        cout << "creating output for view cell " << i << " ... ";
4642#if 0
4643                        // check whether we can add the current ray to the output rays
4644                        for (int k = 0; k < raysOut; ++ k)
4645                        {
4646                                Ray *ray = sampleRays[k];
4647
4648                                for (int j = 0; j < (int)ray->bspIntersections.size(); ++ j)
4649                                {
4650                                        BspLeaf *leaf2 = ray->bspIntersections[j].mLeaf;
4651
4652                                        if (leaf->GetViewCell() == leaf2->GetViewCell())
4653                                        {
4654                                                vcRays.push_back(ray);
4655                                        }
4656                                }
4657                        }
4658#endif
4659                        Intersectable::NewMail();
4660
4661                        ViewCell *vc = leaf->mViewCell;
4662                        char str[64]; sprintf(str, "viewcell%04d.wrl", i);
4663
4664                        Exporter *exporter = Exporter::GetExporter(str);
4665                        exporter->SetFilled();
4666
4667                        exporter->SetWireframe();
4668                        //exporter->SetFilled();
4669
4670                        Material m;//= RandomMaterial();
4671                        m.mDiffuseColor = RgbColor(1, 1, 0);
4672                        exporter->SetForcedMaterial(m);
4673
4674                        AxisAlignedBox3 box = mKdTree->GetBox(leaf);
4675                        exporter->ExportBox(box);
4676
4677                        // export rays piercing this view cell
4678                        exporter->ExportRays(vcRays, 1000, RgbColor(0, 1, 0));
4679
4680                        m.mDiffuseColor = RgbColor(1, 0, 0);
4681                        exporter->SetForcedMaterial(m);
4682
4683                        // exporter->SetWireframe();
4684                        exporter->SetFilled();
4685
4686                        ObjectPvsIterator pit = vc->GetPvs().GetIterator();
4687                       
4688                        while (pit.HasMoreEntries())
4689                        {               
4690                                //-- output PVS of view cell
4691                                Intersectable *intersect = pit.Next();
4692
4693                                if (!intersect->Mailed())
4694                                {
4695                                        exporter->ExportIntersectable(intersect);
4696                                        intersect->Mail();
4697                                }
4698                        }
4699
4700                        DEL_PTR(exporter);
4701                        cout << "finished" << endl;
4702                }
4703
4704                DEL_PTR(rays);
4705        }
4706        else // using kd PVS of objects
4707        {
4708                for (int i = 0; i < limit; ++ i)
4709                {
4710                        VssRay *ray = sampleRays[i];
4711
4712                        // check whether we can add this to the rays
4713                        for (int j = 0; j < pvsOut; j++)
4714                        {
4715                                if (objects[j] == ray->mTerminationObject)
4716                                {
4717                                        rays[j].push_back(ray);
4718                                }
4719                        }
4720                }
4721
4722                if (exportRays)
4723                {
4724                        Exporter *exporter = NULL;
4725                        exporter = Exporter::GetExporter("sample-rays.x3d");
4726                        exporter->SetWireframe();
4727                        exporter->ExportKdTree(*mKdTree);
4728
4729                        for (int i = 0; i < pvsOut; i++)
4730                                exporter->ExportRays(rays[i], RgbColor(1, 0, 0));
4731
4732                        exporter->SetFilled();
4733                        delete exporter;
4734                }
4735
4736                for (int k=0; k < pvsOut; k++)
4737                {
4738                        Intersectable *object = objects[k];
4739                        char str[64]; sprintf(str, "viewcell%04d.wrl", k);
4740
4741                        Exporter *exporter = Exporter::GetExporter(str);
4742                        exporter->SetWireframe();
4743
4744                        // matt: we don't have no kd pvs
4745#if 0
4746                        KdPvsMap::iterator kit = object->mKdPvs.mEntries.begin();
4747                        Intersectable::NewMail();
4748
4749                        // avoid adding the object to the list
4750                        object->Mail();
4751                        ObjectContainer visibleObjects;
4752
4753                        for (; kit != object->mKdPvs.mEntries.end(); i++)
4754                        {
4755                                KdNode *node = (*kit).first;
4756                                exporter->ExportBox(mKdTree->GetBox(node));
4757
4758                                mKdTree->CollectObjects(node, visibleObjects);
4759                        }
4760
4761                        exporter->ExportRays(rays[k],  RgbColor(0, 1, 0));
4762                        exporter->SetFilled();
4763
4764                        for (int j = 0; j < visibleObjects.size(); j++)
4765                                exporter->ExportIntersectable(visibleObjects[j]);
4766
4767                        Material m;
4768                        m.mDiffuseColor = RgbColor(1, 0, 0);
4769                        exporter->SetForcedMaterial(m);
4770                        exporter->ExportIntersectable(object);
4771#endif
4772                        delete exporter;
4773                }
4774        }
4775}
4776
4777
4778ViewCell *KdViewCellsManager::GenerateViewCell(Mesh *mesh) const
4779{
4780        return new KdViewCell(mesh);
4781}
4782
4783
4784void KdViewCellsManager::ExportViewCellGeometry(Exporter *exporter,
4785                                                                                                ViewCell *vc,
4786                                                                                                const AxisAlignedBox3 *sceneBox,
4787                                                                                                const AxisAlignedPlane *clipPlane
4788                                                                                                ) const
4789{
4790        ViewCellContainer leaves;
4791        mViewCellsTree->CollectLeaves(vc, leaves);
4792        ViewCellContainer::const_iterator it, it_end = leaves.end();
4793
4794        for (it = leaves.begin(); it != it_end; ++ it)
4795        {
4796                KdViewCell *kdVc = static_cast<KdViewCell *>(*it);
4797                exporter->ExportBox(mKdTree->GetBox(kdVc->mLeaves[0]));
4798        }
4799}
4800
4801
4802int KdViewCellsManager::GetType() const
4803{
4804        return ViewCellsManager::KD;
4805}
4806
4807
4808
4809KdNode *KdViewCellsManager::GetNodeForPvs(KdLeaf *leaf)
4810{
4811        KdNode *node = leaf;
4812
4813        while (node->mParent && node->mDepth > mKdPvsDepth)
4814                node = node->mParent;
4815
4816        return node;
4817}
4818
4819int KdViewCellsManager::CastLineSegment(const Vector3 &origin,
4820                                                                                const Vector3 &termination,
4821                                                                                ViewCellContainer &viewcells)
4822{
4823        return mKdTree->CastLineSegment(origin, termination, viewcells);
4824}
4825
4826
4827bool KdViewCellsManager::LineSegmentIntersects(const Vector3 &origin,
4828                                                                                           const Vector3 &termination,
4829                                                                                           ViewCell *viewCell)
4830{
4831        return false;
4832}
4833
4834
4835void KdViewCellsManager::CreateMesh(ViewCell *vc)
4836{
4837        // TODO
4838}
4839
4840
4841
4842void KdViewCellsManager::CollectMergeCandidates(const VssRayContainer &rays,
4843                                                                                                vector<MergeCandidate> &candidates)
4844{
4845        // TODO
4846}
4847
4848
4849
4850/**************************************************************************/
4851/*                   VspBspViewCellsManager implementation                */
4852/**************************************************************************/
4853
4854
4855VspBspViewCellsManager::VspBspViewCellsManager(ViewCellsTree *vcTree, VspBspTree *vspBspTree):
4856ViewCellsManager(vcTree), mVspBspTree(vspBspTree)
4857{
4858        Environment::GetSingleton()->GetIntValue("VspBspTree.Construction.samples", mInitialSamples);
4859        mVspBspTree->SetViewCellsManager(this);
4860        mVspBspTree->mViewCellsTree = mViewCellsTree;
4861}
4862
4863
4864VspBspViewCellsManager::~VspBspViewCellsManager()
4865{
4866}
4867
4868
4869float VspBspViewCellsManager::GetProbability(ViewCell *viewCell)
4870{
4871        if (0 && mVspBspTree->mUseAreaForPvs)
4872                return GetArea(viewCell) / GetAccVcArea();
4873        else
4874                return GetVolume(viewCell) / mViewSpaceBox.GetVolume();
4875}
4876
4877
4878void VspBspViewCellsManager::CollectViewCells()
4879{
4880        // view cells tree constructed?
4881        if (!ViewCellsTreeConstructed())
4882        {
4883                mVspBspTree->CollectViewCells(mViewCells, false);
4884        }
4885        else
4886        {       
4887                // we can use the view cells tree hierarchy to get the right set
4888                mViewCellsTree->CollectBestViewCellSet(mViewCells, mNumActiveViewCells);
4889        }
4890}
4891
4892
4893void VspBspViewCellsManager::CollectMergeCandidates(const VssRayContainer &rays,
4894                                                                                                        vector<MergeCandidate> &candidates)
4895{       
4896        cout << "collecting merge candidates ... " << endl;
4897
4898        if (mUseRaysForMerge)
4899        {
4900                mVspBspTree->CollectMergeCandidates(rays, candidates);
4901        }
4902        else
4903        {
4904                vector<BspLeaf *> leaves;
4905                mVspBspTree->CollectLeaves(leaves);
4906       
4907                mVspBspTree->CollectMergeCandidates(leaves, candidates);
4908        }
4909
4910        cout << "fininshed collecting candidates" << endl;
4911}
4912
4913
4914bool VspBspViewCellsManager::ViewCellsConstructed() const
4915{
4916        return mVspBspTree->GetRoot() != NULL;
4917}
4918
4919
4920ViewCell *VspBspViewCellsManager::GenerateViewCell(Mesh *mesh) const
4921{
4922        return new BspViewCell(mesh);
4923}
4924
4925
4926int VspBspViewCellsManager::ConstructSubdivision(const ObjectContainer &objects,
4927                                                                                                 const VssRayContainer &rays)
4928{
4929        mMaxPvsSize = (int)(mMaxPvsRatio * (float)objects.size());
4930
4931        // if view cells were already constructed
4932        if (ViewCellsConstructed())
4933        {
4934                return 0;
4935        }
4936
4937        int sampleContributions = 0;
4938        VssRayContainer sampleRays;
4939
4940        const int limit = min(mInitialSamples, (int)rays.size());
4941
4942        Debug << "samples used for vsp bsp subdivision: " << mInitialSamples
4943                  << ", actual rays: " << (int)rays.size() << endl;
4944
4945        VssRayContainer savedRays;
4946
4947        if (SAMPLE_AFTER_SUBDIVISION)
4948        {
4949                VssRayContainer constructionRays;
4950               
4951                GetRaySets(rays, mInitialSamples, constructionRays, &savedRays);
4952
4953                Debug << "rays used for initial construction: " << (int)constructionRays.size() << endl;
4954                Debug << "rays saved for later use: " << (int)savedRays.size() << endl;
4955       
4956                mVspBspTree->Construct(constructionRays, &mViewSpaceBox);
4957        }
4958        else
4959        {
4960                Debug << "rays used for initial construction: " << (int)rays.size() << endl;
4961                mVspBspTree->Construct(rays, &mViewSpaceBox);
4962        }
4963
4964        // collapse invalid regions
4965        cout << "collapsing invalid tree regions ... ";
4966        long startTime = GetTime();
4967
4968        const int collapsedLeaves = mVspBspTree->CollapseTree();
4969        Debug << "collapsed in " << TimeDiff(startTime, GetTime()) * 1e-3
4970                  << " seconds" << endl;
4971
4972    cout << "finished" << endl;
4973
4974        /////////////////
4975        //-- stats after construction
4976
4977        Debug << mVspBspTree->GetStatistics() << endl;
4978
4979        ResetViewCells();
4980        Debug << "\nView cells after construction:\n" << mCurrentViewCellsStats << endl;
4981
4982
4983        //////////////////////
4984        //-- recast the rest of the rays
4985
4986        startTime = GetTime();
4987
4988        cout << "Computing remaining ray contributions ... ";
4989
4990        if (SAMPLE_AFTER_SUBDIVISION)
4991                ComputeSampleContributions(savedRays, true, false);
4992
4993        cout << "finished" << endl;
4994
4995        Debug << "Computed remaining ray contribution in " << TimeDiff(startTime, GetTime()) * 1e-3
4996                  << " secs" << endl;
4997
4998        cout << "construction finished" << endl;
4999
5000        if (0)
5001        {       ////////
5002                //-- real meshes are contructed at this stage
5003
5004                cout << "finalizing view cells ... ";
5005                FinalizeViewCells(true);
5006                cout << "finished" << endl;
5007        }
5008
5009        return sampleContributions;
5010}
5011
5012
5013void VspBspViewCellsManager::MergeViewCells(const VssRayContainer &rays,
5014                                                                                        const ObjectContainer &objects)
5015{
5016    int vcSize = 0;
5017        int pvsSize = 0;
5018
5019        //-- merge view cells
5020        cout << "starting merge using " << mPostProcessSamples << " samples ... " << endl;
5021        long startTime = GetTime();
5022
5023
5024        if (mMergeViewCells)
5025        {
5026                // TODO: should be done BEFORE the ray casting
5027                // compute tree by merging the nodes based on cost heuristics
5028                mViewCellsTree->ConstructMergeTree(rays, objects);
5029        }
5030        else
5031        {
5032                // compute tree by merging the nodes of the spatial hierarchy
5033                ViewCell *root = ConstructSpatialMergeTree(mVspBspTree->GetRoot());
5034                mViewCellsTree->SetRoot(root);
5035
5036                // compute pvs
5037                ObjectPvs pvs;
5038                UpdatePvsForEvaluation(root, pvs);
5039        }
5040
5041        if (1)
5042        {
5043                char mstats[100];
5044                ObjectPvs pvs;
5045
5046                Environment::GetSingleton()->GetStringValue("ViewCells.mergeStats", mstats);
5047                mViewCellsTree->ExportStats(mstats);
5048        }
5049
5050        cout << "merged view cells in "
5051                 << TimeDiff(startTime, GetTime()) *1e-3 << " secs" << endl;
5052
5053        Debug << "Postprocessing: Merged view cells in "
5054                  << TimeDiff(startTime, GetTime()) *1e-3 << " secs" << endl << endl;
5055       
5056
5057        //////////////////
5058        //-- stats and visualizations
5059
5060        int savedColorCode = mColorCode;
5061       
5062        // get currently active view cell set
5063        ResetViewCells();
5064        Debug << "\nView cells after merge:\n" << mCurrentViewCellsStats << endl;
5065       
5066        if (mShowVisualization) // export merged view cells
5067        {
5068                mColorCode = 0;
5069                Exporter *exporter = Exporter::GetExporter("merged_view_cells.wrl");
5070               
5071                cout << "exporting view cells after merge ... ";
5072
5073                if (exporter)
5074                {
5075                        if (0)
5076                                exporter->SetWireframe();
5077                        else
5078                                exporter->SetFilled();
5079
5080                        ExportViewCellsForViz(exporter, NULL, mColorCode, GetClipPlane());
5081
5082                        if (mExportGeometry)
5083                        {
5084                                Material m;
5085                                m.mDiffuseColor = RgbColor(0, 1, 0);
5086                                exporter->SetForcedMaterial(m);
5087                                exporter->SetFilled();
5088
5089                                exporter->ExportGeometry(objects);
5090                        }
5091
5092                        delete exporter;
5093                }
5094                cout << "finished" << endl;
5095        }
5096
5097        mColorCode = savedColorCode;
5098}
5099
5100
5101void VspBspViewCellsManager::RefineViewCells(const VssRayContainer &rays,
5102                                                                                         const ObjectContainer &objects)
5103{
5104        mRenderer->RenderScene();
5105
5106        SimulationStatistics ss;
5107        static_cast<RenderSimulator *>(mRenderer)->GetStatistics(ss);
5108    Debug << "render time before refine\n\n" << ss << endl;
5109
5110        const long startTime = GetTime();
5111        cout << "Refining the merged view cells ... ";
5112
5113        // refining the merged view cells
5114        const int refined = mViewCellsTree->RefineViewCells(rays, objects);
5115
5116        //-- stats and visualizations
5117        cout << "finished" << endl;
5118        cout << "refined " << refined << " view cells in "
5119                 << TimeDiff(startTime, GetTime()) *1e-3 << " secs" << endl;
5120
5121        Debug << "Postprocessing: refined " << refined << " view cells in "
5122                  << TimeDiff(startTime, GetTime()) *1e-3 << " secs" << endl << endl;
5123}
5124
5125
5126int VspBspViewCellsManager::PostProcess(const ObjectContainer &objects,
5127                                                                                const VssRayContainer &rays)
5128{
5129        if (!ViewCellsConstructed())
5130        {
5131                Debug << "postprocess error: no view cells constructed" << endl;
5132                return 0;
5133        }
5134
5135        // view cells already finished before post processing step
5136        // (i.e. because they were loaded)
5137        if (mViewCellsFinished)
5138        {
5139                FinalizeViewCells(true);
5140                EvaluateViewCellsStats();
5141
5142                return 0;
5143        }
5144
5145        // check if new view cells turned invalid
5146        int minPvs, maxPvs;
5147
5148        if (0)
5149        {
5150                minPvs = mMinPvsSize;
5151                maxPvs = mMaxPvsSize;
5152        }
5153        else
5154        {
5155                // problem matt: why did I start here from zero?
5156                minPvs = 0;
5157                maxPvs = mMaxPvsSize;
5158        }
5159
5160        Debug << "setting validity, min: " << minPvs << " max: " << maxPvs << endl;
5161        cout << "setting validity, min: " << minPvs << " max: " << maxPvs << endl;
5162       
5163        SetValidity(minPvs, maxPvs);
5164
5165        // update valid view space according to valid view cells
5166        if (0) mVspBspTree->ValidateTree();
5167
5168        // area has to be recomputed
5169        mTotalAreaValid = false;
5170        VssRayContainer postProcessRays;
5171        GetRaySets(rays, mPostProcessSamples, postProcessRays);
5172
5173        Debug << "post processing using " << (int)postProcessRays.size() << " samples" << endl;
5174
5175        //////////
5176        //-- merge neighbouring view cells
5177        MergeViewCells(postProcessRays, objects);
5178       
5179        // refines the merged view cells
5180        if (0) RefineViewCells(postProcessRays, objects);
5181
5182
5183        ///////////
5184        //-- render simulation after merge + refine
5185
5186        cout << "\nview cells partition render time before compress" << endl << endl;;
5187        static_cast<RenderSimulator *>(mRenderer)->RenderScene();
5188        SimulationStatistics ss;
5189        static_cast<RenderSimulator *>(mRenderer)->GetStatistics(ss);
5190        cout << ss << endl;
5191       
5192        if (0) CompressViewCells();
5193       
5194        // collapse sibling leaves that share the same view cell
5195        if (0) mVspBspTree->CollapseTree();
5196
5197        // recompute view cell list and statistics
5198        ResetViewCells();
5199
5200        // compute final meshes and volume / area
5201        if (1) FinalizeViewCells(true);
5202
5203        return 0;
5204}
5205
5206
5207int VspBspViewCellsManager::GetType() const
5208{
5209        return VSP_BSP;
5210}
5211
5212
5213ViewCell *VspBspViewCellsManager::ConstructSpatialMergeTree(BspNode *root)
5214{
5215        // terminate recursion
5216        if (root->IsLeaf())
5217        {
5218                BspLeaf *leaf = static_cast<BspLeaf *>(root);
5219                leaf->GetViewCell()->SetMergeCost(0.0f);
5220                return leaf->GetViewCell();
5221        }
5222       
5223       
5224        BspInterior *interior = static_cast<BspInterior *>(root);
5225        ViewCellInterior *viewCellInterior = new ViewCellInterior();
5226               
5227        // evaluate merge cost for priority traversal
5228        float mergeCost = 1.0f / (float)root->mTimeStamp;
5229        viewCellInterior->SetMergeCost(mergeCost);
5230
5231        float volume = 0;
5232       
5233        BspNode *front = interior->GetFront();
5234        BspNode *back = interior->GetBack();
5235
5236
5237        ObjectPvs frontPvs, backPvs;
5238
5239        //-- recursivly compute child hierarchies
5240        ViewCell *backVc = ConstructSpatialMergeTree(back);
5241        ViewCell *frontVc = ConstructSpatialMergeTree(front);
5242
5243
5244        viewCellInterior->SetupChildLink(backVc);
5245        viewCellInterior->SetupChildLink(frontVc);
5246
5247        volume += backVc->GetVolume();
5248        volume += frontVc->GetVolume();
5249
5250        viewCellInterior->SetVolume(volume);
5251
5252        return viewCellInterior;
5253}
5254
5255
5256bool VspBspViewCellsManager::GetViewPoint(Vector3 &viewPoint) const
5257{
5258        if (!ViewCellsConstructed())
5259                return ViewCellsManager::GetViewPoint(viewPoint);
5260
5261        // TODO: set reasonable limit
5262        const int limit = 20;
5263
5264        for (int i = 0; i < limit; ++ i)
5265        {
5266                viewPoint = mViewSpaceBox.GetRandomPoint();
5267                if (mVspBspTree->ViewPointValid(viewPoint))
5268                {
5269                        return true;
5270                }
5271        }
5272
5273        Debug << "failed to find valid view point, taking " << viewPoint << endl;
5274        return false;
5275}
5276
5277
5278bool VspBspViewCellsManager::ViewPointValid(const Vector3 &viewPoint) const
5279{
5280        // $$JB -> implemented in viewcellsmanager (slower, but allows dynamic
5281        // validy update in preprocessor for all managers)
5282        return ViewCellsManager::ViewPointValid(viewPoint);
5283
5284        //      return mViewSpaceBox.IsInside(viewPoint) &&
5285        //                 mVspBspTree->ViewPointValid(viewPoint);
5286}
5287
5288
5289void VspBspViewCellsManager::Visualize(const ObjectContainer &objects,
5290                                                                           const VssRayContainer &sampleRays)
5291{
5292        if (!ViewCellsConstructed())
5293                return;
5294
5295        VssRayContainer visRays;
5296        GetRaySets(sampleRays, mVisualizationSamples, visRays);
5297       
5298        if (1)
5299        {       
5300                //////////////////
5301                //-- export final view cell partition
5302
5303                Exporter *exporter = Exporter::GetExporter("final_view_cells.wrl");
5304               
5305                if (exporter)
5306                {
5307                        cout << "exporting view cells after post process ... ";
5308
5309                        if (0)
5310                        {       // export view space box
5311                                exporter->SetWireframe();
5312                                exporter->ExportBox(mViewSpaceBox);
5313                                exporter->SetFilled();
5314                        }
5315
5316                        Material m;
5317                        m.mDiffuseColor.r = 0.0f;
5318                        m.mDiffuseColor.g = 0.5f;
5319                        m.mDiffuseColor.b = 0.5f;
5320
5321            exporter->SetForcedMaterial(m);
5322
5323                        if (1 && mExportGeometry)
5324                        {
5325                                exporter->ExportGeometry(objects);
5326                        }
5327
5328                        if (0 && mExportRays)
5329                        {
5330                                exporter->ExportRays(visRays, RgbColor(1, 0, 0));
5331                        }
5332                        ExportViewCellsForViz(exporter, NULL, mColorCode, GetClipPlane());
5333
5334                        delete exporter;
5335                        cout << "finished" << endl;
5336                }
5337        }
5338
5339        ////////////////
5340        //-- visualization of the BSP splits
5341
5342        bool exportSplits = false;
5343        Environment::GetSingleton()->GetBoolValue("VspBspTree.Visualization.exportSplits", exportSplits);
5344
5345        if (exportSplits)
5346        {
5347                cout << "exporting splits ... ";
5348                ExportSplits(objects, visRays);
5349                cout << "finished" << endl;
5350        }
5351
5352        ////////
5353        //-- export single view cells
5354       
5355        int leafOut;
5356        Environment::GetSingleton()->GetIntValue("ViewCells.Visualization.maxOutput", leafOut);
5357        const int raysOut = 100;
5358       
5359        ExportSingleViewCells(objects, leafOut, false, true, false, raysOut, "");
5360}
5361
5362
5363void VspBspViewCellsManager::ExportSplits(const ObjectContainer &objects,
5364                                                                                  const VssRayContainer &rays)
5365{
5366        Exporter *exporter = Exporter::GetExporter("bsp_splits.x3d");
5367
5368        if (exporter)
5369        {
5370                Material m;
5371                m.mDiffuseColor = RgbColor(1, 0, 0);
5372                exporter->SetForcedMaterial(m);
5373                exporter->SetWireframe();
5374
5375                exporter->ExportBspSplits(*mVspBspTree, true);
5376
5377                // take forced material, else big scenes cannot be viewed
5378                m.mDiffuseColor = RgbColor(0, 1, 0);
5379                exporter->SetForcedMaterial(m);
5380                exporter->SetFilled();
5381
5382                exporter->ResetForcedMaterial();
5383
5384                // export rays
5385                if (mExportRays)
5386                {
5387                        exporter->ExportRays(rays, RgbColor(1, 1, 0));
5388                }
5389
5390                if (mExportGeometry)
5391                {
5392                        exporter->ExportGeometry(objects);
5393                }
5394                delete exporter;
5395        }
5396}
5397
5398
5399void VspBspViewCellsManager::ExportSingleViewCells(const ObjectContainer &objects,
5400                                                                                                   const int maxViewCells,
5401                                                                                                   const bool sortViewCells,
5402                                                                                                   const bool exportPvs,
5403                                                                                                   const bool exportRays,
5404                                                                                                   const int maxRays,
5405                                                                                                   const string prefix,
5406                                                                                                   VssRayContainer *visRays)
5407{       
5408        if (sortViewCells)
5409        {
5410                // sort view cells to visualize the largest view cells
5411                sort(mViewCells.begin(), mViewCells.end(), ViewCell::LargerRenderCost);
5412        }
5413
5414        //////////
5415        //-- some view cells for output
5416
5417        ViewCell::NewMail();
5418        const int limit = min(maxViewCells, (int)mViewCells.size());
5419       
5420        for (int i = 0; i < limit; ++ i)
5421        {
5422                cout << "creating output for view cell " << i << " ... ";
5423
5424                ViewCell *vc = sortViewCells ? // largest view cell pvs first?
5425                        mViewCells[(int)RandomValue(0, (float)mViewCells.size() - 0.5f)] : mViewCells[i];
5426
5427                if (vc->Mailed() || vc->GetId() == OUT_OF_BOUNDS_ID)
5428                        continue;
5429
5430                vc->Mail();
5431
5432                ObjectPvs pvs;
5433                mViewCellsTree->GetPvs(vc, pvs);
5434
5435                char s[64]; sprintf(s, "%sviewcell%04d.wrl", prefix.c_str(), i);
5436                Exporter *exporter = Exporter::GetExporter(s);
5437               
5438                const float pvsCost = mViewCellsTree->GetPvsCost(vc);
5439                cout << "view cell " << vc->GetId() << ": pvs cost=" << pvsCost << endl;
5440
5441                if (exportRays)
5442                {
5443                        ////////////
5444                        //-- export rays piercing this view cell
5445
5446                        // take rays stored with the view cells during subdivision
5447                        VssRayContainer vcRays;
5448            VssRayContainer collectRays;
5449
5450                        // collect initial view cells
5451                        ViewCellContainer leaves;
5452                        mViewCellsTree->CollectLeaves(vc, leaves);
5453
5454                        ViewCellContainer::const_iterator vit, vit_end = leaves.end();
5455                for (vit = leaves.begin(); vit != vit_end; ++ vit)
5456                        {       
5457                                BspLeaf *vcLeaf = static_cast<BspViewCell *>(*vit)->mLeaves[0];
5458                                VssRayContainer::const_iterator rit, rit_end = vcLeaf->mVssRays.end();
5459
5460                                for (rit = vcLeaf->mVssRays.begin(); rit != rit_end; ++ rit)
5461                                {
5462                                        collectRays.push_back(*rit);
5463                                }
5464                        }
5465
5466                        const int raysOut = min((int)collectRays.size(), maxRays);
5467               
5468                        // prepare some rays for output
5469                        VssRayContainer::const_iterator rit, rit_end = collectRays.end();
5470                        for (rit = collectRays.begin(); rit != rit_end; ++ rit)
5471                        {
5472                                const float p = RandomValue(0.0f, (float)collectRays.size());
5473                       
5474                                if (p < raysOut)
5475                                {
5476                                        vcRays.push_back(*rit);
5477                                }
5478                        }
5479
5480                        exporter->ExportRays(vcRays, RgbColor(1, 1, 1));
5481                }
5482               
5483                ////////////////
5484                //-- export view cell geometry
5485
5486                exporter->SetWireframe();
5487
5488                Material m;//= RandomMaterial();
5489                m.mDiffuseColor = RgbColor(0, 1, 0);
5490                exporter->SetForcedMaterial(m);
5491
5492                ExportViewCellGeometry(exporter, vc, NULL, NULL);
5493                exporter->SetFilled();
5494
5495                if (exportPvs)
5496                {
5497                        Intersectable::NewMail();
5498
5499                        ObjectPvsIterator pit = pvs.GetIterator();
5500
5501                        cout << endl;
5502
5503                        // output PVS of view cell
5504                        while (pit.HasMoreEntries())
5505                        {
5506                                Intersectable *intersect = pit.Next();         
5507                               
5508                                if (!intersect->Mailed())
5509                                {
5510                                        intersect->Mail();
5511
5512                                        m = RandomMaterial();
5513                                        exporter->SetForcedMaterial(m);
5514                                        exporter->ExportIntersectable(intersect);
5515                                }
5516                        }
5517                        cout << endl;
5518                }
5519               
5520                DEL_PTR(exporter);
5521                cout << "finished" << endl;
5522        }
5523}
5524
5525
5526void VspBspViewCellsManager::TestFilter(const ObjectContainer &objects)
5527{
5528        Exporter *exporter = Exporter::GetExporter("filter.x3d");
5529
5530        Vector3 bsize = mViewSpaceBox.Size();
5531        const Vector3 viewPoint(mViewSpaceBox.Center());
5532        float w = Magnitude(mViewSpaceBox.Size()) * mFilterWidth;
5533        const Vector3 width = Vector3(w);
5534       
5535        PrVs testPrVs;
5536       
5537        if (exporter)
5538        {
5539                ViewCellContainer viewCells;
5540       
5541        const AxisAlignedBox3 tbox = GetFilterBBox(viewPoint, mFilterWidth);
5542
5543                GetPrVS(viewPoint, testPrVs, GetFilterWidth());
5544
5545                exporter->SetWireframe();
5546
5547                exporter->SetForcedMaterial(RgbColor(1,1,1));
5548                exporter->ExportBox(tbox);
5549               
5550                exporter->SetFilled();
5551
5552                exporter->SetForcedMaterial(RgbColor(0,1,0));
5553                ExportViewCellGeometry(exporter, GetViewCell(viewPoint), NULL, NULL);
5554
5555                //exporter->ResetForcedMaterial();
5556                exporter->SetForcedMaterial(RgbColor(0,0,1));
5557                ExportViewCellGeometry(exporter, testPrVs.mViewCell, NULL, NULL);
5558
5559        exporter->SetForcedMaterial(RgbColor(1,0,0));
5560                exporter->ExportGeometry(objects);
5561
5562                delete exporter;
5563        }
5564}
5565
5566
5567int VspBspViewCellsManager::ComputeBoxIntersections(const AxisAlignedBox3 &box,
5568                                                                                                        ViewCellContainer &viewCells) const
5569{
5570        return mVspBspTree->ComputeBoxIntersections(box, viewCells);
5571}
5572
5573
5574int VspBspViewCellsManager::CastLineSegment(const Vector3 &origin,
5575                                                                                        const Vector3 &termination,
5576                                                                                        ViewCellContainer &viewcells)
5577{
5578        return mVspBspTree->CastLineSegment(origin, termination, viewcells);
5579}
5580
5581
5582bool VspBspViewCellsManager::LineSegmentIntersects(const Vector3 &origin,
5583                                                                                                   const Vector3 &termination,
5584                                                                                                   ViewCell *viewCell)
5585{
5586        return false;
5587}
5588
5589
5590void VspBspViewCellsManager::VisualizeWithFromPointQueries()
5591{
5592        int numSamples;
5593       
5594        Environment::GetSingleton()->GetIntValue("RenderSampler.samples", numSamples);
5595        cout << "samples" << numSamples << endl;
5596
5597        vector<RenderCostSample> samples;
5598 
5599        if (!mPreprocessor->GetRenderer())
5600                return;
5601
5602        //start the view point queries
5603        long startTime = GetTime();
5604        cout << "starting sampling of render cost ... ";
5605       
5606        mPreprocessor->GetRenderer()->SampleRenderCost(numSamples, samples, true);
5607
5608        cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
5609
5610
5611        // for each sample:
5612        //    find view cells associated with the samples
5613        //    store the sample pvs with the pvs associated with the view cell
5614        //
5615        // for each view cell:
5616        //    compute difference point sampled pvs - view cell pvs
5617        //    export geometry with color coded pvs difference
5618       
5619    std::map<ViewCell *, ObjectPvs> sampleMap;
5620
5621        vector<RenderCostSample>::const_iterator rit, rit_end = samples.end();
5622
5623        for (rit = samples.begin(); rit != rit_end; ++ rit)
5624        {
5625                RenderCostSample sample = *rit;
5626       
5627                ViewCell *vc = GetViewCell(sample.mPosition);
5628
5629                std::map<ViewCell *, ObjectPvs>::iterator it = sampleMap.find(vc);
5630
5631                if (it == sampleMap.end())
5632                {
5633                        sampleMap[vc] = sample.mPvs;
5634                }
5635                else
5636                {
5637                        (*it).second.MergeInPlace(sample.mPvs);
5638                }
5639        }
5640
5641        // visualize the view cells
5642        std::map<ViewCell *, ObjectPvs>::const_iterator vit, vit_end = sampleMap.end();
5643
5644        Material m;//= RandomMaterial();
5645
5646        for (vit = sampleMap.begin(); vit != vit_end; ++ vit)
5647        {
5648                ViewCell *vc = (*vit).first;
5649               
5650                const int pvsVc = mViewCellsTree->GetPvsEntries(vc);
5651                const int pvsPtSamples = (*vit).second.GetSize();
5652
5653        m.mDiffuseColor.r = (float) (pvsVc - pvsPtSamples);
5654                m.mDiffuseColor.b = 1.0f;
5655                //exporter->SetForcedMaterial(m);
5656                //ExportViewCellGeometry(exporter, vc, mClipPlaneForViz);
5657
5658                /*      // counting the pvss
5659                for (rit = samples.begin(); rit != rit_end; ++ rit)
5660                {
5661                        RenderCostSample sample = *rit;
5662                        ViewCell *vc = GetViewCell(sample.mPosition);
5663
5664                        AxisAlignedBox3 box(sample.mPosition - Vector3(1, 1, 1), sample.mPosition + Vector3(1, 1, 1));
5665                        Mesh *hMesh = CreateMeshFromBox(box);
5666
5667                        DEL_PTR(hMesh);
5668                }
5669                */
5670        }
5671}
5672
5673
5674void VspBspViewCellsManager::ExportViewCellGeometry(Exporter *exporter,
5675                                                                                                        ViewCell *vc,
5676                                                                                                        const AxisAlignedBox3 *sceneBox,
5677                                                                                                        const AxisAlignedPlane *clipPlane
5678                                                                                                        ) const
5679{
5680        if (clipPlane)
5681        {
5682                const Plane3 plane = clipPlane->GetPlane();
5683
5684                ViewCellContainer leaves;
5685                mViewCellsTree->CollectLeaves(vc, leaves);
5686                ViewCellContainer::const_iterator it, it_end = leaves.end();
5687
5688                for (it = leaves.begin(); it != it_end; ++ it)
5689                {
5690                        BspNodeGeometry geom;
5691                        BspNodeGeometry front;
5692                        BspNodeGeometry back;
5693
5694                        mVspBspTree->ConstructGeometry(*it, geom);
5695
5696                        const float eps = 0.0001f;
5697                        const int cf = geom.Side(plane, eps);
5698
5699                        if (cf == -1)
5700                        {
5701                                exporter->ExportPolygons(geom.GetPolys());
5702                        }
5703                        else if (cf == 0)
5704                        {
5705                                geom.SplitGeometry(front,
5706                                                                   back,
5707                                                                   plane,
5708                                                                   mViewSpaceBox,
5709                                                                   eps);
5710
5711                                if (back.Valid())
5712                                {
5713                                        exporter->ExportPolygons(back.GetPolys());
5714                                }                       
5715                        }
5716                }
5717        }
5718        else
5719        {
5720                // export mesh if available
5721                // TODO: some bug here?
5722                if (1 && vc->GetMesh())
5723                {
5724                        exporter->ExportMesh(vc->GetMesh());
5725                }
5726                else
5727                {
5728                        BspNodeGeometry geom;
5729                        mVspBspTree->ConstructGeometry(vc, geom);
5730                        exporter->ExportPolygons(geom.GetPolys());
5731                }
5732        }
5733}
5734
5735
5736int VspBspViewCellsManager::GetMaxTreeDiff(ViewCell *vc) const
5737{
5738        ViewCellContainer leaves;
5739        mViewCellsTree->CollectLeaves(vc, leaves);
5740
5741        int maxDist = 0;
5742       
5743        // compute max height difference
5744        for (int i = 0; i < (int)leaves.size(); ++ i)
5745        {
5746                for (int j = 0; j < (int)leaves.size(); ++ j)
5747                {
5748                        BspLeaf *leaf = static_cast<BspViewCell *>(leaves[i])->mLeaves[0];
5749
5750                        if (i != j)
5751                        {
5752                                BspLeaf *leaf2 =static_cast<BspViewCell *>(leaves[j])->mLeaves[0];
5753                                const int dist = mVspBspTree->TreeDistance(leaf, leaf2);
5754                               
5755                                if (dist > maxDist)
5756                                        maxDist = dist;
5757                        }
5758                }
5759        }
5760
5761        return maxDist;
5762}
5763
5764
5765ViewCell *VspBspViewCellsManager::GetViewCell(const Vector3 &point, const bool active) const
5766{
5767        if (!ViewCellsConstructed())
5768                return NULL;
5769
5770        if (!mViewSpaceBox.IsInside(point))
5771          return NULL;
5772
5773        return mVspBspTree->GetViewCell(point, active);
5774}
5775
5776
5777void VspBspViewCellsManager::CreateMesh(ViewCell *vc)
5778{
5779        BspNodeGeometry geom;
5780        mVspBspTree->ConstructGeometry(vc, geom);
5781       
5782        Mesh *mesh = MeshManager::GetSingleton()->CreateResource();
5783       
5784        IncludeNodeGeomInMesh(geom, *mesh);
5785        mesh->ComputeBoundingBox();
5786
5787        vc->SetMesh(mesh);
5788}
5789
5790
5791int VspBspViewCellsManager::CastBeam(Beam &beam)
5792{
5793        return mVspBspTree->CastBeam(beam);
5794}
5795
5796
5797void VspBspViewCellsManager::Finalize(ViewCell *viewCell,
5798                                                                          const bool createMesh)
5799{
5800        float area = 0;
5801        float volume = 0;
5802
5803        ViewCellContainer leaves;
5804        mViewCellsTree->CollectLeaves(viewCell, leaves);
5805
5806        ViewCellContainer::const_iterator it, it_end = leaves.end();
5807
5808    for (it = leaves.begin(); it != it_end; ++ it)
5809        {
5810                BspNodeGeometry geom;
5811                mVspBspTree->ConstructGeometry(*it, geom);
5812
5813                const float lVol = geom.GetVolume();
5814                const float lArea = geom.GetArea();
5815
5816                area += lArea;
5817                volume += lVol;
5818
5819                if (createMesh)
5820                        CreateMesh(*it);
5821        }
5822
5823        viewCell->SetVolume(volume);
5824        viewCell->SetArea(area);
5825}
5826
5827
5828void VspBspViewCellsManager::TestSubdivision()
5829{
5830        ViewCellContainer leaves;
5831        mViewCellsTree->CollectLeaves(mViewCellsTree->GetRoot(), leaves);
5832
5833        ViewCellContainer::const_iterator it, it_end = leaves.end();
5834
5835        const float vol = mViewSpaceBox.GetVolume();
5836        float subdivVol = 0;
5837        float newVol = 0;
5838
5839        for (it = leaves.begin(); it != it_end; ++ it)
5840        {
5841                BspNodeGeometry geom;
5842                mVspBspTree->ConstructGeometry(*it, geom);
5843
5844                const float lVol = geom.GetVolume();
5845               
5846                newVol += lVol;
5847                subdivVol += (*it)->GetVolume();
5848               
5849                float thres = 0.9f;
5850                if ((lVol < ((*it)->GetVolume() * thres)) || (lVol * thres > ((*it)->GetVolume())))
5851                        Debug << "warning: " << lVol << " " << (*it)->GetVolume() << endl;
5852        }
5853       
5854        Debug << "exact volume: " << vol << endl;
5855        Debug << "subdivision volume: " << subdivVol << endl;
5856        Debug << "new volume: " << newVol << endl;
5857}
5858
5859
5860void VspBspViewCellsManager::PrepareLoadedViewCells()
5861{
5862        // TODO: do I still need this here?
5863        if (0) mVspBspTree->RepairViewCellsLeafLists();
5864}
5865
5866
5867
5868/************************************************************************/
5869/*                 VspOspViewCellsManager implementation                */
5870/************************************************************************/
5871
5872
5873VspOspViewCellsManager::VspOspViewCellsManager(ViewCellsTree *vcTree,
5874                                                                                           const string &hierarchyType)
5875: ViewCellsManager(vcTree)
5876{
5877        Environment::GetSingleton()->GetIntValue("Hierarchy.Construction.samples", mInitialSamples);
5878
5879        Environment::GetSingleton()->GetBoolValue("ViewCells.compressObjects", mCompressObjects);
5880
5881        Debug << "compressing objects: " << mCompressObjects << endl;
5882        cout << "compressing objects: " << mCompressObjects << endl;
5883
5884        mHierarchyManager = CreateHierarchyManager(hierarchyType);
5885        mHierarchyManager->SetViewCellsManager(this);
5886        mHierarchyManager->SetViewCellsTree(mViewCellsTree);
5887}
5888
5889
5890VspOspViewCellsManager::VspOspViewCellsManager(ViewCellsTree *vcTree, HierarchyManager *hm)
5891: ViewCellsManager(vcTree), mHierarchyManager(hm)
5892{
5893        Environment::GetSingleton()->GetIntValue("Hierarchy.Construction.samples", mInitialSamples);
5894        Environment::GetSingleton()->GetBoolValue("ViewCells.compressObjects", mCompressObjects);
5895
5896        Debug << "compressing objects: " << mCompressObjects << endl;
5897        cout << "compressing objects: " << mCompressObjects << endl;
5898
5899        mHierarchyManager->SetViewCellsManager(this);
5900        mHierarchyManager->SetViewCellsTree(mViewCellsTree);
5901}
5902
5903
5904Intersectable *
5905VspOspViewCellsManager::GetIntersectable(const VssRay &ray, const bool isTermination) const
5906{
5907        if (mUseKdPvs)
5908        {
5909                return ViewCellsManager::GetIntersectable(ray, isTermination);
5910        }
5911        else
5912        {
5913                return mHierarchyManager->GetIntersectable(ray, isTermination);
5914        }
5915}
5916
5917
5918HierarchyManager *VspOspViewCellsManager::CreateHierarchyManager(const string &hierarchyType)
5919{
5920        HierarchyManager *hierarchyManager;
5921
5922        if (strcmp(hierarchyType.c_str(), "osp") == 0)
5923        {
5924                Debug << "hierarchy manager: osp" << endl;
5925                hierarchyManager = new HierarchyManager(HierarchyManager::KD_BASED_OBJ_SUBDIV);
5926        }
5927        else if (strcmp(hierarchyType.c_str(), "bvh") == 0)
5928        {
5929                Debug << "hierarchy manager: bvh" << endl;
5930                hierarchyManager = new HierarchyManager(HierarchyManager::BV_BASED_OBJ_SUBDIV);
5931        }
5932        else // only view space partition
5933        {
5934                Debug << "hierarchy manager: obj" << endl;
5935                hierarchyManager = new HierarchyManager(HierarchyManager::NO_OBJ_SUBDIV);
5936        }
5937
5938        return hierarchyManager;
5939}
5940
5941
5942VspOspViewCellsManager::~VspOspViewCellsManager()
5943{
5944        DEL_PTR(mHierarchyManager);
5945}
5946
5947
5948float VspOspViewCellsManager::GetProbability(ViewCell *viewCell)
5949{
5950        return GetVolume(viewCell) / mViewSpaceBox.GetVolume();
5951}
5952
5953
5954void VspOspViewCellsManager::CollectViewCells()
5955{
5956        // view cells tree constructed
5957        if (!ViewCellsTreeConstructed())
5958        {
5959                mHierarchyManager->GetVspTree()->CollectViewCells(mViewCells, false);
5960        }
5961        else
5962        {       // we can use the view cells tree hierarchy to get the right set
5963                mViewCellsTree->CollectBestViewCellSet(mViewCells, mNumActiveViewCells);
5964        }
5965}
5966
5967
5968bool VspOspViewCellsManager::ViewCellsConstructed() const
5969{
5970        return mHierarchyManager->GetVspTree()->GetRoot() != NULL;
5971}
5972
5973
5974ViewCell *VspOspViewCellsManager::GenerateViewCell(Mesh *mesh) const
5975{
5976        return new VspViewCell(mesh);
5977}
5978
5979
5980int VspOspViewCellsManager::ConstructSubdivision(const ObjectContainer &objects,
5981                                                                                                 const VssRayContainer &rays)
5982{
5983        mMaxPvsSize = (int)(mMaxPvsRatio * (float)objects.size());
5984
5985        // skip rest if view cells were already constructed
5986        if (ViewCellsConstructed())
5987                return 0;
5988
5989        int sampleContributions = 0;
5990        VssRayContainer sampleRays;
5991
5992        int limit = min (mInitialSamples, (int)rays.size());
5993
5994        VssRayContainer constructionRays;
5995        VssRayContainer savedRays;
5996
5997        Debug << "samples used for vsp bsp subdivision: " << mInitialSamples
5998                  << ", actual rays: " << (int)rays.size() << endl;
5999
6000        GetRaySets(rays, mInitialSamples, constructionRays, &savedRays);
6001
6002        Debug << "initial rays used for construction: " << (int)constructionRays.size() << endl;
6003        Debug << "saved rays: " << (int)savedRays.size() << endl;
6004
6005        mHierarchyManager->Construct(constructionRays, objects, &mViewSpaceBox);
6006
6007#if TEST_EVALUATION
6008        VssRayContainer::const_iterator tit, tit_end = constructionRays.end();
6009        for (tit = constructionRays.begin(); tit != tit_end; ++ tit)
6010        {
6011                storedRays.push_back(new VssRay(*(*tit)));
6012        }
6013#endif
6014
6015        /////////////////////////
6016        //-- print satistics for subdivision and view cells
6017
6018        Debug << endl << endl << *mHierarchyManager << endl;
6019
6020        ResetViewCells();
6021        Debug << "\nView cells after construction:\n" << mCurrentViewCellsStats << endl;
6022
6023        //////////////
6024        //-- recast rest of rays
6025       
6026        const long startTime = GetTime();
6027        cout << "Computing remaining ray contributions ... ";
6028
6029        if (SAMPLE_AFTER_SUBDIVISION)
6030                ComputeSampleContributions(savedRays, true, false);
6031
6032        Debug << "finished computing remaining ray contribution in " << TimeDiff(startTime, GetTime()) * 1e-3
6033                  << " secs" << endl;
6034
6035        if (0)
6036        {       
6037                // real meshes are constructed at this stage
6038                cout << "finalizing view cells ... ";
6039        FinalizeViewCells(true);
6040                cout << "finished" << endl;
6041        }
6042
6043        return sampleContributions;
6044}
6045
6046
6047int VspOspViewCellsManager::PostProcess(const ObjectContainer &objects,
6048                                                                                const VssRayContainer &rays)
6049{
6050        if (!ViewCellsConstructed())
6051        {
6052                Debug << "post process error: no view cells constructed" << endl;
6053                return 0;
6054        }
6055
6056        // if view cells were already constructed before post processing step
6057        // (e.g., because they were loaded), we are finished
6058        if (mViewCellsFinished)
6059        {
6060                FinalizeViewCells(true);
6061                EvaluateViewCellsStats();
6062
6063                return 0;
6064        }
6065
6066        // check if new view cells turned invalid
6067        int minPvs, maxPvs;
6068
6069        if (0)
6070        {
6071                minPvs = mMinPvsSize;
6072                maxPvs = mMaxPvsSize;
6073        }
6074        else
6075        {
6076                // problem matt: why did I start here from zero?
6077                minPvs = 0;
6078                maxPvs = mMaxPvsSize;
6079        }
6080
6081        Debug << "setting validity, min: " << minPvs << " max: " << maxPvs << endl;
6082        cout << "setting validity, min: " << minPvs << " max: " << maxPvs << endl;
6083       
6084        SetValidity(minPvs, maxPvs);
6085
6086       
6087        // area is not up to date, has to be recomputed
6088        mTotalAreaValid = false;
6089        VssRayContainer postProcessRays;
6090        GetRaySets(rays, mPostProcessSamples, postProcessRays);
6091
6092        Debug << "post processing using " << (int)postProcessRays.size() << " samples" << endl;
6093
6094
6095        // compute tree by merging the nodes of the spatial hierarchy
6096        ViewCell *root = ConstructSpatialMergeTree(mHierarchyManager->GetVspTree()->GetRoot());
6097        mViewCellsTree->SetRoot(root);
6098
6099        //////////////////////////
6100        //-- update pvs up to the root of the hierarchy
6101
6102        ObjectPvs pvs;
6103        UpdatePvsForEvaluation(root, pvs);
6104
6105
6106        //////////////////////
6107        //-- render simulation after merge + refine
6108
6109        cout << "\nview cells partition render time before compress" << endl << endl;
6110        static_cast<RenderSimulator *>(mRenderer)->RenderScene();
6111        SimulationStatistics ss;
6112        static_cast<RenderSimulator *>(mRenderer)->GetStatistics(ss);
6113        cout << ss << endl;
6114       
6115
6116        mHierarchyManager->CreateUniqueObjectIds();
6117
6118        ///////////
6119        //-- compression
6120
6121        if (0) CompressViewCells();
6122
6123        /////////////
6124        //-- some tasks still to do on the view cells:
6125        //-- Compute meshes from view cell geometry, evaluate volume and / or area
6126
6127        if (1) FinalizeViewCells(true);
6128
6129        return 0;
6130}
6131
6132
6133int VspOspViewCellsManager::GetType() const
6134{
6135        return VSP_OSP;
6136}
6137
6138
6139ViewCell *VspOspViewCellsManager::ConstructSpatialMergeTree(VspNode *root)
6140{
6141        // terminate recursion
6142        if (root->IsLeaf())
6143        {
6144                VspLeaf *leaf = static_cast<VspLeaf *>(root);
6145                leaf->GetViewCell()->SetMergeCost(0.0f);
6146                return leaf->GetViewCell();
6147        }
6148       
6149        VspInterior *interior = static_cast<VspInterior *>(root);
6150        ViewCellInterior *viewCellInterior = new ViewCellInterior();
6151               
6152        // evaluate merge cost for priority traversal
6153        const float mergeCost = -(float)root->mTimeStamp;
6154        viewCellInterior->SetMergeCost(mergeCost);
6155
6156        float volume = 0;
6157       
6158        VspNode *front = interior->GetFront();
6159        VspNode *back = interior->GetBack();
6160
6161        ObjectPvs frontPvs, backPvs;
6162
6163        /////////
6164        //-- recursivly compute child hierarchies
6165
6166        ViewCell *backVc = ConstructSpatialMergeTree(back);
6167        ViewCell *frontVc = ConstructSpatialMergeTree(front);
6168
6169        viewCellInterior->SetupChildLink(backVc);
6170        viewCellInterior->SetupChildLink(frontVc);
6171
6172        volume += backVc->GetVolume();
6173        volume += frontVc->GetVolume();
6174
6175        viewCellInterior->SetVolume(volume);
6176
6177        return viewCellInterior;
6178}
6179
6180
6181bool VspOspViewCellsManager::GetViewPoint(Vector3 &viewPoint) const
6182{
6183        if (!ViewCellsConstructed())
6184                return ViewCellsManager::GetViewPoint(viewPoint);
6185
6186        // TODO: set reasonable limit
6187        const int limit = 20;
6188
6189        for (int i = 0; i < limit; ++ i)
6190        {
6191                viewPoint = mViewSpaceBox.GetRandomPoint();
6192
6193                if (mHierarchyManager->GetVspTree()->ViewPointValid(viewPoint))
6194                {
6195                        return true;
6196                }
6197        }
6198
6199        Debug << "failed to find valid view point, taking " << viewPoint << endl;
6200        return false;
6201}
6202
6203
6204void VspOspViewCellsManager::ExportViewCellGeometry(Exporter *exporter,
6205                                                                                                        ViewCell *vc,
6206                                                                                                        const AxisAlignedBox3 *sceneBox,
6207                                                                                                        const AxisAlignedPlane *clipPlane
6208                                                                                                        ) const
6209{
6210        ViewCellContainer leaves;
6211        mViewCellsTree->CollectLeaves(vc, leaves);
6212        ViewCellContainer::const_iterator it, it_end = leaves.end();
6213
6214        Plane3 plane;
6215        if (clipPlane)
6216        {
6217                // arbitrary plane definition
6218                plane = clipPlane->GetPlane();
6219        }
6220
6221        for (it = leaves.begin(); it != it_end; ++ it)
6222        {
6223                VspViewCell *vspVc = static_cast<VspViewCell *>(*it);
6224                VspLeaf *l = vspVc->mLeaves[0];
6225
6226                const AxisAlignedBox3 box =
6227                        mHierarchyManager->GetVspTree()->GetBoundingBox(vspVc->mLeaves[0]);
6228               
6229                if (sceneBox && !Overlap(*sceneBox, box))
6230                        continue;
6231
6232                if (clipPlane)
6233                {
6234                        if (box.Side(plane) == -1)
6235                        {
6236                                exporter->ExportBox(box);
6237                        }
6238                        else if (box.Side(plane) == 0)
6239                        {
6240                                // intersection
6241                                AxisAlignedBox3 fbox, bbox;
6242                                box.Split(clipPlane->mAxis, clipPlane->mPosition, fbox, bbox);
6243                                exporter->ExportBox(bbox);
6244                        }
6245                }
6246                else
6247                {
6248                        exporter->ExportBox(box);
6249                }
6250        }
6251}
6252
6253
6254bool VspOspViewCellsManager::ViewPointValid(const Vector3 &viewPoint) const
6255{
6256  // $$JB -> implemented in viewcellsmanager (slower, but allows dynamic
6257  // validy update in preprocessor for all managers)
6258  return ViewCellsManager::ViewPointValid(viewPoint);
6259
6260  //    return mViewSpaceBox.IsInside(viewPoint) &&
6261  //               mVspTree->ViewPointValid(viewPoint);
6262}
6263
6264
6265float VspOspViewCellsManager::UpdateObjectCosts()
6266{
6267        float maxRenderCost = 0;
6268
6269        cout << "updating object pvs cost ... ";
6270        const long startTime = GetTime();
6271
6272        ViewCellContainer::const_iterator vit, vit_end = mViewCells.end();
6273
6274        Intersectable::NewMail();
6275
6276        const float invViewSpaceVol = 1.0f / GetViewSpaceBox().GetVolume();
6277
6278        for (vit = mViewCells.begin(); vit != vit_end; ++ vit)
6279        {
6280                ViewCell *vc = *vit;
6281
6282                ObjectPvsIterator pit = vc->GetPvs().GetIterator();
6283
6284                // output PVS of view cell
6285                while (pit.HasMoreEntries())
6286                {               
6287                        Intersectable *obj = pit.Next();
6288                               
6289                        BvhNode *node = static_cast<BvhNode *>(obj);
6290                       
6291                        // hack!!
6292                        if (!node->IsLeaf())
6293                        {
6294                                cout << "error, can only process leaves" << endl;
6295                                return 0;
6296                        }
6297       
6298                        if (!node->Mailed())
6299                        {
6300                                node->Mail();
6301                                node->mRenderCost = 0;
6302                        }
6303
6304                        const float rc = (float)((BvhLeaf *)node)->mObjects.size();
6305
6306                        node->mRenderCost += rc * vc->GetVolume() * invViewSpaceVol;
6307
6308                        if (node->mRenderCost > maxRenderCost)
6309                                maxRenderCost = node->mRenderCost;
6310                }
6311        }
6312
6313        cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3f << " secs" << endl;
6314
6315        return maxRenderCost;
6316}
6317
6318
6319void VspOspViewCellsManager::Visualize(const ObjectContainer &objects,
6320                                                                           const VssRayContainer &sampleRays)
6321{
6322        if (!ViewCellsConstructed())
6323                return;
6324
6325        VssRayContainer visRays;
6326        GetRaySets(sampleRays, mVisualizationSamples, visRays);
6327
6328        ////////////
6329        //-- export final view cells
6330
6331        Exporter *exporter = Exporter::GetExporter("final_view_cells.wrl");
6332
6333        //Vector3 scale(0.9f, 0.9f, 0.9f);
6334        Vector3 scale(1.0f, 1.0f, 1.0f);
6335
6336        if (exporter)
6337        {
6338                if (CLAMP_TO_BOX)
6339                {       
6340                        exporter->mClampToBox = true;   
6341                }
6342
6343                EvaluateViewCellsStats();
6344
6345                const long starttime = GetTime();
6346                cout << "exporting final view cells (after initial construction + post process) ... " << endl;
6347
6348                // matt: hack for clamping scene
6349                AxisAlignedBox3 bbox = mViewSpaceBox;
6350                bbox.Scale(scale);
6351
6352                if (1 && mExportRays)
6353                {       
6354                        exporter->ExportRays(visRays, RgbColor(0, 1, 0));
6355                }
6356
6357                // hack color code
6358                const int savedColorCode = mColorCode;
6359
6360                const float maxRenderCost = -1;//UpdateObjectCosts();
6361                cout << "maxRenderCost: " << maxRenderCost << endl;
6362                mColorCode = 0; // 0 = random, 1 = export pvs
6363
6364                if (1)
6365                mHierarchyManager->ExportObjectSpaceHierarchy(exporter, objects,
6366                                                                                                          CLAMP_TO_BOX ? &bbox : NULL, maxRenderCost, false);
6367               
6368
6369                if (1)
6370                {
6371                        //ExportViewCellsForViz(exporter, CLAMP_TO_BOX ? &bbox : NULL, mColorCode, GetClipPlane());
6372                        ExportViewCellsForViz(exporter, NULL, mColorCode, GetClipPlane());
6373                }
6374
6375                delete exporter;
6376
6377                cout << "finished in " << TimeDiff(starttime, GetTime()) * 1e-3f << " secs" << endl;
6378                mColorCode = savedColorCode;
6379        }
6380
6381        exporter = Exporter::GetExporter("final_object_partition.wrl");
6382
6383        if (exporter)
6384        {
6385                if (CLAMP_TO_BOX)
6386                {       
6387                        exporter->mClampToBox = true;   
6388                }
6389
6390                EvaluateViewCellsStats();
6391
6392                const long starttime = GetTime();
6393                cout << "exporting final objects (after initial construction + post process) ... ";
6394
6395                // matt: hack for clamping scene
6396                AxisAlignedBox3 bbox = mViewSpaceBox;
6397                bbox.Scale(scale);
6398
6399                // hack color code (show pvs size)
6400                const int savedColorCode = mColorCode;
6401
6402                mColorCode = 1; // 0 = random, 1 = export pvs
6403                // don't visualize render cost
6404                const float maxRenderCost = -1;
6405
6406                if (1)
6407                mHierarchyManager->ExportObjectSpaceHierarchy(exporter, objects,
6408                                                                                                          CLAMP_TO_BOX ? &bbox : NULL, maxRenderCost, false);
6409               
6410
6411                if (1)
6412                {
6413                        ExportViewCellsForViz(exporter, NULL, mColorCode, GetClipPlane());
6414                        //ExportViewCellsForViz(exporter, CLAMP_TO_BOX ? &bbox : NULL, mColorCode, GetClipPlane());
6415                }
6416
6417                delete exporter;
6418
6419                cout << "finished in " << TimeDiff(starttime, GetTime()) * 1e-3f << " secs" << endl;
6420                mColorCode = savedColorCode;
6421        }
6422
6423        // visualization of the merged view cells
6424    if (0)
6425        {       
6426                ExportMergedViewCells(objects);
6427        }
6428
6429        // export some view cells
6430        int leafOut;
6431        Environment::GetSingleton()->GetIntValue("ViewCells.Visualization.maxOutput", leafOut);
6432
6433        const bool sortViewCells = false;
6434        const bool exportPvs = true;
6435        const bool exportRays = true;
6436        const int raysOut = 100;
6437
6438        ExportSingleViewCells(objects,
6439                                                  leafOut,
6440                                                  sortViewCells,
6441                                                  exportPvs,
6442                                                  exportRays,
6443                                                  raysOut,
6444                                                  "");
6445}
6446
6447
6448void VspOspViewCellsManager::ExportSingleViewCells(const ObjectContainer &objects,
6449                                                                                                   const int maxViewCells,
6450                                                                                                   const bool sortViewCells,
6451                                                                                                   const bool exportPvs,
6452                                                                                                   const bool exportRays,
6453                                                                                                   const int maxRays,
6454                                                                                                   const string prefix,
6455                                                                                                   VssRayContainer *visRays)
6456{
6457        if (sortViewCells)
6458        {
6459                // sort view cells to visualize the view cells with highest render cost
6460                sort(mViewCells.begin(), mViewCells.end(), ViewCell::LargerRenderCost);
6461        }
6462
6463        ViewCell::NewMail();
6464        const int limit = min(maxViewCells, (int)mViewCells.size());
6465       
6466        cout << "\nExporting " << limit << " single view cells: " << endl;
6467       
6468        for (int i = 0; i < limit; ++ i)
6469        {
6470                cout << "creating output for view cell " << i << " ... ";
6471               
6472                // largest view cell pvs first of random view cell
6473                ViewCell *vc = sortViewCells ?
6474                        mViewCells[i] : mViewCells[(int)RandomValue(0, (float)mViewCells.size() - 1)];
6475               
6476                if (vc->Mailed()) // view cell already processed
6477                        continue;
6478
6479                vc->Mail();
6480
6481                ObjectPvs pvs;
6482                mViewCellsTree->GetPvs(vc, pvs);
6483
6484                char s[64]; sprintf(s, "%sviewcell%04d.wrl", prefix.c_str(), i);
6485                Exporter *exporter = Exporter::GetExporter(s);
6486               
6487                cout << "view cell " << vc->GetId() << ": pvs cost=" << mViewCellsTree->GetPvsCost(vc) << endl;
6488
6489                if (exportPvs)
6490                {
6491                        Material m;
6492
6493                        Intersectable::NewMail();
6494                       
6495                        ObjectPvsIterator pit = pvs.GetIterator();
6496
6497                        // output PVS of view cell
6498                        while (pit.HasMoreEntries())
6499                        {               
6500                                Intersectable *intersect = pit.Next();
6501                               
6502                                if (!intersect->Mailed())
6503                                {
6504                                        m = RandomMaterial();
6505                                        exporter->SetForcedMaterial(m);
6506
6507                                        exporter->ExportIntersectable(intersect);
6508                                        intersect->Mail();
6509                                }
6510                        }
6511                }
6512
6513                if (exportRays)
6514                {
6515                        ////////////
6516                        //-- export the sample rays
6517
6518                        // output rays stored with the view cells during subdivision
6519                        VssRayContainer vcRays;
6520                        VssRayContainer collectRays;
6521
6522                        // collect intial view cells
6523                        ViewCellContainer leaves;
6524                        mViewCellsTree->CollectLeaves(vc, leaves);
6525
6526                        ViewCellContainer::const_iterator vit, vit_end = leaves.end();
6527
6528                        for (vit = leaves.begin(); vit != vit_end; ++ vit)
6529                        {
6530                                VspLeaf *vcLeaf = static_cast<VspViewCell *>(*vit)->mLeaves[0];
6531                                VssRayContainer::const_iterator rit, rit_end = vcLeaf->mVssRays.end();
6532
6533                                for (rit = vcLeaf->mVssRays.begin(); rit != rit_end; ++ rit)
6534                                {
6535                                        collectRays.push_back(*rit);
6536                                }
6537                        }
6538
6539                        const int raysOut = min((int)collectRays.size(), maxRays);
6540
6541                        VssRayContainer::const_iterator rit, rit_end = collectRays.end();
6542
6543                        for (rit = collectRays.begin(); rit != rit_end; ++ rit)
6544                        {
6545                                const float p = RandomValue(0.0f, (float)collectRays.size());
6546
6547                                if (p < raysOut)
6548                                        vcRays.push_back(*rit);
6549                        }
6550
6551                        exporter->ExportRays(vcRays, RgbColor(1, 1, 1));
6552                }
6553               
6554       
6555                /////////////////
6556                //-- export view cell geometry
6557
6558                exporter->SetWireframe();
6559
6560                Material m;
6561                m.mDiffuseColor = RgbColor(0, 1, 0);
6562                exporter->SetForcedMaterial(m);
6563
6564                ExportViewCellGeometry(exporter, vc, NULL, NULL);
6565                exporter->SetFilled();
6566
6567                DEL_PTR(exporter);
6568                cout << "finished" << endl;
6569        }
6570
6571        cout << endl;
6572}
6573
6574
6575int VspOspViewCellsManager::ComputeBoxIntersections(const AxisAlignedBox3 &box,
6576                                                                                                        ViewCellContainer &viewCells) const
6577{
6578        return mHierarchyManager->GetVspTree()->ComputeBoxIntersections(box, viewCells);
6579}
6580
6581
6582int VspOspViewCellsManager::CastLineSegment(const Vector3 &origin,
6583                                                                                        const Vector3 &termination,
6584                                                                                        ViewCellContainer &viewcells)
6585{
6586        return mHierarchyManager->CastLineSegment(origin, termination, viewcells);
6587}
6588
6589
6590bool VspOspViewCellsManager::LineSegmentIntersects(const Vector3 &origin,
6591                                                                                                   const Vector3 &termination,
6592                                                                                                   ViewCell *viewCell)
6593{
6594        return false;
6595}
6596
6597
6598bool VspOspViewCellsManager::ExportViewCells(const string filename,
6599                                                                                         const bool exportPvs,
6600                                                                                         const ObjectContainer &objects)
6601{
6602        if (!ViewCellsConstructed() || !ViewCellsTreeConstructed())
6603                return false;
6604
6605        const long starttime = GetTime();
6606        cout << "exporting view cells to xml ... ";
6607       
6608        OUT_STREAM stream(filename.c_str());
6609
6610        // for output we need unique ids for each view cell
6611        CreateUniqueViewCellIds();
6612
6613        stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"<<endl;
6614        stream << "<VisibilitySolution>" << endl;
6615
6616        if (exportPvs)
6617        {
6618        ///////////////
6619                //-- export bounding boxes
6620                //-- we need the boxes to identify objects in the target engine
6621
6622                if (mUseKdPvs)
6623                {
6624                        stream << "<BoundingBoxes>" << endl;
6625                        vector<KdIntersectable *>::const_iterator kit, kit_end = mPreprocessor->mKdTree->mKdIntersectables.end();
6626
6627                        int id = 0;
6628
6629                        for (kit = mPreprocessor->mKdTree->mKdIntersectables.begin(); kit != kit_end; ++ kit, ++ id)
6630                        {
6631                                Intersectable *obj = (*kit);
6632                                const AxisAlignedBox3 box = obj->GetBox();
6633
6634                                // set kd node id
6635                                obj->SetId(id);
6636
6637                                stream << "<BoundingBox" << " id=\"" << id << "\""
6638                                   << " min=\"" << box.Min().x << " " << box.Min().y << " " << box.Min().z << "\""
6639                                   << " max=\"" << box.Max().x << " " << box.Max().y << " " << box.Max().z << "\" />" << endl;
6640                        }
6641                        stream << "</BoundingBoxes>" << endl;
6642                }
6643                else
6644                {
6645                        mHierarchyManager->ExportBoundingBoxes(stream, objects);
6646                }
6647        }
6648
6649
6650        //////////////////////////
6651        //-- export the view cells and the pvs
6652
6653        const int numViewCells = mCurrentViewCellsStats.viewCells;
6654
6655        stream << "<ViewCells number=\"" << numViewCells << "\" >" << endl;
6656        mViewCellsTree->Export(stream, exportPvs);
6657        stream << "</ViewCells>" << endl;
6658
6659        //////////////////////
6660        //-- export the view space hierarchy
6661       
6662        stream << "<ViewSpaceHierarchy type=\"vsp\""
6663                   << " min=\"" << mViewSpaceBox.Min().x << " " << mViewSpaceBox.Min().y << " " << mViewSpaceBox.Min().z << "\""
6664                   << " max=\"" << mViewSpaceBox.Max().x << " " << mViewSpaceBox.Max().y << " " << mViewSpaceBox.Max().z << "\">" << endl;
6665
6666        mHierarchyManager->GetVspTree()->Export(stream);
6667        stream << "</ViewSpaceHierarchy>" << endl;
6668
6669        ////////////////////// 
6670        //-- export the object space partition
6671       
6672        mHierarchyManager->ExportObjectSpaceHierarchy(stream);
6673       
6674        stream << "</VisibilitySolution>" << endl;
6675        stream.close();
6676       
6677        cout << "finished in " << TimeDiff(starttime, GetTime()) * 1e-3 << " secs" << endl;
6678        return true;
6679}
6680
6681
6682
6683ViewCell *VspOspViewCellsManager::GetViewCell(const Vector3 &point,
6684                                                                                          const bool active) const
6685{
6686        if (!ViewCellsConstructed())
6687                return NULL;
6688
6689        if (!mViewSpaceBox.IsInside(point))
6690                return NULL;
6691
6692        return mHierarchyManager->GetVspTree()->GetViewCell(point, active);
6693}
6694
6695
6696void VspOspViewCellsManager::CreateMesh(ViewCell *vc)
6697{
6698        Mesh *mesh = MeshManager::GetSingleton()->CreateResource();
6699       
6700        ViewCellContainer leaves;
6701        mViewCellsTree->CollectLeaves(vc, leaves);
6702
6703        ViewCellContainer::const_iterator it, it_end = leaves.end();
6704
6705    for (it = leaves.begin(); it != it_end; ++ it)
6706        {
6707                VspLeaf *leaf = static_cast<VspViewCell *>(*it)->mLeaves[0];
6708                const AxisAlignedBox3 box = mHierarchyManager->GetVspTree()->GetBoundingBox(leaf);
6709        IncludeBoxInMesh(box, *mesh);
6710        }
6711
6712        mesh->ComputeBoundingBox();
6713
6714        vc->SetMesh(mesh);
6715}
6716
6717
6718int VspOspViewCellsManager::CastBeam(Beam &beam)
6719{
6720        // matt: TODO
6721        return 0;
6722}
6723
6724
6725void VspOspViewCellsManager::Finalize(ViewCell *viewCell, const bool createMesh)
6726{
6727        float area = 0;
6728        float volume = 0;
6729
6730        ViewCellContainer leaves;
6731        mViewCellsTree->CollectLeaves(viewCell, leaves);
6732
6733        ViewCellContainer::const_iterator it, it_end = leaves.end();
6734
6735    for (it = leaves.begin(); it != it_end; ++ it)
6736        {
6737                VspLeaf *leaf = static_cast<VspViewCell *>(*it)->mLeaves[0];
6738               
6739                const AxisAlignedBox3 box = mHierarchyManager->GetVspTree()->GetBoundingBox(leaf);
6740
6741                const float lVol = box.GetVolume();
6742                const float lArea = box.SurfaceArea();
6743
6744                area += lArea;
6745                volume += lVol;
6746
6747        CreateMesh(*it);
6748        }
6749
6750        viewCell->SetVolume(volume);
6751        viewCell->SetArea(area);
6752}
6753
6754
6755void VspOspViewCellsManager::PrepareLoadedViewCells()
6756{
6757        // TODO
6758}
6759
6760
6761static void PrintCompressionStats(HierarchyManager *hm, const int pvsEntries)
6762{
6763        float mem = (float)pvsEntries * ObjectPvs::GetEntrySize();
6764               
6765        float fullmem = mem +
6766                        (hm->GetVspTree()->GetStatistics().Leaves() * 16 +
6767                         hm->mBvHierarchy->GetStatistics().Leaves() * 16) / float(1024 * 1024);
6768
6769        cout << "entries: " << pvsEntries << ", mem=" << mem << ", fullmem=" << fullmem <<endl;
6770        Debug << "entries: " << pvsEntries << ", mem=" << mem << ", fullmem=" << fullmem <<endl;
6771}
6772
6773
6774void VspOspViewCellsManager::CompressViewCells()
6775{
6776        if (!(ViewCellsTreeConstructed() && mCompressViewCells))
6777                return;
6778
6779        ////////////
6780        //-- compression
6781
6782        int pvsEntries = mViewCellsTree->CountStoredPvsEntries(mViewCellsTree->GetRoot());
6783
6784        cout << "before compression: " << endl;
6785        Debug << "before compression: " << endl;
6786       
6787        PrintCompressionStats(mHierarchyManager, pvsEntries);
6788
6789        if (mCompressObjects)
6790        {
6791                cout << "compressing in the objects: " << endl;
6792                Debug << "compressing in the objects: " << endl;
6793
6794                pvsEntries = mHierarchyManager->CompressObjectSpace();
6795        }
6796        else
6797        {
6798                cout << "compressing in the view space: " << endl;
6799                Debug << "compressing in the view space: " << endl;
6800
6801                mViewCellsTree->SetViewCellsStorage(ViewCellsTree::COMPRESSED);
6802                pvsEntries = mViewCellsTree->CountStoredPvsEntries(mViewCellsTree->GetRoot());
6803        }
6804
6805        PrintCompressionStats(mHierarchyManager, pvsEntries);
6806}
6807
6808
6809void VspOspViewCellsManager::CollectObjects(const AxisAlignedBox3 &box,
6810                                                                                        ObjectContainer &objects)
6811{
6812        mHierarchyManager->CollectObjects(box, objects);
6813}
6814
6815
6816#if 1
6817
6818void VspOspViewCellsManager::EvalViewCellPartition()
6819{
6820        int samplesPerPass;
6821        int numSamples;
6822        int castSamples = 0;
6823        int oldSamples = 0;
6824        int samplesForStats;
6825        char statsPrefix[100];
6826        char suffix[100];
6827        int splitsStepSize;
6828
6829        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.samplesPerPass", samplesPerPass);
6830        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.samplesForStats", samplesForStats);
6831        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.samples", numSamples);
6832        Environment::GetSingleton()->GetStringValue("ViewCells.Evaluation.statsPrefix", statsPrefix);
6833        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.stepSize", splitsStepSize);
6834       
6835        bool useHisto;
6836        int histoMem;
6837
6838        Environment::GetSingleton()->GetBoolValue("ViewCells.Evaluation.histogram", useHisto);
6839        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.histoMem", histoMem);
6840
6841        Debug << "step size: " << splitsStepSize << endl;
6842        Debug << "view cell evaluation samples per pass: " << samplesPerPass << endl;
6843        Debug << "view cell evaluation samples: " << numSamples << endl;
6844        Debug << "view cell stats prefix: " << statsPrefix << endl;
6845
6846    cout << "reseting pvs ... ";
6847               
6848        // reset pvs and start over from zero
6849        mViewCellsTree->ResetPvs();
6850       
6851        cout << "finished" << endl;
6852    cout << "Evaluating view cell partition ... " << endl;
6853
6854        int pass = 0;
6855
6856        while (castSamples < numSamples)
6857        {               
6858                ///////////////
6859                //-- we have to use uniform sampling strategy for construction rays
6860
6861                VssRayContainer evaluationSamples;
6862                const int samplingType = mEvaluationSamplingType;
6863
6864                long startTime = GetTime();
6865                Real timeDiff;
6866
6867                cout << "casting " << samplesPerPass << " samples ... ";
6868                Debug << "casting " << samplesPerPass << " samples ... ";
6869       
6870                // use mixed distributions
6871                CastEvaluationSamples(samplesPerPass, evaluationSamples);
6872
6873                timeDiff = TimeDiff(startTime, GetTime());
6874                cout << "finished in " << timeDiff * 1e-3f << " secs" << endl;
6875                Debug << "finished in " << timeDiff * 1e-3f << " secs" << endl;
6876               
6877                // don't use sample contributions because already accounted for inside the mixture distribution!
6878               
6879                castSamples += samplesPerPass;
6880
6881                if ((castSamples >= samplesForStats + oldSamples) ||
6882                        (castSamples >= numSamples))
6883                {
6884                        oldSamples += samplesForStats;
6885
6886                        ///////////
6887                        //-- output stats
6888
6889                        sprintf(suffix, "-%09d-eval.log", castSamples);
6890                        const string filename = string(statsPrefix) + string(suffix);
6891
6892                        startTime = GetTime();
6893                       
6894                        cout << "compute new statistics ... " << endl;
6895
6896                        ofstream ofstr(filename.c_str());
6897                        mHierarchyManager->EvaluateSubdivision2(ofstr, splitsStepSize, false, useHisto, histoMem, pass);
6898
6899                        timeDiff = TimeDiff(startTime, GetTime());
6900                        cout << "finished in " << timeDiff * 1e-3 << " secs" << endl;
6901                        cout << "*************************************" << endl;
6902
6903                        Debug << "statistics computed in " << timeDiff * 1e-3 << " secs" << endl;
6904
6905#if 0
6906                        //////////////
6907                        // filtered stats
6908
6909                        sprintf(suffix, "-%09d-eval-filter.log", castSamples);
6910                        const string filename2 = string(statsPrefix) + string(suffix);
6911
6912                        startTime = GetTime();
6913                       
6914                        cout << "compute new statistics for filtered pvs ... " << endl;
6915
6916                        ofstream ofstr2(filename2.c_str());
6917                        mHierarchyManager->EvaluateSubdivision2(ofstr2, splitsStepSize, true);
6918
6919                        timeDiff = TimeDiff(startTime, GetTime());
6920                        cout << "finished in " << timeDiff * 1e-3 << " secs" << endl;
6921                        cout << "*************************************" << endl;
6922                        Debug << "filtered statistics computed in " << timeDiff * 1e-3 << " secs" << endl;
6923#endif
6924
6925                        // only for debugging purpose
6926                        if (0)
6927                        {
6928                                ViewCellContainer viewCells;
6929                                mViewCellsTree->CollectLeaves(mViewCellsTree->GetRoot(), viewCells);
6930
6931                                ViewCellContainer::const_iterator vit, vit_end = viewCells.end();
6932                                int pvsSize = 0;
6933
6934                                for (vit = viewCells.begin(); vit != vit_end; ++ vit)
6935                                {
6936                                        pvsSize += (*vit)->GetPvs().GetSize();
6937                                }
6938
6939                                cout << "debug entries: " << pvsSize << ", memcost: "
6940                                         << (float)pvsSize * ObjectPvs::GetEntrySize() << endl;
6941                        }
6942                        ++ pass;
6943                }
6944
6945                disposeRays(evaluationSamples, NULL);
6946        }
6947
6948        ////////////
6949        //-- histogram
6950#if 1
6951        const int numLeaves = mViewCellsTree->GetNumInitialViewCells(mViewCellsTree->GetRoot());
6952        int histoStepSize;
6953
6954        Environment::GetSingleton()->GetBoolValue("ViewCells.Evaluation.histogram", useHisto);
6955        Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.histoStepSize", histoStepSize);
6956
6957        if (useHisto)
6958        {
6959                // evaluate view cells in a histogram           
6960                char str[64];
6961
6962                // hack: just show final view cells
6963                const int pass = (int)mViewCells.size();
6964
6965                //for (int pass = histoStepSize; pass <= numLeaves; pass += histoStepSize)
6966                if (1)
6967                {
6968                        string filename;
6969
6970                        cout << "computing histogram for " << pass << " view cells" << endl;
6971
6972                        //////////////////////////////////////////
6973            //-- evaluate histogram for pvs size
6974
6975                        cout << "computing pvs histogram for " << pass << " view cells" << endl;
6976
6977                        sprintf(str, "-%09d-histo-pvs2.log", pass);
6978                        filename = string(statsPrefix) + string(str);
6979
6980                        EvalViewCellHistogramForPvsSize(filename, pass);
6981                }
6982        }
6983#endif
6984}
6985
6986#endif
6987
6988void VspOspViewCellsManager::FinalizeViewCells(const bool createMesh)
6989{       
6990        ViewCellsManager::FinalizeViewCells(createMesh);
6991
6992        if (mHierarchyManager->mUseTraversalTree)
6993        {
6994                // create a traversal tree for optimal view cell casting
6995                mHierarchyManager->CreateTraversalTree();
6996        }
6997}
6998
6999
7000}
Note: See TracBrowser for help on using the repository browser.